var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var _res;
Date.getClientDateTime = function () {
    let date = new Date();
    let curDate = new Date(date.getTime() - (date.getTimezoneOffset() * 60 * 1000));
    return curDate.toISOString().slice(0, 16);
};
Date.convert = function (textDate) {
    if (!textDate)
        return null;
    if (textDate.indexOf('-') === -1)
        return null;
    let dateParts = textDate.split("-");
    return new Date(parseInt(dateParts[0]), parseInt(dateParts[1]) - 1, parseInt(dateParts[2]));
};
Date.prototype.convertLocal = function (dateStr) {
    const parts = dateStr.split("/");
    if (parts.length !== 3)
        return null;
    const day = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10) - 1;
    const year = parseInt(parts[2], 10);
    const date = new Date(year, month, day);
    return isNaN(date.getTime()) ? null : date;
};
Date.prototype.monthsIntoDays = function (currDate, months) {
    let totalDays = 0;
    let date = new Date(currDate.getTime());
    for (let i = 0; i < months; i++) {
        const year = date.getFullYear();
        const month = date.getMonth();
        const lastDayOfMonth = new Date(year, month + 1, 0).getDate();
        totalDays += lastDayOfMonth;
        date.setMonth(month + 1);
    }
    return totalDays;
};
Date.prototype.addDays = function (days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
};
Date.prototype.formatear = function () {
    var dd = this.getDate();
    var mm = this.getMonth() + 1;
    var yyyy = this.getFullYear();
    if (dd < 10)
        dd = '0' + dd;
    if (mm < 10)
        mm = '0' + mm;
    return yyyy + '-' + mm + '-' + dd;
};
Date.prototype.formatearLocal = function () {
    var dd = this.getDate();
    var mm = this.getMonth() + 1;
    var yyyy = this.getFullYear();
    if (dd < 10)
        dd = '0' + dd;
    if (mm < 10)
        mm = '0' + mm;
    return Sol.Environment.language == "en" ? mm + '/' + dd + '/' + yyyy : dd + '/' + mm + '/' + yyyy;
};
Date.prototype.formatearLocalConHora = function (showSeconds) {
    var sufijo = "";
    var hh = this.getHours();
    var mm = this.getMinutes();
    var ss = this.getSeconds();
    if (Sol.Environment.language == "en") {
        sufijo = hh > 11 ? " pm" : " am";
        if (hh > 11)
            hh -= 12;
    }
    if (hh < 10)
        hh = '0' + hh;
    if (mm < 10)
        mm = '0' + mm;
    var result = this.formatearLocal() + ' ' + hh + ':' + mm;
    if (showSeconds) {
        if (ss < 10)
            ss = '0' + ss;
        result += ':' + ss;
    }
    return result + sufijo;
};
Date.prototype.getAge = function () {
    var today = new Date();
    var age = today.getFullYear() - this.getFullYear();
    if (today.getMonth() < this.getMonth() || (today.getMonth() == this.getMonth() && today.getDate() < this.getDay()))
        age--;
    return age;
};
Date.prototype.getDaysFrom = function (startDate) {
    var oneDay = 24 * 60 * 60 * 1000;
    return Math.round(Math.abs((startDate.getTime() - this.getTime()) / oneDay));
};
Date.prototype.getLastDayOfMonth = function () {
    var result = this;
    result.setMonth(result.getMonth() + 1);
    result = result.addDays(-1);
    return result;
};
String.prototype.isNumeric = function () { return /^\d+$/.test(this); };
String.prototype.getLettersAndNumbers = function () { return this.replace(/[^a-zA-Z0-9]+/g, ''); };
String.prototype.soloDigitos = function () { return this.replace(/\D+/g, ''); };
String.prototype.removeHtmlTags = function () { return this.replace(/<.*?>/g, ''); };
String.prototype.removeDiacritics = function () { return this.normalize('NFD').replace(/[\u0300-\u036f]/g, ""); };
String.prototype.insert = function (text, index) {
    return index > 0 ? this.replace(new RegExp('.{' + index + '}'), '$&' + text) : text + this;
};
String.prototype.padLeft = function (replacement) {
    return String(replacement + this).slice(-replacement.length);
};
String.prototype.highlight = function (term) {
    var regex = new RegExp(term, "gi");
    return this.replace(regex, str => "<strong>" + str + "</strong>");
};
String.prototype.capitalizeFirstLetter = function () {
    return this && this[0].toUpperCase() + this.slice(1);
};
var Sol;
(function (Sol) {
    let Lightness;
    (function (Lightness) {
        Lightness[Lightness["Light"] = 0] = "Light";
        Lightness[Lightness["Dark"] = 1] = "Dark";
    })(Lightness = Sol.Lightness || (Sol.Lightness = {}));
    class Colors {
        static lightOrDark(color) {
            let c = +("0x" + color.slice(1).replace(color.length < 5 && /./g, '$&$&'));
            let r = c >> 16;
            let g = c >> 8 & 255;
            let b = c & 255;
            let hsp = Math.sqrt(0.299 * (r * r) +
                0.587 * (g * g) +
                0.114 * (b * b));
            return hsp > 127.5 ? Lightness.Light : Lightness.Dark;
        }
    }
    Sol.Colors = Colors;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class NumberEx {
        static filesizeToString(value) {
            var counter = -1;
            var units = ['Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb'];
            do {
                value /= 1024;
                counter++;
            } while (value > 1024);
            return Math.max(value, 0.1).toFixed(1) + units[counter];
        }
    }
    Sol.NumberEx = NumberEx;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Http;
    (function (Http) {
        class Cookies {
            static setCookie(key, value, days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expiration = "expires=" + date.toUTCString();
                document.cookie = key + "=" + value + "; " + expiration;
            }
            static getCookie(key) {
                let name = key + "=";
                let decodedCookie = decodeURIComponent(document.cookie);
                let ca = decodedCookie.split(';');
                for (let i = 0; i < ca.length; i++) {
                    let c = ca[i];
                    while (c.charAt(0) == ' ')
                        c = c.substring(1);
                    if (c.indexOf(name) == 0)
                        return c.substring(name.length, c.length);
                }
                return "";
            }
        }
        Http.Cookies = Cookies;
    })(Http = Sol.Http || (Sol.Http = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Credencial {
        load(model) {
            this.empresa = model.Empresa;
            this.idioma = model.Idioma;
            this.ticket = model.Ticket;
            this.codigoSistema = model.CodigoSistema;
            this.user = model.User;
            this.userCity = model.UserCity;
        }
        export() {
            return {
                Empresa: this.empresa,
                Idioma: this.idioma,
                Ticket: this.ticket,
                HusoHorario: Sol.Environment.timeZone,
                CodigoSistema: this.codigoSistema,
                User: null,
                UserCity: null
            };
        }
    }
    Sol.Credencial = Credencial;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Environment {
        static get fileServer() { return this._fileServer; }
        static set fileServer(value) {
            this._fileServer = value;
            this.filePath = this._fileServer + "/download/";
            this.uploadPath = this._fileServer + "/upload/";
        }
        static get imagePath() { return this.filePath.replace("/download", "/image"); }
        static get isMobile() { return window.innerWidth <= 800; }
        static get sessionID() {
            var session = Sol.Http.Cookies.getCookie("sol_session") || btoa(Math.random().toString());
            Sol.Http.Cookies.setCookie("sol_session", session, 30);
            return session;
        }
        static get timeZone() { return new Date().getTimezoneOffset() / -60; }
        static loadLibrary(lib) {
            if (this.libraries.includes(lib.name))
                return;
            this.libraries.push(lib.name);
            if (lib.cssFile)
                this.loadCss(lib.cssFile);
            this.loadJs(lib.source);
        }
        static loadJs(url) {
            const script = document.createElement("script");
            script.type = "text/javascript";
            script.setAttribute("src", this.systemUrl + url);
            document.head.appendChild(script);
        }
        static loadCss(url) {
            const link = document.createElement("link");
            link.setAttribute("rel", "stylesheet");
            link.setAttribute("type", "text/css");
            link.setAttribute("href", this.systemUrl + url);
            document.head.appendChild(link);
        }
    }
    Environment._fileServer = "";
    Environment.filePath = "/download/";
    Environment.resources = {};
    Environment.uploadPath = "/upload/";
    Environment.libraries = [];
    Environment.systemUrl = "";
    Sol.Environment = Environment;
})(Sol || (Sol = {}));
Sol.Environment.credential = new Sol.Credencial();
var Sol;
(function (Sol) {
    class EventHandler {
        constructor() {
            this.queue = new Sol.List();
        }
        any() { return this.queue.hasItems(); }
        connect(control, domEvent) {
            this.queue.forEach(action => control.html.addEventListener(domEvent, () => action()));
        }
        invoke(...args) { this.queue.forEach(q => q.apply(null, args)); }
        subscribe(action) { this.queue.add(action); }
        unsubscribeAll() { this.queue.empty(); }
    }
    Sol.EventHandler = EventHandler;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class KeyValueCollection {
        constructor() {
            this._enumerador = [];
        }
        agregar(item, valor) {
            this._enumerador.push({ key: item, value: valor || item });
        }
        definir(item, valor) {
            if (valor != null && valor != undefined) {
                var vItem = this.toList().that(e => e.key == item);
                if (vItem)
                    vItem.value = valor;
                else
                    this.agregar(item, valor);
            }
            else
                this._enumerador = this.toList().where(e => e.key != item).toArray();
        }
        toList() { return Sol.List.from(this._enumerador); }
        toString() { return this._enumerador.join(" "); }
        estaVacia() { return this._enumerador.length == 0; }
        forEach(accion) {
            for (var i of this._enumerador)
                accion(i);
        }
        item(llave) {
            for (var i of this._enumerador)
                if (i.key == llave)
                    return i.value;
            return null;
        }
        remove(key) {
            this._enumerador = Sol.List.from(this._enumerador).where(i => i.key != key).toArray();
        }
    }
    Sol.KeyValueCollection = KeyValueCollection;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Estilos extends Sol.KeyValueCollection {
        clear() {
            this._enumerador = [];
            if (this.parent && this.parent.html)
                this.parent.html.removeAttribute("style");
        }
        definir(item, value) {
            super.definir(item, value);
            if (this.parent && this.parent.html)
                this.parent.html.style[item] = value;
        }
        remove(key) {
            if (this.parent && this.parent.html)
                this.parent.html.style[key] = null;
            super.remove(key);
        }
        toString() {
            return this.toList().select(s => s.key + ':' + s.value).toArray().join(";");
        }
    }
    Sol.Estilos = Estilos;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class List {
        constructor() {
            this._enumerador = [];
        }
        add(item) {
            this._enumerador.push(item);
            this.listChanged();
        }
        addMany(items) {
            this._enumerador = this._enumerador.concat(Array.isArray(items) ? items : items.toArray());
            this.listChanged();
            return this;
        }
        all(condicion) {
            for (var i of this._enumerador)
                if (!condicion(i))
                    return false;
            return true;
        }
        any(condicion) {
            for (var i of this._enumerador)
                if (condicion(i))
                    return true;
            return false;
        }
        cast() { return this.select(i => i); }
        static concatLists(sources) {
            const result = new List();
            sources.forEach(lst => result.addMany(lst));
            return result;
        }
        contains(item, comparer = null) {
            return this.any(i => !comparer ? i == item : comparer.equalsTo(i, item));
        }
        get count() { return this._enumerador.length; }
        static from(items) {
            const result = new List();
            if (items)
                result._enumerador = items;
            return result;
        }
        hasItems() { return this._enumerador && this._enumerador.length > 0; }
        insert(position, item) {
            this._enumerador.splice(position, 0, item);
            this.listChanged();
        }
        join(separator) { return this._enumerador.join(separator || " "); }
        distinct(comparer = null) {
            let result = new List();
            this.forEach(i => {
                if (!result.contains(i, comparer))
                    result.add(i);
            });
            return result;
        }
        first() {
            if (!this.hasItems())
                return null;
            return this._enumerador[0];
        }
        forEach(accion) {
            if (!this._enumerador)
                return;
            for (var i of this._enumerador)
                accion(i);
        }
        groupBy(propertyName) {
            var keys = this.select(i => i[propertyName]).distinct();
            var result = new List();
            keys.forEach(key => result.add({
                key: key,
                items: this.where(i => i[propertyName] == key)
            }));
            return result;
        }
        indice(item) { return this._enumerador.indexOf(item); }
        item(index) { return this._enumerador[index]; }
        indexWhere(condition) {
            for (var i = 0; i < this._enumerador.length; i++)
                if (condition(this.item(i)))
                    return i;
            return null;
        }
        last() {
            if (!this.hasItems())
                return null;
            return this.item(this.count - 1);
        }
        max() {
            var result = null;
            this.forEach(item => result = item > result ? item : result);
            return result;
        }
        orderBy(predicate) {
            var resultArray = this._enumerador.sort((a, b) => {
                var valueA = predicate(a);
                var valueB = predicate(b);
                if (valueA > valueB)
                    return 1;
                if (valueB > valueA)
                    return -1;
                return 0;
            });
            return List.from(resultArray);
        }
        forEachReverse(accion) {
            for (var i = this._enumerador.length - 1; i >= 0; i--)
                accion(this._enumerador[i]);
        }
        static range(from, to) {
            var result = new List();
            if (from > to)
                return result;
            for (var i = from; i <= to; i++)
                result.add(i);
            return result;
        }
        remove(item) {
            const index = this._enumerador.indexOf(item);
            if (index >= 0)
                this._enumerador.splice(index, 1);
            this.listChanged();
        }
        removeItem(index) {
            this._enumerador.splice(index, 1);
        }
        removeLast(count = 1) {
            var limit = this.count - count;
            for (var i = this.count - 1; i >= limit; i--)
                this.removeItem(i);
        }
        removeWhere(condition) {
            this._enumerador = this.where(i => !condition(i)).toArray();
        }
        reverse() {
            const result = new List();
            var array = this._enumerador;
            result.addMany(array.map((x, y) => array[array.length - 1 - y]));
            return result;
        }
        select(selector) {
            var retorno = new List();
            this.forEach(i => retorno.add(selector(i)));
            return retorno;
        }
        skip(n) {
            var result = new List();
            for (var i = n; i < this.count; i++)
                result.add(this.item(i));
            return result;
        }
        sum(selector) {
            var result = 0;
            this.forEach(i => result += selector(i));
            return result;
        }
        take(quantity) {
            const result = new List();
            for (var i = 0; i < quantity && i < this.count - 1; i++)
                result.add(this.item(i));
            return result;
        }
        that(condicion) {
            if (!this._enumerador)
                return null;
            for (var i of this._enumerador)
                if (condicion(i))
                    return i;
            return null;
        }
        toArray() { return this._enumerador; }
        union(items) {
            var nuevosItems = List.from(items);
            nuevosItems.forEach(item => {
                if (!this.contains(item))
                    this.add(item);
            });
            return this;
        }
        empty() {
            this._enumerador = [];
            this.listChanged();
        }
        where(condition) {
            var result = new List();
            this.forEach(i => { if (condition(i))
                result.add(i); });
            return result;
        }
        listChanged() {
            if (this.onListChanged)
                this.onListChanged();
        }
    }
    Sol.List = List;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ControlList extends Sol.List {
        addMany(items) {
            var controls;
            if (items instanceof Sol.List)
                controls = items.toArray();
            else
                controls = items;
            super.addMany(controls);
            let modoSol = this.parent && this.parent.modoSol;
            for (var item of controls) {
                if (!item.parent)
                    item.parent = this.parent;
                if (modoSol) {
                    item.abrir();
                    item.parent.html.appendChild(item.html);
                    item.registerEvents();
                }
            }
            return this;
        }
        add(item) {
            if (!item)
                return;
            super.add(item);
            if (!item.parent)
                item.parent = this.parent;
            if (this.parent && this.parent.modoSol && this.parent.html) {
                item.abrir();
                item.parent.html.appendChild(item.html);
                item.registerEvents();
            }
        }
        insert(pos, item) {
            pos = pos < 0 ? this.count + pos + 1 : pos;
            super.insert(pos, item);
            item.parent = this.parent;
            if (this.parent && this.parent.modoSol) {
                item.abrir();
                if (this.count == 1 || pos >= this.count - 1)
                    item.parent.html.appendChild(item.html);
                else
                    this._enumerador[pos + 1].html.before(item.html);
                item.registerEvents();
            }
        }
        remove(item) {
            if (!item)
                return;
            item.destroy();
            super.remove(item);
            if (this.parent &&
                this.parent.modoSol &&
                (item === null || item === void 0 ? void 0 : item.html) instanceof HTMLElement &&
                item.html.parentNode)
                item.html.parentNode.removeChild(item.html);
        }
        removeItem(index) {
            var item = this.item(index);
            if (!item)
                return;
            item.destroy();
            super.removeItem(index);
            if (this.parent && this.parent.modoSol && item.html && item.html.parentNode)
                item.html.parentNode.removeChild(item.html);
        }
        empty() {
            super.empty();
            this.forEachReverse(ctr => ctr.destroy());
            if (this.parent && this.parent.modoSol && this.parent.html)
                while (this.parent.html.firstChild)
                    this.parent.html.removeChild(this.parent.html.firstChild);
        }
    }
    Sol.ControlList = ControlList;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ClasesCss extends Sol.List {
        add(item) {
            if (!item)
                return;
            super.add(item);
            if (this.parent && this.parent.html && this.parent.modoSol)
                this.parent.html.classList.add(item);
        }
        empty() {
            super.empty();
            if (this.parent && this.parent.html && this.parent.modoSol)
                this.parent.html.className = "";
        }
        remove(item) {
            if (!item)
                return;
            super.remove(item);
            if (this.parent && this.parent.html && this.parent.modoSol)
                this.parent.html.classList.remove(item);
        }
        removeAll(items) {
            Sol.List.from(items).forEach(i => this.remove(i));
        }
        toggle(item) {
            if (this.contains(item))
                this.remove(item);
            else
                this.add(item);
        }
        toggleValue(item, value) {
            if (!value)
                this.remove(item);
            else
                this.add(item);
        }
    }
    Sol.ClasesCss = ClasesCss;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Attributes extends Sol.KeyValueCollection {
        definir(item, valor) {
            super.definir(item, valor);
            if (this.parent.modoSol && this.parent.html)
                this.parent.html.setAttribute(item, valor);
        }
        remove(key) {
            super.remove(key);
            if (this.parent.modoSol && this.parent.html)
                this.parent.html.removeAttribute(key);
        }
    }
    Sol.Attributes = Attributes;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class FrameworkConfig {
    }
    FrameworkConfig.controlCounter = 1;
    Sol.FrameworkConfig = FrameworkConfig;
    class Control {
        constructor(tagName) {
            this.tag = "div";
            this.atributos = new Sol.Attributes();
            this.css = new Sol.ClasesCss();
            this.clickResult = false;
            this.controls = new Sol.ControlList();
            this.estilos = new Sol.Estilos();
            this.modoSol = false;
            this.tagCerrada = false;
            this._transparent = false;
            this._visible = true;
            if (tagName)
                this.tag = tagName;
            this.html = document.createElement(this.tag);
            this.id = "c" + FrameworkConfig.controlCounter++;
            this.atributos.parent = this;
            this.controls.parent = this;
            this.estilos.parent = this;
            this.css.parent = this;
        }
        get alto() {
            if (this.modoSol)
                this._alto = parseFloat(getComputedStyle(this.html, null).height.replace("px", ""));
            return this._alto;
        }
        set alto(valor) {
            this._alto = valor;
            if (this.modoSol)
                this.estilos.definir("height", valor + "px");
        }
        get ancho() {
            if (this.modoSol)
                this._ancho = parseFloat(getComputedStyle(this.html, null).width.replace("px", ""));
            return this._ancho;
        }
        set ancho(valor) {
            this._ancho = valor;
            if (this.modoSol)
                this.estilos.definir("width", valor + "px");
        }
        get htmlContent() { return this.modoSol && this.html ? this.html.innerHTML : this._htmlContent; }
        set htmlContent(value) {
            this._htmlContent = value;
            if (this.modoSol && this.html)
                this.html.innerHTML = value;
        }
        get id() { return this.html.id; }
        set id(value) { this.html.id = value; }
        get tagName() { return this.tag; }
        get tip() {
            return this._tip;
        }
        set tip(value) {
            this._tip = value;
            this.atributos.definir("title", value);
        }
        get text() {
            if (this.modoSol && this.html) {
                for (var i = 0; i < this.html.childNodes.length; i++) {
                    if (this.html.childNodes.item(i).nodeType == 3) {
                        this._text = this.html.childNodes.item(i).data;
                        break;
                    }
                }
            }
            return this._text;
        }
        set text(value) {
            if (this._text == value)
                return;
            this.removeAllTextNodes();
            this._text = value;
            if (this.modoSol && this.html) {
                if (this._text && this._text.length > 0 && this._text[0] == '&')
                    this.html.innerHTML = this._text;
                else
                    this.html.textContent = value;
            }
        }
        get transparent() {
            if (this.modoSol)
                this._transparent = this.html.style.visibility == "hidden";
            return this._transparent;
        }
        set transparent(valor) {
            this._transparent = valor;
            if (this.modoSol)
                this.html.style.visibility = valor ? "hidden" : "visible";
        }
        get visible() {
            if (this.modoSol)
                this._visible = this.html && (this.html.offsetWidth > 0 || this.html.offsetHeight > 0);
            return this._visible;
        }
        set visible(value) {
            let oldValue = this._visible;
            this._visible = value;
            if (this.modoSol) {
                if (value)
                    this.show();
                else
                    this.hide();
                if (!oldValue && value && this.onExhibido)
                    this.onExhibido(this);
            }
        }
        abrir(target) {
            this.render();
            if (target) {
                document.querySelector(target).appendChild(this.html);
                this.registerEvents();
                window.dispatchEvent(new Event('resize'));
            }
            return this.html.outerHTML;
        }
        add(control) {
            this.controls.add(control);
        }
        addMany(items) {
            return this.controls.addMany(items);
        }
        addCtr(text = null, css = null, tag = "div") {
            const result = Control.create(text, css, tag);
            this.add(result);
            return result;
        }
        applyFormat(format) {
            if (format.FontColor)
                this.estilos.definir("color", format.FontColor);
            else
                this.estilos.remove("color");
            if (format.BackColor)
                this.estilos.definir("background-color", format.BackColor);
            else
                this.estilos.remove("background-color");
        }
        hide() {
            if (this.html)
                this.html.style.display = "none";
        }
        destroy() {
            if (this.modoSol && this.html && this.html.parentNode)
                this.html.parentNode.removeChild(this.html);
            this.modoSol = false;
            if (this.controls)
                this.controls.forEach(ctr => ctr.destroy());
            this.atributos = null;
            this.css = null;
            this.estilos = null;
            this.text = null;
            this.onClick = null;
            this.onMouseEnter = null;
            this.onMouseLeave = null;
        }
        registerEvents() {
            if (this.onDragStart)
                (this.html.ondragstart = ev => this.onDragStart(this, ev));
            if (this.onDragEnter)
                (this.html.ondragenter = ev => this.onDragEnter(this, ev));
            if (this.onDragLeave)
                (this.html.ondragleave = ev => this.onDragLeave(this, ev));
            if (this.onDragOver)
                (this.html.ondragover = ev => this.onDragOver(this, ev));
            if (this.onDrop)
                (this.html.ondrop = ev => this.onDrop(this, ev));
            if (this.onMouseDown)
                (this.html.onmousedown = () => this.onMouseDown());
            this.controls.forEach(ctr => ctr.registerEvents());
            if (this.defaultFormat)
                this.applyFormat(this.defaultFormat);
        }
        show() {
            if (this.html)
                this.html.style.display = null;
            if (this.html && window.getComputedStyle(this.html, null).display == "none")
                this.html.style.display = "initial";
            if (this.onExhibido)
                this.onExhibido(this);
        }
        build() { }
        startRender() {
            if (!!this.tag)
                this.atributos.forEach(attr => this.html.setAttribute(attr.key, attr.value));
            if (this.htmlContent)
                this.html.innerHTML = this.htmlContent;
            else if (this.text && !this.textAfterControls) {
                if (this.text.length > 0 && this.text[0] == '&')
                    this.html.innerHTML = this.text;
                else {
                    this.removeAllTextNodes();
                    this.html.appendChild(document.createTextNode(this.text));
                }
            }
        }
        preClick(e) {
            this.clickEvent = e;
            if (this.onClick)
                this.onClick(this);
            if (!this.clickResult)
                e.stopPropagation();
            return this.clickResult;
        }
        prerender() {
            if (this.onClick)
                this.html.onclick = e => this.preClick(e);
            if (this.onDoubleClick)
                this.html.ondblclick = () => this.onDoubleClick();
            if (this.onMouseEnter)
                this.html.onmouseenter = () => this.onMouseEnter();
            if (this.onMouseLeave)
                this.html.onmouseleave = () => this.onMouseLeave();
            if (this.draggable)
                this.atributos.agregar("draggable", "true");
            if (this.transparent == true)
                this.estilos.definir("visibility", "hidden");
            if (!this.visible)
                this.estilos.definir("display", "none");
            if (this.alto)
                this.estilos.definir("height", this.alto + "px");
            if (this.ancho)
                this.estilos.definir("width", this.ancho + "px");
            if (this.css.join() != "")
                this.atributos.agregar("class", this.css.join());
            if (!this.estilos.estaVacia())
                this.atributos.agregar("style", this.estilos.toString());
        }
        render() {
            this.modoSol = false;
            this.build();
            this.prerender();
            this.startRender();
            this.controls.forEach(ctr => {
                if (!ctr.parent)
                    ctr.parent = this;
                ctr.render();
                this.html.appendChild(ctr.html);
            });
            if (this.text && this.textAfterControls) {
                if (this.text.length > 0 && this.text[0] == '&')
                    this.html.innerHTML = this.text;
                else {
                    this.removeAllTextNodes();
                    this.html.appendChild(document.createTextNode(this.text));
                }
            }
            this.modoSol = true;
        }
        removeAllTextNodes() {
            let nodes = this.html.childNodes;
            for (let i = nodes.length - 1; i >= 0; i--) {
                const node = nodes[i];
                if (node.nodeType === Node.TEXT_NODE)
                    this.html.removeChild(node);
            }
        }
        static create(text = null, cssClass = null, tag = "div") {
            const ctr = new Control(tag);
            if (text)
                ctr.text = text;
            if (cssClass)
                ctr.css.add(cssClass);
            return ctr;
        }
    }
    Sol.Control = Control;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class RequiredIcon extends Sol.Control {
        constructor() {
            super("span");
            this.css.add("sol_required_icon");
            this.text = "&#xf12a;";
            this.tip = Sol.Environment.resources.required;
        }
    }
    Sol.RequiredIcon = RequiredIcon;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Label extends Sol.Control {
        constructor(text) {
            super("label");
            this.countDisplay = new Sol.Control("span");
            this.requiredIcon = new Sol.RequiredIcon();
            this.disableAsterisk = false;
            this.text = text;
        }
        get expanded() { return this.editor.visible; }
        set expanded(v) {
            if (!this.minimizable)
                return;
            this.editor.visible = v;
            this.css.remove("sol_label_expanded");
            this.css.remove("sol_label_minimized");
            this.css.add(v ? "sol_label_expanded" : "sol_label_minimized");
        }
        get showRequiredIcon() { return this.requiredIcon.visible; }
        set showRequiredIcon(value) { this.requiredIcon.visible = value; }
        setCount(value) {
            this.countDisplay.text = value ? " (" + value.toString() + ')' : "";
        }
        build() {
            super.build();
            if (this.editor)
                this.atributos.agregar("for", this.editor.id);
            this.requiredIcon.visible = !this.disableAsterisk && this.editor && this.editor.required && !this.editor.readonly;
            this.add(this.requiredIcon);
            if (this.minimizable)
                this.onClick = () => this.expanded = !this.expanded;
            if (this.largeDescription)
                this.initializeLargeDescriptionButton();
            if (this.editor)
                this.add(this.countDisplay);
        }
        initializeLargeDescriptionButton() {
            const description = new Sol.Control("span");
            description.text = "&#xf128;";
            description.css.add("sol_label_large_description");
            description.tip = this.largeDescription;
            this.add(description);
        }
    }
    Sol.Label = Label;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let FieldVisibility;
    (function (FieldVisibility) {
        FieldVisibility[FieldVisibility["Never"] = 0] = "Never";
        FieldVisibility[FieldVisibility["OnlyInserting"] = 1] = "OnlyInserting";
        FieldVisibility[FieldVisibility["OnlyEditing"] = 2] = "OnlyEditing";
        FieldVisibility[FieldVisibility["Always"] = 3] = "Always";
        FieldVisibility[FieldVisibility["OnlyFilter"] = 4] = "OnlyFilter";
        FieldVisibility[FieldVisibility["OnlyColumn"] = 5] = "OnlyColumn";
        FieldVisibility[FieldVisibility["HiddenIfReadonlyAndEmpty"] = 6] = "HiddenIfReadonlyAndEmpty";
        FieldVisibility[FieldVisibility["Hidden"] = 7] = "Hidden";
    })(FieldVisibility = Sol.FieldVisibility || (Sol.FieldVisibility = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let SelectorType;
    (function (SelectorType) {
        SelectorType[SelectorType["None"] = 0] = "None";
        SelectorType[SelectorType["Simple"] = 1] = "Simple";
        SelectorType[SelectorType["Complex"] = 2] = "Complex";
    })(SelectorType = Sol.SelectorType || (Sol.SelectorType = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        let FormPosition;
        (function (FormPosition) {
            FormPosition[FormPosition["form"] = 0] = "form";
            FormPosition[FormPosition["toolBox"] = 1] = "toolBox";
            FormPosition[FormPosition["totalization"] = 2] = "totalization";
        })(FormPosition = Web.FormPosition || (Web.FormPosition = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let CapitalizationMode;
    (function (CapitalizationMode) {
        CapitalizationMode[CapitalizationMode["None"] = 0] = "None";
        CapitalizationMode[CapitalizationMode["Lowercase"] = 1] = "Lowercase";
        CapitalizationMode[CapitalizationMode["Uppercase"] = 2] = "Uppercase";
    })(CapitalizationMode = Sol.CapitalizationMode || (Sol.CapitalizationMode = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let Alignment;
    (function (Alignment) {
        Alignment[Alignment["Left"] = 0] = "Left";
        Alignment[Alignment["Right"] = 1] = "Right";
        Alignment[Alignment["Center"] = 2] = "Center";
    })(Alignment = Sol.Alignment || (Sol.Alignment = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let VerticalAlignment;
    (function (VerticalAlignment) {
        VerticalAlignment[VerticalAlignment["Center"] = 0] = "Center";
        VerticalAlignment[VerticalAlignment["Top"] = 1] = "Top";
        VerticalAlignment[VerticalAlignment["Bottom"] = 2] = "Bottom";
    })(VerticalAlignment = Sol.VerticalAlignment || (Sol.VerticalAlignment = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let EditorErrorState;
    (function (EditorErrorState) {
        EditorErrorState[EditorErrorState["Normal"] = 0] = "Normal";
        EditorErrorState[EditorErrorState["Error"] = 1] = "Error";
    })(EditorErrorState = Sol.EditorErrorState || (Sol.EditorErrorState = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Field extends Sol.Control {
        constructor(tagName) {
            super(tagName ? tagName : "input");
            this._errorState = Sol.EditorErrorState.Normal;
            this.onFocus = new Sol.EventHandler();
            this.onInput = new Sol.EventHandler();
            this.onLeave = new Sol.EventHandler();
            this.onSet = new Sol.EventHandler();
            this.onValueModified = new Sol.EventHandler();
            this.disableEnter = false;
            this.alignment = Sol.Alignment.Left;
            this.anchoAutomatico = false;
            this.autoWidth = true;
            this.autoResize = false;
            this.useWrapper = true;
            this.capitalizacion = Sol.CapitalizationMode.None;
            this.isComplex = false;
            this.required = false;
            this.soloNumeros = false;
            this.textBold = false;
            this.css.add("sol_campo");
            this.tagCerrada = true;
        }
        get errorState() { return this._errorState; }
        set errorState(value) {
            this._errorState = value;
            value === Sol.EditorErrorState.Error ? this.css.add("sol_field_error") : this.css.remove("sol_field_error");
        }
        get htmlInput() { return this.html; }
        get onChange() { return this._onChange; }
        set onChange(value) {
            this._onChange = value;
            this.setOnChanged(value);
        }
        get inputType() { return this.htmlInput.type; }
        set inputType(value) { this.htmlInput.type = value; }
        get selectedText() {
            return this.htmlInput.value.substring(this.htmlInput.selectionStart, this.htmlInput.selectionEnd) || this.value;
        }
        toControl() { return this; }
        isEmpty() { var _a; return !this.textValue || ((_a = this.textValue) === null || _a === void 0 ? void 0 : _a.trim()) == ""; }
        foco() {
            if (!this.html)
                return;
            try {
                this.html.focus();
            }
            catch (_a) { }
        }
        clear() {
            if (!isNaN(this.defaultValue))
                this.value = this.defaultValue;
            else
                this.value = "";
        }
        limpiarTexto() { this.textValue = this.textValue.soloDigitos(); }
        validate() {
            if (this.mask && !this.applyMask())
                return Sol.Environment.resources.empty_field + this.caption + Sol.Environment.resources.format + this.mask;
            if (this.isEmpty() && !this.required)
                return null;
        }
        get posicionCursor() {
            var cursorPosition = 0;
            if ('selectionStart' in this.html)
                cursorPosition = this.htmlInput.selectionStart;
            else if ('selection' in document) {
                this.htmlInput.focus();
                var vDocument = document;
                var vSelection = vDocument.selection.createRange();
                var vSize = vDocument.selection.createRange().text.length;
                vSelection.moveStart('character', -this.htmlInput.value.length);
                cursorPosition = vSelection.text.length - vSize;
            }
            return cursorPosition;
        }
        get placeHolder() { return this._placeHolder; }
        set placeHolder(value) {
            this._placeHolder = value;
            this.atributos.definir("placeholder", value);
        }
        get mask() { return this._mask; }
        set mask(value) {
            this._mask = value;
            this.applyMask();
        }
        selectAllText() { this.htmlInput.select(); }
        selectText(inicio, fin) {
            if (this.value.length == 0)
                return;
            if (this.htmlInput["createTextRange"]) {
                var selection = this.htmlInput.TextRange();
                selection.collapse(true);
                selection.moveEnd('character', inicio);
                selection.moveStart('character', fin);
                selection.select();
            }
            else if (this.htmlInput.setSelectionRange) {
                this.htmlInput.focus();
                this.htmlInput.setSelectionRange(inicio, fin);
            }
        }
        get readonly() { return this._readonly; }
        set readonly(value) {
            value = value && !this.alwaysEditable;
            this._readonly = value;
            if (value) {
                this.atributos.definir("readonly", "readonly");
                this.css.add("solo_lectura");
            }
            else {
                this.atributos.remove("readonly");
                this.css.remove("solo_lectura");
            }
        }
        get textValue() {
            if (this.modoSol && this.html)
                this._textValue = this.htmlInput.value;
            if (this._textValue && this.capitalizacion == Sol.CapitalizationMode.Lowercase)
                this._textValue = this._textValue.toLowerCase();
            else if (this._textValue && this.capitalizacion == Sol.CapitalizationMode.Uppercase)
                this._textValue = this._textValue.toUpperCase();
            return this._textValue;
        }
        set textValue(value) { this.setTextValue(value); }
        get value() { return this.textValue; }
        set value(v) {
            this.textValue = v;
            this.onSet.invoke();
            if (this.onValueChanged)
                this.onValueChanged(this);
        }
        filterNumber(e) {
            var excepciones = [8, 46, 37, 39];
            if (Sol.List.from(excepciones).contains(e.which))
                return true;
            if (e.which < 48 || e.which > 57)
                return false;
            return true;
        }
        registerEvents() {
            super.registerEvents();
            this.onFocus.connect(this, "focus");
            this.onLeave.connect(this, "blur");
            this.onInput.connect(this, "input");
            this.onValueModified.connect(this, "change");
        }
        setValueWhenEmpty(value) {
            if (!this.value)
                this.value = value;
        }
        build() {
            const TAMANO_GRANDE = 370;
            super.build();
            if (this.inputMode)
                this.atributos.agregar("inputmode", this.inputMode);
            if (this.autoResize && this.textValue)
                this.atributos.agregar("size", (this.textValue.length + 2).toString());
            if (this.maxLength)
                this.atributos.agregar("maxlength", this.maxLength.toString());
            if (this.minLength)
                this.atributos.agregar("minlength", this.minLength.toString());
            this.atributos.agregar("autocomplete", this.autoCompleteKey || "off");
            if (this.alignment == Sol.Alignment.Right)
                this.estilos.definir("text-align", "right");
            if (this.alignment == Sol.Alignment.Center)
                this.estilos.definir("text-align", "center");
            if (this.capitalizacion == Sol.CapitalizationMode.Lowercase)
                this.estilos.definir("text-transform", "lowercase");
            else if (this.capitalizacion == Sol.CapitalizationMode.Uppercase)
                this.estilos.definir("text-transform", "uppercase");
            if (this.required)
                this.atributos.agregar("required");
            if (this.disableEnter)
                this.atributos.agregar("disableenter");
            if (this.defaultValue)
                this.atributos.agregar("value", this.defaultValue);
            if (this.maxLength > 32 && this.autoWidth)
                this.ancho = TAMANO_GRANDE;
            if (this.textBold)
                this.estilos.agregar("font-weight", "bold");
            this.onLeave.subscribe(() => this.applyMask());
            if (this.readonly) {
                this.atributos.agregar("readonly");
                this.css.add("solo_lectura");
            }
            this.html.onkeyup = () => {
                if (this.anchoAutomatico)
                    this.teclaLiberada();
                if (this.autoResize)
                    this.autoResizeField();
            };
            if (this.soloNumeros)
                this.html.onkeypress = e => this.filterNumber(e);
            if (this.onKeyUp)
                this.html.onkeyup = e => this.onKeyUp(e);
            if (this.onKeyDown)
                this.html.onkeydown = e => this.onKeyDown(e);
            if (this.onKeyPress)
                this.html.onkeypress = e => this.onKeyPress(e);
            if (this.soloNumeros)
                this.html.onblur = () => this.onFieldLeave();
            if (this.onChange)
                this.html.onchange = () => this.onChange;
            if (this.inputOptions)
                this.configureInputOptions();
        }
        setOnChanged(value) { }
        setTextValue(value) {
            this._textValue = value;
            if (this.modoSol && this.html)
                this.htmlInput.value = value;
            else if (this.tag === "input" && this.atributos)
                this.atributos.definir("value", value);
        }
        applyMask() {
            if (this.isEmpty() || !this.mask)
                return;
            var input = this.value.getLettersAndNumbers();
            var inputPos = input.length - 1;
            var result = "";
            for (var maskPos = this.mask.length - 1; maskPos >= 0; maskPos--) {
                var curMask = this.mask[maskPos];
                var curInput = inputPos >= 0 ? input[inputPos] : '0';
                if (curMask == 'X') {
                    result = curInput.toUpperCase() + result;
                    inputPos--;
                }
                else if (curMask == '9') {
                    if (!curInput.isNumeric())
                        return false;
                    result = curInput + result;
                    inputPos--;
                }
                else
                    result = curMask + result;
            }
            this.value = result;
            return true;
        }
        teclaLiberada() {
            if (!this.anchoAutomatico)
                return;
            var nWidth = this.textValue.length * 9;
            if (nWidth < this.ancho)
                nWidth = this.ancho;
            this.htmlInput.width = nWidth;
        }
        onFieldLeave() {
            if (this.soloNumeros)
                this.limpiarTexto();
        }
        autoResizeField() {
            if (!this.autoResize)
                return;
            this.htmlInput.size = this.textValue.length + 2;
        }
        configureInputOptions() {
            let allowedRegex = "";
            if (this.inputOptions.allowNumbers)
                allowedRegex += "0-9";
            if (this.inputOptions.allowLetters)
                allowedRegex += "A-Z";
            if (this.inputOptions.specialChars)
                allowedRegex += this.inputOptions.specialChars;
            let regex = new RegExp("([^" + allowedRegex + "])", "gi");
            this.onInput.subscribe(() => {
                let start = this.htmlInput.selectionStart;
                let end = this.htmlInput.selectionEnd;
                const current = this.htmlInput.value;
                const corrected = current.replace(regex, '');
                this.htmlInput.value = corrected;
                if (corrected.length < current.length)
                    --end;
                this.htmlInput.setSelectionRange(start, end);
            });
        }
    }
    Sol.Field = Field;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ExtensibleField extends Sol.Control {
        constructor() {
            super();
            this.mainField = new Sol.Field();
            this.useWrapper = true;
            this.add(this.mainField);
            this.css.add("sol_extensible_field");
        }
        get errorState() { return this.mainField.errorState; }
        set errorState(value) { this.mainField.errorState = value; }
        get required() { return this.mainField.required; }
        set required(v) { this.mainField.required = v; }
        get readonly() { return this.mainField.readonly; }
        set readonly(v) { this.mainField.readonly = v; }
        get onLeave() { return this.mainField.onLeave; }
        set onLeave(v) { this.mainField.onLeave = v; }
        get onFocus() { return this.mainField.onFocus; }
        set onFocus(v) { this.mainField.onFocus = v; }
        get textValue() { return this.mainField.textValue; }
        set textValue(v) { this.mainField.textValue = v; }
        get alignment() { return this.mainField.alignment; }
        set alignment(v) { this.mainField.alignment = v; }
        get placeHolder() { return this.mainField.placeHolder; }
        set placeHolder(v) { this.mainField.placeHolder = v; }
        get value() { return this.getValue(); }
        set value(v) { this.setValue(v); }
        clear() { this.mainField.clear(); }
        foco() { this.mainField.foco(); }
        isEmpty() { return this.mainField.isEmpty(); }
        toControl() { return this; }
        validate() { return this.mainField.validate(); }
        getValue() { return this.mainField.value; }
        setValue(v) { this.mainField.value = v; }
    }
    Sol.ExtensibleField = ExtensibleField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let AccessType;
    (function (AccessType) {
        AccessType[AccessType["External"] = 0] = "External";
        AccessType[AccessType["Internal"] = 1] = "Internal";
    })(AccessType = Sol.AccessType || (Sol.AccessType = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Http;
    (function (Http) {
        class AjaxRequest {
            constructor(request) {
                this.request = request;
            }
            abort() {
                this.request.abort();
            }
        }
        Http.AjaxRequest = AjaxRequest;
    })(Http = Sol.Http || (Sol.Http = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Http;
    (function (Http) {
        class Ajax {
            static get(url, success, error) {
                var request = new XMLHttpRequest();
                request.onreadystatechange = function () {
                    if (this.readyState == 4) {
                        if (this.status == 200) {
                            var data = null;
                            if (this.responseText)
                                data = JSON.parse(this.responseText);
                            if (success)
                                success(data);
                        }
                        else if (error)
                            error();
                    }
                };
                request.open("GET", url, true);
                request.setRequestHeader("Access-Control-Allow-Origin", "*");
                request.setRequestHeader("Access-Control-Allow-Headers", "*");
                request.setRequestHeader("Accept", "application/json");
                request.send();
            }
            static post(url, data, success, error) {
                try {
                    if (!navigator.onLine && Sol.Web.System.version !== "beta" && !this.isDialogVisible) {
                        const conectionError = new Sol.NoConnectionDialog();
                        Sol.Web.System.screens.add(conectionError);
                        conectionError.visible = true;
                        this.isDialogVisible = true;
                        conectionError.onClose = () => this.isDialogVisible = false;
                        return;
                    }
                    var request = new XMLHttpRequest();
                    var failed;
                    request.onreadystatechange = function () {
                        if (this.readyState == 4) {
                            if (this.status == 200) {
                                var data = null;
                                if (this.responseText)
                                    data = JSON.parse(this.responseText);
                                if (success)
                                    success(data);
                            }
                            else if (error && !failed) {
                                failed = true;
                                error();
                            }
                        }
                        else if (this.status == 500 && error && !failed) {
                            failed = true;
                            error();
                            request.abort();
                            return;
                        }
                    };
                    request.onerror = function () { if (error)
                        error(); };
                    request.open("POST", Sol.Environment.systemUrl + url);
                    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                    request.send(JSON.stringify(data));
                }
                catch (_a) {
                    if (error)
                        error();
                    else
                        throw 0;
                }
                return new Http.AjaxRequest(request);
            }
            static exec(url, manager, method, data, success = null, error = null) {
                var request = {
                    credential: Sol.Environment.credential.ticket ? Sol.Environment.credential.export() : null,
                    manager: manager,
                    method: method,
                    data: JSON.stringify(data)
                };
                Http.Ajax.post(url, request, e => { if (success)
                    success(e); }, () => { if (error)
                    error(); });
            }
            static postAsync(url, data) {
                return __awaiter(this, void 0, void 0, function* () {
                    const xhr = new XMLHttpRequest();
                    return new Promise(resolve => {
                        xhr.open("POST", url, true);
                        xhr.onload = () => {
                            var data = null;
                            if (xhr.responseText)
                                data = JSON.parse(xhr.responseText);
                            resolve(data);
                        };
                        xhr.onerror = () => resolve(null);
                        xhr.setRequestHeader('Content-Type', 'application/json');
                        data !== null && data !== void 0 ? data : (data = {});
                        xhr.send(JSON.stringify(data));
                    });
                });
            }
        }
        Ajax.isDialogVisible = false;
        Http.Ajax = Ajax;
    })(Http = Sol.Http || (Sol.Http = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Http;
    (function (Http) {
        class AjaxLight {
            static get(url, success, error) {
                var request = new XMLHttpRequest();
                request.onreadystatechange = function () {
                    if (this.readyState == 4) {
                        if (this.status == 200) {
                            var data = null;
                            if (this.responseText)
                                data = JSON.parse(this.responseText);
                            if (success)
                                success(data);
                        }
                        else if (error)
                            error();
                    }
                };
                request.open("GET", url, true);
                request.setRequestHeader("Access-Control-Allow-Origin", "*");
                request.setRequestHeader("Access-Control-Allow-Headers", "*");
                request.setRequestHeader("Accept", "application/json");
                request.send();
            }
            static post(url, data, success, error) {
                try {
                    var request = new XMLHttpRequest();
                    var failed;
                    request.onreadystatechange = function () {
                        if (this.readyState == 4) {
                            if (this.status == 200) {
                                var data = null;
                                if (this.responseText)
                                    data = JSON.parse(this.responseText);
                                if (success)
                                    success(data);
                            }
                            else if (error && !failed) {
                                failed = true;
                                error();
                            }
                        }
                        else if (this.status == 500 && error && !failed) {
                            failed = true;
                            error();
                            request.abort();
                            return;
                        }
                    };
                    request.onerror = function () { if (error)
                        error(); };
                    request.open("POST", Sol.Environment.systemUrl + url);
                    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                    request.send(JSON.stringify(data));
                }
                catch (_a) {
                    if (error)
                        error();
                    else
                        throw 0;
                }
                return new Http.AjaxRequest(request);
            }
            static exec(manager, method, data, success = null, error = null) {
                var request = {
                    credential: Sol.Environment.credential.ticket ? Sol.Environment.credential.export() : null,
                    manager: manager,
                    method: method,
                    data: JSON.stringify(data)
                };
                Http.AjaxLight.post("/exec", request, e => { if (success)
                    success(e); }, () => { if (error)
                    error(); });
            }
            static postAsync(url, data) {
                return __awaiter(this, void 0, void 0, function* () {
                    const xhr = new XMLHttpRequest();
                    return new Promise(resolve => {
                        xhr.open("POST", url, true);
                        xhr.onload = () => {
                            var data = null;
                            if (xhr.responseText)
                                data = JSON.parse(xhr.responseText);
                            resolve(data);
                        };
                        xhr.onerror = () => resolve(null);
                        xhr.setRequestHeader('Content-Type', 'application/json');
                        data !== null && data !== void 0 ? data : (data = {});
                        xhr.send(JSON.stringify(data));
                    });
                });
            }
        }
        Http.AjaxLight = AjaxLight;
    })(Http = Sol.Http || (Sol.Http = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Http;
    (function (Http) {
        class Push {
            constructor(group, code, onMessage) {
                this.pushUrl = "https://push.letrearte.com/";
                this.group = group;
                this.code = code;
                if (!onMessage)
                    return;
                Sol.Environment.loadLibrary({
                    name: "signalr",
                    source: "/frameworks/signalr.js"
                });
                const timeout = setTimeout(() => {
                    if (!signalR)
                        return;
                    let hubUrl = this.pushUrl + "solhub?g=" + group + "&c=" + code;
                    console.log(hubUrl);
                    this.connection = new signalR.HubConnectionBuilder().withUrl(hubUrl).build();
                    this.connection.start();
                    this.connection.on("SolHubMessage", (e) => onMessage(e));
                    clearTimeout(timeout);
                }, 1000);
            }
            notify() {
                Http.AjaxLight.post("/push", { group: this.group, companyID: this.code }, null, null);
            }
        }
        Http.Push = Push;
    })(Http = Sol.Http || (Sol.Http = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Http;
    (function (Http) {
        class UploadEngine {
            constructor() {
                this.request = new XMLHttpRequest();
                this.request.onreadystatechange = () => this.uploadCompleted();
                this.request.upload.onprogress = e => this.reportProgress(e);
                this.request.onprogress = e => this.reportProgress(e);
            }
            get downloadUrl() { return Sol.Environment.filePath + this.identifier; }
            get url() { return Sol.Environment.fileServer + "/image/"; }
            process(file) {
                const formData = new FormData();
                formData.append("archivo", file);
                this.request.open("POST", Sol.Environment.uploadPath);
                this.request.send(formData);
            }
            reportProgress(e) {
                const progress = Math.ceil((e.loaded / e.total) * 100);
                if (this.onProgress)
                    this.onProgress(progress);
            }
            uploadCompleted() {
                if (this.request.readyState !== 4)
                    return;
                var model = JSON.parse(this.request.response);
                if (!model.Fail) {
                    this.code = model.ID;
                    this.identifier = model.Identifier;
                    this.size = model.Size;
                    this.extension = model.Extension;
                    if (this.onUploadComplete)
                        this.onUploadComplete();
                }
            }
        }
        Http.UploadEngine = UploadEngine;
    })(Http = Sol.Http || (Sol.Http = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Globalization;
    (function (Globalization) {
        class BrazilianCulture {
            formatCurrency(value) {
                var formatter = new Intl.NumberFormat("pt-Br", {
                    style: 'currency',
                    currency: "BRL",
                    minimumFractionDigits: 2
                });
                var result = formatter.format(value);
                return result.replace("R$", "R$ ");
            }
            getMonthNames() {
                return Sol.List.from(["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]);
            }
        }
        Globalization.BrazilianCulture = BrazilianCulture;
    })(Globalization = Sol.Globalization || (Sol.Globalization = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Text extends Sol.Control {
        constructor() {
            super();
            this.tag = null;
        }
    }
    Sol.Text = Text;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class LineBreak extends Sol.Control {
        constructor() {
            super("br");
            this.tagCerrada = true;
        }
    }
    Sol.LineBreak = LineBreak;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Loader extends Sol.Control {
        constructor() {
            super();
            this.css.add("sol_loader");
            this.visible = false;
            for (var i = 1; i <= 5; i++) {
                var ctrLoader = new Sol.Control("span");
                ctrLoader.css.add("sol_loader" + i);
                this.add(ctrLoader);
            }
        }
    }
    Sol.Loader = Loader;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ProgressBar extends Sol.Control {
        constructor() {
            super("progress");
            this._valor = 0;
            this.maximo = 100;
        }
        get valor() { return this._valor; }
        set valor(valor) {
            this._valor = valor;
            this.tip = Math.round(valor) + '%';
            if (this.modoSol)
                this.atributos.definir("value", valor.toString());
        }
        build() {
            this.atributos.agregar("max", this.maximo.toString());
            this.atributos.agregar("value", this.valor.toString());
            super.build();
        }
    }
    Sol.ProgressBar = ProgressBar;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class SolIcon extends Sol.Control {
        constructor(key) {
            super("icon");
            this.imageSize = 18;
            this.imageKey = key;
            this.css.add("sol_icon");
        }
        build() {
            super.build();
            this.estilos.agregar("background-image", "url('" + Sol.Environment.systemUrl + "/theme/resources/icon/" + this.imageKey + ".png')");
            this.estilos.agregar("width", this.imageSize + "px");
            this.estilos.agregar("height", this.imageSize + "px");
        }
    }
    Sol.SolIcon = SolIcon;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let ButtonType;
    (function (ButtonType) {
        ButtonType[ButtonType["Normal"] = 0] = "Normal";
        ButtonType[ButtonType["Link"] = 1] = "Link";
        ButtonType[ButtonType["Custom"] = 2] = "Custom";
        ButtonType[ButtonType["Alternate"] = 3] = "Alternate";
    })(ButtonType = Sol.ButtonType || (Sol.ButtonType = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Popup extends Sol.Control {
        constructor() {
            super("ul");
            this.autoClose = true;
            this.autoWidth = true;
            this.css.add("sol_popup");
        }
        showAtCaret() {
            const pos = this.getCaretTopPoint();
            this.html.style.top = "calc(var(--popupVertOffset) + " + (pos.top + 10) + "px)";
            this.html.style.left = pos.left + "px";
            this.show();
        }
        clearContent() { this.controls.empty(); }
        show() {
            if (this.autoWidth && this.parent)
                this.estilos.definir("min-width", this.parent.ancho + "px");
            super.show();
        }
        build() {
            super.build();
            if (!this.autoClose)
                this.css.add("sol_popup_manual");
        }
        getCaretTopPoint() {
            const selection = document.getSelection();
            const range = selection.getRangeAt(0);
            let rectangle;
            let range2;
            const node = range.startContainer;
            const offset = range.startOffset;
            if (offset > 0) {
                range2 = document.createRange();
                range2.setStart(node, (offset - 1));
                range2.setEnd(node, offset);
                rectangle = range2.getBoundingClientRect();
                return { left: rectangle.right, top: rectangle.top };
            }
            else if (offset < node.length) {
                range2 = document.createRange();
                range2.setStart(node, offset);
                range2.setEnd(node, (offset + 1));
                rectangle = range2.getBoundingClientRect();
                return { left: rectangle.left, top: rectangle.top };
            }
            else {
                rectangle = node.getBoundingClientRect();
                const styles = getComputedStyle(node);
                const lineHeight = parseInt(styles.lineHeight);
                const fontSize = parseInt(styles.fontSize);
                const delta = (lineHeight - fontSize) / 2;
                return { left: rectangle.left, top: (rectangle.top + delta) };
            }
        }
    }
    Sol.Popup = Popup;
})(Sol || (Sol = {}));
document.onmouseup = e => {
    const popups = document.querySelectorAll(".sol_popup");
    const path = Sol.List.from(e.composedPath());
    var popupElem;
    popups.forEach(popup => {
        popupElem = popup;
        if (!path.any(el => el.id == popup.id) && popupElem.style.display != "none") {
            popupElem.style.display = "none";
            popupElem["onHiding"] = true;
        }
    });
};
var Sol;
(function (Sol) {
    class Button extends Sol.Control {
        constructor() {
            super("button");
            this._enabled = true;
            this._checked = false;
            this.icon = new Sol.Control("i");
            this.popup = new Sol.Popup();
            this.counter = new Sol.Control("span");
            this.subitems = new Sol.List();
            this.type = Sol.ButtonType.Normal;
            this.tipoHtml = "button";
            this.onFocus = new Sol.EventHandler();
            this.onLeave = new Sol.EventHandler();
        }
        get accessKey() { return this._accessKey; }
        set accessKey(value) {
            this._accessKey = value;
            this.atributos.definir("accesskey", value);
        }
        get enabled() {
            if (this.modoSol && this.html)
                this._enabled = !this.html.disabled;
            return this._enabled;
        }
        set enabled(v) {
            this._enabled = v;
            if (this.modoSol && this.html) {
                this.html.removeAttribute("disabled");
                if (!this._enabled)
                    this.html.setAttribute("disabled", "disabled");
            }
        }
        get checked() { return this._checked; }
        set checked(value) {
            this._checked = value;
            this.css.remove("chequeado");
            if (this._checked)
                this.css.add("chequeado");
        }
        get imageCode() { return this.icon.text; }
        set imageCode(v) { this.icon.text = v; }
        addIcon(iconKey) { this.controls.insert(0, new Sol.SolIcon(this.imageKey = iconKey)); }
        focus() { if (this.html)
            this.html.focus(); }
        hidePopup() { this.popup.visible = false; }
        registerEvents() {
            super.registerEvents();
            this.onFocus.connect(this, "focus");
            this.onLeave.connect(this, "blur");
        }
        build() {
            super.build();
            this.textAfterControls = true;
            if (this.type != Sol.ButtonType.Custom)
                this.css.add("sol_boton");
            this.atributos.agregar("type", this.tipoHtml);
            if (this.type == Sol.ButtonType.Link)
                this.css.add("sol_boton_enlace");
            if (!this.enabled)
                this.atributos.agregar("disabled");
            if (this.imageCode)
                this.add(this.icon);
            if (this.imageKey)
                this.addIcon(this.imageKey);
            if (this.abbreviation) {
                var abbrControl = new Sol.Control("abbr");
                abbrControl.text = this.abbreviation;
                if (this.abbreviationColor)
                    abbrControl.estilos.agregar("background-color", this.abbreviationColor);
                this.add(abbrControl);
            }
            this.counter.visible = this.counterValue > 0;
            if (this.counterColor)
                this.counter.estilos.agregar("background-color", this.counterColor);
            if (this.showCounter)
                this.add(this.counter);
            if (this.type === Sol.ButtonType.Alternate)
                this.onClick = () => this.meCheckClick();
            if (this.subitems.hasItems()) {
                this.css.add("sol_boton_subitems");
                this.subitems.forEach(s => {
                    if (this.onSubitemClick)
                        s.onClick = () => {
                            this.onSubitemClick(s);
                            this.popup.visible = false;
                        };
                    this.popup.add(s);
                });
                this.popup.visible = false;
                this.onClick = () => this.meClick();
                this.add(this.popup);
            }
        }
        setCounterValue(valor) {
            this.counterValue = valor;
            this.counter.text = valor.toString();
            this.counter.visible = valor > 0;
        }
        meClick() {
            this.popup.visible = !this.popup.visible;
        }
        meCheckClick() {
            this.checked = !this.checked;
            if (this.onChecked)
                this.onChecked();
        }
    }
    Sol.Button = Button;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let MessageType;
    (function (MessageType) {
        MessageType[MessageType["Error"] = 0] = "Error";
        MessageType[MessageType["Success"] = 1] = "Success";
        MessageType[MessageType["Confirmation"] = 2] = "Confirmation";
        MessageType[MessageType["Information"] = 3] = "Information";
        MessageType[MessageType["Alert"] = 4] = "Alert";
    })(MessageType = Sol.MessageType || (Sol.MessageType = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ScreenMessage extends Sol.Control {
        constructor() {
            super();
            this.okButton = new Sol.Button();
            this.cancelButton = new Sol.Button();
            this.descriptionDisplay = new Sol.Control();
            this.captionControl = new Sol.Control();
            this.closeWhenTap = true;
            this.onCancel = null;
            this.onConfirm = null;
            this.type = Sol.MessageType.Error;
            this.css.add("sol_mensaje");
            this.captionControl.css.add("sol_mensaje_caption");
            this.add(this.captionControl);
            this.descriptionDisplay.css.add("sol_mensaje_description");
            this.add(this.descriptionDisplay);
        }
        get caption() { return this.captionControl.text; }
        set caption(s) { this.setCaption(s); }
        setCaption(value) {
            this.captionControl.text = value || "";
        }
        build() {
            super.build();
            switch (this.type) {
                case Sol.MessageType.Error:
                    this.css.add("sol_mensaje_error");
                    break;
                case Sol.MessageType.Success:
                    this.css.add("sol_mensaje_exito");
                    break;
                case Sol.MessageType.Confirmation:
                    this.css.add("sol_mensaje_confirmacion");
                    break;
                case Sol.MessageType.Information:
                    this.css.add("sol_mensaje_aviso");
                    break;
                case Sol.MessageType.Alert:
                    this.css.add("sol_mensaje_alert");
                    break;
            }
            this.descriptionDisplay.text = this.description;
            if (this.type == Sol.MessageType.Confirmation) {
                this.okButton.text = this.okButtonText || "OK";
                this.okButton.css.add("boton_ok");
                this.cancelButton.text = Sol.Environment.resources.cancelar;
                this.cancelButton.css.add("boton_cancelar");
                this.add(this.okButton);
                this.add(this.cancelButton);
                this.cancelButton.onClick = () => this.cancelClick();
                this.okButton.onClick = () => this.confirmClick();
            }
            else
                this.onClick = () => this.tap();
        }
        tap() {
            if (this.closeWhenTap)
                this.visible = false;
            if (this.type == Sol.MessageType.Confirmation)
                this.cancelClick();
        }
        cancelClick() {
            if (this.onCancel)
                this.onCancel(this);
        }
        confirmClick() {
            if (this.onConfirm)
                this.onConfirm(this);
        }
    }
    Sol.ScreenMessage = ScreenMessage;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ScreenMessageItem extends Sol.Control {
        constructor(text, relatedEditor, messageCode) {
            super();
            this.text = text;
            this.relatedEditor = relatedEditor;
            this.messageCode = messageCode;
            if (relatedEditor)
                this.css.add("sol_screen_message_item");
        }
    }
    Sol.ScreenMessageItem = ScreenMessageItem;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ScreenMessageList extends Sol.ScreenMessage {
        get items() { return this.captionControl.controls.cast(); }
        addItem(text, relatedEditor, messageCode) {
            this.removeItem(relatedEditor, messageCode);
            const item = new Sol.ScreenMessageItem(text, relatedEditor, messageCode);
            if (relatedEditor)
                relatedEditor.errorState = Sol.EditorErrorState.Error;
            item.onClick = () => { var _a; return (_a = item.relatedEditor) === null || _a === void 0 ? void 0 : _a.foco(); };
            this.captionControl.add(item);
        }
        removeItem(relatedEditor, messageCode) {
            let item = this.items.that(i => i.relatedEditor == relatedEditor && i.messageCode == messageCode);
            this.captionControl.controls.remove(item);
            if (!this.captionControl.controls.hasItems())
                this.hide();
        }
        clearItems() {
            var _a;
            (_a = this.captionControl.controls) === null || _a === void 0 ? void 0 : _a.empty();
            this.hide();
        }
        setErrors(errors) {
            this.clearItems();
            errors.forEach(e => this.addItem(e.text, e.relatedEditor, e.messageCode));
        }
        setItem(text, relatedEditor, messageCode) {
            this.clearItems();
            this.addItem(text, relatedEditor, messageCode);
        }
        setCaption(value) { this.setItem(value); }
    }
    Sol.ScreenMessageList = ScreenMessageList;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Form extends Sol.Control {
        constructor() {
            super();
            this.titleControl = new Sol.Control("h4");
            this.loader = new Sol.Loader();
            this.error = new Sol.ScreenMessageList();
            this.cancelButton = new Sol.Button();
            this.editors = new Sol.List();
            this.footer = new Sol.Control("footer");
            this.okButton = new Sol.Button();
            this.showCancelButton = true;
            this.showOkButton = true;
            this.css.add("sol_form");
            this.okButton.text = Sol.Environment.resources.ok;
            this.onExhibido = () => this.focus();
            this.error.visible = false;
            this.error.closeWhenTap = false;
            this.add(this.error);
        }
        focus() {
            var firstEditor = this.controls.that(ctr => ctr._IEditor && !ctr.readonly);
            if (firstEditor)
                firstEditor.foco();
        }
        getEditor(propertyName) {
            if (!propertyName)
                return null;
            const path = propertyName.split('$');
            var container = this;
            var editor = this.editors.that(e => e.propertyName == propertyName);
            for (var part of path) {
                if (!container || !container.editors)
                    return null;
                editor = container.editors.that(e => e.propertyName == part);
                container = editor;
            }
            return editor;
        }
        hideMessages(relatedEditor, messageCode) {
            if (relatedEditor)
                this.error.removeItem(relatedEditor, messageCode);
            else
                this.error.clearItems();
        }
        showError(message, relatedEditor, messageCode) {
            if (relatedEditor)
                this.error.addItem(message, relatedEditor, messageCode);
            else
                this.error.setItem(message);
            this.error.visible = true;
            this.workComplete();
            window.scrollTo(0, 0);
        }
        showErrors(errors) {
            this.error.setErrors(errors);
            this.error.visible = true;
            this.workComplete();
            window.scrollTo(0, 0);
        }
        setEditorValue(propertyName, value) {
            const field = this.getEditor(propertyName);
            if (field)
                field.value = value;
        }
        toControl() {
            return this;
        }
        workComplete() {
            this.loader.visible = false;
        }
        build() {
            super.build();
            if (this.title) {
                this.titleControl.text = this.title;
                this.controls.insert(0, this.titleControl);
            }
            this.initializeFooter();
            this.configureEnterKey();
        }
        cancel() {
            if (this.loader.visible)
                return false;
            if (this.onCancel)
                this.onCancel(this);
            return false;
        }
        configureEnterKey() {
            if (!this.okButton.visible)
                return;
            setTimeout(() => {
                if (!this.html)
                    return;
                var inputs = this.html.getElementsByTagName("input");
                [].forEach.call(inputs, i => {
                    if (!i.hasAttribute("disableenter"))
                        i.addEventListener("keyup", event => {
                            if (event.key !== "Enter")
                                return;
                            if (this.okButton && this.okButton.onClick)
                                this.okButton.onClick();
                            event.preventDefault();
                        });
                });
            }, 300);
        }
        initializeFooter() {
            if (!this.footer.visible)
                return;
            this.add(this.footer);
            if (this.showCancelButton) {
                this.footer.controls.insert(0, this.cancelButton);
                if (!this.cancelButton.text)
                    this.cancelButton.text = Sol.Environment.resources.cancelar;
                this.cancelButton.css.add("sol_formulario_cancelar");
                this.cancelButton.parent = this;
                this.cancelButton.onClick = () => this.cancel();
            }
            if (this.showOkButton) {
                this.okButton.css.add("sol_formulario_ok");
                this.okButton.onClick = () => this.save();
                this.footer.add(this.okButton);
                this.footer.add(this.loader);
            }
            if (this.okIcon) {
                var icono = new Sol.Control("i");
                icono.text = this.okIcon;
                this.okButton.add(icono);
            }
        }
        save() {
            if (this.loader.visible)
                return false;
            this.error.visible = false;
            this.editors.forEach(edt => edt.errorState = Sol.EditorErrorState.Normal);
            if (!this.validateEmptyFields(this.editors))
                return;
            if (!this.validateFields(this.editors))
                return;
            if (this.onValidate) {
                var validation = this.onValidate(this);
                if (!validation.success) {
                    if (validation.message) {
                        this.showError(validation.message.replace(":", ""));
                        window.scrollTo(0, 0);
                    }
                    return false;
                }
            }
            if (this.onSave) {
                this.loader.visible = true;
                this.onSave(this);
            }
            return false;
        }
        validateEmptyFields(editors) {
            let emptyFields = editors.where(edt => edt.required && edt.visible && edt.isEmpty());
            if (emptyFields.hasItems()) {
                this.showErrors(emptyFields.select(f => ({
                    text: Sol.Environment.resources.empty_field + f.caption,
                    relatedEditor: f
                })));
                window.scrollTo({ top: 0, behavior: 'smooth' });
                return false;
            }
            return true;
        }
        validateFields(editors) {
            for (var editor of editors.toArray()) {
                let validationMessage = editor.validate();
                if (validationMessage) {
                    this.showError(validationMessage);
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                    return false;
                }
            }
            return true;
        }
    }
    Sol.Form = Form;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class FieldWrapper extends Sol.Control {
        constructor() {
            super();
            this.css.add("sol_detalles_wrapper");
        }
    }
    Sol.FieldWrapper = FieldWrapper;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class NotesField extends Sol.Control {
        constructor() {
            super("p");
            this.autoHeight = true;
            this.isComplex = true;
            this.minHeight = 40;
            this.spellCheck = true;
            this.css.addMany(["sol_campo", "sol_notes_field"]);
            this.atributos.agregar("contenteditable", "true");
        }
        get readonly() { return this._readonly; }
        set readonly(value) {
            this._readonly = value;
            this.atributos.definir("contenteditable", value ? "false" : "true");
        }
        get value() { return this.htmlContent; }
        set value(v) { this.htmlContent = v; }
        clear() { this.value = ""; }
        foco() { }
        isEmpty() { var _a; return !((_a = this.value) === null || _a === void 0 ? void 0 : _a.removeHtmlTags().trim()); }
        ;
        toControl() { return this; }
        validate() { return null; }
        build() {
            if (!this.autoHeight)
                this.css.add("sol_text_field_limited_height");
            if (!this.spellCheck)
                this.atributos.definir("spellcheck", "false");
            if (this.onChange)
                this.html.onchange = () => this.onChange();
            super.build();
        }
    }
    Sol.NotesField = NotesField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class TextField extends Sol.Field {
        constructor() {
            super("textarea");
            this.autoHeight = true;
            this.spellCheck = true;
            this.tagCerrada = false;
            this.estilos.agregar("resize", "none");
            this.estilos.agregar("overflow", "hidden");
            this.isComplex = true;
            this.autoWidth = false;
            this.useWrapper = false;
            this.onSet.subscribe(() => this.adjustHeight());
        }
        build() {
            if (this.autoHeight) {
                this.onKeyUp = () => this.adjustHeight();
                this.onValueChanged = () => this.adjustHeight();
            }
            if (!this.spellCheck)
                this.atributos.definir("spellcheck", "false");
            super.build();
            this.atributos.definir("type", null);
            this.adjustHeight();
        }
        adjustHeight() {
            var _a, _b;
            const OFFSET = 0;
            const curDisplay = (_a = this.html) === null || _a === void 0 ? void 0 : _a.style.display;
            this.estilos.definir("display", "block");
            this.estilos.definir("height", "1px");
            this.estilos.definir("height", Math.max(this.minHeight ? this.minHeight : 25, (((_b = this.html) === null || _b === void 0 ? void 0 : _b.scrollHeight) || 0) - OFFSET) + "px");
            if (this.html)
                this.html.style.display = curDisplay;
        }
        setOnChanged(value) { this.adjustHeight(); }
        setTextValue(value) {
            super.setTextValue(value);
            if (!this.modoSol || !this.html) {
                this.htmlContent = value;
                setTimeout(() => this.adjustHeight(), 300);
            }
        }
    }
    Sol.TextField = TextField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class PasswordField extends Sol.ExtensibleField {
        constructor() {
            super(...arguments);
            this.passwordButton = new Sol.Button();
            this.showButton = true;
        }
        get showPassword() { return this._showPassword; }
        set showPassword(value) {
            this._showPassword = value;
            this.mainField.atributos.definir("type", value ? "text" : "password");
            this.passwordButton.imageCode = value ? "&#xf070;" : "&#xf06e;";
            this.passwordButton.tip = value ? Sol.Environment.resources.password_field : Sol.Environment.resources.password_field_hide;
        }
        build() {
            this.css.add("sol_password_field");
            this.mainField.inputType = "password";
            this.mainField.maxLength = 16;
            this.passwordButton.imageCode = "&#xf06e;";
            this.passwordButton.type = Sol.ButtonType.Custom;
            this.passwordButton.tip = Sol.Environment.resources.password_field;
            this.passwordButton.visible = this.showButton;
            this.passwordButton.onClick = () => this.showPassword = !this.showPassword;
            this.add(this.passwordButton);
            super.build();
        }
    }
    Sol.PasswordField = PasswordField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class EmailField extends Sol.Field {
        build() {
            this.atributos.definir("type", "email");
            this.maxLength = 255;
            this.estilos.definir("width", "255px");
            this.capitalizacion = Sol.CapitalizationMode.Lowercase;
            super.build();
            this.ancho = null;
        }
    }
    Sol.EmailField = EmailField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class UrlField extends Sol.ExtensibleField {
        constructor() {
            super(...arguments);
            this.urlButton = new Sol.Button();
            this.showButton = true;
        }
        clear() {
            super.clear();
            this.urlButton.enabled = false;
        }
        build() {
            super.build();
            this.mainField.atributos.definir("type", "url");
            this.mainField.disableEnter = true;
            this.mainField.maxLength = 255;
            this.mainField.onLeave.subscribe(() => this.leave());
            this.mainField.onKeyUp = () => this.urlButton.enabled = !this.isEmpty();
            this.urlButton.imageCode = "&#xf0ac;";
            this.urlButton.onClick = () => window.open(this.mainField.value, "_blank");
            this.urlButton.enabled = false;
            this.urlButton.visible = this.showButton;
            this.add(this.urlButton);
        }
        setValue(v) {
            super.setValue(v);
            this.urlButton.enabled = !this.isEmpty();
        }
        leave() {
            var regExUrl = /^((?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/;
            if (regExUrl.test(this.mainField.textValue) && this.mainField.textValue.indexOf("http://") === -1)
                this.mainField.textValue = "http://" + this.mainField.textValue;
        }
    }
    Sol.UrlField = UrlField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class DateField extends Sol.Field {
        constructor() {
            super();
            this.useWrapper = true;
            this.atributos.definir("type", "date");
        }
        get dateValue() { return Date.convert(this.textValue); }
        set dateValue(value) { this.value = value.formatear(); }
        setToday() {
            var today = new Date();
            this.value = today.formatear();
        }
        build() {
            super.build();
            if (this.maxValue)
                this.atributos.agregar("max", this.maxValue.formatear());
        }
        addDays(days) {
            var newDate = new Date(this.dateValue);
            newDate.setDate(newDate.getDate() + days);
            this.value = newDate.formatear();
        }
        addMonths(months) {
            var newDate = new Date(this.dateValue);
            newDate.setMonth(newDate.getMonth() + months);
            this.value = newDate.formatear();
        }
    }
    Sol.DateField = DateField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class DateTimeField extends Sol.Field {
        constructor() {
            super();
            this.atributos.definir("type", "datetime-local");
        }
        build() {
            super.build();
            if (this.useCurrentDateTimeAsDefault && this.isEmpty())
                this.value = Date.getClientDateTime();
        }
    }
    Sol.DateTimeField = DateTimeField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class TimeField extends Sol.Field {
        constructor() {
            super();
            this.atributos.definir("type", "time");
        }
    }
    Sol.TimeField = TimeField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class IntegerField extends Sol.Field {
        constructor() {
            super();
            this.useWrapper = true;
            this.atributos.definir("type", "number");
            this.css.add("sol_numeric_field");
        }
        isEmpty() { return !parseInt(this.value); }
        get numericValue() { return parseInt(this.value) || 0; }
        set numericValue(v) { this.value = v.toString(); }
        build() {
            super.build();
            if (!this.allowNegative)
                this.atributos.definir("min", "0");
            if (this.maxValue)
                this.atributos.definir("max", this.maxValue.toString());
        }
        setOnChanged(value) {
            if (this.onChange)
                this.html.oninput = () => this.onChange();
        }
    }
    Sol.IntegerField = IntegerField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class TimeStampField extends Sol.Control {
        constructor() {
            super();
            this.hoursField = new Sol.IntegerField();
            this.minutesField = new Sol.IntegerField();
            this.useWrapper = true;
            this.onValueModified = new Sol.EventHandler();
            this.css.addMany(["sol_timestamp_field", "sol_campo"]);
            const separator = new Sol.Control("span");
            separator.text = ':';
            this.minutesField.maxLength = 2;
            this.minutesField.onValueModified.subscribe(() => this.onValueModified.invoke());
            this.hoursField.onValueModified.subscribe(() => this.onValueModified.invoke());
            this.addMany([this.hoursField, separator, this.minutesField]);
        }
        get readonly() { return this.hoursField.readonly; }
        set readonly(value) {
            this.hoursField.readonly = value;
            this.minutesField.readonly = value;
        }
        get value() { return this.hoursField.value + ':' + this.minutesField.value; }
        set value(v) {
            this.clear();
            if (!v)
                return;
            let values = v.split(":");
            this.hoursField.value = values[0];
            this.minutesField.value = values[1];
        }
        clear() {
            this.hoursField.clear();
            this.minutesField.clear();
        }
        foco() { }
        isEmpty() { return true; }
        toControl() { return this; }
        validate() { return null; }
    }
    Sol.TimeStampField = TimeStampField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class VehiclePlateField extends Sol.Field {
        constructor() {
            super();
            this.plate = new RegExp(/^[A-Z]{3}[- ]?\d[A-Z0-9][A-Z0-9]\d$/);
            this.maxLength = 8;
        }
        validate() {
            return !this.plate.test(this.value.toUpperCase()) ? "Favor informar uma placa de veículo válida." : null;
        }
    }
    Sol.VehiclePlateField = VehiclePlateField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class WeekDaysField extends Sol.Control {
        constructor() {
            super();
            this.sundayCheck = new Sol.Check();
            this.mondayCheck = new Sol.Check();
            this.tuesdayCheck = new Sol.Check();
            this.wednesdayCheck = new Sol.Check();
            this.thursdayCheck = new Sol.Check();
            this.fridayCheck = new Sol.Check();
            this.saturdayCheck = new Sol.Check();
            this.holidayCheck = new Sol.Check();
            this.allChecks = Sol.List.from([this.sundayCheck, this.mondayCheck, this.tuesdayCheck, this.wednesdayCheck, this.thursdayCheck, this.fridayCheck, this.saturdayCheck, this.holidayCheck]);
            this.isComplex = false;
            this.initializeChecks();
            this.css.add("sol_week_days_field");
        }
        get value() {
            var result = "";
            this.allChecks.forEach(ck => result += ck.checked ? "1" : "0");
            return result;
        }
        set value(valorStr) {
            this.clear();
            if (!valorStr)
                return;
            if (valorStr.length != 8)
                return;
            var i = 0;
            this.allChecks.forEach(ck => ck.checked = valorStr[i++] === "1");
        }
        toControl() { return this; }
        isEmpty() {
            return this.allChecks.all(ck => !ck.checked);
        }
        clear() {
            this.allChecks.forEach(ck => ck.checked = false);
        }
        validate() { return null; }
        initializeChecks() {
            this.sundayCheck.caption = Sol.Environment.resources.sunday;
            this.add(this.sundayCheck);
            this.mondayCheck.caption = Sol.Environment.resources.monday;
            this.add(this.mondayCheck);
            this.tuesdayCheck.caption = Sol.Environment.resources.tuesday;
            this.add(this.tuesdayCheck);
            this.wednesdayCheck.caption = Sol.Environment.resources.wednesday;
            this.add(this.wednesdayCheck);
            this.thursdayCheck.caption = Sol.Environment.resources.thursday;
            this.add(this.thursdayCheck);
            this.fridayCheck.caption = Sol.Environment.resources.friday;
            this.add(this.fridayCheck);
            this.saturdayCheck.caption = Sol.Environment.resources.saturday;
            this.add(this.saturdayCheck);
            this.holidayCheck.caption = Sol.Environment.resources.holiday;
            this.add(this.holidayCheck);
        }
        foco() {
            throw new Error("Method not implemented.");
        }
    }
    Sol.WeekDaysField = WeekDaysField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class NumericField extends Sol.Control {
        constructor() {
            super("input");
            this.decimalTyping = false;
            this.useWrapper = true;
            this._decimals = 0;
            this._errorState = Sol.EditorErrorState.Normal;
            this.isComplex = false;
            this.numberStyle = "decimal";
            this.tamanoMaximo = 18;
            this.onValueModified = new Sol.EventHandler();
            this.onSet = new Sol.EventHandler();
            this.onFocus = new Sol.EventHandler();
            this.tagCerrada = true;
            this.css.add("sol_campo");
            this.atributos.definir("type", "text");
            this.atributos.definir("inputmode", "numeric");
            this.atributos.definir("pattern", "[0-9]*");
            this.atributos.definir("autocomplete", "off");
            this.estilos.definir("text-align", "right");
            this.onClick = () => this.fieldClick();
            this.html.onkeydown = e => this.keyDownEvent(e);
            this.html.onkeyup = e => this.keyUpEvent(e);
            this.onFocus.subscribe(() => this.selectAllText());
        }
        get decimalPosition() { return this.htmlInput.value.indexOf(Sol.Environment.resources.decimal); }
        get decimals() { return this._decimals; }
        set decimals(value) {
            this._decimals = value;
            this.presentNumber(this.value);
        }
        get readonly() { return this._readonly; }
        set readonly(value) {
            this._readonly = value;
            if (value) {
                this.atributos.definir("readonly", "readonly");
                this.css.add("solo_lectura");
            }
            else {
                this.atributos.remove("readonly");
                this.css.remove("solo_lectura");
            }
        }
        get errorState() { return this._errorState; }
        set errorState(value) {
            this._errorState = value;
            value === Sol.EditorErrorState.Error ? this.css.add("sol_field_error") : this.css.remove("sol_field_error");
        }
        get formattedValue() { return this.formatNumber(this.value); }
        get htmlInput() { return this.html; }
        set onModified(fn) {
            var i = setInterval(() => {
                if (!this.htmlInput)
                    return;
                this.htmlInput.addEventListener("change", () => fn(this));
                clearInterval(i);
            }, 300);
        }
        get value() {
            if (!this.htmlInput && this.waitingValue)
                return this.waitingValue;
            if (!this.htmlInput)
                return 0;
            var currentNumber = parseInt((this.isNegative ? "-" : "0") + this.htmlInput.value.replace(/\D/g, ''));
            if (this.decimalPosition !== -1) {
                var decimalCount = this.htmlInput.value.length - this.decimalPosition - 1;
                var zeros = "";
                for (var i = 0; i < decimalCount; i++)
                    zeros += "0";
                currentNumber /= parseInt("1" + zeros);
            }
            return currentNumber;
        }
        set value(value) {
            if (value < 0 && !this.acceptsNegative)
                value *= -1;
            this.setValue(value);
        }
        get numericValue() { return this.value; }
        set numericValue(v) { this.value = v; }
        enableNegative(enabled) { this.acceptsNegative = enabled; }
        formatNumber(v) {
            return v.toLocaleString(Sol.Environment.language, {
                style: this.numberStyle,
                currency: this.currency,
                minimumFractionDigits: this.decimals,
                maximumFractionDigits: this.decimals
            });
        }
        toControl() { return this; }
        isEmpty() { return this.value == 0; }
        foco() {
            if (!this.htmlInput)
                return;
            this.htmlInput.focus();
            setTimeout(() => this.htmlInput.select(), 400);
        }
        clear() { this.htmlInput.value = ""; }
        registerEvents() {
            super.registerEvents();
            this.onFocus.connect(this, "focus");
            if (this.onValueModified.any()) {
                var i = setInterval(() => {
                    if (!this.htmlInput)
                        return;
                    this.htmlInput.addEventListener("change", () => this.onValueModified.invoke());
                    clearInterval(i);
                }, 300);
            }
        }
        refreshNumber() {
            if (!this.htmlInput)
                return;
            if (this.decimalPosition == -1)
                this.decimalTyping = false;
            this.presentNumber(this.value);
            this.setCursorPosition(this.previousPosition + this.positionVariation);
        }
        selectAllText() { this.htmlInput.select(); }
        validate() { return null; }
        build() {
            super.build();
            if (this.required)
                this.atributos.agregar("required");
            this.atributos.definir("maxlength", this.tamanoMaximo.toString());
            if (this.defaultValue && !this.isSet)
                this.atributos.definir("value", this.formatNumber(this.defaultValue));
        }
        fieldClick() {
            const decimalPos = this.htmlInput.value.indexOf(Sol.Environment.resources.decimal);
            const curPos = this.getCursorPosition();
            this.decimalTyping = curPos >= decimalPos;
        }
        getCursorPosition() {
            return this.htmlInput.selectionStart;
        }
        keyDownEvent(e) {
            var keyCode = e.keyCode;
            var which = e.which;
            var ctrlKey = e.ctrlKey;
            this.blockKey = false;
            this.positionVariation = 0;
            this.previousText = this.htmlInput.value;
            this.previousPosition = this.getCursorPosition();
            if ((keyCode >= 112 && keyCode <= 123) || (keyCode >= 91 && keyCode <= 93) ||
                (keyCode >= 9 && keyCode <= 31) || (keyCode < 8 && (which === 0 || which === keyCode)) ||
                keyCode === 144 || keyCode === 145 || keyCode === 45 || keyCode === 224) {
                this.blockKey = true;
                return true;
            }
            if (keyCode == 109 || keyCode == 189) {
                if (this.acceptsNegative)
                    this.isNegative = true;
                this.refreshNumber();
                return false;
            }
            if (keyCode == 107 || keyCode == 187) {
                this.isNegative = false;
                this.refreshNumber();
                return false;
            }
            if (ctrlKey) {
                this.blockKey = true;
                return true;
            }
            if (keyCode >= 34 && keyCode <= 40) {
                this.blockKey = true;
                return true;
            }
            if (this.readonly) {
                this.blockKey = true;
                return false;
            }
            if (keyCode == 46) {
                this.blockKey = true;
                return true;
            }
            if (keyCode == 8) {
                if (this.previousText[this.previousPosition - 1] == Sol.Environment.resources.decimal)
                    return false;
                this.positionVariation--;
                return true;
            }
            if (keyCode == 110 || keyCode == 188 || keyCode == 190 || e.key == ',') {
                var decimalPosition = this.decimalPosition;
                if (decimalPosition !== -1)
                    this.htmlInput.setSelectionRange(decimalPosition + 1, this.htmlInput.value.length);
                this.decimalTyping = true;
                this.blockKey = true;
                return false;
            }
            if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || !isNaN(parseFloat(e.key))) {
                this.positionVariation++;
                return true;
            }
            return false;
        }
        keyUpEvent(e) {
            if (!this.blockKey && this.previousText != this.htmlInput.value)
                this.refreshNumber();
            return true;
        }
        presentNumber(v) {
            if (!this.htmlInput)
                return;
            this.htmlInput.value = this.formatNumber(v);
        }
        setCursorPosition(pos) {
            var text = this.htmlInput.value;
            var counter = 0;
            var considerZero = this.value < 1;
            var thousands = 0;
            for (var i = 0; i < text.length; i++) {
                if (text[i] == Sol.Environment.resources.millar) {
                    pos++;
                    thousands++;
                    counter++;
                    continue;
                }
                if (text[i] == Sol.Environment.resources.decimal)
                    pos -= thousands;
                if (!this.decimalTyping && text[i] == Sol.Environment.resources.decimal) {
                    this.htmlInput.setSelectionRange(i, i);
                    return;
                }
                var numberCheck = "123456789";
                if (considerZero)
                    numberCheck += "0";
                if (numberCheck.indexOf(text[i]) !== -1) {
                    if (counter == pos) {
                        this.htmlInput.setSelectionRange(i, i);
                        return;
                    }
                    considerZero = true;
                }
                counter++;
            }
            var nextPosition = text.length;
            if (!this.decimalTyping) {
                nextPosition -= this.decimals;
                if (this.decimals > 0)
                    nextPosition--;
            }
            this.htmlInput.setSelectionRange(nextPosition, nextPosition);
        }
        setValue(v) {
            this.isNegative = v < 0;
            this.isSet = true;
            this.setForeColor(v);
            if (this.html) {
                this.waitingValue = null;
                this.presentNumber(v || 0);
                this.onSet.invoke();
            }
            else {
                this.atributos.definir("value", this.formatNumber(this.value));
                this.waitingValue = v;
                setTimeout(() => {
                    if (this.waitingValue)
                        this.presentNumber(v || 0);
                    this.onSet.invoke();
                }, 300);
            }
        }
        setForeColor(newValue) {
            if (!this.forecolorRedWhenNegative)
                return;
            this.estilos.definir("color", newValue < 0 ? "#FF0000" : null);
        }
    }
    Sol.NumericField = NumericField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class CurrencyField extends Sol.Control {
        constructor() {
            super();
            this.field = new Sol.NumericField();
            this.isComplex = false;
            this.useWrapper = true;
            this.onCurrencyChanged = new Sol.EventHandler();
            this.css.add("sol_currency_field");
            this.selectedCurrency = Sol.Environment.defaultCurrency;
            this.field.numberStyle = "currency";
            this.field.decimals = 2;
            this.add(this.field);
        }
        get selectedCurrency() { return this._selectedCurrency; }
        set selectedCurrency(v) {
            v = v || Sol.Environment.defaultCurrency || { ISO: "BRL", Name: "" };
            this._selectedCurrency = v;
            this.field.currency = v.ISO;
            this.field.refreshNumber();
        }
        get acceptsNegative() { return this.field.acceptsNegative; }
        set acceptsNegative(value) { this.field.acceptsNegative = value; }
        get formatedNumber() { return this.field.formatNumber(this.numericValue); }
        get decimals() { return this.field.decimals; }
        set decimals(value) { this.field.decimals = value; }
        get forecolorRedWhenNegative() { return this.field.forecolorRedWhenNegative; }
        set forecolorRedWhenNegative(v) { this.field.forecolorRedWhenNegative = v; }
        get required() { return this.field.required; }
        set required(v) { this.field.required = v; }
        get readonly() { return this.field.readonly; }
        set readonly(v) { this.field.readonly = v; }
        get errorState() { return this.field.errorState; }
        set errorState(v) { this.field.errorState = v; }
        get textValue() { return this.field.htmlInput.value; }
        set textValue(value) { this.field.htmlInput.value = value; }
        get value() { return this.selectedCurrency.ISO + this.field.value; }
        set value(v) {
            v = v || this.selectedCurrency.ISO + '0';
            var currencyPart = v.substr(0, 3);
            var amountPart = v.substr(3);
            var currencies = Sol.List.from(Sol.Environment.currencies);
            this.selectedCurrency = currencies.that(c => c.ISO == currencyPart);
            this.field.value = parseFloat(amountPart);
        }
        get numericValue() { return this.field.value; }
        set numericValue(v) { this.field.value = v; }
        get onChange() { return this._onChange; }
        set onChange(fn) {
            this._onChange = fn;
            setTimeout(() => { this.field.onModified = () => fn(this.field); }, 300);
        }
        get onValueModified() { return this.field.onValueModified; }
        get onSet() { return this.field.onSet; }
        clear() { this.field.clear(); }
        foco() { this.field.foco(); }
        formatNumber(value) { return this.field.formatNumber(value); }
        isEmpty() { return this.field.isEmpty(); }
        toControl() { return this; }
        validate() { return null; }
        build() {
            super.build();
            if (this.textBold)
                this.field.estilos.agregar("font-weight", "bold");
            this.field.acceptsNegative = this.acceptsNegative;
            if (this.allowChangeCurrency && Sol.Environment.currencies.length > 1)
                this.initializeCurrencySelector();
            if (this.defaultValue)
                this.value = this.defaultValue;
        }
        initializeCurrencySelector() {
            var currencySelector = new Sol.Button();
            var currencies = Sol.List.from(Sol.Environment.currencies);
            currencySelector.imageCode = '&#xf0dd;';
            currencySelector.type = Sol.ButtonType.Custom;
            currencySelector.onSubitemClick = item => this.currencyClick(item);
            currencies.forEach(c => {
                var item = new Sol.Control("li");
                item.text = c.Name;
                item.data = c;
                currencySelector.subitems.add(item);
            });
            this.add(currencySelector);
        }
        currencyClick(item) {
            this.selectedCurrency = item.data;
            this.onCurrencyChanged.invoke();
            if (this.onChange)
                this.onChange();
        }
        static sumFields(fields) {
            const formatterField = new CurrencyField();
            return fields
                .where(f => !!(f === null || f === void 0 ? void 0 : f.selectedCurrency))
                .select(f => f.selectedCurrency.ISO)
                .distinct()
                .select(c => {
                formatterField.value = c + fields.where(f => f.selectedCurrency.ISO == c).sum(f => f.numericValue);
                return formatterField.formatedNumber;
            });
        }
    }
    Sol.CurrencyField = CurrencyField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class CurrencyFilter extends Sol.Control {
        constructor() {
            super();
            this.amountMin = new Sol.CurrencyField();
            this.toLabel = new Sol.Control("span");
            this.amountMax = new Sol.CurrencyField();
            this.isComplex = false;
            this.add(this.amountMin);
            this.toLabel.text = "até";
            this.add(this.toLabel);
            this.add(this.amountMax);
        }
        get value() {
            return {
                Minimum: this.amountMin.numericValue,
                Maximum: this.amountMax.numericValue
            };
        }
        set value(v) { }
        toControl() { return this; }
        isEmpty() {
            return this.amountMin.isEmpty() && this.amountMax.isEmpty();
        }
        foco() { }
        clear() {
            this.amountMin.clear();
            this.amountMax.clear();
        }
        validate() { return null; }
    }
    Sol.CurrencyFilter = CurrencyFilter;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class PercentField extends Sol.NumericField {
        constructor() {
            super();
            this.css.add("sol_percent_field");
            this.decimals = 2;
            this.tamanoMaximo = 6;
        }
    }
    Sol.PercentField = PercentField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class DateRangeField extends Sol.IntegerField {
        build() {
            this.onChange = () => this.calculateEndDate();
            if (this.configuration && this.container) {
                this.startField = this.container.editors.that(cp => cp.propertyName == this.configuration.StartDateProperty);
                this.endField = this.container.editors.that(cp => cp.propertyName == this.configuration.EndDateProperty);
                setTimeout(() => this.startField.html.onchange = e => this.calculateRange(), 300);
                setTimeout(() => this.endField.html.onchange = e => this.calculateRange(), 300);
            }
            super.build();
        }
        calculateEndDate() {
            if (!this.startField || !this.endField || !this.startField.dateValue)
                return;
            this.endField.dateValue = this.startField.dateValue.addDays(parseInt("0" + this.value));
        }
        calculateRange() {
            if (!this.startField || !this.endField || !this.startField.dateValue || !this.endField.dateValue)
                return;
            this.value = this.endField.dateValue.getDaysFrom(this.startField.dateValue).toString();
        }
    }
    Sol.DateRangeField = DateRangeField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ColorField extends Sol.Field {
        build() {
            this.atributos.definir("type", "color");
            super.build();
        }
    }
    Sol.ColorField = ColorField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Check extends Sol.Control {
        constructor(caption, checked) {
            super("label");
            this.allowSaveValueAsDefault = true;
            this.breakInForm = true;
            this.label = new Sol.Control("span");
            this.onFocus = new Sol.EventHandler();
            this.onLeave = new Sol.EventHandler();
            this.onValueModified = new Sol.EventHandler();
            this.onSet = new Sol.EventHandler();
            this.input = new Sol.Control("input");
            this._checked = false;
            this.defaultValue = false;
            this.css.add("sol_check");
            this.input.atributos.agregar("type", "checkbox");
            this.add(this.input);
            this.clickResult = true;
            this.caption = caption;
            if (checked)
                this.checked = true;
        }
        get caption() { return this.label.text; }
        set caption(value) { this.label.text = value; }
        get required() { return false; }
        set required(v) { }
        get onChange() { return this._onChange; }
        set onChange(value) {
            this._onChange = value;
            this.html.onchange = () => this._onChange();
        }
        get checked() {
            if (this.modoSol && this.input.html)
                this._checked = this.input.html.checked;
            return this._checked;
        }
        set checked(valor) {
            var previousValue = this._checked;
            this._checked = valor;
            if (this.modoSol && this.input.html)
                this.input.html.checked = this._checked;
            if (valor != previousValue && this.onChange)
                this.onChange();
        }
        get readonly() {
            var _a;
            return (_a = this.input.atributos) === null || _a === void 0 ? void 0 : _a.toList().any(i => i.key == "disabled");
        }
        set readonly(value) {
            if (this.alwaysEditable)
                value = false;
            if (value)
                this.input.atributos.definir("disabled", "disabled");
            else
                this.input.atributos.remove("disabled");
        }
        validate() { return null; }
        get value() { return this.checked; }
        set value(v) {
            this.checked = v;
            this.defaultValue = null;
            this.onSet.invoke();
        }
        clear() { this.checked = this.defaultValue; }
        build() {
            super.build();
            if (this.label.text)
                this.controls.insert(1, this.label);
            if (this.defaultValue)
                this.checked = true;
            if (this.checked)
                this.input.atributos.agregar("checked");
            if (this.readonly)
                this.input.atributos.agregar("disabled");
            if (this.largeDescription)
                this.initializeLargeDescriptionButton();
            if (this.alwaysEditable)
                this.readonly = false;
        }
        toControl() { return this; }
        isEmpty() { return !this.checked; }
        foco() { if (this.html)
            this.html.focus(); }
        registerEvents() {
            super.registerEvents();
            this.onFocus.connect(this.input, "focus");
            this.onLeave.connect(this.input, "blur");
            this.onValueModified.connect(this.input, "change");
        }
        initializeLargeDescriptionButton() {
            const description = new Sol.Control("span");
            description.text = "&#xf128;";
            description.css.add("sol_label_large_description");
            description.tip = this.largeDescription;
            this.label.add(description);
        }
    }
    Sol.Check = Check;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class RadioField extends Sol.Check {
        constructor() {
            super();
            this.input.atributos.definir("type", "radio");
        }
        build() {
            super.build();
            if (this.group)
                this.input.atributos.agregar("name", this.group);
        }
    }
    Sol.RadioField = RadioField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class MultipleChoice extends Sol.Control {
        constructor() {
            super(...arguments);
            this.inlineItems = true;
            this.onChange = new Sol.EventHandler();
            this.onValueModified = new Sol.EventHandler();
            this.onSet = new Sol.EventHandler();
        }
        get items() { return this.controls.cast(); }
        get readonly() { return this._readonly; }
        set readonly(value) {
            this._readonly = value;
            this.items.forEach(i => i.readonly = value);
        }
        get selectedItem() { return this.items.that(r => r.checked); }
        get options() { return this._options; }
        set options(value) {
            this._options = value;
            this.loadOptions();
        }
        validate() { return null; }
        get selectedCode() {
            if (!this.selectedItem)
                return null;
            return parseInt(this.selectedItem.codigo);
        }
        set selectedCode(value) {
            let item = this.items.that(i => i.codigo == value.toString());
            if (item) {
                this.items.forEach(i => i.checked = false);
                item.checked = true;
                this.onChange.invoke();
            }
        }
        get value() {
            if (!this.selectedItem)
                return { Campo: null, Valor: null };
            return {
                Campo: this.selectedItem.caption,
                Valor: this.selectedItem.codigo
            };
        }
        set value(v) {
            if (!v)
                return;
            var selected = this.items.that(r => r.codigo == v.Valor);
            if (selected)
                selected.value = true;
            this.onSet.invoke();
        }
        loadOptions() {
            if (this.inlineItems)
                this.css.add("sol_multiple_choice_inline");
            const optionList = Sol.List.from(this.options);
            if (optionList.hasItems() && !optionList.any(o => o.Checked))
                optionList.first().Checked = true;
            optionList.forEach(option => {
                const radio = new Sol.RadioField();
                radio.caption = option.Description;
                radio.group = this.id;
                radio.codigo = option.Code;
                radio.checked = option.Checked;
                radio.data = option.Data;
                radio.onChange = () => this.onChange.invoke(this);
                radio.onValueModified.subscribe(() => this.onValueModified.invoke(this));
                this.add(radio);
            });
        }
        isEmpty() { return this.items.all(i => !i.checked); }
        foco() { this.items.first().foco(); }
        registerEvents() {
            super.registerEvents();
            this.onSet.invoke();
        }
        setSelectedIndex(index) {
            this.items.item(index).checked = true;
        }
        toControl() { return this; }
        build() {
            super.build();
            this.css.add("sol_multiple_choice");
            if (this.configuration && this.configuration.InlineItems)
                this.inlineItems = true;
            if (this.inlineItems)
                this.add(new Sol.LineBreak());
            if (this.defaultValue)
                this.selectedCode = this.defaultValue.Valor || this.defaultValue;
        }
        clear() { }
    }
    Sol.MultipleChoice = MultipleChoice;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Counter extends Sol.Control {
        constructor() {
            super("span");
            this._value = 0;
            this.animationEnabled = true;
            this.duration = 1500;
            this.maxValue = 0;
            this.speed = 100;
            this.text = "0";
        }
        get value() { return this._value; }
        set value(newValue) {
            var maxValueExceeded = false;
            if (this.maxValue > 0 && newValue > this.maxValue) {
                maxValueExceeded = true;
                newValue = this.maxValue;
            }
            this._value = newValue;
            if (!newValue) {
                this.text = "0";
                return;
            }
            if (!this.animationEnabled) {
                this.text = newValue.toString();
                if (maxValueExceeded)
                    this.text += '+';
                return;
            }
            var animationValue = 0;
            var myDuration = this.duration;
            var degree = newValue / (myDuration / this.speed);
            var interval = setInterval(() => {
                this.text = Math.floor(animationValue).toString();
                animationValue += degree;
                if (animationValue >= (newValue - degree)) {
                    clearInterval(interval);
                    this.text = newValue.toString();
                    if (maxValueExceeded)
                        this.text += '+';
                }
            }, this.speed);
        }
    }
    Sol.Counter = Counter;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class CheckList extends Sol.Control {
        constructor() {
            super();
            this.checksArea = new Sol.Control();
            this.searchArea = new Sol.Control();
            this.searchField = new Sol.Field();
            this.isComplex = false;
            this._readonly = false;
            this.css.addMany(["sol_campo", "sol_lista_checks"]);
            this.initializeSearchArea();
            this.checksArea.css.add("sol_lista_checks_options");
            this.add(this.checksArea);
        }
        get checks() { return this.checksArea.controls.where(ctr => ctr instanceof Sol.Check).cast(); }
        get groups() { return this.checksArea.controls.where(ctr => ctr.tagName == "h5"); }
        get readonly() { return this._readonly; }
        set readonly(value) {
            this._readonly = value;
            this.checks.forEach(chk => chk.readonly = value);
        }
        get options() { return this._options; }
        set options(value) {
            this._options = value;
            this.checksArea.controls.empty();
            if (!value)
                return;
            var newOptions = Sol.List.from(value);
            var isGrouped = newOptions.any(o => !!o.Group);
            this.searchArea.visible = newOptions.count >= 15;
            if (isGrouped)
                newOptions.groupBy("Group").forEach(g => {
                    const header = new Sol.Control("h5");
                    header.text = g.key;
                    this.checksArea.add(header);
                    g.items.forEach(i => this.checksArea.add(this.createCheck(i, g.key)));
                });
            else if (this._options)
                Sol.List.from(this._options).forEach(o => this.checksArea.add(this.createCheck(o, null)));
        }
        get selectedCodes() {
            return this.checks.where(ck => ck.checked).select(ck => ck.codigo);
        }
        set selectedCodes(value) {
            this.checks.forEach(ck => ck.checked = value.any(v => v == ck.codigo));
        }
        get value() {
            return this.checks
                .select(chk => ({
                Codigo: chk.codigo,
                Chequeado: chk.checked
            }))
                .toArray();
        }
        set value(v) {
            if (!v)
                return;
            var items = Sol.List.from(v);
            this.checks.forEach(ck => ck.checked = items.any(p => p.Chequeado &&
                (ck.codigo == p.Codigo || ck.codigo.endsWith('/' + p.Codigo))));
        }
        clear() {
            this.clearSearch();
            this.checks.forEachReverse(ck => ck.checked = false);
        }
        clearSearch() {
            this.searchField.clear();
            this.searchField.foco();
        }
        filterByGroup(groupLabel) {
            this.searchField.clear();
            this.groups.forEach(g => g.visible = !groupLabel || g.text == groupLabel);
            this.checks.forEach(ch => ch.visible = !groupLabel || ch.data == groupLabel);
        }
        foco() { }
        isCodeChecked(code) { return this.selectedCodes.contains(code); }
        isEmpty() {
            var items = Sol.List.from(this.value);
            return !items.any(i => i.Chequeado);
        }
        validate() { return null; }
        toControl() { return this; }
        createCheck(option, groupLabel) {
            const check = new Sol.Check();
            check.codigo = option.Code;
            check.caption = option.Description;
            check.checked = option.Checked;
            check.data = groupLabel;
            check.option = option;
            return check;
        }
        initializeSearchArea() {
            this.searchArea.css.add("sol_lista_checks_bar");
            let selectAllCheck = new Sol.Check();
            selectAllCheck.tip = Sol.Environment.resources.selectAllButton;
            selectAllCheck.onClick = () => selectAllCheck.value ? this.selectAll() : this.unselectAll();
            this.searchArea.add(selectAllCheck);
            this.searchField.placeHolder = Sol.Environment.resources.buscar + "...";
            this.searchField.estilos.agregar("font-size", "10px;");
            this.searchArea.add(this.searchField);
            const deleteButton = new Sol.Button();
            deleteButton.imageCode = '&#xf00d;';
            deleteButton.type = Sol.ButtonType.Custom;
            deleteButton.css.add("sol_checklist_delete_button");
            deleteButton.onClick = () => {
                this.searchField.clear();
                this.searchField.onKeyUp(null);
            };
            this.searchArea.add(deleteButton);
            this.searchField.onKeyUp = () => this.checksArea.controls.forEach(ctr => {
                var _a, _b;
                ctr.visible =
                    this.searchField.isEmpty() ||
                        (ctr.text || "").toLowerCase().indexOf(this.searchField.value.toLowerCase()) > -1 ||
                        (ctr instanceof Sol.Check && ctr.caption.toLowerCase().indexOf(this.searchField.value.toLowerCase()) > -1) ||
                        (ctr instanceof Sol.Check && ((_b = (_a = ctr.option) === null || _a === void 0 ? void 0 : _a.ExtendedDescription) === null || _b === void 0 ? void 0 : _b.toLowerCase().indexOf(this.searchField.value.toLowerCase())) > -1);
                let u = 0;
            });
            this.add(this.searchArea);
        }
        selectAll() {
            this.checks.forEach(i => i.checked = true);
        }
        unselectAll() {
            this.checks.forEach(i => i.checked = false);
        }
    }
    Sol.CheckList = CheckList;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ComboItem extends Sol.Control {
        constructor(code, text) {
            super("option");
            this.selected = false;
            if (code || code == "0")
                this.code = code;
            if (text)
                this.text = text;
        }
        build() {
            if (this.code || this.code == "0")
                this.atributos.agregar("value", this.code.toString());
            if (this.selected)
                this.atributos.agregar("selected");
            super.build();
        }
        toDatumModel() {
            return { Campo: this.text, Valor: this.code || null };
        }
    }
    Sol.ComboItem = ComboItem;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class CheckMenu extends Sol.Control {
        constructor(caption = null) {
            super("li");
            this.captionControl = new Sol.Control("span");
            this.checkControl = new Sol.Control("span");
            this.caption = caption;
            this.checkControl.css.add("sol_combo_periodo_check_area");
            this.captionControl.css.add("sol_combo_periodo_caption");
            this.add(this.checkControl);
            this.add(this.captionControl);
        }
        get caption() { return this.captionControl.text; }
        set caption(v) { this.captionControl.text = v; }
        get checked() { return this._checked; }
        set checked(v) {
            this._checked = v;
            this.checkControl.text = v ? "&#xf00c;" : "";
        }
    }
    Sol.CheckMenu = CheckMenu;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Combo extends Sol.Control {
        constructor() {
            super("select");
            this._valor = { Campo: null, Valor: null };
            this._errorState = Sol.EditorErrorState.Normal;
            this.displayMember = "Name";
            this.isComplex = false;
            this.required = false;
            this.useWrapper = true;
            this.valueMember = "ID";
            this.onFocus = new Sol.EventHandler();
            this.onLeave = new Sol.EventHandler();
            this.onValueModified = new Sol.EventHandler();
            this.onSet = new Sol.EventHandler();
            this.css.add("sol_campo");
        }
        get blocked() { return this._blocked; }
        set blocked(value) {
            this._blocked = value;
            if (value)
                this.estilos.agregar("pointer-events", "none");
            else
                this.estilos.remove("pointer-events");
        }
        get errorState() { return this._errorState; }
        set errorState(value) {
            this._errorState = value;
            value === Sol.EditorErrorState.Error ? this.css.add("sol_field_error") : this.css.remove("sol_field_error");
        }
        get selectedCode() { return this.getSelectedCode(); }
        set selectedCode(v) { this.setSelectedCode(v); }
        get selectedText() { return this.getSelectedText(); }
        get items() { return this.controls.cast(); }
        get selectedItem() {
            if (this.modoSol && this.html)
                this._valor.Valor = this.html.value;
            var vValor = this._valor.Valor;
            return this.items.that(ci => ci.code == vValor);
        }
        get readonly() {
            return this.atributos.toList().any(i => i.key == "disabled");
        }
        set readonly(valor) {
            if (valor)
                this.atributos.definir("disabled", "disabled");
            else
                this.atributos.remove("disabled");
        }
        validate() { return null; }
        get value() { return this.getValue(); }
        set value(v) { this.setValue(v); }
        get onChange() { return this._onChange; }
        set onChange(value) {
            this._onChange = value;
            this.html.addEventListener("change", () => this._onChange());
        }
        addBlankItem() {
            this.add(new Sol.ComboItem());
        }
        addItems(items) {
            var cl = Sol.List.from(items);
            this.controls.addMany(cl.select(i => {
                var comboItem = new Sol.ComboItem();
                comboItem.code = i.Valor;
                comboItem.text = i.Campo;
                return comboItem;
            }));
        }
        isEmpty() {
            return this.getValue() == null ||
                (!this.getValue().Valor && !this.getValue().Campo) ||
                (this.getValue().Valor == '0' && !this.getValue().Campo);
        }
        foco() { if (this.html)
            this.html.focus(); }
        getItemByCode(code) { return this.items.that(i => i.code == code); }
        getItemByText(text) { return this.items.that(i => i.text == text); }
        clear() {
            if (this.items.hasItems())
                this.selectedCode = this.items.first().code;
        }
        clearOptions() { this.controls.empty(); }
        loadOptions(options) {
            let optionList = Sol.List.from(options);
            if (this.autoSelectUniqueOption) {
                let validOptions = optionList.where(o => !!o.Code || o.Code != '0');
                if (validOptions.count == 1) {
                    validOptions.first().Checked = true;
                    this.onSet.invoke();
                }
            }
            this.controls.addMany(optionList.select(o => {
                var item = new Sol.ComboItem();
                item.code = o.Code;
                item.text = o.Description;
                item.selected = o.Checked;
                return item;
            }));
        }
        removeItemByCode(code) {
            var removedItem = this.items.that(i => i.code == code);
            this.controls.remove(removedItem);
        }
        setDataSource(data, defaultName) {
            this.controls.empty();
            if (!data)
                return;
            var dataCollection = Sol.List.from(data);
            dataCollection.forEach(item => {
                var comboItem = new Sol.ComboItem();
                comboItem.text = item[this.displayMember];
                comboItem.code = item[this.valueMember];
                comboItem.data = item;
                comboItem.selected = comboItem.text === defaultName;
                this.add(comboItem);
            });
        }
        setItemVisibility(code, visible) {
            const item = this.getItemByCode(code);
            if (!item)
                return;
            if (!visible && code == this.selectedCode)
                this.selectedCode = null;
            item.visible = visible;
        }
        toControl() { return this; }
        registerEvents() {
            super.registerEvents();
            this.onFocus.connect(this, "focus");
            this.onLeave.connect(this, "blur");
            this.onValueModified.connect(this, "change");
            if (!this.disableChangeEventOnSetValue)
                this.onSet.invoke();
        }
        addItem(code, text, selected = false) {
            if (this.items.any(i => i.code == code))
                return;
            let item = new Sol.ComboItem();
            item.code = code;
            item.text = text;
            item.selected = selected;
            this.add(item);
        }
        build() {
            super.build();
            if (typeof (this.defaultValue) != 'undefined' && this.defaultValue != null)
                this.value = this.defaultValue;
            if (this.required)
                this.atributos.agregar("required");
            if (this.readonly)
                this.atributos.agregar("disabled");
            if (this.customCssClass)
                this.css.add(this.customCssClass);
            if (this._valor && (this._valor.Valor || this._valor.Valor === 0))
                this.items.forEachReverse(ctr => ctr.selected = ctr.code == this._valor.Valor);
            if (this.onKeyDown)
                this.html.onkeydown = e => this.onKeyDown(e);
        }
        getSelectedCode() {
            if (this.modoSol && this.html)
                this._valor.Valor = this.html.value;
            return this._valor.Valor;
        }
        setSelectedCode(v) {
            this._valor.Valor = v;
            if (this.modoSol && this.html)
                this.html.value = this._valor.Valor;
        }
        getSelectedText() {
            if (this.modoSol && this.html) {
                let select = this.html;
                if (select.selectedIndex == -1)
                    return null;
                this._valor.Campo = select.options[select.selectedIndex].text;
                this._valor.Valor = select.value;
            }
            return this._valor.Campo;
        }
        getValue() {
            if (!this.modoSol && this.defaultValue)
                return this.defaultValue;
            var controlSeleccionado = this.selectedItem;
            var itemSelecionado = { Campo: null, Valor: null };
            if (controlSeleccionado)
                itemSelecionado = controlSeleccionado.toDatumModel();
            return itemSelecionado;
        }
        setValue(v) {
            if (v !== 0)
                v = v || "";
            if (v === true)
                this._valor.Valor = 1;
            else if (v === false)
                this._valor.Valor = 0;
            else if (typeof v === "string")
                this._valor.Valor = v;
            else if (typeof v === "number")
                this._valor.Valor = v;
            else {
                v.Valor = v.Valor || "";
                this._valor = v;
                if (!this.items.any(i => i.code == (v.Valor || 0)))
                    this.addItem(this._valor.Valor, this._valor.Campo, true);
            }
            if (this.html) {
                this.html.value = this._valor.Valor;
                if (this.html.value != this._valor.Valor) {
                    this.addItem(this._valor.Valor, this._valor.Campo);
                    this.html.value = this._valor.Valor;
                }
            }
            if (this.onChange && !this.disableChangeEventOnSetValue)
                this.onChange();
            this.onSet.invoke();
        }
    }
    Sol.Combo = Combo;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ComboFilter extends Sol.Combo {
        constructor() {
            super();
            this.css.add("sol_combo_filter");
        }
    }
    Sol.ComboFilter = ComboFilter;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let IntervalType;
    (function (IntervalType) {
        IntervalType[IntervalType["Anytime"] = 0] = "Anytime";
        IntervalType[IntervalType["CurrentMonth"] = 1] = "CurrentMonth";
        IntervalType[IntervalType["PreviousMonth"] = 2] = "PreviousMonth";
        IntervalType[IntervalType["DateRange"] = 3] = "DateRange";
        IntervalType[IntervalType["Today"] = 4] = "Today";
        IntervalType[IntervalType["Tomorrow"] = 5] = "Tomorrow";
        IntervalType[IntervalType["Yesterday"] = 6] = "Yesterday";
        IntervalType[IntervalType["LastWeek"] = 7] = "LastWeek";
        IntervalType[IntervalType["ThisWeek"] = 8] = "ThisWeek";
        IntervalType[IntervalType["ThisQuarter"] = 9] = "ThisQuarter";
        IntervalType[IntervalType["LastQuarter"] = 10] = "LastQuarter";
        IntervalType[IntervalType["ThisYear"] = 11] = "ThisYear";
        IntervalType[IntervalType["LastYear"] = 12] = "LastYear";
        IntervalType[IntervalType["Month"] = 13] = "Month";
        IntervalType[IntervalType["Quarter"] = 14] = "Quarter";
        IntervalType[IntervalType["Past"] = 15] = "Past";
        IntervalType[IntervalType["NextDays"] = 16] = "NextDays";
    })(IntervalType = Sol.IntervalType || (Sol.IntervalType = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class IntervalComboOption extends Sol.CheckMenu {
        constructor() {
            super(...arguments);
            this.quarter = 1;
            this.days = 0;
        }
        getValue() {
            return {
                Opcion: this.option,
                Inicio: this.startDate,
                Termino: this.endDate,
                Quarter: this.quarter,
                Days: this.days
            };
        }
    }
    Sol.IntervalComboOption = IntervalComboOption;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class MonthField extends Sol.Combo {
        constructor() {
            super();
            for (var number = 1; number <= 12; number++) {
                var date = new Date(2015, number - 1);
                var month = date.toLocaleString(Sol.Environment.language, { month: "long" }).capitalizeFirstLetter();
                this.addItems([{ Campo: month, Valor: number }]);
            }
        }
    }
    Sol.MonthField = MonthField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class MonthYearField extends Sol.Control {
        constructor() {
            super();
            this.monthField = new Sol.MonthField();
            this.yearField = new Sol.Combo();
            this.css.add("month_year_field");
            this.yearField.addItems(Sol.List.range(2000, new Date().getFullYear() + 5)
                .select(n => ({ Campo: n.toString(), Valor: n.toString() }))
                .toArray());
            this.yearField.selectedCode = new Date().getFullYear().toString();
            this.yearField.onChange = () => { if (this.onChange)
                this.onChange(this); };
            this.monthField.onChange = () => { if (this.onChange)
                this.onChange(this); };
            this.add(this.monthField);
            this.addCtr(Sol.Environment.resources.de, null, "span");
            this.add(this.yearField);
        }
        get endDate() { return this.startDate.getLastDayOfMonth(); }
        get selectedMonth() { return parseInt(this.monthField.selectedCode || "0"); }
        set selectedMonth(value) { this.monthField.selectedCode = value.toString(); }
        get selectedText() {
            if (!this.monthField.selectedItem || !this.yearField.selectedItem)
                return "";
            return this.monthField.selectedItem.text + ' ' + Sol.Environment.resources.de + ' ' + this.yearField.selectedItem.text;
        }
        get selectedYear() { return parseInt(this.yearField.selectedItem.text); }
        set selectedYear(value) { this.yearField.selectedCode = value.toString(); }
        get startDate() { return new Date(this.selectedYear, this.selectedMonth - 1, 1); }
        get value() {
            return {
                Month: this.selectedMonth,
                Year: this.selectedYear,
                Start: this.startDate,
                End: this.endDate
            };
        }
        set value(v) {
            this.selectedMonth = v.Month;
            this.selectedYear = v.Year;
        }
        foco() { this.monthField.foco(); }
        setByDate(date) {
            this.selectedMonth = date.getMonth() + 1;
            this.selectedYear = date.getFullYear();
        }
        setCurrentMonth() {
            const today = new Date();
            this.selectedMonth = today.getMonth() + 1;
            this.selectedYear = today.getFullYear();
        }
        setLastMonth() {
            const today = new Date();
            const isPreviousYear = today.getMonth() === 0;
            this.selectedMonth = isPreviousYear ? 11 : today.getMonth();
            this.selectedYear = today.getFullYear() - (isPreviousYear ? 1 : 0);
        }
        toControl() { return this; }
        clear() { }
        isEmpty() { return false; }
        validate() { return null; }
    }
    Sol.MonthYearField = MonthYearField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class IntervalCombo extends Sol.Control {
        constructor() {
            super();
            this.mainField = new Sol.Control("span");
            this.popup = new Sol.Popup();
            this.anytimeOption = new Sol.IntervalComboOption();
            this.daysField = new Sol.IntegerField();
            this.monthField = new Sol.MonthYearField();
            this.nextDaysOption = new Sol.IntervalComboOption();
            this.quarterField = new Sol.Combo();
            this.options = new Sol.List();
            this.tomorrowOption = new Sol.IntervalComboOption();
            this.isComplex = false;
            this.css.add("sol_combo_periodo");
            this.mainField.css.add("sol_campo");
            this.mainField.text = Sol.Environment.resources.cualquier;
            this.mainField.onClick = () => this.popup.visible = !this.popup.visible && !this.readonly;
            this.add(this.mainField);
            this.popup.visible = false;
            this.add(this.popup);
            this.createAnytimeOption();
            this.createCurrentMonthOption();
            this.createPreviousMonthOption();
            this.createDateRangeOption();
            this.createTodayOption();
            this.createTomorrowOption();
            this.createYesterdayOption();
            this.createLastWeekOption();
            this.createCurrentWeekOption();
            this.createCurrentQuarterOption();
            this.createLastQuarterOption();
            this.createCurrentYearOption();
            this.createLastYearOption();
            this.createMonthOption();
            this.createQuarterOption();
            this.createPastOption();
            this.createInNextDaysOption();
        }
        get description() {
            let result;
            if (!this.selectedOption)
                return;
            switch (this.selectedOption.option) {
                case Sol.IntervalType.Month:
                    let monthDate = Date.convert(this.selectedOption.startDate);
                    this.monthField.setByDate(monthDate);
                    result = this.monthField.selectedText;
                    break;
                case Sol.IntervalType.DateRange:
                    let startDate = Date.convert(this.selectedOption.startDate);
                    let endDate = Date.convert(this.selectedOption.endDate);
                    result = startDate.formatearLocal() + Sol.Environment.resources.periodo_a + endDate.formatearLocal();
                    break;
                case Sol.IntervalType.Quarter:
                    result = this.quarterField.selectedItem ?
                        this.quarterField.selectedItem.text :
                        this.quarterField.items.item(this.selectedOption.quarter - 1).text;
                    break;
                case Sol.IntervalType.NextDays:
                    result = this.selectedOption.days == 1 ? Sol.Environment.resources.manana :
                        `Nos próximos ${this.selectedOption.days} dias`;
                    break;
                default:
                    result = this.selectedOption.caption;
            }
            return result;
        }
        get showAnyOption() { return this.anytimeOption.visible; }
        set showAnyOption(value) { this.anytimeOption.visible = value; }
        get showTomorrow() { return this.tomorrowOption.visible; }
        set showTomorrow(value) {
            this.tomorrowOption.visible = value;
            this.nextDaysOption.visible = value;
        }
        isEmpty() {
            if (!this.selectedOption)
                return true;
            return this.selectedOption.option == Sol.IntervalType.Anytime;
        }
        clear() {
            this.selectedOption = this.anytimeOption;
            this.mainField.text = this.selectedOption.caption;
        }
        validate() { return null; }
        get value() {
            return this.selectedOption.getValue();
        }
        set value(v) {
            v = v || { Opcion: Sol.IntervalType.Anytime };
            this.selectedOption = this.options.item(v.Opcion);
            if (v.Inicio)
                this.selectedOption.startDate = v.Inicio;
            if (v.Termino)
                this.selectedOption.endDate = v.Termino;
            if (v.Quarter)
                this.selectedOption.quarter = v.Quarter;
            this.selectedOption.days = v.Days || 0;
            this.updateText();
        }
        toControl() { return this; }
        build() {
            super.build();
            if (this.defaultValue)
                this.value = this.defaultValue;
        }
        createAnytimeOption() {
            this.anytimeOption.caption = Sol.Environment.resources.cualquier;
            this.anytimeOption.onClick = () => this.itemClick(this.anytimeOption);
            this.anytimeOption.option = Sol.IntervalType.Anytime;
            this.anytimeOption.checked = true;
            this.popup.add(this.anytimeOption);
            this.selectedOption = this.anytimeOption;
            this.options.add(this.anytimeOption);
        }
        createCurrentMonthOption() {
            let currentMonthOption = new Sol.IntervalComboOption();
            currentMonthOption.caption = Sol.Environment.resources.mes_actual;
            currentMonthOption.onClick = () => this.itemClick(currentMonthOption);
            currentMonthOption.option = Sol.IntervalType.CurrentMonth;
            this.popup.add(currentMonthOption);
            this.options.add(currentMonthOption);
        }
        createPreviousMonthOption() {
            let previosMonthOption = new Sol.IntervalComboOption();
            previosMonthOption.caption = Sol.Environment.resources.mes_anterior;
            previosMonthOption.onClick = () => this.itemClick(previosMonthOption);
            previosMonthOption.option = Sol.IntervalType.PreviousMonth;
            this.popup.add(previosMonthOption);
            this.options.add(previosMonthOption);
        }
        createDateRangeOption() {
            let today = new Date();
            let formattedToday = today.formatear();
            let dateClick = false;
            var dateRangeOption = new Sol.IntervalComboOption();
            dateRangeOption.css.add("sol_combo_periodo_date_range");
            dateRangeOption.caption = Sol.Environment.resources.periodo_de;
            dateRangeOption.onClick = () => {
                if (!dateClick)
                    this.itemClick(dateRangeOption);
                else
                    dateRangeOption.clickResult = true;
                dateClick = false;
            };
            dateRangeOption.option = Sol.IntervalType.DateRange;
            dateRangeOption.startDate = formattedToday;
            dateRangeOption.endDate = formattedToday;
            if (Sol.Environment.isMobile)
                dateRangeOption.add(new Sol.LineBreak());
            var startDateField = new Sol.DateField();
            startDateField.onClick = () => {
                dateClick = true;
                startDateField.clickResult = true;
            };
            var startEventManager = setTimeout(() => {
                if (!startDateField.html)
                    return;
                startDateField.html.onchange = () => {
                    dateRangeOption.startDate = startDateField.value;
                    this.updateText();
                };
                clearTimeout(startEventManager);
            }, 100);
            startDateField.value = formattedToday;
            dateRangeOption.add(startDateField);
            var preposition = new Sol.Control("span");
            preposition.text = Sol.Environment.resources.periodo_a;
            dateRangeOption.add(preposition);
            var endDateField = new Sol.DateField();
            endDateField.onClick = () => {
                dateClick = true;
                endDateField.clickResult = true;
            };
            var endEventManager = setTimeout(() => {
                if (!endDateField.html)
                    return;
                endDateField.html.onchange = e => {
                    dateRangeOption.endDate = endDateField.value;
                    this.updateText();
                };
                clearTimeout(endEventManager);
            }, 100);
            endDateField.value = formattedToday;
            dateRangeOption.add(endDateField);
            this.popup.add(dateRangeOption);
            this.options.add(dateRangeOption);
        }
        createPastOption() {
            let pastOption = new Sol.IntervalComboOption();
            pastOption.caption = Sol.Environment.resources.past_option;
            pastOption.onClick = () => this.itemClick(pastOption);
            pastOption.option = Sol.IntervalType.Past;
            this.popup.add(pastOption);
            this.options.add(pastOption);
        }
        createTodayOption() {
            let todayOption = new Sol.IntervalComboOption();
            todayOption.caption = Sol.Environment.resources.hoy;
            todayOption.onClick = () => this.itemClick(todayOption);
            todayOption.option = Sol.IntervalType.Today;
            this.popup.add(todayOption);
            this.options.add(todayOption);
        }
        createTomorrowOption() {
            this.tomorrowOption.caption = Sol.Environment.resources.manana;
            this.tomorrowOption.onClick = () => this.itemClick(this.tomorrowOption);
            this.tomorrowOption.option = Sol.IntervalType.Tomorrow;
            this.popup.add(this.tomorrowOption);
            this.options.add(this.tomorrowOption);
        }
        createYesterdayOption() {
            let yesterdayOption = new Sol.IntervalComboOption();
            yesterdayOption.caption = Sol.Environment.resources.yesterday;
            yesterdayOption.onClick = () => this.itemClick(yesterdayOption);
            yesterdayOption.option = Sol.IntervalType.Yesterday;
            this.popup.add(yesterdayOption);
            this.options.add(yesterdayOption);
        }
        createLastWeekOption() {
            let lastWeekOption = new Sol.IntervalComboOption();
            lastWeekOption.caption = Sol.Environment.resources.lastWeek;
            lastWeekOption.onClick = () => this.itemClick(lastWeekOption);
            lastWeekOption.option = Sol.IntervalType.LastWeek;
            this.popup.add(lastWeekOption);
            this.options.add(lastWeekOption);
        }
        createCurrentWeekOption() {
            let currentWeekOption = new Sol.IntervalComboOption();
            currentWeekOption.caption = Sol.Environment.resources.currentWeek;
            currentWeekOption.onClick = () => this.itemClick(currentWeekOption);
            currentWeekOption.option = Sol.IntervalType.ThisWeek;
            this.popup.add(currentWeekOption);
            this.options.add(currentWeekOption);
        }
        createCurrentQuarterOption() {
            let currentQuarterOption = new Sol.IntervalComboOption();
            currentQuarterOption.caption = Sol.Environment.resources.thisQuarter;
            currentQuarterOption.onClick = () => this.itemClick(currentQuarterOption);
            currentQuarterOption.option = Sol.IntervalType.ThisQuarter;
            this.popup.add(currentQuarterOption);
            this.options.add(currentQuarterOption);
        }
        createLastQuarterOption() {
            let lastQuarterOption = new Sol.IntervalComboOption();
            lastQuarterOption.caption = Sol.Environment.resources.lastQuarter;
            lastQuarterOption.onClick = () => this.itemClick(lastQuarterOption);
            lastQuarterOption.option = Sol.IntervalType.LastQuarter;
            this.popup.add(lastQuarterOption);
            this.options.add(lastQuarterOption);
        }
        createCurrentYearOption() {
            let currentYearOption = new Sol.IntervalComboOption();
            currentYearOption.caption = Sol.Environment.resources.this_year;
            currentYearOption.onClick = () => this.itemClick(currentYearOption);
            currentYearOption.option = Sol.IntervalType.ThisYear;
            this.popup.add(currentYearOption);
            this.options.add(currentYearOption);
        }
        createLastYearOption() {
            let lastYearOption = new Sol.IntervalComboOption();
            lastYearOption.caption = Sol.Environment.resources.previous_year;
            lastYearOption.onClick = () => this.itemClick(lastYearOption);
            lastYearOption.option = Sol.IntervalType.LastYear;
            this.popup.add(lastYearOption);
            this.options.add(lastYearOption);
        }
        createMonthOption() {
            let monthOption = new Sol.IntervalComboOption();
            monthOption.caption = Sol.Environment.resources.mes + ':';
            monthOption.checkControl.onClick = () => this.itemClick(monthOption);
            monthOption.option = Sol.IntervalType.Month;
            this.popup.add(monthOption);
            this.options.add(monthOption);
            this.monthField.onChange = () => {
                monthOption.startDate = this.monthField.startDate.formatear();
                monthOption.endDate = this.monthField.endDate.formatear();
                this.updateText();
            };
            monthOption.startDate = this.monthField.startDate.formatear();
            monthOption.endDate = this.monthField.endDate.formatear();
            monthOption.add(this.monthField);
        }
        createQuarterOption() {
            let quarterOption = new Sol.IntervalComboOption();
            quarterOption.caption = Sol.Environment.resources.quarter + ':';
            quarterOption.onClick = () => this.itemClick(quarterOption);
            quarterOption.option = Sol.IntervalType.Quarter;
            this.popup.add(quarterOption);
            this.options.add(quarterOption);
            this.quarterField.onChange = () => {
                this.updateText();
                quarterOption.quarter = parseInt(this.quarterField.selectedCode);
            };
            this.quarterField.loadOptions([
                { Code: "1", Description: '1º ' + Sol.Environment.resources.quarter },
                { Code: "2", Description: '2º ' + Sol.Environment.resources.quarter },
                { Code: "3", Description: '3º ' + Sol.Environment.resources.quarter },
                { Code: "4", Description: '4º ' + Sol.Environment.resources.quarter }
            ]);
            this.quarterField.onClick = () => this.quarterField.clickEvent.stopPropagation();
            quarterOption.add(this.quarterField);
        }
        createInNextDaysOption() {
            this.nextDaysOption.caption = "Nos próximos ";
            this.nextDaysOption.onClick = () => this.itemClick(this.nextDaysOption);
            this.nextDaysOption.option = Sol.IntervalType.NextDays;
            this.daysField.onChange = () => {
                this.updateText();
                this.nextDaysOption.days = this.daysField.numericValue;
            };
            this.daysField.maxValue = 9999;
            this.daysField.onClick = () => this.daysField.clickEvent.stopPropagation();
            this.nextDaysOption.add(this.daysField);
            this.nextDaysOption.addCtr("dias", null, "span");
            this.popup.add(this.nextDaysOption);
            this.options.add(this.nextDaysOption);
        }
        itemClick(option) {
            this.selectedOption = option;
            this.options.forEach(opt => opt.checked = false);
            option.checked = true;
            this.updateText();
            this.popup.hide();
            if (this.onModified)
                this.onModified(this);
        }
        updateText() {
            this.mainField.text = this.description;
            this.options.forEach(opt => opt.checked = false);
            if (this.selectedOption)
                this.selectedOption.checked = true;
        }
        foco() { }
    }
    Sol.IntervalCombo = IntervalCombo;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class EditorContainer extends Sol.Control {
        constructor() {
            super(...arguments);
            this.editors = new Sol.List();
        }
        getEditor(propertyName) {
            if (this.editors)
                return this.editors.that(e => e.propertyName == propertyName);
        }
        clearControls() {
            this.controls.empty();
            if (this.editors)
                this.editors.empty();
        }
        setEditorValue(propertyName, value) {
            const field = this.getEditor(propertyName);
            if (field)
                field.value = value;
        }
        toControl() { return this; }
        validate() { return null; }
    }
    Sol.EditorContainer = EditorContainer;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class MultipleComboItem extends Sol.Control {
        constructor(model) {
            super("li");
            this.checkControl = new Sol.Check();
            this._model = model;
            if (model.Color) {
                this.checkControl.estilos.definir("border-left", "3px solid " + model.Color);
                this.checkControl.estilos.definir("margin-left", "4px");
            }
            this.add(this.checkControl);
            this.checkControl.caption = model.Description;
            this.checkControl.checked = model.Checked;
            this.checkControl.onChange = () => this.checkedChanged();
        }
        get model() { return this._model; }
        set model(model) { this._model = model; }
        check() {
            if (this._model.Checked)
                return;
            this.checkControl.checked = true;
            this.checkedChanged();
        }
        uncheck() {
            if (!this._model.Checked)
                return;
            this.checkControl.checked = false;
            this.checkedChanged();
        }
        checkedChanged() {
            this._model.Checked = this.checkControl.checked;
            if (this.onCheckedChanged)
                this.onCheckedChanged(this);
        }
    }
    Sol.MultipleComboItem = MultipleComboItem;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class MultipleCombo extends Sol.Control {
        constructor() {
            super();
            this.mainField = new Sol.Control("span");
            this.popup = new Sol.Popup();
            this.items = new Sol.List();
            this.isComplex = false;
            this.onValueModified = new Sol.EventHandler();
            this.onSet = new Sol.EventHandler();
            this.css.add("sol_combo_multiple");
            this.mainField.css.add("sol_campo");
            this.mainField.text = Sol.Environment.resources.cualquier;
            this.mainField.onClick = () => this.popup.visible = !this.popup.visible;
            this.add(this.mainField);
            this.popup.visible = false;
            this.add(this.popup);
        }
        get selectedItems() { return this.items.where(i => i.model.Checked); }
        get selectedCodes() { return this.selectedItems.select(i => i.model.Code).toArray(); }
        validate() { return null; }
        get value() { return this.getValue(); }
        set value(v) { this.setValue(v); }
        toControl() { return this; }
        isEmpty() { return !this.selectedItems.hasItems(); }
        foco() { }
        clear() { this.items.forEach(i => i.uncheck()); }
        setOptions(options) {
            this.createItems(this.popup, options);
        }
        createItems(target, options) {
            if (!options)
                return;
            target.css.add("sol_combo_multiple_options");
            const optionsCollection = Sol.List.from(options);
            optionsCollection.where(o => !!o.Description).forEach(o => {
                const item = new Sol.MultipleComboItem(o);
                item.onCheckedChanged = () => this.valueModified(item);
                target.add(item);
                this.items.add(item);
            });
        }
        getValue() { return this.selectedCodes; }
        setValue(v) {
            this.clear();
            if (!v)
                return;
            var selected = this.items.where(i => v.indexOf(i.model.Code) > -1);
            selected.forEach(i => i.check());
            this.onSet.invoke();
        }
        refreshDisplay() {
            var selected = this.selectedItems;
            this.mainField.text = selected.hasItems() ?
                selected.select(i => i.model.Description).join(", ") :
                Sol.Environment.resources.cualquier;
        }
        unselectItems() { this.items.forEach(i => i.uncheck()); }
        valueModified(sender) {
            this.refreshDisplay();
            this.onValueModified.invoke();
        }
    }
    Sol.MultipleCombo = MultipleCombo;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class PhoneField extends Sol.Control {
        constructor() {
            super();
            this.typeCombo = new Sol.Combo();
            this.numberField = new Sol.Field();
            this.code = 0;
            this.css.add("sol_campo_telefono");
            this.initializeCombo();
            this.numberField.ancho = 140;
            this.add(this.numberField);
        }
        get showType() { return this.typeCombo.visible; }
        set showType(value) { this.typeCombo.visible = value; }
        get value() {
            return {
                ID: this.code,
                Número: this.numberField.value,
                Tipo: parseInt(this.typeCombo.selectedCode) || 0
            };
        }
        set value(v) {
            this.code = v.ID;
            this.numberField.value = v.Número;
            this.typeCombo.selectedCode = v.Tipo.toString();
        }
        clear() {
            this.code = 0;
            this.numberField.clear();
            this.numberField.foco();
        }
        foco() { this.numberField.foco(); }
        isEmpty() { return !this.numberField.value || this.numberField.value.trim() == ""; }
        toControl() { return this; }
        validate() { return null; }
        build() {
            super.build();
            this.typeCombo.readonly = this.readonly;
            this.numberField.readonly = this.readonly;
        }
        initializeCombo() {
            this.typeCombo.add(new Sol.ComboItem(4, "&#xf232;"));
            this.typeCombo.add(new Sol.ComboItem(0, "&#xf095;"));
            this.typeCombo.add(new Sol.ComboItem(1, "&#xf098;"));
            this.typeCombo.add(new Sol.ComboItem(2, "&#xf10b;"));
            this.typeCombo.add(new Sol.ComboItem(3, "&#xf015;"));
            this.typeCombo.add(new Sol.ComboItem(5, "&#xf1d8;"));
            this.typeCombo.controls.item(0).tip = Sol.Environment.resources.whatsapp;
            this.typeCombo.controls.item(1).tip = Sol.Environment.resources.telefono;
            this.typeCombo.controls.item(2).tip = Sol.Environment.resources.comercial;
            this.typeCombo.controls.item(3).tip = Sol.Environment.resources.movil;
            this.typeCombo.controls.item(4).tip = Sol.Environment.resources.casa;
            this.typeCombo.controls.item(5).tip = Sol.Environment.resources.telegram;
            this.typeCombo.onChange = () => this.typeComboChanged();
            this.add(this.typeCombo);
        }
        typeComboChanged() {
            this.numberField.foco();
            if (this.onTypeChanged)
                this.onTypeChanged(this);
        }
    }
    Sol.PhoneField = PhoneField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class MultipleFieldItem extends Sol.Control {
        constructor(field) {
            super();
            this.deleteButton = new Sol.Button();
            this.code = 0;
            this.field = field;
            this.css.add("sol_extensible_field");
            this.add(field.toControl());
        }
        clear() { this.field.clear(); }
        focus() { this.field.foco(); }
        isEmpty() { return this.field.isEmpty(); }
        get readonly() { return this.field.readonly; }
        set readonly(value) {
            this.field.readonly = value;
            this.deleteButton.visible = !value;
        }
        get value() { return this.field.value; }
        set value(v) { this.field.value = v; }
        build() {
            super.build();
            this.deleteButton.text = "x";
            this.deleteButton.onClick = () => this.onDelete(this);
            this.add(this.deleteButton);
        }
    }
    Sol.MultipleFieldItem = MultipleFieldItem;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class MultipleField extends Sol.Control {
        constructor() {
            super();
            this.addButton = new Sol.Button();
            this.buttonCount = 1;
            this.isComplex = false;
            this.onDeleted = new Sol.EventHandler();
            this.onSet = new Sol.EventHandler();
            this.onValueModified = new Sol.EventHandler();
            this.css.add("sol_campo");
            this.css.add("sol_campo_multiple");
        }
        get items() { return this.controls.where(ct => ct instanceof Sol.MultipleFieldItem).cast(); }
        get readonly() { return this._readonly; }
        set readonly(value) {
            this._readonly = value;
            this.addButton.estilos.definir("opacity", value ? "0" : "100");
            this.addButton.enabled = !value;
            this.items.forEach(i => i.readonly = value);
        }
        get value() { return this.getValue(); }
        set value(value) { this.setValue(value); }
        get valueList() { return this.items.where(i => !i.isEmpty()).select(i => i.value).toArray(); }
        clear() {
            for (var indice = this.controls.count - (this.buttonCount + 1); indice > 0; indice--) {
                let ctr = this.controls.item(indice);
                if (!(ctr instanceof Sol.Button))
                    this.controls.remove(ctr);
            }
            if (this.items.hasItems())
                this.items.first().clear();
        }
        foco() { }
        isEmpty() {
            return this.controls.count - (this.readonly ? 0 : this.buttonCount) <= 1 &&
                this.controls.item(0).isEmpty();
        }
        toControl() { return this; }
        validate() { return null; }
        addField() { this.placeItem(this.instantiateItem()); }
        build() {
            super.build();
            this.addButton.text = "+";
            this.addButton.tip = Sol.Environment.resources.anadir_item;
            this.addButton.css.add("sol_campo_multiple_boton");
            this.addButton.onClick = () => this.addField();
            this.add(this.addButton);
        }
        deleteField(item) {
            if (this.controls.count > this.buttonCount + 1)
                this.controls.remove(item);
            else
                item.clear();
        }
        placeItem(item) {
            if (this.modoSol)
                this.controls.insert(this.controls.count - this.buttonCount, item);
            else
                this.add(item);
            item.focus();
        }
        getValue() {
            return this.items
                .where(i => !i.isEmpty())
                .select(i => [{ Campo: "ID", Valor: i.code }, { Campo: this.editorProperty, Valor: i.value }])
                .toArray();
        }
        setValue(value) {
            this.clear();
            for (var i = 0; i < value.length; i++) {
                let fields = Sol.List.from(value[i]);
                let getFieldValue = (fieldName) => { var _a; return (_a = fields.that(cp => cp.Campo == fieldName)) === null || _a === void 0 ? void 0 : _a.Valor; };
                let item = this.instantiateItem();
                item.code = getFieldValue("ID");
                item.value = getFieldValue(this.editorProperty);
                this.placeItem(item);
            }
            this.onSet.invoke();
        }
        instantiateItem() {
            var _a;
            let item = new Sol.MultipleFieldItem(this.onAddNew(this));
            item.readonly = this.readonly;
            (_a = item.field.onValueModified) === null || _a === void 0 ? void 0 : _a.subscribe(() => this.onValueModified.invoke());
            item.onDelete = e => {
                this.deleteField(e);
                this.onDeleted.invoke(this);
            };
            return item;
        }
    }
    Sol.MultipleField = MultipleField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ImageBox extends Sol.Control {
        constructor(source = null) {
            super();
            this.imageBox = new Sol.Control("img");
            this.deleteButton = new Sol.Button();
            this.source = source;
            this.deleteButton.visible = false;
            this.deleteButton.type = Sol.ButtonType.Custom;
            this.deleteButton.imageCode = '&#xf014;';
            this.deleteButton.onClick = () => {
                if (this.onDelete)
                    this.onDelete(this);
            };
            this.css.add("sol_images");
            this.add(this.deleteButton);
            this.add(this.imageBox);
        }
        get source() { return this.imageBox.atributos.item("src"); }
        set source(v) { this.imageBox.atributos.definir("src", v); }
        get imagenWidth() { return this.imageBox.ancho; }
        set imagenWidth(v) { this.imageBox.ancho = v; }
        get imagenHeight() { return this.imageBox.alto; }
        set imagenHeight(v) { this.imageBox.alto = v; }
        get showDeleteButton() { return this.deleteButton.visible; }
        set showDeleteButton(v) { this.deleteButton.visible = v; }
        build() {
            this.deleteButton.estilos.agregar("margin-top", (this.imagenHeight - 30) + "px");
            super.build();
        }
    }
    Sol.ImageBox = ImageBox;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class PhonesEditor extends Sol.MultipleField {
        constructor() {
            super();
            this.whatsAppButton = new Sol.Button();
            this.showPhoneType = true;
            this.useWrapper = true;
            this.buttonCount = 2;
            this.css.add("sol_campo_telefono_container");
            this.onAddNew = () => this.createField();
        }
        build() {
            this.addField();
            if (!this.disableWhatsAppButton)
                this.createWhatsAppButton();
            super.build();
        }
        getValue() {
            return this.controls
                .where(ct => ct instanceof Sol.MultipleFieldItem)
                .cast()
                .where(ct => !ct.isEmpty())
                .select(ct => ct.value)
                .toArray();
        }
        setValue(value) {
            this.clear();
            var totalItems = value.length;
            for (var i = 0; i < totalItems; i++) {
                if (i > 0)
                    this.addField();
                let fields = Sol.List.from(value[i]);
                let getFieldValue = (fieldName) => {
                    const fieldData = fields.that(cp => cp.Campo == fieldName);
                    if (!fieldData)
                        return null;
                    return fieldData.Valor;
                };
                let phoneModel = {
                    ID: parseInt(getFieldValue("ID")),
                    Número: getFieldValue("Número"),
                    Tipo: fields.that(cp => cp.Campo == "Tipo").Valor.Valor
                };
                this.controls.item(i).value = phoneModel;
            }
            this.checkWhatsAppNumber();
        }
        checkWhatsAppNumber() {
            this.whatsAppButton.enabled = !!this.getWhatsAppField();
        }
        createField() {
            var phoneField = new Sol.PhoneField();
            phoneField.parent = this;
            phoneField.showType = this.showPhoneType;
            if (!this.disableWhatsAppButton)
                phoneField.onTypeChanged = () => this.checkWhatsAppNumber();
            phoneField.readonly = this.readonly;
            return phoneField;
        }
        createWhatsAppButton() {
            this.whatsAppButton.css.addMany(["sol_campo_multiple_boton", "sol_campo_multiple_boton_whats"]);
            this.whatsAppButton.imageCode = "&#xf232;";
            this.whatsAppButton.onClick = () => this.openWhatsApp();
            this.whatsAppButton.tip = Sol.Environment.resources.sendWhats;
            this.add(this.whatsAppButton);
        }
        deleteField(item) {
            super.deleteField(item);
            this.checkWhatsAppNumber();
        }
        getWhatsAppField() {
            return this.items
                .select(ctr => ctr.field)
                .cast()
                .that(phone => phone.value.Tipo == 4);
        }
        openWhatsApp() {
            var whats = this.getWhatsAppField();
            if (!whats)
                return;
            var whatsNumber = whats.value.Número;
            if (!whatsNumber)
                return;
            var whatsLink = "https://wa.me/" + (whatsNumber.soloDigitos().length == 11 ? "55" + whatsNumber.soloDigitos() : whatsNumber.soloDigitos());
            window.open(whatsLink, "_blank");
        }
    }
    Sol.PhonesEditor = PhonesEditor;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class RatingField extends Sol.Control {
        constructor() {
            super(...arguments);
            this.UNSELECTED_CLASS = "sol_rating_field_unselected";
            this.SELECTED_CLASS = "sol_rating_field_selected";
            this.stars = new Sol.List();
            this.isComplex = false;
            this.maxValue = 5;
            this.useWrapper = true;
            this._valor = 0;
        }
        validate() { return null; }
        get value() { return this._valor; }
        set value(v) {
            this._valor = v;
            var counter = 1;
            this.stars.forEach(s => {
                s.css.empty();
                s.css.add(v >= counter++ ? this.SELECTED_CLASS : this.UNSELECTED_CLASS);
            });
        }
        foco() { }
        toControl() { return this; }
        clear() { }
        isEmpty() { return this.value == 0; }
        build() {
            super.build();
            this.css.add("sol_rating_field");
            for (var i = 1; i <= this.maxValue; i++) {
                var star = new Sol.Control("i");
                star.css.add(this._valor >= i ? this.SELECTED_CLASS : this.UNSELECTED_CLASS);
                star.text = '&#xf005;';
                star.onClick = e => {
                    if (!this.readonly)
                        this.value = this.stars.indice(e) + 1;
                };
                this.add(star);
                this.stars.add(star);
            }
        }
    }
    Sol.RatingField = RatingField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ListField extends Sol.Combo {
        constructor() {
            super();
            this.atributos.agregar("size", "2");
            this.css.add("sol_list");
        }
        get selectedItems() {
            var codes = Sol.List.from(this.html.selectedOptions).select(i => i.value);
            return codes.select(c => this.getItemByCode(c));
        }
        build() {
            if (this.multiple)
                this.atributos.agregar("multiple");
            if (this.enableDeleteKey)
                this.onKeyDown = e => this.keydown(e);
            super.build();
        }
        containsCode(code) {
            return this.items.any(i => i.code == code);
        }
        removeSelected() {
            if (this.multiple)
                this.selectedItems.forEach(i => this.controls.remove(i));
            else if (this.selectedItem)
                this.controls.remove(this.selectedItem);
        }
        keydown(e) {
            if (e.key === "Delete")
                this.removeSelected();
        }
    }
    Sol.ListField = ListField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Tab extends Sol.Control {
        constructor() {
            super("span");
            this._selected = false;
        }
        get selected() { return this._selected; }
        set selected(value) {
            this._selected = value;
            if (value)
                this.css.add("sol_tab_selected");
            else
                this.css.remove("sol_tab_selected");
        }
    }
    Sol.Tab = Tab;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class TabControl extends Sol.Control {
        constructor() {
            super();
            this.space = new Sol.Control();
            this.tabs = new Sol.List();
            this.css.add("sol_tab_control");
        }
        addTab(alias, title, content) {
            const tab = new Sol.Tab();
            tab.alias = alias;
            tab.text = title;
            tab.content = content;
            this.tabs.add(tab);
        }
        select(alias) {
            this.selectTab(this.tabs.that(t => t.alias == alias));
        }
        build() {
            super.build();
            const tabBar = new Sol.Control();
            tabBar.css.add("sol_tab_bar");
            tabBar.controls.addMany(this.tabs.select(t => t));
            this.tabs.forEach(t => t.onClick = () => this.selectTab(t));
            this.add(tabBar);
            this.space.controls.addMany(this.tabs.select(t => t.content));
            this.space.controls.forEach(ctr => ctr.visible = false);
            this.add(this.space);
            if (this.tabs.hasItems())
                this.selectTab(this.tabs.first());
        }
        selectTab(tab) {
            this.tabs.forEach(t => t.selected = false);
            this.space.controls.forEach(ctr => ctr.visible = false);
            tab.selected = true;
            tab.content.visible = true;
            if (this.onTabClick)
                this.onTabClick(tab);
        }
    }
    Sol.TabControl = TabControl;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class DialogBox extends Sol.Control {
        constructor() {
            super("dialog");
            this.dialogHeader = new Sol.Control("header");
            this.dialogTitle = new Sol.Control("span");
            this.showBlocker = true;
            this.contentArea = new Sol.Control();
            this.dialogTitle.css.add("titulo");
            this.dialogHeader.add(this.dialogTitle);
            let closeButton = new Sol.Button();
            closeButton.imageCode = '&#xf00d;';
            closeButton.css.add("cerrar");
            closeButton.onClick = () => this.onClosing();
            this.dialogHeader.add(closeButton);
            this.add(this.dialogHeader);
            this.add(this.contentArea);
        }
        get title() { return this.dialogTitle.text; }
        set title(texto) { this.dialogTitle.text = texto; }
        get visible() {
            if (this.modoSol && this.html)
                this._visible = this.html.offsetWidth > 0 && this.html.offsetHeight > 0;
            return this._visible;
        }
        set visible(valor) {
            var oldValue = this._visible;
            this._visible = valor;
            if (!this.modoSol || !this.html)
                return;
            this.html.setAttribute("open", valor ? "" : null);
            if (valor) {
                this.createBlocker();
                this.html.style.display = 'block';
            }
            else {
                this.html.style.display = 'none';
                this.removeBlocker();
            }
            if (!oldValue && valor && this.onExhibido)
                this.onExhibido(this);
        }
        close() {
            this.removeBlocker();
            this.parent.controls.remove(this);
        }
        build() {
            super.build();
            if (this.visible)
                this.atributos.agregar("open");
            setTimeout(() => this.configureDragging(), 300);
        }
        createBlocker() {
            if (!this.showBlocker)
                return;
            var blocker = document.createElement("div");
            var body = document.getElementsByTagName("body")[0];
            blocker.className = "sol_blocker";
            body.insertBefore(blocker, body.childNodes[0]);
        }
        onClosing() {
            this.visible = false;
            if (this.onClose)
                this.onClose(this);
        }
        configureDragging() {
            this.dialogHeader.html.onmousedown = e => this.headerMouseDown(e);
        }
        removeBlocker() {
            var blockers = document.getElementsByClassName("sol_blocker");
            for (var i = blockers.length - 1; i >= 0; i--)
                blockers.item(i).remove();
        }
        headerMouseDown(e) {
            e = e || window.event;
            e.preventDefault();
            this.startX = e.clientX;
            this.startY = e.clientY;
            document.onmousemove = ev => this.dialogDrag(ev);
            document.onmouseup = () => this.dialogEndDrag();
        }
        dialogDrag(e) {
            e = e || window.event;
            e.preventDefault();
            var x = this.startX - e.clientX;
            var y = this.startY - e.clientY;
            this.startX = e.clientX;
            this.startY = e.clientY;
            var element = this.html;
            element.style.top = (element.offsetTop - y) + "px";
            element.style.left = (element.offsetLeft - x) + "px";
        }
        dialogEndDrag() {
            document.onmouseup = null;
            document.onmousemove = null;
        }
    }
    Sol.DialogBox = DialogBox;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ExpandoLabel extends Sol.Control {
        constructor() {
            super();
            this.MINUS = '&#xf146;';
            this.PLUS = '&#xf0fe;';
            this.expandoButton = new Sol.Button();
            this.label = new Sol.Label();
            this.onExpanded = new Sol.EventHandler();
            this.css.add("sol_expando_label");
            this.expandoButton.type = Sol.ButtonType.Custom;
            this.expandoButton.onClick = () => this.expanded = !this.expanded;
            this.add(this.expandoButton);
            this.label.onClick = () => this.expanded = !this.expanded;
            this.add(this.label);
        }
        get caption() { return this.label.text; }
        set caption(v) { this.label.text = v; }
        get expanded() { return this.associatedControl && this.associatedControl.visible; }
        set expanded(value) {
            if (!this.associatedControl)
                return;
            this.associatedControl.visible = value;
            this.expandoButton.imageCode = this.associatedControl.visible ? this.MINUS : this.PLUS;
            if (value)
                this.onExpanded.invoke(this);
        }
        build() {
            this.expandoButton.imageCode = this.expanded ? this.MINUS : this.PLUS;
            this.label.editor = this.associatedControl;
        }
    }
    Sol.ExpandoLabel = ExpandoLabel;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ExpandoButton extends Sol.Control {
        constructor() {
            super("button");
            this.sign = new Sol.Control("span");
            this._isExpanded = false;
            this.atributos.agregar("type", "button");
            this.estilos.agregar("border", "0px");
            this.estilos.agregar("background", "none");
            this.estilos.agregar("padding", "0px");
            this.estilos.agregar("cursor", "pointer");
            this.sign.estilos.agregar("border", "1px solid #000");
            this.sign.estilos.agregar("border-radius", "3px");
            this.sign.estilos.agregar("font-family", "Courier");
            this.sign.estilos.agregar("margin-left", "4px");
            this.sign.estilos.agregar("padding", "0px 3px");
            this.add(this.sign);
            this.onClick = () => this.isExpanded = !this.isExpanded;
            this.isExpanded = false;
        }
        get isExpanded() { return this._isExpanded; }
        set isExpanded(value) {
            this._isExpanded = value;
            this.sign.text = this._isExpanded ? '-' : '+';
            if (this.associatedControl)
                this.associatedControl.visible = this._isExpanded;
            if (this.isExpanded && this.onShow)
                this.onShow(this);
        }
    }
    Sol.ExpandoButton = ExpandoButton;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class TextDisplay extends Sol.Control {
        get value() { return this.text; }
        set value(v) { this.text = v; }
        foco() { }
        toControl() { return this; }
        validate() { return null; }
        isEmpty() { return false; }
        clear() { }
    }
    Sol.TextDisplay = TextDisplay;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ObjectDisplay extends Sol.Control {
        constructor() {
            super("span");
            this.alignment = Sol.Alignment.Left;
            this.useWrapper = true;
            this.onValueModified = new Sol.EventHandler();
            this.onSet = new Sol.EventHandler();
            this.css.add("sol_display");
        }
        get value() {
            return {
                Campo: this.text,
                Valor: this.code,
                Color: this.color
            };
        }
        set value(v) {
            this.setValue(v);
        }
        build() {
            if (this.customClass)
                this.css.add(this.customClass);
            if (this.width)
                this.ancho = this.width;
            if (this.defaultValue)
                this.value = this.defaultValue;
            if (this.alignment == Sol.Alignment.Right)
                this.estilos.definir("text-align", "right");
            if (this.alignment == Sol.Alignment.Center)
                this.estilos.definir("text-align", "center");
            if (this.showAsField) {
                this.css.add("sol_campo");
                this.estilos.definir("display", "block");
            }
        }
        setValue(v) {
            if (!v && !this.defaultValue) {
                this.text = "";
                this.code = 0;
                this.css.remove("sol_object_display_color");
                if (this.hideWhenEmpty) {
                    this.visible = false;
                    if (this.myLabel)
                        this.myLabel.visible = false;
                }
                return;
            }
            if (!v && this.defaultValue)
                v = this.defaultValue;
            if (this.htmlMode) {
                this.htmlContent = v;
                return;
            }
            if (typeof v === "string" || typeof v === "number")
                this.text = v.toString();
            else {
                this.text = v.Campo;
                this.code = v.Valor;
            }
            if (v.Color) {
                this.css.add("sol_campo");
                this.css.add("sol_object_display_color");
                this.color = v.Color;
                this.estilos.definir("border-left-color", v.Color);
            }
            this.onSet.invoke();
        }
        clear() { this.value = null; }
        foco() { }
        toControl() { return this; }
        validate() { return null; }
        isEmpty() { return false; }
    }
    Sol.ObjectDisplay = ObjectDisplay;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    let SelectorSourceMode;
    (function (SelectorSourceMode) {
        SelectorSourceMode[SelectorSourceMode["Normal"] = 0] = "Normal";
        SelectorSourceMode[SelectorSourceMode["Custom"] = 1] = "Custom";
    })(SelectorSourceMode = Sol.SelectorSourceMode || (Sol.SelectorSourceMode = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class SelectorItem extends Sol.Control {
        constructor() { super("li"); }
        get focused() { return this._focused; }
        set focused(value) {
            this._focused = value;
            if (this._focused)
                this.css.add("focused");
            else
                this.css.remove("focused");
        }
    }
    Sol.SelectorItem = SelectorItem;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ClearIcon extends Sol.Control {
        constructor() {
            super("i");
            this.text = 'x';
            this.css.add("sol_clear");
        }
    }
    Sol.ClearIcon = ClearIcon;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class SelectorIcon extends Sol.Control {
        constructor() {
            super("i");
            this.css.add("sol_lens");
        }
    }
    Sol.SelectorIcon = SelectorIcon;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class LensIcon extends Sol.SelectorIcon {
        constructor() {
            super();
            this.text = "&#xf002;";
        }
    }
    Sol.LensIcon = LensIcon;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class SelectorField extends Sol.Control {
        constructor(tagName) {
            super(tagName);
            this._value = null;
            this.clearIcon = new Sol.ClearIcon();
            this.itemLoad = new Sol.Control("li");
            this.filterByText = true;
            this.mainField = new Sol.Field();
            this.popup = new Sol.Popup();
            this.searchButton = new Sol.LensIcon();
            this.textoItemSeleccionado = null;
            this.codeProperty = "ID";
            this.displayProperty = "Nombre";
            this.sourceMode = Sol.SelectorSourceMode.Normal;
            this.onValueModified = new Sol.EventHandler();
            this.css.add("sol_selector");
            this.mainField.placeHolder = Sol.Environment.resources.typeToSearch;
            this.mainField.maxLength = 85;
            this.mainField.disableEnter = true;
            this.add(this.mainField);
            this.clearIcon.onClick = () => {
                this.clear();
                this.foco();
            };
            this.add(this.clearIcon);
            this.addExtraIcons();
            this.searchButton.onClick = () => this.searchAll();
            this.add(this.searchButton);
            this.popup.visible = false;
            this.itemLoad.text = Sol.Environment.resources.cargando;
            this.popup.add(this.itemLoad);
        }
        get focusedItem() { return this.items.that(i => i.focused); }
        ;
        get items() { return this.popup.controls.where(ctr => ctr instanceof Sol.SelectorItem).cast(); }
        get readonly() { return this.mainField.readonly; }
        set readonly(value) { this.setReadonly(value); }
        get errorState() { return this.mainField.errorState; }
        set errorState(value) { this.mainField.errorState = value; }
        get selectedCode() { return this._value; }
        get selectedText() { return this.mainField.value; }
        set selectedText(value) { this.mainField.value = value; }
        get value() { return this._value; }
        set value(value) {
            if (!value)
                return;
            if (value > 0) {
                this._value = value;
                this.search(value, true);
                return;
            }
            const datum = value;
            this._value = datum.Valor;
            this.mainField.value = datum.Campo;
            this.textoItemSeleccionado = datum.Campo;
            this.enableButtons(true);
            if (this.onValueSet)
                this.onValueSet(value);
            this.internalValueSet(value);
        }
        clear() {
            this.mainField.clear();
            this.textoItemSeleccionado = null;
            this._value = null;
            this.enableButtons(false);
            this.onValueModified.invoke();
        }
        foco() { this.mainField.foco(); }
        isEmpty() { return !this._value; }
        toControl() { return this; }
        validate() { return null; }
        addExtraIcons() { }
        build() {
            super.build();
            this.mainField.readonly = this.readonly;
            if (!this.readonly) {
                this.mainField.onChange = () => this.checkSelectedItem();
                this.mainField.onKeyDown = e => this.fieldKeyDown(e);
                this.mainField.onKeyUp = e => this.fieldKeyUp(e);
                this.add(this.popup);
            }
            if (this.defaultValue)
                this.value = this.defaultValue;
        }
        clearPopup() {
            for (var i = this.popup.controls.count - 1; i > 0; i--)
                this.popup.controls.remove(this.popup.controls.item(i));
        }
        enableButtons(value) { }
        fieldKeyDown(e) {
            var handled;
            if (e.key == "ArrowDown") {
                if (this.popup.visible) {
                    var currentIndex = this.items.indice(this.focusedItem);
                    var itemCount = this.items.count;
                    this.items.item(currentIndex).focused = false;
                    currentIndex = currentIndex < itemCount - 1 ? currentIndex + 1 : 0;
                    this.items.item(currentIndex).focused = true;
                }
                else
                    this.search();
                handled = true;
            }
            if (e.key == "ArrowUp" && this.popup.visible) {
                var currentIndex = this.items.indice(this.focusedItem);
                var itemCount = this.items.count;
                this.items.item(currentIndex).focused = false;
                currentIndex = currentIndex > 0 ? currentIndex - 1 : itemCount - 1;
                this.items.item(currentIndex).focused = true;
                handled = true;
            }
            if (e.key == "Enter" && this.popup.visible) {
                this.itemClick(this.focusedItem);
                handled = true;
            }
            if (e.key == "Escape" && this.popup.visible) {
                this.popup.hide();
                handled = true;
            }
            if (handled) {
                e.cancelBubble = true;
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
            return true;
        }
        fieldKeyUp(e) {
            this.checkSelectedItem();
            const isBackspace = e.key == "Backspace";
            const isDelete = e.key == "Delete";
            const isLetterOrNumber = /^[a-zA-Z0-9]$/.test(e.key);
            if (isBackspace || isDelete || isLetterOrNumber)
                this.search();
            return false;
        }
        fillCustomPopup(data) {
            this.itemLoad.visible = false;
            if (!data)
                return;
            Sol.List.from(data).forEach(d => {
                const item = new Sol.SelectorItem();
                item.code = d[this.codeProperty];
                item.text = d[this.displayProperty];
                item.onClick = e => this.itemClick(e);
                item.extraData = d;
                if (this.onInstantiateCustomItem)
                    this.onInstantiateCustomItem(item, d);
                this.popup.add(item);
            });
            if (this.popup.controls.count > 1)
                this.popup.controls.item(1).focused = true;
        }
        internalItemSelected(item) { }
        internalValueSet(value) { }
        itemClick(item, cancelItemSected) {
            if (!item)
                return;
            if (item.blocked) {
                alert(Sol.Environment.resources.blocked);
                return;
            }
            this.mainField.textValue = item.text || item.displayText;
            this.textoItemSeleccionado = this.mainField.textValue;
            this._value = item.code;
            this.enableButtons(true);
            this.popup.hide();
            this.internalItemSelected(item);
            if (this.onItemSelected && !cancelItemSected)
                this.onItemSelected(item);
            this.onValueModified.invoke();
        }
        search(code, cancelClickEvent) {
            return __awaiter(this, void 0, void 0, function* () {
                this.popup.show();
                this.popup.ancho = this.mainField.ancho;
                this.clearPopup();
                this.itemLoad.visible = true;
                if (this.sourceMode == Sol.SelectorSourceMode.Custom) {
                    this.fillCustomPopup(yield this.onCustomSource(code));
                    if (code)
                        this.itemClick(this.items.first(), cancelClickEvent);
                    return;
                }
            });
        }
        setReadonly(value) {
            this.mainField.readonly = value;
            this.searchButton.visible = !value;
            this.clearIcon.visible = !value;
            this.mainField.placeHolder = value ? "" : Sol.Environment.resources.typeToSearch;
        }
        checkSelectedItem() {
            if (this.value > 0 && this.textoItemSeleccionado && this.textoItemSeleccionado != this.mainField.textValue) {
                this._value = null;
                if (this.onValueSet)
                    this.onValueSet({ Valor: 0 });
                if (this.onClearExtraData)
                    this.onClearExtraData(this);
            }
        }
        searchAll() {
            if (this.popup.visible) {
                this.popup.hide();
                return;
            }
            this.mainField.foco();
            this.filterByText = false;
            this.search();
        }
    }
    Sol.SelectorField = SelectorField;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class Gauge extends Sol.Control {
        constructor() {
            super(...arguments);
            this.canvas = new Sol.Control("canvas");
            this.isComplex = false;
            this.size = 50;
            this.textSize = 16;
            this._valor = 0;
            this.valueOffSet = 6;
        }
        get gaugeCaption() { return this.value.toString() + (this.showPercent ? "%" : ""); }
        get value() { return this._valor; }
        set value(v) {
            this._valor = v;
            if (this.modoSol)
                this.draw();
        }
        build() {
            super.build();
            this.css.add("sol_gauge");
            this.canvas.atributos.agregar("width", this.size + "px");
            this.canvas.atributos.agregar("height", this.size + "px");
            this.add(this.canvas);
            setTimeout(() => {
                this.draw();
                if (!this.readonly)
                    this.canvas.html.addEventListener('click', e => this.canvasClick(e));
            }, 300);
        }
        toControl() { return this; }
        isEmpty() { return false; }
        foco() { }
        clear() { this.value = 0; }
        validate() { return null; }
        canvasClick(e) {
            var x = e.pageX - this.canvas.html.offsetLeft;
            var y = e.pageY - this.canvas.html.offsetTop;
            var angle = Math.atan2(y - (this.size / 2), x - (this.size / 2)) * 180 / Math.PI;
            this.degreesToValue(angle);
        }
        draw() {
            if (!this.canvas.html || !(this.canvas.html.getContext))
                return;
            var ctx = this.canvas.html.getContext("2d");
            ctx.clearRect(0, 0, this.canvas.html.width, this.canvas.html.height);
            ctx.beginPath();
            ctx.lineWidth = 10;
            ctx.strokeStyle = "lightgray";
            ctx.arc(this.size / 2, this.size / 2, (this.size / 2) - 5, 0, 2 * Math.PI);
            ctx.stroke();
            if (this.value > 0) {
                ctx.beginPath();
                ctx.strokeStyle = this.valueToColor();
                if (this.value >= 100)
                    ctx.arc(this.size / 2, this.size / 2, (this.size / 2) - 5, 0, 2 * Math.PI);
                else
                    ctx.arc(this.size / 2, this.size / 2, (this.size / 2) - 5, (Math.PI / 180) * 180, this.valueToDegrees());
                ctx.stroke();
            }
            ctx.font = this.textSize + "px Segoe UI";
            ctx.textAlign = "center";
            ctx.fillText(this.gaugeCaption, (this.size / 2) - 1, (this.size / 2) + this.valueOffSet);
        }
        degreesToValue(degrees) {
            var value = 50 + (degrees / 3.6);
            value = Math.round(value / 10) * 10;
            this.value = value;
        }
        valueToColor() {
            var _a;
            if (this.gaugeColor)
                return this.gaugeColor;
            ;
            var colorSet = Sol.List.from([
                { condition: () => this.value < 50, color: "#cc3300" },
                { condition: () => this.value < 80, color: "#e68a00" },
                { condition: () => this.value < 100, color: "#004d99" },
                { condition: () => this.value === 100, color: "#53c68c" }
            ]);
            return (_a = colorSet.that(c => c.condition())) === null || _a === void 0 ? void 0 : _a.color;
        }
        valueToDegrees() {
            return (Math.PI / 180) * ((this.value - 50) * 3.6);
        }
    }
    Sol.Gauge = Gauge;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class FormDialog extends Sol.DialogBox {
        constructor() {
            super();
            this.form = new Sol.Form();
            this.contentArea.add(this.form);
            this.form.onCancel = () => this.visible = false;
        }
        get onSave() { return this.form.onSave; }
        set onSave(value) { this.form.onSave = value; }
        addToForm(ctr) { this.form.add(ctr); }
        workComplete() { this.form.workComplete(); }
    }
    Sol.FormDialog = FormDialog;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var WebComponents;
    (function (WebComponents) {
        class VerticalTimeline extends Sol.Control {
            constructor() {
                super("ol");
                this.currentItem = 1;
                this.maxValue = 1;
                this.itemCount = 3;
                this.css.add("sol_timeline");
            }
            build() {
                super.build();
                this.controls.addMany(Sol.List.range(1, this.itemCount - 1)
                    .select(i => {
                    var item = new Sol.Control("li");
                    item.text = i.toString();
                    item.css.add(i == this.currentItem ? "current" : i <= this.maxValue ? "completed" : "blocked");
                    if (i != this.currentItem && i <= this.maxValue && this.itemClick)
                        item.onClick = () => this.itemClick(i);
                    return item;
                }));
            }
        }
        WebComponents.VerticalTimeline = VerticalTimeline;
    })(WebComponents = Sol.WebComponents || (Sol.WebComponents = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        let ChartType;
        (function (ChartType) {
            ChartType[ChartType["None"] = 0] = "None";
            ChartType[ChartType["Pie"] = 1] = "Pie";
            ChartType[ChartType["Line"] = 2] = "Line";
            ChartType[ChartType["Flow"] = 3] = "Flow";
            ChartType[ChartType["Map"] = 4] = "Map";
        })(ChartType = Charts.ChartType || (Charts.ChartType = {}));
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        let LegendPosition;
        (function (LegendPosition) {
            LegendPosition[LegendPosition["Top"] = 0] = "Top";
            LegendPosition[LegendPosition["Right"] = 1] = "Right";
            LegendPosition[LegendPosition["Bottom"] = 2] = "Bottom";
            LegendPosition[LegendPosition["Left"] = 3] = "Left";
        })(LegendPosition = Charts.LegendPosition || (Charts.LegendPosition = {}));
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        class BaseChart extends Sol.Control {
            constructor() {
                super();
                this.canvas = new Sol.Control("canvas");
                this.chartWidth = 300;
                this.chartHeight = 300;
                this.enableLegend = true;
                this.responsive = true;
                this.add(this.canvas);
            }
            showChart() {
                if (this.canvas.html)
                    setTimeout(() => {
                        if (!(this.canvas.html.getContext))
                            return;
                        var graphics = this.canvas.html.getContext("2d");
                        if (this.chartWidth)
                            this.canvas.html.setAttribute("width", this.chartWidth + "px");
                        if (this.chartHeight)
                            this.canvas.html.setAttribute("height", this.chartHeight + "px");
                        this.chartObject = new Chart(graphics, this.getConfig());
                    }, 300);
            }
        }
        Charts.BaseChart = BaseChart;
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        class PieChart extends Charts.BaseChart {
            constructor() {
                super(...arguments);
                this.legendPosition = Charts.LegendPosition.Bottom;
            }
            get defaultColors() {
                return ["#1aa9bc", "#dd6464", "#fe9f97", "#f67019", "#f53794",
                    "#537bc4", "#acc236", "#166a8f", "#00a950", "#58595b", "#457c39",
                    "#8549ba", "#e4bd0b", "#de3d83", "#f7772c", "#333333",
                    "#558a86", "#a63e14", "#4dc9f6", "#a5a6a9"];
            }
            ;
            getConfig() {
                return {
                    type: "pie",
                    data: {
                        datasets: [
                            {
                                data: this.values,
                                backgroundColor: this.colors,
                                label: ""
                            }
                        ],
                        labels: this.labels
                    },
                    options: {
                        responsive: this.responsive,
                        legend: {
                            display: this.enableLegend
                        }
                    },
                };
            }
        }
        Charts.PieChart = PieChart;
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        class LineChart extends Charts.BaseChart {
            getConfig() {
                return {
                    type: "line",
                    data: {
                        datasets: [
                            {
                                data: this.values,
                                borderColor: "#34244f",
                            }
                        ],
                        labels: this.labels
                    },
                    options: {
                        responsive: this.responsive,
                        maintainAspectRatio: false,
                        legend: {
                            display: this.enableLegend
                        }
                    }
                };
            }
        }
        Charts.LineChart = LineChart;
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        class FlowChartBalloon extends Sol.Control {
            constructor() {
                super();
                this.css.add("sol_flow_chart_balloon");
            }
            build() {
                super.build();
                const nameWrapper = new Sol.Control();
                nameWrapper.css.add("sol_flow_chart_balloon_wrap");
                if (this.statusColor) {
                    const colorLegend = new Sol.Control("span");
                    colorLegend.css.add("sol_flow_chart_balloon_legend");
                    colorLegend.estilos.agregar("background-color", this.statusColor);
                    nameWrapper.add(colorLegend);
                }
                const nameControl = new Sol.Control("span");
                nameControl.text = this.statusName;
                nameWrapper.add(nameControl);
                this.add(nameWrapper);
                if (this.timeText) {
                    const timeControl = new Sol.Control();
                    timeControl.text = this.timeText + " em média";
                    timeControl.css.add("sol_flow_chart_balloon_time");
                    this.add(timeControl);
                }
                if (this.statsText) {
                    const statsControl = new Sol.Control();
                    statsControl.text = this.statsText;
                    statsControl.css.add("sol_flow_chart_balloon_stats");
                    this.add(statsControl);
                }
            }
        }
        Charts.FlowChartBalloon = FlowChartBalloon;
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        class FlowChart extends Sol.Control {
            constructor(records) {
                super();
                this.history = new Sol.List();
                this.records = Sol.List.from(records);
                this.css.add("sol_flow_chart");
            }
            build() {
                super.build();
                this.drawChart(this.records.that(r => r.IsInitial).StatusID);
            }
            drawChart(statusID) {
                const WIDTH_OFFSET = 0.2;
                if (statusID == this.history.last())
                    this.history.removeLast();
                else if (this.currentStatus)
                    this.history.add(this.currentStatus);
                this.currentStatus = statusID;
                const currentRecords = this.records.where(r => r.StatusID == statusID && r.NextStatusID > 0);
                const recordCount = currentRecords.count;
                var maxRows = Math.max(currentRecords.count, 1);
                if (recordCount > 0 && recordCount % 2 === 0)
                    maxRows++;
                this.controls.empty();
                const table = new Sol.Control("table");
                const mainRow = this.addRow(table);
                const previousStatusCell = this.addCell(mainRow, maxRows);
                previousStatusCell.css.add("sol_flow_chart_balloon_col");
                if (this.history.hasItems()) {
                    const previousStatusBalloon = new Charts.FlowChartBalloon();
                    previousStatusBalloon.code = this.history.last();
                    previousStatusBalloon.text = this.getStatusName(previousStatusBalloon.code);
                    previousStatusBalloon.onClick = () => this.drawChart(previousStatusBalloon.code);
                    previousStatusCell.add(previousStatusBalloon);
                    const previousFlowCell = this.addCell(mainRow, maxRows);
                    const previousFlow = new Sol.Control();
                    previousFlow.css.add("sol_flow_chart_root");
                    previousFlowCell.add(previousFlow);
                }
                const currentStatusCell = this.addCell(mainRow, maxRows);
                currentStatusCell.css.add("sol_flow_chart_balloon_col");
                const currentStatusBalloon = new Charts.FlowChartBalloon();
                currentStatusBalloon.code = statusID;
                currentStatusBalloon.statusName = this.getStatusName(statusID);
                currentStatusBalloon.statusColor = this.getStatuColor(statusID);
                const currentRecord = this.records.that(r => r.StatusID == statusID && !r.NextStatusID);
                if (currentRecord)
                    currentStatusBalloon.statsText = currentRecord.Quantity + " (" + currentRecord.QuantityPercentText + ")";
                currentStatusCell.add(currentStatusBalloon);
                const rootFlowCell = this.addCell(mainRow, maxRows);
                var rootHeight = 20;
                if (currentRecord)
                    rootHeight = Math.max(Math.ceil(WIDTH_OFFSET * (100 - currentRecord.QuantityPercent)), 1);
                if (currentRecords.hasItems()) {
                    const rootFlow = new Sol.Control();
                    rootFlow.css.add("sol_flow_chart_root");
                    rootFlow.estilos.agregar("height", rootHeight + "px");
                    rootFlowCell.add(rootFlow);
                }
                if (!currentRecords.hasItems())
                    this.addCell(mainRow, maxRows);
                else {
                    var currentRow = mainRow;
                    var isEmptyCenter = false;
                    for (var targetIndex = 1; targetIndex <= recordCount; targetIndex++) {
                        var r = currentRecords.item(targetIndex - 1);
                        currentRow = currentRow || this.addRow(table);
                        const curveCell = this.addCell(currentRow, 1);
                        curveCell.css.add("sol_flow_chart_curve_col");
                        var isCenter = recordCount % 2 === 1 && targetIndex === Math.floor(recordCount / 2) + 1;
                        isEmptyCenter = !isEmptyCenter && recordCount > 0 && targetIndex === (recordCount / 2) + 1;
                        isCenter = isCenter || isEmptyCenter;
                        if (isCenter) {
                            if (recordCount > 1) {
                                const upCurve = new Sol.Control();
                                const upPercent = currentRecords.take(targetIndex - 1).sum(r => r.QuantityPercent);
                                const upCurveWidth = Math.ceil(Math.max(1, WIDTH_OFFSET * upPercent));
                                const downCurve = new Sol.Control();
                                const downPercent = currentRecords.skip(targetIndex - (isEmptyCenter ? 1 : 0)).sum(r => r.QuantityPercent);
                                const downCurveWidth = Math.ceil(Math.max(1, WIDTH_OFFSET * downPercent));
                                upCurve.estilos.agregar("border-right-width", upCurveWidth + "px");
                                upCurve.estilos.agregar("border-bottom-width", upCurveWidth + "px");
                                upCurve.estilos.agregar("border-bottom-right-radius", upCurveWidth + "px");
                                upCurve.estilos.agregar("height", isEmptyCenter ? "1px" : "28px");
                                upCurve.estilos.agregar("width", "0px");
                                upCurve.css.add("sol_flow_chart_curve");
                                curveCell.add(upCurve);
                                if (!isEmptyCenter) {
                                    const centerFlow = new Sol.Control();
                                    centerFlow.css.add("sol_flow_chart_center");
                                    centerFlow.estilos.agregar("height", Math.max(1, WIDTH_OFFSET * r.QuantityPercent) + "px");
                                    curveCell.add(centerFlow);
                                }
                                downCurve.estilos.agregar("border-right-width", downCurveWidth + "px");
                                downCurve.estilos.agregar("border-top-width", downCurveWidth + "px");
                                downCurve.estilos.agregar("border-top-right-radius", downCurveWidth + "px");
                                downCurve.estilos.agregar("height", isEmptyCenter ? "1px" : "30px");
                                downCurve.estilos.agregar("width", "0px");
                                downCurve.css.add("sol_flow_chart_curve");
                                curveCell.add(downCurve);
                            }
                            else {
                                const uniqueFlow = new Sol.Control();
                                uniqueFlow.css.add("sol_flow_chart_center");
                                uniqueFlow.estilos.agregar("height", rootHeight + "px");
                                curveCell.add(uniqueFlow);
                            }
                        }
                        else {
                            const isUpCurve = targetIndex <= recordCount / 2;
                            const curveWidth = Math.ceil(Math.max(1, WIDTH_OFFSET * r.QuantityPercent));
                            var barWidth = 0;
                            if (isUpCurve && targetIndex > 1)
                                barWidth = Math.max(1, WIDTH_OFFSET * currentRecords.take(targetIndex - 1).sum(r => r.QuantityPercent));
                            if (!isUpCurve && targetIndex < recordCount)
                                barWidth = Math.max(1, WIDTH_OFFSET * currentRecords.skip(targetIndex - (isEmptyCenter ? 1 : 0)).sum(r => r.QuantityPercent));
                            if (barWidth) {
                                const verticalBar = new Sol.Control();
                                verticalBar.css.add("sol_flow_chart_bar");
                                verticalBar.estilos.agregar("width", barWidth + "px");
                                if (isUpCurve)
                                    verticalBar.estilos.agregar("margin-top", (-75 + curveWidth + 24) + "px");
                                curveCell.add(verticalBar);
                            }
                            const curve = new Sol.Control();
                            curveCell.estilos.agregar("vertical-align", isUpCurve ? "bottom" : "top");
                            curve.css.add("sol_flow_chart_curve");
                            curve.estilos.agregar("border-left-width", curveWidth + "px");
                            curve.estilos.agregar("margin-left", Math.max(barWidth - 1, 0) + "px");
                            curve.estilos.agregar("border-" + (isUpCurve ? "top" : "bottom") + "-width", curveWidth + "px");
                            curve.estilos.agregar("border-" + (isUpCurve ? "top" : "bottom") + "-left-radius", "20px");
                            curveCell.add(curve);
                        }
                        const targetStatusCell = this.addCell(currentRow, 1);
                        targetStatusCell.css.add("sol_flow_chart_balloon_col");
                        currentRow = null;
                        if (isEmptyCenter) {
                            targetIndex--;
                            continue;
                        }
                        const targetBalloon = new Charts.FlowChartBalloon();
                        targetBalloon.code = r.NextStatusID;
                        targetBalloon.statusName = r.NextStatusName;
                        targetBalloon.statusColor = r.NextStatusColor;
                        targetBalloon.statsText = r.Quantity + " (" + r.QuantityPercentText + ")";
                        targetBalloon.timeText = r.AverageTimeText;
                        targetBalloon.onClick = () => this.drawChart(targetBalloon.code);
                        targetStatusCell.add(targetBalloon);
                    }
                }
                this.add(table);
                this.onItemShown(this);
            }
            addRow(table) {
                const row = new Sol.Control("tr");
                table.add(row);
                return row;
            }
            addCell(tableRow, rowSpan) {
                const cell = new Sol.Control("td");
                if (rowSpan > 1)
                    cell.atributos.agregar("rowspan", rowSpan.toString());
                tableRow.add(cell);
                return cell;
            }
            getStatusName(code) {
                return this.records.that(r => r.StatusID == code).StatusName;
            }
            getStatuColor(code) {
                return this.records.that(r => r.StatusID == code).StatusColor;
            }
        }
        Charts.FlowChart = FlowChart;
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        let ActionSelectionMode;
        (function (ActionSelectionMode) {
            ActionSelectionMode[ActionSelectionMode["None"] = 0] = "None";
            ActionSelectionMode[ActionSelectionMode["All"] = 1] = "All";
        })(ActionSelectionMode = Web.ActionSelectionMode || (Web.ActionSelectionMode = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        class FieldGroupEditor extends Sol.EditorContainer {
        }
        Web.FieldGroupEditor = FieldGroupEditor;
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        let Ordering;
        (function (Ordering) {
            Ordering[Ordering["ascending"] = 1] = "ascending";
            Ordering[Ordering["descending"] = 2] = "descending";
        })(Ordering = Web.Ordering || (Web.Ordering = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class LoaderControl extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.loader = new Sol.Loader();
                    this.timeout = 500;
                }
                hide() {
                    if (!this.isHidden) {
                        var parent = this.baseControl.parent;
                        parent.controls.remove(this);
                        this.baseControl.visible = true;
                    }
                    this.isHidden = true;
                }
                show() {
                    this.isHidden = false;
                    setTimeout(() => {
                        if (this.isHidden)
                            return;
                        this.baseControl.visible = false;
                        var parent = this.baseControl.parent;
                        var position = parent.controls.indice(this.baseControl);
                        parent.controls.insert(position, this);
                        this.loader.visible = true;
                    }, this.timeout);
                }
                build() {
                    super.build();
                    this.css.add("sol_loader_control");
                    var captionControl = new Sol.Control();
                    captionControl.css.add("sol_loader_control_caption");
                    captionControl.text = this.caption;
                    this.add(captionControl);
                    this.add(this.loader);
                }
            }
            Components.LoaderControl = LoaderControl;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var WebComponents;
    (function (WebComponents) {
        class PdfViewer extends Sol.Control {
            constructor() {
                super("object");
                this.hideToolbar = false;
                this.atributos.agregar("type", "application/pdf");
            }
            build() {
                super.build();
                if (this.hideToolbar)
                    this.source += "#toolbar=0";
                this.atributos.agregar("data", this.source);
            }
        }
        WebComponents.PdfViewer = PdfViewer;
    })(WebComponents = Sol.WebComponents || (Sol.WebComponents = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Geo;
    (function (Geo) {
        class MapDialog extends Sol.DialogBox {
            constructor() {
                super();
                this.editButton = new Sol.Button();
                this.nameField = new Sol.Control();
                this.picture = new Sol.ImageBox();
                this.picture.imagenWidth = 120;
                this.picture.imagenHeight = 150;
                this.picture.estilos.agregar("float", "left");
                this.picture.estilos.agregar("margin-right", "10px");
                this.contentArea.add(this.picture);
                this.nameField.estilos.agregar("font-weight", "bold");
                this.contentArea.add(this.nameField);
                this.editButton.text = Sol.Environment.resources.editar;
                this.contentArea.add(this.editButton);
            }
            build() {
                super.build();
                if (!this.picture.source)
                    this.picture.visible = false;
            }
        }
        Geo.MapDialog = MapDialog;
    })(Geo = Sol.Geo || (Sol.Geo = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Geo;
    (function (Geo) {
        class Map extends Sol.Control {
            constructor() {
                super();
                this.css.add("sol_map");
                this.registerLibrary();
            }
            initializeMap(callback) {
                if (this.map) {
                    callback();
                    return;
                }
                var intervalTest = setInterval(() => {
                    if (typeof L == 'undefined' || !this.html || this.isLoaded)
                        return;
                    clearInterval(intervalTest);
                    this.isLoaded = true;
                    this.map = L.map(this.id).setView([-30.1087957, -51.3172297], 11);
                    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
                        maxZoom: 19,
                        attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
                    }).addTo(this.map);
                    callback();
                }, 100);
            }
            search(text, withMarker) {
            }
            showEntities(entities) {
                this.initializeMap(() => Sol.List.from(entities).forEach(entity => {
                    L.marker([entity.Latitude, entity.Longitude]).addTo(this.map)
                        .bindPopup(entity.Name)
                        .openPopup();
                }));
            }
            showDialog() {
                var dialog = new Geo.MapDialog();
                var me = this["me"];
                var entity = this["myEntitiy"];
                dialog.code = entity.ID;
                dialog.ancho = 320;
                dialog.alto = 195;
                dialog.title = me.entityName;
                dialog.nameField.text = entity.Name;
                dialog.editButton.onClick = () => me.onEdit(entity.ID, null);
                if (entity.Picture)
                    dialog.picture.source = Sol.Environment.filePath + entity.Picture;
                me.add(dialog);
            }
            clearMarkers() {
            }
            registerLibrary() {
            }
        }
        Geo.Map = Map;
    })(Geo = Sol.Geo || (Sol.Geo = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ScreenTitle extends Sol.Control {
                constructor() { super("h3"); }
            }
            Screens.ScreenTitle = ScreenTitle;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class RecoverPasswordScreen extends Sol.Form {
                constructor() {
                    super();
                    this.divEmail = new Sol.Control();
                    this.iconEmail = new Sol.Control("i");
                    this.email = new Sol.EmailField();
                    this.iconEmail.text = '&#xf0e0;';
                    this.email.placeHolder = Sol.Environment.resources.sistema_email;
                    this.email.required = true;
                    this.email.anchoAutomatico = false;
                    this.css.add("sol_recordatorio_clave");
                    this.divEmail.css.add("sol_login_campo");
                    this.divEmail.add(this.iconEmail);
                    this.divEmail.add(this.email);
                    this.add(this.divEmail);
                    this.okButton.text = Sol.Environment.resources.enviar;
                }
                focus() { this.email.foco(); }
            }
            Screens.RecoverPasswordScreen = RecoverPasswordScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        let SettingsCategory;
        (function (SettingsCategory) {
            SettingsCategory[SettingsCategory["General"] = 0] = "General";
            SettingsCategory[SettingsCategory["Parameters"] = 1] = "Parameters";
            SettingsCategory[SettingsCategory["AvailableFields"] = 2] = "AvailableFields";
            SettingsCategory[SettingsCategory["Modules"] = 3] = "Modules";
            SettingsCategory[SettingsCategory["Support"] = 4] = "Support";
        })(SettingsCategory = Web.SettingsCategory || (Web.SettingsCategory = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        class ProgressDialog extends Sol.DialogBox {
            constructor() {
                super();
                this.descriptionDisplay = new Sol.Control();
                this.bar = new Sol.ProgressBar();
                this.timeLeftDisplay = new Sol.Control();
                this.css.add("sol_progress_dialog");
                this.title = "Processando";
                const label = new Sol.Control();
                label.text = "Aguarde enquanto estamos processando sua solicitação...";
                this.contentArea.add(label);
                this.contentArea.add(this.descriptionDisplay);
                this.contentArea.add(this.bar);
                this.timeLeftDisplay.css.add("sol_progress_dialog_time_left");
                this.contentArea.add(this.timeLeftDisplay);
                const cancelButton = new Sol.Button();
                cancelButton.text = Sol.Environment.resources.cancelar;
                cancelButton.onClick = () => this.cancel();
                this.contentArea.add(cancelButton);
            }
            cancel() {
                this.onClosing();
                Web.System.exec("hhao4398s", "Cancel", { processId: this.processID });
            }
            follow(processID) {
                this.processID = processID;
                var interval = setInterval(() => {
                    Web.System.exec("hhao4398s", "GetStatus", { processId: processID }, e => {
                        if (e.Percentage == null) {
                            clearInterval(interval);
                            this.onClosing();
                        }
                        else if (e.Percentage == 100) {
                            this.bar.valor = 100;
                            if (e.Response) {
                                this.response = e.Response;
                                clearInterval(interval);
                                this.onClosing();
                                this.onCompleted();
                            }
                        }
                        else {
                            this.descriptionDisplay.text = e.Description;
                            this.timeLeftDisplay.text = e.TimeLeft;
                            this.bar.valor = e.Percentage;
                        }
                    });
                }, 1300);
            }
        }
        Web.ProgressDialog = ProgressDialog;
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class BaseScreen extends Sol.Control {
                get model() { return this.__model; }
                set model(v) {
                    this.__model = v;
                    this.onSetModel();
                }
                get screenCaption() { return this._screenCaption; }
                set screenCaption(value) {
                    this._screenCaption = value;
                    this.onSetScreenCaption();
                }
                onOpenScreen() { }
                onCloseScreen() { return true; }
                refreshSearch() { }
                build() {
                    super.build();
                    this.css.add("sol_pantalla");
                    this.atributos.agregar("titulo", this.screenCaption);
                }
                onSetModel() { }
                onSetScreenCaption() { }
            }
            Screens.BaseScreen = BaseScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ScreensZone extends Sol.Control {
                constructor() {
                    super();
                    this.isOpening = false;
                    this.navigation = new Sol.Control("nav");
                    this.solZone = new Sol.Control("section");
                    this.quickButton = new Sol.Button();
                    this.quickToolsBar = new Sol.Control();
                    this.add(this.navigation);
                    this.add(this.solZone);
                    this.configureBrowserBackButton();
                    this.configurePageExit();
                }
                get currentID() {
                    return this.solZone
                        .controls
                        .reverse()
                        .that(screen => screen instanceof Screens.DetailsScreen).code;
                }
                get currentScreen() {
                    return this.solZone.controls.that(control => control.visible);
                }
                get currentDetails() {
                    return this.screens.where(sc => sc instanceof Screens.DetailsScreen).last();
                }
                get currentFileScreen() {
                    var _a;
                    return this.screens.where(sc => sc instanceof Screens.Registro).last() ||
                        ((_a = this.screens.first()) === null || _a === void 0 ? void 0 : _a.startFileScreen);
                }
                get allMenus() {
                    let result = this.menuBag;
                    this.menuBag.forEach(mn => result.addMany(mn.Submenus));
                    return result;
                }
                get screens() {
                    return this.solZone.controls.cast();
                }
                get showNavigation() { return this.navigation.visible; }
                set showNavigation(value) {
                    this.navigation.visible = value;
                    this.quickToolsBar.visible = value;
                }
                addScreen(screen) {
                    this.solZone.add(screen);
                }
                backToDashboard() {
                    var _a;
                    var canceled = false;
                    this.solZone.controls.forEachReverse(control => {
                        if (canceled)
                            return;
                        if (!(control instanceof Screens.DashboardScreen) || control instanceof Screens.MonitoringScreen) {
                            if (control instanceof Screens.BaseScreen && !control.onCloseScreen()) {
                                canceled = true;
                                return;
                            }
                            this.solZone.controls.remove(control);
                        }
                    });
                    if (canceled)
                        return false;
                    this.solZone.controls.first().visible = true;
                    this.refreshNavigation();
                    (_a = this.currentScreen) === null || _a === void 0 ? void 0 : _a.refreshSearch();
                    return true;
                }
                closeCurrentScreen(forceClosing = false) {
                    if (this.solZone.controls.count == 1)
                        return;
                    const currentScreen = this.currentScreen;
                    if (!currentScreen)
                        return;
                    if (!forceClosing && !currentScreen.onCloseScreen())
                        return;
                    this.solZone.controls.removeItem(this.solZone.controls.count - 1);
                    this.showScreen(this.solZone.controls.item(this.solZone.controls.count - 1));
                    if (this.currentScreen instanceof Screens.Registro)
                        this.currentScreen.refreshSearch();
                }
                getPreviousScreen() {
                    return this.solZone.controls.item(this.solZone.controls.count - 2);
                }
                openScreen(screenName, type, message = null, iconCode = null, title = null, callback = null, code = null, anchorage = null) {
                    if (this.isOpening)
                        return;
                    this.isOpening = true;
                    const loader = new Web.Components.LoaderControl();
                    loader.caption = Sol.Environment.resources.cargando;
                    loader.baseControl = this.solZone;
                    if (!anchorage)
                        loader.show();
                    const requestData = {
                        ScreenName: screenName,
                        ClassName: type,
                        Code: code,
                        Anchorage: anchorage
                    };
                    Web.System.exec("lsperos32", "Open", requestData, e => {
                        loader.hide();
                        this.isOpening = false;
                        this.openScreenWithModel(screenName, iconCode, e, message, title, callback);
                        this.refreshNavigation();
                    }, () => {
                        this.openScreenWithModel("ErrorScreen");
                        this.isOpening = false;
                    });
                }
                create(typeCode, callback = null) {
                    if (this.isOpening)
                        return;
                    this.isOpening = true;
                    let requestData = {
                        ScreenName: "Registro",
                        ClassName: typeCode
                    };
                    Web.System.exec("lsperos32", "Open", requestData, e => {
                        this.isOpening = false;
                        const fileScreen = new Screens.Registro();
                        fileScreen.setModel(e);
                        const detailsScreen = fileScreen.createDetailsScreen(Sol.Environment.resources.crear + ' ' + e.ItemName, 0);
                        detailsScreen.myForm.onCancel = () => this.closeCurrentScreen();
                        detailsScreen.onSaved.unsubscribeAll();
                        detailsScreen.onSaved.subscribe(() => this.closeCurrentScreen());
                        Web.System.screens.showScreen(detailsScreen);
                        detailsScreen.foco();
                        if (callback)
                            callback(detailsScreen);
                    }, () => {
                        this.openScreenWithModel("ErrorScreen");
                        this.isOpening = false;
                    });
                }
                edit(typeCode, code, callback = null) {
                    if (this.isOpening)
                        return;
                    this.isOpening = true;
                    let requestData = {
                        ScreenName: "Registro",
                        ClassName: typeCode
                    };
                    Web.System.exec("lsperos32", "Open", requestData, e => {
                        this.isOpening = false;
                        const fileScreen = new Screens.Registro();
                        fileScreen.setModel(e);
                        const detailsScreen = fileScreen.createDetailsScreen(Sol.Environment.resources.editar, code);
                        detailsScreen.closingAlertEnabled = false;
                        detailsScreen.myForm.onCancel = () => this.closeCurrentScreen();
                        detailsScreen.onSaved.unsubscribeAll();
                        detailsScreen.onSaved.subscribe(() => this.closeCurrentScreen());
                        Web.System.screens.showScreen(detailsScreen);
                        detailsScreen.foco();
                        detailsScreen.load(code);
                        if (callback)
                            callback(detailsScreen);
                    }, () => {
                        this.openScreenWithModel("ErrorScreen");
                        this.isOpening = false;
                    });
                }
                getMyDetails(ctr) {
                    let inspectedCtr = ctr;
                    do
                        inspectedCtr = inspectedCtr.parent;
                    while (!!inspectedCtr && !(inspectedCtr instanceof Screens.DetailsScreen));
                    return inspectedCtr;
                }
                getScreenType(screenName) {
                    if (screenName.indexOf(".") > -1)
                        screenName = screenName.substring(screenName.lastIndexOf(".") + 1);
                    return eval("new Sol.Web.Screens." + screenName + "()");
                }
                openScreenWithModel(screenName, icono = null, model = null, mensaje = null, title = null, callback = null) {
                    var screen = this.getScreenType(screenName);
                    screen.model = model;
                    screen.systemMessage = mensaje;
                    screen.screenIcon = icono;
                    if (title)
                        screen.screenCaption = title;
                    if (callback)
                        callback(screen);
                    if (!screen.embbededMode)
                        this.solZone.controls.forEachReverse(ctr => ctr.visible = false);
                    screen.visible = true;
                    this.removeLoaders();
                    if (!screen.embbededMode)
                        this.solZone.add(screen);
                    this.refreshNavigation();
                    screen.onOpenScreen();
                    return screen;
                }
                processSystemMessaje(message) {
                    if (!message)
                        return;
                    eval("this." + message + "()");
                }
                reloadDashboard() {
                    this.solZone.controls.empty();
                    this.openScreen("DashboardScreen", null, null, null, null, null, this.currentDashboardCode);
                }
                scrollTop(y = 0) {
                    document.body.scrollTop = y;
                    document.documentElement.scrollTop = y;
                }
                screenFullPath() {
                    var screenPath = [];
                    this.solZone.controls.forEach(screen => {
                        if (screen instanceof Screens.BaseScreen && screen.screenCaption)
                            screenPath.push(screen.screenCaption);
                    });
                    return screenPath.join(' / ');
                }
                showScreen(screen) {
                    var hide = false;
                    for (var i = this.solZone.controls.count - 1; i >= 0; i--) {
                        var iScreen = this.solZone.controls.item(i);
                        if (iScreen.id == screen.id)
                            hide = true;
                        else {
                            if (hide)
                                iScreen.visible = false;
                            else
                                this.solZone.controls.remove(iScreen);
                        }
                    }
                    screen.visible = true;
                    this.refreshNavigation();
                }
                showPreviousScreen(pantalla) {
                    var vIndice = this.solZone.controls.indice(pantalla);
                    pantalla.visible = false;
                    this.solZone.controls.item(--vIndice).visible = true;
                    this.refreshNavigation();
                }
                build() {
                    super.build();
                    this.initializeQuickToolsBar();
                }
                configureBrowserBackButton() {
                    history.pushState(null, null, document.URL);
                    window.addEventListener('popstate', () => {
                        history.pushState(null, null, document.URL);
                        this.closeCurrentScreen();
                    });
                }
                configurePageExit() {
                    window.onbeforeunload = () => {
                        const isThereLockedScreen = this.screens.any(s => s instanceof Screens.BaseScreen && !s.onCloseScreen());
                        if (isThereLockedScreen)
                            return Sol.Environment.resources.confirm_exit;
                        else
                            return;
                    };
                }
                createLeftBreadcrumbButton() {
                    var screenCount = this.solZone.controls.count;
                    if (screenCount === 1) {
                        var homeIcon = new Sol.Control("i");
                        homeIcon.text = "&#xf015;";
                        this.navigation.add(homeIcon);
                    }
                    else {
                        var backButton = new Sol.Button();
                        backButton.type = Sol.ButtonType.Custom;
                        backButton.imageCode = "&#xf053;";
                        backButton.onClick = () => this.closeCurrentScreen();
                        backButton.estilos.agregar("cursor", "pointer");
                        this.navigation.add(backButton);
                    }
                }
                createSeparator() {
                    var vSeparador = new Sol.Control("span");
                    vSeparador.text = "/";
                    return vSeparador;
                }
                initializeQuickToolsBar() {
                    if (!this.systemScreen.model.QuickTools || this.systemScreen.model.QuickTools.length == 0)
                        return;
                    this.quickToolsBar.css.add("sol_quick_tools_bar");
                    this.quickToolsBar.add(this.quickButton);
                    this.controls.insert(0, this.quickToolsBar);
                    this.initializeQuickActions();
                }
                initializeQuickActions() {
                    var quickTools = Sol.List.from(this.systemScreen.model.QuickTools);
                    this.quickButton.text = "+";
                    this.quickButton.tip = Sol.Environment.resources.quickActions;
                    var searchItem = new Sol.Control("li");
                    var searchField = new Sol.Field();
                    searchField.placeHolder = Sol.Environment.resources.buscar + "...";
                    searchField.ancho = 275;
                    searchField.onClick = () => searchField.clickEvent.stopPropagation();
                    searchField.onKeyUp = () => {
                        var items = this.quickButton.subitems.skip(1);
                        items.forEach(ctr => ctr.visible = ctr.controls.item(1).text.toLowerCase().indexOf(searchField.value.toLowerCase()) > -1);
                    };
                    searchItem.add(searchField);
                    this.quickButton.subitems.add(searchItem);
                    this.quickButton.subitems.addMany(quickTools.select(qk => {
                        var quickTool = new Sol.Control("li");
                        var icon = new Sol.Control("i");
                        icon.text = qk.Icon;
                        quickTool.add(icon);
                        var caption = new Sol.Control("span");
                        caption.text = qk.Title;
                        quickTool.add(caption);
                        quickTool.onClick = () => {
                            if (!this.backToDashboard())
                                return;
                            this.quickButton.hidePopup();
                            this.openScreen(qk.Screen, qk.ClassName, null, null, qk.Icon, screen => screen.onOpenScreen = () => screen.addNew());
                        };
                        return quickTool;
                    }).toArray());
                }
                navigationClick(trail) {
                    var loader = this.solZone.controls.that(ctr => ctr instanceof Web.Components.LoaderControl && ctr.visible);
                    if (loader)
                        loader.hide();
                    var total = this.solZone.controls.count;
                    if (this.navigation.controls.indice(trail) == 1) {
                        this.backToDashboard();
                        return;
                    }
                    for (var indice = total - 1; indice > 0; indice--) {
                        var control = this.solZone.controls.item(indice);
                        if (trail.screenId == control.id) {
                            this.showScreen(control);
                            if (this.currentScreen instanceof Screens.Registro)
                                this.currentScreen.refreshSearch();
                            break;
                        }
                        else if (control instanceof Screens.BaseScreen &&
                            !control.onCloseScreen())
                            break;
                    }
                }
                refreshNavigation() {
                    var requiresSeparator = false;
                    var screenCount = this.solZone.controls.count;
                    var dashboards = Sol.List.from(this.systemScreen.model.Dashboards);
                    this.navigation.controls.empty();
                    this.createLeftBreadcrumbButton();
                    for (var index = 0; index < screenCount; index++) {
                        var screen = this.solZone.controls.item(index);
                        if (!screen.screenCaption)
                            continue;
                        if (requiresSeparator)
                            this.navigation.add(this.createSeparator());
                        var miga;
                        if (index == 0 && dashboards.count > 1) {
                            var buttonTrail = new Screens.ButtonTrail();
                            buttonTrail.subitems.addMany(dashboards.select(d => {
                                var item = new Sol.Control("li");
                                item.text = d.Title;
                                item.data = d;
                                return item;
                            }).toArray());
                            buttonTrail.onSubitemClick = i => {
                                var entry = i.data;
                                buttonTrail.hidePopup();
                                if (!this.backToDashboard())
                                    return;
                                if (entry.Code != this.currentDashboardCode) {
                                    this.solZone.controls.empty();
                                    this.currentDashboardCode = entry.Code;
                                    this.openScreen("DashboardScreen", null, null, null, null, null, entry.Code);
                                }
                            };
                            miga = buttonTrail;
                        }
                        else
                            miga = screen.visible ? new Screens.TextTrail() : new Screens.LinkTrail();
                        if (!screen.visible)
                            miga.onClick = e => this.navigationClick(e);
                        miga.text = screen.screenCaption;
                        miga.screenId = screen.id;
                        this.navigation.add(miga);
                        if (screen.visible)
                            break;
                        requiresSeparator = true;
                    }
                }
                removeLoaders() {
                    this.controls.where(ctr => ctr instanceof Web.Components.LoaderControl).forEachReverse(ctr => this.controls.remove(ctr));
                    this.solZone.visible = true;
                }
            }
            Screens.ScreensZone = ScreensZone;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        class System {
            static exec(manager, method, data, success = null, error = null) {
                var request = {
                    credential: Sol.Environment.credential.ticket ? Sol.Environment.credential.export() : null,
                    manager: manager,
                    method: method,
                    data: JSON.stringify(data)
                };
                return Sol.Http.Ajax.post("/exec", request, e => { if (success)
                    success(e); }, () => { if (error)
                    error(); });
            }
            static execLarge(manager, method, data, success, error = null) {
                const request = {
                    credential: Sol.Environment.credential.ticket ? Sol.Environment.credential.export() : null,
                    manager: manager,
                    method: method,
                    data: JSON.stringify(data)
                };
                Sol.Http.Ajax.post("/exec", request, e => {
                    const response = e;
                    if (response.IsSyncronous && success)
                        success(response.Response);
                    else {
                        const progress = new Web.ProgressDialog();
                        progress.onClose = () => {
                            this.screens.controls.remove(progress);
                            error === null || error === void 0 ? void 0 : error.apply(this);
                        };
                        progress.onCompleted = () => success(progress.response);
                        this.screens.add(progress);
                        progress.follow(response.ProcessID);
                    }
                }, () => { if (error)
                    error(); });
            }
            static create(typeCode, callback = null) {
                this.screens.create(typeCode, callback);
            }
            static edit(typeCode, code, callback = null) {
                this.screens.edit(typeCode, code, callback);
            }
            static openSystem(systemCode) {
                var currentFileScreen = this.screens.screens.that(s => s instanceof Web.Screens.Registro);
                Sol.Environment.credential.empresa = systemCode;
                this.exec("hjkj28d", "ChangeCompany", { companyID: systemCode }, e => {
                    Sol.Environment.credential.load(e.Credential);
                    System.openHome(e);
                    if (currentFileScreen) {
                        var menus = Sol.List.from(e.Menus);
                        var equivalentMenu;
                        menus.forEach(m => equivalentMenu = Sol.List.from(m.Submenus).that(s => s.Pantalla == "Registro" &&
                            s.Clase == currentFileScreen.model.ClassType));
                        if (equivalentMenu)
                            this.screens.openScreen(equivalentMenu.Pantalla, equivalentMenu.Clase, equivalentMenu.MensajeDeSistema, equivalentMenu.Icono);
                    }
                });
            }
            static openTab(t) {
                window.open(window.location.protocol + "//" + window.location.host + "?ticket=" + t);
            }
            static openHome(model) {
                if (System.home)
                    System.home.destroy();
                new Web.Screens.SystemScreen(model).abrir("#sol");
            }
            static requestSupervisorKey(message, successCallback) {
                let code = prompt(message);
                if (code != null)
                    System.exec("hjkj28d", "CheckSupervisorCode", { authCode: code }, e => {
                        if (e)
                            successCallback();
                        else
                            alert("Código inválido!");
                    });
            }
            static start(language) {
                Sol.Environment.credential.idioma = language;
                System.initializeMonitoring();
                var loginScreen = new Web.Screens.Login();
                loginScreen.abrir("body");
            }
            static startEmbed(systemUrl, ticket) {
                const language = "pt";
                Sol.Environment.systemUrl = systemUrl;
                Sol.Environment.filePath = systemUrl + "/download/";
                Sol.Environment.uploadPath = systemUrl + "/upload/";
                Sol.Environment.loadCss("/css");
                Sol.Environment.loadJs("/res/" + language + ".js");
                Sol.Environment.loadJs("/frameworks/chart.min.js");
                const data = { ticket: ticket, language: language };
                System.initializeMonitoring();
                System.exec("hjkj28d", "EnterDirectly", data, model => {
                    if (!model.Fail) {
                        Sol.Environment.credential.load(model.Credencial);
                        model.SystemModel.EmbedMode = true;
                        System.openHome(model.SystemModel);
                    }
                    else
                        System.start(language);
                });
            }
            static startDirectly(ticket) {
                Sol.Environment.credential.idioma = "pt";
                System.initializeMonitoring();
                const data = { ticket: ticket, language: "pt" };
                System.initializeMonitoring();
                System.exec("hjkj28d", "EnterDirectly", data, model => {
                    if (!model.Fail) {
                        Sol.Environment.credential.load(model.Credencial);
                        System.openHome(model.SystemModel);
                    }
                    else
                        System.start("pt");
                });
            }
            static startWithCredentials(user, pass) {
                Sol.Environment.credential.idioma = "pt";
                System.initializeMonitoring();
                const data = { credentials: { Username: user, Password: pass }, language: "pt" };
                System.initializeMonitoring();
                System.exec("hjkj28d", "EnterWithCredentials", data, model => {
                    if (!model.Fail) {
                        Sol.Environment.credential.load(model.Credencial);
                        System.openHome(model.SystemModel);
                    }
                    else
                        System.start("pt");
                });
            }
            static initializeMonitoring() {
                window.onkeyup = e => {
                    if (!this.screens)
                        return;
                    if (e.key == "PrintScreen")
                        this.exec("pp3iasd4", "RegisterPrintScreen", {
                            credential: Sol.Environment.credential.export(),
                            screen: this.screens.screenFullPath()
                        });
                };
            }
        }
        System.commonPermissions = new Sol.List();
        Web.System = System;
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        class FilterLabel extends Sol.Label {
            build() {
                super.build();
                if (this.showVisionButton) {
                    const visionButton = new Sol.Button();
                    visionButton.type = Sol.ButtonType.Link;
                    visionButton.imageCode = "&#xf00a;";
                    visionButton.text = Sol.Environment.resources.vision;
                    visionButton.css.add("sol_tabla_search_vision");
                    visionButton.onClick = () => this.onViewRequested();
                    this.add(visionButton);
                }
            }
        }
        Web.FilterLabel = FilterLabel;
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            class LoadBehaviour {
                apply(form, editor, config, code) {
                    Web.System.exec(config.ManagerCode, config.MethodName, { code: code }, e => Sol.List.from(e.Configs).forEach(cfg => {
                        const targetEditor = form.getEditor(cfg.EditorName);
                        targetEditor[cfg.PropertyName] = cfg.Value;
                        if (cfg.PropertyName == "visible" && targetEditor.myLabel)
                            targetEditor.myLabel.visible = cfg.Value;
                    }));
                }
            }
            Behaviours.LoadBehaviour = LoadBehaviour;
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            class SetVisibilityBehaviour {
                apply(form, editor, config, code) {
                    this.form = form;
                    this.editor = editor;
                    this.config = config;
                    editor.onValueModified.subscribe(() => this.toggleVisibility());
                    editor.onSet.subscribe(() => this.toggleVisibility());
                    if (!this.form.code)
                        setTimeout(() => this.toggleVisibility(), 300);
                }
                toggleVisibility() {
                    var _a, _b, _c;
                    let value = this.editor instanceof Sol.Combo || this.editor instanceof Sol.MultipleChoice ? this.editor.selectedCode : this.editor.value;
                    value = ((_a = value) === null || _a === void 0 ? void 0 : _a.Valor) ? value.Valor : value;
                    const targetEditor = this.form.getEditor(this.config.PropertyName);
                    if (!targetEditor)
                        return;
                    const currentCode = this.form.parent.code;
                    const targetControl = targetEditor.parent instanceof Sol.FieldWrapper ? targetEditor.parent : targetEditor.toControl();
                    if (this.config.SingleValue)
                        this.config.InValues = [this.config.SingleValue];
                    let isVisibile = Sol.List.from(this.config.InValues).contains(value);
                    if (isVisibile && currentCode && targetEditor.fieldModel.Visibility == Sol.FieldVisibility.OnlyInserting)
                        isVisibile = false;
                    if (isVisibile && !currentCode && targetEditor.fieldModel.Visibility == Sol.FieldVisibility.OnlyEditing)
                        isVisibile = false;
                    targetControl.visible = isVisibile;
                    targetEditor.visibleByBehaviour = isVisibile;
                    if (!(targetControl instanceof Sol.FieldWrapper) && targetEditor.myLabel)
                        targetEditor.myLabel.visible = isVisibile;
                    if (isVisibile)
                        (_b = targetEditor.onValueModified) === null || _b === void 0 ? void 0 : _b.invoke();
                    if (targetEditor.group && targetEditor.group.GroupDisplay)
                        targetEditor.group.GroupDisplay.visible = isVisibile ||
                            this.form.editors.any(edt => {
                                var _a;
                                return (targetEditor.group.GroupDisplay == ((_a = edt.group) === null || _a === void 0 ? void 0 : _a.GroupDisplay) &&
                                    edt.visibleByBehaviour !== false);
                            });
                    if ((_c = targetEditor.myLabel) === null || _c === void 0 ? void 0 : _c.minimizable)
                        targetEditor.myLabel.expanded = isVisibile;
                }
            }
            Behaviours.SetVisibilityBehaviour = SetVisibilityBehaviour;
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            class SetReadonlyBehaviour {
                apply(form, editor, config, code) {
                    this.form = form;
                    this.editor = editor;
                    this.config = config;
                    editor.onValueModified.subscribe(() => this.toggleReadonly());
                    editor.onSet.subscribe(() => this.toggleReadonly());
                }
                toggleReadonly() {
                    if (this.editor.readonly)
                        return;
                    let value = this.editor instanceof Sol.Combo || this.editor instanceof Sol.MultipleChoice ? this.editor.selectedCode : this.editor.value;
                    value = value.Valor ? value.Valor : value;
                    if (this.config.Value)
                        this.config.InValues = [this.config.Value];
                    const isReadonly = Sol.List.from(this.config.InValues).contains(value);
                    const targetEditor = this.form.getEditor(this.config.PropertyName);
                    if (targetEditor)
                        targetEditor.readonly = isReadonly;
                }
            }
            Behaviours.SetReadonlyBehaviour = SetReadonlyBehaviour;
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            class SetRequiredBehaviour {
                apply(form, editor, config, code) {
                    this.form = form;
                    this.editor = editor;
                    this.config = config;
                    editor.onValueModified.subscribe(() => this.toggleRequiredState());
                    editor.onSet.subscribe(() => this.toggleRequiredState());
                }
                toggleRequiredState() {
                    let value = this.editor instanceof Sol.Combo || this.editor instanceof Sol.MultipleChoice ? this.editor.selectedCode : this.editor.value;
                    value = value.Valor ? value.Valor : value;
                    const targetEditor = this.form.getEditor(this.config.PropertyName);
                    if (!targetEditor)
                        return;
                    if (this.config.SingleValue)
                        this.config.InValues = [this.config.SingleValue];
                    const isRequired = Sol.List.from(this.config.InValues).contains(value);
                    targetEditor.required = isRequired;
                    if (targetEditor.myLabel)
                        targetEditor.myLabel.showRequiredIcon = isRequired;
                }
            }
            Behaviours.SetRequiredBehaviour = SetRequiredBehaviour;
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            let CallMethodMode;
            (function (CallMethodMode) {
                CallMethodMode[CallMethodMode["Always"] = 0] = "Always";
                CallMethodMode[CallMethodMode["WhenTrue"] = 1] = "WhenTrue";
                CallMethodMode[CallMethodMode["WhenFalse"] = 2] = "WhenFalse";
            })(CallMethodMode = Behaviours.CallMethodMode || (Behaviours.CallMethodMode = {}));
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            class CallMethodBehaviour {
                apply(form, editor, config, code) {
                    this.form = form;
                    this.editor = editor;
                    this.config = config;
                    editor.onValueModified.subscribe(() => this.callMethod());
                    if (!config.DisableOnSet)
                        editor.onSet.subscribe(() => this.callMethod());
                }
                callMethod() {
                    const value = parseInt(this.editor instanceof Sol.Combo || this.editor instanceof Sol.MultipleChoice ? this.editor.selectedCode : this.editor.value);
                    const targetEditor = this.form.getEditor(this.config.PropertyName);
                    const isTrue = this.config.Value == value || Sol.List.from(this.config.Values).contains(value);
                    if (!targetEditor)
                        return;
                    if (this.config.Mode == Behaviours.CallMethodMode.Always || (isTrue && this.config.Mode == Behaviours.CallMethodMode.WhenTrue) || (!isTrue && this.config.Mode == Behaviours.CallMethodMode.WhenFalse))
                        targetEditor[this.config.MethodName].apply(targetEditor, isTrue ? this.config.WhenTrueArgs : this.config.WhenFalseArgs);
                }
            }
            Behaviours.CallMethodBehaviour = CallMethodBehaviour;
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            class ChangeLabelBehaviour {
                apply(form, editor, config, code) {
                    this.form = form;
                    this.editor = editor;
                    this.config = config;
                    editor.onValueModified.subscribe(() => this.changeLabel());
                    editor.onSet.subscribe(() => this.changeLabel());
                }
                changeLabel() {
                    const value = parseInt(this.editor instanceof Sol.Combo || this.editor instanceof Sol.MultipleChoice ? this.editor.selectedCode : this.editor.value);
                    const targetEditor = this.form.getEditor(this.config.PropertyName);
                    if (this.config.Value)
                        this.config.InValues = [this.config.Value];
                    const changeCaption = Sol.List.from(this.config.InValues).contains(value);
                    if (changeCaption)
                        targetEditor.myLabel.text = this.config.NewCaption;
                }
            }
            Behaviours.ChangeLabelBehaviour = ChangeLabelBehaviour;
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            class CalculationBehaviour {
                get fields() { return Sol.List.from([...this.config.Formula["matchAll"](/\[\w*\]/gm)]).select(m => m[0].slice(1, -1)); }
                get editors() { return this.fields.select(fld => this.form.getEditor(fld)).where(fld => !!fld); }
                apply(form, editor, config, code) {
                    this.form = form;
                    this.editor = editor;
                    this.config = config;
                    setTimeout(() => this.editors.where(edt => !edt.readonly).forEach(edt => {
                        var _a, _b, _c;
                        (_a = edt.onValueModified) === null || _a === void 0 ? void 0 : _a.subscribe(() => this.calc());
                        (_b = edt.onValueModified) === null || _b === void 0 ? void 0 : _b.connect(edt.toControl(), "change");
                        (_c = edt.onSet) === null || _c === void 0 ? void 0 : _c.subscribe(() => this.calc());
                    }), 300);
                }
                calc() {
                    let formula = this.config.Formula;
                    this.fields.forEach(fld => { var _a; return formula = formula.replace('[' + fld + ']', (((_a = this.form.getEditor(fld)) === null || _a === void 0 ? void 0 : _a[this.config.ValueProperty]) || 0).toString()); });
                    this.editor.numericValue = eval(formula);
                }
            }
            Behaviours.CalculationBehaviour = CalculationBehaviour;
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Behaviours;
        (function (Behaviours) {
            class LoadFieldBehaviour {
                get fromToes() { return Sol.List.from(this.config.FromToes); }
                apply(form, editor, config, code) {
                    this.config = config;
                    this.form = form;
                    this.selector = editor;
                    editor.onValueModified.subscribe(() => this.loadData());
                }
                loadData() {
                    const targetEditors = this.fromToes.select(ft => {
                        const editor = this.form.getEditor(ft.To);
                        if (!editor)
                            return null;
                        editor.data = ft;
                        return editor;
                    })
                        .where(e => !!e);
                    if (!this.selector.selectedCode) {
                        targetEditors.forEach(e => e.clear());
                        return;
                    }
                    const data = {
                        className: this.config.ClassName,
                        code: parseInt(this.selector.selectedCode.toString()),
                        subtype: false,
                        propertyList: this.fromToes.select(ft => ft.From).toArray()
                    };
                    Web.System.exec("sn9d23vs7d", "Load", data, model => {
                        if (model.Fail)
                            return;
                        const values = Sol.List.from(model.Data);
                        targetEditors.forEach(e => {
                            var _a;
                            let fromTo = e.data;
                            if (fromTo.WhenEmpty && !e.isEmpty())
                                return;
                            e.value = (_a = values.that(v => v.Campo == fromTo.From)) === null || _a === void 0 ? void 0 : _a.Valor;
                        });
                    });
                }
            }
            Behaviours.LoadFieldBehaviour = LoadFieldBehaviour;
        })(Behaviours = Web.Behaviours || (Web.Behaviours = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Displays;
            (function (Displays) {
                class ColorizedDisplay extends Sol.Control {
                    constructor() {
                        super("span");
                        this.css.add("sol_colorized_display");
                    }
                    setValue(v) {
                        this.text = v.Campo;
                        if (v.Color == "#000000")
                            return;
                        this.estilos.definir("background-color", v.Color);
                        Sol.Colors.lightOrDark(v.Color) == Sol.Lightness.Dark ? this.estilos.definir("color", "#fff") : this.estilos.definir("color", "var(--textColor);");
                    }
                }
                Displays.ColorizedDisplay = ColorizedDisplay;
            })(Displays = Components.Displays || (Components.Displays = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class Toolbar extends Sol.Control {
                constructor() {
                    super();
                    this.css.add("sol_barra_herramientas");
                }
            }
            Components.Toolbar = Toolbar;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CalculableField extends Sol.Control {
                constructor() {
                    super();
                    this.mainField = new Sol.CurrencyField();
                    this.calcButton = new Sol.Button();
                    this.acceptsNegative = true;
                    this.useWrapper = true;
                    this.css.add("sol_calculable_field");
                    this.mainField.readonly = true;
                    this.add(this.mainField);
                    this.calcButton.css.add("sol_calculable_field_button");
                    this.calcButton.imageCode = "&#xf1ec;";
                    this.add(this.calcButton);
                    if (this.acceptsNegative)
                        this.mainField.acceptsNegative = true;
                }
                get readonly() { return this.mainField.readonly; }
                set readonly(value) { this.setReadOnly(value); }
                get value() { return this.mainField.value; }
                set value(value) { this.mainField.value = value; }
                get decimalValue() { return this.mainField.numericValue; }
                set decimalValue(value) { this.mainField.numericValue = value; }
                clear() { this.mainField.clear(); }
                foco() { this.mainField.foco(); }
                isEmpty() { return this.mainField.isEmpty(); }
                toControl() { return this; }
                validate() { return this.mainField.validate(); }
                setReadOnly(value) {
                    this.mainField.readonly = value;
                }
            }
            Components.CalculableField = CalculableField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CalculableDateField extends Sol.Control {
                constructor() {
                    super();
                    this.mainField = new Sol.DateField();
                    this.calcButton = new Sol.Button();
                    this.useWrapper = true;
                    this.css.add("sol_calculable_field");
                    this.calcButton.css.add("sol_calculable_field_button");
                    this.calcButton.imageCode = "&#xf021;";
                }
                get readonly() { return this.mainField.readonly; }
                set readonly(value) { this.setReadOnly(value); }
                get value() { return this.mainField.value; }
                set value(value) { this.mainField.value = value; }
                build() {
                    super.build();
                    this.add(this.mainField);
                    this.add(this.calcButton);
                }
                clear() { this.mainField.clear(); }
                foco() { this.mainField.foco(); }
                isEmpty() { return this.mainField.isEmpty(); }
                toControl() { return this; }
                validate() { return this.mainField.validate(); }
                setReadOnly(value) {
                    this.mainField.readonly = value;
                }
            }
            Components.CalculableDateField = CalculableDateField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        class EntityPicture extends Sol.Control {
            constructor(relationID = null) {
                super("img");
                this.css.add("sol_entity_pic");
                this.relationID = relationID;
            }
            get relationID() { return this._relationID; }
            set relationID(value) {
                this._relationID = value;
                let imgUrl = !value ? "data:," :
                    (Sol.Environment.systemUrl + "/person?c=" + Sol.Environment.credential.empresa + "&r=" + value);
                this.atributos.definir("src", imgUrl);
            }
        }
        Web.EntityPicture = EntityPicture;
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CollectionSelectorItem extends Sol.Control {
                constructor(m) {
                    super("li");
                    this.colorLegend = new Sol.Control("color");
                    this.deleteButton = new Sol.Control("sup");
                    this.model = m;
                    this.css.add("sol_selector_coleccion_item");
                    if (m.Color)
                        this.colorLegend.estilos.agregar("background-color", m.Color);
                }
                get canDelete() { return this.deleteButton.visible; }
                set canDelete(v) { this.deleteButton.visible = v; }
                get caption() { return this.model.Description; }
                build() {
                    if (this.model.Color)
                        this.add(this.colorLegend);
                    if (this.isPerson)
                        this.add(new Web.EntityPicture(parseInt(this.model.Code)));
                    this.addCtr(this.model.Description, null, "span");
                    this.deleteButton.text = "x";
                    this.deleteButton.onClick = () => this.deleteMe();
                    this.add(this.deleteButton);
                    super.build();
                }
                deleteMe() {
                    const selector = this.parent;
                    selector.valorAnterior = selector.value;
                    selector.controls.remove(this);
                    if (this.onDeleted)
                        this.onDeleted(this);
                }
            }
            Components.CollectionSelectorItem = CollectionSelectorItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CollectionSelector extends Sol.Control {
                constructor() {
                    super();
                    this.mainField = new Sol.Field();
                    this.popup = new Sol.Popup();
                    this._allowAddNew = true;
                    this.allowRemove = true;
                    this.displayProperty = "EntidadRelacionada$Nombre";
                    this.isComplex = false;
                    this._readonly = false;
                    this.css.add("sol_campo");
                    this.css.add("sol_selector_coleccion");
                    this.mainField.css.remove("sol_campo");
                    this.mainField.placeHolder = Sol.Environment.resources.typeToSearch;
                    this.mainField.onClick = () => this.fieldKeyUp(null);
                    this.mainField.onLeave.subscribe(() => this.fieldLeave());
                    this.mainField.onKeyUp = e => this.fieldKeyUp(e);
                    this.mainField.onKeyPress = e => this.fieldKeyPress(e);
                    this.add(this.mainField);
                    this.popup.visible = false;
                    this.popup.autoClose = false;
                    this.add(this.popup);
                }
                get allowAddNew() { return this._allowAddNew; }
                set allowAddNew(value) {
                    this._allowAddNew = value;
                    this.mainField.visible = this._allowAddNew;
                }
                get popupItems() { return this.popup.controls.cast(); }
                get selectedItems() {
                    return this.controls
                        .where(ctr => ctr instanceof Components.CollectionSelectorItem)
                        .cast();
                }
                get readonly() { return this._readonly; }
                set readonly(value) {
                    this._readonly = value;
                    this.mainField.visible = !value && (!this.configuration || this.configuration.AllowAddNew);
                    this.selectedItems.forEach(i => i.canDelete = !value);
                }
                validate() { return null; }
                get value() {
                    return this.selectedItems
                        .select(i => { return { ID: parseInt(i.model.Code) }; })
                        .toArray();
                }
                set value(v) {
                    this.clear();
                    Sol.List.from(v).forEach(datos => {
                        var option = this.parseOption(datos);
                        var item = new Components.CollectionSelectorItem(option);
                        item.isPerson = this.isPerson;
                        item.parent = this;
                        item.canDelete = !this.readonly;
                        if (this.configuration && !this.configuration.AllowRemove)
                            item.canDelete = false;
                        item.onDeleted = () => this.itemRemoved();
                        this.controls.insert(this.controls.count - 2, item);
                    });
                }
                build() {
                    if (this.customClass)
                        this.css.add(this.customClass);
                    if (this.configuration) {
                        this.allowAddNew = this.configuration.AllowAddNew;
                        if (!this.allowAddNew)
                            this.mainField.visible = false;
                        this.allowRemove = this.configuration.AllowRemove;
                    }
                    this.loadOptions();
                    super.build();
                }
                isEmpty() {
                    return !Sol.List.from(this.value).hasItems();
                }
                clear() {
                    for (var i = this.controls.count - 3; i >= 0; i--)
                        this.controls.removeItem(i);
                }
                loadSearchResults(model) {
                    for (var i = 0; i < model.Data.length; i++)
                        model.Data[i].push({ Campo: "ID", Valor: model.Codes[i] });
                    this.options = Sol.List
                        .from(model.Data)
                        .select(d => this.parseOption(d))
                        .toArray();
                    this.loadOptions();
                }
                toControl() { return this; }
                itemClick(vItem) {
                    this.selectItem(vItem);
                    this.saveNewItem(vItem);
                    setTimeout(() => { this.popup.visible = true; }, 300);
                }
                selectItem(item) {
                    if (!Sol.List.from(this.value).any(i => i.ID == item.model.Code)) {
                        this.valorAnterior = this.value;
                        var newItem = new Components.CollectionSelectorItem(item.model);
                        newItem.isPerson = this.isPerson;
                        newItem.parent = this;
                        newItem.canDelete = true;
                        newItem.onDeleted = () => this.itemRemoved();
                        this.controls.insert(this.controls.count - 2, newItem);
                        if (this.onChanged)
                            this.onChanged(this);
                    }
                    this.mainField.clear();
                    this.mainField.foco();
                }
                fieldEnter() {
                    this.fieldKeyUp(null);
                }
                fieldLeave() {
                    setTimeout(() => { this.popup.visible = false; }, 300);
                    if (this.mainField.value == "")
                        return;
                    var selectedItem = this.popupItems.that(ctr => ctr.caption == this.mainField.value);
                    if (!selectedItem)
                        return;
                    this.selectItem(selectedItem);
                }
                fieldKeyPress(e) {
                    if (e.which == 13) {
                        var item = this.popupItems.that(ctr => ctr.caption.toLowerCase() == this.mainField.value.toLowerCase());
                        if (!item)
                            return true;
                        this.selectItem(item);
                        return false;
                    }
                }
                fieldKeyUp(e) {
                    if (this.configuration && this.configuration.DynamicResults) {
                        var properties = new Sol.List();
                        properties.add("ID");
                        properties.add(this.displayProperty);
                        if (this.configuration.IsColorable)
                            properties.add("Color");
                        var data = {
                            className: this.clase,
                            currentPage: 1,
                            rowCount: 20,
                            filters: this.getFilters().toArray(),
                            sortProperty: this.displayProperty,
                            sortOrder: Web.Ordering.ascending,
                            properties: properties.toArray(),
                            pageInfo: true
                        };
                        this.stopCurrentRequest();
                        this.currentRequest = Web.System.exec("i3n48smak", "Search", data, model => {
                            this.popup.show();
                            this.loadSearchResults(model);
                        });
                    }
                    else {
                        this.popup.show();
                        this.popupItems.forEachReverse(ctr => ctr.visible = ctr.caption.toLowerCase().indexOf(this.mainField.value.toLowerCase()) == 0);
                        if (this.mainField.isEmpty())
                            return true;
                        var suggestion = this.popupItems.that(ctr => ctr.visible);
                        var ignoreSuggestionKeys = Sol.List.from([8, 37, 13]);
                        if (suggestion && !ignoreSuggestionKeys.contains(e === null || e === void 0 ? void 0 : e.which)) {
                            var position = this.mainField.posicionCursor;
                            this.mainField.value = suggestion.caption;
                            this.mainField.selectText(position, this.mainField.value.length);
                        }
                    }
                    return true;
                }
                getFilters() {
                    var filters = new Sol.List();
                    filters.add({ PropertyName: this.displayProperty, FilterType: "SText", FilterValue: this.mainField.value });
                    if (this.isRelation)
                        filters.add({ PropertyName: "Activo", FilterType: "SBoolean", FilterValue: true });
                    return filters;
                }
                itemRemoved() {
                    if (this.onChanged)
                        this.onChanged(this);
                }
                loadOptions() {
                    if (!this.options)
                        return;
                    this.popup.controls.empty();
                    this.options.forEach(o => {
                        const item = new Components.CollectionSelectorItem(o);
                        item.isPerson = this.isPerson;
                        item.onClick = () => this.itemClick(item);
                        item.onDeleted = () => this.itemRemoved();
                        if (!this.allowRemove)
                            item.canDelete = false;
                        this.popup.add(item);
                        if (o.Checked)
                            this.selectItem(item);
                    });
                }
                saveNewItem(item) {
                }
                parseOption(data) {
                    var dataCollection = Sol.List.from(data);
                    var color = null;
                    if (dataCollection.any(d => d.Campo == "Color"))
                        color = dataCollection.that(d => d.Campo == "Color").Valor;
                    return {
                        Code: dataCollection.that(d => d.Campo == "ID").Valor,
                        Color: color,
                        Description: dataCollection.that(d => d.Campo.match(/Nombre$/) != null).Valor,
                        Checked: false
                    };
                }
                stopCurrentRequest() {
                    if (!this.currentRequest)
                        return;
                    this.currentRequest.abort();
                    this.currentRequest = null;
                }
                foco() { }
            }
            Components.CollectionSelector = CollectionSelector;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let ListViewFieldPriority;
            (function (ListViewFieldPriority) {
                ListViewFieldPriority[ListViewFieldPriority["Normal"] = 0] = "Normal";
                ListViewFieldPriority[ListViewFieldPriority["High"] = 1] = "High";
                ListViewFieldPriority[ListViewFieldPriority["Descriptive"] = 2] = "Descriptive";
            })(ListViewFieldPriority = Components.ListViewFieldPriority || (Components.ListViewFieldPriority = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let ListViewFieldPosition;
            (function (ListViewFieldPosition) {
                ListViewFieldPosition[ListViewFieldPosition["Left"] = 0] = "Left";
                ListViewFieldPosition[ListViewFieldPosition["Right"] = 1] = "Right";
                ListViewFieldPosition[ListViewFieldPosition["Image"] = 2] = "Image";
                ListViewFieldPosition[ListViewFieldPosition["Block"] = 3] = "Block";
            })(ListViewFieldPosition = Components.ListViewFieldPosition || (Components.ListViewFieldPosition = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ListViewItem extends Sol.Control {
                constructor() {
                    super("li");
                    this.numberDisplay = new Sol.Control("span");
                    this.code = 0;
                    this.editors = new Sol.List();
                    this.itemObjects = new Sol.List();
                    this.hiddenProperties = new Sol.List();
                    this._itemNumber = 1;
                    this._selected = false;
                }
                get itemNumber() { return this._itemNumber; }
                set itemNumber(value) {
                    this._itemNumber = value;
                    this.numberDisplay.text = String(value).padStart(2, '0') + '.';
                }
                get selected() { return this._selected; }
                set selected(value) {
                    if (this._selected == value)
                        return;
                    this._selected = value;
                    if (value) {
                        this.list.items.where(i => i.selected && i != this).forEach(i => i.selected = false);
                        this.css.add("sol_list_view_selected");
                        this.html.scrollIntoView(false);
                    }
                    else
                        this.css.remove("sol_list_view_selected");
                }
                fillData(data) {
                    if (this.showItemNumber) {
                        this.numberDisplay.css.add("sol_list_view_number");
                        this.add(this.numberDisplay);
                    }
                    this.list.configuration.where(cfg => !cfg.disabled).forEach(cfg => {
                        var _a;
                        var model;
                        if (data)
                            model = data.that(i => i.Campo == cfg.property);
                        var dataDisplay;
                        if (model && cfg.property.endsWith("ID"))
                            model.Valor = model.Valor.toString().padLeft("0000");
                        if (cfg.position == Components.ListViewFieldPosition.Image) {
                            if (!model || !model.Valor)
                                return;
                            var image = model.Valor;
                            this.estilos.agregar("background-image", "url(" + Sol.Environment.imagePath + image + ")");
                            this.estilos.agregar("background-size", this.list.imageSize + "px " + this.list.imageSize + "px");
                            this.estilos.agregar("background-size", this.list.imageSize + "px " + this.list.imageSize + "px");
                            this.estilos.agregar("min-height", (this.list.imageSize + 10) + "px");
                            this.estilos.agregar("padding-left", (this.list.imageSize + 15) + "px");
                            return;
                        }
                        if ((cfg.hidden && model) || (cfg.hiddenWhenEmpty && !(model === null || model === void 0 ? void 0 : model.Valor))) {
                            this.hiddenProperties.add(model);
                            return;
                        }
                        if (cfg.editor) {
                            dataDisplay = new Sol.Control("span");
                            var label = new Sol.Label();
                            label.text = cfg.caption + ':';
                            var editor = Web.Editors.createField(cfg.editor, null);
                            if (this.list.readonly)
                                editor.readonly = true;
                            if (editor instanceof Sol.Field)
                                editor.autoWidth = false;
                            label.editor = editor;
                            if (cfg.caption)
                                dataDisplay.add(label);
                            dataDisplay.add(editor.toControl());
                            if (model)
                                editor.value = model.Valor;
                            editor.visible = !cfg.hiddenWhenEmpty || !editor.isEmpty();
                            this.editors.add(editor);
                        }
                        else if (model && model.Valor && model.Valor.Color) {
                            dataDisplay = new Components.Displays.ColorizedDisplay();
                            dataDisplay.setValue(model.Valor);
                            dataDisplay.visible = !(!dataDisplay.text);
                        }
                        else {
                            dataDisplay = new Sol.Control("span");
                            if (model) {
                                if (cfg.caption)
                                    dataDisplay.text = cfg.caption + ": ";
                                dataDisplay.text = dataDisplay.text || "";
                                if (model.Valor && model.Valor.Campo)
                                    dataDisplay.text = model.Valor.Campo;
                                else {
                                    dataDisplay.text += model.Valor;
                                    if (!model.Valor)
                                        dataDisplay.text = "";
                                }
                                if (!model.Valor && cfg.defaultText)
                                    dataDisplay.text = cfg.defaultText;
                            }
                            else if (cfg.defaultText)
                                dataDisplay.text = cfg.defaultText;
                        }
                        if (cfg.position == Components.ListViewFieldPosition.Left || cfg.position == Components.ListViewFieldPosition.Right) {
                            const position = cfg.position == Components.ListViewFieldPosition.Left ? "left" : "right";
                            dataDisplay.estilos.agregar("float", position);
                            if (((_a = cfg.editor) === null || _a === void 0 ? void 0 : _a.DataType) != "Imagen")
                                dataDisplay.estilos.agregar("margin-" + (position == "left" ? "right" : "left"), "15px");
                        }
                        if (cfg.position == Components.ListViewFieldPosition.Block) {
                            cfg.lineBreak = true;
                            dataDisplay.estilos.agregar("display", "block");
                        }
                        if (cfg.lineBreak)
                            dataDisplay.estilos.agregar("clear", "both");
                        if (cfg.priority == Components.ListViewFieldPriority.Descriptive)
                            dataDisplay.estilos.agregar("font-style", "italic");
                        if (cfg.priority == Components.ListViewFieldPriority.High)
                            dataDisplay.css.add("sol_list_view_high");
                        if (cfg.cssClass)
                            dataDisplay.css.add(cfg.cssClass);
                        this.add(dataDisplay);
                        this.itemObjects.add({ configuration: cfg, display: dataDisplay });
                    });
                    var idModel = data.that(d => d.Campo == "ID");
                    if (idModel) {
                        if (typeof idModel.Valor == "number")
                            this.code = idModel.Valor;
                        else if (typeof idModel.Valor.Valor == "number")
                            this.code = idModel.Valor;
                    }
                    if (this.list.configuration.where(cfg => !cfg.disabled).last().position != Components.ListViewFieldPosition.Block)
                        this.add(new Sol.LineBreak());
                }
                getEditor(propertyName) {
                    return this.editors.that(e => e.propertyName == propertyName);
                }
                getDisplay(propertyName) {
                    var itemObj = this.itemObjects.that(i => i.configuration.property == propertyName);
                    if (!itemObj)
                        return null;
                    return itemObj.display;
                }
                getModelValue(propertyName) {
                    var key = Sol.List.from(this.model).that(m => m.Campo == propertyName);
                    if (!key)
                        return null;
                    return key.Valor;
                }
                toControl() { return this; }
            }
            Components.ListViewItem = ListViewItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ListView extends Sol.Control {
                constructor() {
                    super();
                    this.list = new Sol.Control("ul");
                    this.messageControl = new Sol.Control();
                    this.currentPage = 1;
                    this.filters = [];
                    this.imageSize = 80;
                    this.serverUrl = "";
                    this.pageSize = 20;
                    this.orderByProperty = "Nombre";
                    this.selectable = false;
                    this.serviceKey = "i3n48smak";
                    this.serviceMethod = "Search";
                    this.add(this.list);
                    this.css.add("sol_list_view");
                    this.messageControl.css.add("sol_list_view_empty");
                    this.messageText = Sol.Environment.resources.list_is_empty;
                    this.list.controls.onListChanged = () => this.messageControl.visible = !this.list.controls.hasItems();
                    this.add(this.messageControl);
                }
                get checkedCodes() { return this.checkedItems.select(i => i.code).toArray(); }
                get checkedItems() { return this.items.where(i => i.checked); }
                get messageText() { return this._messageText; }
                set messageText(value) {
                    this._messageText = value;
                    this.messageControl.text = value;
                    this.messageControl.visible = !!value;
                }
                get properties() {
                    var propCollection = this.configuration
                        .where(cfg => cfg.loadable)
                        .select(cfg => cfg.property)
                        .union(["ID"]);
                    if (this.groupProperty)
                        propCollection.add(this.groupProperty);
                    return propCollection.toArray();
                }
                get items() { return this.list.controls.where(ctr => ctr instanceof Components.ListViewItem).cast(); }
                isEmpty() { return !this.items.hasItems(); }
                get selectedIndex() { return this.items.indice(this.selectedItem); }
                get selectedItem() { return this.items.that(i => i.selected); }
                get values() {
                    return this.items
                        .select(ln => {
                        var itemData = ln.editors.where(f => !(!f.propertyName))
                            .select(f => ({ Campo: f.propertyName, Valor: f.value }));
                        itemData.add({ Campo: "ID", Valor: ln.code });
                        itemData = itemData.union(ln.hiddenProperties.where(v => !!v).select(v => {
                            delete v.__type;
                            return v;
                        }).toArray());
                        if (ln.onGettingExtraData)
                            itemData = itemData.union(ln.onGettingExtraData(ln));
                        return itemData.toArray();
                    }).toArray();
                }
                set values(v) {
                    this.clear();
                    this.addItems(v);
                }
                clear() {
                    this.list.controls.forEachReverse(ctr => {
                        if (!(ctr instanceof Sol.DialogBox))
                            this.list.controls.remove(ctr);
                    });
                }
                resetIDs() { this.items.forEach(i => i.code = 0); }
                search(requestData = null) {
                    requestData = requestData || {
                        className: this.className,
                        currentPage: this.currentPage,
                        rowCount: this.pageSize,
                        filters: this.filters,
                        sortProperty: this.orderByProperty,
                        sortOrder: Web.Ordering.ascending,
                        properties: this.properties,
                        pageInfo: true
                    };
                    this.stopCurrentRequest();
                    this.messageControl.text = Sol.Environment.resources.searching;
                    this.currentRequest = Web.System.exec(this.serviceKey, this.serviceMethod, requestData, model => {
                        var _a;
                        this.messageControl.text = this._messageText;
                        this.addItems(model.Data, model.Codes);
                        if (this.selectionEnabled && this.items.hasItems() && this.items.count == model.Codes.length)
                            this.items.first().selected = true;
                        this.lastTotals = Sol.List.from((_a = model.TotalInfo) === null || _a === void 0 ? void 0 : _a.Totals);
                        if (this.onAfterSearch)
                            this.onAfterSearch();
                    });
                }
                addItemFromData(data, code) {
                    var listItem = new Components.ListViewItem();
                    var rowItems = Sol.List.from(data);
                    listItem.list = this;
                    listItem.model = data;
                    listItem.code = code;
                    listItem.showItemNumber = this.showItemNumbers;
                    listItem.fillData(rowItems);
                    if (this.selectable)
                        listItem.onClick = () => {
                            this.selectedCode = listItem.code;
                            if (this.onSelect)
                                this.onSelect(data, code);
                        };
                    if (this.onInstantiateItem)
                        this.onInstantiateItem(listItem);
                    this.list.add(listItem);
                    this.updateNumbers();
                    return listItem;
                }
                addItems(items, ids = null) {
                    var data = Sol.List.from(items);
                    var index = 0;
                    var lastGroup;
                    data.forEach(row => {
                        if (this.groupProperty) {
                            var currentGroup = Sol.List.from(row).that(d => d.Campo == this.groupProperty).Valor;
                            if (currentGroup != lastGroup) {
                                var groupHeader = new Sol.Control("li");
                                groupHeader.text = currentGroup;
                                groupHeader.css.add("sol_list_view_header");
                                this.list.add(groupHeader);
                            }
                            lastGroup = currentGroup;
                        }
                        var id = 0;
                        if (ids)
                            id = ids[index];
                        this.addItemFromData(row, id);
                        index++;
                    });
                }
                addObjectItems(items) {
                    this.addItems(Sol.List.from(items)
                        .select(obj => this.configuration.select(cfg => ({ Campo: cfg.property, Valor: obj[cfg.property] })).toArray())
                        .toArray());
                }
                clearAndSearch() {
                    this.clear();
                    this.search();
                }
                containsCode(code) { return this.items.any(i => i.code == code); }
                removeItem(item) {
                    this.list.controls.remove(item);
                    this.updateNumbers();
                }
                select() {
                    if (!this.selectedItem)
                        return;
                    const selectedItem = this.selectedItem;
                    this.selectedCode = selectedItem.code;
                    if (this.onSelect)
                        this.onSelect(selectedItem.model, selectedItem.code);
                }
                selectDown() {
                    if (!this.selectedItem || this.selectedIndex == this.items.count - 1)
                        return;
                    this.items.item(this.selectedIndex + 1).selected = true;
                }
                selectUp() {
                    if (!this.selectedItem || this.selectedIndex == 0)
                        return;
                    this.items.item(this.selectedIndex - 1).selected = true;
                }
                build() {
                    super.build();
                    if (this.selectable)
                        this.css.add("sol_list_view_selectable");
                    if (this.showImage)
                        this.css.add("sol_list_view_images");
                }
                stopCurrentRequest() {
                    this.messageControl.text = this._messageText;
                    if (!this.currentRequest)
                        return;
                    this.currentRequest.abort();
                    this.currentRequest = null;
                }
                updateNumbers() {
                    if (!this.showItemNumbers)
                        return;
                    let i = 1;
                    this.items.forEach(item => item.itemNumber = i++);
                }
            }
            Components.ListView = ListView;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class Scrapbook extends Sol.Control {
                constructor() {
                    super();
                    this.css.add("sol_scrapbook");
                }
                get pictures() { return this.controls.cast(); }
                addItem(code, description, color, imageCode) {
                    var picture = new Components.ScrapbookPicture();
                    picture.code = code;
                    picture.description = description;
                    picture.color = color;
                    picture.imageCode = imageCode;
                    picture.onClick = () => this.onItemSelected(picture);
                    this.add(picture);
                }
            }
            Components.Scrapbook = Scrapbook;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScrapbookPicture extends Sol.Control {
                constructor() {
                    super("figure");
                }
                build() {
                    super.build();
                    const imageBox = new Sol.ImageBox();
                    if (this.imageCode)
                        imageBox.source = Sol.Environment.imagePath + this.imageCode;
                    else {
                        this.css.add("sol_scrapbook_no_image");
                        this.estilos.definir("border-left-color", this.color);
                    }
                    imageBox.visible = !!this.imageCode;
                    this.add(imageBox);
                    const caption = new Sol.Control("figcaption");
                    caption.text = this.description;
                    this.add(caption);
                }
            }
            Components.ScrapbookPicture = ScrapbookPicture;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SearchBox extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.searchField = new Sol.Field();
                    this.resultsDisplay = new Sol.Control("span");
                    this.arrowUpItem = new Sol.Button();
                    this.arrowDownItem = new Sol.Button();
                }
                toggleVisibility() {
                    this.visible = !this.visible;
                    this.searchField.foco();
                }
                build() {
                    this.searchField.placeHolder = Sol.Environment.resources.typeToSearch;
                    this.searchField.onKeyUp = () => this.search();
                    this.add(this.searchField);
                    this.resultsDisplay.css.add("sol_search_box_results_display");
                    this.add(this.resultsDisplay);
                    this.arrowUpItem.imageCode = "&#xf106;";
                    this.arrowUpItem.type = Sol.ButtonType.Custom;
                    this.arrowUpItem.visible = false;
                    this.arrowUpItem.onClick = () => this.searchUp();
                    this.add(this.arrowUpItem);
                    this.arrowDownItem.imageCode = "&#xf107;";
                    this.arrowDownItem.type = Sol.ButtonType.Custom;
                    this.arrowDownItem.visible = false;
                    this.arrowDownItem.onClick = () => this.searchDown();
                    this.add(this.arrowDownItem);
                }
                search() {
                    if (this.searchField.isEmpty()) {
                        this.resultsDisplay.text = '';
                        return;
                    }
                    this.results = this.onSearch(this.searchField.value);
                    this.resultCount = this.results.count - 1;
                    this.resultsDisplay.text = this.results.hasItems() ? "1" + Sol.Environment.resources.de + this.results.count : Sol.Environment.resources.no_encontrado;
                    if (this.results.hasItems()) {
                        this.currentResult = 0;
                        this.onSelect(this.results.first());
                    }
                    this.refreshArrows();
                }
                refreshArrows() {
                    this.arrowUpItem.visible = this.resultCount > 1;
                    this.arrowDownItem.visible = this.arrowUpItem.visible;
                }
                searchUp() {
                    this.currentResult = this.currentResult == 0 ? this.resultCount : this.currentResult - 1;
                    this.onSelect(this.results.item(this.currentResult));
                }
                searchDown() {
                    this.currentResult = this.currentResult == this.resultCount ? this.currentResult = 0 : this.currentResult + 1;
                    this.onSelect(this.results.item(this.currentResult));
                }
            }
            Components.SearchBox = SearchBox;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                let ProductIcon;
                (function (ProductIcon) {
                    ProductIcon[ProductIcon["NotSet"] = 0] = "NotSet";
                    ProductIcon[ProductIcon["Ok"] = 1] = "Ok";
                    ProductIcon[ProductIcon["Warning"] = 2] = "Warning";
                    ProductIcon[ProductIcon["New"] = 3] = "New";
                })(ProductIcon = Selectors.ProductIcon || (Selectors.ProductIcon = {}));
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class ViewDocumentIcon extends Sol.SelectorIcon {
                    constructor() {
                        super();
                        this.text = "&#xf15b;";
                    }
                }
                Selectors.ViewDocumentIcon = ViewDocumentIcon;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let DetailsNavigationDirection;
            (function (DetailsNavigationDirection) {
                DetailsNavigationDirection[DetailsNavigationDirection["Backward"] = -1] = "Backward";
                DetailsNavigationDirection[DetailsNavigationDirection["Forward"] = 1] = "Forward";
            })(DetailsNavigationDirection = Screens.DetailsNavigationDirection || (Screens.DetailsNavigationDirection = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class GridCell extends Sol.Control {
                constructor() {
                    super("td");
                    this.clickToEdit = false;
                    this.columnSpan = 1;
                    this.text = "&nbsp;";
                    this.controls.onListChanged = () => {
                        if (this.controls.hasItems())
                            this.text = "";
                    };
                }
                setAlignment(value) {
                    if (value == Sol.Alignment.Center)
                        this.estilos.definir("text-align", "center");
                    if (value == Sol.Alignment.Right)
                        this.estilos.definir("text-align", "right");
                }
                setVerticalAlignment(value) {
                    if (value == Sol.VerticalAlignment.Top)
                        this.estilos.definir("vertical-align", "top");
                    if (value == Sol.VerticalAlignment.Bottom)
                        this.estilos.definir("vertical-align", "bottom");
                }
                build() {
                    super.build();
                    if (this.columnSpan > 1)
                        this.atributos.agregar("colspan", this.columnSpan.toString());
                }
            }
            Components.GridCell = GridCell;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CheckCell extends Components.GridCell {
                constructor() {
                    super();
                    this.check = new Sol.Check();
                    this.css.add("sol_tabla_check");
                    this.check.visible = false;
                    this.add(this.check);
                }
            }
            Components.CheckCell = CheckCell;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let MessageFolder;
            (function (MessageFolder) {
                MessageFolder[MessageFolder["InBox"] = 1] = "InBox";
                MessageFolder[MessageFolder["Sent"] = 2] = "Sent";
                MessageFolder[MessageFolder["Archived"] = 3] = "Archived";
                MessageFolder[MessageFolder["Trash"] = 4] = "Trash";
            })(MessageFolder = Components.MessageFolder || (Components.MessageFolder = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SystemMessage extends Sol.Control {
                constructor(model) {
                    super();
                    this.archiveButton = new Sol.Button();
                    this.readButton = new Sol.Button();
                    this.trashButton = new Sol.Button();
                    this.model = model;
                    this.css.add("sol_system_message");
                    if (model.IsNew)
                        this.css.add("sol_system_message_unread");
                    if (model.SenderAcronym) {
                        const abbreviation = new Sol.Control();
                        abbreviation.text = model.SenderAcronym;
                        abbreviation.css.add("sol_message_abbreviation");
                        abbreviation.estilos.agregar("background-color", model.SenderColor);
                        if (model.SenderEmail)
                            abbreviation.estilos.agregar("margin-bottom", "10px");
                        this.add(abbreviation);
                    }
                    const wrapper = new Sol.Control();
                    const date = new Sol.Control("span");
                    date.text = model.Creación;
                    date.css.add("sol_message_date");
                    wrapper.add(date);
                    const sender = new Sol.Control("span");
                    sender.text = model.Sender;
                    sender.css.add("sol_message_sender");
                    wrapper.add(sender);
                    if (model.SenderEmail)
                        wrapper.addCtr(model.SenderEmail, "sol_message_email", "span");
                    if (!model.SenderAcronym)
                        wrapper.estilos.agregar("float", "right");
                    this.add(wrapper);
                    const subject = new Sol.Control();
                    subject.text = model.Subject;
                    subject.css.add("sol_message_subject");
                    this.add(subject);
                    if (model.Attachment) {
                        const attachment = new Sol.Control();
                        attachment.text = model.Attachment <= 1 ? `${model.Attachment} ${Sol.Environment.resources.attached_file}` : `${model.Attachment} ${Sol.Environment.resources.attached_file_pl}`;
                        attachment.css.add("sol_message_attachment");
                        this.add(attachment);
                    }
                    const toolBox = new Sol.Control();
                    toolBox.css.add("sol_message_toolBox");
                    if (model.IsNew) {
                        this.readButton.type = Sol.ButtonType.Link;
                        this.readButton.text = Sol.Environment.resources.markAsRead;
                        this.readButton.onClick = () => this.markAsRead();
                        toolBox.add(this.readButton);
                    }
                    if (model.AllowArchive) {
                        this.archiveButton.type = Sol.ButtonType.Link;
                        this.archiveButton.text = Sol.Environment.resources.archive;
                        this.archiveButton.onClick = () => this.changeFolder(Components.MessageFolder.Archived);
                        toolBox.add(this.archiveButton);
                    }
                    if (model.AllowSendToTrash) {
                        this.trashButton.type = Sol.ButtonType.Link;
                        this.trashButton.text = Sol.Environment.resources.eliminar;
                        this.trashButton.onClick = () => this.changeFolder(Components.MessageFolder.Trash);
                        toolBox.add(this.trashButton);
                    }
                    this.add(toolBox);
                }
                markAsRead() {
                    this.css.remove("sol_system_message_unread");
                    this.readButton.visible = false;
                    Web.System.exec("scv5qy9z", "MarkAsRead", { messageID: this.model.ID }, () => this.refreshMessageList());
                }
                changeFolder(folder) {
                    this.css.add("sol_system_message_loading");
                    const data = {
                        messageID: this.model.ID,
                        folder: folder
                    };
                    Web.System.exec("scv5qy9z", "ChangeFolder", data, e => {
                        if (e.Fail)
                            this.css.remove("sol_system_message_loading");
                        else
                            this.refreshMessageList();
                    });
                    this.clickResult = false;
                }
                refreshMessageList() {
                    Web.System.screens.currentScreen.refreshSearch();
                }
            }
            Components.SystemMessage = SystemMessage;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TitleDescriptionDrawer extends Sol.Control {
                constructor(data) {
                    super();
                    this.addCtr(data.Title, "sol_title_description_drawer_title");
                    this.addCtr(data.Description, "sol_title_description_drawer_desc");
                }
            }
            Components.TitleDescriptionDrawer = TitleDescriptionDrawer;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DataCombo extends Sol.Combo {
                constructor() {
                    super(...arguments);
                    this.autoLoad = true;
                    this.displayProperty = "Nombre";
                    this.valueProperty = "ID";
                    this.useWrapper = true;
                    this.filters = new Sol.List();
                    this.maxItems = 500;
                }
                clearItems() {
                    this.setValue(null);
                    this.controls.empty();
                    if (this.onUpdated)
                        this.onUpdated(this);
                }
                refresh(callback = null) {
                    if (!this.className)
                        return;
                    if (this.onBeforeRefresh)
                        this.onBeforeRefresh(this);
                    var currentValue = null;
                    if (!this.isEmpty())
                        currentValue = this.value;
                    this.controls.empty();
                    Sol.List.from(this.preFilters).forEach(flt => this.setFilter(flt));
                    if (this.isRelation)
                        this.setFilter({ PropertyName: "Activo", FilterType: "SBoolean", FilterValue: true });
                    if (this.contextClass)
                        this.setFilter({ PropertyName: this.propertyName, FilterType: "_context", FilterValue: this.contextClass });
                    if (this.anchorageProperty)
                        this.setFilter({ PropertyName: this.anchorageProperty, FilterType: "SInteger", FilterValue: Web.System.screens.getMyDetails(this).anchorageCode });
                    let data = {
                        className: this.className,
                        currentPage: 1,
                        rowCount: this.maxItems,
                        filters: this.filters.toArray(),
                        sortProperty: this.sortProperty || this.displayProperty,
                        sortOrder: Web.Ordering.ascending,
                        properties: [this.valueProperty, this.displayProperty],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        this.add(new Sol.ComboItem(0, this.showAllOption ? '[' + Sol.Environment.resources.todos + ']' : ""));
                        if (this.showEmptyFilterOption)
                            this.add(new Sol.ComboItem(-1, '[' + Sol.Environment.resources.none + ']'));
                        let uniqueSelection = this.autoSelectUniqueOption && model.Codes.length == 1;
                        for (var i = 0; i < model.Codes.length; i++) {
                            var rowData = Sol.List.from(model.Data[i]);
                            const code = this.valueProperty == "ID" ?
                                model.Codes[i] :
                                rowData.that(cmp => cmp.Campo == this.valueProperty).Valor;
                            this.addItem(code, rowData.that(cmp => cmp.Campo.indexOf(this.displayProperty) > -1).Valor, uniqueSelection);
                        }
                        this.isUpdated = true;
                        if (this.waitingValue) {
                            this.value = this.waitingValue;
                            this.waitingValue = null;
                        }
                        if (currentValue)
                            this.value = currentValue;
                        if (uniqueSelection)
                            this.onSet.invoke();
                        if (!callback && this.onUpdated)
                            this.onUpdated(this);
                        if (callback)
                            callback();
                    });
                }
                setCode(v) { this.setSelectedCode(v); }
                setFilter(filter) {
                    this.filters.removeWhere(flt => flt.PropertyName == filter.PropertyName);
                    this.filters.add(filter);
                }
                getSelectedCode() {
                    if (this.waitingValue)
                        return this.waitingValue.Valor;
                    return super.getSelectedCode();
                }
                setSelectedCode(v) {
                    super.setSelectedCode(v);
                    if (this.modoSol && this.html) {
                        if (!this.className || this.isUpdated)
                            this.html.value = this._valor.Valor;
                        else
                            this.waitingValue = { Campo: "", Valor: v };
                    }
                    else
                        this.waitingValue = { Campo: "", Valor: v };
                }
                getValue() {
                    if (this.waitingValue)
                        return this.waitingValue;
                    return super.getValue();
                }
                setValue(v) {
                    super.setValue(v);
                    if (this.modoSol && this.html) {
                        if (!this.className || this.isUpdated) {
                            this.html.value = this._valor.Valor;
                            if (this.html.value != this._valor.Valor) {
                                this.addItem(this._valor.Valor, this._valor.Campo);
                                this.html.value = this._valor.Valor;
                            }
                        }
                        else
                            this.waitingValue = v;
                    }
                    else if (v && v.Valor && this.className)
                        this.waitingValue = v;
                }
            }
            Components.DataCombo = DataCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class GridSelection {
                constructor() {
                    this.codes = new Sol.List();
                }
                get isEmpty() { return !this.allSelected && !this.codes.hasItems(); }
                clear() {
                    this.allSelected = false;
                    this.codes.empty();
                }
                isCodeSelected(code) {
                    return (this.allSelected && !this.codes.contains(code)) ||
                        (!this.allSelected && this.codes.contains(code));
                }
                select(code) {
                    if (!this.codes.contains(code))
                        this.codes.add(code);
                    else
                        this.codes.remove(code);
                }
            }
            Components.GridSelection = GridSelection;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DecisionButton extends Sol.Button {
                constructor(code, model) {
                    super();
                    this.type = Sol.ButtonType.Custom;
                    this.model = model;
                    this.code = code;
                    this.tip = model.Name;
                    this.text = model.Name;
                    this.abbreviation = model.Abbreviation;
                    this.abbreviationColor = model.Color;
                }
            }
            Components.DecisionButton = DecisionButton;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let ColumnOrder;
            (function (ColumnOrder) {
                ColumnOrder[ColumnOrder["NotSet"] = 0] = "NotSet";
                ColumnOrder[ColumnOrder["Ascending"] = 1] = "Ascending";
                ColumnOrder[ColumnOrder["Descending"] = 2] = "Descending";
            })(ColumnOrder = Components.ColumnOrder || (Components.ColumnOrder = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class GridHeader extends Sol.Control {
                constructor(model) {
                    var _a;
                    super("th");
                    this._sortOrder = Components.ColumnOrder.NotSet;
                    this.sortable = false;
                    this.columnInfo = model;
                    this.propertyName = model.PropertyName;
                    this.sortProperty = model.OrderingPropertyName;
                    this.tip = model.ColumnTip;
                    var fixedWidthTypes = {};
                    fixedWidthTypes["SDateTime"] = 130;
                    fixedWidthTypes["SDate"] = 130;
                    fixedWidthTypes["SNumber"] = 130;
                    fixedWidthTypes["SPercent"] = 120;
                    fixedWidthTypes["SMoney"] = 122;
                    fixedWidthTypes["SBoolean"] = 50;
                    fixedWidthTypes["SIdentity"] = 90;
                    fixedWidthTypes["SInteger"] = 90;
                    if (fixedWidthTypes[model.DataType])
                        this.ancho = fixedWidthTypes[model.DataType];
                    this.setColumnWidth(model.Width || ((_a = model.EditorModel) === null || _a === void 0 ? void 0 : _a.Width));
                    if (model.Alignment == Sol.Alignment.Left)
                        this.estilos.agregar("text-align", "left");
                    if (model.ShowTitle) {
                        if (model.DataType == "SBoolean" && !!model.EditorModel) {
                            this.selectAllCheck = new Sol.Check();
                            this.selectAllCheck.caption = model.Title;
                            this.selectAllCheck.onValueModified.subscribe(() => this.onSelectAll());
                            this.add(this.selectAllCheck);
                        }
                        else if (model.Title && model.Title[0] == "&")
                            this.drawIcon(model.Title);
                        else
                            this.text = model.Title;
                    }
                    else
                        this.ancho = 25;
                    this.sortable = model.Sortable;
                }
                get selected() { return this.selectAllCheck.checked; }
                get sortOrder() { return this._sortOrder; }
                set sortOrder(valor) {
                    this._sortOrder = valor;
                    this.css.remove("ascendente");
                    this.css.remove("descendiente");
                    if (!this.sortable)
                        return;
                    if (valor == Components.ColumnOrder.Ascending)
                        this.css.add("ascendente");
                    if (valor == Components.ColumnOrder.Descending)
                        this.css.add("descendiente");
                }
                build() {
                    if (this.sortable)
                        this.css.add("ordenable");
                }
                drawIcon(iconCode) {
                    var icon = new Sol.Control("i");
                    icon.text = iconCode;
                    icon.css.add("icono");
                    this.ancho = 25;
                    this.add(icon);
                }
                setColumnWidth(width) {
                    if (!width)
                        return;
                    let value = (width + 18) + "px";
                    this.estilos.definir("width", value);
                    this.estilos.definir("min-width", value);
                    this.estilos.definir("max-width", value);
                }
            }
            Components.GridHeader = GridHeader;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class InputUpload extends Sol.Control {
                    constructor() {
                        super("input");
                        this.tagCerrada = true;
                        this.atributos.agregar("type", "file");
                        this.atributos.agregar("name", "archivos[]");
                        this.estilos.agregar("position", "absolute");
                        this.estilos.agregar("z-index", "999");
                        this.estilos.agregar("cursor", "pointer");
                        this.estilos.agregar("opacity", "0");
                        this.estilos.agregar("height", "26px");
                        this.estilos.agregar("width", "170px");
                    }
                    clear() {
                        this.html.value = "";
                    }
                    build() {
                        super.build();
                        if (this.multiple)
                            this.atributos.agregar("multiple");
                        if (this.accept)
                            this.atributos.agregar("accept", this.accept);
                    }
                }
                Uploads.InputUpload = InputUpload;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class FileSignaturePanel extends Sol.Control {
                    constructor() {
                        super();
                        this.signButton = new Sol.Button();
                        this.askFirsignButton = new Sol.Button();
                        this.signersArea = new Sol.Control("span");
                        this.signError = new Sol.ScreenMessage();
                        this.css.add("sol_file_signature_panel");
                        this.signError.type = Sol.MessageType.Error;
                        this.signError.visible = false;
                        this.add(this.signError);
                        this.signButton.text = Sol.Environment.resources.sign;
                        this.signButton.type = Sol.ButtonType.Link;
                        this.signButton.imageCode = "&#xf00c;";
                        this.signButton.onClick = () => this.sign();
                        this.signButton.visible = false;
                        this.add(this.signButton);
                        this.add(this.signersArea);
                        this.askFirsignButton.text = "Solicitar assinatura";
                        this.askFirsignButton.type = Sol.ButtonType.Link;
                        this.askFirsignButton.imageCode = "&#xf00c;";
                        this.askFirsignButton.onClick = () => this.requestSign();
                        this.askFirsignButton.visible = false;
                        this.add(this.askFirsignButton);
                    }
                    get allowSign() { return this.signButton.visible; }
                    set allowSign(value) { this.signButton.visible = value; }
                    get allowAskForSign() { return this.askFirsignButton.visible; }
                    set allowAskForSign(value) { this.askFirsignButton.visible = value; }
                    setSigners(signers) {
                        this.signersArea.controls.empty();
                        this.signersArea.controls.addMany(Sol.List.from(signers).select(signer => {
                            const signerControl = new Sol.Control("span");
                            signerControl.css.add("sol_file_signature_panel_signer");
                            signerControl.text = "Assinado por " + signer.SignerName;
                            signerControl.data = signer;
                            signerControl.tip = "Clique para baixar o protocolo de assinatura";
                            signerControl.onClick = () => this.downloadProtocol(signer.SignID);
                            return signerControl;
                        }));
                    }
                    requestSign() {
                        this.signError.visible = false;
                        if (!confirm("Confirma a solicitação de assinatura ao contratado?"))
                            return;
                        const data = { fileID: this.uploadItem.code, contractID: this.uploadItem.myUpload.code };
                        Web.System.exec("vvasleos", "RequestSign", data, e => {
                            if (e.Fail) {
                                this.signError.text = e.ErrorMessage;
                                this.signError.visible = true;
                            }
                            else
                                alert("Solicitação enviada com sucesso");
                        });
                    }
                    downloadProtocol(signatureID) {
                        this.signError.visible = false;
                        Web.System.exec("qoeaslska", "GetProtocol", { signatureID: signatureID }, e => window.open(e.FileLink, "_blank"));
                    }
                    sign() {
                        this.signError.visible = false;
                        var doSingleModel = {
                            className: this.uploadItem.myUpload.className,
                            methodName: "Sign",
                            id: 0,
                            inputs: [{ Campo: "Identifier", Valor: this.uploadItem.identificador }]
                        };
                        Web.System.exec("79k8j542h", "DoSingle", doSingleModel, e => {
                            if (e.Fail) {
                                this.signError.text = e.ErrorMessage;
                                this.signError.visible = true;
                                return;
                            }
                            if (e.NoCertificateUploaded) {
                                const dialog = new Uploads.FileSignerHelpDialog();
                                dialog.fileID = this.uploadItem.code;
                                dialog.show();
                                this.add(dialog);
                                return;
                            }
                            this.uploadItem.myUpload.createItem(e.NewFileModel);
                            this.uploadItem.myUpload.updateSignInfo();
                        }, null);
                    }
                }
                Uploads.FileSignaturePanel = FileSignaturePanel;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class UploadItemBase extends Sol.Control {
                    constructor() {
                        super();
                        this.css.add("sol_upload_item");
                        this.onDragEnter = (ctr, e) => {
                            this.css.add("sol_upload_folder_drag");
                            e.preventDefault();
                        };
                        this.onDragLeave = () => this.css.remove("sol_upload_folder_drag");
                        this.onDragOver = (ctr, e) => this.itemDragOver(e);
                        this.onDrop = (ctr, e) => this.itemDrop(e);
                        this.onDragStart = (ctr, e) => {
                            if (this.blocked) {
                                e.preventDefault();
                                return false;
                            }
                            e.dataTransfer.setData("upload_item", this.id);
                        };
                    }
                    get selected() { return this._selected; }
                    set selected(value) {
                        this._selected = value;
                        if (value)
                            this.css.add("sol_upload_item_selected");
                        else
                            this.css.remove("sol_upload_item_selected");
                    }
                    updatePath() {
                        var fld = this.folder;
                        var nodes = new Sol.List();
                        while (!!fld) {
                            nodes.add(fld.itemName);
                            fld = fld.folder;
                        }
                        this.path = nodes.reverse().join("¨");
                        this.updateIndent();
                    }
                    updateIndent() {
                        this.estilos.definir("margin-left", !this.path ? "0px" : this.path.split("¨").length * 20 + "px");
                    }
                    itemDragOver(e) {
                        e.preventDefault();
                    }
                    itemDrop(e) {
                        var draggedID = e.dataTransfer.getData("upload_item");
                        if (!draggedID)
                            return;
                        e.preventDefault();
                        this.css.remove("sol_upload_folder_drag");
                        e.stopPropagation();
                        if (this.onItemDrop)
                            this.onItemDrop(this, draggedID);
                    }
                }
                Uploads.UploadItemBase = UploadItemBase;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class ExpirationPanel extends Sol.Control {
                    constructor() {
                        super("span");
                        this.dateDisplay = new Sol.Control("span");
                        this.dateField = new Sol.DateField();
                        this.resetButton = new Sol.Button();
                        this.saveButton = new Sol.Button();
                        this.startButton = new Sol.Button();
                        this.statusDisplay = new Sol.Control("span");
                        this._dateValue = null;
                        this.startButton.type = Sol.ButtonType.Link;
                        this.startButton.text = Sol.Environment.resources.setExpiration;
                        this.startButton.css.add("sol_upload_expiration");
                        this.startButton.onClick = () => this.showField();
                        this.add(this.startButton);
                        this.dateField.visible = false;
                        this.dateField.onKeyDown = e => this.fieldKeyDown(e);
                        this.add(this.dateField);
                        this.saveButton.imageCode = "&#xf0c7;";
                        this.saveButton.visible = false;
                        this.saveButton.css.add("sol_upload_save_expiration");
                        this.saveButton.onClick = () => this.saveDate();
                        this.add(this.saveButton);
                        this.dateDisplay.css.add("sol_upload_expiration");
                        this.dateDisplay.visible = false;
                        this.add(this.dateDisplay);
                        this.resetButton.text = "x";
                        this.resetButton.type = Sol.ButtonType.Custom;
                        this.resetButton.css.add("sol_upload_reset_expiration");
                        this.resetButton.visible = false;
                        this.resetButton.onClick = () => this.resetDate();
                        this.add(this.resetButton);
                        this.statusDisplay.visible = false;
                        this.add(this.statusDisplay);
                    }
                    get dateValue() { return this._dateValue; }
                    set dateValue(value) {
                        this._dateValue = value;
                        if (value) {
                            this.date = new Date(value + "T00:00");
                            this.showDate();
                        }
                    }
                    fieldKeyDown(e) {
                        if (e.key === "Escape") {
                            this.dateField.visible = false;
                            this.saveButton.visible = false;
                        }
                        if (e.key === "Enter")
                            this.saveDate();
                    }
                    resetDate() {
                        this.date = null;
                        this._dateValue = null;
                        this.startButton.visible = true;
                        this.dateDisplay.visible = false;
                        this.resetButton.visible = false;
                        this.statusDisplay.visible = false;
                    }
                    showDate() {
                        this.startButton.visible = false;
                        this.dateField.visible = false;
                        this.saveButton.visible = false;
                        this.dateDisplay.visible = true;
                        this.dateDisplay.text = this.date.formatearLocal();
                        this.resetButton.visible = true;
                        this.statusDisplay.css.empty();
                        this.statusDisplay.visible = true;
                        if (this.date.addDays(1) <= new Date()) {
                            this.statusDisplay.text = Sol.Environment.resources.statusExpired;
                            this.statusDisplay.css.add("sol_upload_status_expired");
                        }
                        else if (this.date < new Date().addDays(15)) {
                            this.statusDisplay.text = Sol.Environment.resources.statusExpiring;
                            this.statusDisplay.css.add("sol_upload_status_expiring");
                        }
                        else {
                            this.statusDisplay.text = Sol.Environment.resources.statusOnForce;
                            this.statusDisplay.css.add("sol_upload_status_onforce");
                        }
                    }
                    showField() {
                        this.dateField.visible = true;
                        this.saveButton.visible = true;
                        this.dateField.foco();
                    }
                    saveDate() {
                        if (this.dateField.isEmpty()) {
                            alert(Sol.Environment.resources.schedule_field_date_error);
                            return;
                        }
                        this._dateValue = this.dateField.value;
                        this.date = this.dateField.dateValue;
                        this.showDate();
                        this.onChange();
                    }
                }
                Uploads.ExpirationPanel = ExpirationPanel;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class UploadItem extends Uploads.UploadItemBase {
                    constructor() {
                        super();
                        this.numberLabel = new Sol.Control("span");
                        this.nameLabel = new Sol.Control("span");
                        this.sizeLabel = new Sol.Control("span");
                        this.deleteButton = new Sol.Control("span");
                        this.descriptionField = new Sol.Field();
                        this.expirationPanel = new Uploads.ExpirationPanel();
                        this.documentNumberField = new Sol.Field();
                        this.documentTypeCombo = new Components.DataCombo();
                        this.failMessage = new Sol.Control();
                        this.request = new XMLHttpRequest();
                        this.uploadLabel = new Sol.Control("span");
                        this.userLabel = new Sol.Control("span");
                        this.dateLabel = new Sol.DateTimeField();
                        this.progressBar = new Sol.ProgressBar();
                        this.thumbnail = new Sol.ImageBox();
                        this.code = 0;
                        this.isDone = false;
                        this.canDelete = false;
                        this.showDescription = true;
                        this.showFileSize = false;
                        this.signaturePanel = new Uploads.FileSignaturePanel();
                        this.numberLabel.css.add("sol_upload_number");
                        this.numberLabel.visible = false;
                        this.uploadLabel.css.add("sol_upload_checklist");
                        this.uploadLabel.text = Sol.Environment.resources.upload_checkitem;
                        this.uploadLabel.visible = false;
                        this.nameLabel.add(this.progressBar);
                        this.nameLabel.css.add("sol_upload_archivo");
                        this.nameLabel.onClick = () => this.download();
                        this.failMessage.text = Sol.Environment.resources.file_error;
                        this.failMessage.visible = false;
                        this.failMessage.css.add("sol_upload_error");
                        this.thumbnail.css.add("sol_upload_thumbnail");
                        this.documentTypeCombo.onChange = () => false;
                        this.documentTypeCombo.css.add("sol_upload_doc_type");
                        this.documentTypeCombo.className = "Solarium.DocumentType, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.documentNumberField.css.add("sol_upload_doc_number");
                        this.documentNumberField.maxLength = 25;
                        this.descriptionField.autoWidth = false;
                        this.descriptionField.maxLength = 255;
                        this.descriptionField.placeHolder = Sol.Environment.resources.file_description;
                        this.descriptionField.css.add("sol_upload_description");
                        this.descriptionField.onChange = () => this.save();
                        this.userLabel.visible = false;
                        this.userLabel.css.add("sol_upload_user");
                        this.dateLabel.visible = false;
                        this.dateLabel.readonly = true;
                        this.dateLabel.css.add("sol_upload_date");
                        this.sizeLabel.css.add("sol_upload_tamano");
                        this.deleteButton.text = "x";
                        this.deleteButton.ancho = 12;
                        this.deleteButton.css.add("sol_upload_eliminar");
                        this.deleteButton.onClick = () => this.delete();
                        this.expirationPanel.onChange = () => this.save();
                        this.signaturePanel.uploadItem = this;
                        this.signaturePanel.visible = false;
                        this.request.onreadystatechange = () => this.uploadCompleted();
                        (this.request.upload).me = this;
                        this.request.upload.onprogress = e => this.reportProgress(e);
                        this.request.onprogress = e => this.reportProgress(e);
                    }
                    get autoSave() {
                        return this.myUpload &&
                            this.myUpload.autoSave &&
                            !this.myUpload.singleFile &&
                            !!this.myUpload.code;
                    }
                    get isImage() {
                        var imageExtensions = [".png", ".jpg", ".jpeg", ".gif", ".tiff", ".tif", ".webp", ".bmp"];
                        return imageExtensions.indexOf(this.extension) > -1;
                    }
                    get isChecklistItem() { return this._isChecklistItem; }
                    set isChecklistItem(value) {
                        this._isChecklistItem = value;
                        this.uploadLabel.visible = value && !this.extension;
                    }
                    get date() { return this.dateLabel.text; }
                    set date(s) {
                        var _a;
                        this.dateLabel.value = s;
                        this.dateLabel.visible = !!s && ((_a = this.myUpload) === null || _a === void 0 ? void 0 : _a.showUploadDate);
                    }
                    get description() { return this.descriptionField.textValue; }
                    set description(s) { this.descriptionField.textValue = s; }
                    get downloadUrl() { var _a; return this.link || (((_a = this.myUpload) === null || _a === void 0 ? void 0 : _a.customDownloadUrl) || Sol.Environment.filePath) + this.identificador; }
                    get fail() { return this.failMessage.visible; }
                    set fail(v) { this.failMessage.visible = v; }
                    get itemName() { return this.nameLabel.text; }
                    set itemName(valor) { this.nameLabel.text = valor; }
                    get number() { return this._number; }
                    set number(value) {
                        this._number = value;
                        this.numberLabel.text = (value < 9 ? "0" : "") + value.toString() + '.';
                    }
                    get showNumber() { return this.numberLabel.visible; }
                    set showNumber(value) { this.numberLabel.visible = value; }
                    get tamano() { return this._tamano; }
                    set tamano(value) {
                        this._tamano = value;
                        this.sizeLabel.text = Sol.NumberEx.filesizeToString(value);
                        this.sizeLabel.visible = value > 0;
                    }
                    get url() { return Sol.Environment.filePath + this.identificador; }
                    get userName() { return this.userLabel.text; }
                    set userName(s) {
                        var _a;
                        this.userLabel.text = s;
                        this.userLabel.visible = !!s && ((_a = this.myUpload) === null || _a === void 0 ? void 0 : _a.showUser);
                    }
                    get objectValue() {
                        return {
                            ID: this.code,
                            Extensión: this.extension,
                            Nombre: this.itemName,
                            Description: this.description,
                            ExternalLink: this.link,
                            Identificador: this.identificador,
                            Tamaño: this.tamano,
                            ExpirationDate: this.expirationPanel.dateValue,
                            FolderPath: this.path,
                            IsChecklistItem: this.isChecklistItem,
                            DocumentType: parseInt(this.documentTypeCombo.selectedCode),
                            DocumentNumber: this.documentNumberField.value,
                            Blocked: this.blocked
                        };
                    }
                    set objectValue(value) {
                        var _a;
                        this.code = value.ID;
                        this.extension = value.Extensión;
                        this.itemName = value.Nombre;
                        this.description = value.Description;
                        this.identificador = value.Identificador;
                        this.tamano = value.Tamaño;
                        this.expirationPanel.dateValue = value.ExpirationDate;
                        if (value.UserName)
                            this.userName = value.UserName;
                        if (value.Creación)
                            this.date = value.Creación;
                        this.path = value.FolderPath;
                        this.link = value.ExternalLink;
                        this.isChecklistItem = value.IsChecklistItem;
                        this.documentTypeCombo.selectedCode = (_a = value.DocumentType) === null || _a === void 0 ? void 0 : _a.toString();
                        this.documentNumberField.value = value.DocumentNumber;
                        this.blocked = value.Blocked;
                    }
                    get valor() {
                        return Sol.List.from(this.toDatumModel());
                    }
                    set valor(v) {
                        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
                        this.code = v.that(i => i.Campo == "ID").Valor;
                        this.extension = v.that(i => i.Campo == "Extensión").Valor;
                        this.itemName = v.that(i => i.Campo == "Nombre").Valor;
                        this.description = v.that(i => i.Campo == "Description").Valor;
                        this.identificador = v.that(i => i.Campo == "Identificador").Valor;
                        this.tamano = v.that(i => i.Campo == "Tamaño").Valor;
                        this.link = (_a = v.that(i => i.Campo == "ExternalLink")) === null || _a === void 0 ? void 0 : _a.Valor;
                        this.userName = (_b = v.that(i => i.Campo == "FileEntityName")) === null || _b === void 0 ? void 0 : _b.Valor;
                        this.date = v.that(i => i.Campo == "Creación").Valor;
                        this.expirationPanel.dateValue = (_c = v.that(i => i.Campo == "ExpirationDate")) === null || _c === void 0 ? void 0 : _c.Valor;
                        this.isChecklistItem = (_d = v.that(i => i.Campo == "isChecklistItem")) === null || _d === void 0 ? void 0 : _d.Valor;
                        this.documentTypeCombo.selectedCode = (_e = v.that(i => i.Campo == "DocumentType")) === null || _e === void 0 ? void 0 : _e.Valor;
                        this.documentNumberField.value = (_f = v.that(i => i.Campo == "DocumentNumber")) === null || _f === void 0 ? void 0 : _f.Valor;
                        this.isChecklistItem = (_g = v.that(i => i.Campo == "isChecklistItem")) === null || _g === void 0 ? void 0 : _g.Valor;
                        this.path = (_h = v.that(i => i.Campo == "FolderPath")) === null || _h === void 0 ? void 0 : _h.Valor;
                        this.blocked = (_j = v.that(i => i.Campo == "Blocked")) === null || _j === void 0 ? void 0 : _j.Valor;
                        this.showThumbnail();
                    }
                    hideProgressBar() { this.progressBar.visible = false; }
                    isChildOf(folder) {
                        if (this.folder == folder)
                            return true;
                        var parentFolder = this.folder;
                        while (!!parentFolder) {
                            if (parentFolder == folder)
                                return true;
                            parentFolder = parentFolder.folder;
                        }
                        return false;
                    }
                    process(uploadPath = Sol.Environment.uploadPath) {
                        this.isDone = false;
                        var formData = new FormData();
                        formData.append("archivo", this.file);
                        if (this.autoSave) {
                            formData.append("className", this.myUpload.contextClassName);
                            formData.append("propertyName", this.myUpload.propertyName);
                            formData.append("code", this.myUpload.code.toString());
                        }
                        this.request.open("POST", uploadPath);
                        this.request.send(formData);
                    }
                    toDatumModel() {
                        return [
                            { Campo: "ID", Valor: this.code || 0 },
                            { Campo: "Extensión", Valor: this.extension },
                            { Campo: "Nombre", Valor: this.itemName },
                            { Campo: "Description", Valor: this.description },
                            { Campo: "Identificador", Valor: this.identificador },
                            { Campo: "Tamaño", Valor: this.tamano },
                            { Campo: "ExpirationDate", Valor: this.expirationPanel.dateValue },
                            { Campo: "ExternalLink", Valor: this.link },
                            { Campo: "DocumentType", Valor: this.documentTypeCombo.selectedCode },
                            { Campo: "DocumentNumber", Valor: this.documentNumberField.value },
                            { Campo: "IsChecklistItem", Valor: this.isChecklistItem },
                            { Campo: "Creación", Valor: this.date },
                            { Campo: "IsFolder", Valor: false },
                            { Campo: "FolderPath", Valor: this.path },
                            { Campo: "Blocked", Valor: this.blocked }
                        ];
                    }
                    build() {
                        this.add(this.thumbnail);
                        this.add(this.numberLabel);
                        this.add(this.uploadLabel);
                        this.add(this.nameLabel);
                        this.add(this.deleteButton);
                        if (this.showFileSize)
                            this.add(this.sizeLabel);
                        const emptyControl = new Sol.Control();
                        emptyControl.estilos.agregar("clear", "both");
                        this.add(emptyControl);
                        this.add(this.failMessage);
                        const extraFields = new Sol.Control();
                        extraFields.css.add("sol_upload_extrafields");
                        if (this.myUpload.showDocumentType) {
                            this.documentTypeCombo.readonly = this.readonly;
                            this.documentTypeCombo.filters.add(this.myUpload.documentTypeKey ? { PropertyName: "TargetKey", FilterType: "SText", FilterValue: this.myUpload.documentTypeKey } :
                                { PropertyName: "OnlyGeneralTypes", FilterType: "SBoolean", FilterValue: true });
                            extraFields.addCtr("Tipo:", "span");
                            extraFields.add(this.documentTypeCombo);
                            this.documentTypeCombo.refresh();
                        }
                        if (this.myUpload.showDocumentNumber) {
                            this.documentNumberField.readonly = this.readonly;
                            extraFields.addCtr(this.myUpload.documentNumberCaption + ':', "span");
                            extraFields.add(this.documentNumberField);
                        }
                        this.descriptionField.readonly = this.readonly;
                        if (this.showDescription)
                            extraFields.add(this.descriptionField);
                        if (extraFields.controls.hasItems())
                            this.add(extraFields);
                        this.add(this.userLabel);
                        this.add(this.dateLabel);
                        if (this.expirable)
                            this.add(this.expirationPanel);
                        if (this.extension == ".pdf" || this.itemName.indexOf(".pdf") > 1)
                            this.add(this.signaturePanel);
                        this.deleteButton.visible = this.canDelete && !this.blocked;
                        super.build();
                    }
                    reportProgress(e) {
                        this.progressBar.valor = Math.ceil((e.loaded / e.total) * 100);
                    }
                    uploadCompleted() {
                        var _a, _b;
                        if (this.request.readyState !== 4)
                            return;
                        try {
                            this.isDone = true;
                            this.uploadLabel.visible = false;
                            this.deleteButton.transparent = false;
                            this.progressBar.visible = false;
                            var model = JSON.parse(this.request.response);
                            if (model.Fail)
                                this.fail = true;
                            else {
                                this.code = this.code || model.ID;
                                this.identificador = model.Identifier;
                                this.tamano = model.Size;
                                this.extension = model.Extension;
                                (_a = this.myUpload) === null || _a === void 0 ? void 0 : _a.saveNewFile(this);
                                this.showThumbnail();
                                if (model.ID && Web.System.screens.currentScreen instanceof Web.Screens.DetailsScreen)
                                    Web.System.screens.currentScreen.lastUpdate = null;
                                if (this.onUploadComplete)
                                    this.onUploadComplete(this);
                                if (this.file.onUploadComplete)
                                    this.file.onUploadComplete(this);
                                if ((_b = this.myUpload) === null || _b === void 0 ? void 0 : _b.onItemAdded)
                                    this.myUpload.onItemAdded(this);
                                if (model.SavingTime)
                                    Web.System.screens.currentDetails.lastUpdate = model.SavingTime;
                            }
                        }
                        catch (_c) {
                            this.fail = true;
                        }
                    }
                    delete() {
                        var _a, _b;
                        if (this.readonly)
                            return;
                        (_a = this.myUpload) === null || _a === void 0 ? void 0 : _a.mainList.controls.remove(this);
                        (_b = this.myUpload) === null || _b === void 0 ? void 0 : _b.updateToolbox();
                        if (this.onDelete)
                            this.onDelete(this);
                    }
                    download() {
                        var _a, _b;
                        if (!this.isDone || this.fail)
                            return;
                        if ((_b = (_a = this.myUpload) === null || _a === void 0 ? void 0 : _a.onDownload) === null || _b === void 0 ? void 0 : _b.call(this, this))
                            return;
                        if (this.isChecklistItem && !this.identificador) {
                            this.myUpload.targetUploadItem = this;
                            this.myUpload.startUpload();
                            return;
                        }
                        window.open(this.downloadUrl);
                    }
                    showThumbnail() {
                        var _a;
                        if (!this.isImage || !((_a = this.myUpload) === null || _a === void 0 ? void 0 : _a.showThumbnails))
                            return;
                        this.css.add("sol_upload_item_thumb");
                        this.thumbnail.source = Sol.Environment.filePath + this.identificador;
                    }
                    save() {
                        var _a;
                        if (!this.code || !this.autoSave)
                            return;
                        const saveData = {
                            className: (_a = this.myUpload) === null || _a === void 0 ? void 0 : _a.className,
                            id: this.code,
                            data: [{ Campo: "Description", Valor: this.descriptionField.value },
                                { Campo: "ExpirationDate", Valor: this.expirationPanel.dateValue }],
                            lastUpdate: null
                        };
                        Web.System.exec("3b5v9v45", "Save", saveData, e => Web.System.screens.currentDetails.lastUpdate = e.SavingTime);
                    }
                }
                Uploads.UploadItem = UploadItem;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class FolderItem extends Uploads.UploadItemBase {
                    constructor() {
                        super();
                        this.nameField = new Sol.Field();
                        this.fileCountDisplay = new Sol.Control("span");
                        this.code = 0;
                        this._closed = true;
                        this.css.add("sol_upload_folder");
                        this.nameField.disableEnter = true;
                        this.nameField.autoResize = true;
                        this.nameField.autoWidth = false;
                        this.nameField.maxLength = 255;
                        this.nameField.onKeyDown = e => this.fieldKeyDown(e);
                        this.nameField.onLeave.subscribe(() => this.commitName());
                        this.add(this.nameField);
                        this.fileCountDisplay.css.add("sol_upload_folder_count");
                        this.add(this.fileCountDisplay);
                        this.draggable = true;
                        this.editable = false;
                        this.closed = true;
                    }
                    get closed() { return this._closed; }
                    set closed(value) {
                        this._closed = value;
                        this.css.add(value ? "sol_upload_folder_closed" : "sol_upload_folder_open");
                        this.css.remove(value ? "sol_upload_folder_open" : "sol_upload_folder_closed");
                    }
                    get editable() { return this._editable; }
                    set editable(value) {
                        this._editable = value;
                        this.nameField.readonly = !value;
                        if (value)
                            this.focus();
                    }
                    get fileCount() { return this._fileCount; }
                    set fileCount(value) {
                        this._fileCount = value;
                        this.fileCountDisplay.text = !value ? "" : '(' + value + ')';
                    }
                    get itemName() { return this.nameField.value; }
                    set itemName(value) { this.nameField.value = value; }
                    get value() {
                        return Sol.List.from([
                            { Campo: "ID", Valor: this.code },
                            { Campo: "Nombre", Valor: this.folderModel.Nombre },
                            { Campo: "IsFolder", Valor: true },
                            { Campo: "FolderPath", Valor: this.path },
                            { Campo: "Blocked", Valor: this.blocked }
                        ]);
                    }
                    set value(v) {
                        var _a;
                        this.folderModel = {
                            ID: v.that(i => i.Campo == "ID").Valor,
                            Nombre: v.that(i => i.Campo == "Nombre").Valor,
                            FolderPath: v.that(i => i.Campo == "FolderPath").Valor,
                            Blocked: (_a = v.that(i => i.Campo == "Blocked")) === null || _a === void 0 ? void 0 : _a.Valor,
                            IsFolder: true
                        };
                        this.code = this.folderModel.ID;
                        this.itemName = this.folderModel.Nombre;
                    }
                    get objectValue() { return this.folderModel; }
                    set objectValue(value) {
                        this.folderModel = value;
                        this.itemName = value.Nombre;
                        this.path = value.FolderPath;
                    }
                    isChildOf(folder) {
                        if (this == folder)
                            return true;
                        var parentFolder = this.folder;
                        while (!!parentFolder) {
                            if (parentFolder == folder)
                                return true;
                            parentFolder = parentFolder.folder;
                        }
                        return false;
                    }
                    cancelEdit() {
                        this.itemName = this.folderModel.Nombre;
                        this.editable = false;
                    }
                    commitName() {
                        if (!this.itemName) {
                            this.cancelEdit();
                            return;
                        }
                        var itemName = this.itemName;
                        var name = itemName;
                        var counter = 1;
                        while (this.myUpload.folders.any(fld => fld.folder == this.folder && fld != this && fld.itemName == itemName))
                            itemName = name + ' ' + ++counter;
                        this.itemName = itemName;
                        this.folderModel.Nombre = itemName;
                        this.editable = false;
                        this.onFolderRenamed();
                    }
                    fieldKeyDown(e) {
                        if (e.key === "Escape")
                            this.cancelEdit();
                        if (e.key === "Enter")
                            this.commitName();
                    }
                    focus() {
                        this.nameField.foco();
                        this.nameField.selectAllText();
                    }
                }
                Uploads.FolderItem = FolderItem;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class ChecklistButton extends Sol.Button {
                    constructor() {
                        super();
                        this.CHECKLIST_CLASS = "Solarium.Checklist, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.imageCode = "&#xf03a;";
                        this.subitems.add(Sol.Control.create(Sol.Environment.resources.cargando, null, "li"));
                    }
                    meClick() {
                        super.meClick();
                        if (this.isLoaded)
                            return;
                        var datos = {
                            className: this.CHECKLIST_CLASS,
                            currentPage: 1,
                            rowCount: 20,
                            filters: [],
                            sortProperty: "Nombre",
                            sortOrder: Web.Ordering.ascending,
                            properties: ["ID", "Nombre"],
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", datos, model => {
                            this.popup.controls.empty();
                            for (var i = 0; i < model.Codes.length; i++) {
                                const rowData = Sol.List.from(model.Data[i]);
                                const item = new Sol.Control("li");
                                item.data = model.Codes[i];
                                item.text = rowData.that(cmp => cmp.Campo == "Nombre").Valor;
                                item.onClick = () => {
                                    this.popup.visible = false;
                                    this.addCheckList(item.data);
                                };
                                this.popup.add(item);
                            }
                            if (!this.popup.controls.hasItems())
                                this.addCtr(Sol.Environment.resources.no_encontrado, null, "li");
                        });
                    }
                    addCheckList(code) {
                        const request = {
                            className: this.CHECKLIST_CLASS,
                            code: code,
                            subtype: false
                        };
                        Web.System.exec("sn9d23vs7d", "Load", request, model => {
                            const data = Sol.List.from(model.Data);
                            const folder = this.myUpload.createFolder(data.that(d => d.Campo == "Nombre").Valor);
                            const items = Sol.List.from(data.that(d => d.Campo == "ChecklistItems").Valor);
                            items.forEach(ph => {
                                const itemData = Sol.List.from(ph);
                                const item = this.myUpload.createItem({
                                    ID: 0,
                                    Nombre: itemData.that(d => d.Campo == "Nombre").Valor,
                                    Description: itemData.that(d => d.Campo == "Description").Valor
                                });
                                item.isChecklistItem = true;
                                item.hideProgressBar();
                                item.isDone = true;
                                if (folder)
                                    this.myUpload.moveItemToFolder(item, folder, true);
                            });
                        });
                    }
                }
                Uploads.ChecklistButton = ChecklistButton;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class Upload extends Sol.Control {
                    constructor() {
                        super(...arguments);
                        this.checklistButton = new Uploads.ChecklistButton();
                        this.createFolderButton = new Sol.Button();
                        this.deleteAllButton = new Sol.Button();
                        this.deleteFolderButton = new Sol.Button();
                        this.deleteHeader = new Sol.Control("th");
                        this.emptyMessage = new Sol.Control();
                        this.fileButton = new Sol.Button();
                        this.mainList = new Sol.Control();
                        this.newFileButton = new Sol.Button();
                        this.numbersButton = new Sol.Button();
                        this.renameFolderButton = new Sol.Button();
                        this.selectAllButton = new Sol.Button();
                        this.toolbar = new Sol.Control();
                        this.downloadButton = new Sol.Button();
                        this.autoSave = true;
                        this.isComplex = true;
                        this.showUploadDate = true;
                        this.showDescription = true;
                        this.showFileSize = false;
                        this.showUser = true;
                        this.toControl = () => this;
                        this.showThumbnails = true;
                        this.isEmpty = () => !this.files.hasItems();
                    }
                    get selectedFolder() {
                        const selectedItem = this.selectedItem;
                        return selectedItem instanceof Uploads.FolderItem ? selectedItem : selectedItem === null || selectedItem === void 0 ? void 0 : selectedItem.folder;
                    }
                    get selectedItem() {
                        return this.items.that(i => i.selected);
                    }
                    get folders() {
                        return this.mainList
                            .controls
                            .where(ctr => ctr instanceof Uploads.FolderItem)
                            .cast();
                    }
                    get files() {
                        return this.mainList
                            .controls
                            .where(ctr => ctr instanceof Uploads.UploadItem)
                            .cast()
                            .where(ui => !ui.fail);
                    }
                    get items() {
                        return this.mainList
                            .controls
                            .where(ctr => ctr instanceof Uploads.UploadItemBase)
                            .cast();
                    }
                    get isUploading() { return this.files.any(item => !item.isDone); }
                    get showDownloadButton() { return this.downloadButton.visible; }
                    set showDownloadButton(value) { this.downloadButton.visible = value; }
                    get showToolbar() { return this.toolbar.visible; }
                    set showToolbar(value) { this.toolbar.visible = value; }
                    get identificadores() { return this.files.select(item => item.identificador).toArray(); }
                    get selectedFiles() { return this.files.where(item => item.selected == true); }
                    get readonly() {
                        return this._readonly;
                    }
                    set readonly(value) {
                        this._readonly = value;
                        if (this.inputFile)
                            this.inputFile.visible = !value || this.collaborativeMode;
                        this.newFileButton.visible = !value || this.collaborativeMode;
                        this.createFolderButton.visible = !value;
                        this.renameFolderButton.visible = !value;
                        this.deleteFolderButton.visible = !value;
                        this.fileButton.visible = !value || this.collaborativeMode;
                        this.deleteHeader.visible = !value;
                        this.deleteAllButton.visible = !value;
                        this.selectAllButton.visible = !value;
                        if (value)
                            this.css.add("sol_upload_readonly");
                        else
                            this.css.remove("sol_upload_readonly");
                    }
                    get value() {
                        if (this.singleFile)
                            return this.files.hasItems() ? this.files.first().objectValue : null;
                        else
                            return this.files.select(item => item.toDatumModel()).union(this.folders.select(fld => fld.value.toArray()).toArray()).toArray();
                    }
                    set value(v) {
                        var _a;
                        this.clear();
                        if (this.singleFile) {
                            if (!v || !v.ID)
                                return;
                            this.createItem(v);
                        }
                        else {
                            this.models = Sol.List.from(v).select(item => this.convertData(Sol.List.from(item)));
                            this.buildFolder("");
                            this.updateFileCount();
                        }
                        (_a = this.onValueSet) === null || _a === void 0 ? void 0 : _a.apply(this);
                    }
                    addToToolbar(control) { this.toolbar.add(control); }
                    clear() {
                        this.mainList.controls.empty();
                        this.emptyMessage.show();
                    }
                    ;
                    clearFileIds() {
                        this.files.forEach(i => i.code = 0);
                    }
                    createFolder(name = null) {
                        var folderName = name || Sol.Environment.resources.createFolder;
                        var nameIndex = 1;
                        const baseFolder = this.selectedFolder;
                        if (baseFolder === null || baseFolder === void 0 ? void 0 : baseFolder.closed)
                            this.toggleFolderState(baseFolder);
                        while (this.folders.any(i => i.itemName === folderName && i.folder == baseFolder))
                            folderName = Sol.Environment.resources.createFolder + ' ' + ++nameIndex;
                        const model = {
                            ID: 0,
                            IsFolder: true,
                            Nombre: folderName
                        };
                        const folder = this.createItem(model);
                        if (baseFolder)
                            this.moveItemToFolder(folder, baseFolder, true);
                        folder.editable = !name;
                        this.saveNewFolder(folder);
                        return folder;
                    }
                    createItem(data) {
                        var item;
                        if (data.IsFolder) {
                            const folderItem = new Uploads.FolderItem();
                            folderItem.code = data.ID;
                            folderItem.myUpload = this;
                            folderItem.objectValue = data;
                            folderItem.blocked = data.Blocked;
                            folderItem.onItemDrop = (fld, id) => this.itemDragged(fld, id);
                            folderItem.onClick = () => this.itemClicked(item);
                            folderItem.onFolderRenamed = () => this.save();
                            this.mainList.add(folderItem);
                            item = folderItem;
                        }
                        else {
                            const uploadItem = new Uploads.UploadItem();
                            uploadItem.myUpload = this;
                            uploadItem.objectValue = data;
                            uploadItem.canDelete = true;
                            uploadItem.hideProgressBar();
                            uploadItem.isDone = true;
                            uploadItem.readonly = this.readonly &&
                                (!this.collaborativeMode || Sol.Environment.credential.user != data.UserName);
                            uploadItem.showFileSize = this.showFileSize;
                            uploadItem.showDescription = this.showDescription;
                            uploadItem.link = data.ExternalLink;
                            uploadItem.expirable = this.allowScheduleExpiration;
                            uploadItem.blocked = data.Blocked;
                            uploadItem.onDelete = i => this.itemDeleted(i);
                            uploadItem.draggable = !this.singleFile;
                            uploadItem.onClick = () => this.itemClicked(item);
                            uploadItem.onItemDrop = (i, id) => this.itemDragged(i, id);
                            this.mainList.add(uploadItem);
                            if (this.onInstantiateItem)
                                this.onInstantiateItem(uploadItem);
                            item = uploadItem;
                        }
                        this.emptyMessage.visible = false;
                        this.updateToolbox();
                        item.updateIndent();
                        return item;
                    }
                    moveItemToFolder(item, targetFolder, save) {
                        item.folder = targetFolder;
                        if (targetFolder)
                            targetFolder.html.after(item.html);
                        else
                            this.mainList.html.appendChild(item.html);
                        item.updatePath();
                        this.updateFileCount();
                        if (save)
                            this.save();
                    }
                    startUpload() {
                        const evt = document.createEvent("MouseEvents");
                        evt.initEvent("click", true, false);
                        this.inputFile.html.dispatchEvent(evt);
                    }
                    updateToolbox() {
                        var number = 1;
                        this.files.forEach(i => i.number = number++);
                        this.downloadButton.enabled = this.selectedFiles.hasItems();
                        this.deleteAllButton.enabled = this.selectedFiles.hasItems();
                        this.selectAllButton.enabled = !this.isEmpty();
                    }
                    uploadFiles(files) {
                        if (this.singleFile)
                            this.clear();
                        if (files)
                            for (var item of files) {
                                if (this.targetUploadItem) {
                                    this.targetUploadItem.itemName = item.name;
                                    this.targetUploadItem.file = item;
                                    this.targetUploadItem.userName = Sol.Environment.credential.user;
                                    this.targetUploadItem.showNumber = this.numbersButton.checked;
                                    this.targetUploadItem.process(this.customUploadUrl);
                                    this.targetUploadItem = null;
                                }
                                else {
                                    const uploadItem = new Uploads.UploadItem();
                                    uploadItem.itemName = item.name;
                                    uploadItem.file = item;
                                    uploadItem.myUpload = this;
                                    uploadItem.showFileSize = this.showFileSize;
                                    uploadItem.showDescription = this.showDescription;
                                    uploadItem.userName = Sol.Environment.credential.user;
                                    uploadItem.showNumber = this.numbersButton.checked;
                                    uploadItem.expirable = this.allowScheduleExpiration;
                                    uploadItem.onDelete = i => this.itemDeleted(i);
                                    uploadItem.draggable = !this.singleFile;
                                    uploadItem.onClick = () => this.itemClicked(uploadItem);
                                    uploadItem.onItemDrop = (fld, id) => this.itemDragged(fld, id);
                                    this.addItem(uploadItem, this.selectedFolder);
                                    uploadItem.process(this.customUploadUrl);
                                    if (this.onInstantiateItem)
                                        this.onInstantiateItem(uploadItem);
                                    if (this.onUploadStarted)
                                        this.onUploadStarted(uploadItem);
                                }
                            }
                        this.updateToolbox();
                        this.inputFile.clear();
                        this.emptyMessage.hide();
                    }
                    validate() { return null; }
                    build() {
                        this.css.add("sol_upload");
                        this.css.add("sol_tabla");
                        if (this.singleFile)
                            this.css.add("sol_upload_single_file");
                        else
                            this.initToolbar();
                        this.initList();
                        this.initInput();
                        this.initFileButton();
                        this.configureDrop();
                        this.getPlugins();
                        super.build();
                    }
                    addItem(item, folder = null) {
                        this.mainList.add(item);
                        if (folder)
                            this.moveItemToFolder(item, folder, false);
                        this.updateToolbox();
                        this.saveNewFile(item);
                    }
                    buildFolder(path, folder = null) {
                        const folders = this.models.where(m => m.IsFolder && m.FolderPath == path);
                        const items = this.models.where(m => !m.IsFolder && m.FolderPath == path);
                        folders.forEach(folderModel => {
                            const item = this.createItem(folderModel);
                            item.folder = folder;
                            const subpath = !path ? folderModel.Nombre : path + '¨' + folderModel.Nombre;
                            this.buildFolder(subpath, item);
                            item.visible = !path;
                        });
                        items.forEach(fileModel => {
                            const item = this.createItem(fileModel);
                            item.folder = folder;
                            item.visible = !path;
                        });
                    }
                    configureDrop() {
                        this.mainList.onDragOver = () => false;
                        this.mainList.onDragEnter = () => false;
                        this.mainList.onDragLeave = () => false;
                        this.mainList.onDrop = (i, e) => {
                            var draggedID = e.dataTransfer.getData("upload_item");
                            if (!draggedID)
                                return;
                            e.preventDefault();
                            this.css.remove("sol_upload_folder_drag");
                            e.stopPropagation();
                            this.itemDragged(null, draggedID);
                        };
                    }
                    convertData(v) {
                        var _a, _b, _c, _d, _e, _f, _g;
                        return {
                            ID: v.that(i => i.Campo == "ID").Valor,
                            Extensión: v.that(i => i.Campo == "Extensión").Valor,
                            Nombre: v.that(i => i.Campo == "Nombre").Valor,
                            Description: v.that(i => i.Campo == "Description").Valor,
                            Identificador: v.that(i => i.Campo == "Identificador").Valor,
                            Tamaño: v.that(i => i.Campo == "Tamaño").Valor,
                            ExternalLink: (_a = v.that(i => i.Campo == "ExternalLink")) === null || _a === void 0 ? void 0 : _a.Valor,
                            UserName: (_b = v.that(i => i.Campo == "FileEntityName")) === null || _b === void 0 ? void 0 : _b.Valor,
                            Creación: v.that(i => i.Campo == "Creación").Valor,
                            ExpirationDate: (_c = v.that(i => i.Campo == "ExpirationDate")) === null || _c === void 0 ? void 0 : _c.Valor,
                            IsFolder: v.that(i => i.Campo == "IsFolder").Valor,
                            IsChecklistItem: v.that(i => i.Campo == "IsChecklistItem").Valor,
                            FolderPath: ((_d = v.that(i => i.Campo == "FolderPath")) === null || _d === void 0 ? void 0 : _d.Valor) || "",
                            DocumentType: (_e = v.that(i => i.Campo == "DocumentType")) === null || _e === void 0 ? void 0 : _e.Valor,
                            DocumentNumber: (_f = v.that(i => i.Campo == "DocumentNumber")) === null || _f === void 0 ? void 0 : _f.Valor,
                            Blocked: (_g = v.that(i => i.Campo == "Blocked")) === null || _g === void 0 ? void 0 : _g.Valor
                        };
                    }
                    deleteFolder() {
                        if (!confirm(Sol.Environment.resources.confirmar_operacion +
                            Sol.Environment.resources.deleteFolder.toLowerCase() + '?'))
                            return;
                        let selectedFolder = this.selectedFolder;
                        this.items.where(i => !i.blocked).where(i => i.isChildOf(selectedFolder)).forEachReverse(i => this.mainList.controls.remove(i));
                        this.renameFolderButton.enabled = false;
                        this.deleteFolderButton.enabled = false;
                        this.updateFileCount();
                        this.save();
                    }
                    getItemByID(id) { return this.items.that(i => i.id === id); }
                    getPlugins() {
                        Web.System.exec("pp30123kdhhj", "GetAvailableFilePlugins", null, e => Sol.List.from(e).forEach(p => {
                            let plugin = eval("new " + p.ClassName + "()");
                            plugin.configure(this);
                        }));
                    }
                    initList() {
                        this.emptyMessage.text = Sol.Environment.resources.no_file;
                        this.emptyMessage.css.add("sol_upload_empty");
                        this.add(this.emptyMessage);
                        this.mainList.css.add("sol_upload_list");
                        this.add(this.mainList);
                    }
                    initFileButton() {
                        this.fileButton.text = (this.singleFile ? Sol.Environment.resources.choose_file : Sol.Environment.resources.anadir_item) + "...";
                        this.fileButton.css.add("sol_upload_agregar");
                        this.fileButton.type = Sol.ButtonType.Link;
                        this.fileButton.visible = !this.readonly || this.collaborativeMode;
                        this.add(this.fileButton);
                    }
                    initInput() {
                        this.inputFile = new Uploads.InputUpload();
                        this.inputFile.visible = !this.readonly || this.collaborativeMode;
                        this.inputFile.multiple = !this.singleFile;
                        this.html.onchange = e => this.onInputChange(e);
                        this.add(this.inputFile);
                    }
                    initToolbar() {
                        this.toolbar.css.add("sol_toolbar");
                        this.initNewFileButton();
                        this.initCreateFolderButton();
                        this.initRenameFolderButton();
                        this.initDeleteFolderButton();
                        this.initDownloadButton();
                        this.initDeleteAllButton();
                        this.initSelectAllButton();
                        this.initShowNumbersButton();
                        this.initChecklistButton();
                        this.add(this.toolbar);
                    }
                    initNewFileButton() {
                        this.newFileButton.imageCode = '&#xf067;';
                        this.newFileButton.tip = Sol.Environment.resources.anadir_item;
                        this.newFileButton.estilos.agregar("margin-right", "4px");
                        this.newFileButton.onClick = () => {
                            this.targetUploadItem = null;
                            this.startUpload();
                        };
                        this.toolbar.add(this.newFileButton);
                    }
                    initCreateFolderButton() {
                        this.createFolderButton.imageKey = 'folder_new';
                        this.createFolderButton.tip = Sol.Environment.resources.createFolder;
                        this.createFolderButton.onClick = () => this.createFolder();
                        this.toolbar.add(this.createFolderButton);
                    }
                    initDeleteFolderButton() {
                        this.deleteFolderButton.imageKey = 'folder_delete';
                        this.deleteFolderButton.tip = Sol.Environment.resources.deleteFolder;
                        this.deleteFolderButton.estilos.agregar("margin-right", "4px");
                        this.deleteFolderButton.onClick = () => this.deleteFolder();
                        this.deleteFolderButton.enabled = false;
                        this.toolbar.add(this.deleteFolderButton);
                    }
                    initRenameFolderButton() {
                        this.renameFolderButton.imageKey = 'folder_edit';
                        this.renameFolderButton.tip = Sol.Environment.resources.editFolder;
                        this.renameFolderButton.onClick = () => this.renameFolder();
                        this.renameFolderButton.enabled = false;
                        this.toolbar.add(this.renameFolderButton);
                    }
                    initDownloadButton() {
                        this.downloadButton.imageCode = '&#xf019;';
                        this.downloadButton.tip = Sol.Environment.resources.downloadAll;
                        this.downloadButton.enabled = false;
                        this.downloadButton.onClick = () => this.download();
                        this.toolbar.add(this.downloadButton);
                    }
                    initShowNumbersButton() {
                        this.numbersButton.imageCode = '&#xf162;';
                        this.numbersButton.type = Sol.ButtonType.Alternate;
                        this.numbersButton.tip = Sol.Environment.resources.showNumbers;
                        this.numbersButton.checked = false;
                        this.numbersButton.onChecked = () => {
                            this.updateToolbox();
                            this.files.forEach(i => i.showNumber = this.numbersButton.checked);
                        };
                        this.toolbar.add(this.numbersButton);
                    }
                    initDeleteAllButton() {
                        this.deleteAllButton.imageCode = '&#xf1f8;';
                        this.deleteAllButton.tip = Sol.Environment.resources.deleteAll;
                        this.deleteAllButton.enabled = false;
                        this.deleteAllButton.onClick = () => this.deleteAll();
                        this.toolbar.add(this.deleteAllButton);
                    }
                    deleteAll() {
                        if (!confirm(Sol.Environment.resources.confirmDeleteAll))
                            return;
                        this.mainList.controls.forEachReverse(item => {
                            if (item instanceof Uploads.UploadItem && item.selected)
                                this.mainList.controls.remove(item);
                        });
                        this.emptyMessage.visible = true;
                        this.updateToolbox();
                        this.updateFileCount();
                        this.save();
                    }
                    initSelectAllButton() {
                        this.selectAllButton.imageCode = '&#xf14a;';
                        this.selectAllButton.tip = Sol.Environment.resources.selectAll;
                        this.selectAllButton.enabled = false;
                        this.selectAllButton.onClick = () => this.selectAll();
                        this.toolbar.add(this.selectAllButton);
                    }
                    selectAll() {
                        this.mainList.controls.forEachReverse(item => {
                            if (item instanceof Uploads.UploadItem)
                                item.selected = true;
                        });
                        this.updateToolbox();
                    }
                    initChecklistButton() {
                        if (!Web.System.commonPermissions.contains("AddChecklistPermission"))
                            return;
                        this.checklistButton.myUpload = this;
                        this.toolbar.add(this.checklistButton);
                    }
                    itemClicked(item) {
                        item.selected = !item.selected;
                        this.renameFolderButton.enabled = false;
                        this.deleteFolderButton.enabled = false;
                        this.updateToolbox();
                        if (item instanceof Uploads.FolderItem) {
                            this.toggleFolderState(item);
                            this.renameFolderButton.enabled = item.selected && !item.blocked;
                            this.deleteFolderButton.enabled = item.selected && !item.blocked;
                        }
                    }
                    itemDeleted(item) {
                        if (this.onItemDeleted)
                            this.onItemDeleted(item);
                        if (this.isEmpty())
                            this.emptyMessage.visible = true;
                        this.updateFileCount();
                        this.save();
                    }
                    itemDragged(targetItem, itemID) {
                        const item = this.getItemByID(itemID);
                        var targetFolder = null;
                        if (targetItem instanceof Uploads.FolderItem) {
                            if (targetItem.closed)
                                this.toggleFolderState(targetItem);
                            targetFolder = targetItem;
                        }
                        else if (targetItem)
                            targetFolder = targetItem.folder;
                        if (item instanceof Uploads.FolderItem) {
                            if (targetFolder === null || targetFolder === void 0 ? void 0 : targetFolder.isChildOf(item)) {
                                alert("Não é possível mover uma pasta para seu interior.");
                                return;
                            }
                            if (this.folders.any(fld => fld.folder == targetFolder && fld.itemName == item.itemName)) {
                                alert("Já existe uma pasta com este nome na pasta de destino.");
                                return;
                            }
                            this.moveFolder(item, targetFolder);
                        }
                        else
                            this.moveItemToFolder(item, targetFolder, true);
                    }
                    download() {
                        const data = {
                            Filename: this.caption,
                            Names: this.selectedFiles.select(i => i.itemName).toArray(),
                            Identifiers: this.selectedFiles.select(i => i.identificador).toArray()
                        };
                        const serviceUrl = Sol.Environment.filePath.replace("download/", "downloadfiles/");
                        Sol.Http.Ajax.post(serviceUrl, data, e => window.open(Sol.Environment.filePath.replace("download/", "") + e.FileLink), null);
                    }
                    moveFolder(folder, targetFolder) {
                        folder.folder = targetFolder;
                        if (targetFolder)
                            Sol.List.from(Array.from(this.mainList.html.children))
                                .select(ch => this.getItemByID(ch.id))
                                .where(item => item.isChildOf(folder))
                                .forEachReverse(item => {
                                targetFolder.html.after(item.html);
                                item.updatePath();
                            });
                        else
                            Sol.List.from(Array.from(this.mainList.html.children))
                                .select(ch => this.getItemByID(ch.id))
                                .where(item => item.isChildOf(folder))
                                .forEach(item => {
                                this.mainList.html.appendChild(item.html);
                                item.updatePath();
                            });
                        this.updateFileCount();
                        this.save();
                    }
                    onInputChange(e) {
                        var tagInput = e.target;
                        var files = tagInput.files;
                        this.uploadFiles(files);
                    }
                    renameFolder() {
                        this.selectedItem.editable = true;
                    }
                    save() {
                        if (!this.autoSave || !this.code || this.singleFile)
                            return;
                        const saveData = {
                            className: this.contextClassName,
                            id: this.code,
                            data: [{ Campo: this.propertyName, Valor: this.value }]
                        };
                        Web.System.exec("3b5v9v45", "Save", saveData, e => Web.System.screens.currentScreen.lastUpdate = e.SavingTime);
                    }
                    saveNewFolder(folder) {
                        if (!this.autoSave || !this.code)
                            return;
                        let folderValues = folder.value;
                        folderValues.add({ Campo: this.fieldModel.AsociativePropertyName, Valor: this.code });
                        const saveData = {
                            className: this.className,
                            id: 0,
                            data: folderValues.toArray()
                        };
                        Web.System.exec("3b5v9v45", "Save", saveData, e => {
                            folder.code = e.ID;
                            Web.System.screens.currentScreen.lastUpdate = e.SavingTime;
                        });
                    }
                    saveNewFile(file) {
                        if (!this.autoSave || !this.code)
                            return;
                        let fileValues = file.valor;
                        fileValues.add({ Campo: this.fieldModel.AsociativePropertyName, Valor: this.code });
                        const saveData = {
                            className: this.className,
                            id: file.code || 0,
                            data: fileValues.toArray()
                        };
                        Web.System.exec("3b5v9v45", "Save", saveData, e => {
                            file.code = e.ID;
                            Web.System.screens.currentScreen.lastUpdate = e.SavingTime;
                        });
                    }
                    toggleFolderState(folder) {
                        folder.closed = !folder.closed;
                        this.items.where(i => i.folder == folder).forEach(i => {
                            i.visible = !folder.closed;
                            if (!i.visible && i instanceof Uploads.FolderItem && !i.closed)
                                this.toggleFolderState(i);
                        });
                    }
                    updateFileCount() {
                        this.folders.forEach(folder => folder.fileCount = this.items.where(i => i.folder == folder).count);
                    }
                    foco() { }
                    ;
                }
                Uploads.Upload = Upload;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class FollowupItem extends Sol.Control {
                constructor() {
                    super();
                    this.hourDisplay = new Sol.Control("span");
                    this.iconDisplay = new Sol.Control("span");
                    this.userDisplay = new Sol.Control("span");
                    this.textDisplay = new Sol.Control("span");
                    this.privateDisplay = new Sol.Control("span");
                    this.contactsArea = new Sol.Control();
                    this.dealDisplay = new Sol.Control();
                    this.code = 0;
                    this._contacts = new Sol.List();
                    this.isNew = false;
                    this.css.add("seguimiento_item");
                    this.iconDisplay.css.add("span_icon");
                    this.add(this.iconDisplay);
                    this.userDisplay.css.add("usuario");
                    this.add(this.userDisplay);
                    this.hourDisplay.css.add("fechahora");
                    this.add(this.hourDisplay);
                    this.privateDisplay.text = Sol.Environment.resources.privateMessage;
                    this.privateDisplay.visible = false;
                    this.privateDisplay.css.add("private_message");
                    this.add(this.privateDisplay);
                    this.textDisplay.css.add("message");
                    this.textDisplay.estilos.agregar("color", this.textColor);
                    this.textDisplay.onClick = () => this.textClick();
                    this.add(this.textDisplay);
                    this.contactsArea.css.add("sol_seguimientos_contact_area");
                    this.add(this.contactsArea);
                    this.dealDisplay.css.add("seguimiento_item_deal");
                    this.dealDisplay.visible = false;
                    this.dealDisplay.onClick = () => Web.System.edit("66990749", this.dealCode);
                    this.add(this.dealDisplay);
                }
                get contacts() { return this._contacts; }
                set contacts(v) {
                    this._contacts = v;
                    this.contactsArea.controls.empty();
                    this.contactsArea.controls.addMany(this._contacts.select(ct => {
                        var item = new Sol.Control("span");
                        item.css.add("sol_seguimientos_contact");
                        item.text = ct.text;
                        return item;
                    }));
                }
                get datetime() { return this._datetime; }
                set datetime(valor) {
                    this._datetime = valor;
                    this.hourDisplay.text = valor.formatearLocalConHora();
                }
                get fileLink() { return this._fileLink; }
                set fileLink(value) {
                    if (!value)
                        return;
                    this.textDisplay.css.add("clickable");
                    this._fileLink = value;
                }
                get message() { return this.textDisplay.htmlContent; }
                set message(value) { this.textDisplay.htmlContent = value; }
                get userName() { return this.userDisplay.text; }
                set userName(value) { this.userDisplay.text = value; }
                get textColor() { return this._textColor; }
                set textColor(value) {
                    this._textColor = value;
                    this.textDisplay.estilos.definir("color", value);
                }
                get iconCode() { return this._iconCode; }
                set iconCode(v) {
                    this._iconCode = v;
                    this.iconDisplay.text = Components.MessagesEditor.iconKeys[v];
                    if (!Components.MessagesEditor.iconKeys[v])
                        this.iconDisplay.text = "&#xf086";
                }
                get isPrivate() { return this._isPrivate; }
                set isPrivate(value) {
                    this._isPrivate = value;
                    this.privateDisplay.visible = value;
                }
                get dealDescription() { return this._dealDescription; }
                set dealDescription(value) {
                    this._dealDescription = value;
                    this.dealDisplay.text = "Negócio relacionado: " + value;
                    this.dealDisplay.visible = !!value;
                }
                textClick() {
                    if (this.fileLink)
                        window.open(this.fileLink);
                }
            }
            Components.FollowupItem = FollowupItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class MessageField extends Sol.Control {
                constructor() {
                    super();
                    this.CSS_MENTION = "sol_message_field_user";
                    this.editor = new Sol.Control("p");
                    this.popup = new Sol.Popup();
                    this.searchContactService = "i3n48smak";
                    this.methodName = "Search";
                    this.css.add("sol_message_field");
                    this.editor.atributos.agregar("contenteditable", "true");
                    this.editor.css.add("sol_campo");
                    this.add(this.editor);
                    this.popup.autoWidth = false;
                    this.popup.visible = false;
                    this.add(this.popup);
                }
                get mentions() {
                    return Sol.List.from(Array.from(this.editor.html.getElementsByClassName(this.CSS_MENTION)))
                        .select(el => ({
                        loginID: parseInt(el.getAttribute("code")),
                        personName: el.innerText
                    }))
                        .where(m => !!m.loginID);
                }
                get value() { return this.editor.htmlContent; }
                set value(value) { this.editor.htmlContent = value; }
                clear() { this.editor.htmlContent = ""; }
                foco() { this.editor.html.focus(); }
                isEmpty() { return !this.editor.htmlContent.trim(); }
                build() {
                    super.build();
                    setTimeout(() => {
                        this.editor.html.onkeyup = e => this.editorKeyUp(e);
                        this.editor.html.onkeydown = e => this.editorKeyDow(e);
                        this.editor.html.onblur = () => this.selection = this.saveSelection();
                    });
                }
                editorKeyDow(e) {
                    if (e.keyCode == 13 && this.popup.visible) {
                        this.blockEnter = true;
                        this.mention(this.getFocusedMenu());
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                    return true;
                }
                editorKeyUp(e) {
                    if (e.keyCode === 50) {
                        this.searchTerm = "";
                        this.searchLogins();
                        return false;
                    }
                    if (e.keyCode === 13 && !e.shiftKey) {
                        console.log(this.blockEnter);
                        if (this.blockEnter) {
                            this.blockEnter = false;
                            return false;
                        }
                        if (this.onSend)
                            this.onSend();
                        return false;
                    }
                    if (e.keyCode >= 65 && e.keyCode <= 90 && this.popup.visible) {
                        this.searchTerm += String.fromCharCode(e.keyCode);
                        this.searchLogins();
                        return false;
                    }
                    if (e.keyCode == 40 && this.popup.visible) {
                        var currentIndex = this.popup.controls.indice(this.getFocusedMenu());
                        var itemCount = this.popup.controls.count;
                        this.popup.controls.cast().item(currentIndex).focused = false;
                        currentIndex = currentIndex < itemCount - 1 ? currentIndex + 1 : 0;
                        this.popup.controls.cast().item(currentIndex).focused = true;
                        e.preventDefault();
                        e.stopPropagation();
                        e.returnValue = false;
                        e.cancelBubble = true;
                        return false;
                    }
                    if (e.keyCode == 38 && this.popup.visible) {
                        var currentIndex = this.popup.controls.indice(this.getFocusedMenu());
                        var itemCount = this.popup.controls.count;
                        this.popup.controls.cast().item(currentIndex).focused = false;
                        currentIndex = currentIndex > 0 ? currentIndex - 1 : itemCount - 1;
                        this.popup.controls.cast().item(currentIndex).focused = true;
                        e.preventDefault();
                        e.stopPropagation();
                        e.returnValue = false;
                        e.cancelBubble = true;
                        return false;
                    }
                    this.popup.visible = false;
                    if (this.onInput)
                        this.onInput();
                }
                fillPopup(model) {
                    for (var i = 0; i < model.Codes.length; i++) {
                        var data = model.Data[i];
                        var dataCollection = Sol.List.from(data);
                        var item = new Sol.SelectorItem();
                        var textValue = dataCollection.that(cmp => cmp.Campo == "EntidadRelacionada$Nombre").Valor;
                        item.code = model.Codes[i];
                        item.text = textValue;
                        item.onClick = e => this.mention(e);
                        item.extraData = data;
                        this.popup.add(item);
                    }
                    if (this.popup.controls.hasItems())
                        this.popup.controls.first().focused = true;
                }
                getFilters() {
                    var resultList = Sol.List.from([
                        { PropertyName: "Interno", FilterValue: false, FilterType: "SBoolean" },
                        { PropertyName: "Activo", FilterValue: true, FilterType: "SBoolean" },
                        { PropertyName: "Externo", FilterValue: false, FilterType: "SBoolean" }
                    ]);
                    if (this.searchTerm)
                        resultList.add({ PropertyName: "EntidadRelacionada$Nombre", FilterValue: this.searchTerm, FilterType: "SText" });
                    return resultList;
                }
                getFocusedMenu() {
                    return this.popup.controls.cast().that(i => i.focused);
                }
                mention(item) {
                    var userSpan = new Sol.Control("span");
                    userSpan.text = item.text;
                    userSpan.atributos.agregar("code", item.code.toString());
                    userSpan.css.add(this.CSS_MENTION);
                    this.editor.html.focus();
                    this.restoreSelection(this.selection);
                    if (this.searchTerm) {
                        let selection = document.getSelection();
                        let range = selection.getRangeAt(0);
                        range.setStart(range.startContainer, selection.focusOffset - this.searchTerm.length);
                        range.setEnd(range.startContainer, selection.focusOffset);
                        range.deleteContents();
                    }
                    userSpan.abrir();
                    document.execCommand("insertHTML", false, userSpan.html.outerHTML + "&nbsp;");
                    if (this.onInput)
                        this.onInput();
                    if (this.onMention)
                        this.onMention();
                    this.popup.visible = false;
                    return false;
                }
                restoreSelection(range) {
                    if (!range)
                        return;
                    if (window.getSelection) {
                        var sel = window.getSelection();
                        sel.removeAllRanges();
                        sel.addRange(range);
                    }
                    else if (document.selection && range.select)
                        document.select();
                    if (this.searchTerm)
                        range.setStart(range.startContainer, (range.startOffset - this.searchTerm.length));
                }
                saveSelection() {
                    if (window.getSelection) {
                        var sel = window.getSelection();
                        if (sel.getRangeAt && sel.rangeCount)
                            return sel.getRangeAt(0);
                    }
                    else if (document.selection && document.selection.createRange)
                        return document.selection.createRange();
                    return null;
                }
                searchLogins() {
                    const data = {
                        className: "Solarium.Login, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 1,
                        rowCount: 10,
                        filters: this.getFilters().toArray(),
                        sortProperty: "EntidadRelacionada$Nombre",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "EntidadRelacionada$Nombre"],
                        pageInfo: false,
                        contextID: this.code
                    };
                    if (this.ajax)
                        this.ajax.abort();
                    this.ajax = Web.System.exec(this.searchContactService, this.methodName, data, response => {
                        this.popup.controls.empty();
                        this.fillPopup(response);
                        this.popup.showAtCaret();
                    });
                }
            }
            Components.MessageField = MessageField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class MessagesEditor extends Sol.Control {
                constructor() {
                    super();
                    this.dealCombo = new Components.DataCombo();
                    this.errorMessage = new Sol.ScreenMessage();
                    this.messagesArea = new Sol.Control();
                    this.messageField = new Components.MessageField();
                    this.oldMessagesButton = new Sol.Button();
                    this.oldMessagesSpace = new Sol.Control();
                    this.page = 0;
                    this.iconCombo = new Sol.Combo();
                    this.textColor = new Sol.ColorField();
                    this.privateMessageCheck = new Sol.Check();
                    this.contactSelector = new Components.CollectionSelector();
                    this.saveButton = new Sol.Button();
                    this.showContacts = true;
                    this.showMessageTitle = true;
                    this._code = 0;
                    this.css.add("sol_seguimientos_messages");
                    this.messagesArea.css.add("sol_message_editor");
                    this.messageField.onMention = () => this.privateMessageCheck.value = true;
                }
                get items() { return this.messagesArea.controls.cast(); }
                get value() {
                    return this.items
                        .where(item => item.isNew)
                        .select(item => ({
                        Texto: item.message,
                        FechaHora: item.datetime,
                        TextColor: item.textColor,
                        IconCode: item.iconCode,
                        ContextID: this.code,
                        ContextClassName: this.contextClassName,
                        FileID: item.fileID,
                        Contacts: item.contacts.select(i => ({ ID: parseInt(i.model.Code) })).toArray(),
                        IsPrivate: this.privateMessageCheck.checked
                    }))
                        .toArray();
                }
                get searchContactService() { return this.messageField.searchContactService; }
                ;
                set searchContactService(value) { this.messageField.searchContactService = value; }
                ;
                get methodName() { return this.messageField.methodName; }
                ;
                set methodName(value) { this.messageField.methodName = value; }
                ;
                get code() { return this._code; }
                ;
                set code(value) {
                    this._code = value;
                    this.messageField.code = value;
                }
                ;
                addMessageIfNotEmpty() {
                    if (this.messageField.value.removeHtmlTags())
                        this.addMessage();
                }
                focus() {
                    this.errorMessage.visible = false;
                    this.messageField.foco();
                }
                getNewItems() {
                    return this.items.where(i => i.isNew);
                }
                loadContacts() {
                    if (!this.code)
                        return;
                    var datos = {
                        className: "Solarium.Contact, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 1,
                        rowCount: 20,
                        filters: [{
                                PropertyName: "CompanyFilter",
                                FilterValue: {
                                    Campo: "CompanyFilter",
                                    Valor: this.code
                                },
                                FilterType: ""
                            }],
                        sortProperty: "ID",
                        sortOrder: Web.Ordering.descending,
                        properties: ["ID", "TypeWithNombre"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", datos, model => this.contactSelector.loadSearchResults(model), null);
                }
                loadPage() {
                    const ITEM_COUNT = 20;
                    var properties = Sol.List.from(["ID", "FechaHora", "Texto", "CreatorName", "IsPrivate", "TextColor", "IconCode", "RelatedFile$DownloadUrl", "RelatedFile$Identificador"]);
                    if (this.showContacts)
                        properties.add("Contacts");
                    if (this.showDeals)
                        properties.addMany(["DealCode", "DealDescription"]);
                    const data = {
                        className: this.className,
                        currentPage: ++this.page,
                        rowCount: ITEM_COUNT,
                        filters: [{
                                PropertyName: this.associativeProperty,
                                FilterValue: {
                                    Campo: this.associativeProperty,
                                    Valor: this.code
                                },
                                FilterType: ""
                            },
                            {
                                PropertyName: "MinDatetimeFilter",
                                FilterValue: this.lastMessage,
                                FilterType: ""
                            }],
                        sortProperty: "FechaHora",
                        sortOrder: Web.Ordering.descending,
                        properties: properties.toArray(),
                        pageInfo: true
                    };
                    const baseMsg = this.addMessagesToEnd ? this.messagesArea.controls.count : 1;
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        var results = Sol.List.from(model.Data);
                        var i = 0;
                        var firstDateTime;
                        results.forEach(item => {
                            var _a, _b;
                            const itemCode = model.Codes[i++];
                            if (this.messagesArea.controls.cast().any(fi => fi.code == itemCode))
                                return;
                            var dataValues = Sol.List.from(item);
                            const followup = new Components.FollowupItem();
                            followup.code = itemCode;
                            firstDateTime = dataValues.that(d => d.Campo == "FechaHora").Valor;
                            followup.hourDisplay.text = firstDateTime;
                            followup.message = dataValues.that(d => d.Campo == "Texto").Valor;
                            followup.userName = dataValues.that(d => d.Campo == "CreatorName").Valor;
                            followup.textColor = dataValues.that(d => d.Campo == "TextColor").Valor;
                            followup.iconCode = dataValues.that(d => d.Campo == "IconCode").Valor;
                            followup.isPrivate = dataValues.that(d => d.Campo == "IsPrivate").Valor;
                            followup.dealCode = (_a = dataValues.that(d => d.Campo == "DealCode")) === null || _a === void 0 ? void 0 : _a.Valor;
                            followup.dealDescription = (_b = dataValues.that(d => d.Campo == "DealDescription")) === null || _b === void 0 ? void 0 : _b.Valor;
                            followup.fileLink = dataValues.that(d => d.Campo == "RelatedFile$DownloadUrl").Valor;
                            followup.parent = this;
                            let contacts = dataValues.that(d => d.Campo == "Contacts");
                            if (contacts) {
                                var contactData = Sol.List.from(contacts.Valor);
                                followup.contacts = contactData.select(ct => {
                                    var dataItems = Sol.List.from(ct);
                                    return new Components.CollectionSelectorItem({
                                        Code: dataItems.that(d => d.Campo == "ID").Valor,
                                        Description: dataItems.that(d => d.Campo == "TypeWithNombre").Valor
                                    });
                                });
                            }
                            this.messagesArea.controls.insert(baseMsg, followup);
                        });
                        this.oldMessagesSpace.visible = this.page < (model.PageCount - 1);
                        if (this.page == 1)
                            this.scrollBottom();
                        this.lastMessage = firstDateTime || this.lastMessage;
                        this.addMessagesToEnd = false;
                    });
                }
                refresh() {
                    this.resetEditor();
                    this.addNewItems();
                    if (!this.code)
                        return;
                    this.page = 0;
                    this.loadPage();
                }
                resetEditor() {
                    this.messageField.clear();
                    this.resetMessages();
                }
                build() {
                    super.build();
                    if (this.fullScreen)
                        this.css.add("sol_seguimientos_messages_fullscreen");
                    if (this.showMessageTitle) {
                        var messagesTitle = new Sol.Control("h4");
                        messagesTitle.text = Sol.Environment.resources.messages;
                        this.add(messagesTitle);
                    }
                    this.configureFileDrop();
                    this.add(this.messagesArea);
                    this.oldMessagesSpace.css.add("sol_seguimientos_viejos");
                    this.messagesArea.add(this.oldMessagesSpace);
                    this.oldMessagesButton.type = Sol.ButtonType.Link;
                    this.oldMessagesButton.data = this;
                    this.oldMessagesButton.text = Sol.Environment.resources.ver_anteriores;
                    this.oldMessagesButton.onClick = () => this.loadPage();
                    this.oldMessagesSpace.add(this.oldMessagesButton);
                    this.oldMessagesSpace.visible = false;
                    this.errorMessage.type = Sol.MessageType.Error;
                    this.errorMessage.caption = Sol.Environment.resources.texto_requerido;
                    this.errorMessage.visible = false;
                    this.add(this.errorMessage);
                    this.initMessageField();
                    this.initContactSelector();
                    this.initIconCombo();
                    this.initColorSelector();
                    this.initPrivateMessageCheck();
                    this.initDealSelector();
                    this.initSaveButton();
                    if (this.uploadControl) {
                        this.uploadControl.onUploadStarted = i => this.fileAdded(i);
                        this.uploadControl.onItemDeleted = i => this.fileDeleted(i);
                    }
                    if (this.code)
                        this.push = new Sol.Http.Push("chat" + this.className, this.code, () => this.loadLastMessages());
                }
                addMessage() {
                    this.errorMessage.visible = false;
                    if (this.messageField.isEmpty()) {
                        this.errorMessage.visible = true;
                        return false;
                    }
                    var message = this.messageField.value.trim();
                    while (message.endsWith("<div><br></div>"))
                        message = message.substr(0, message.length - 15);
                    message = message.replaceAll("<a", "<a target='_blank'");
                    const item = new Components.FollowupItem();
                    item.isNew = true;
                    item.datetime = new Date();
                    item.message = message;
                    item.userName = Web.System.userName;
                    item.textColor = this.textColor.value;
                    item.contacts = this.contactSelector.selectedItems;
                    item.iconCode = parseInt(this.iconCombo.selectedCode);
                    item.isPrivate = this.privateMessageCheck.checked;
                    item.dealCode = parseInt(this.dealCombo.selectedCode);
                    item.dealDescription = this.dealCombo.selectedText;
                    this.messagesArea.add(item);
                    this.scrollBottom();
                    this.saveItem(item);
                    this.messageField.clear();
                    this.messageField.foco();
                    this.contactSelector.clear();
                    return false;
                }
                saveItem(item) {
                    if (!this.automaticSaving)
                        return;
                    const fieldData = Sol.List.from([{ Campo: this.associativeProperty, Valor: this.code },
                        { Campo: "Texto", Valor: item.message },
                        { Campo: "TextColor", Valor: item.textColor },
                        { Campo: "ContextID", Valor: this.code },
                        { Campo: "ContextClassName", Valor: this.contextClassName },
                        { Campo: "RelatedFile", Valor: item.fileID },
                        { Campo: "IsPrivate", Valor: item.isPrivate },
                        { Campo: "DealCode", Valor: item.dealCode },
                        { Campo: "IconCode", Valor: item.iconCode }]);
                    if (this.showContacts && item.contacts.hasItems())
                        fieldData.add({
                            Campo: "Contacts",
                            Valor: item.contacts.select(i => { return { "ID": parseInt(i.model.Code) }; }).toArray()
                        });
                    const saveData = {
                        className: this.className,
                        id: item.code,
                        data: fieldData.toArray()
                    };
                    item.isNew = false;
                    Web.System.exec("3b5v9v45", "Save", saveData, model => {
                        var _a;
                        item.code = model.ID;
                        (_a = this.push) === null || _a === void 0 ? void 0 : _a.notify();
                    });
                }
                addNewItems() {
                    if (!this.newItemsBag)
                        return;
                    this.newItemsBag.forEachReverse(item => this.messagesArea.controls.insert(0, item));
                }
                configureFileDrop() {
                    if (!this.enableUploads)
                        return;
                    this.messagesArea.onDragOver = () => this.enableDrop();
                    this.messagesArea.onDragEnter = () => this.enableDrop();
                    this.messagesArea.onDragLeave = () => this.cancelDrop();
                    this.messagesArea.onDrop = (me, e) => this.fileDrop(e);
                }
                enableDrop() {
                    this.messagesArea.css.add("sol_message_editor_waiting_file");
                    return false;
                }
                cancelDrop() {
                    this.messagesArea.css.remove("sol_message_editor_waiting_file");
                    return false;
                }
                fileAdded(ui) {
                    const item = new Components.FollowupItem();
                    item.isNew = true;
                    item.datetime = new Date();
                    item.message = Sol.Environment.resources.fileAdded + ui.itemName;
                    item.userName = Web.System.userName;
                    item.parent = this;
                    item.textColor = this.textColor.value;
                    item.iconCode = 9;
                    this.messagesArea.controls.insert(0, item);
                    ui.onUploadComplete = upi => {
                        item.fileLink = upi.downloadUrl;
                        this.saveFile(upi, item);
                    };
                    this.saveItem(item);
                }
                fileDeleted(ui) {
                    const item = new Components.FollowupItem();
                    item.isNew = true;
                    item.datetime = new Date();
                    item.message = Sol.Environment.resources.fileDeleted + ui.itemName;
                    item.userName = Web.System.userName;
                    item.parent = this;
                    item.textColor = this.textColor.value;
                    item.iconCode = 9;
                    this.messagesArea.controls.insert(0, item);
                    this.saveItem(item);
                }
                fileDrop(e) {
                    let files = e.dataTransfer.files;
                    this.uploadControl.uploadFiles(files);
                    if (this.onFileDropped)
                        this.onFileDropped();
                    return this.cancelDrop();
                }
                initMessageField() {
                    const messageLabel = new Sol.Label();
                    messageLabel.text = Sol.Environment.resources.nuevo_seguimiento + ':';
                    messageLabel.largeDescription = Sol.Environment.resources.nuevo_seguimiento_descripción;
                    this.add(messageLabel);
                    this.messageField.onInput = () => {
                        this.privateMessageCheck.readonly = !this.messageField.mentions.hasItems();
                        if (this.privateMessageCheck.readonly)
                            this.privateMessageCheck.checked = false;
                    };
                    this.messageField.onSend = () => this.addMessageIfNotEmpty();
                    this.add(this.messageField);
                }
                initColorSelector() {
                    var colorWrapper = new Sol.Control();
                    colorWrapper.css.addMany(["sol_detalles_wrapper", "sol_seguimientos_options"]);
                    var colorLabel = new Sol.Label();
                    colorLabel.editor = this.textColor;
                    colorLabel.text = Sol.Environment.resources.color + ':';
                    colorWrapper.add(colorLabel);
                    colorWrapper.add(this.textColor);
                    this.add(colorWrapper);
                }
                initPrivateMessageCheck() {
                    this.privateMessageCheck.readonly = true;
                    this.privateMessageCheck.caption = Sol.Environment.resources.privateMessage;
                    this.add(this.privateMessageCheck);
                }
                initContactSelector() {
                    if (!this.showContacts)
                        return;
                    var contactWrapper = new Sol.Control();
                    contactWrapper.css.addMany(["sol_detalles_wrapper", "sol_seguimientos_options", "sol_seguimientos_option_contact"]);
                    var contactLabel = new Sol.Label();
                    contactLabel.editor = this.contactSelector;
                    contactLabel.text = Sol.Environment.resources.contact + ':';
                    contactWrapper.add(contactLabel);
                    contactWrapper.add(this.contactSelector);
                    this.add(contactWrapper);
                }
                initDealSelector() {
                    let dealWrapper = new Sol.FieldWrapper();
                    let dealLabel = new Sol.Label();
                    dealLabel.editor = this.contactSelector;
                    dealLabel.text = "Negociação:";
                    dealWrapper.add(dealLabel);
                    this.dealCombo.className = "Solarium.Commercial.Venta, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.dealCombo.displayProperty = "CodeAndIdentifier";
                    this.dealCombo.sortProperty = "ID";
                    this.dealCombo.preFilters = [
                        { PropertyName: "Destinatario", FilterType: "SInteger", FilterValue: this.code },
                        { PropertyName: "Status$EnAndamiento", FilterType: "SBoolean", FilterValue: 1 }
                    ];
                    dealWrapper.add(this.dealCombo);
                    this.dealCombo.refresh(() => {
                        var _a;
                        if (((_a = Web.System.screens.currentDetails) === null || _a === void 0 ? void 0 : _a.className) == this.dealCombo.className)
                            this.dealCombo.selectedCode = Web.System.screens.currentDetails.code.toString();
                    });
                    this.add(dealWrapper);
                }
                initIconCombo() {
                    var iconWrapper = new Sol.Control();
                    iconWrapper.css.addMany(["sol_detalles_wrapper", "sol_seguimientos_options"]);
                    var iconLabel = new Sol.Label();
                    iconLabel.editor = this.iconCombo;
                    iconLabel.text = Sol.Environment.resources.icon + ':';
                    iconWrapper.add(iconLabel);
                    for (var i = 0; i <= MessagesEditor.iconKeys.length; i++)
                        this.iconCombo.add(new Sol.ComboItem(i, MessagesEditor.iconKeys[i]));
                    this.iconCombo.css.add("icon_combo");
                    iconWrapper.add(this.iconCombo);
                    this.add(iconWrapper);
                }
                initSaveButton() {
                    this.saveButton.css.add("sol_message_editor_button");
                    this.saveButton.text = Sol.Environment.resources.anadir_item;
                    this.saveButton.onClick = () => this.addMessage();
                    this.saveButton.data = this;
                    this.add(this.saveButton);
                }
                resetMessages() {
                    this.messagesArea.controls.empty();
                    this.messagesArea.add(this.oldMessagesSpace);
                    this.page = 0;
                }
                loadLastMessages() {
                    this.addMessagesToEnd = true;
                    this.page = 0;
                    this.loadPage();
                }
                scrollBottom() {
                    var _a;
                    (_a = this.messagesArea.html) === null || _a === void 0 ? void 0 : _a.scroll({ top: this.messagesArea.html.scrollHeight, behavior: "smooth" });
                }
                saveFile(upi, fi) {
                    const saveData = {
                        className: "Solarium.Archivo, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        id: 0,
                        data: upi.toDatumModel(),
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", saveData, e => {
                        fi.fileID = e.ID;
                        this.saveItem(fi);
                    });
                }
            }
            MessagesEditor.iconKeys = ["", "&#xf095", "&#xf0e0", "&#xf12a", "&#xf1b9", "&#xf0d6", "&#xf0e7", "&#xf119", "&#xf017", "&#xf15b"];
            Components.MessagesEditor = MessagesEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class Grid extends Sol.Control {
                constructor() {
                    super("table");
                    this.tableHeader = new Sol.Control("thead");
                    this.tableBody = new Sol.Control("tbody");
                    this.allowDelete = true;
                    this.columns = new Sol.List();
                    this.fixedRows = true;
                    this._readonly = true;
                    this._rowCount = 20;
                    this.selection = new Components.GridSelection();
                    this.sortOrder = Components.ColumnOrder.Ascending;
                    this.showChecks = true;
                    this.showHeader = true;
                    this.css.add("sol_tabla_data");
                    this.add(this.tableHeader);
                    this.tableBody.css.add("sol_tabla_espacio_lineas");
                    this.add(this.tableBody);
                }
                get fixedColumnsCount() { return this.showChecks ? 1 : 0; }
                isEmpty() { return !this.tableBody.controls.hasItems(); }
                get readonly() { return this._readonly; }
                ;
                set readonly(value) {
                    this._readonly = value;
                    this.rows.forEach(row => row.editors.forEach(edt => edt.readonly = edt.readonly || value));
                }
                get rowCount() { return this.fixedRows ? this._rowCount : this.tableBody.controls.count; }
                set rowCount(value) { this._rowCount = value; }
                get rows() {
                    var _a;
                    return ((_a = this.tableBody.controls) === null || _a === void 0 ? void 0 : _a.cast().where(row => row.rowType == Components.GridRowType.Data)) || new Sol.List();
                }
                get showVerticalLines() { return this._showVerticalLines; }
                set showVerticalLines(value) {
                    this._showVerticalLines = value;
                    this.css.toggleValue("sol_tabla_data_vert_lines", value);
                }
                addRow(data = null) {
                    let row = new Components.GridRow();
                    row.myGrid = this;
                    row.index = this.rows.count + 1;
                    row.rowData = Sol.List.from(data);
                    if (data) {
                        let rowId = row.rowData.that(d => d.Campo == "ID");
                        row.code = rowId ? rowId.Valor : 0;
                    }
                    this.fillRow(row);
                    this.tableBody.add(row);
                    if (this.onInstantiateRow)
                        this.onInstantiateRow(row);
                    if (this.onRowCreated)
                        this.onRowCreated(row);
                    return row;
                }
                buildHeader() {
                    if (!this.showHeader)
                        return;
                    var headerLine = new Sol.Control("tr");
                    if (this.showChecks) {
                        const checkColumn = new Sol.Control("th");
                        this.selectAllCheck = new Sol.Check();
                        this.selectAllCheck.onChange = () => this.selectAll();
                        checkColumn.add(this.selectAllCheck);
                        headerLine.add(checkColumn);
                    }
                    var col = 1;
                    this.columns.orderBy(cl => cl.Position).forEach(cl => cl.Position = col++);
                    this.headers = this.columns.orderBy(cl => cl.Position).select(cl => new Components.GridHeader(cl));
                    this.headers.forEach(header => {
                        if (header.sortable)
                            header.onClick = () => this.columnClick(header);
                        if (header.sortProperty == this.sortProperty || header.propertyName == this.sortProperty)
                            header.sortOrder = this.sortOrder;
                        header.onSelectAll = () => {
                            const isSelected = header.selected;
                            this.rows.forEach(row => {
                                let check = row.getEditor(header.propertyName);
                                if (!check.readonly)
                                    check.value = isSelected;
                            });
                        };
                    });
                    headerLine.controls.addMany(this.headers);
                    if (!this.readonly && this.allowDelete) {
                        var deleteColumn = new Sol.Control("th");
                        deleteColumn.ancho = 16;
                        headerLine.add(deleteColumn);
                    }
                    if (this.fixedRows)
                        this.generateBlankRows(this.rowCount);
                    this.configureColumnReorder(headerLine);
                    this.tableHeader.add(headerLine);
                }
                clear() {
                    var _a;
                    (_a = this.tableBody.controls) === null || _a === void 0 ? void 0 : _a.empty();
                }
                clearSelection() {
                    var _a;
                    (_a = this.selectAllCheck) === null || _a === void 0 ? void 0 : _a.clear();
                    this.selection.clear();
                }
                deleteAllRows() { this.tableBody.controls.empty(); }
                deleteRow(row) {
                    this.tableBody.controls.remove(row);
                }
                deleteColumn(column) {
                    this.tableBody.controls.remove(column);
                }
                empty() {
                    this.deleteAllRows();
                    this.tableHeader.controls.empty();
                }
                fillBlankRow(row) {
                    row.controls.addMany(this.columns.select(cl => {
                        const cell = new Components.GridCell();
                        cell.columnInfo = cl;
                        cell.setAlignment(cl.Alignment);
                        cell.clickToEdit = this.isCellClickable(cl);
                        if (cell.clickToEdit)
                            cell.onClick = () => {
                                if (this.onRowClick && row.code)
                                    this.onRowClick(row.code, row.index);
                            };
                        return cell;
                    }));
                }
                findRowsByProperty(propertyName, value) {
                    return this.rows.where(row => row.rowData.any(d => d.Campo == propertyName && d.Valor == value));
                }
                generateBlankRows(count) {
                    let index = this.rows.count + 1;
                    this.tableBody.controls.addMany(Sol.List.range(this.rowCount - count, this.rowCount - 1).select(i => {
                        let row = new Components.GridRow();
                        row.index = index++;
                        if (this.onRowChecked)
                            row.onRowChecked = (code, checked) => this.rowChecked(code, checked);
                        if (this.onTotalChanged)
                            row.onTotalChanged = () => this.onTotalChanged();
                        if (this.showChecks)
                            row.createCheckCell();
                        this.fillBlankRow(row);
                        if (!this.readonly)
                            row.createDeleteCell();
                        return row;
                    }));
                }
                getColumnIndexByPropertyName(propertyName) {
                    return this.columns.indice(this.columns.that(col => col.PropertyName === propertyName));
                }
                getEditors(propertyName) {
                    return this.rows.select(row => row.editors.that(edt => edt.propertyName == propertyName));
                }
                getPropertyValueByID(propertyName, code) {
                    const row = this.rows.that(row => row.code == code);
                    return row.rowData.that(i => i.Campo == propertyName).Valor;
                }
                loadData(model) {
                    var _a, _b, _c;
                    let hasGroup = !!model.GroupProperty;
                    let lastGroup = "\u0000";
                    this.currentData = model;
                    this.clear();
                    if (this.tableHeader.controls && !this.tableHeader.controls.hasItems())
                        this.buildHeader();
                    if (this.fixedRows && !this.rows.hasItems())
                        this.generateBlankRows(this.rowCount);
                    let dataIndex = 0, rowIndex = 0;
                    let rowCount = this.fixedRows ? this.rowCount : (((_a = model.Data) === null || _a === void 0 ? void 0 : _a.length) || 0);
                    for (; dataIndex < rowCount; dataIndex++) {
                        let rowData = Sol.List.from(model.Data[dataIndex]);
                        if (!rowData)
                            break;
                        if (hasGroup) {
                            let groupName = (_b = rowData.that(d => d.Campo == model.GroupProperty)) === null || _b === void 0 ? void 0 : _b.Valor;
                            groupName = (groupName === null || groupName === void 0 ? void 0 : groupName.Campo) || groupName;
                            groupName = !groupName ? model.EmptyGroupCaption : `${model.GroupCaption}: ${groupName}`;
                            if (groupName != lastGroup) {
                                let groupTitleRow = new Components.SubgroupTitleRow(groupName, this.tableHeader.controls.first().controls.count);
                                this.tableBody.controls.insert(rowIndex++, groupTitleRow);
                                lastGroup = groupName;
                            }
                        }
                        if (!this.fixedRows) {
                            let row = this.addRow(rowData.toArray());
                            row.code = model.Codes[dataIndex];
                            row.applyFormat(model.Formats[dataIndex]);
                        }
                        rowIndex++;
                        let row = this.rows.item(dataIndex);
                        row.rowData = rowData;
                        if (rowData.hasItems()) {
                            row.code = model.Codes[dataIndex];
                            row.applyFormat(model.Formats[dataIndex]);
                            if (this.showChecks) {
                                this.isSelectingAll = true;
                                row.check.visible = true;
                                row.check.checked = this.selection.isCodeSelected(row.code);
                                this.isSelectingAll = false;
                            }
                            var columnInfo;
                            for (var cl = 0; cl < this.columns.count; cl++) {
                                columnInfo = this.columns.item(cl);
                                if (columnInfo.PropertyName) {
                                    const cellValue = (_c = rowData.that(cmp => cmp.Campo == columnInfo.PropertyName)) === null || _c === void 0 ? void 0 : _c.Valor;
                                    if (cellValue == null)
                                        continue;
                                    const cell = row.controls.item(cl + this.fixedColumnsCount);
                                    this.fillCell(cell, columnInfo, cellValue, row.code);
                                }
                            }
                            if (this.onInstantiateRow)
                                this.onInstantiateRow(row);
                        }
                        else
                            break;
                    }
                    return dataIndex;
                }
                setColumnVisibility(propertyName, value) {
                    var _a;
                    const header = this.headers.that(h => h.propertyName == propertyName);
                    if (header)
                        header.visible = value;
                    this.rows.where(row => !!row.getCellByPropertyName(propertyName)).forEach(row => row.getCellByPropertyName(propertyName).visible = value);
                    let column = this.columns.that(cl => cl.PropertyName == propertyName);
                    if (column)
                        column.Visible = value;
                    (_a = this.footer) === null || _a === void 0 ? void 0 : _a.controls.cast().forEach(frow => {
                        let cell = frow.cells.that(c => { var _a; return ((_a = c.columnInfo) === null || _a === void 0 ? void 0 : _a.PropertyName) == propertyName; });
                        if (cell)
                            cell.visible = value;
                    });
                }
                updateRow(row, data = null) {
                    row.rowData = Sol.List.from(data);
                    row.controls.empty();
                    this.fillRow(row);
                }
                columnClick(header) {
                    if (header.sortOrder == Components.ColumnOrder.NotSet) {
                        this.tableHeader.controls.first().controls.cast()
                            .forEach(t => { t.sortOrder = Components.ColumnOrder.NotSet; });
                        header.sortOrder = Components.ColumnOrder.Ascending;
                        this.sortProperty = header.sortProperty;
                        this.sortOrder = Components.ColumnOrder.Ascending;
                    }
                    else if (header.sortOrder == Components.ColumnOrder.Ascending) {
                        header.sortOrder = Components.ColumnOrder.Descending;
                        this.sortOrder = Components.ColumnOrder.Descending;
                    }
                    else {
                        header.sortOrder = Components.ColumnOrder.Ascending;
                        this.sortOrder = Components.ColumnOrder.Ascending;
                    }
                    if (this.onColumnClick)
                        this.onColumnClick(header.columnInfo);
                }
                columnDrop(header, e) {
                    var propertyDrop = e.dataTransfer.getData("dataview_header");
                    if (!propertyDrop)
                        return;
                    e.preventDefault();
                    header.css.remove("sol_tabla_drag");
                    if (propertyDrop == header.propertyName)
                        return;
                    var currentPos = this.getColumnByPropertyName(header.propertyName).Position;
                    this.columns.forEach(col => {
                        if (col.PropertyName == propertyDrop)
                            col.Position = currentPos;
                        else if (col.Position >= currentPos)
                            col.Position++;
                    });
                    if (this.onColumnDrop)
                        this.onColumnDrop();
                }
                configureColumnReorder(headerLine) {
                    if (!this.allowReorder)
                        return;
                    headerLine.controls
                        .where(ctr => ctr instanceof Components.GridHeader)
                        .cast()
                        .forEach(header => {
                        header.draggable = true;
                        header.onDragStart = (ctr, e) => e.dataTransfer.setData("dataview_header", header.propertyName);
                        header.onDragEnter = () => header.css.add("sol_tabla_drag");
                        header.onDragLeave = () => header.css.remove("sol_tabla_drag");
                        header.onDragOver = (ctr, e) => e.preventDefault();
                        header.onDrop = (ctr, e) => this.columnDrop(header, e);
                    });
                }
                fillCell(cell, colInfo, value, code) {
                    var _a;
                    const collections = Sol.List.from(["Roles", "Languages", "Categories", "CustomerTags", "Profiles", "Systems", "Inspectors"]);
                    cell.setAlignment(colInfo.Alignment);
                    cell.setVerticalAlignment(colInfo.VerticalAlignment);
                    if (cell.editor)
                        cell.editor = value;
                    else if (colInfo.Drawer == "TitleDescriptionDrawer")
                        this.drawTitleDescription(cell, value);
                    else if (colInfo.Drawer == "ColoredText")
                        this.drawColeredText(cell, value);
                    else if (colInfo.Drawer == "IconCounter")
                        this.drawIconCounter(cell, value);
                    else if (colInfo.Drawer == "UrlViewer")
                        this.drawUrlViewer(cell, value);
                    else if (colInfo.Drawer == "CollectionDrawer" || collections.contains(colInfo.PropertyName))
                        this.insertCollectionEditor(cell, value, code, colInfo);
                    else if (colInfo.DataType == "SLargeText")
                        this.drawParagraph(cell, value);
                    else if (colInfo.DataType == "SColor")
                        this.drawColor2(cell, value);
                    else if (colInfo.DataType == "SDate")
                        this.createSDateCell(cell, value);
                    else if (colInfo.DataType == "SPercent")
                        this.drawProgressBar(cell, value);
                    else if (colInfo.DataType == "SRating")
                        this.drawRating(cell, value);
                    else if (colInfo.PropertyName == "StatusChanger")
                        this.drawDecisions(cell, value, code);
                    else if (colInfo.PropertyName == "MessageDisplay")
                        this.drawMessage(cell, value, code);
                    else if (value.Color)
                        this.drawColor(cell, value);
                    else if (value.Valor && value.Valor.Color)
                        this.drawColor(cell, value.Valor);
                    else if (colInfo.DataType == "SText" && value.Valor)
                        cell.text = value.Valor;
                    else if (value.IsPerson)
                        this.drawEntity(cell, value);
                    else if (colInfo.Drawer == "EntityDrawer")
                        this.drawEntity(cell, value.Valor);
                    else if (value.Campo || value.Campo == "")
                        cell.text = value.Campo == colInfo.PropertyName ?
                            (((_a = value.Valor) === null || _a === void 0 ? void 0 : _a.Valor) ? value.Valor.Campo : value.Valor) : value.Campo;
                    else if (value[0] == "&")
                        this.drawIcon(cell, value);
                    else if (colInfo.DataType == "SBoolean")
                        this.drawActive(cell, value);
                    else if (colInfo.PropertyName == "IconCode")
                        this.drawIcon(cell, Components.MessagesEditor.iconKeys[value]);
                    else if (colInfo.PropertyName == "Nombre")
                        this.drawTextBoldCell(cell, value);
                    else if (colInfo.PropertyName == "EntidadRelacionada$Nombre")
                        this.drawTextBoldCell(cell, value);
                    else if (typeof value === "object")
                        cell.text = "";
                    else
                        cell.text = value;
                }
                isCellClickable(cl) {
                    return cl.PropertyName != "StatusChanger" && (!cl.EditorModel || cl.EditorModel.DataType == "Display");
                }
                fillRow(row) {
                    var focusFlag = false;
                    this.columns.where(cl => cl.Visible).forEach(cl => {
                        var _a;
                        const cell = new Components.GridCell();
                        cell.grid = this;
                        cell.setAlignment(cl.Alignment);
                        let cellValue = row.rowData.that(d => d.Campo == cl.PropertyName);
                        cell.columnInfo = cl;
                        cell.clickToEdit = this.isCellClickable(cl);
                        if (cell.clickToEdit)
                            cell.onClick = () => {
                                if (this.onRowClick && row.code)
                                    this.onRowClick(row.code, row.index);
                            };
                        if (cl.EditorModel) {
                            let editor = Web.Editors.createField(cl.EditorModel, this.className, row.code);
                            cell.editor = editor;
                            editor.container = row;
                            editor.readonly = this.readonly ||
                                cl.EditorModel.ReadOnly ||
                                (cl.EditorModel.ReadOnlyAtEdition && !!row.code) ||
                                ((_a = cellValue === null || cellValue === void 0 ? void 0 : cellValue.State) === null || _a === void 0 ? void 0 : _a.IsReadonly);
                            Sol.List.from(cl.EditorModel.Behaviours).forEach(b => {
                                let behaviour = eval("new Sol.Web.Behaviours." + b.BehaviourName + "()");
                                behaviour.apply(row, editor, b.Configuration, row.code);
                            });
                            if (editor instanceof Sol.Field) {
                                const field = editor;
                                field.alignment = cl.Alignment;
                                field.autoWidth = false;
                                if (field.minLength && field.maxLength == field.minLength)
                                    field.alignment = Sol.Alignment.Center;
                            }
                            if (cl.EditorModel.Width)
                                cell.ancho = cl.EditorModel.Width + 8;
                            if (editor instanceof Sol.Check) {
                                editor.caption = "";
                                cell.estilos.agregar("text-align", "center");
                            }
                            if (editor instanceof Components.DataCombo)
                                editor.refresh();
                            if (cellValue)
                                editor.value = cellValue.Valor;
                            editor.onChange = () => {
                                if (cl.onEditorChange)
                                    cl.onEditorChange(row, editor);
                                if (this.onInlineEditorChanged)
                                    this.onInlineEditorChanged(editor, false);
                            };
                            if (cl.EditorModel.ShowHistory) {
                                const historyButton = new Components.HistoryButton();
                                historyButton.className = this.className;
                                historyButton.propertyName = cl.PropertyName;
                                historyButton.beforeList = () => historyButton.code = row.code;
                                cell.add(historyButton);
                            }
                            cell.add(editor.toControl());
                            row.editors.add(editor);
                            if (editor instanceof Components.Selectors.Selector && row.rowData) {
                                var id = row.rowData.that(d => d.Campo == cl.EditorModel.PropertyName + "$ID");
                                var name = row.rowData.that(d => d.Campo == cl.EditorModel.PropertyName + "$Nombre");
                                if (id && name)
                                    editor.value = {
                                        Campo: name.Valor,
                                        Valor: id.Valor
                                    };
                            }
                            if (!focusFlag && !editor.readonly) {
                                editor.foco();
                                focusFlag = true;
                            }
                        }
                        else if (cellValue)
                            this.fillCell(cell, cl, cellValue, row.code);
                        row.add(cell);
                    });
                    if (row.getEditor("Total") && this.onTotalChanged) {
                        row.onTotalChanged = () => this.onTotalChanged();
                        row.configureTotal();
                    }
                    if (!this.readonly && this.allowDelete) {
                        var deleteCell = row.createDeleteCell();
                        var deleteButton = new Sol.Control("sup");
                        deleteButton.text = "x";
                        deleteButton.onClick = () => {
                            if (this.onRowDelete)
                                this.onRowDelete(row);
                        };
                        deleteCell.add(deleteButton);
                    }
                    if (this.onTotalChanged)
                        this.onTotalChanged();
                }
                getColumnByPropertyName(propertyName) {
                    return this.columns.that(cl => cl.PropertyName == propertyName);
                }
                rowChecked(code, checked) {
                    if (!this.isSelectingAll)
                        this.selection.select(code);
                    this.onRowChecked(code, checked);
                }
                selectAll() {
                    this.selection.allSelected = !this.selection.allSelected;
                    this.isSelectingAll = true;
                    this.rows.where(r => !r.isEmpty).forEach(row => row.check.checked = this.selection.allSelected);
                    this.isSelectingAll = false;
                    this.selection.codes.empty();
                }
                drawActive(cell, value) {
                    if (value == null)
                        return;
                    var switchSpan = new Sol.Control("span");
                    if (value == "No" || value == "Não") {
                        switchSpan.css.add("sol_switch_disabled");
                        switchSpan.tip = Sol.Environment.resources.inactivo;
                    }
                    else {
                        switchSpan.css.add("sol_switch_enabled");
                        switchSpan.tip = Sol.Environment.resources.activo;
                    }
                    switchSpan.htmlContent = "&nbsp;";
                    cell.add(switchSpan);
                    cell.clickToEdit = false;
                }
                drawColor(cell, value) {
                    if (!value.Campo)
                        return;
                    var colorSpan = new Components.Displays.ColorizedDisplay();
                    colorSpan.setValue(value);
                    cell.add(colorSpan);
                }
                drawColor2(cell, value) {
                    var colorSpan = new Sol.Control("span");
                    colorSpan.css.add("icono_color");
                    colorSpan.estilos.agregar("background-color", value);
                    cell.add(colorSpan);
                }
                drawIcon(cell, iconCode) {
                    var icon = new Sol.Control("i");
                    icon.text = iconCode;
                    icon.css.add("icono");
                    cell.ancho = 20;
                    cell.add(icon);
                }
                drawDecisions(cell, value, code) {
                    if (!this.availableDecisions)
                        return;
                    cell.css.add("sol_tabla_decision");
                    cell.controls.addMany(this.availableDecisions
                        .where(decision => decision.StatusCode == value)
                        .select(decision => {
                        const decisionButton = new Components.DecisionButton(code, decision);
                        decisionButton.text = null;
                        decisionButton.onClick = () => this.onDecision(decisionButton);
                        return decisionButton;
                    }));
                }
                createSDateCell(cell, value) {
                    if (value.Valor)
                        cell.text = value.Valor;
                    else
                        cell.text = value;
                    cell.estilos.agregar("text-align", "center");
                }
                drawMessage(cell, value, code) {
                    const message = new Components.SystemMessage(JSON.parse(value));
                    cell.add(message);
                }
                drawTextBoldCell(cell, value) {
                    const display = new Sol.Control("span");
                    display.text = value;
                    display.estilos.agregar("font-weight", "600");
                    cell.add(display);
                }
                drawProgressBar(cell, value) {
                    if (typeof (value) === "string" && value.indexOf('%') > -1)
                        cell.text = value;
                    else {
                        const progressBar = new Sol.ProgressBar();
                        progressBar.valor = parseFloat(value);
                        cell.add(progressBar);
                    }
                }
                drawTitleDescription(cell, value) {
                    cell.add(new Components.TitleDescriptionDrawer(value));
                }
                drawRating(cell, value) {
                    const ratingField = new Sol.RatingField();
                    ratingField.value = value;
                    ratingField.readonly = true;
                    cell.add(ratingField);
                }
                drawColeredText(cell, value) {
                    const display = new Sol.Control("span");
                    display.text = value.Text;
                    if (value.Color)
                        display.estilos.definir("color", value.Color);
                    if (value.BackColor)
                        display.estilos.definir("background-color", value.BackColor);
                    if (value.UseSolIcon)
                        display.css.add("sol_i");
                    cell.add(display);
                }
                drawUrlViewer(cell, value) {
                    const loup = new Sol.Button();
                    loup.imageCode = "&#xf002;";
                    loup.onClick = () => window.open(value, "_blank");
                    cell.add(loup);
                }
                insertCollectionEditor(cell, value, code, info) {
                    var _a, _b, _c, _d, _e, _f;
                    const selector = new Components.CollectionSelector();
                    selector.isPerson = (_a = info.DrawerSettings) === null || _a === void 0 ? void 0 : _a.isPerson;
                    selector.options = info.Options;
                    selector.clase = (_b = info.DrawerSettings) === null || _b === void 0 ? void 0 : _b.className;
                    selector.codigo = code;
                    selector.value = value;
                    selector.propertyName = info.PropertyName;
                    selector.configuration =
                        {
                            AllowAddNew: (_c = info.DrawerSettings) === null || _c === void 0 ? void 0 : _c.allowAddNew,
                            AllowRemove: (_d = info.DrawerSettings) === null || _d === void 0 ? void 0 : _d.allowRemove,
                            DynamicResults: (_e = info.DrawerSettings) === null || _e === void 0 ? void 0 : _e.dynamicResults,
                            IsColorable: (_f = info.DrawerSettings) === null || _f === void 0 ? void 0 : _f.isColorable
                        };
                    selector.onChanged = () => {
                        if (this.onInlineEditorChanged)
                            this.onInlineEditorChanged(selector, true);
                    };
                    cell.text = "";
                    cell.clickToEdit = false;
                    cell.add(selector);
                }
                drawIconCounter(cell, info) {
                    if (!info.Value)
                        return;
                    cell.css.add("sol_message_counter");
                    const container = new Sol.Control();
                    container.addCtr(info.IconCode, null, "i");
                    container.addCtr(info.Value < 100 ? info.Value.toString() : "99+", null, "span");
                    container.tip = info.Tip;
                    cell.add(container);
                }
                drawParagraph(cell, text) {
                    cell.addCtr(text, "sol_p", 'p');
                }
                drawEntity(cell, value) {
                    const wrapper = new Sol.Control();
                    wrapper.css.add("sol_tabla_entity_pic");
                    wrapper.add(new Web.EntityPicture(value.Valor));
                    wrapper.addCtr(value.Campo, null, "span");
                    cell.add(wrapper);
                }
            }
            Components.Grid = Grid;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let GridRowType;
            (function (GridRowType) {
                GridRowType[GridRowType["Data"] = 0] = "Data";
                GridRowType[GridRowType["Subgroup"] = 1] = "Subgroup";
            })(GridRowType = Components.GridRowType || (Components.GridRowType = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class GridRow extends Sol.Control {
                constructor() {
                    super("tr");
                    this.code = 0;
                    this.editors = new Sol.List();
                    this.rowType = Components.GridRowType.Data;
                }
                get cells() { return this.controls.cast(); }
                get isEmpty() { return !this.code; }
                createCheckCell() {
                    let checkCell = new Components.CheckCell();
                    this.add(checkCell);
                    this.check = checkCell.check;
                    this.check.onChange = () => {
                        if (this.onRowChecked)
                            this.onRowChecked(this.code, this.check.checked);
                    };
                }
                createDeleteCell() {
                    var deleteCell = new Components.GridCell();
                    deleteCell.estilos.agregar("text-align", "center");
                    this.add(deleteCell);
                    return deleteCell;
                }
                configureTotal() {
                    let approvedCheck = this.getEditor("Approved");
                    let totalField = this.getEditor("Total");
                    let quantityField = this.getEditor("Quantity") || this.getEditor("CurrentQuantity");
                    let priceField = this.getEditor("Price");
                    let taxesField = this.getEditor("Taxes");
                    let otherField = this.getEditor("Other");
                    if (quantityField)
                        quantityField.onModified = () => this.calculateTotal(totalField, quantityField, priceField, taxesField, otherField);
                    if (priceField)
                        priceField.onChange = () => this.calculateTotal(totalField, quantityField, priceField, taxesField, otherField);
                    if (taxesField)
                        priceField.onChange = () => this.calculateTotal(totalField, quantityField, priceField, taxesField, otherField);
                    if (otherField)
                        priceField.onChange = () => this.calculateTotal(totalField, quantityField, priceField, taxesField, otherField);
                    if (approvedCheck)
                        approvedCheck.onChange = () => this.totalChanged();
                    if (totalField)
                        totalField.onChange = () => this.totalChanged();
                }
                getCellByPropertyName(propertyName) {
                    return this.cells.that(cl => cl.columnInfo && cl.columnInfo.PropertyName == propertyName);
                }
                getEditor(propertyName) {
                    return this.editors.that(e => e.propertyName === propertyName);
                }
                getDataByPropertyName(propertyName) {
                    return this.rowData.that(d => d.Campo == propertyName).Valor;
                }
                toControl() { return this; }
                calculateTotal(totalField, quantityField, priceField, taxesField, otherField) {
                    let total = quantityField.numericValue * priceField.numericValue;
                    if (taxesField)
                        total += taxesField.numericValue;
                    if (otherField)
                        total += otherField.numericValue;
                    totalField.numericValue = total;
                    this.totalChanged();
                }
                totalChanged() {
                    if (this.onTotalChanged)
                        setTimeout(() => this.onTotalChanged(), 300);
                }
            }
            Components.GridRow = GridRow;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class FileOptions extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.accessibilitySucessMessage = new Sol.ScreenMessage();
                    this.form = new Sol.Form();
                    this.fieldGrid = new Web.Components.Grid();
                    this.positionCombo = new Sol.Combo();
                }
                build() {
                    super.build();
                    var model = this.model;
                    this.screenCaption = model.Title;
                    this.css.add("sol_field_options");
                    this.initializeTitle();
                    this.initializeForm();
                }
                initializeTitle() {
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                }
                initializeForm() {
                    var model = this.model;
                    var fields = Sol.List.from(model.Fields);
                    const totalPositionWrapper = new Sol.FieldWrapper();
                    const positionLabel = new Sol.Label();
                    positionLabel.text = "Totalization bar position:";
                    totalPositionWrapper.add(positionLabel);
                    this.positionCombo.loadOptions([{ Code: "0", Description: "Bottom" }, { Code: "1", Description: "Top" }]);
                    this.positionCombo.selectedCode = model.TotalizationBarPosition.toString();
                    totalPositionWrapper.add(this.positionCombo);
                    this.form.add(totalPositionWrapper);
                    const fieldsLabel = new Sol.Label();
                    fieldsLabel.css.add("sol_detalles_complex_title");
                    fieldsLabel.text = Sol.Environment.resources.campos_disponibles + ':';
                    this.form.add(fieldsLabel);
                    this.fieldGrid.readonly = false;
                    this.fieldGrid.showChecks = false;
                    this.fieldGrid.showVerticalLines = true;
                    this.fieldGrid.fixedRows = false;
                    this.fieldGrid.allowDelete = false;
                    this.fieldGrid.onRowCreated = row => this.fieldRowCreated(row);
                    this.fieldGrid.columns = Sol.List.from([
                        {
                            Title: Sol.Environment.resources.activo,
                            DataType: "SBoolean",
                            PropertyName: "Available",
                            Alignment: Sol.Alignment.Center,
                            ShowTitle: true,
                            Visible: true,
                            EditorModel: {
                                DataType: "SBoolean",
                                PropertyName: "Available",
                                Title: "",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        },
                        {
                            Alignment: Sol.Alignment.Left,
                            Title: Sol.Environment.resources.name,
                            DataType: "SText",
                            PropertyName: "Nombre",
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: "Property",
                            DataType: "SText",
                            Alignment: Sol.Alignment.Left,
                            PropertyName: "Field",
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Alignment: Sol.Alignment.Left,
                            Title: "EditorKey",
                            DataType: "SText",
                            PropertyName: "EditorKey",
                            ShowTitle: true,
                            Visible: true,
                            EditorModel: {
                                DataType: "SText",
                                MaxLength: 35,
                                PropertyName: "EditorKey",
                                Title: "",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        },
                        {
                            Alignment: Sol.Alignment.Left,
                            Title: "FilterEditorKey",
                            DataType: "SText",
                            PropertyName: "FilterEditorKey",
                            ShowTitle: true,
                            Visible: true,
                            EditorModel: {
                                DataType: "SText",
                                MaxLength: 35,
                                PropertyName: "FilterEditorKey",
                                Title: "",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        },
                        {
                            Alignment: Sol.Alignment.Center,
                            Title: "FilterPosition",
                            DataType: "SInteger",
                            PropertyName: "FilterPosition",
                            ShowTitle: true,
                            Visible: true,
                            EditorModel: {
                                DataType: "SInteger",
                                PropertyName: "FilterPosition",
                                Title: "",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        },
                        {
                            Title: "FilterVisible",
                            DataType: "SBoolean",
                            PropertyName: "FilterVisible",
                            Alignment: Sol.Alignment.Center,
                            ShowTitle: true,
                            Visible: true,
                            EditorModel: {
                                DataType: "SBoolean",
                                PropertyName: "FilterVisible",
                                DefaultValue: true,
                                Title: "",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        },
                        {
                            Alignment: Sol.Alignment.Left,
                            Title: "Mask",
                            DataType: "SText",
                            PropertyName: "Mask",
                            ShowTitle: true,
                            Visible: true,
                            EditorModel: {
                                DataType: "SText",
                                MaxLength: 25,
                                PropertyName: "Mask",
                                Title: "",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        },
                        {
                            Alignment: Sol.Alignment.Center,
                            Title: "Position",
                            DataType: "SInteger",
                            PropertyName: "Position",
                            ShowTitle: true,
                            Visible: true,
                            EditorModel: {
                                DataType: "SInteger",
                                PropertyName: "Position",
                                Title: "",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        },
                        {
                            Alignment: Sol.Alignment.Left,
                            Title: "Required",
                            DataType: "SBoolean",
                            PropertyName: "IsRequired",
                            ShowTitle: true,
                            Visible: true,
                            EditorModel: {
                                DataType: "SBoolean",
                                PropertyName: "IsRequired",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        }
                    ]);
                    this.fieldGrid.buildHeader();
                    fields.forEach(field => this.fieldGrid.addRow([
                        { Campo: "Available", Valor: field.Available },
                        { Campo: "Nombre", Valor: field.FieldName },
                        { Campo: "Field", Valor: field.Field },
                        { Campo: "PropertyName", Valor: field.PropertyName },
                        { Campo: "Configurable", Valor: field.Configurable },
                        { Campo: "EditorKey", Valor: field.EditorKey },
                        { Campo: "FilterEditorKey", Valor: field.FilterEditorKey },
                        { Campo: "FilterPosition", Valor: field.FilterPosition },
                        { Campo: "FilterVisible", Valor: field.FilterVisible },
                        { Campo: "Mask", Valor: field.Mask },
                        { Campo: "Position", Valor: field.Position },
                        { Campo: "IsRequired", Valor: field.IsRequired },
                        { Campo: "RequiredOptionEnabled", Valor: field.RequiredOptionEnabled }
                    ]));
                    this.form.add(this.fieldGrid);
                    this.form.onCancel = () => Web.System.screens.closeCurrentScreen();
                    this.form.onSave = () => this.saveOptions();
                    this.add(this.form);
                }
                fieldRowCreated(row) {
                    if (!row.getDataByPropertyName("Configurable"))
                        row.getEditor("Available").value = true;
                    row.getEditor("Available").readonly = !row.getDataByPropertyName("Configurable");
                    row.getEditor("IsRequired").readonly = !row.getDataByPropertyName("RequiredOptionEnabled");
                }
                saveOptions() {
                    this.accessibilitySucessMessage.visible = false;
                    var model = this.model;
                    var fields = this.fieldGrid
                        .rows
                        .select(row => ({
                        Field: row.getDataByPropertyName("PropertyName"),
                        Available: row.getEditor("Available").value,
                        EditorKey: row.getEditor("EditorKey").value,
                        FilterEditorKey: row.getEditor("FilterEditorKey").value,
                        FilterPosition: row.getEditor("FilterPosition").value,
                        FilterVisible: row.getEditor("FilterVisible").value,
                        Mask: row.getEditor("Mask").value,
                        Position: row.getEditor("Position").value,
                        Activatable: !row.getEditor("Available").readonly,
                        IsRequired: row.getEditor("IsRequired").value
                    }))
                        .toArray();
                    const saveRequest = {
                        ClassName: model.ClassName,
                        Fields: fields,
                        TotalizationBarPosition: parseInt(this.positionCombo.selectedCode)
                    };
                    Web.System.exec("nlskd23jor", "ConfigureFileScreen", saveRequest, () => {
                        Web.System.screens.closeCurrentScreen();
                        if (this.onSaved)
                            this.onSaved(this);
                    });
                }
            }
            Screens.FileOptions = FileOptions;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class FileTool extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.form = new Sol.Form();
                    this.fields = new Sol.List();
                    this.results = new Sol.Control();
                    this.resultsLabel = new Sol.Label();
                }
                get myModel() { return this.model; }
                focus() { if (this.fields.hasItems())
                    setTimeout(() => this.fields.first().foco(), 300); }
                getEditor(propertyName) {
                    return this.form.getEditor(propertyName);
                }
                build() {
                    super.build();
                    this.screenCaption = this.myModel.ToolName;
                    this.css.add("sol_file_tool");
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.myModel.ToolName;
                    this.add(screenTitle);
                    this.form.cancelButton.text = Sol.Environment.resources.cerrar;
                    this.form.onCancel = () => Web.System.screens.closeCurrentScreen();
                    this.form.onSave = () => this.runTool();
                    if (this.myModel.OkCaption)
                        this.form.okButton.text = this.myModel.OkCaption;
                    if (this.myModel.CloseCaption)
                        this.form.cancelButton.text = this.myModel.CloseCaption;
                    this.add(this.form);
                    if (this.myModel.Description) {
                        var descriptionText = new Sol.Control("p");
                        descriptionText.text = this.myModel.Description;
                        this.form.add(descriptionText);
                    }
                    this.fields = Web.Editors.fillForm(this.myModel.Fields, this.form, null, Screens.FormState.Insertion, null, 0).fields;
                    this.resultsLabel.text = Sol.Environment.resources.resultados + ':';
                    this.resultsLabel.visible = false;
                    this.add(this.resultsLabel);
                    this.results.css.add("sol_file_tool_results");
                    this.results.visible = false;
                    this.add(this.results);
                }
                runTool() {
                    let inputs = this.fields
                        .select(cp => ({ Campo: cp.propertyName, Valor: cp.value }))
                        .toArray();
                    let runToolRequest = {
                        className: this.model.ToolClass,
                        inputs: inputs,
                        contextClass: this.fileScreen.classType,
                        contextCode: this.fileScreen.anchorageCode,
                        filters: this.fileScreen.filters
                    };
                    if (this.myModel.IsLargeProcess)
                        Web.System.execLarge("n954tvg7", "Run", runToolRequest, e => this.processResponse(e), () => this.form.workComplete());
                    else
                        Web.System.exec("n954tvg7", "Run", runToolRequest, e => this.processResponse(e));
                }
                processResponse(model) {
                    this.form.workComplete();
                    if (!model.Fail && this.myModel.CustomActionName) {
                        var toolAction = eval("new Sol.Web.Actions." + this.myModel.CustomActionName + "()");
                        toolAction.fileScreen = this.fileScreen;
                        toolAction.toolScreen = this;
                        toolAction.processResponse(model);
                    }
                    else {
                        var response = model;
                        this.writeResponse(response.Message || response.ErrorMessage, response.Fail);
                        if (!response.Fail) {
                            this.fields.forEach(f => f.clear());
                            this.fields.first().foco();
                            if (!response.Message) {
                                Web.System.screens.closeCurrentScreen();
                                Web.System.screens.currentScreen.refreshSearch();
                            }
                        }
                    }
                }
                writeResponse(text, error) {
                    this.results.visible = true;
                    this.resultsLabel.visible = true;
                    var responseControl = new Sol.Control();
                    responseControl.text = text;
                    if (error)
                        responseControl.estilos.agregar("color", "#8e0b1f");
                    this.results.controls.insert(0, responseControl);
                    this.form.workComplete();
                }
            }
            Screens.FileTool = FileTool;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class LicitationItemSelector extends Web.Components.DataCombo {
                constructor() {
                    super();
                    this.displayProperty = "ItemTitle";
                    this.onBeforeRefresh = () => this.setFilters();
                }
                setFilters() {
                    const code = Web.System.screens.screens.that(sc => sc instanceof Web.Screens.DetailsScreen).code;
                    this.preFilters = [{ PropertyName: "LicitationBatch$Licitation", FilterType: "SInteger", FilterValue: code }];
                }
            }
            Licitations.LicitationItemSelector = LicitationItemSelector;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class LicitationBatchSelector extends Web.Components.DataCombo {
                constructor() {
                    super();
                    this.displayProperty = "BatchTitle";
                    this.onBeforeRefresh = () => this.setFilters();
                }
                setFilters() {
                    const code = Web.System.screens.screens.that(sc => sc instanceof Web.Screens.DetailsScreen).code;
                    this.preFilters = [{ PropertyName: "Licitation", FilterType: "SInteger", FilterValue: code }];
                }
            }
            Licitations.LicitationBatchSelector = LicitationBatchSelector;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class LicitationChatEditor extends Web.Components.ListView {
                constructor() {
                    super();
                    this.code = 0;
                    this.configuration = Sol.List.from([
                        { property: "Nombre", priority: Web.Components.ListViewFieldPriority.High, position: Web.Components.ListViewFieldPosition.Left, loadable: true },
                        { property: "Date", priority: Web.Components.ListViewFieldPriority.Normal, position: Web.Components.ListViewFieldPosition.Left, loadable: true },
                        { property: "Time", priority: Web.Components.ListViewFieldPriority.Normal, position: Web.Components.ListViewFieldPosition.Left, loadable: true },
                        { property: "Message", priority: Web.Components.ListViewFieldPriority.Descriptive, position: Web.Components.ListViewFieldPosition.Left, loadable: true, lineBreak: true }
                    ]);
                    this.className = "Solarium.Government.Licitations.LicitationChat, Solarium.Government.Licitations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.orderByProperty = "Date";
                }
                build() {
                    super.build();
                    this.filters = [{
                            FilterType: "SInterger",
                            PropertyName: "Licitation",
                            FilterValue: this.code
                        }];
                    this.search();
                }
                clear() { }
                foco() { }
                toControl() { return this; }
                validate() { return null; }
            }
            Licitations.LicitationChatEditor = LicitationChatEditor;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class StatusDisplay extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.display = new Sol.Control();
                    this.history = new Components.HistoryButton();
                    this._className = "Solarium.Commercial.Negocio`3[[Solarium.Empresa, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Solarium.Commercial.Cliente, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Solarium.Commercial.StatusProcesoComercial, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.readonly = true;
                    this.isComplex = false;
                }
                get className() { return this._className; }
                set className(value) {
                    this._className = value;
                    this.history.className = value;
                }
                set negocioID(value) { this.history.code = value; }
                ;
                isEmpty() { return false; }
                get status() { return this.display.text; }
                set status(valor) { this.display.text = valor; }
                validate() { return null; }
                get value() { return this._valor; }
                set value(valor) {
                    this._valor = valor;
                    this.status = valor.Campo;
                }
                get defaultValue() { return this.value; }
                set defaultValue(valor) { this.value = valor; }
                build() {
                    const wrapper = new Sol.Control();
                    this.css.add("sol_texto_status");
                    this.display.css.add("box");
                    wrapper.add(this.display);
                    this.history.propertyName = "Status";
                    this.history.className = this.className;
                    wrapper.add(this.history);
                    this.add(wrapper);
                    super.build();
                }
                toControl() { return this; }
                foco() { }
                clear() { }
            }
            Components.StatusDisplay = StatusDisplay;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class HistoryButton extends Sol.Control {
                constructor() {
                    super("span");
                    this.isLoaded = false;
                    this.historialList = new Components.ListView();
                    this.css.add("sol_history_button");
                    const historialButton = new Sol.Button();
                    historialButton.imageCode = '&#xf017;';
                    historialButton.onClick = () => this.showHistory();
                    this.add(historialButton);
                    this.historialList.css.add("sol_popup");
                    this.historialList.ancho = 350;
                    this.historialList.visible = false;
                    this.historialList.configuration = Sol.List.from([
                        { property: "NewValue", priority: Components.ListViewFieldPriority.Normal, position: Components.ListViewFieldPosition.Left },
                        { property: "ChangeDate", priority: Components.ListViewFieldPriority.Normal, position: Components.ListViewFieldPosition.Right },
                        { property: "LoginName", priority: Components.ListViewFieldPriority.Descriptive, position: Components.ListViewFieldPosition.Left, lineBreak: true },
                        { property: "ElapsedTime", priority: Components.ListViewFieldPriority.Descriptive, position: Components.ListViewFieldPosition.Left },
                        { property: "Description", position: Components.ListViewFieldPosition.Block }
                    ]);
                    this.add(this.historialList);
                }
                showHistory() {
                    if (this.beforeList)
                        this.beforeList();
                    if (!this.code)
                        return;
                    this.historialList.show();
                    if (this.isLoaded)
                        return;
                    let data = {
                        className: this.className,
                        id: this.code,
                        property: this.propertyName,
                        pageNumber: 1,
                        pageCount: 100
                    };
                    Web.System.exec("i3n48smak", "GetPropertyHistory", data, e => {
                        this.historialList.addItems(e.Changes);
                        this.isLoaded = true;
                    });
                }
            }
            Components.HistoryButton = HistoryButton;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let PaymentType;
            (function (PaymentType) {
                PaymentType[PaymentType["notSet"] = 1] = "notSet";
                PaymentType[PaymentType["anteciped"] = 2] = "anteciped";
                PaymentType[PaymentType["cash"] = 3] = "cash";
                PaymentType[PaymentType["time"] = 4] = "time";
                PaymentType[PaymentType["installments"] = 5] = "installments";
            })(PaymentType = Components.PaymentType || (Components.PaymentType = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let PaymentMode;
            (function (PaymentMode) {
                PaymentMode[PaymentMode["notSet"] = 1] = "notSet";
                PaymentMode[PaymentMode["money"] = 2] = "money";
                PaymentMode[PaymentMode["check"] = 3] = "check";
                PaymentMode[PaymentMode["deposit"] = 4] = "deposit";
                PaymentMode[PaymentMode["bankSlip"] = 5] = "bankSlip";
                PaymentMode[PaymentMode["transfer"] = 6] = "transfer";
                PaymentMode[PaymentMode["debitCard"] = 7] = "debitCard";
                PaymentMode[PaymentMode["creditCard"] = 8] = "creditCard";
                PaymentMode[PaymentMode["PIX"] = 9] = "PIX";
                PaymentMode[PaymentMode["voucher"] = 10] = "voucher";
                PaymentMode[PaymentMode["creditAmount"] = 16] = "creditAmount";
            })(PaymentMode = Components.PaymentMode || (Components.PaymentMode = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PaymentTypeChoice extends Sol.MultipleChoice {
                get cardCompanyCombo() { return this.container.getEditor("PaymentCardCompany"); }
                get paymentModeCombo() { return this.container.getEditor("PaymentMode"); }
                get selectedMode() { return parseInt(this.paymentModeCombo.selectedCode); }
                get paymentEditor() { return this.parent.parent.parent; }
                get bankAccountEditor() { return this.container.getEditor("BankAccount"); }
                get bankInfoAccountEditor() { return this.container.getEditor("BankInfoDisplay"); }
                get selectedType() { return this.selectedCode; }
                constructor() {
                    super();
                    this.inlineItems = true;
                    this.onChange.subscribe(() => this.selectFields());
                }
                build() {
                    super.build();
                    this.selectFields();
                    this.configurePaymentEditor();
                    if (this.container.getEditor("ShowFinancialScreen"))
                        this.container.getEditor("ShowFinancialScreen").visible = false;
                }
                calculateDueDate() {
                    var days = this.container.editors.that(cp => cp.propertyName == "TimeInDays").numericValue;
                    var dueDateEditor = this.container.editors.that(cp => cp.propertyName == "DueDate");
                    if (!dueDateEditor || !days)
                        return;
                    var date = this.container.editors.that(cp => cp.propertyName == "BillingDate").dateValue != null ? this.container.editors.that(cp => cp.propertyName == "BillingDate").dateValue : new Date();
                    dueDateEditor.value = date.addDays(days).formatear();
                }
                configurePaymentEditor() {
                    if (this.cardCompanyCombo)
                        this.cardCompanyCombo.parent.visible = false;
                    this.container.editors.that(cp => cp.propertyName == "BillingDate").parent.visible = false;
                    if (this.bankAccountEditor)
                        this.bankAccountEditor.parent.visible = false;
                    this.bankInfoAccountEditor.visible = false;
                    var timeInDaysEditor = this.container.editors.that(cp => cp.propertyName == "TimeInDays");
                    timeInDaysEditor.parent.visible = false;
                    timeInDaysEditor.onChange = () => this.calculateDueDate();
                    timeInDaysEditor.onValueChanged = () => setTimeout(() => this.calculateDueDate(), 150);
                    this.paymentModeCombo.onChange = () => this.paymentModeChanged();
                }
                configurateTemplateMode() {
                    const totalEditor = this.container.getEditor("Total");
                    const dueDateEditor = this.container.getEditor("DueDate");
                    const billingDateEditor = this.container.getEditor("BillingDate");
                    const advancedPaymentDateEditor = this.container.getEditor("AdvancedPayment");
                    const installmentsEditor = this.container.getEditor("Installments");
                    const installmentsDueDateColumn = installmentsEditor.availableColumns.that(i => i.PropertyName == "DueDate");
                    const installmentsAmountColumn = installmentsEditor.availableColumns.that(i => i.PropertyName == "Amount");
                    if (totalEditor)
                        totalEditor.parent.visible = false;
                    if (dueDateEditor)
                        dueDateEditor.parent.visible = false;
                    if (billingDateEditor)
                        billingDateEditor.parent.visible = false;
                    if (advancedPaymentDateEditor)
                        advancedPaymentDateEditor.parent.visible = false;
                    if (installmentsDueDateColumn)
                        installmentsDueDateColumn.Visible = false;
                    if (installmentsAmountColumn)
                        installmentsAmountColumn.Visible = false;
                }
                paymentModeChanged() {
                    var isCarCompanyVisible = Sol.List.from([Components.PaymentMode.debitCard, Components.PaymentMode.creditCard, Components.PaymentMode.voucher]).contains(this.selectedMode);
                    if (this.cardCompanyCombo)
                        this.cardCompanyCombo.parent.visible = isCarCompanyVisible;
                    if (this.bankAccountEditor)
                        this.bankAccountEditor.parent.visible = this.bankAccountEditor.items.count > 1 &&
                            Sol.List.from([Components.PaymentMode.PIX, Components.PaymentMode.transfer, Components.PaymentMode.deposit, Components.PaymentMode.bankSlip]).contains(this.selectedMode) && this.selectedType != Components.PaymentType.notSet;
                    this.bankInfoAccountEditor.visible = false;
                    if (this.bankAccountEditor && this.bankAccountEditor.parent.visible)
                        this.bankAccountEditor.refresh(() => {
                            var _a;
                            if (this.bankAccountEditor.isEmpty() && this.bankAccountEditor.items.count == 2) {
                                this.bankAccountEditor.selectedCode = (_a = this.bankAccountEditor.items.last().code) === null || _a === void 0 ? void 0 : _a.toString();
                                this.bankAccountEditor.onChange();
                            }
                            if (!this.bankAccountEditor.isEmpty())
                                this.paymentEditor.showBankInfo(parseInt(this.bankAccountEditor.selectedCode));
                        });
                }
                selectFields() {
                    var _a, _b, _c;
                    this.paymentModeCombo.parent.visible = this.selectedType != Components.PaymentType.notSet;
                    const showBankControls = this.selectedType != Components.PaymentType.notSet && this.paymentEditor.isBankOperation(this.selectedMode);
                    if (this.bankAccountEditor)
                        this.bankAccountEditor.parent.visible = showBankControls;
                    var dueDateEditor = this.container.editors.that(cp => cp.propertyName == "DueDate");
                    dueDateEditor.parent.visible = this.selectedType == Components.PaymentType.time;
                    var advancedPaymentEditor = this.container.editors.that(cp => cp.propertyName == "AdvancedPayment");
                    advancedPaymentEditor.parent.visible = this.selectedType == Components.PaymentType.anteciped;
                    const installmentsEditor = this.container.editors.that(cp => cp.propertyName == "Installments");
                    const installmentsCountEditor = this.container.editors.that(cp => cp.propertyName == "InstallmentsCount");
                    const calcInstallmentsButton = this.container.editors.that(cp => cp.propertyName == "InstallmentsButton");
                    const installmentsVisible = this.selectedType == Components.PaymentType.installments;
                    installmentsCountEditor.parent.visible = installmentsVisible;
                    calcInstallmentsButton.visible = installmentsVisible;
                    calcInstallmentsButton.installmentsEditor = installmentsEditor;
                    calcInstallmentsButton.myEditor = this.paymentEditor;
                    this.container.toControl().controls.item(this.container.toControl().controls.indice(installmentsEditor) - 1).visible = installmentsVisible;
                    installmentsEditor.toControl().visible = installmentsVisible;
                    let lazyBillingEditor = this.container.editors.that(cp => cp.propertyName == "LazyBilling");
                    if (lazyBillingEditor)
                        lazyBillingEditor.visible = installmentsVisible;
                    const advanceValueEditor = this.container.editors.that(cp => cp.propertyName == "Advance");
                    const advancePaymentMode = this.container.getEditor("AdvancePaymentMode");
                    const advanceFieldsVisible = this.selectedType != Components.PaymentType.notSet &&
                        this.selectedType != Components.PaymentType.anteciped &&
                        ((_a = this.paymentEditor.configuration) === null || _a === void 0 ? void 0 : _a.ShowAdvancedAmountOptions);
                    const advanceWrapper = advanceValueEditor.parent;
                    this.container.toControl().controls.item(this.container.toControl().controls.indice(advanceWrapper) - 1).visible = advanceFieldsVisible;
                    advanceWrapper.visible = advanceFieldsVisible;
                    advancePaymentMode.parent.visible = advanceFieldsVisible;
                    const totalsVisible = this.selectedType != Components.PaymentType.notSet && !((_b = this.paymentEditor.configuration) === null || _b === void 0 ? void 0 : _b.HideTotalGroup);
                    var totalEditor = this.container.editors.that(cp => cp.propertyName == "Total");
                    totalEditor.parent.visible = totalsVisible;
                    this.container.toControl().controls.item(this.container.toControl().controls.indice(totalEditor.parent) - 1).visible = totalsVisible;
                    const remainingEditor = this.container.getEditor("RemainingBalance");
                    remainingEditor.parent.visible = totalsVisible && ((_c = this.paymentEditor.configuration) === null || _c === void 0 ? void 0 : _c.ShowAdvancedAmountOptions);
                    if (this.paymentModeCombo.controls.item(Components.PaymentMode.debitCard - 1))
                        this.paymentModeCombo.controls.item(Components.PaymentMode.debitCard - 1).visible = this.selectedType != Components.PaymentType.time;
                    if (this.paymentModeCombo.controls.item(Components.PaymentMode.voucher - 1))
                        this.paymentModeCombo.controls.item(Components.PaymentMode.voucher - 1).visible = this.selectedType != Components.PaymentType.time;
                    var billingDateEditor = this.container.editors.that(cp => cp.propertyName == "BillingDate");
                    billingDateEditor.parent.visible = this.selectedType != Components.PaymentType.notSet;
                    if (this.selectedType == Components.PaymentType.installments && installmentsCountEditor.numericValue != installmentsEditor.rowCount)
                        this.paymentEditor.calculateInstallments();
                    var timeInDaysEditor = this.container.editors.that(cp => cp.propertyName == "TimeInDays");
                    timeInDaysEditor.parent.visible = this.selectedType == Components.PaymentType.time;
                    if (this.paymentEditor && this.paymentEditor.configuration && this.paymentEditor.configuration.TemplateMode)
                        this.configurateTemplateMode();
                    if (this.bankAccountEditor)
                        this.paymentEditor.bankAccountInfo.visible = this.selectedType != Components.PaymentType.notSet && !this.bankAccountEditor.isEmpty();
                }
            }
            Components.PaymentTypeChoice = PaymentTypeChoice;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class BirthdateField extends Sol.Control {
                constructor() {
                    super();
                    this.dateContainer = new Sol.Control();
                    this.dateLabel = new Sol.Label();
                    this.dateField = new Sol.DateField();
                    this.ageContainer = new Sol.Control();
                    this.ageLabel = new Sol.Label();
                    this.ageField = new Sol.Field();
                    this.isComplex = false;
                    this.css.add("sol_birthdate");
                    this.dateLabel.text = Sol.Environment.resources.nacimiento;
                    this.dateLabel.editor = this.dateField;
                    this.dateContainer.add(this.dateLabel);
                    this.dateField.maxValue = new Date();
                    this.dateContainer.add(this.dateField);
                    this.add(this.dateContainer);
                    this.ageLabel.text = Sol.Environment.resources.edad;
                    this.ageLabel.editor = this.ageField;
                    this.ageContainer.add(this.ageLabel);
                    this.ageField.readonly = true;
                    this.ageField.ancho = 50;
                    this.ageField.alignment = Sol.Alignment.Center;
                    this.ageContainer.add(this.ageField);
                    this.add(this.ageContainer);
                }
                get value() { return this.dateField.value; }
                set value(v) {
                    this.dateField.value = v;
                    this.calculateAge();
                }
                toControl() { return this; }
                ;
                isEmpty() { return this.dateField.isEmpty(); }
                foco() { this.dateField.foco(); }
                ;
                clear() { this.dateField.clear(); }
                ;
                validate() { return null; }
                build() {
                    super.build();
                    this.dateField.required = this.required;
                    this.dateField.readonly = this.readonly;
                    var eventManager = setTimeout(() => {
                        if (this.html) {
                            this.html.onchange = e => this.calculateAge();
                            clearTimeout(eventManager);
                        }
                    }, 100);
                }
                calculateAge() {
                    var date = this.dateField.dateValue;
                    if (!date) {
                        this.ageField.clear();
                        return;
                    }
                    var age = date.getAge();
                    this.ageField.value = age || age == 0 ? age.toString() : "";
                }
            }
            Components.BirthdateField = BirthdateField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DualCombo extends Sol.Control {
                constructor() {
                    super("span");
                    this.mainCombo = new Components.DataCombo();
                    this.subCombo = new Components.DataCombo();
                    this.subLabel = new Sol.Label();
                    this.mainLabel = new Sol.Label();
                    this.onValueModified = new Sol.EventHandler();
                    this.onSet = new Sol.EventHandler();
                    this.onFocus = new Sol.EventHandler();
                    this.onLeave = new Sol.EventHandler();
                    this.onMainComboLoaded = new Sol.EventHandler();
                    const mainWrapper = new Sol.FieldWrapper();
                    this.mainLabel.editor = this.mainCombo;
                    mainWrapper.add(this.mainLabel);
                    this.mainCombo.onValueModified.subscribe(() => this.mainComboChanged());
                    mainWrapper.add(this.mainCombo);
                    this.add(mainWrapper);
                    const subWrapper = new Sol.FieldWrapper();
                    this.subLabel.editor = this.subCombo;
                    subWrapper.add(this.subLabel);
                    subWrapper.add(this.subCombo);
                    this.add(subWrapper);
                }
                get onChange() { return this.subCombo.onChange; }
                set onChange(value) { this.subCombo.onChange = value; }
                get selectedCode() { return this.subCombo.selectedCode; }
                get readonly() { return this._readonly; }
                set readonly(value) {
                    this._readonly = value;
                    this.subCombo.readonly = value;
                    this.mainCombo.readonly = value;
                }
                get errorState() { return this.mainCombo.errorState; }
                set errorState(value) {
                    this._errorState = value;
                    this.subCombo.errorState = value;
                    this.mainCombo.errorState = value;
                }
                get value() { return this.getValue(); }
                set value(v) { this.setValue(v); }
                getValue() { return this.subCombo.value; }
                setValue(v) {
                    this.subCombo.value = v;
                    if (!this.subCombo.isEmpty())
                        this.loadMainCombo();
                }
                foco() { this.mainCombo.foco(); }
                isEmpty() { return this.subCombo.isEmpty(); }
                toControl() { return this; }
                validate() { return null; }
                build() {
                    this.mainLabel.text = this.mainCaption;
                    this.mainCombo.caption = this.mainCaption;
                    this.mainCombo.className = this.mainClassName;
                    this.subLabel.text = this.subCaption;
                    this.subCombo.caption = this.subCaption;
                    this.subCombo.className = this.subClassName;
                    this.subCombo.displayProperty = this.subDisplayProperty || this.subCombo.displayProperty;
                    this.subCombo.required = this.required;
                    this.mainCombo.required = this.required;
                    this.mainCombo.displayProperty = this.mainDisplayProperty || this.mainCombo.displayProperty;
                    this.mainCombo.refresh(() => this.mainComboChanged());
                    if (this.onKeyDown)
                        this.html.onkeydown = e => this.onKeyDown(e);
                    super.build();
                }
                clear() { }
                registerEvents() {
                    super.registerEvents();
                    this.onValueModified.connect(this, "change");
                    this.onFocus.connect(this, "focus");
                    this.onLeave.connect(this, "blur");
                    if (!this.disableChangeEventOnSetValue)
                        this.onSet.invoke();
                }
                loadMainCombo() {
                    const data = {
                        className: this.subClassName,
                        code: parseInt(this.subCombo.selectedCode),
                        subtype: false,
                        propertyList: [this.associativeProperty]
                    };
                    Web.System.exec("sn9d23vs7d", "Load", data, model => {
                        var _a;
                        if (model.Fail)
                            return;
                        const values = Sol.List.from(model.Data);
                        this.mainCombo.selectedCode = (_a = values.that(v => v.Campo == this.associativeProperty)) === null || _a === void 0 ? void 0 : _a.Valor.Valor;
                        this.onMainComboLoaded.invoke();
                    });
                }
                mainComboChanged() {
                    this.subCombo.filters = Sol.List.from([{ FilterType: "SInteger", PropertyName: this.associativeProperty, FilterValue: this.mainCombo.selectedCode }]);
                    this.subCombo.clearOptions();
                    if (this.mainCombo.isEmpty())
                        return;
                    this.subCombo.refresh();
                }
            }
            Components.DualCombo = DualCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let TotalizationBarPosition;
            (function (TotalizationBarPosition) {
                TotalizationBarPosition[TotalizationBarPosition["Bottom"] = 0] = "Bottom";
                TotalizationBarPosition[TotalizationBarPosition["Top"] = 1] = "Top";
            })(TotalizationBarPosition = Screens.TotalizationBarPosition || (Screens.TotalizationBarPosition = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let FormState;
            (function (FormState) {
                FormState[FormState["Insertion"] = 0] = "Insertion";
                FormState[FormState["Edition"] = 1] = "Edition";
            })(FormState = Screens.FormState || (Screens.FormState = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Forms;
        (function (Forms) {
            class BaseForm {
                checkFieldVisibility(info, state) {
                    return info.Visibility == Sol.FieldVisibility.Always ||
                        info.Visibility == Sol.FieldVisibility.Hidden ||
                        (info.Visibility == Sol.FieldVisibility.HiddenIfReadonlyAndEmpty && state == Web.Screens.FormState.Edition) ||
                        (info.Visibility == Sol.FieldVisibility.OnlyEditing && state == Web.Screens.FormState.Edition) ||
                        (info.Visibility == Sol.FieldVisibility.OnlyInserting && state == Web.Screens.FormState.Insertion);
                }
                getEditor(fieldModel, form, contextClass, code, structure) {
                    let editor = Web.Editors.createField(fieldModel, contextClass, code, structure);
                    if (!editor)
                        return null;
                    editor.fieldModel = fieldModel;
                    editor.container = form;
                    editor.filterType = fieldModel.DataType;
                    editor.group = fieldModel.Group;
                    if (fieldModel.Savable)
                        editor.savable = true;
                    if (fieldModel.Visibility == Sol.FieldVisibility.Hidden)
                        editor.visible = false;
                    Sol.List.from(fieldModel.Behaviours).forEach(b => {
                        const behaviour = eval("new Sol.Web.Behaviours." + b.BehaviourName + "()");
                        behaviour.apply(form, editor, b.Configuration, code);
                    });
                    if (!code && editor instanceof Web.Components.DataCombo && editor.autoLoad)
                        setTimeout(() => editor.refresh(), 300);
                    return editor;
                }
                getLabel(editor, fieldModel, structure = [], disableMinimizedControls = false) {
                    if (fieldModel.Title &&
                        !(editor instanceof Web.Components.DualCombo) &&
                        !(editor instanceof Web.Components.BirthdateField) &&
                        !(editor instanceof Sol.Check) &&
                        !(editor instanceof Web.Components.PaymentTypeChoice) &&
                        !(editor instanceof Web.Components.Uploads.ImageField && editor.flotable)) {
                        const label = new Sol.Label();
                        label.text = fieldModel.Title;
                        label.largeDescription = fieldModel.LargeDescription;
                        editor.myLabel = label;
                        label.editor = editor;
                        if (fieldModel.Visibility == Sol.FieldVisibility.Hidden)
                            label.visible = false;
                        if (editor.isComplex)
                            label.css.add("sol_detalles_complex_title");
                        else if (editor instanceof Sol.MultipleChoice)
                            label.css.add("sol_detalles_complex_title");
                        else if (!label.text.endsWith('?'))
                            label.text += ':';
                        label.minimizable = !disableMinimizedControls &&
                            editor.isComplex &&
                            !fieldModel.Required &&
                            fieldModel.PropertyName != "Destinatario" &&
                            !editor.nonMinimizable;
                        structure.length > 2;
                        label.expanded = !label.minimizable || !!editor.defaultValue;
                        if (editor.isListComponent)
                            editor.onCountChanged.subscribe(count => label.setCount(count));
                        if (!editor.useWrapper)
                            label.estilos.agregar("clear", "both");
                        return label;
                    }
                    return null;
                }
                getFieldsForThisState(structure, state) {
                    return Sol.List.from(structure)
                        .where(fieldModel => this.checkFieldVisibility(fieldModel, state));
                }
                placeEditor(editor, baseControl, code, contextClass) {
                    const field = editor.toControl();
                    baseControl.add(field);
                    if (editor.fieldModel.TextAfter)
                        baseControl.addCtr(editor.fieldModel.TextAfter, "sol_detalles_after", "span");
                    if (field instanceof Sol.Check && field.breakInForm)
                        baseControl.add(new Sol.Control());
                    if (field instanceof Sol.PhonesEditor)
                        baseControl.add(new Sol.LineBreak());
                    if (editor.isComplex)
                        field.css.add("sol_detalles_complex");
                    if (editor.fieldModel.ShowHistory) {
                        const historyButton = new Web.Components.HistoryButton();
                        historyButton.code = code;
                        historyButton.propertyName = editor.propertyName;
                        historyButton.className = contextClass;
                        baseControl.add(historyButton);
                    }
                }
                placeEditorInToolbar(editor, fieldModel, toolbar) {
                    const field = editor.toControl();
                    const baseControl = editor.useWrapper ? new Sol.FieldWrapper() : toolbar;
                    if (field instanceof Sol.Button)
                        field.type = Sol.ButtonType.Custom;
                    if (editor.useWrapper) {
                        const label = this.getLabel(editor, fieldModel);
                        baseControl.add(label);
                    }
                    else if (fieldModel.Title)
                        field.text = fieldModel.Title;
                    baseControl.add(field);
                    if (editor.useWrapper)
                        toolbar.add(baseControl);
                }
            }
            Forms.BaseForm = BaseForm;
        })(Forms = Web.Forms || (Web.Forms = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Forms;
        (function (Forms) {
            class CommonForm extends Forms.BaseForm {
                fillForm(structure, form, toolbar, state, contextClass, code, disableMinimizedControls, totalizationBarPos) {
                    var _a, _b;
                    try {
                        const totalizationBar = new Sol.Control();
                        totalizationBar.css.add("sol_totalization_bar");
                        var fields = new Sol.List();
                        var labels = new Sol.List();
                        var groups = new Sol.List();
                        var currentGroup;
                        var currentGroupDisplay;
                        var currentGroupWrapper;
                        this.getFieldsForThisState(structure, state)
                            .orderBy(fieldModel => { var _a; return ((_a = fieldModel.Group) === null || _a === void 0 ? void 0 : _a.Position) || 0; })
                            .forEach(fieldModel => {
                            var _a;
                            var editor = this.getEditor(fieldModel, form, contextClass, code, structure);
                            if (!editor)
                                return;
                            var field = editor.toControl();
                            var wrapper = new Sol.FieldWrapper();
                            var useWrapper = editor.useWrapper;
                            var baseControl = useWrapper ? wrapper : form.toControl();
                            if (fieldModel.FormPosition == Web.FormPosition.form && ((_a = fieldModel.Group) === null || _a === void 0 ? void 0 : _a.Caption) != currentGroup) {
                                if (currentGroupWrapper)
                                    form.toControl().add(currentGroupWrapper);
                                groups.add(fieldModel.Group);
                                currentGroup = fieldModel.Group.Caption;
                                currentGroupDisplay = form.toControl().addCtr(currentGroup, "sol_group");
                                if (this.wrapFieldGroups) {
                                    currentGroupWrapper = new Sol.Control();
                                    currentGroupWrapper.css.add("sol_group_wrapper");
                                }
                            }
                            if (editor.group)
                                editor.group.GroupDisplay = currentGroupDisplay;
                            const label = this.getLabel(editor, fieldModel, structure, disableMinimizedControls);
                            if (label) {
                                if (fieldModel.FormPosition == Web.FormPosition.form &&
                                    !useWrapper &&
                                    currentGroupWrapper)
                                    currentGroupWrapper.add(label);
                                else if (fieldModel.FormPosition == Web.FormPosition.form ||
                                    fieldModel.FormPosition == Web.FormPosition.totalization)
                                    baseControl.add(label);
                                labels.add(label);
                            }
                            if (fieldModel.FormPosition == Web.FormPosition.form) {
                                var controlTarget = baseControl;
                                if (!useWrapper && !!currentGroupWrapper)
                                    controlTarget = currentGroupWrapper;
                                this.placeEditor(editor, controlTarget, code, contextClass);
                                if (useWrapper) {
                                    if (!currentGroupWrapper)
                                        form.toControl().add(baseControl);
                                    else
                                        currentGroupWrapper.add(baseControl);
                                }
                            }
                            else if (fieldModel.FormPosition == Web.FormPosition.totalization) {
                                baseControl.add(field);
                                totalizationBar.add(wrapper);
                            }
                            else if (toolbar)
                                this.placeEditorInToolbar(editor, fieldModel, toolbar);
                            fields.add(editor);
                        });
                        if (currentGroupWrapper)
                            form.toControl().add(currentGroupWrapper);
                        var initPos = 0;
                        while (((_a = form.parent) === null || _a === void 0 ? void 0 : _a.controls.item(initPos)) instanceof Web.Screens.ScreenTitle ||
                            ((_b = form.parent) === null || _b === void 0 ? void 0 : _b.controls.item(initPos)) instanceof Web.Components.Toolbar)
                            initPos++;
                        if (totalizationBar.controls.hasItems()) {
                            if (totalizationBarPos == Web.Screens.TotalizationBarPosition.Top)
                                form.parent.controls.insert(initPos++, totalizationBar);
                            else
                                form.toControl().add(totalizationBar);
                        }
                        form.editors = fields;
                        return {
                            fields: fields,
                            labels: labels,
                            groups: groups
                        };
                    }
                    catch (_c) {
                        const errorMessage = new Sol.ScreenMessage();
                        errorMessage.text = Sol.Environment.resources.error_form;
                        errorMessage.type = Sol.MessageType.Error;
                        form.toControl().add(errorMessage);
                    }
                }
            }
            Forms.CommonForm = CommonForm;
        })(Forms = Web.Forms || (Web.Forms = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class ImageField extends Sol.Control {
                    constructor() {
                        super();
                        this.EMPTY_DATA = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
                        this.imageBox = new Sol.ImageBox();
                        this.uploadInput = new Uploads.InputUpload();
                        this.addButton = new Sol.Button();
                        this.uploadEngine = null;
                        this.code = 0;
                        this.imageWidth = 100;
                        this.imageHeight = 100;
                        this.isComplex = false;
                        this.css.add("sol_image_field");
                        this.imageBox.source = this.EMPTY_DATA;
                        this.add(this.imageBox);
                    }
                    get readonly() { return this._readonly; }
                    set readonly(value) {
                        this._readonly = value;
                        this.imageBox.showDeleteButton = !value;
                    }
                    isEmpty() { return !this.value || !this.value.ID; }
                    validate() { return null; }
                    get value() {
                        if (!this.uploadEngine || !this.uploadEngine.identificador)
                            return null;
                        return {
                            ID: this.code,
                            Extensión: this.uploadEngine.extension,
                            Nombre: this.uploadEngine.itemName,
                            Identificador: this.uploadEngine.identificador,
                            Tamaño: this.uploadEngine.tamano
                        };
                    }
                    set value(v) {
                        this.uploadEngine = null;
                        this.clear();
                        if (v.ID == 0)
                            return;
                        this.uploadEngine = new Uploads.UploadItem();
                        this.code = v.ID;
                        this.uploadEngine.extension = v.Extensión;
                        this.uploadEngine.itemName = v.Nombre;
                        this.uploadEngine.identificador = v.Identificador;
                        this.uploadEngine.tamano = v.Tamaño;
                        this.uploadEngine.parent = this;
                        this.uploadEngine.isDone = true;
                        this.imageBox.source = this.uploadEngine.url;
                    }
                    clear() {
                        this.code = 0;
                        this.imageBox.source = this.EMPTY_DATA;
                        if (!this.uploadEngine)
                            return;
                        this.uploadEngine.extension = null;
                        this.uploadEngine.itemName = null;
                        this.uploadEngine.identificador = null;
                        this.uploadEngine.tamano = null;
                    }
                    build() {
                        super.build();
                        if (this.flotable)
                            this.css.add("sol_image_field_flotable");
                        if (this.imageWidth)
                            this.imageBox.imagenWidth = this.imageWidth;
                        if (this.imageHeight)
                            this.imageBox.imagenHeight = this.imageHeight;
                        if (!this.imageBox.source)
                            this.imageBox.source = "data:,";
                        if (this.readonly)
                            return;
                        var toolBar = new Sol.Control();
                        toolBar.css.add("sol_image_field_bar");
                        this.uploadInput.accept = "image/*";
                        toolBar.add(this.uploadInput);
                        this.addButton.text = this.caption ?
                            Sol.Environment.resources.select + ' ' + this.caption :
                            Sol.Environment.resources.choose_file;
                        this.addButton.type = Sol.ButtonType.Link;
                        this.addButton.css.add("sol_upload_seleccionar");
                        toolBar.add(this.addButton);
                        var clearButton = new Sol.Button();
                        clearButton.text = 'x';
                        clearButton.css.add("sol_image_field_clear");
                        clearButton.onClick = () => this.clear();
                        toolBar.add(clearButton);
                        this.add(toolBar);
                        this.html.onchange = e => this.onInputChange(e);
                    }
                    onInputChange(e) {
                        var tagInput = e.target;
                        if (!tagInput.files)
                            return;
                        var archivo = tagInput.files[0];
                        this.uploadEngine = new Uploads.UploadItem();
                        this.uploadEngine.itemName = archivo.name;
                        this.uploadEngine.file = archivo;
                        this.uploadEngine.parent = this;
                        this.uploadEngine.onUploadComplete = () => this.onUploadComplete(this.uploadEngine);
                        this.uploadEngine.process();
                    }
                    onUploadComplete(e) {
                        this.imageBox.source = e.url;
                    }
                    foco() { }
                    toControl() { return this; }
                }
                Uploads.ImageField = ImageField;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let StepStatus;
            (function (StepStatus) {
                StepStatus[StepStatus["Done"] = 0] = "Done";
                StepStatus[StepStatus["Current"] = 1] = "Current";
                StepStatus[StepStatus["Next"] = 2] = "Next";
            })(StepStatus = Components.StepStatus || (Components.StepStatus = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class Step extends Sol.Control {
                constructor(group) {
                    super();
                    this.group = group;
                    this.css.add("sol_progress_steps_step");
                    const outer = this.addCtr(null, "sol_progress_steps_outer");
                    const inner = outer.addCtr(null, "sol_progress_steps_inner");
                    inner.addCtr(this.group.Icon, null, "i");
                    this.addCtr(group.Caption, "sol_progress_steps_caption");
                }
                setStatus(status) {
                    const cssClasses = ["sol_progress_steps_step_done", "sol_progress_steps_step_current", ""];
                    this.css.removeAll(cssClasses);
                    this.css.add(cssClasses[status]);
                }
            }
            Components.Step = Step;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class StepSeparator extends Sol.Control {
                constructor(index) {
                    super();
                    this.index = index;
                    this.css.add("sol_progress_steps_separator");
                }
                setStatus(status) {
                    const cssClasses = ["sol_progress_steps_separator_done", "sol_progress_steps_separator_current", ""];
                    this.css.removeAll(cssClasses);
                    this.css.add(cssClasses[status]);
                }
            }
            Components.StepSeparator = StepSeparator;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ProgressStepLine extends Sol.Control {
                constructor(groups) {
                    super();
                    this.steps = new Sol.List();
                    this.clickable = true;
                    this.css.add("sol_progress_steps");
                    var first = true;
                    var stepIndex = 0;
                    groups.forEach(g => {
                        if (!first)
                            this.add(new Components.StepSeparator(stepIndex));
                        const step = new Components.Step(g);
                        step.index = stepIndex++;
                        step.onClick = () => {
                            if (this.clickable)
                                this.selectedStep = step;
                        };
                        this.add(step);
                        this.steps.add(step);
                        first = false;
                    });
                }
                get elements() { return this.controls.cast(); }
                get selectedStep() { return this._selectedStep; }
                set selectedStep(step) {
                    var _a;
                    this._selectedStep = step;
                    this.paintLine();
                    (_a = this.onStepSelected) === null || _a === void 0 ? void 0 : _a.apply(this);
                }
                get selectedGroup() { return this.selectedStep.group; }
                get selectedIndex() { return this.selectedStep.index; }
                set selectedIndex(value) { this.selectedStep = this.steps.item(value); }
                build() {
                    super.build();
                    this.selectedStep = this.steps.first();
                }
                paintLine() {
                    this.elements.forEach(el => el.setStatus(el.index < this.selectedIndex ? Components.StepStatus.Done :
                        (el.index == this.selectedIndex ? Components.StepStatus.Current : Components.StepStatus.Next)));
                }
            }
            Components.ProgressStepLine = ProgressStepLine;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class InlineUpload extends Sol.Control {
                    constructor() {
                        super();
                        this.mainDisplay = new Sol.Control("span");
                        this.filenameDisplay = new Sol.Control("span");
                        this.sizeDisplay = new Sol.Control("span");
                        this.inputUpload = new Uploads.InputUpload();
                        this.addButton = new Sol.Button();
                        this.deleteButton = new Sol.Button();
                        this.uploadEngine = null;
                        this.codigo = 0;
                        this.isComplex = false;
                        this.useWrapper = true;
                        this.css.addMany(["sol_campo", "sol_inline_upload"]);
                        this.filenameDisplay.css.add("sol_inline_upload_filename");
                        this.filenameDisplay.text = ' ';
                        this.filenameDisplay.onClick = () => this.download();
                        this.mainDisplay.add(this.filenameDisplay);
                        this.sizeDisplay.css.add("sol_inline_upload_filesize");
                        this.mainDisplay.add(this.sizeDisplay);
                        this.add(this.mainDisplay);
                        this.deleteButton.visible = false;
                        this.inputUpload.visible = false;
                    }
                    get readonly() { return this._readonly; }
                    set readonly(value) {
                        this._readonly = value;
                        this.deleteButton.visible = !value;
                        this.addButton.visible = !value;
                    }
                    get value() {
                        if (!this.uploadEngine)
                            return null;
                        return {
                            ID: this.codigo,
                            Extensión: this.uploadEngine.extension,
                            Nombre: this.uploadEngine.filename,
                            Identificador: this.uploadEngine.identifier,
                            Tamaño: this.uploadEngine.size,
                            ExternalLink: this.externalLink
                        };
                    }
                    set value(v) {
                        this.uploadEngine = null;
                        if (v.ID == 0)
                            return;
                        this.uploadEngine = new Sol.Http.UploadEngine();
                        this.codigo = v.ID;
                        this.uploadEngine.extension = v.Extensión;
                        this.uploadEngine.filename = v.Nombre;
                        this.uploadEngine.identifier = v.Identificador;
                        this.uploadEngine.size = v.Tamaño;
                        this.filenameDisplay.text = v.Nombre;
                        this.externalLink = v.ExternalLink;
                        this.sizeDisplay.text = Sol.NumberEx.filesizeToString(v.Tamaño);
                        this.sizeDisplay.visible = !this.externalLink;
                        this.deleteButton.visible = !this.readonly;
                    }
                    clear() {
                        this.codigo = 0;
                        this.filenameDisplay.text = ' ';
                        this.sizeDisplay.text = "";
                        this.deleteButton.visible = false;
                        this.uploadEngine = null;
                    }
                    isEmpty() {
                        return !this.value || !this.value.Identificador;
                    }
                    validate() { return null; }
                    build() {
                        super.build();
                        if (!this.readonly) {
                            this.add(this.inputUpload);
                            this.deleteButton.type = Sol.ButtonType.Custom;
                            this.deleteButton.text = "x";
                            this.deleteButton.onClick = () => this.clear();
                            this.add(this.deleteButton);
                            this.addButton.imageCode = "&#xf093;";
                            this.addButton.type = Sol.ButtonType.Custom;
                            this.addButton.onClick = () => this.selectFile();
                            this.add(this.addButton);
                        }
                        this.html.onchange = e => this.onInputChange(e);
                    }
                    selectFile() {
                        const evt = document.createEvent("MouseEvents");
                        evt.initEvent("click", true, false);
                        this.inputUpload.html.dispatchEvent(evt);
                    }
                    onInputChange(e) {
                        var tagInput = e.target;
                        var file = tagInput.files[0];
                        this.uploadEngine = new Sol.Http.UploadEngine();
                        this.uploadEngine.filename = file.name;
                        this.uploadEngine.onUploadComplete = () => this.uploadFinished();
                        this.uploadEngine.onProgress = n => this.updateProgress(n);
                        this.uploadEngine.process(file);
                    }
                    uploadFinished() {
                        this.codigo = this.uploadEngine.code;
                        this.filenameDisplay.text = this.uploadEngine.filename;
                        this.sizeDisplay.text = Sol.NumberEx.filesizeToString(this.uploadEngine.size);
                        this.sizeDisplay.visible = true;
                        this.deleteButton.visible = true;
                        this.externalLink = null;
                        this.mainDisplay.estilos.remove("background-color");
                        this.mainDisplay.estilos.remove("background-size");
                        if (this.onUploadComplete)
                            this.onUploadComplete(this);
                    }
                    download() {
                        if (!this.isEmpty())
                            window.open(this.externalLink || this.uploadEngine.downloadUrl);
                    }
                    foco() { }
                    toControl() { return this; }
                    updateProgress(progress) {
                        this.mainDisplay.estilos.definir("background-image", "-webkit-gradient(linear, left 0%, left 100%, from(#fafafa), to(#fafafa))");
                        this.mainDisplay.estilos.definir("background-size", `${progress}% 100%`);
                        this.mainDisplay.estilos.definir("background-repeat", "no-repeat");
                    }
                }
                Uploads.InlineUpload = InlineUpload;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                let ReportColumnAvailability;
                (function (ReportColumnAvailability) {
                    ReportColumnAvailability[ReportColumnAvailability["none"] = 0] = "none";
                    ReportColumnAvailability[ReportColumnAvailability["visibleByDefault"] = 1] = "visibleByDefault";
                    ReportColumnAvailability[ReportColumnAvailability["optional"] = 2] = "optional";
                })(ReportColumnAvailability = Reports.ReportColumnAvailability || (Reports.ReportColumnAvailability = {}));
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                let ReportType;
                (function (ReportType) {
                    ReportType[ReportType["QuantityReport"] = 0] = "QuantityReport";
                    ReportType[ReportType["IntervalReport"] = 1] = "IntervalReport";
                    ReportType[ReportType["Totalizer"] = 2] = "Totalizer";
                    ReportType[ReportType["Average"] = 3] = "Average";
                    ReportType[ReportType["ResultList"] = 4] = "ResultList";
                })(ReportType = Reports.ReportType || (Reports.ReportType = {}));
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                class DashboardPublishing extends Sol.Control {
                    constructor() {
                        super();
                        this.colorPicker = new Sol.ColorField();
                        this.fontColorPicker = new Sol.ColorField();
                        this.dashboardCombo = new Components.DataCombo();
                        this.myForm = new Sol.Form();
                        this.titleField = new Sol.Field();
                        this.topicField = new Sol.Field();
                        this.topicLabel = new Sol.Label();
                        this.reportOpen = new Sol.Check();
                        this.isMultiCurrency = false;
                        this.showCompleteViewOption = true;
                        this.css.add("sol_dashboard_publishing");
                    }
                    get reportTitle() { return this.titleField.value; }
                    set reportTitle(value) { this.titleField.value = value; }
                    build() {
                        super.build();
                        this.initHeader();
                        this.initBackButton();
                        this.initForm();
                    }
                    initHeader() {
                        if (!this.showTitle)
                            return;
                        this.addCtr(Sol.Environment.resources.publishToDash, null, "h4");
                    }
                    initBackButton() {
                        if (!this.showBackButton)
                            return;
                        let backButton = this.addCtr(Sol.Environment.resources.backToReport, "sol_reports_command", "span");
                        backButton.onClick = () => this.onClose(this);
                        this.add(backButton);
                    }
                    initForm() {
                        this.myForm.okButton.text = "OK";
                        this.myForm.showCancelButton = false;
                        this.myForm.onSave = () => this.publish();
                        this.add(this.myForm);
                        this.initTitleField();
                        this.initDashboardCombo();
                        this.initTopicField();
                        this.initColorSelector();
                        this.initOpenOption();
                    }
                    initTitleField() {
                        let label = new Sol.Label();
                        label.text = Sol.Environment.resources.title + ':';
                        label.editor = this.titleField;
                        this.myForm.add(label);
                        this.titleField.maxLength = 85;
                        this.titleField.required = true;
                        this.titleField.caption = Sol.Environment.resources.title;
                        this.titleField.foco();
                        this.myForm.add(this.titleField);
                    }
                    initDashboardCombo() {
                        let label = new Sol.Label();
                        label.text = Sol.Environment.resources.dashboard + ':';
                        label.editor = this.dashboardCombo;
                        this.myForm.add(label);
                        this.dashboardCombo.required = true;
                        this.dashboardCombo.displayMember = "Nombre";
                        this.dashboardCombo.caption = Sol.Environment.resources.dashboard;
                        this.dashboardCombo.className = "Solarium.UserPreferences.Dashboard, Solarium.UserPreferences, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null";
                        this.dashboardCombo.onValueModified.subscribe(() => this.checkTopicOption());
                        this.dashboardCombo.refresh();
                        this.myForm.add(this.dashboardCombo);
                    }
                    initTopicField() {
                        this.topicLabel.text = "Tópico:";
                        this.topicLabel.editor = this.topicField;
                        this.topicLabel.visible = false;
                        this.myForm.add(this.topicLabel);
                        this.topicField.visible = false;
                        this.topicField.maxLength = 50;
                        this.myForm.add(this.topicField);
                    }
                    initColorSelector() {
                        let colorWrapper = new Sol.Control();
                        colorWrapper.css.addMany(["sol_detalles_wrapper", "sol_dashboard_publishing_color"]);
                        let colorLabel = new Sol.Label();
                        colorLabel.editor = this.colorPicker;
                        colorLabel.text = Sol.Environment.resources.color + ':';
                        colorWrapper.add(colorLabel);
                        this.colorPicker.value = "#f7f7f7";
                        colorWrapper.add(this.colorPicker);
                        let fontColorLabel = new Sol.Label();
                        fontColorLabel.editor = this.fontColorPicker;
                        fontColorLabel.text = Sol.Environment.resources.fontColor + ':';
                        colorWrapper.add(fontColorLabel);
                        colorWrapper.add(this.fontColorPicker);
                        this.myForm.add(colorWrapper);
                    }
                    initOpenOption() {
                        if (!this.showCompleteViewOption)
                            return;
                        this.reportOpen.caption = Sol.Environment.resources.show_report_open,
                            this.visible = true,
                            this.myForm.add(this.reportOpen);
                    }
                    checkTopicOption() {
                        Web.System.exec("341d485s", "HasTopicOptionEnabled", { dashboardID: this.dashboardCombo.selectedCode }, result => {
                            this.topicLabel.visible = result;
                            this.topicField.visible = result;
                        });
                    }
                    publish() {
                        if (!this.myForm.validateEmptyFields(Sol.List.from([this.titleField, this.dashboardCombo])))
                            return;
                        let filters = this.filters.select(filter => ({
                            ClassType: this.classType,
                            FilterType: filter.FilterType,
                            FilterValue: JSON.stringify(filter.FilterValue),
                            PropertyName: filter.PropertyName
                        })).toArray();
                        let columns = this.columns.select(column => ({
                            Title: column.Title,
                            PropertyName: column.PropertyName,
                            ClassType: this.classType,
                            Availability: column.Availability,
                            Loadable: column.Loadable
                        })).toArray();
                        let data = {
                            model: {
                                Code: 0,
                                Title: this.reportTitle,
                                ReportTypeName: this.reportTypeName,
                                ReportType: this.reportType,
                                ClassType: this.classType,
                                PivotPropertyName: this.pivotPropertyName,
                                IsMultiCurrency: this.isMultiCurrency,
                                SelectedCurrency: this.currency,
                                CurrencyPropertyName: this.currencyPropertyName,
                                Filters: filters,
                                Columns: columns,
                                ReportOpen: this.reportOpen.value,
                                Identifier: this.identifier,
                                Color: this.colorPicker.value,
                                FontColor: this.fontColorPicker.value,
                                Dashboard: this.dashboardCombo.selectedCode,
                                Topic: this.topicField.value
                            }
                        };
                        Web.System.exec("341d485s", "Publish", data, model => {
                            if (model.Fail)
                                this.myForm.showError(model.ErrorMessage);
                            else
                                this.onClose();
                        });
                    }
                }
                Reports.DashboardPublishing = DashboardPublishing;
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                class DashboardPublishingDialog extends Sol.DialogBox {
                    constructor() {
                        super();
                        this.form = new Reports.DashboardPublishing();
                        this.title = Sol.Environment.resources.publishToDash;
                        this.css.add("sol_pantalla");
                        this.onClose = () => this.close();
                        this.form.reportType = Reports.ReportType.ResultList;
                        this.form.identifier = "total";
                        this.form.onClose = () => this.close();
                        this.form.showCompleteViewOption = false;
                        this.add(this.form);
                    }
                    set classType(value) { this.form.classType = value; }
                    set propertyName(value) { this.form.pivotPropertyName = value; }
                    set filters(value) { this.form.filters = value; }
                    set columns(value) { this.form.columns = value; }
                    set reportTypeName(value) { this.form.reportTypeName = value; }
                }
                Reports.DashboardPublishingDialog = DashboardPublishingDialog;
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PublishIcon extends Sol.Button {
                constructor() {
                    super();
                    this.imageCode = "&#xf1e0;";
                    this.css.add("sol_tabla_publish_button");
                    this.tip = Sol.Environment.resources.publishToDash;
                    this.onClick = () => this.openDialog();
                }
                openDialog() {
                    let dialog = new Components.Reports.DashboardPublishingDialog();
                    dialog.classType = this.classType;
                    dialog.propertyName = this.propertyName;
                    dialog.filters = this.filters;
                    dialog.columns = this.columns;
                    dialog.reportTypeName = this.reportTypeName;
                    Web.System.screens.add(dialog);
                }
            }
            Components.PublishIcon = PublishIcon;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DataOverview extends Sol.Control {
            }
            Components.DataOverview = DataOverview;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class DecisionScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.screenTitle = new Screens.ScreenTitle();
                    this.form = new Sol.Form();
                    this.questionText = new Sol.Control();
                    this.nextStatus = new Sol.Control();
                    this.nextStatusName = new Web.Components.Displays.ColorizedDisplay();
                    this.nextStatusDescription = new Sol.Control("pre");
                    this.processingText = new Sol.Control();
                    this.css.add("sol_pantalla_operacion");
                    this.add(this.screenTitle);
                    this.form.onCancel = () => Web.System.screens.closeCurrentScreen();
                    this.form.onSave = () => this.run();
                    this.form.okButton.text = "OK";
                    this.form.cancelButton.text = Sol.Environment.resources.back;
                    this.questionText.css.add("sol_pantalla_pregunta");
                    this.form.add(this.questionText);
                    this.nextStatus.css.add("sol_pantalla_next_status");
                    this.form.add(this.nextStatus);
                    this.form.add(this.nextStatusDescription);
                    this.processingText.css.add("sol_pantalla_pregunta");
                    this.form.add(this.processingText);
                    this.add(this.form);
                }
                build() {
                    var model = this.model;
                    this.screenTitle.text = model.Name + " " + model.ClassName;
                    this.questionText.text = Sol.Environment.resources.confirmar_operacion + " " + model.Name.toLocaleLowerCase() + "?";
                    if (model.Name.toLowerCase() == model.NextStatusName.toLowerCase())
                        this.questionText.css.add("sol_next_status_question");
                    this.nextStatus.text = Sol.Environment.resources.nextStatusMessage + ": ";
                    this.nextStatusName.setValue({ Campo: model.NextStatusName, Color: model.Color, Valor: null });
                    this.nextStatus.add(this.nextStatusName);
                    if (model.NextStatusDescription.length > 1) {
                        this.nextStatusDescription.text = model.NextStatusDescription;
                        this.nextStatusDescription.css.add("sol_pantalla_next_status_description");
                        this.nextStatusDescription.estilos.agregar("border-color", model.Color);
                    }
                    this.processingText.text = Sol.Environment.resources.processing;
                    if (model.Structure) {
                        this.componentes = Web.Editors.fillForm(model.Structure, this.form, null, Screens.FormState.Insertion, null, this.code, true);
                        this.confirmed = false;
                    }
                    super.build();
                    this.form.okButton.visible = !this.confirmed;
                    this.form.cancelButton.enabled = !this.confirmed;
                    this.questionText.visible = !this.confirmed;
                    this.nextStatus.visible = !this.confirmed;
                    this.nextStatusDescription.visible = !this.confirmed;
                    this.processingText.visible = this.confirmed;
                    if (this.confirmed)
                        this.run();
                }
                getValues() {
                    return this.componentes.fields
                        .select(cp => ({ Campo: cp.propertyName, Valor: cp.value }))
                        .toArray();
                }
                run() {
                    var model = this.model;
                    var doMultipleModel = {
                        className: model.ClassType,
                        methodName: null,
                        decisionID: model.DecisionCode,
                        ids: [this.code],
                        selectionMode: Web.ActionSelectionMode.None,
                        filters: null,
                        inputs: this.componentes ? this.getValues() : null
                    };
                    Web.System.exec("79k8j542h", "DoMultiple", doMultipleModel, response => {
                        var _a, _b, _c, _d, _e, _f;
                        this.processingText.visible = false;
                        if (!response.Fail) {
                            Web.System.screens.closeCurrentScreen();
                            (_a = this.parentScreen) === null || _a === void 0 ? void 0 : _a.refreshSearch();
                            (_c = (_b = Web.System.screens.currentFileScreen) === null || _b === void 0 ? void 0 : _b.onFileChanged) === null || _c === void 0 ? void 0 : _c.invoke();
                            if (model.CloseScreen && !this.disableCloseCurrentScreen)
                                Web.System.screens.closeCurrentScreen();
                            else if (this.parentScreen instanceof Screens.DetailsScreen) {
                                (_d = this.parentScreen) === null || _d === void 0 ? void 0 : _d.load(this.code);
                                let fileScreen = (_e = this.parentScreen) === null || _e === void 0 ? void 0 : _e.myScreen;
                                fileScreen === null || fileScreen === void 0 ? void 0 : fileScreen.refreshSearch();
                                (_f = fileScreen === null || fileScreen === void 0 ? void 0 : fileScreen.onFileChanged) === null || _f === void 0 ? void 0 : _f.invoke();
                            }
                        }
                        else {
                            this.form.showError(response.ErrorMessage);
                            this.form.cancelButton.enabled = true;
                            this.nextStatus.visible = false;
                            this.nextStatusDescription.visible = false;
                            this.questionText.visible = false;
                        }
                    });
                }
            }
            Screens.DecisionScreen = DecisionScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class FilterViewItem extends Sol.Control {
                constructor(model) {
                    super();
                    this.css.add("sol_filter_view_item");
                    this.model = model;
                    if (model.IsPerson)
                        this.add(new Web.EntityPicture(model.ObjectID));
                    const display = model.ObjectInterface.Color ? new Components.Displays.ColorizedDisplay() : new Sol.Control();
                    if (display instanceof Components.Displays.ColorizedDisplay)
                        display.setValue(model.ObjectInterface);
                    else
                        display.estilos.definir("font-weight", "bold");
                    display.text = model.ObjectInterface.Campo || model.ObjectInterface;
                    this.add(display);
                    this.addCtr(model.CountMessage, "sol_filter_view_item_count");
                }
            }
            Components.FilterViewItem = FilterViewItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ColumnsSelectorDialog extends Sol.FormDialog {
                constructor() {
                    super();
                    this.availableFieldsLabel = new Sol.Label();
                    this.checkList = new Sol.CheckList();
                    this.columns = new Sol.List();
                    this.title = Sol.Environment.resources.elegir_columnas;
                    this.availableFieldsLabel.text = Sol.Environment.resources.columnas_disponibles + ':';
                    this.form.add(this.availableFieldsLabel);
                    this.form.add(this.checkList);
                    this.form.okButton.text = "OK";
                    this.form.onValidate = () => this.validate();
                    this.form.onSave = () => this.save();
                    this.checkList.estilos.agregar("max-height", "302px");
                    this.onExhibido = () => this.checkList.clearSearch();
                    this.ancho = 350;
                }
                get availableColumns() { return this.columns; }
                set availableColumns(value) {
                    this.columns = value;
                    this.checkList.options = this.columns.select(col => ({
                        Code: col.PropertyName,
                        Description: col.Title && col.Title[0] == '&' ? col.ColumnTip : col.Title,
                        Checked: !this.myTable ? col.selected : this.myTable.columns.any(cl => cl.PropertyName == col.PropertyName)
                    }))
                        .orderBy(o => o.Description)
                        .toArray();
                }
                get selectedColumns() {
                    return this.columns.where(cl => this.isColumnSelected(cl.PropertyName));
                }
                isColumnSelected(columnName) {
                    return this.checkList.isCodeChecked(columnName);
                }
                validate() {
                    return {
                        success: this.allowEmptySelection || !this.checkList.isEmpty(),
                        message: Sol.Environment.resources.ningun_seleccionado
                    };
                }
                save() {
                    this.visible = false;
                    this.onSaved();
                    this.workComplete();
                }
            }
            Components.ColumnsSelectorDialog = ColumnsSelectorDialog;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                ;
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ReportScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.report = new Web.Components.Reports.Report();
                    this.css.addMany(["sol_report_screen", "sol_reports"]);
                    this.add(this.report);
                }
                get onSearch() { return this.report.onSearch; }
                set onSearch(value) { this.report.onSearch = value; }
                get showPrintButton() { return this.report.showPrintButton; }
                set showPrintButton(value) { this.report.showPrintButton = value; }
                openReport(model) {
                    this.report.initialize(model);
                }
                openSuggestion(suggestion) {
                    this.screenCaption = suggestion.ReportTitle;
                    this.report.createFromSuggestion(suggestion);
                }
                setFilterStructure(structure) {
                    this.report.customFiltersStructure = structure;
                }
            }
            Screens.ReportScreen = ReportScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                class ReportPrintableVersion extends Sol.Control {
                    constructor() {
                        super("html");
                        this.contentArea = new Sol.Control();
                        this.htmlTitle = new Sol.Control("title");
                        this.companyTitle = new Sol.Control("h4");
                        const head = new Sol.Control("head");
                        const styleSheet = new Sol.Control("link");
                        styleSheet.atributos.agregar("href", Sol.Environment.systemUrl + "/theme/sol.css");
                        styleSheet.atributos.agregar("rel", "stylesheet");
                        head.add(styleSheet);
                        const styleTag = new Sol.Control("style");
                        styleTag.text = ".sol_reports_command, .sol_reports_command ~ br { display: none }";
                        head.add(styleTag);
                        head.add(this.htmlTitle);
                        this.add(head);
                        const body = new Sol.Control("body");
                        body.id = "sol";
                        body.css.add("sol_tabla");
                        body.estilos.agregar("background-color", "#fff");
                        body.add(this.companyTitle);
                        body.add(this.contentArea);
                        this.add(body);
                    }
                    build() {
                        super.build();
                        this.htmlTitle.text = this.companyName + " - " + this.title;
                        this.companyTitle.text = this.companyName;
                        this.contentArea.htmlContent = this.content;
                    }
                }
                Reports.ReportPrintableVersion = ReportPrintableVersion;
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                let ReportCellAlignment;
                (function (ReportCellAlignment) {
                    ReportCellAlignment[ReportCellAlignment["Left"] = 0] = "Left";
                    ReportCellAlignment[ReportCellAlignment["Right"] = 1] = "Right";
                    ReportCellAlignment[ReportCellAlignment["Center"] = 2] = "Center";
                })(ReportCellAlignment = Reports.ReportCellAlignment || (Reports.ReportCellAlignment = {}));
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                let ReportRowType;
                (function (ReportRowType) {
                    ReportRowType[ReportRowType["Data"] = 0] = "Data";
                    ReportRowType[ReportRowType["SubTotal"] = 1] = "SubTotal";
                    ReportRowType[ReportRowType["Total"] = 2] = "Total";
                    ReportRowType[ReportRowType["Header"] = 3] = "Header";
                    ReportRowType[ReportRowType["Average"] = 4] = "Average";
                    ReportRowType[ReportRowType["SectionTitle"] = 5] = "SectionTitle";
                })(ReportRowType = Reports.ReportRowType || (Reports.ReportRowType = {}));
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                class ReportRow extends Sol.Control {
                    constructor() {
                        super("tr");
                    }
                }
                Reports.ReportRow = ReportRow;
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        class MapChartPoint extends Sol.Control {
            constructor(model, map, data) {
                super("span");
                this.POINT_OFFSET = 7;
                this.css.add("sol_map_point");
                this.model = model;
                this.map = map;
                this.chartData = data;
                this.text = model.Value.toString();
                this.tip = model.Description;
                this.estilos.agregar("background-color", model.Color);
                this.estilos.agregar("margin-left", this.leftPos + "px");
                this.estilos.agregar("margin-top", this.topPos + "px");
                this.estilos.agregar("padding", model.Radius + "px");
                this.estilos.agregar("border-radius", (model.Radius + 15) + "px");
            }
            get leftPos() { return ((this.mapWidth / (this.mapRight - this.mapLeft)) * (this.model.Longitude - this.mapLeft)) - this.model.Radius; }
            get mapLeft() { return this.chartData.MapCorners.TopLeft.Longitude; }
            get mapRight() { return this.chartData.MapCorners.TopRight.Longitude; }
            get mapBottom() { return this.chartData.MapCorners.BottomLeft.Latitude; }
            get mapTop() { return this.chartData.MapCorners.TopLeft.Latitude; }
            get mapHeight() { return this.map.html.offsetHeight; }
            get mapWidth() { return this.map.html.offsetWidth; }
            get topPos() { return ((this.mapHeight / (this.mapBottom - this.mapTop)) * (this.model.Latitude - this.mapTop)) - this.POINT_OFFSET - this.model.Radius; }
        }
        Charts.MapChartPoint = MapChartPoint;
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Charts;
    (function (Charts) {
        class MapChart extends Sol.Control {
            constructor(data) {
                super();
                this.css.add("sol_map_chart");
                const mapImage = new Sol.Control("img");
                mapImage.atributos.agregar("src", data.MapUrl);
                this.add(mapImage);
                setTimeout(() => Sol.List.from(data.Points)
                    .where(p => !!p.Value)
                    .forEachReverse(p => this.controls.insert(0, new Charts.MapChartPoint(p, mapImage, data))), 300);
            }
        }
        Charts.MapChart = MapChart;
    })(Charts = Sol.Charts || (Sol.Charts = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                class Report extends Sol.Control {
                    constructor() {
                        super();
                        this.currencySelector = new Sol.Combo();
                        this.deleteFavoriteButton = new Sol.Control("span");
                        this.favoriteButton = new Sol.Control("span");
                        this.headerArea = new Sol.Control();
                        this.intervalSelector = new Sol.IntervalCombo();
                        this.isExpanded = false;
                        this.mainView = new Sol.Control();
                        this.titleControl = new Sol.Control("span");
                        this.table = new Sol.Control("table");
                        this.tableBody = new Sol.Control("tbody");
                        this.titleField = new Sol.Field();
                        this.saveTitleButton = new Sol.Button();
                        this.editTitleButton = new Sol.Button();
                        this.cancelTitleButton = new Sol.Button();
                        this.isMonitored = true;
                        this.minimizable = false;
                        this.showBackButton = false;
                        this.showChartLegend = false;
                        this.showPrintButton = false;
                        this.showRemoveButton = false;
                        this.css.add("sol_report_view");
                        this.intervalSelector.value = { Opcion: Sol.IntervalType.CurrentMonth };
                        this.selectedCurrency = Sol.Environment.defaultCurrency.ISO;
                        this.add(this.mainView);
                    }
                    get reportTitle() { return this.titleControl.text; }
                    createFromSuggestion(suggestion, filters = []) {
                        this.mySuggestion = suggestion;
                        this.customFiltersStructure = suggestion.CustomFiltersStructure;
                        this.filters = Sol.List.from(filters);
                        this.load();
                    }
                    getUsedFilters() {
                        this.replaceIntervalFilterBySelector();
                        this.loadDefaultCustomFilters();
                        var usedFilters = new Sol.List();
                        usedFilters.addMany(this.filters);
                        if (this.mySuggestion.IsMultiCurrency)
                            usedFilters.add({
                                FilterType: "SText",
                                PropertyName: this.mySuggestion.CurrencyPropertyName,
                                FilterValue: this.selectedCurrency
                            });
                        if (this.customFilters)
                            usedFilters.addMany(this.customFilters);
                        return usedFilters;
                    }
                    initialize(model) {
                        this.mainView.controls.empty();
                        this.model = model;
                        this.initializeHeader();
                        this.initializeRemoveButton();
                        this.initializeBackButton();
                        this.initFavoriteButtons();
                        this.initializePrintView();
                        this.initializePublishButton();
                        this.initializeColumnsButton();
                        if (this.showBackButton || this.allowPublishToDashboard || this.showPrintButton)
                            this.mainView.add(new Sol.LineBreak());
                        this.initializeCustomFilters();
                        this.initializeIntervalSelector();
                        this.initializeCurrencySelector();
                        this.initializeChart();
                        this.initTotalizer();
                        this.initializeTable();
                    }
                    print() {
                        const preview = new Reports.ReportPrintableVersion();
                        preview.companyName = Web.System.companyName;
                        preview.title = this.mySuggestion.ReportTitle;
                        preview.content = this.html.outerHTML;
                        window.open("", "_blank", "").document.write(preview.abrir());
                    }
                    refresh() {
                        this.isExpanded = this.table.visible;
                        this.mainView.controls.empty();
                        this.table = new Sol.Control("table");
                        this.tableBody = new Sol.Control("tbody");
                        if (!this.mainView.visible) {
                            this.controls.removeItem(1);
                            this.mainView.visible = true;
                        }
                        this.load();
                    }
                    fillRow(target, type, row) {
                        const reportRow = new Reports.ReportRow();
                        reportRow.groupId = row.GroupID;
                        reportRow.css.add(row.CssClass);
                        Sol.List.from(row.Cells).where(item => !!item).forEach(item => {
                            var cell = new Sol.Control("td");
                            if (item.FillRow)
                                item.ColumnSpan = Sol.List.from(this.model.Headers).last().Cells.length;
                            if (item.ColumnSpan > 1)
                                cell.atributos.agregar("colspan", item.ColumnSpan.toString());
                            if (item.RowSpan > 1)
                                cell.atributos.agregar("rowspan", item.RowSpan.toString());
                            cell.text = item.Text;
                            cell.htmlContent = item.HtmlContent;
                            if (item.Alignment == Reports.ReportCellAlignment.Center)
                                cell.estilos.agregar("text-align", "center");
                            if (item.Alignment == Reports.ReportCellAlignment.Right)
                                cell.estilos.agregar("text-align", "right");
                            if (item.Bold)
                                cell.estilos.agregar("font-weight", "bold");
                            if (item.Width)
                                cell.estilos.agregar("width", item.Width + "px");
                            if (item.CssClass)
                                cell.css.add(item.CssClass);
                            if (type == Reports.ReportRowType.Data &&
                                !reportRow.controls.hasItems() &&
                                this.myChart &&
                                this.myChart instanceof Sol.Charts.PieChart)
                                this.fillColorizedCell(cell, this.myChart.colors[target.controls.count]);
                            if (item.FlagColor)
                                this.fillColorizedCell(cell, item.FlagColor);
                            if (item.BackColor) {
                                cell.estilos.agregar("background-color", item.BackColor);
                                cell.estilos.agregar("background-image", "none");
                            }
                            if (item.TextColor)
                                cell.estilos.agregar("color", item.TextColor);
                            if (item.Totalizer) {
                                if (this.allowPublishToDashboard) {
                                    let totalPublishButton = new Sol.Button();
                                    totalPublishButton.imageCode = "&#xf1e0;";
                                    totalPublishButton.css.add("sol_reports_button_publish_line");
                                    totalPublishButton.tip = Sol.Environment.resources.publishToDash;
                                    totalPublishButton.onClick = () => this.publish(Reports.ReportType.Totalizer, item.Totalizer);
                                    cell.add(totalPublishButton);
                                }
                                let legend = new Sol.Control("span");
                                legend.text = cell.text;
                                cell.text = "";
                                legend.css.add("sol_reports_legend_line");
                                cell.add(legend);
                            }
                            reportRow.add(cell);
                        });
                        if (type == Reports.ReportRowType.Average)
                            reportRow.css.add("sol_reports_average");
                        if (type == Reports.ReportRowType.Total)
                            reportRow.css.add("sol_reports_totalization");
                        if (type == Reports.ReportRowType.SubTotal)
                            reportRow.css.add("sol_reports_subtotalization");
                        if (type == Reports.ReportRowType.SectionTitle)
                            reportRow.css.add("sol_reports_section_title");
                        if (type == Reports.ReportRowType.Header)
                            reportRow.css.add("sol_reports_section_header");
                        if (row.SubreportSuggestion) {
                            reportRow.css.add("sol_reports_row_clickable");
                            reportRow.onClick = () => this.openSubreport(row);
                        }
                        target.add(reportRow);
                    }
                    openSubreport(row) {
                        const data = {
                            report: row.SubreportSuggestion,
                            filters: row.SubreportSuggestion.DefaultFilters,
                            isMonitored: true
                        };
                        Web.System.exec("hw9rh93h5", "Generate", data, model => {
                            const subreport = new Web.Screens.ReportScreen();
                            subreport.screenCaption = row.SubreportSuggestion.ReportTitle;
                            Web.System.screens.addScreen(subreport);
                            Web.System.screens.showScreen(subreport);
                            subreport.openReport(model.Report);
                        });
                    }
                    fillColorizedCell(cell, color) {
                        var colorLegend = new Sol.Control("span");
                        colorLegend.css.add("sol_reports_color_legend");
                        colorLegend.estilos.agregar("background-color", color);
                        cell.add(colorLegend);
                        var legend = new Sol.Control("span");
                        legend.text = cell.text;
                        cell.add(legend);
                        cell.text = "";
                    }
                    getSelectedCurrency() {
                        if (!this.mySuggestion.IsMultiCurrency)
                            return null;
                        return this.currencySelector.selectedCode;
                    }
                    initializeChart() {
                        if (this.mySuggestion.ReportType == Reports.ReportType.Totalizer)
                            return;
                        switch (this.model.ChartType) {
                            case Sol.Charts.ChartType.Pie:
                                this.initializePieChart();
                                break;
                            case Sol.Charts.ChartType.Line:
                                this.initializeLineChart();
                                break;
                            case Sol.Charts.ChartType.Flow:
                                this.initializeFlowChart();
                                break;
                            case Sol.Charts.ChartType.Map:
                                this.initializeMapChart();
                                break;
                        }
                    }
                    initializePieChart() {
                        let pie = new Sol.Charts.PieChart();
                        let chartModel = this.model.ChartData;
                        this.parent.css.add("sol_reports_pie");
                        pie.labels = chartModel.Labels;
                        pie.values = chartModel.Values;
                        pie.colors = chartModel.Colors || pie.defaultColors;
                        pie.enableLegend = this.showChartLegend;
                        pie.responsive = false;
                        pie.chartHeight = 170;
                        pie.chartWidth = 170;
                        pie.css.add("sol_reports_chart");
                        this.mainView.add(pie);
                        pie.showChart();
                        this.myChart = pie;
                    }
                    initializeLineChart() {
                        var lineChart = new Sol.Charts.LineChart();
                        var chartModel = this.model.ChartData;
                        this.parent.css.add("sol_reports_line");
                        lineChart.labels = chartModel.Labels;
                        lineChart.values = chartModel.Values;
                        lineChart.enableLegend = this.showChartLegend;
                        lineChart.chartHeight = 0;
                        lineChart.chartWidth = 0;
                        lineChart.css.add("sol_reports_chart");
                        this.mainView.add(lineChart);
                        lineChart.showChart();
                        this.myChart = lineChart;
                    }
                    initializeFlowChart() {
                        const flowChart = new Sol.Charts.FlowChart(this.model.ChartData);
                        flowChart.css.add("sol_reports_chart");
                        flowChart.onItemShown = e => setTimeout(() => this.showGroup(e.currentStatus), 200);
                        this.mainView.add(flowChart);
                        this.myChart = flowChart;
                    }
                    initializeMapChart() {
                        const mapChart = new Sol.Charts.MapChart(this.model.ChartData);
                        this.mainView.add(mapChart);
                        this.myChart = mapChart;
                    }
                    initializeHeader() {
                        this.headerArea.controls.empty();
                        this.titleControl.text = this.mySuggestion ? this.mySuggestion.ReportTitle : this.model.Title;
                        this.titleControl.css.add("sol_reports_title");
                        this.headerArea.addMany([this.titleField, this.titleControl]);
                        if (this.minimizable && this.model && this.model.ChartType != Sol.Charts.ChartType.None) {
                            this.titleControl.css.add("sol_reports_title_expando");
                            this.titleControl.onClick = () => this.table.visible = !this.table.visible;
                        }
                        this.titleField.visible = false;
                        if (this.allowEditTitle) {
                            this.titleField.maxLength = 85;
                            this.titleField.autoWidth = false;
                            this.titleField.onKeyDown = e => this.titleKeydow(e);
                            this.editTitleButton = new Sol.Button();
                            this.editTitleButton.onClick = () => this.editTitle();
                            this.configureHeaderButton(this.editTitleButton, Sol.Environment.resources.editar, "&#xf044;");
                            this.saveTitleButton = new Sol.Button();
                            this.saveTitleButton.visible = false;
                            this.saveTitleButton.onClick = () => this.saveEdit();
                            this.configureHeaderButton(this.saveTitleButton, Sol.Environment.resources.grabar, "&#xf0c7;");
                            this.cancelTitleButton = new Sol.Button();
                            this.cancelTitleButton.visible = false;
                            this.cancelTitleButton.onClick = () => this.cancelEdit();
                            this.configureHeaderButton(this.cancelTitleButton, Sol.Environment.resources.cancelar, "&#xf05e;");
                        }
                        this.mainView.add(this.headerArea);
                    }
                    configureHeaderButton(button, caption, icon) {
                        button.tip = caption;
                        button.css.add("sol_reports_button_title");
                        button.imageCode = icon;
                        this.headerArea.add(button);
                    }
                    editTitle() {
                        this.titleField.visible = true;
                        this.titleField.ancho = this.titleControl.html.offsetWidth + 5;
                        this.titleField.value = this.titleControl.text;
                        this.titleField.css.add("sol_reports_title_field");
                        this.titleControl.visible = false;
                        this.cancelTitleButton.visible = true;
                        this.saveTitleButton.visible = true;
                        this.editTitleButton.visible = false;
                        this.titleField.foco();
                        this.titleField.selectAllText();
                    }
                    cancelEdit() {
                        this.titleField.visible = false;
                        this.titleControl.visible = true;
                        this.cancelTitleButton.visible = false;
                        this.saveTitleButton.visible = false;
                        this.editTitleButton.visible = true;
                    }
                    saveEdit() {
                        if (this.titleField.isEmpty()) {
                            alert("Informe o título, por favor.");
                            return;
                        }
                        let title = this.titleField.value;
                        this.titleControl.text = title;
                        this.mySuggestion.ReportTitle = title;
                        this.cancelEdit();
                        if (!this.favoriteID)
                            return;
                        let data = {
                            className: "Solarium.UserPreferences.FavoriteReport, Solarium.UserPreferences, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            id: this.favoriteID,
                            data: [{ Campo: "Nombre", Valor: title }]
                        };
                        Web.System.exec("3b5v9v45", "Save", data);
                        this.listChanged = true;
                    }
                    titleKeydow(e) {
                        if (e.key == "Enter") {
                            this.saveEdit();
                            return false;
                        }
                        if (e.key == "Escape") {
                            this.cancelEdit();
                            return false;
                        }
                        return true;
                    }
                    initializeRemoveButton() {
                        if (!this.showRemoveButton)
                            return;
                        let removeButton = new Sol.Control("span");
                        removeButton.text = Sol.Environment.resources.eliminar;
                        removeButton.css.addMany(["sol_reports_command", "sol_reports_remove"]);
                        removeButton.onClick = () => {
                            if (this.onRemove)
                                this.onRemove(this);
                        };
                        this.mainView.add(removeButton);
                    }
                    initializeBackButton() {
                        if (!this.showBackButton)
                            return;
                        const backButton = new Sol.Control("span");
                        backButton.text = Sol.Environment.resources.reports_back;
                        backButton.css.addMany(["sol_reports_command", "sol_reports_cmd_back"]);
                        backButton.onClick = () => {
                            if (this.onClose)
                                this.onClose(this.listChanged);
                        };
                        this.mainView.add(backButton);
                    }
                    initFavoriteButtons() {
                        if (!this.allowSaveAsFavorite)
                            return;
                        this.favoriteButton.text = Sol.Environment.resources.saveAsFavorite;
                        this.favoriteButton.css.addMany(["sol_reports_command", "sol_reports_cmd_favorite"]);
                        this.favoriteButton.onClick = () => this.save();
                        this.favoriteButton.visible = !this.favoriteID;
                        this.mainView.add(this.favoriteButton);
                        this.deleteFavoriteButton.text = Sol.Environment.resources.removeFromFavorites;
                        this.deleteFavoriteButton.css.addMany(["sol_reports_command", "sol_reports_cmd_unfavorite"]);
                        this.deleteFavoriteButton.onClick = () => this.removeFavorite();
                        this.deleteFavoriteButton.visible = !!this.favoriteID;
                        this.mainView.add(this.deleteFavoriteButton);
                    }
                    initializePrintView() {
                        if (!this.showPrintButton)
                            return;
                        let printButton = new Sol.Control("span");
                        printButton.text = Sol.Environment.resources.printable_version;
                        printButton.css.addMany(["sol_reports_command", "sol_reports_cmd_print"]);
                        printButton.onClick = () => this.print();
                        this.mainView.add(printButton);
                    }
                    initializePublishButton() {
                        if (!this.allowPublishToDashboard)
                            return;
                        let publishButton = new Sol.Control("span");
                        publishButton.text = Sol.Environment.resources.publishToDash;
                        publishButton.css.addMany(["sol_reports_command", "sol_reports_cmd_publish"]);
                        publishButton.onClick = () => this.publish(this.mySuggestion.ReportType);
                        this.mainView.add(publishButton);
                    }
                    initializeColumnsButton() {
                        if (!Sol.List.from(this.mySuggestion.Columns).any(cl => cl.Availability == Reports.ReportColumnAvailability.optional))
                            return;
                        let columnsButton = new Sol.Control("span");
                        columnsButton.text = Sol.Environment.resources.moreColumns;
                        columnsButton.css.addMany(["sol_reports_command", "sol_reports_cmd_columns"]);
                        columnsButton.onClick = () => this.openColumnsDialog();
                        this.mainView.add(columnsButton);
                    }
                    openColumnsDialog() {
                        let dialog = new Components.ColumnsSelectorDialog();
                        let optionalCols = Sol.List.from(this.mySuggestion.Columns)
                            .where(cl => cl.Availability == Reports.ReportColumnAvailability.optional);
                        dialog.allowEmptySelection = true;
                        dialog.availableColumns =
                            optionalCols.select(cl => ({
                                PropertyName: cl.PropertyName,
                                Title: cl.Title,
                                selected: cl.IsSelected
                            }));
                        dialog.onSaved = () => {
                            optionalCols.forEach(cl => cl.IsSelected = dialog.isColumnSelected(cl.PropertyName));
                            this.refresh();
                        };
                        this.parent.parent.add(dialog);
                    }
                    initializeCustomFilters() {
                        var _a;
                        this.customFiltersArea = new Sol.EditorContainer();
                        if (!this.customFiltersStructure || this.customFiltersStructure.length == 0)
                            return;
                        Web.Editors.fillForm(this.customFiltersStructure, this.customFiltersArea, null, Web.Screens.FormState.Edition, (_a = this.mySuggestion) === null || _a === void 0 ? void 0 : _a.Type, 0);
                        if (this.customFilters)
                            this.customFilters.forEach(flt => {
                                var editor = this.customFiltersArea.editors.that(e => e.propertyName == flt.PropertyName);
                                if (editor)
                                    editor.value = flt.FilterValue;
                            });
                        let searchButton = new Sol.Button();
                        searchButton.text = Sol.Environment.resources.buscar;
                        searchButton.css.add("sol_reports_search");
                        searchButton.onClick = () => this.search();
                        this.customFiltersArea.add(searchButton);
                        this.mainView.add(this.customFiltersArea);
                    }
                    initializeIntervalSelector() {
                        if (!this.mySuggestion || this.mySuggestion.ReportType != Reports.ReportType.IntervalReport)
                            return;
                        var currentSelectorValue = this.intervalSelector.value;
                        this.intervalSelector = new Sol.IntervalCombo();
                        this.intervalSelector.value = currentSelectorValue;
                        this.intervalSelector.showAnyOption = false;
                        this.intervalSelector.showTomorrow = false;
                        this.intervalSelector.onModified = () => this.refresh();
                        this.mainView.add(this.intervalSelector);
                    }
                    initializeCurrencySelector() {
                        if (!this.mySuggestion || !this.mySuggestion.IsMultiCurrency)
                            return;
                        this.currencySelector = new Sol.Combo();
                        this.currencySelector.displayMember = "Name";
                        this.currencySelector.valueMember = "ISO";
                        this.currencySelector.setDataSource(Sol.Environment.currencies);
                        if (this.selectedCurrency)
                            this.currencySelector.selectedCode = this.selectedCurrency;
                        this.currencySelector.onChange = () => {
                            this.selectedCurrency = this.currencySelector.value.Valor;
                            this.refresh();
                        };
                        this.mainView.add(this.currencySelector);
                    }
                    initializeTable() {
                        if (this.mySuggestion.ReportType == Reports.ReportType.Totalizer)
                            return;
                        let tableHead = new Sol.Control("thead");
                        this.tableBody = new Sol.Control("tbody");
                        Sol.List.from(this.model.Headers).where(h => !!h).forEach(row => this.fillRow(tableHead, Reports.ReportRowType.Header, row));
                        Sol.List.from(this.model.Rows).forEach(row => this.fillRow(this.tableBody, row.RowType, row));
                        this.table.css.add(this.model.TableCssClass);
                        this.table.controls.empty();
                        this.table.add(tableHead);
                        this.table.add(this.tableBody);
                        this.mainView.add(this.table);
                        this.table.visible = !this.minimizable || this.isExpanded || this.model.ChartType == Sol.Charts.ChartType.None;
                    }
                    initErrorMessage(message = null) {
                        this.mainView.addCtr(message || Sol.Environment.resources.reports_error, "sol_reports_error");
                    }
                    initTotalizer() {
                        if (this.mySuggestion.ReportType != Reports.ReportType.Totalizer)
                            return;
                        let tile = new Reports.DashboardTile();
                        tile.createFromSuggestion(this.mySuggestion, this.filters.toArray());
                        this.mainView.add(tile);
                    }
                    initErrorMode(message = null) {
                        this.initializeHeader();
                        this.initializeBackButton();
                        this.initializeCustomFilters();
                        this.initErrorMessage(message);
                    }
                    load() {
                        if (this.mySuggestion.ReportType == Reports.ReportType.Totalizer) {
                            this.allowSaveAsFavorite = false;
                            this.initialize(null);
                            return;
                        }
                        let data = {
                            report: this.mySuggestion,
                            filters: this.getUsedFilters().toArray(),
                            isMonitored: this.isMonitored
                        };
                        Web.System.exec("hw9rh93h5", "Generate", data, model => {
                            if (model.Fail) {
                                this.initErrorMode(model.ErrorMessage);
                                return;
                            }
                            this.initialize(model.Report);
                        }, () => this.initErrorMode());
                    }
                    loadDefaultCustomFilters() {
                        if (!this.customFiltersStructure)
                            return;
                        this.customFilters = this.customFilters ||
                            Sol.List.from(this.customFiltersStructure)
                                .where(f => f.DefaultValue)
                                .select(f => ({
                                FilterType: f.DataType,
                                FilterValue: f.DefaultValue,
                                PropertyName: f.PropertyName
                            }));
                    }
                    publish(reportType, identifier = null) {
                        this.mainView.visible = false;
                        let scr = new Reports.DashboardPublishing();
                        scr.showTitle = true;
                        scr.showBackButton = true;
                        scr.showCompleteViewOption = false;
                        scr.classType = this.mySuggestion.Type;
                        scr.columns = Sol.List.from(this.mySuggestion.Columns);
                        scr.filters = this.filters;
                        scr.reportTypeName = this.mySuggestion.ReportTypeName;
                        scr.reportType = reportType;
                        scr.reportTitle = this.mySuggestion.ReportTitle;
                        scr.pivotPropertyName = this.mySuggestion.PropertyName;
                        scr.identifier = identifier;
                        scr.isMultiCurrency = this.mySuggestion.IsMultiCurrency;
                        scr.currency = this.getSelectedCurrency();
                        scr.currencyPropertyName = this.mySuggestion.CurrencyPropertyName;
                        scr.onClose = () => this.closePublishing(scr);
                        this.add(scr);
                    }
                    closePublishing(screen) {
                        this.controls.remove(screen);
                        this.mainView.visible = true;
                    }
                    removeFavorite() {
                        Web.System.exec("341d485s", "DeleteFavorite", { favoriteID: this.favoriteID }, e => {
                            if (e.Fail) {
                                this.initErrorMessage(e.ErrorMessage);
                                return;
                            }
                            this.favoriteID = 0;
                            this.favoriteButton.visible = true;
                            this.deleteFavoriteButton.visible = false;
                            this.listChanged = true;
                        });
                    }
                    replaceIntervalFilterBySelector() {
                        if (this.mySuggestion.ReportType != Reports.ReportType.IntervalReport)
                            return;
                        this.filters = this.filters.where(flt => flt.PropertyName != "Creación");
                        this.filters.add({
                            FilterType: "Periodo",
                            PropertyName: "Creación",
                            FilterValue: this.intervalSelector.value
                        });
                    }
                    save() {
                        let filters = this.filters.select(filter => ({
                            ClassType: this.mySuggestion.Type,
                            FilterType: filter.FilterType,
                            FilterValue: JSON.stringify(filter.FilterValue),
                            PropertyName: filter.PropertyName
                        })).toArray();
                        let columns = Sol.List.from(this.mySuggestion.Columns).select(column => ({
                            Title: column.Title,
                            PropertyName: column.PropertyName,
                            ClassType: this.mySuggestion.Type,
                            Availability: column.Availability,
                            Loadable: column.Loadable,
                            IsSelected: column.IsSelected
                        })).toArray();
                        let data = {
                            model: {
                                Code: 0,
                                Title: this.mySuggestion.ReportTitle,
                                ReportTypeName: this.mySuggestion.ReportTypeName,
                                ClassType: this.mySuggestion.Type,
                                PivotPropertyName: this.mySuggestion.PropertyName,
                                IsMultiCurrency: this.mySuggestion.IsMultiCurrency,
                                SelectedCurrency: this.getSelectedCurrency(),
                                CurrencyPropertyName: this.mySuggestion.CurrencyPropertyName,
                                Filters: filters,
                                Columns: columns
                            }
                        };
                        Web.System.exec("341d485s", "SaveFavorite", data, e => {
                            if (e.Fail) {
                                this.initErrorMessage(e.ErrorMessage);
                                return;
                            }
                            this.favoriteID = e.FavoriteID;
                            this.favoriteButton.visible = false;
                            this.deleteFavoriteButton.visible = true;
                            this.listChanged = true;
                            alert(Sol.Environment.resources.grabado_ok);
                        });
                    }
                    search() {
                        this.customFilters = this.customFiltersArea
                            .editors
                            .where(edt => !edt.isEmpty())
                            .select(edt => ({
                            FilterType: edt.filterType,
                            FilterValue: edt.value,
                            PropertyName: edt.propertyName
                        }));
                        if (this.onSearch)
                            this.onSearch(this);
                        else
                            this.load();
                    }
                    showGroup(groupId) {
                        this.tableBody.controls.cast().forEach(row => row.visible = row.groupId == groupId);
                    }
                }
                Reports.Report = Report;
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                class ReportsIndex extends Sol.Control {
                    constructor() {
                        super();
                        this.indexPage = new Sol.Control();
                        this.allowDashboardCustomization = false;
                        this.css.add("sol_reports");
                        this.add(this.indexPage);
                        this.addTitle(this.indexPage, Sol.Environment.resources.reports);
                    }
                    loadReports() {
                        let requestData = {
                            ScreenName: "ReportScreen",
                            ClassName: this.className
                        };
                        Web.System.exec("lsperos32", "Open", requestData, e => this.initScreen(e));
                    }
                    refresh() {
                        if (!this.currentReport)
                            return;
                        this.currentReport.filters = Sol.List.from(this.table.lastFilters);
                        this.currentReport.refresh();
                    }
                    build() {
                        super.build();
                        this.indexPage.addCtr(Sol.Environment.resources.cargando, "sol_reports_text_attention");
                    }
                    addTitle(target, title) {
                        target.addCtr(title, "sol_reports_section_title", "h4");
                    }
                    initScreen(model) {
                        let allReports = Sol.List.from(model.AllReports);
                        let favorites = Sol.List.from(model.FavoriteReports);
                        this.indexPage.controls.empty();
                        this.createSection("Meus relatórios favoritos", favorites);
                        this.createSection("Totalizadores", allReports.where(r => r.ReportType == Reports.ReportType.Totalizer));
                        this.createSection("Relatórios recomendados", allReports.where(r => r.IsRecommended));
                        this.createSection("Relatórios sugeridos por IA", allReports.where(r => !r.IsRecommended));
                        if (!allReports.hasItems() && !favorites.hasItems()) {
                            this.indexPage.addCtr(Sol.Environment.resources.text_empty_report, "sol_reports_text_attention");
                            return;
                        }
                        this.indexPage.addCtr(Sol.Environment.resources.text_attention_report, "sol_reports_text_attention");
                    }
                    createSection(title, reports) {
                        if (!reports.hasItems())
                            return;
                        let section = new Sol.Control();
                        section.css.add("sol_reports_index_section");
                        this.addTitle(section, title);
                        reports.forEach(rpt => {
                            let reportButton = new Sol.Button();
                            reportButton.text = rpt.ReportTitle;
                            reportButton.data = rpt;
                            reportButton.type = Sol.ButtonType.Custom;
                            reportButton.onClick = () => this.reportClick(reportButton.data);
                            section.add(reportButton);
                        });
                        this.indexPage.add(section);
                    }
                    reportClick(model) {
                        this.table.setFilters(model.Filters, true);
                        this.currentReport = new Reports.Report();
                        this.currentReport.allowEditTitle = true;
                        this.currentReport.showBackButton = true;
                        this.currentReport.allowPublishToDashboard = this.allowDashboardCustomization;
                        this.currentReport.showPrintButton = true;
                        this.currentReport.allowSaveAsFavorite = true;
                        this.currentReport.favoriteID = model.FavoriteID;
                        this.currentReport.onClose = c => this.closeReport(c);
                        this.currentReport.createFromSuggestion(model, this.table.lastFilters);
                        this.indexPage.visible = false;
                        this.add(this.currentReport);
                    }
                    closeReport(listChanged) {
                        this.indexPage.visible = true;
                        this.controls.remove(this.currentReport);
                        this.currentReport = null;
                        if (listChanged)
                            this.loadReports();
                    }
                }
                Reports.ReportsIndex = ReportsIndex;
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SaveReportDialog extends Sol.FormDialog {
                constructor() {
                    super();
                    this.label = new Sol.Label();
                    this.nameField = new Sol.Field();
                    this.label.text = Sol.Environment.resources.nombre_informe + ':';
                    this.label.editor = this.nameField;
                    this.form.add(this.label);
                    this.nameField.maxLength = 50;
                    this.nameField.required = true;
                    this.form.add(this.nameField);
                    this.form.onSave = (e) => this.save();
                }
                clear() {
                    this.nameField.clear();
                }
                save() {
                    let filters = this.myTable.searchFields
                        .where(cp => !cp.isEmpty() && cp.value)
                        .select(cp => ({
                        ClassType: this.myTable.className,
                        PropertyName: cp.propertyName,
                        FilterValue: JSON.stringify(cp.value),
                        FilterType: cp.filterType
                    })).toArray();
                    let position = 1;
                    let columns = this.myTable.columns
                        .select(cl => ({
                        PropertyName: cl.PropertyName,
                        Position: position++,
                        ColumnWidth: null,
                        Sorted: cl.OrderingPropertyName == this.myTable.sortProperty,
                        SortOrder: this.myTable.sortOrder
                    })).toArray();
                    let reportModel = {
                        ClassName: this.myTable.className,
                        Name: this.nameField.textValue,
                        Filters: filters,
                        Columns: columns
                    };
                    Web.System.exec("qls4dgg24s", "Save", reportModel, () => this.complete());
                }
                complete() {
                    this.form.workComplete();
                    this.visible = false;
                    this.myTable.loadCustomReports();
                }
            }
            Components.SaveReportDialog = SaveReportDialog;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Kanban;
            (function (Kanban) {
                class KanbanColum extends Sol.Control {
                    constructor(model, view) {
                        super();
                        this.css.add("sol_kanban_column");
                        const title = new Components.Displays.ColorizedDisplay();
                        title.setValue({ Campo: model.Name, Color: model.Color, Valor: null });
                        this.add(title);
                        if (model.Totals)
                            this.controls.addMany(Sol.List.from(model.Totals).select(tot => {
                                const total = new Sol.Control();
                                total.css.add("sol_kanban_total");
                                total.estilos.agregar("color", model.Color);
                                total.text = tot;
                                return total;
                            }));
                        const decisions = view.availableDecisions.where(decision => decision.StatusCode == model.StatusID);
                        var curDate;
                        Sol.List.from(model.Cards).forEach(c => {
                            if (curDate != c.FormattedDate) {
                                const dateText = new Sol.Control();
                                dateText.text = c.FormattedDate;
                                dateText.css.add("sol_kanban_date");
                                this.add(dateText);
                            }
                            this.add(new Kanban.Card(model, c, view, decisions));
                            curDate = c.FormattedDate;
                        });
                    }
                }
                Kanban.KanbanColum = KanbanColum;
            })(Kanban = Components.Kanban || (Components.Kanban = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Kanban;
            (function (Kanban) {
                class KanbanView extends Sol.Control {
                    constructor() {
                        super();
                        this.toolbar = new Sol.Control();
                        this.cardsArea = new Sol.Control();
                        this.amountCombo = new Sol.Combo();
                        this.css.add("sol_kanban_view");
                        this.cardsArea.css.add("sol_kanban");
                        this.addMany([this.toolbar, this.cardsArea]);
                    }
                    refresh(page, rowCount, filters) {
                        this.page = page;
                        this.rowCount = rowCount;
                        this.lastFilters = filters;
                        const kanbanData = {
                            className: this.className,
                            currentPage: page,
                            resultCount: rowCount,
                            filters: filters,
                            amountProperty: this.amountCombo.selectedCode
                        };
                        Web.System.exec("dsj38en91", "RefreshKanban", kanbanData, model => {
                            this.loadData(model);
                            this.onSearch(model.TotalPages, model.TotalResults, model.ResultCount);
                        });
                    }
                    build() {
                        super.build();
                        this.initToolbar();
                    }
                    initToolbar() {
                        this.toolbar.css.add("sol_toolbar");
                        if (this.kanbanInfo.ShowTotalCombo) {
                            this.amountCombo.loadOptions(this.kanbanInfo.AmountPropertyOptions);
                            this.amountCombo.onValueModified.subscribe(() => this.refresh(this.page, this.rowCount, this.lastFilters));
                            this.toolbar.addCtr("Valor:", null, "label");
                            this.toolbar.add(this.amountCombo);
                        }
                    }
                    loadData(model) {
                        this.cardsArea.controls.empty();
                        this.cardsArea.controls.addMany(Sol.List.from(model.Colums).select(cl => new Kanban.KanbanColum(cl, this)));
                    }
                }
                Kanban.KanbanView = KanbanView;
            })(Kanban = Components.Kanban || (Components.Kanban = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class FilterView extends Sol.Control {
                constructor() {
                    super();
                    this.css.add("sol_filter_view");
                }
                loadItems(items) {
                    this.controls.empty();
                    this.addMany(Sol.List.from(items).select(i => {
                        const item = new Components.FilterViewItem(i);
                        item.onClick = () => this.onRequestFilter(item);
                        return item;
                    }));
                }
                showLoader() {
                    this.controls.empty();
                    this.addCtr(Sol.Environment.resources.cargando, null);
                }
            }
            Components.FilterView = FilterView;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let DataViewMode;
            (function (DataViewMode) {
                DataViewMode[DataViewMode["Grid"] = 0] = "Grid";
                DataViewMode[DataViewMode["Map"] = 1] = "Map";
                DataViewMode[DataViewMode["Reports"] = 2] = "Reports";
                DataViewMode[DataViewMode["Kanban"] = 3] = "Kanban";
                DataViewMode[DataViewMode["FilterView"] = 4] = "FilterView";
                DataViewMode[DataViewMode["Overview"] = 5] = "Overview";
            })(DataViewMode = Components.DataViewMode || (Components.DataViewMode = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class Bell extends Sol.Button {
                constructor() {
                    super();
                    this.imageCode = "&#xf0f3;";
                    this.onClick = () => this.stop();
                }
                destroy() {
                    if (this.connection)
                        this.connection.stop();
                    if (this.player)
                        this.player.pause();
                    super.destroy();
                }
                build() {
                    super.build();
                    Sol.Environment.loadLibrary({
                        name: "signalr",
                        source: "/frameworks/signalr.js"
                    });
                    this.player = new Audio("/Theme/Resources/alert.mp3");
                    this.player.loop = true;
                    setTimeout(() => {
                        var huburl = "https://push.letrearte.com/solhub?g=new_deal&c=" + Sol.Environment.credential.empresa;
                        console.log(huburl);
                        this.connection = new signalR.HubConnectionBuilder().withUrl(huburl).build();
                        this.connection.start();
                        this.connection.on("SolHubMessage", () => this.beep());
                    }, 1000);
                }
                beep() {
                    this.player.play();
                    this.css.add("sol_bell_on");
                }
                stop() {
                    this.player.pause();
                    this.css.remove("sol_bell_on");
                }
            }
            Components.Bell = Bell;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PageSizeCombo extends Sol.Combo {
                constructor() {
                    super();
                    this.addItems([{ Campo: "10", Valor: 10 }, { Campo: "20", Valor: 20 }, { Campo: "50", Valor: 50 }, { Campo: "100", Valor: 100 }]);
                }
            }
            Components.PageSizeCombo = PageSizeCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class GridNavigation extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.previousPageButton = new Sol.Button();
                    this.nextPageButton = new Sol.Button();
                    this.pageSizeCombo = new Components.PageSizeCombo();
                }
                get pageSize() { return parseInt(this.pageSizeCombo.selectedCode); }
                set pageSize(value) { this.pageSizeCombo.selectedCode = value.toString(); }
                updateButtonState(currentPage, pageCount) {
                    if (currentPage == 1)
                        this.previousPageButton.css.add("desactivado");
                    else
                        this.previousPageButton.css.remove("desactivado");
                    if (currentPage == pageCount)
                        this.nextPageButton.css.add("desactivado");
                    else
                        this.nextPageButton.css.remove("desactivado");
                }
                build() {
                    super.build();
                    this.css.add("sol_tabla_navegacion");
                    this.previousPageButton.imageCode = "&#xf053;";
                    this.previousPageButton.css.add("desactivado");
                    this.previousPageButton.onClick = () => this.onPreviousPage();
                    this.add(this.previousPageButton);
                    this.nextPageButton.imageCode = "&#xf054;";
                    this.nextPageButton.css.add("desactivado");
                    this.nextPageButton.onClick = () => this.onNextPage();
                    this.add(this.nextPageButton);
                    this.add(this.pageSizeCombo);
                    this.pageSizeCombo.onChange = () => this.onPageSizeChanged(this);
                }
            }
            Components.GridNavigation = GridNavigation;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DataView extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.addButton = new Sol.Button();
                    this.bell = new Components.Bell();
                    this.bottomNavigation = new Components.GridNavigation();
                    this.configButton = new Sol.Button();
                    this.reportsViewButton = new Sol.Button();
                    this.columnsDialog = new Components.ColumnsSelectorDialog();
                    this.bottomResultsText = new Sol.Control("span");
                    this.customReportsArea = new Sol.Control();
                    this.error = new Sol.ScreenMessage();
                    this.filterViewButton = new Sol.Button();
                    this.filterView = new Components.FilterView();
                    this.gridArea = new Sol.Control("td");
                    this.groupButton = new Sol.Button();
                    this.overviewButton = new Sol.Button();
                    this.gridViewButton = new Sol.Button();
                    this.kanban = new Components.Kanban.KanbanView();
                    this.kanbanViewButton = new Sol.Button();
                    this.mainTotalField = new Sol.CurrencyField();
                    this.map = new Sol.Geo.Map();
                    this.mapViewButton = new Sol.Button();
                    this.rodapie = new Sol.Control("tfoot");
                    this.mainTable = new Sol.Control("table");
                    this.mainTableLine = new Sol.Control("tr");
                    this.refreshButton = new Sol.Button();
                    this.reportsArea = new Components.Reports.ReportsIndex();
                    this.saveButton = new Sol.Button();
                    this.saveReportDialog = new Components.SaveReportDialog();
                    this.searchArea = new Sol.Control("td");
                    this.searchButton = new Sol.Button();
                    this.searchForm = new Sol.Form();
                    this.toolboxBar = new Sol.Control();
                    this.topNavigation = new Components.GridNavigation();
                    this.topNavigationBar = new Sol.Control();
                    this.topResultsText = new Sol.Control("span");
                    this.publishQuantityIcon = new Components.PublishIcon();
                    this.viewModeBar = new Sol.Control();
                    this.excelButton = new Sol.Button();
                    this.printButton = new Sol.Button();
                    this.grid = new Components.Grid();
                    this.allowNew = true;
                    this.allowSelectColumns = true;
                    this.availableColumns = new Sol.List();
                    this.searchFields = new Sol.List();
                    this.customReportsList = new Sol.List();
                    this.filters = new Sol.List();
                    this.footer = new Sol.Control();
                    this.isComplex = true;
                    this.page = 1;
                    this.pageCount = 0;
                    this.savableProperties = [];
                    this.kanbanInfo = {};
                    this.showSearchBox = true;
                    this.toolbox = new Sol.Control();
                    this._viewMode = Components.DataViewMode.Grid;
                    this.onDecision = new Sol.EventHandler();
                    this.onInstantiateRow = () => { };
                }
                get allowDelete() { return this.grid.allowDelete; }
                set allowDelete(value) { this.grid.allowDelete = value; }
                get allowReorder() { return this.grid.allowReorder; }
                set allowReorder(value) { this.grid.allowReorder = value; }
                get availableDecisions() { return this.grid.availableDecisions.toArray(); }
                set availableDecisions(value) {
                    this.grid.availableDecisions = Sol.List.from(value);
                    this.kanban.availableDecisions = this.grid.availableDecisions;
                }
                get className() { return this.grid.className; }
                set className(value) { this.grid.className = value; }
                get selection() { return this.grid.selection; }
                get columns() { return this.grid.columns; }
                set columns(value) { this.grid.columns = value; }
                get cost() { return 0; }
                get margin() { return this.total; }
                toControl() { return this; }
                get fixedRows() { return this.grid.fixedRows; }
                set fixedRows(value) { this.grid.fixedRows = value; }
                get icon() { return this.grid.icon; }
                set icon(value) { this.grid.icon = value; }
                get isSummable() { return true; }
                get rows() { return this.grid.rows; }
                get readonly() { return this.grid.readonly; }
                set readonly(value) {
                    this.grid.readonly = value;
                    this.addButton.visible = !value;
                }
                get rowCount() { return this.grid.rowCount; }
                set rowCount(value) { this.grid.rowCount = value; }
                get searchBoxOpen() { return this.searchButton.checked; }
                set searchBoxOpen(value) {
                    this.searchButton.checked = value;
                    this.searchButtonChecked(false);
                }
                get sortProperty() { return this.grid.sortProperty; }
                set sortProperty(value) { this.grid.sortProperty = value; }
                get sortOrder() { return this.grid.sortOrder; }
                set sortOrder(value) { this.grid.sortOrder = value; }
                get showChecks() { return this.grid.showChecks; }
                set showChecks(value) { this.grid.showChecks = value; }
                get showFieldChanges() { return this.grid.showFieldChanges; }
                set showFieldChanges(value) { this.grid.showFieldChanges = value; }
                get showHeader() { return this.grid.showHeader; }
                set showHeader(value) { this.grid.showHeader = value; }
                get showVerticalLines() { return this.grid.showVerticalLines; }
                set showVerticalLines(value) { this.grid.showVerticalLines = value; }
                get total() {
                    return this.rows
                        .where(row => (row.getEditor("Approved") !== null &&
                        row.getEditor("Approved").checked &&
                        row.getEditor("Total") !== null)
                        ||
                            (row.getEditor("Approved") == null &&
                                row.getEditor("Total") !== null))
                        .sum(row => row.getEditor("Total").numericValue);
                }
                validate() { return null; }
                get value() { return this.getValor(); }
                set value(v) { this.setValor(v); }
                get viewMode() { return this._viewMode; }
                set viewMode(value) {
                    this._viewMode = value;
                    this.overviewButton.checked = value == Components.DataViewMode.Overview;
                    this.gridViewButton.checked = value == Components.DataViewMode.Grid;
                    this.kanbanViewButton.checked = value == Components.DataViewMode.Kanban;
                    this.mapViewButton.checked = value == Components.DataViewMode.Map;
                    this.filterViewButton.checked = value == Components.DataViewMode.FilterView;
                    this.reportsViewButton.checked = value == Components.DataViewMode.Reports;
                    this.grid.visible = value == Components.DataViewMode.Grid;
                    this.topNavigationBar.visible = value == Components.DataViewMode.Grid || value == Components.DataViewMode.Kanban;
                    this.footer.visible = value == Components.DataViewMode.Grid || value == Components.DataViewMode.Kanban;
                    this.kanban.visible = value == Components.DataViewMode.Kanban;
                    this.map.visible = value == Components.DataViewMode.Map;
                    if (this.overviewControl)
                        this.overviewControl.visible = value == Components.DataViewMode.Overview;
                    this.filterView.visible = value == Components.DataViewMode.FilterView;
                    this.reportsArea.visible = value == Components.DataViewMode.Reports;
                    this.excelButton.enabled = value == Components.DataViewMode.Grid || value == Components.DataViewMode.Reports;
                    if (value == Components.DataViewMode.Reports)
                        this.reportsArea.loadReports();
                    this.toolbox.controls.where(b => b !== this.excelButton).cast().forEach(b => b.enabled = value == Components.DataViewMode.Grid);
                    this.refreshButton.enabled = true;
                    this.groupButton.enabled = value == Components.DataViewMode.Grid;
                    this.printButton.enabled = value == Components.DataViewMode.Grid || value == Components.DataViewMode.Reports;
                    if (!this.disableRefresh && !this.isOpening)
                        this.refresh();
                    this.disableRefresh = false;
                    if (this.isOpening || Sol.Environment.isMobile || value == Components.DataViewMode.Reports || value == Components.DataViewMode.FilterView)
                        return;
                    this.savePreference("ViewMode", value);
                }
                savePreference(propertyName, value) {
                    const data = {
                        ClassName: this.className,
                        PreferenceProperty: propertyName,
                        PreferenceValue: value
                    };
                    Web.System.exec("qlsmeret", "SavePreference", data);
                }
                addRow(data = null) { return this.grid.addRow(data); }
                clearSelection() { this.grid.clearSelection(); }
                deleteRow(row) {
                    this.grid.deleteRow(row);
                    this.refreshTotal();
                    this.showCurrentTotals();
                    return false;
                }
                empty() { this.grid.deleteAllRows(); }
                findRowsByProperty(propertyName, value) { return this.grid.findRowsByProperty(propertyName, value); }
                foco() {
                    if (this.searchFields.hasItems())
                        this.searchFields.first().foco();
                }
                getCodeByRowIndex(index) { return this.rows.item(index - 1).code; }
                getColumnValues(propertyName) {
                    return Sol.List.from(this.value).select(i => Sol.List.from(i).that(fld => fld.Campo == propertyName).Valor);
                }
                getFilters() {
                    if (!this.modoSol && this.initialFilters)
                        return Sol.List.from(this.initialFilters);
                    const filters = this.searchFields
                        .where(cp => !cp.isEmpty())
                        .select(cp => ({
                        PropertyName: cp.propertyName,
                        FilterValue: cp.value,
                        FilterType: cp.filterType
                    }));
                    if (this.anchorage)
                        filters.add(this.anchorage);
                    return filters;
                }
                getPropertyValueByID(propertyName, code) {
                    return this.grid.getPropertyValueByID(propertyName, code);
                }
                GetRowByCode(code) { return this.grid.rows.that(row => row.code == code); }
                isEmpty() { return this.grid.isEmpty(); }
                clear() {
                    this.grid.clear();
                    this.rodapie.controls.empty();
                }
                loadCustomReports() {
                    var reportListModel = { ClassName: this.className };
                    Web.System.exec("qls4dgg24s", "List", reportListModel, e => this.loadCustomReportsComplete(e));
                }
                rebuildTable() {
                    this.grid.empty();
                    this.grid.buildHeader();
                }
                refresh(callback = null) {
                    var _a;
                    this.error.visible = false;
                    switch (this.viewMode) {
                        case Components.DataViewMode.Grid:
                        case Components.DataViewMode.Reports:
                            const properties = this.columns.select(cl => cl.PropertyName);
                            this.publishQuantityIcon.visible = false;
                            if (!properties.hasItems())
                                return;
                            if (!this.currentCustomReport) {
                                this.defaultViewSortProperty = this.sortProperty;
                                this.defaultViewSortOrder = this.sortOrder;
                            }
                            const updateColumns = false;
                            const data = {
                                className: this.className,
                                currentPage: this.page,
                                rowCount: this.rowCount,
                                filters: this.lastFilters,
                                sortProperty: this.sortProperty,
                                sortOrder: this.sortOrder == Components.ColumnOrder.Descending ? Web.Ordering.descending : Web.Ordering.ascending,
                                properties: properties.toArray(),
                                pageInfo: true,
                                contextID: (_a = this.anchorage) === null || _a === void 0 ? void 0 : _a.FilterValue,
                                columnInfo: updateColumns,
                                groupBy: this.currentGroup
                            };
                            Web.System.exec("i3n48smak", "Search", data, model => {
                                if (model.Fail) {
                                    this.error.visible = true;
                                    this.searchForm.workComplete();
                                    return;
                                }
                                if (updateColumns) {
                                    this.availableColumns = Sol.List.from(model.Columns);
                                    this.columns = this.availableColumns;
                                    this.rebuildTable();
                                }
                                this.resultCount = model.ResultCount;
                                this.pageResultCount = this.grid.loadData(model);
                                this.pageCount = model.PageCount;
                                this.refreshNavigation(model.ResultCount, this.pageResultCount);
                                this.showTotals(model.TotalInfo);
                                this.highlightSearchedTerms();
                                this.searchForm.workComplete();
                                callback === null || callback === void 0 ? void 0 : callback.call(this);
                            });
                            break;
                        case Components.DataViewMode.Map:
                            var mapData = {
                                className: this.className,
                                filters: this.lastFilters
                            };
                            Web.System.exec("dh3q8bdpq", "SearchMap", mapData, model => {
                                this.map.showEntities(model.Entities);
                                this.searchForm.workComplete();
                            });
                            break;
                        case Components.DataViewMode.Kanban:
                            this.kanban.refresh(this.page, this.rowCount, this.lastFilters);
                            break;
                        case Components.DataViewMode.Overview:
                            this.overviewControl.refresh(this.lastFilters);
                            this.searchForm.workComplete();
                            break;
                    }
                    this.reportsArea.refresh();
                }
                refreshNavigation(resultCount, itemCount) {
                    this.rodapie.controls.empty();
                    if (resultCount == 0)
                        this.bottomResultsText.text = Sol.Environment.resources.no_encontrado;
                    else {
                        var initialResult = ((this.page - 1) * this.rowCount) + 1;
                        var finalResult = initialResult + itemCount - 1;
                        this.bottomResultsText.text = Sol.Environment.resources.mostrando + initialResult + " - " + finalResult + Sol.Environment.resources.de + resultCount;
                        this.publishQuantityIcon.filters = Sol.List.from(this.lastFilters);
                        this.publishQuantityIcon.columns = this.getColumnsAsReportColumns();
                        this.publishQuantityIcon.visible = true;
                    }
                    this.topResultsText.text = this.bottomResultsText.text;
                    this.bottomNavigation.updateButtonState(this.page, this.pageCount);
                    this.topNavigation.updateButtonState(this.page, this.pageCount);
                }
                refreshTotal() {
                    this.mainTotalField.numericValue = this.total;
                    if (this.onTotalsChanged)
                        this.onTotalsChanged();
                }
                registerEvents() {
                    super.registerEvents();
                    this.setFilters(this.initialFilters);
                }
                saveColumns() {
                    var _a;
                    const columnPreferences = this.columns.select(col => ({
                        PropertyName: col.PropertyName,
                        Position: col.Position,
                        ColumnWidth: null,
                        Sorted: col.OrderingPropertyName == this.sortProperty,
                        SortOrder: this.sortOrder
                    })).toArray();
                    if (this.currentCustomReport)
                        this.currentCustomReport.Columns = columnPreferences;
                    const preferencesModel = {
                        Credential: Sol.Environment.credential.export(),
                        ClassName: this.className,
                        CustomReport: (_a = this.currentCustomReport) === null || _a === void 0 ? void 0 : _a.ID,
                        Columns: columnPreferences
                    };
                    Web.System.exec("qlsmeret", "SaveGridColumns", preferencesModel);
                }
                search() {
                    this.page = 1;
                    this.lastFilters = this.getFilters().toArray();
                    this.refresh();
                    if (Sol.Environment.isMobile) {
                        this.searchButton.checked = false;
                        this.searchButtonChecked(false);
                    }
                }
                setColumnReadonly(propertyName, value) {
                    this.rows.forEach(row => row.getEditor(propertyName).readonly = value);
                    const column = this.availableColumns.that(cl => cl.PropertyName == propertyName);
                    if (column)
                        column.EditorModel.ReadOnly = value;
                }
                setColumnVisibility(propertyName, value) {
                    this.grid.setColumnVisibility(propertyName, value);
                }
                setDefaultColumns() {
                    this.columns = this.availableColumns
                        .where(column => column.Visible)
                        .orderBy(column => column.Position);
                }
                setFilters(filters, commit = false) {
                    if (!filters)
                        return;
                    if (!this.modoSol)
                        this.initialFilters = filters;
                    let newFilters = new Sol.List();
                    this.clearSearchFilters();
                    Sol.List.from(filters).forEach(flt => {
                        let filter = this.searchFields.that(campo => campo.propertyName == flt.PropertyName);
                        if (!filter)
                            return;
                        let filterValue = JSON.parse(flt.FilterValue);
                        filter.value = filterValue;
                        newFilters.add({ FilterType: flt.FilterType, PropertyName: flt.PropertyName, FilterValue: filterValue });
                    });
                    if (commit)
                        this.lastFilters = newFilters.toArray();
                }
                setFilter(propertyName, value) {
                    let filter = this.searchFields.that(campo => campo.propertyName == propertyName);
                    if (!filter)
                        return;
                    filter.value = value;
                }
                showNextPage(callback = null) {
                    if (this.page >= this.pageCount)
                        return;
                    this.page++;
                    this.refresh(callback);
                }
                showPage(pageNumber, callback = null) {
                    this.page = pageNumber;
                    this.refresh(callback);
                }
                showPreviousPage(callback = null) {
                    if (this.page <= 1)
                        return;
                    this.page--;
                    this.refresh(callback);
                }
                sum(propertyName) {
                    return this.rows.sum(row => row.getEditor(propertyName).numericValue);
                }
                updateRow(row, data = null) { this.grid.updateRow(row, data); }
                build() {
                    super.build();
                    this.initializeMainStructure();
                    this.initializeErrorMessage();
                    if (this.showSearchBox)
                        this.initializeSearchArea();
                    if (this.showToolbox)
                        this.initializeToolbox();
                    this.initializeTopNavigationBar();
                    this.initializeOverview();
                    this.initializeGridArea();
                    if (this.kanbanInfo.ShowKanban)
                        this.initializeKanban();
                    if (this.showMap)
                        this.initializeMap();
                    if (this.showSearchBox)
                        this.initializeFilterView();
                    if (this.showReports)
                        this.initializeReports();
                    this.initializeFooter();
                    if (this.showSearchBox)
                        this.loadCustomReports();
                    if (this.defaultValue)
                        this.value = this.defaultValue;
                }
                getColumnIndexByPropertyName(propertyName) {
                    return this.grid.getColumnIndexByPropertyName(propertyName);
                }
                getValor() {
                    return this.rows.select(ln => ln.editors
                        .select(editor => ({ Campo: editor.propertyName, Valor: editor.value }))
                        .union([{ Campo: "ID", Valor: ln.code }])
                        .union(Sol.List.from(this.savableProperties).select(p => ({ Campo: p, Valor: ln.getDataByPropertyName(p) })).toArray())
                        .toArray())
                        .toArray();
                }
                setValor(v) {
                    this.grid.deleteAllRows();
                    Sol.List.from(v).cast().forEach(d => this.addRow(d));
                    setTimeout(() => {
                        this.refreshTotal();
                        this.showCurrentTotals();
                    }, 500);
                }
                addBell() {
                    if (!this.showBell)
                        return;
                    this.bell.classHash = this.classHash;
                    this.toolbox.controls.insert(0, this.bell);
                }
                addGroupButton() {
                    var _a;
                    if (!((_a = this.availableGroups) === null || _a === void 0 ? void 0 : _a.length))
                        return;
                    this.groupButton.imageCode = "&#xf247;";
                    this.groupButton.tip = Sol.Environment.resources.dataviewGroup;
                    this.toolbox.controls.insert(0, this.groupButton);
                    const noneMenu = new Sol.CheckMenu(Sol.Environment.resources.none);
                    noneMenu.checked = true;
                    noneMenu.onClick = () => this.changeGroup(noneMenu);
                    this.groupButton.subitems.add(noneMenu);
                    this.groupButton.subitems.addMany(Sol.List.from(this.availableGroups).select(g => {
                        const groupMenu = new Sol.CheckMenu(g.GroupName);
                        groupMenu.data = g.PropertyName;
                        groupMenu.onClick = () => this.changeGroup(groupMenu);
                        return groupMenu;
                    }));
                }
                changeGroup(menu) {
                    this.groupButton.subitems.cast().forEach(m => m.checked = false);
                    menu.checked = true;
                    this.currentGroup = menu.data;
                    this.groupButton.hidePopup();
                    this.page = 1;
                    this.refresh();
                }
                addConfigButton() {
                    if (!this.showConfigButton)
                        return;
                    this.configButton.imageCode = "&#xf013;";
                    this.configButton.tip = Sol.Environment.resources.configuraciones;
                    this.addColumnsSelectorButton();
                    this.addVerticalLinesSwitch();
                    this.toolbox.controls.insert(0, this.configButton);
                }
                addColumnsSelectorButton() {
                    if (!this.allowSelectColumns)
                        return;
                    const columnsMenu = new Sol.CheckMenu();
                    columnsMenu.caption = Sol.Environment.resources.elegir_columnas + "...";
                    columnsMenu.onClick = () => this.choiceColumns();
                    this.columnsDialog.myTable = this;
                    this.columnsDialog.visible = false;
                    this.columnsDialog.onSaved = () => this.columnsChanged();
                    this.controls.insert(0, this.columnsDialog);
                    this.configButton.subitems.add(columnsMenu);
                }
                addVerticalLinesSwitch() {
                    const verticalLinesMenu = new Sol.CheckMenu();
                    verticalLinesMenu.caption = "Linhas verticais";
                    verticalLinesMenu.checked = this.showVerticalLines;
                    verticalLinesMenu.onClick = () => {
                        verticalLinesMenu.checked = !verticalLinesMenu.checked;
                        this.showVerticalLines = verticalLinesMenu.checked;
                        this.configButton.hidePopup();
                        this.savePreference("ShowVerticalLines", verticalLinesMenu.checked);
                    };
                    this.configButton.subitems.add(verticalLinesMenu);
                }
                addExcelButton() {
                    this.excelButton.imageCode = '&#xf1c3;';
                    this.excelButton.tip = Sol.Environment.resources.excel;
                    this.excelButton.onClick = () => this.exportToExcel();
                    this.toolbox.controls.insert(0, this.excelButton);
                }
                addPrintButton() {
                    this.printButton.imageCode = '&#xf02f;';
                    this.printButton.tip = Sol.Environment.resources.print;
                    this.printButton.onClick = () => this.print();
                    this.toolbox.controls.insert(0, this.printButton);
                }
                addRefreshButton() {
                    this.refreshButton.imageCode = '&#xf021;';
                    this.refreshButton.tip = Sol.Environment.resources.actualizar;
                    this.refreshButton.onClick = () => this.refresh();
                    this.toolbox.controls.insert(0, this.refreshButton);
                }
                addTotalRow(addMainField) {
                    this.totalRow = new Components.GridRow();
                    let checkCell = new Components.GridCell();
                    checkCell.columnSpan = 2;
                    if (this.showChecks)
                        this.totalRow.add(checkCell);
                    this.grid.fillBlankRow(this.totalRow);
                    if (!this.readonly)
                        this.totalRow.add(new Components.GridCell());
                    let totalIndex = this.getColumnIndexByPropertyName("Total");
                    if (addMainField && !this.readonly && totalIndex > 0) {
                        this.mainTotalField.readonly = true;
                        this.mainTotalField.textBold = true;
                        this.totalRow.controls.item(totalIndex).add(this.mainTotalField);
                    }
                    if (this.showChecks)
                        this.totalRow.controls.removeItem(1);
                    this.totalRow.controls.first().text = Sol.Environment.resources.totales;
                    this.totalRow.controls.skip(1).forEach(ctr => ctr.estilos.agregar("text-align", "right"));
                    this.rodapie.add(this.totalRow);
                    return this.totalRow;
                }
                showCurrentTotals() {
                    const totals = this.columns.where(cl => cl.ShowTotals).select(cl => ({
                        PropertyName: cl.PropertyName,
                        Totals: Sol.CurrencyField.sumFields(this.grid.getEditors(cl.PropertyName))
                            .select(v => ({ FormattedValue: v }))
                            .toArray()
                    })).toArray();
                    this.showTotals({ Totals: totals });
                }
                showTotals(total) {
                    if (!total || this.disableTotals)
                        return;
                    let totalList = Sol.List.from(total.Totals);
                    if (!totalList.hasItems())
                        return;
                    if (!this.totalRow || !this.totalRow.html.isConnected)
                        this.addTotalRow(true);
                    totalList.forEach(total => {
                        let colIndex = this.getColumnIndexByPropertyName(total.PropertyName);
                        let cell = this.totalRow.controls.item(colIndex);
                        if (!cell)
                            return;
                        let values = Sol.List.from(total.Totals).select(tot => tot.FormattedValue);
                        cell.controls.empty();
                        cell.controls.addMany(values.select(value => {
                            let valueControl = new Sol.Control();
                            valueControl.text = value;
                            valueControl.textAfterControls = true;
                            if (this.allowDashboardCustomization) {
                                let icon = new Components.PublishIcon();
                                icon.classType = this.className;
                                icon.reportTypeName = "Scussel.Models.Reports.Engines.ResultListReport, Scussel.Models.Reports, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                                icon.propertyName = total.PropertyName;
                                icon.filters = Sol.List.from(this.lastFilters);
                                icon.columns = this.getColumnsAsReportColumns();
                                valueControl.add(icon);
                            }
                            return valueControl;
                        }));
                    });
                    this.addTotalExtraRows(total);
                }
                addTotalExtraRows(total) {
                    if (!total.ExtraRows || total.ExtraRows.length == 0)
                        return;
                    Sol.List.from(total.ExtraRows).forEach(row => {
                        var extraRow = this.addTotalRow(false);
                        extraRow.cells.first().text = row.Caption;
                        Sol.List.from(row.Data).forEach(rowData => {
                            const colIndex = this.getColumnIndexByPropertyName(rowData.PropertyName);
                            extraRow.cells.item(colIndex).text = rowData.Text;
                        });
                    });
                }
                getColumnsAsReportColumns() {
                    return this.columns.select(cl => ({
                        Title: cl.Title,
                        PropertyName: cl.PropertyName,
                        ClassType: this.className,
                        Availability: Components.Reports.ReportColumnAvailability.visibleByDefault,
                        Loadable: true
                    }));
                }
                highlightSearchedTerms() {
                    Sol.List.from(this.lastFilters)
                        .where(filter => filter.FilterType == "SText" || filter.FilterType == "SEmail")
                        .where(filter => !filter.FilterValue.Campo)
                        .where(filter => this.getColumnIndexByPropertyName(filter.PropertyName) >= 0)
                        .forEach(filter => {
                        let columnIndex = this.getColumnIndexByPropertyName(filter.PropertyName) + this.grid.fixedColumnsCount;
                        this.rows
                            .where(row => !(!row.controls.item(columnIndex).text))
                            .where(row => !(!row.controls.item(columnIndex).html))
                            .forEach(row => row.controls.item(columnIndex).html.innerHTML = row.controls.item(columnIndex).text.highlight(filter.FilterValue));
                    });
                }
                initializeErrorMessage() {
                    this.error.caption = Sol.Environment.resources.error;
                    this.error.visible = false;
                    this.gridArea.add(this.error);
                }
                initializeFooter() {
                    if (!this.disableTotals && !this.readonly && (this.availableColumns.any(cl => cl.PropertyName === "Total" || cl.ShowTotals)))
                        this.addTotalRow(true);
                    this.footer.css.add("sol_tabla_footer");
                    this.gridArea.add(this.footer);
                    if (this.showSearchBox) {
                        this.bottomResultsText.text = Sol.Environment.resources.cargando;
                        this.bottomResultsText.css.add("sol_tabla_comentario");
                        this.footer.add(this.bottomResultsText);
                        this.publishQuantityIcon.classType = this.className;
                        this.publishQuantityIcon.reportTypeName = "Scussel.Models.Reports.Engines.QuantityListReport, Scussel.Models.Reports, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.publishQuantityIcon.visible = false;
                        this.footer.add(this.publishQuantityIcon);
                    }
                    if (!this.readonly && this.allowNew) {
                        this.addButton.type = Sol.ButtonType.Link;
                        this.addButton.text = Sol.Environment.resources.anadir_item;
                        this.addButton.css.add("sol_tabla_comentario");
                        this.addButton.onClick = () => this.addRowClick();
                        this.footer.add(this.addButton);
                    }
                    if (this.fixedRows) {
                        this.footer.add(this.bottomNavigation);
                        this.bottomNavigation.pageSize = this.rowCount;
                        this.bottomNavigation.onPreviousPage = () => this.showPreviousPage();
                        this.bottomNavigation.onNextPage = () => this.showNextPage();
                        this.bottomNavigation.onPageSizeChanged = e => this.changePageSize(e);
                    }
                    this.footer.add(new Sol.LineBreak());
                }
                initializeOverview() {
                    if (!this.overviewControl)
                        return;
                    this.gridArea.add(this.overviewControl);
                }
                initializeGridArea() {
                    this.mainTableLine.add(this.gridArea);
                    this.grid.onColumnClick = m => this.columnClick(m);
                    this.grid.onRowClick = (code, index) => this.rowClick(code, index);
                    this.grid.onRowChecked = (code, state) => this.rowCheck(code, state);
                    this.grid.onColumnDrop = () => this.columnDrop();
                    this.grid.onTotalChanged = () => this.refreshTotal();
                    this.grid.onDecision = d => this.makeDecision(d);
                    this.grid.onInlineEditorChanged = (edt, sc) => this.inlineEditorChanged(edt, sc);
                    this.grid.onRowDelete = row => this.rowDeleting(row);
                    this.grid.onInstantiateRow = row => this.onInstantiateRow(row);
                    this.grid.onRowCreated = row => this.rowCreated(row);
                    this.grid.footer = this.rodapie;
                    this.grid.disableTotals = this.disableTotals;
                    this.gridArea.add(this.grid);
                    this.grid.add(this.rodapie);
                    this.setDefaultColumns();
                    this.grid.buildHeader();
                }
                initializeKanban() {
                    this.kanban.className = this.className;
                    this.kanban.kanbanInfo = this.kanbanInfo;
                    this.kanban.onEdit = code => this.onEdit(code, null);
                    this.kanban.onDecision = dec => this.makeDecision(dec);
                    this.kanban.onSearch = (tp, tr, rc) => this.kanbanUpdated(tp, tr, rc);
                    this.gridArea.add(this.kanban);
                }
                initializeMainStructure() {
                    this.css.add("sol_tabla");
                    this.mainTable.css.add("sol_tabla_main");
                    this.add(this.mainTable);
                    this.mainTable.add(this.mainTableLine);
                    this.searchArea.css.add("sol_tabla_search");
                    this.gridArea.css.add("sol_tabla_grid");
                }
                initializeFilterView() {
                    this.filterView.visible = false;
                    this.gridArea.add(this.filterView);
                }
                initializeMap() {
                    this.map.visible = false;
                    this.map.entityName = this.titulo;
                    this.map.onEdit = i => this.onEdit(i, null);
                    this.gridArea.add(this.map);
                }
                initializeReports() {
                    this.reportsArea.className = this.className;
                    this.reportsArea.table = this;
                    this.reportsArea.allowDashboardCustomization = this.allowDashboardCustomization;
                    this.gridArea.add(this.reportsArea);
                }
                initializeSearchArea() {
                    this.searchArea.visible = !Sol.Environment.isMobile;
                    this.mainTableLine.add(this.searchArea);
                    this.searchButton.type = Sol.ButtonType.Alternate;
                    this.searchButton.imageCode = "&#xf002;";
                    this.searchButton.onChecked = () => this.searchButtonChecked(true);
                    this.searchButton.tip = Sol.Environment.resources.buscar;
                    this.searchButton.css.add("sol_tabla_search_button");
                    this.searchArea.add(this.searchButton);
                    this.searchForm.add(this.customReportsArea);
                    this.customReportsArea.css.add("sol_tabla_search_reports");
                    this.searchForm.okButton.text = Sol.Environment.resources.buscar;
                    this.searchForm.cancelButton.text = Sol.Environment.resources.limpiar;
                    this.searchForm.onCancel = () => this.clearSearchFilters();
                    this.searchForm.onSave = () => this.search();
                    this.searchForm.title = Sol.Environment.resources.buscar;
                    this.searchArea.add(this.searchForm);
                    if (this.showConfigButton) {
                        this.saveButton.text = Sol.Environment.resources.guardar;
                        this.saveButton.onClick = () => this.openSaveDialog();
                        this.searchForm.footer.add(this.saveButton);
                    }
                    this.saveReportDialog.myTable = this;
                    this.saveReportDialog.title = Sol.Environment.resources.guardar;
                    this.saveReportDialog.visible = false;
                    this.controls.insert(0, this.saveReportDialog);
                    this.filters.forEach(model => {
                        model.ViewCaption = `${Sol.Environment.resources.vision} ${Sol.Environment.resources.por.toLowerCase()} ${model.Caption.toLowerCase()}`;
                        const label = new Web.FilterLabel();
                        label.text = model.Caption + ":";
                        label.tip = model.ViewCaption;
                        label.showVisionButton = model.HasVision;
                        label.onViewRequested = () => this.requestFilterView(model);
                        this.searchForm.add(label);
                        const editor = Web.Editors.createFilter(model, this.className);
                        label.editor = editor;
                        editor.container = this.searchForm;
                        if (editor instanceof Web.Geo.AddressEditor) {
                            label.editor = editor;
                            label.minimizable = true;
                            label.expanded = false;
                        }
                        if (editor instanceof Components.DualComboFilter)
                            label.visible = false;
                        if (editor instanceof Sol.ComboFilter)
                            editor.onChange = () => this.search();
                        this.searchForm.editors.add(editor);
                        this.searchForm.add(editor.toControl());
                        this.searchFields.add(editor);
                    });
                }
                initializeToolbox() {
                    if (this.showSearchBox && Sol.Environment.isMobile) {
                        var searchButton = new Sol.Button();
                        searchButton.imageCode = "&#xf002;";
                        searchButton.onClick = () => {
                            this.searchButton.checked = true;
                            this.searchButtonChecked(false);
                        };
                        this.viewModeBar.add(searchButton);
                    }
                    if (this.overviewControl) {
                        this.overviewButton.imageCode = "&#xf080;";
                        this.overviewButton.text = Sol.Environment.resources.overview;
                        this.overviewButton.onClick = () => this.viewMode = Components.DataViewMode.Overview;
                        this.viewModeBar.add(this.overviewButton);
                    }
                    this.gridViewButton.imageCode = "&#xf0ce;";
                    this.gridViewButton.text = Sol.Environment.resources.grid;
                    this.gridViewButton.onClick = () => this.viewMode = Components.DataViewMode.Grid;
                    this.viewModeBar.add(this.gridViewButton);
                    if (this.kanbanInfo.ShowKanban) {
                        this.kanbanViewButton.imageCode = "&#xf00a;";
                        this.kanbanViewButton.text = Sol.Environment.resources.cards;
                        this.kanbanViewButton.onClick = () => this.viewMode = Components.DataViewMode.Kanban;
                        this.viewModeBar.add(this.kanbanViewButton);
                    }
                    if (this.showMap) {
                        this.mapViewButton.imageCode = "&#xf279;";
                        this.mapViewButton.text = Sol.Environment.resources.mapa;
                        this.mapViewButton.onClick = () => this.viewMode = Components.DataViewMode.Map;
                        this.viewModeBar.add(this.mapViewButton);
                    }
                    if (this.showSearchBox) {
                        this.filterViewButton.imageCode = "&#xf00a;";
                        this.filterViewButton.visible = false;
                        this.filterViewButton.onClick = () => this.viewMode = Components.DataViewMode.FilterView;
                        this.viewModeBar.add(this.filterViewButton);
                    }
                    this.reportsViewButton.imageCode = "&#xf200;";
                    this.reportsViewButton.text = Sol.Environment.resources.reports;
                    this.reportsViewButton.onClick = () => this.viewMode = Components.DataViewMode.Reports;
                    this.viewModeBar.add(this.reportsViewButton);
                    this.viewModeBar.css.add("sol_tabla_viewmodebar");
                    this.toolboxBar.add(this.viewModeBar);
                    this.toolbox.css.add("sol_tabla_toolbox");
                    this.toolboxBar.css.add("sol_toolbar");
                    this.toolboxBar.add(this.toolbox);
                    this.toolboxBar.add(new Sol.LineBreak());
                    this.gridArea.add(this.toolboxBar);
                    if (this.canExportToExcel) {
                        this.addExcelButton();
                        this.addPrintButton();
                    }
                    this.addConfigButton();
                    this.addGroupButton();
                    this.addRefreshButton();
                    this.addBell();
                }
                initializeTopNavigationBar() {
                    if (!this.fixedRows)
                        return;
                    this.topNavigationBar.css.add("sol_tabla_footer");
                    this.gridArea.add(this.topNavigationBar);
                    if (this.showSearchBox) {
                        this.topResultsText.text = Sol.Environment.resources.cargando;
                        this.topResultsText.css.add("sol_tabla_comentario");
                        this.topNavigationBar.add(this.topResultsText);
                    }
                    this.topNavigationBar.add(this.topNavigation);
                    this.topNavigation.pageSize = this.rowCount;
                    this.topNavigation.onPreviousPage = () => this.showPreviousPage();
                    this.topNavigation.onNextPage = () => this.showNextPage();
                    this.topNavigation.onPageSizeChanged = e => this.changePageSize(e);
                    this.topNavigationBar.add(new Sol.LineBreak());
                }
                loadCustomReportsComplete(list) {
                    this.customReportsArea.controls.empty();
                    this.customReportsList.empty();
                    if (!list || !list.length)
                        return;
                    this.customReportsList.addMany(list);
                    var title = new Sol.Control("h5");
                    title.text = Sol.Environment.resources.vistas_personalizadas;
                    this.customReportsArea.add(title);
                    var defaultReport = new Sol.RadioField();
                    defaultReport.caption = Sol.Environment.resources.por_defecto;
                    defaultReport.group = this.id;
                    defaultReport.checked = !this.currentCustomReport;
                    defaultReport.onChange = () => this.customReportSelected(defaultReport);
                    this.customReportsArea.add(defaultReport);
                    var items = Sol.List.from(list);
                    this.customReportsArea.controls.addMany(items.select(i => {
                        var deleteButton = new Sol.Button();
                        deleteButton.imageCode = '&#xf014;';
                        deleteButton.data = i.ID;
                        deleteButton.onClick = () => this.deleteCustomReport(deleteButton);
                        var option = new Sol.RadioField();
                        option.caption = i.Name;
                        option.group = this.id;
                        option.data = i;
                        option.onChange = () => this.customReportSelected(option);
                        option.checked = this.currentCustomReport && this.currentCustomReport.Name == i.Name;
                        option.add(deleteButton);
                        return option;
                    }));
                    var filterTitle = new Sol.Control("h5");
                    filterTitle.text = Sol.Environment.resources.search_filters;
                    filterTitle.estilos.agregar("margin-top", "20px");
                    this.customReportsArea.add(filterTitle);
                    this.customReportsArea.visible = this.searchButton.checked && this.customReportsList.hasItems();
                }
                addRowClick() {
                    var _a;
                    if (this.onAddingItem)
                        this.onAddingItem(this);
                    else {
                        let newRow = this.addRow();
                        if (newRow.editors.hasItems())
                            (_a = newRow.editors.that(e => !e.readonly)) === null || _a === void 0 ? void 0 : _a.foco();
                    }
                    return false;
                }
                columnClick(model) {
                    this.refresh();
                    this.saveColumns();
                }
                rowCheck(code, checked) {
                    if (this.onItemChecked)
                        this.onItemChecked(this);
                }
                rowClick(code, rowIndex) {
                    if (this.onEdit)
                        this.onEdit(code, rowIndex);
                }
                rowCreated(row) {
                    if (this.onRowCreated)
                        this.onRowCreated(row);
                }
                rowDeleting(row) {
                    if (this.onDeletingRow)
                        this.onDeletingRow(row);
                    else
                        this.deleteRow(row);
                }
                changePageSize(sender) {
                    this.grid.deleteAllRows();
                    this.rowCount = sender.pageSize;
                    this.bottomNavigation.pageSize = this.rowCount;
                    this.topNavigation.pageSize = this.rowCount;
                    this.page = 1;
                    this.grid.generateBlankRows(this.rowCount);
                    this.refresh();
                    this.savePreference("LineCount", sender.pageSize);
                }
                choiceColumns() {
                    this.hideDialogs();
                    this.configButton.hidePopup();
                    this.columnsDialog.availableColumns = this.availableColumns.where(cl => !cl.IsFixed);
                    this.columnsDialog.visible = true;
                }
                columnDrop() {
                    this.rebuildTable();
                    this.search();
                    this.saveColumns();
                }
                columnsChanged() {
                    if (this.currentCustomReport) {
                        this.currentCustomReport.Columns = this.columnsDialog.selectedColumns.select(cl => ({
                            PropertyName: cl.PropertyName,
                            Position: cl.Position,
                            ColumnWidth: null,
                            Sorted: cl.OrderingPropertyName == this.sortProperty,
                            SortOrder: this.sortOrder
                        })).toArray();
                        this.loadCurrentCustomReport();
                    }
                    else {
                        this.availableColumns.forEach(cl => cl.Visible = this.columnsDialog.isColumnSelected(cl.PropertyName));
                        this.setDefaultColumns();
                    }
                    this.rebuildTable();
                    this.search();
                    this.saveColumns();
                }
                customReportSelected(e) {
                    if (!e.checked)
                        return;
                    this.clearSearchFilters();
                    if (e.data) {
                        this.currentCustomReport = e.data;
                        this.loadCurrentCustomReport();
                    }
                    else {
                        this.currentCustomReport = null;
                        this.sortProperty = this.defaultViewSortProperty;
                        this.sortOrder = this.defaultViewSortOrder;
                        this.setDefaultColumns();
                    }
                    this.rebuildTable();
                    this.search();
                }
                deleteCustomReport(e) {
                    if (!confirm(Sol.Environment.resources.confirmar_operacion +
                        Sol.Environment.resources.delete.toLowerCase() + "?"))
                        return;
                    let id = e.data;
                    Web.System.exec("qls4dgg24s", "Delete", { id: id }, () => this.deleteCustomReportComplete(id));
                }
                deleteCustomReportComplete(id) {
                    if (this.currentCustomReport && this.currentCustomReport.ID === id)
                        this.currentCustomReport = null;
                    this.loadCustomReports();
                }
                inlineEditorChanged(editor, saveChanges) {
                    if (this.columns.that(cl => cl.PropertyName == editor.propertyName))
                        setTimeout(() => this.showCurrentTotals(), 300);
                    if (!saveChanges)
                        return;
                    let savingData = {
                        className: editor.clase,
                        id: editor.codigo,
                        data: [{ Campo: editor.propertyName, Valor: editor.value }],
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", savingData, model => {
                        if (model.Fail)
                            editor.value = editor.valorAnterior;
                    }, () => editor.value = editor.valorAnterior);
                }
                exportToExcel() {
                    if (this.viewMode == Components.DataViewMode.Reports) {
                        if (!this.reportsArea.currentReport) {
                            alert(Sol.Environment.resources.reportFromExcelError);
                            return;
                        }
                        ;
                        var chartData = {
                            credential: Sol.Environment.credential.export(),
                            filters: this.reportsArea.currentReport.getUsedFilters().toArray(),
                            suggestion: this.reportsArea.currentReport.mySuggestion
                        };
                        Web.System.exec("kaloei232k", "ExportFromReport", chartData, e => window.open(Sol.Environment.filePath + e.FileLink, "_blank"), null);
                    }
                    else if (this.viewMode == Components.DataViewMode.Grid) {
                        const gridData = {
                            className: this.className,
                            title: this.currentCustomReport ? this.currentCustomReport.Name : this.titulo,
                            filters: this.lastFilters,
                            sortProperty: this.sortProperty,
                            sortOrder: this.sortOrder,
                            properties: this.columns.select(cl => cl.PropertyName).toArray()
                        };
                        Web.System.execLarge("kaloei232k", "ExportFromList", gridData, e => window.open(Sol.Environment.filePath + e.FileLink, "_blank"), null);
                    }
                }
                hideDialogs() {
                    this.saveReportDialog.visible = false;
                    this.columnsDialog.visible = false;
                }
                clearSearchFilters() {
                    this.searchFields.forEachReverse(flt => flt.clear());
                }
                kanbanUpdated(totalPages, totalResults, resultCount) {
                    this.pageCount = totalPages;
                    this.refreshNavigation(totalResults, resultCount);
                    this.searchForm.workComplete();
                }
                loadCurrentCustomReport() {
                    this.setFilters(this.currentCustomReport.Filters);
                    var columns = Sol.List.from(this.currentCustomReport.Columns);
                    this.columns = this.availableColumns
                        .where(cl => columns.any(i => i.PropertyName == cl.PropertyName))
                        .select(cl => {
                        var sourceColumn = columns.that(i => i.PropertyName == cl.PropertyName);
                        var cloneColumn = Object.assign({}, cl);
                        cloneColumn.Position = sourceColumn.Position;
                        if (sourceColumn.Sorted) {
                            this.sortProperty = cl.OrderingPropertyName;
                            this.sortOrder = sourceColumn.SortOrder;
                        }
                        return cloneColumn;
                    });
                }
                makeDecision(e) {
                    var cell = e.parent;
                    if (e.model.Structure || e.model.IsCancel) {
                        let decisionScreen = new Web.Screens.DecisionScreen();
                        decisionScreen.parentScreen = this.myScreen;
                        decisionScreen.model = e.model;
                        decisionScreen.code = e.code;
                        decisionScreen.screenCaption = e.text;
                        decisionScreen.disableCloseCurrentScreen = true;
                        Web.System.screens.addScreen(decisionScreen);
                        Web.System.screens.showScreen(decisionScreen);
                    }
                    else {
                        cell.controls.forEach(ctr => ctr.visible = false);
                        cell.text = Sol.Environment.resources.saving;
                        const doMultipleModel = {
                            className: e.model.ClassType,
                            methodName: null,
                            decisionID: e.model.DecisionCode,
                            selectionMode: Web.ActionSelectionMode.None,
                            filters: null,
                            ids: [e.code],
                            inputs: null
                        };
                        Web.System.exec("79k8j542h", "DoMultiple", doMultipleModel, ev => {
                            cell.controls.forEach(ctr => ctr.visible = true);
                            cell.text = "";
                            this.refresh();
                            if (ev.Fail) {
                                this.error.caption = ev.ErrorMessage;
                                this.error.visible = true;
                                return;
                            }
                            this.onDecision.invoke();
                        });
                    }
                }
                print() {
                    var _a;
                    if (this.viewMode == Components.DataViewMode.Reports) {
                        (_a = this.reportsArea.currentReport) === null || _a === void 0 ? void 0 : _a.print();
                        return;
                    }
                    const gridData = {
                        className: this.className,
                        title: this.currentCustomReport ? this.currentCustomReport.Name : this.titulo,
                        filters: this.lastFilters,
                        sortProperty: this.sortProperty,
                        sortOrder: this.sortOrder,
                        properties: this.columns.select(cl => cl.PropertyName).toArray()
                    };
                    Web.System.execLarge("palq39mfs", "Print", gridData, e => window.open(e.FileLink, "_blank"), null);
                }
                requestFilterView(model) {
                    const data = {
                        className: this.className,
                        filters: this.getFilters().toArray(),
                        pivotPropertyName: model.PropertyName
                    };
                    this.filterViewButton.visible = true;
                    this.filterViewButton.text = model.ViewCaption;
                    this.filterView.onRequestFilter = e => this.onFilterRequested(e, model.PropertyName);
                    this.filterView.showLoader();
                    this.viewMode = Components.DataViewMode.FilterView;
                    Web.System.exec("i3n48smak", "GetView", data, e => this.filterView.loadItems(e));
                }
                onFilterRequested(item, propertyName) {
                    const filterEditor = this.searchFields.that(sf => sf.propertyName == propertyName);
                    if (filterEditor instanceof Sol.MultipleCombo)
                        filterEditor.value = [item.model.ObjectInterfaceData.Valor.toString()];
                    else
                        filterEditor.value = item.model.ObjectInterfaceData;
                    this.disableRefresh = true;
                    this.viewMode = Components.DataViewMode.Grid;
                    this.search();
                }
                openSaveDialog() {
                    this.hideDialogs();
                    this.saveReportDialog.clear();
                    this.saveReportDialog.visible = true;
                    if (this.currentCustomReport)
                        this.saveReportDialog.nameField.value = this.currentCustomReport.Name;
                    this.saveReportDialog.nameField.foco();
                }
                searchButtonChecked(saveOption) {
                    this.searchForm.visible = this.searchButton.checked;
                    this.searchArea.ancho = this.searchButton.checked ? 280 : 42;
                    this.customReportsArea.visible = this.searchButton.checked && this.customReportsList.hasItems();
                    if (this.searchButton.checked)
                        this.searchForm.focus();
                    this.searchArea.visible = this.searchButton.checked || !Sol.Environment.isMobile;
                    this.gridArea.visible = !this.searchButton.checked || !Sol.Environment.isMobile;
                    if (!saveOption || Sol.Environment.isMobile)
                        return;
                    this.savePreference("SearchBoxOpen", this.searchButton.checked);
                }
            }
            Components.DataView = DataView;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        class Editors {
            static createField(model, contextClass, code = null, structure = null) {
                var newEditor;
                if (this.editorFactory[model.DataType])
                    newEditor = this.editorFactory[model.DataType](model, contextClass, code, structure);
                else
                    newEditor = this.editorFactory["default"](model, contextClass, code, structure);
                if (!newEditor)
                    return null;
                newEditor.propertyName = model.PropertyName;
                newEditor.caption = model.Title;
                if (newEditor instanceof Web.Components.DetailsEditor)
                    newEditor.formState = !code ? Web.Screens.FormState.Insertion : Web.Screens.FormState.Edition;
                if (!code) {
                    newEditor.defaultValue = model.DefaultValue;
                    if (model.UserDefault && (newEditor instanceof Sol.Combo || model.EnableUserDefault))
                        newEditor.defaultValue = JSON.parse(model.UserDefault);
                }
                if (model.Settings)
                    for (const item in model.Settings)
                        newEditor[item] = model.Settings[item];
                if (!newEditor.readonly && !code)
                    newEditor.readonly = model.ReadOnly;
                if (!newEditor.readonly && code)
                    newEditor.readonly = model.ReadOnly || model.ReadOnlyAtEdition;
                newEditor.required = (!code && model.Required) || (code && model.RequiredAtEdition);
                return newEditor;
            }
            static createFilter(model, contextClass) {
                const newEditor = this.filterFactory[this.filterFactory[model.DataType] ? model.DataType : "default"](model, contextClass);
                newEditor.filterType = model.FilterClass;
                newEditor.propertyName = model.PropertyName;
                if (model.DefaultValue)
                    newEditor.value = model.DefaultValue;
                if (model.Settings)
                    for (const item in model.Settings)
                        newEditor[item] = model.Settings[item];
                return newEditor;
            }
            static fillForm(structure, form, toolbar, state, contextClass, code, disableMinimizedControls = false, totalizationBarPos = Web.Screens.TotalizationBarPosition.Bottom, groupMode = Web.Screens.FieldGroupMode.Frames) {
                var formEngine = new Web.Forms.CommonForm();
                if (groupMode == Web.Screens.FieldGroupMode.WrapGroups)
                    formEngine.wrapFieldGroups = true;
                if (groupMode == Web.Screens.FieldGroupMode.ProgessSteps)
                    formEngine = new Web.Forms.ProgressForm();
                if (groupMode == Web.Screens.FieldGroupMode.SideBar)
                    formEngine = new Web.Forms.SideBarForm();
                return formEngine.fillForm(structure, form, toolbar, state, contextClass, code, disableMinimizedControls, totalizationBarPos);
            }
            static registerEditor(key, action) {
                if (!action)
                    return;
                this.editorFactory[key] = action;
            }
            static registerFilter(key, action) {
                this.filterFactory[key] = action;
            }
            static createStatusDataCombo(model) {
                var comboFiltro = new Web.Components.DataCombo();
                comboFiltro.filterType = "StatusProceso";
                if (model.Options)
                    model.Options.forEach(o => {
                        var comboItemOpcion = new Sol.ComboItem();
                        comboItemOpcion.code = o.Code;
                        comboItemOpcion.text = o.Description;
                        comboItemOpcion.selected = o.Code == "1" && model.DefaultValue === true;
                        comboFiltro.add(comboItemOpcion);
                    });
                if (model.DefaultValue === true)
                    comboFiltro.defaultValue = { Valor: 1 };
                else
                    comboFiltro.defaultValue = { Valor: model.DefaultValue };
                return comboFiltro;
            }
            static fillDataViewStructure(dataView, structure) {
                dataView.availableColumns.addMany(Sol.List.from(structure).select(cp => ({
                    Alignment: cp.GridAlignment,
                    Title: cp.Title,
                    DataType: cp.DataType,
                    ShowTitle: true,
                    EditorModel: cp,
                    Visible: true,
                    Sortable: false,
                    ShowTotals: cp.ShowTotals,
                    PropertyName: cp.PropertyName,
                    VerticalAlignment: cp.VerticalAlignment
                })).toArray());
            }
        }
        Editors.editorFactory = {
            "SText": model => {
                if (model.Options && model.Options.length > 0) {
                    var combo = new Web.Components.DataCombo();
                    if (!model.Required)
                        combo.add(new Sol.ComboItem());
                    combo.loadOptions(model.Options);
                    return combo;
                }
                else if (model.MaxLength >= 256) {
                    const textField = new Sol.TextField();
                    textField.capitalizacion = model.Capitalization;
                    textField.maxLength = model.MaxLength;
                    return textField;
                }
                else {
                    const field = new Sol.Field();
                    field.capitalizacion = model.Capitalization;
                    field.maxLength = model.MaxLength;
                    field.minLength = model.MinLength;
                    field.placeHolder = model.Tip;
                    field.mask = model.Mask;
                    field.textBold = model.PropertyName.indexOf("Nombre") !== -1 || model.PropertyName == "Subject";
                    if (model.Width) {
                        field.autoWidth = false;
                        field.ancho = model.Width;
                    }
                    if (model.MaxLength <= 5)
                        field.alignment = Sol.Alignment.Center;
                    return field;
                }
            },
            "NotesField": () => new Sol.NotesField(),
            "SType": model => {
                if (model.Options && model.Options.length > 0) {
                    var combo = new Sol.Combo();
                    if (!model.Required)
                        combo.add(new Sol.ComboItem());
                    combo.loadOptions(model.Options);
                    return combo;
                }
                else {
                    const field = new Sol.Field();
                    field.maxLength = 255;
                    field.placeHolder = model.Tip;
                    return field;
                }
            },
            "SBoolean": model => {
                var check = new Sol.Check();
                check.caption = model.Title;
                check.largeDescription = model.LargeDescription;
                return check;
            },
            "SingleCombo": model => {
                var singleCombo = new Sol.Combo();
                singleCombo.loadOptions(model.Options);
                return singleCombo;
            },
            "ApprovedCheck": model => {
                var approvedCheck = new Web.Components.ApprovedCheck();
                approvedCheck.caption = model.Title;
                return approvedCheck;
            },
            "InterestingCheck": model => {
                var interestingCheck = new Web.Components.InterestingCheck();
                interestingCheck.caption = model.Title;
                return interestingCheck;
            },
            "birthdate": () => new Web.Components.BirthdateField(),
            "SDate": model => {
                const dateField = new Sol.DateField();
                if (model.Width)
                    dateField.ancho = model.Width;
                return dateField;
            },
            "SDateTime": () => new Sol.DateTimeField(),
            "SMoney": model => {
                const currencyField = new Sol.CurrencyField();
                currencyField.allowChangeCurrency = model.AllowChangeCurrency;
                currencyField.acceptsNegative = model.AcceptsNegative;
                currencyField.textBold = model.PropertyName.indexOf("Total") !== -1;
                currencyField.decimals = model.Decimals;
                if (model.Width)
                    currencyField.ancho = model.Width;
                return currencyField;
            },
            "MonthTotalizer": () => new Web.Components.MonthTotalizer(),
            "SEmail": () => new Sol.EmailField(),
            "SUrl": () => new Sol.UrlField(),
            "SNumber": model => {
                let numericField = new Sol.NumericField();
                numericField.decimals = model.Decimals || 0;
                numericField.tamanoMaximo = model.MaxLength || numericField.tamanoMaximo;
                numericField.acceptsNegative = model.AcceptsNegative;
                if (model.Width)
                    numericField.ancho = model.Width;
                return numericField;
            },
            "SColor": () => new Sol.ColorField(),
            "VehiclePlate": () => new Sol.VehiclePlateField(),
            "SPassword": () => new Sol.PasswordField(),
            "SLocalText": model => {
                var campoLocalizable = new Web.Components.LocalTextField();
                if (model.MaxLength > 0)
                    campoLocalizable.tamanoMaximo = model.MaxLength;
                return campoLocalizable;
            },
            "SOptionList": model => {
                var listEditor = new Sol.CheckList();
                listEditor.options = model.Options;
                return listEditor;
            },
            "SModules": model => {
                const modulesEditor = new Web.Components.ModulesEditor();
                modulesEditor.options = model.Options;
                return modulesEditor;
            },
            "SPermissionList": model => {
                var listEditor = new Sol.CheckList();
                listEditor.options = model.Options;
                return listEditor;
            },
            "STextList": model => {
                var listEditor = new Sol.CheckList();
                listEditor.options = model.Options;
                return listEditor;
            },
            "Teléfono": () => new Sol.PhonesEditor(),
            "ErrorCountDisplay": () => new Web.Components.Displays.ErrorCountDisplay(),
            "LicitationDatesCalculator": () => new Web.Licitations.LicitationDatesCalculator(),
            "coleccion": model => {
                var collectionSelector = new Web.Components.CollectionSelector();
                collectionSelector.clase = model.DataTypeFullName;
                collectionSelector.options = model.Options;
                collectionSelector.configuration = model.Configuration || {};
                collectionSelector.configuration.DynamicResults = true;
                collectionSelector.configuration.AllowAddNew = !model.ReadOnly;
                collectionSelector.configuration.AllowRemove = !model.ReadOnly;
                collectionSelector.displayProperty = model.IsRelation ? "EntidadRelacionada$Nombre" : "Nombre";
                collectionSelector.isRelation = model.IsRelation;
                return collectionSelector;
            },
            "selector": model => {
                var _a;
                const selector = model.IsRelation ?
                    new Web.Components.Selectors.RelationSelector() : new Web.Components.Selectors.Selector();
                selector.className = model.DataTypeFullName;
                selector.miInfo = model;
                selector.estructura = model.Structure;
                if ((_a = model.Settings) === null || _a === void 0 ? void 0 : _a.inferFromContext)
                    setTimeout(() => selector.inferValue(), 300);
                return selector;
            },
            "SInteger": model => {
                if (model.Options && model.Options.length > 0) {
                    var combo = new Web.Components.DataCombo();
                    combo.loadOptions(model.Options);
                    return combo;
                }
                else {
                    var intField = new Sol.IntegerField();
                    intField.maxLength = model.MaxLength || 9;
                    intField.alignment = Sol.Alignment.Left;
                    if (model.Width)
                        intField.ancho = model.Width;
                    return intField;
                }
            },
            "tabla": model => {
                if (!model.Structure)
                    return null;
                if (!model.StructureHasLargeFields) {
                    const table = new Web.Components.DataView();
                    table.className = model.DataTypeFullName;
                    table.showSearchBox = false;
                    table.fixedRows = false;
                    table.readonly = model.ReadOnly;
                    table.showVerticalLines = true;
                    table.showChecks = false;
                    table.showFieldChanges = model.ShowHistory;
                    if (model.Width)
                        table.ancho = model.Width;
                    Editors.fillDataViewStructure(table, model.Structure);
                    return table;
                }
                else {
                    var collectionEditor = new Web.Components.Collections.CollectionEditor();
                    collectionEditor.itemTitle = model.CollectionItemTitle;
                    collectionEditor.fields = model.Structure;
                    return collectionEditor;
                }
            },
            "CollectionEditor": model => {
                const collectionEditor = new Web.Components.Collections.CollectionEditor();
                collectionEditor.itemTitle = model.CollectionItemTitle;
                collectionEditor.fields = model.Structure;
                return collectionEditor;
            },
            "TableDialog": model => {
                const tableDlg = new Web.Components.TableDialogEditor();
                Editors.fillDataViewStructure(tableDlg.dataview, model.Structure);
                return tableDlg;
            },
            "InstallmentsEditor": model => {
                var installmentsEditor = new Web.Components.InstallmentsEditor();
                installmentsEditor.readonly = model.ReadOnly;
                Editors.fillDataViewStructure(installmentsEditor, model.Structure);
                return installmentsEditor;
            },
            "Archivo": () => {
                const singleUpload = new Web.Components.Uploads.InlineUpload();
                return singleUpload;
            },
            "upload": (model, contextClass, code) => {
                var uploads = new Web.Components.Uploads.Upload();
                uploads.code = code;
                uploads.showFileSize = true;
                uploads.className = model.DataTypeFullName;
                uploads.contextClassName = contextClass;
                if (!code && model.DefaultValue)
                    uploads.value = model.DefaultValue;
                return uploads;
            },
            "ImageGallery": model => {
                const gallery = new Web.Components.Uploads.ImageGallery();
                gallery.imagenWidth = model.Width;
                gallery.imagenHeight = model.Height;
                return gallery;
            },
            "AddressDisplay": () => new Sol.Web.Geo.AddressDisplay(),
            "seguimientos": (model, contextClass, code) => {
                if (model.PropertyName == "Messages") {
                    var followupsEditor = new Web.Components.FollowUpsEditor();
                    followupsEditor.code = code;
                    followupsEditor.className = model.DataTypeFullName;
                    followupsEditor.associativeProperty = model.AsociativePropertyName;
                    return followupsEditor;
                }
                else {
                    const followupsButton = new Web.Components.FollowupsButton();
                    followupsButton.text = model.Title;
                    followupsButton.code = code;
                    followupsButton.contextClassName = contextClass;
                    followupsButton.automaticSaving = !(!code);
                    followupsButton.className = model.DataTypeFullName;
                    followupsButton.associativeProperty = model.AsociativePropertyName;
                    followupsButton.enableUploads = true;
                    return followupsButton;
                }
            },
            "SaleFollowUps": (model, contextClass) => {
                var saleFollowups = new Web.Components.SaleFollowupsButon();
                saleFollowups.contextClassName = contextClass;
                return saleFollowups;
            },
            "status": (model, contextClass, code) => {
                const statusDisplay = new Web.Components.StatusDisplay();
                statusDisplay.negocioID = code;
                statusDisplay.useWrapper = model.FormPosition == Web.FormPosition.form;
                return statusDisplay;
            },
            "LicitationChat": (model, contextClass, code) => {
                const licitationChat = new Web.Licitations.LicitationChatEditor();
                licitationChat.code = code;
                return licitationChat;
            },
            "LicitationItemSelector": model => {
                const licitationItemSelector = new Web.Licitations.LicitationItemSelector();
                licitationItemSelector.className = model.DataTypeFullName;
                return licitationItemSelector;
            },
            "LicitationBatchSelector": (model, contextClass, code) => {
                const licitationBatchSelector = new Web.Licitations.LicitationBatchSelector();
                licitationBatchSelector.className = model.DataTypeFullName;
                return licitationBatchSelector;
            },
            "WinnersList": (model, contextClass, code) => {
                const winnersEditor = new Web.Licitations.WinnersListEditor();
                winnersEditor.code = code;
                return winnersEditor;
            },
            "ForecasttoPNCPLog": (model, contextClass, code) => {
                const forecastLogEditor = new Web.Components.PNCP.BudgetForecastPNCPLogEditor();
                forecastLogEditor.code = code;
                return forecastLogEditor;
            },
            "VehicleContractsList": (model, contextClass, code) => {
                const vehicleConEditor = new Web.Contracts.VehicleContractListEditor();
                vehicleConEditor.code = code;
                return vehicleConEditor;
            },
            "PropertyContractsList": (model, contextClass, code) => {
                const propertyConEditor = new Web.Contracts.PropertyContractListEditor();
                propertyConEditor.code = code;
                return propertyConEditor;
            },
            "Imagen": model => {
                const imageField = new Web.Components.Uploads.ImageField();
                if (model.Height)
                    imageField.imageHeight = model.Height;
                if (model.Width)
                    imageField.imageWidth = model.Width;
                return imageField;
            },
            "CursoFecha": model => {
                var courseSelector = new Web.Components.Selectors.CourseSelector();
                courseSelector.estructura = model.Structure;
                return courseSelector;
            },
            "SIdentity": () => {
                var campoID = new Sol.IntegerField();
                campoID.alignment = Sol.Alignment.Center;
                campoID.readonly = true;
                campoID.textBold = true;
                return campoID;
            },
            "SYesNo": model => {
                var enumCombo = new Sol.Combo();
                enumCombo.valueMember = "Code";
                enumCombo.displayMember = "Description";
                enumCombo.setDataSource(model.Options);
                return enumCombo;
            },
            "SEnumeration`1": model => {
                var enumCombo = new Sol.Combo();
                enumCombo.valueMember = "Code";
                if (model.Width)
                    enumCombo.ancho = model.Width;
                enumCombo.displayMember = "Description";
                enumCombo.setDataSource(model.Options);
                return enumCombo;
            },
            "SJson": () => new Web.Components.Questions.MultipleChoiceQuestionEditor(),
            "SRating": () => new Sol.RatingField(),
            "SLargeText": () => new Sol.TextField(),
            "CompanyUnit": model => {
                const customerSelector = new Web.Components.Selectors.UnitSelector();
                customerSelector.configuration = model.Configuration;
                customerSelector.estructura = model.Structure;
                customerSelector.className = model.DataTypeFullName;
                customerSelector.etiqueta = model.Title;
                customerSelector.miInfo = model;
                return customerSelector;
            },
            "Employee": model => {
                const employeeSelector = new Web.Components.Selectors.EmployeeSelector();
                employeeSelector.configuration = model.Configuration;
                employeeSelector.estructura = model.Structure;
                employeeSelector.className = model.DataTypeFullName;
                employeeSelector.etiqueta = model.Title;
                employeeSelector.miInfo = model;
                return employeeSelector;
            },
            "Evaluation": model => {
                var evaluation = new Web.Components.Quality.QualityEvaluation();
                evaluation.structure = model.Structure;
                return evaluation;
            },
            "detailed": model => {
                var detailsEditor = new Web.Components.DetailsEditor();
                detailsEditor.model = model.ScreenModel;
                return detailsEditor;
            },
            "DeliveryEditor": model => {
                var deliveryEditor = new Web.Components.DeliveryEditor();
                deliveryEditor.model = model.ScreenModel;
                return deliveryEditor;
            },
            "PaymentEditor": model => {
                const paymentEditor = new Web.Components.PaymentEditor();
                paymentEditor.model = model.ScreenModel;
                paymentEditor.configuration = model.Configuration;
                return paymentEditor;
            },
            "PurchasePaymentEditor": model => {
                const purchasePaymentEditor = new Web.Components.PurchasePaymentEditor();
                purchasePaymentEditor.model = model.ScreenModel;
                return purchasePaymentEditor;
            },
            "PaymentTypeChoice": model => {
                var paymentChoice = new Web.Components.PaymentTypeChoice();
                paymentChoice.options = model.Options;
                return paymentChoice;
            },
            "InstallmentsButton": () => new Web.Components.CalcInstallmentsButton(),
            "TabEditor": (model, _, code) => {
                const tabEditor = new Web.Components.TabEditor(model.Configuration);
                tabEditor.text = model.Title;
                tabEditor.code = code;
                return tabEditor;
            },
            "MultipleChoice": model => {
                var multipleChoice = new Sol.MultipleChoice();
                multipleChoice.options = model.Options;
                multipleChoice.configuration = model.Configuration;
                return multipleChoice;
            },
            "Login": () => new Web.Components.Selectors.LoginSelector(),
            "DateRangeField": model => {
                var dateRangeField = new Sol.DateRangeField();
                dateRangeField.configuration = model.Configuration;
                return dateRangeField;
            },
            "SPercent": model => {
                const percentField = new Sol.PercentField();
                percentField.acceptsNegative = model.AcceptsNegative;
                if (model.Width)
                    percentField.ancho = model.Width;
                if (model.Decimals) {
                    percentField.decimals = model.Decimals;
                    percentField.tamanoMaximo = model.Decimals + 4;
                }
                return percentField;
            },
            "STime": model => {
                const timeField = new Sol.TimeField();
                if (model.Width)
                    timeField.ancho = model.Width;
                return timeField;
            },
            "SWeekDays": () => new Sol.WeekDaysField(),
            "STimeStamp": () => new Sol.TimeStampField(),
            "InlineUpload": () => new Web.Components.Uploads.InlineUpload(),
            "CategorySelector": model => {
                var categorySelector = new Web.Components.Selectors.CategorySelector();
                categorySelector.className = model.DataTypeFullName;
                return categorySelector;
            },
            "SpecificationsEditor": model => new Web.Components.SpecificationsEditor(),
            "DebitCreditEditor": () => new Web.Components.DebitCreditEditor(),
            "DynamicDetailsEditor": () => {
                var dynamicForm = new Web.Components.DynamicDetailsEditor();
                return dynamicForm;
            },
            "ServicesEditor": () => new Web.Components.ServicesEditor(),
            "ServiceTypeEditor": model => {
                var serviceTypeEditor = new Web.Components.ServiceOrders.ServiceTypeEditor();
                serviceTypeEditor.className = model.DataTypeFullName;
                return serviceTypeEditor;
            },
            "Vehicle": (model, cls) => {
                var vehicleSelector = new Web.Components.Selectors.VehicleSelector();
                vehicleSelector.configuration = model.Configuration;
                vehicleSelector.estructura = model.Structure;
                vehicleSelector.className = model.DataTypeFullName;
                vehicleSelector.etiqueta = model.Title;
                vehicleSelector.miInfo = model;
                return vehicleSelector;
            },
            "País": () => new Sol.Web.Geo.CountrySelector(),
            "RealStateProperty": (model, cls) => {
                var vehicleSelector = new Web.Components.Selectors.PropertySelector();
                vehicleSelector.configuration = model.Configuration;
                vehicleSelector.estructura = model.Structure;
                vehicleSelector.className = model.DataTypeFullName;
                vehicleSelector.etiqueta = model.Title;
                vehicleSelector.miInfo = model;
                vehicleSelector.miInfo = model;
                vehicleSelector.contextClass = cls;
                return vehicleSelector;
            },
            "RelatedProductsEditor": model => {
                var relatedProductsEditor = new Web.Components.RelatedProductsEditor();
                relatedProductsEditor.configurarion = model.Configuration;
                return relatedProductsEditor;
            },
            "ProductComponentsEditor": () => {
                var productComponentsEditor = new Web.Components.ProductComponentsEditor();
                return productComponentsEditor;
            },
            "RelatedCustomerEditor": () => new Web.Components.RelatedCustomerEditor(),
            "SHtml": () => new Web.Components.HtmlEditor(),
            "Display": model => {
                const display = new Sol.ObjectDisplay();
                display.width = model.Width;
                return display;
            },
            "TextDisplay": () => new Sol.TextDisplay(),
            "FileHistory": (m, c, code) => {
                var fileHistory = new Web.Components.FileHistory();
                fileHistory.code = code;
                return fileHistory;
            },
            "SaleParticipation": model => {
                var saleParticipation = new Web.Components.SaleParticipationEditor();
                saleParticipation.readonly = model.ReadOnly;
                Editors.fillDataViewStructure(saleParticipation, model.Structure);
                return saleParticipation;
            },
            "CommissionedPartner": model => {
                var comissionedPartner = new Web.Components.CommissionedPartnerEditor();
                comissionedPartner.readonly = model.ReadOnly;
                Editors.fillDataViewStructure(comissionedPartner, model.Structure);
                return comissionedPartner;
            },
            "SGauge": () => new Sol.Gauge(),
            "FileSigner": (model, contextClass, code) => {
                let fileSigner = new Web.Components.Uploads.FileSigner();
                fileSigner.className = model.DataTypeFullName;
                fileSigner.code = code;
                fileSigner.contextClassName = contextClass;
                if (!code && model.DefaultValue)
                    fileSigner.value = model.DefaultValue;
                return fileSigner;
            },
            "TaxRulesEditor": () => {
                var taxRulesEditor = new Web.Components.TaxRulesEditor();
                return taxRulesEditor;
            },
            "CreatorField": (model, className, code) => {
                const creatorField = new Web.Components.CreatorField();
                creatorField.className = className;
                creatorField.code = code;
                return creatorField;
            },
            "DeliveryChoice": model => {
                var deliveryChoiceEditor = new Web.Components.DeliveryChoice();
                deliveryChoiceEditor.options = model.Options;
                return deliveryChoiceEditor;
            },
            "GoalScopeSelector": (model, c, code) => {
                var goalScopeSelector = new Web.Components.Selectors.GoalEngineSelector();
                goalScopeSelector.configuration = model.Configuration;
                if (code == 0)
                    setTimeout(() => goalScopeSelector.change(), 300);
                return goalScopeSelector;
            },
            "CompanySelector": () => new Web.Components.Selectors.CompanySelector(),
            "StudentHistory": (m, c, code) => {
                var studentHistoryEditor = new Web.Components.Education.StudentHistory();
                studentHistoryEditor.studentCode = code;
                return studentHistoryEditor;
            },
            "SystemSelector": model => {
                const systemSelector = new Web.Components.Selectors.SystemSelector();
                systemSelector.loadOptions(model.Options);
                return systemSelector;
            },
            "NFeEditor": (model, c, code) => {
                var nfeEditor = new Web.Components.NFe.NFeEditor();
                nfeEditor.code = code;
                nfeEditor.configuration = model.Configuration;
                return nfeEditor;
            },
            "ProfileModuleCombo": model => {
                const pmCombo = new Web.Components.ProfileModuleCombo();
                pmCombo.loadOptions(model.Options);
                return pmCombo;
            },
            "AccountSelector": () => new Web.Components.Selectors.AccountSelector(),
            "InterestsField": () => new Web.Components.InterestsField(),
            "BankInfoDisplay": () => new Sol.Web.Components.BankInfoDisplay(),
            "FinancialScreenLink": () => new Web.Components.FinancialScreenLink(),
            "BankAccountCombo": model => {
                const editor = new Web.Components.BankAccountCombo();
                editor.className = model.DataTypeFullName;
                return editor;
            },
            "MessageSenderEditor": () => new Web.Components.MessageSenderEditor(),
            "DualCombo": model => {
                const dualCombo = new Web.Components.DualCombo();
                dualCombo.subClassName = model.DataTypeFullName;
                return dualCombo;
            },
            "CategoryDualCombo": model => {
                const dualCombo = new Web.Components.CategoryDualCombo();
                dualCombo.subClassName = model.DataTypeFullName;
                return dualCombo;
            },
            "SicafDisplay": () => new Web.Government.SicafDisplay(),
            "IntegrationsEditor": (model, className, code) => {
                const integEditor = new Web.Components.IntegrationsEditor();
                integEditor.className = className;
                integEditor.code = code;
                return integEditor;
            },
            "SMonthYear": () => {
                const monthYear = new Sol.MonthYearField();
                monthYear.setCurrentMonth();
                return monthYear;
            },
            "SCurrencyType": () => {
                let combo = new Sol.Combo();
                combo.loadOptions(Sol.List.from(Sol.Environment.currencies).select(c => ({ Code: c.ISO, Description: c.Name })).toArray());
                return combo;
            },
            "LicitationDecimalsField": model => {
                const field = new Web.Licitations.DecimalsField();
                if (model.Width)
                    field.ancho = model.Width;
                return field;
            },
            "default": model => {
                var selector;
                if (model.SelectorType == Sol.SelectorType.Complex)
                    selector = new Web.Components.Selectors.Selector();
                else if (model.Options)
                    selector = new Sol.Combo();
                else
                    selector = new Web.Components.DataCombo();
                if (selector instanceof Web.Components.Selectors.Selector) {
                    selector.allowCreateNew = !!model.Structure;
                    selector.allowEdit = !!model.Structure;
                    selector.estructura = model.Structure;
                    selector.etiqueta = model.Title;
                    selector.miInfo = model;
                    selector.className = model.DataTypeFullName;
                    selector.displayProperty = model.IsRelation ? "EntidadRelacionada$Nombre" : "Nombre";
                    selector.filterProperty = selector.displayProperty;
                    selector.resultsOrder = selector.displayProperty;
                    selector.isRelation = model.IsRelation;
                    selector.configuration = model.Configuration;
                }
                if (selector instanceof Web.Components.DataCombo) {
                    selector.displayProperty = model.IsRelation ? "EntidadRelacionada$Nombre" : "Nombre";
                    selector.className = model.DataTypeFullName;
                    selector.isRelation = model.IsRelation;
                    setTimeout(() => selector.refresh(), 300);
                }
                if (selector instanceof Sol.Combo) {
                    selector.loadOptions(model.Options);
                }
                if (model.Width)
                    selector.ancho = model.Width;
                return selector;
            }
        };
        Editors.filterFactory = {
            "SText": model => {
                if (model.Options && model.Options.length > 0) {
                    const combo = new Web.Components.DataCombo();
                    combo.loadOptions(model.Options);
                    return combo;
                }
                return new Sol.Field();
            },
            "combo": model => Editors.createStatusDataCombo(model),
            "SingleCombo": model => {
                const singleCombo = new Sol.Combo();
                singleCombo.loadOptions(model.Options);
                return singleCombo;
            },
            "SystemSelector": model => {
                const systemSelector = new Web.Components.Selectors.SystemSelector();
                systemSelector.loadOptions(model.Options);
                setTimeout(() => systemSelector.notifySet(), 300);
                return systemSelector;
            },
            "SYear": model => {
                var _a;
                const yearCombo = new Sol.Combo();
                if (!((_a = model.Settings) === null || _a === void 0 ? void 0 : _a.requiredFilter))
                    yearCombo.addBlankItem();
                yearCombo.loadOptions(Sol.List.from(model.Options).reverse().toArray());
                return yearCombo;
            },
            "selector": model => {
                var selector = model.IsRelation ?
                    new Web.Components.Selectors.RelationSelector() : new Web.Components.Selectors.Selector();
                selector.className = model.ClassName;
                return selector;
            },
            "SDateTime": () => new Sol.IntervalCombo(),
            "SDate": () => new Sol.IntervalCombo(),
            "SInteger": model => {
                if (model.Options && model.Options.length > 0) {
                    const combo = new Sol.Combo();
                    combo.loadOptions(model.Options);
                    return combo;
                }
                else {
                    const intField = new Sol.IntegerField();
                    intField.alignment = Sol.Alignment.Left;
                    return intField;
                }
            },
            "CursoFecha": () => new Web.Components.Selectors.CourseSelector(),
            "SIdentity": () => {
                var campoID = new Sol.IntegerField();
                campoID.alignment = Sol.Alignment.Center;
                return campoID;
            },
            "SEnumeration": model => {
                var enumCombo = new Sol.Combo();
                enumCombo.valueMember = "Code";
                enumCombo.displayMember = "Description";
                enumCombo.setDataSource(model.Options);
                return enumCombo;
            },
            "CompanyUnit": model => {
                const unitSelector = new Web.Components.Selectors.UnitSelector();
                unitSelector.className = model.ClassName;
                unitSelector.configuration = model.Configuration;
                return unitSelector;
            },
            "ComboFilter": model => {
                var comboFilter = new Sol.ComboFilter();
                comboFilter.valueMember = "Code";
                comboFilter.displayMember = "Description";
                comboFilter.setDataSource(model.Options);
                return comboFilter;
            },
            "multiple_combo": model => {
                const multipleCombo = new Sol.MultipleCombo();
                multipleCombo.setOptions(model.Options);
                return multipleCombo;
            },
            "StatusFilter": model => {
                const statusFilter = new Web.Components.StatusFilter();
                statusFilter.setOptions(model.Options);
                return statusFilter;
            },
            "DataCombo": (model, contextClass) => {
                var _a;
                const dataCombo = new Web.Components.DataCombo();
                dataCombo.caption = model.Caption;
                dataCombo.isRelation = model.IsRelation;
                dataCombo.className = ((_a = model.Configuration) === null || _a === void 0 ? void 0 : _a.className) || model.ClassName;
                dataCombo.displayProperty = model.IsRelation ? "EntidadRelacionada$Nombre" : "Nombre";
                dataCombo.contextClass = contextClass;
                dataCombo.propertyName = model.PropertyName;
                dataCombo.showAllOption = true;
                dataCombo.showEmptyFilterOption = !model.IsRequired;
                setTimeout(() => dataCombo.refresh(), 300);
                return dataCombo;
            },
            "RequiredDataCombo": model => {
                var specialCombo = new Web.Components.DataCombo();
                specialCombo.isRelation = model.IsRelation;
                specialCombo.className = model.ClassName;
                specialCombo.displayProperty = model.IsRelation ? "EntidadRelacionada$Nombre" : "Nombre";
                specialCombo.required = true;
                specialCombo.refresh();
                return specialCombo;
            },
            "Login": () => new Web.Components.Selectors.LoginSelector(),
            "BirthdateCombo": () => new Web.Components.BirthdateCombo(),
            "default": () => new Sol.Field(),
            "SGauge": model => {
                const combo = new Web.Components.DataCombo();
                combo.loadOptions(model.Options);
                return combo;
            },
            "SMonth": model => {
                const monthCombo = new Sol.Combo();
                monthCombo.loadOptions(model.Options);
                return monthCombo;
            },
            "Entidad": model => {
                const entitySelector = new Web.Components.Selectors.EntitySelector();
                entitySelector.className = model.ClassName;
                entitySelector.etiqueta = model.Caption;
                return entitySelector;
            },
            "SMoney": () => new Sol.CurrencyFilter()
        };
        Web.Editors = Editors;
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ActionScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.form = new Sol.Form();
                    this.fields = new Sol.List();
                }
                get myModel() { return this.model; }
                get values() {
                    return this.fields
                        .select(cp => ({ Campo: cp.propertyName, Valor: cp.value }))
                        .toArray();
                }
                focus() { setTimeout(() => this.fields.first().foco(), 300); }
                showError(message) { this.form.showError(message); }
                build() {
                    super.build();
                    var model = this.model;
                    this.screenCaption = model.Name;
                    this.css.add("sol_file_tool");
                    const screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = model.Name;
                    this.add(screenTitle);
                    this.form.cancelButton.text = Sol.Environment.resources.cerrar;
                    this.form.onCancel = () => Web.System.screens.closeCurrentScreen();
                    this.add(this.form);
                    this.fields = Web.Editors.fillForm(model.Fields, this.form, null, Screens.FormState.Insertion, null, this.myModel.EditingCode).fields;
                }
            }
            Screens.ActionScreen = ActionScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let FieldGroupMode;
            (function (FieldGroupMode) {
                FieldGroupMode[FieldGroupMode["Frames"] = 0] = "Frames";
                FieldGroupMode[FieldGroupMode["ProgessSteps"] = 1] = "ProgessSteps";
                FieldGroupMode[FieldGroupMode["SideBar"] = 2] = "SideBar";
                FieldGroupMode[FieldGroupMode["WrapGroups"] = 3] = "WrapGroups";
            })(FieldGroupMode = Screens.FieldGroupMode || (Screens.FieldGroupMode = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class FollowupsButton extends Sol.Button {
                constructor() {
                    super();
                    this.code = 0;
                    this.isComplex = false;
                    this.automaticSaving = false;
                    this.showSchedule = true;
                    this.showUnread = true;
                    this.text = Sol.Environment.resources.seguimientos;
                    this.onClick = () => this.meClick();
                    this.imageCode = '&#xf0e6;';
                }
                isEmpty() { return true; }
                validate() { return null; }
                get value() { return this._value; }
                set value(value) { this.setValue(value); }
                build() {
                    this.showCounter = this.showUnread;
                    super.build();
                }
                setValue(value) { this._value = value; }
                toControl() { return this; }
                foco() { }
                clear() { }
                render() {
                    this.countUnreadMessages();
                    super.render();
                }
                meClick() {
                    var screen = new Web.Screens.FollowupScreen();
                    screen.screenCaption = this.text;
                    screen.code = this.code;
                    screen.myButton = this;
                    screen.messagesEditor.contextClassName = this.contextClassName;
                    screen.messagesEditor.showContacts = this.showContacts;
                    screen.messagesEditor.showDeals = this.showDeals;
                    screen.messagesEditor.className = this.className;
                    screen.messagesEditor.associativeProperty = this.associativeProperty;
                    screen.messagesEditor.automaticSaving = this.automaticSaving;
                    screen.messagesEditor.saveButton.enabled = !this.automaticSaving || this.code > 0;
                    screen.messagesEditor.newItemsBag = this.newItemsBag;
                    screen.messagesEditor.enableUploads = this.enableUploads;
                    screen.messagesEditor.searchContactService = this.searchContactService || screen.messagesEditor.searchContactService;
                    screen.messagesEditor.methodName = this.methodName || screen.messagesEditor.methodName;
                    screen.showSchedule = this.showSchedule;
                    Web.System.screens.addScreen(screen);
                    Web.System.screens.showScreen(screen);
                    screen.messagesEditor.refresh();
                    screen.messagesEditor.focus();
                    screen.messagesEditor.loadContacts();
                    if (this.code)
                        this.markAllAsRead();
                    screen.onFormSaved.subscribe(() => {
                        screen.messagesEditor.addMessageIfNotEmpty();
                        this.value = screen.messagesEditor.value;
                        if (!this.automaticSaving)
                            this.newItemsBag = screen.messagesEditor.getNewItems();
                    });
                    return false;
                }
                countUnreadMessages() {
                    if (!this.showUnread || this.code == 0)
                        return;
                    var data = {
                        className: this.className,
                        property: this.associativeProperty,
                        code: this.code
                    };
                    Web.System.exec("nlkk990dsa", "Unread", data, e => {
                        var resultado = e;
                        this.setCounterValue(resultado);
                    });
                }
                markAllAsRead() {
                    if (!this.code || !this.counterValue)
                        return;
                    var data = {
                        className: this.className,
                        property: this.associativeProperty,
                        code: this.code
                    };
                    Web.System.exec("nlkk990dsa", "Read", data, null, null);
                }
            }
            Components.FollowupsButton = FollowupsButton;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Kanban;
            (function (Kanban) {
                class Card extends Sol.Control {
                    constructor(columnModel, model, view, decisions) {
                        super();
                        this.css.add("sol_kanban_card");
                        const wrapper = new Sol.Control();
                        wrapper.css.add("sol_kanban_card_desc");
                        if (view)
                            wrapper.onClick = () => view.onEdit(model.ID, null);
                        const codeText = new Sol.Control("span");
                        codeText.css.add("sol_kanban_card_code");
                        if (columnModel)
                            codeText.estilos.agregar("color", columnModel.Color);
                        codeText.text = model.Identifier;
                        if (model.BreakAfterCode)
                            codeText.add(new Sol.LineBreak());
                        wrapper.add(codeText);
                        const descText = new Sol.Text();
                        descText.text = model.Description;
                        wrapper.add(descText);
                        this.add(wrapper);
                        this.addMany(Sol.List.from(model.ExtraData).select(extra => {
                            const extraDataWrapper = new Sol.Control();
                            extraDataWrapper.css.add("sol_kanban_extra");
                            extraDataWrapper.addCtr(extra.Campo + ": ", null, "span");
                            extraDataWrapper.addCtr(extra.Valor, null, "span");
                            return extraDataWrapper;
                        }));
                        if (model.Total) {
                            const totalText = new Sol.Control();
                            totalText.css.add("sol_kanban_card_tot");
                            totalText.text = model.TotalCaption + ": " + model.Total;
                            if (model.FollowupRelationID)
                                totalText.estilos.agregar("float", "right");
                            this.add(totalText);
                        }
                        if (model.FollowupRelationID) {
                            const followups = new Components.FollowupsButton();
                            followups.css.add("sol_kanban_followup");
                            followups.type = Sol.ButtonType.Custom;
                            followups.tip = followups.text;
                            followups.text = "";
                            followups.code = model.FollowupRelationID;
                            followups.className = "Solarium.SeguimientoRelación, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                            followups.associativeProperty = "Relación";
                            followups.automaticSaving = true;
                            followups.showUnread = false;
                            followups.contextClassName = "Solarium.Commercial.Cliente, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                            this.add(followups);
                        }
                        if (decisions.hasItems()) {
                            const decisionArea = this.addCtr(null, "sol_tabla_decision");
                            decisionArea.controls.addMany(decisions.select(decision => {
                                const decisionButton = new Components.DecisionButton(model.ID, decision);
                                decisionButton.text = null;
                                decisionButton.onClick = () => view.onDecision(decisionButton);
                                return decisionButton;
                            }));
                        }
                    }
                }
                Kanban.Card = Card;
            })(Kanban = Components.Kanban || (Components.Kanban = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class Registro extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.createButton = new Sol.Button();
                    this.messagesArea = new Sol.Control();
                    this.successMessage = new Sol.ScreenMessage();
                    this.noItemsSelectedMessage = new Sol.ScreenMessage();
                    this.confirmacionAccion = new Sol.ScreenMessage();
                    this.mensajeErrorAccion = new Sol.ScreenMessage();
                    this.actionSucessMessage = new Sol.ScreenMessage();
                    this.toolBar = new Sol.Control();
                    this.dataview = new Web.Components.DataView();
                    this.forceSubtype = false;
                    this.onFileChanged = new Sol.EventHandler();
                }
                get anchorageCode() { var _a; return ((_a = this.anchorage) === null || _a === void 0 ? void 0 : _a.FilterValue) || 0; }
                get classType() { return this._model.ClassType; }
                get filters() { return this.dataview.lastFilters; }
                addNew() {
                    this.hideAllMessages();
                    this.details = this.createDetailsScreen(this.createButton.text + ' ' + this._model.ItemName);
                    if (!this.embbededMode)
                        Web.System.screens.showScreen(this.details);
                    this.details.foco();
                }
                onOpenScreen() {
                    this.dataview.search();
                }
                refreshSearch() {
                    this.dataview.clearSelection();
                    this.onFileChanged.invoke();
                    this.dataview.refresh();
                }
                setFormField(propertyName, value) {
                    const editor = this.details.getEditor(propertyName);
                    editor.value = value;
                    if (editor.isComplex)
                        this.details.getLabel(propertyName).expanded = true;
                }
                setFilter(propertyName, value) {
                    this.dataview.setFilter(propertyName, value);
                }
                setFilters(filters) { this.dataview.setFilters(filters); }
                setModel(value) {
                    this.model = value;
                    this._model = value;
                }
                setViewMode(mode) { this.dataview.viewMode = mode; }
                build() {
                    this.setModel(this.model);
                    this.css.add("sol_registro");
                    this.createTitle();
                    this.initializeMessages(this._model.GeneralMessages);
                    this.initializeToolbar();
                    this.initializeSummary();
                    this.createSuccessMessage();
                    this.initializeDataView();
                    this.initializeTableMultipleActions();
                    super.build();
                }
                createDetailsScreen(screenCaption, code = 0) {
                    const details = this.instantiateDetailsScreen();
                    details.formState = !code ? Screens.FormState.Insertion : Screens.FormState.Edition;
                    details.screenCaption = screenCaption;
                    details.showLeftPanel = true;
                    details.anchorage = this.anchorage;
                    details.hideBackToTopButton = !!this.anchorage;
                    details.loadSubtype = this.forceSubtype;
                    details.model = this._model.DetailsModel;
                    details.code = code;
                    details.autoReload = this._model.EnableAutoReload;
                    details.classHash = this._model.ClassHash;
                    details.myScreen = this;
                    details.myForm.onCancel = () => this.cancelDetailsScreen();
                    details.onSaved.subscribe((d, m, data) => this.detailsSaved(data));
                    details.entityName = this._model.Name;
                    details.enableTotalCalculation = !this._model.DisableTotalCalculation;
                    details.showSaveAndNew = this._model.EnableSaveAndNew && !this._model.Readonly && this._model.AllowAddNew;
                    details.showSaveButton = this._model.ShowSaveButton;
                    details.allowCreateWithSameData = this._model.EnableCreateWithSameData && this._model.AllowAddNew;
                    details.saveAndCloseCaption = this._model.SaveAndCloseButtonCaption;
                    details.totalizationBarPosition = this._model.TotalizationBarPosition;
                    details.showNavigationButtons = !!code && !!this.curEditIndex && this.dataview.resultCount > 1;
                    details.onNavigate.subscribe(d => this.navigate(d));
                    if (!code)
                        details.defaultDecisions = Sol.List.from(this._model.Decisions).where(d => d.IsDefault).toArray();
                    if (this.embbededMode) {
                        this.visible = false;
                        this.parent.add(details);
                    }
                    else
                        Web.System.screens.addScreen(details);
                    return details;
                }
                editItem(code, rowIndex) {
                    this.hideAllMessages();
                    this.curEditIndex = rowIndex;
                    this.details = this.createDetailsScreen(Sol.Environment.resources.editar, code);
                    if (!this.embbededMode)
                        Web.System.screens.showScreen(this.details);
                    this.details.foco();
                    this.details.load(code);
                }
                hideAllMessages() {
                    this.successMessage.visible = false;
                    this.noItemsSelectedMessage.visible = false;
                    this.mensajeErrorAccion.visible = false;
                    this.actionSucessMessage.visible = false;
                    this.confirmacionAccion.visible = false;
                }
                instantiateDetailsScreen() { return new Screens.DetailsScreen(); }
                onMultipleActionDone() { }
                createTitle() {
                    this.screenCaption = this._model.Title;
                    const title = new Screens.ScreenTitle();
                    title.text = this._model.Title;
                    this.add(title);
                }
                createSuccessMessage() {
                    if (this._model.Readonly)
                        return;
                    this.add(this.messagesArea);
                    this.successMessage.type = Sol.MessageType.Success;
                    this.successMessage.visible = false;
                    this.messagesArea.add(this.successMessage);
                }
                initializeMessages(messages) {
                    if (messages.length == 0)
                        return;
                    const list = new Screens.ScreenMessageList;
                    list.load(messages);
                    this.add(list);
                }
                initializeToolbar() {
                    this.toolBar.css.add("sol_registro_toolbar");
                    this.add(this.toolBar);
                    this.initializeCreateButton();
                    this.initializeLinksMenu();
                    this.initializeToolsButtons();
                    this.initializeOptionsButton();
                }
                initializeCreateButton() {
                    if (this._model.Readonly || !this._model.AllowAddNew)
                        return;
                    this.createButton.text = this._model.NewButtonCaption;
                    this.createButton.imageCode = "&#xf067;";
                    this.createButton.onClick = () => this.addNew();
                    this.toolBar.add(this.createButton);
                }
                initializeLinksMenu() {
                    var linksButton = new Sol.Button();
                    linksButton.text = Sol.Environment.resources.links;
                    linksButton.imageCode = "&#xf15c;";
                    linksButton.onSubitemClick = e => this.linksButtonSubitemClick(e);
                    this._model.FileMenus.forEach(mn => {
                        var item = new Sol.Control("li");
                        item.text = mn.Nombre + "...";
                        item.data = mn;
                        linksButton.subitems.add(item);
                    });
                    if (linksButton.subitems.hasItems())
                        this.toolBar.add(linksButton);
                }
                linksButtonSubitemClick(e) {
                    var info = e.data;
                    Web.System.screens.openScreen(info.Pantalla, info.Clase);
                }
                initializeOptionsButton() {
                    if (!this._model.FileOptionsModel)
                        return;
                    var optionsButton = new Sol.Button();
                    optionsButton.text = Sol.Environment.resources.configuraciones;
                    optionsButton.imageCode = "&#xf013;";
                    optionsButton.onClick = () => this.optionsButtonClick();
                    this.toolBar.add(optionsButton);
                }
                navigate(direction) {
                    if (direction == Screens.DetailsNavigationDirection.Backward && this.dataview.page == 1 && this.curEditIndex == 1)
                        this.dataview.showPage(this.dataview.pageCount, () => this.loadItemByRowIndex(this.dataview.pageResultCount));
                    else if (direction == Screens.DetailsNavigationDirection.Forward && this.dataview.page == this.dataview.pageCount && this.curEditIndex == this.dataview.pageResultCount)
                        this.dataview.showPage(1, () => this.loadItemByRowIndex(1));
                    else if (direction == Screens.DetailsNavigationDirection.Forward && this.curEditIndex == this.dataview.rowCount)
                        this.dataview.showNextPage(() => this.loadItemByRowIndex(1));
                    else if (direction == Screens.DetailsNavigationDirection.Backward && this.curEditIndex == 1)
                        this.dataview.showPreviousPage(() => this.loadItemByRowIndex(this.dataview.rowCount));
                    else
                        this.loadItemByRowIndex(this.curEditIndex + (direction == Screens.DetailsNavigationDirection.Forward ? 1 : -1));
                }
                loadItemByRowIndex(rowIndex) {
                    this.curEditIndex = rowIndex;
                    let code = this.dataview.getCodeByRowIndex(this.curEditIndex);
                    this.details.load(code);
                }
                optionsButtonClick() {
                    var screen = Web.System.screens.openScreenWithModel("FileOptions", null, this._model.FileOptionsModel);
                    screen.onSaved = e => {
                        Web.System.screens.backToDashboard();
                        Web.System.screens.openScreen("Registro", this._model.ClassType);
                    };
                }
                initializeToolsButtons() {
                    if (!this._model.Tools)
                        return;
                    var tools = Sol.List.from(this._model.Tools);
                    if (tools.count > 3) {
                        const toolsButton = new Sol.Button();
                        toolsButton.text = Sol.Environment.resources.tools;
                        toolsButton.imageCode = "&#xf0ad;";
                        toolsButton.onSubitemClick = e => this.openTool(e, e.data);
                        tools.forEach(t => {
                            const item = new Sol.Control("li");
                            item.text = t.ToolName + "...";
                            item.data = t;
                            toolsButton.subitems.add(item);
                        });
                        if (toolsButton.subitems.hasItems())
                            this.toolBar.add(toolsButton);
                    }
                    else
                        tools.forEach(t => {
                            const toolButton = new Sol.Button();
                            toolButton.text = t.ToolName;
                            toolButton.imageCode = t.Icon || "&#xf0ad;";
                            toolButton.onClick = e => this.openTool(e, t);
                            this.toolBar.add(toolButton);
                        });
                }
                openTool(e, toolInfo) {
                    var _a;
                    if (((_a = toolInfo.Fields) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                        const screen = Web.System.screens.openScreenWithModel("FileTool", null, toolInfo);
                        screen.fileScreen = this;
                        screen.focus();
                        return;
                    }
                    this.hideAllMessages();
                    if (toolInfo.ShowConfirmation && !confirm(Sol.Environment.resources.confirmar_operacion + Sol.Environment.resources.start.toLowerCase() + '?'))
                        return;
                    let runToolRequest = {
                        className: toolInfo.ToolClass,
                        inputs: [],
                        contextClass: this.classType,
                        contextCode: this.anchorageCode,
                        filters: this.dataview.lastFilters
                    };
                    if (toolInfo.IsLargeProcess)
                        Web.System.execLarge("n954tvg7", "Run", runToolRequest, e => this.processToolResponse(toolInfo, e));
                    else
                        Web.System.exec("n954tvg7", "Run", runToolRequest, e => this.processToolResponse(toolInfo, e));
                }
                processToolResponse(toolInfo, model) {
                    if (model.Fail) {
                        this.mensajeErrorAccion.caption = model.ErrorMessage;
                        this.mensajeErrorAccion.visible = true;
                    }
                    else {
                        if (toolInfo.CustomActionName) {
                            const toolAction = eval("new Sol.Web.Actions." + toolInfo.CustomActionName + "()");
                            toolAction.processResponse(model);
                        }
                        else {
                            this.successMessage.caption = Sol.Environment.resources.exito_accion;
                            this.successMessage.visible = true;
                        }
                        this.refreshSearch();
                    }
                }
                initializeSummary() {
                    if (!this._model.CardModel)
                        return;
                    this._model.CardModel.FollowupRelationID = null;
                    const card = new Web.Components.Kanban.Card(null, this._model.CardModel, null, new Sol.List());
                    card.css.add("sol_kanban_file_screen");
                    this.add(card);
                }
                initializeDataView() {
                    this.dataview.myScreen = this;
                    this.dataview.anchorage = this.anchorage;
                    this.dataview.className = this._model.ClassType;
                    this.dataview.classHash = this._model.ClassHash;
                    this.dataview.availableGroups = this._model.DataView.Groups;
                    this.dataview.availableDecisions = this._model.Decisions;
                    this.dataview.allowReorder = !this._model.DataView.FixedColumns;
                    this.dataview.showToolbox = true;
                    this.dataview.showBell = this._model.DataView.HasInstantAlert;
                    this.dataview.kanbanInfo = this._model.DataView.KanbanInfo;
                    this.dataview.allowDefineColumnsSet = this._model.DataView.AllowDefineColumnsSet;
                    this.dataview.showVerticalLines = this._model.DataView.ShowVerticalLines;
                    this.dataview.showMap = this._model.DataView.ShowMap;
                    this.dataview.showReports = true;
                    this.dataview.showConfigButton = !this._model.DataView.FixedColumns;
                    this.dataview.availableColumns.addMany(this._model.DataView.Columns);
                    this.dataview.filters.addMany(this._model.DataView.Filters);
                    this.dataview.icon = this.screenIcon;
                    this.dataview.titulo = this._model.Title;
                    this.dataview.rowCount = this._model.DataView.LineCount;
                    if (!this._model.Readonly || this.showDetailsWhenReadonly)
                        this.dataview.onEdit = (c, i) => this.editItem(c, i);
                    this.dataview.onItemChecked = () => this.hideAllMessages();
                    this.dataview.showChecks = !this._model.Readonly && this._model.Methods.length > 0;
                    this.dataview.sortProperty = this._model.DataView.DefaultSortedColumn;
                    this.dataview.sortOrder = this._model.DataView.DefaultSortOrder;
                    this.dataview.canExportToExcel = this._model.DataView.CanExport;
                    this.dataview.allowDashboardCustomization = this._model.DataView.CanEditDashboards;
                    this.dataview.onDecision.subscribe(() => this.onFileChanged.invoke());
                    this.add(this.dataview);
                    this.dataview.isOpening = true;
                    this.dataview.searchBoxOpen = this._model.DataView.SearchBoxOpen;
                    if (this._model.DataView.OverviewClass)
                        this.dataview.overviewControl = eval(`new ${this._model.DataView.OverviewClass}()`);
                    this.dataview.viewMode = this._model.DataView.ViewMode;
                    this.dataview.isOpening = false;
                }
                initializeTableMultipleActions() {
                    if (this._model.Readonly)
                        return;
                    var actions = Sol.List.from(this._model.Methods);
                    this.noItemsSelectedMessage.caption = Sol.Environment.resources.ningun_seleccionado;
                    this.noItemsSelectedMessage.visible = false;
                    this.confirmacionAccion.type = Sol.MessageType.Confirmation;
                    this.confirmacionAccion.visible = false;
                    this.confirmacionAccion.onCancel = msg => msg.visible = false;
                    this.confirmacionAccion.onConfirm = e => this.confirmAction(e.data);
                    this.mensajeErrorAccion.visible = false;
                    this.actionSucessMessage.type = Sol.MessageType.Success;
                    this.actionSucessMessage.visible = false;
                    this.actionSucessMessage.caption = Sol.Environment.resources.exito_accion;
                    if (actions.hasItems()) {
                        this.messagesArea.add(this.noItemsSelectedMessage);
                        this.messagesArea.add(this.confirmacionAccion);
                        this.messagesArea.add(this.mensajeErrorAccion);
                        this.messagesArea.add(this.actionSucessMessage);
                    }
                    actions.forEach(action => {
                        const toolButton = new Sol.Button();
                        toolButton.imageCode = action.Icon;
                        toolButton.tip = action.Name;
                        toolButton.onClick = () => this.accionClick(action);
                        toolButton.data = action;
                        this.dataview.toolbox.add(toolButton);
                    });
                }
                confirmAction(action, inputs = null) {
                    this.hideAllMessages();
                    const doMultipleModel = {
                        className: action.ClassName,
                        decisionID: null,
                        methodName: action.MethodName,
                        selectionMode: this.dataview.selection.allSelected ? Web.ActionSelectionMode.All : Web.ActionSelectionMode.None,
                        filters: this.dataview.lastFilters,
                        ids: this.dataview.selection.codes.toArray(),
                        inputs: inputs
                    };
                    if (action.LargeProcess)
                        Web.System.execLarge("79k8j542h", "DoMultipleLarge", doMultipleModel, e => this.processActionResponse(action, e));
                    else
                        Web.System.exec("79k8j542h", "DoMultiple", doMultipleModel, e => this.processActionResponse(action, e));
                }
                processActionResponse(action, e) {
                    if (!e.Fail) {
                        if (action.CustomClass) {
                            let actionName = (action.CustomClass.indexOf('.') == -1 ? "Sol.Web.Actions." : "") + action.CustomClass;
                            const actionClass = eval("new " + actionName + "(e.Response)");
                            actionClass.processResponse(e);
                        }
                        else {
                            this.actionSucessMessage.visible = true;
                            this.refreshSearch();
                            this.onMultipleActionDone();
                            Web.System.screens.processSystemMessaje(this.systemMessage);
                        }
                    }
                    else {
                        this.mensajeErrorAccion.caption = e.ErrorMessage;
                        this.mensajeErrorAccion.visible = true;
                    }
                }
                accionClick(actionModel) {
                    this.hideAllMessages();
                    if (this.dataview.selection.isEmpty) {
                        this.noItemsSelectedMessage.visible = true;
                        return;
                    }
                    if (actionModel.ShowForm) {
                        var screen = Web.System.screens.openScreenWithModel("ActionScreen", null, actionModel);
                        screen.form.onSave = () => {
                            this.confirmAction(actionModel, screen.values);
                            Web.System.screens.closeCurrentScreen();
                        };
                        screen.focus();
                        return;
                    }
                    if (actionModel.ShowConfirmation) {
                        this.confirmacionAccion.data = actionModel;
                        this.confirmacionAccion.caption = actionModel.ConfirmationMessage;
                        this.confirmacionAccion.visible = true;
                    }
                    else
                        this.confirmAction(actionModel);
                }
                cancelDetailsScreen() {
                    this.showMe();
                }
                detailsSaved(data) {
                    this.showMe();
                    this.refreshSearch();
                    this.successMessage.caption = Sol.Environment.resources.grabado_ok;
                    if (this.details.createNewAfterSaving) {
                        const formData = Sol.List.from(data);
                        this.addNew();
                        Sol.List.from(this._model.DetailsModel.Structure)
                            .where(f => f.SaveAndNewOptions && f.SaveAndNewOptions.KeepValue)
                            .forEach(f => {
                            var _a, _b;
                            const editor = this.details.editors.that(edt => edt.propertyName == f.PropertyName);
                            if (!editor)
                                return;
                            if (editor instanceof Web.Components.DetailsEditor) {
                                let detailedData = formData
                                    .where(i => i.Campo.startsWith(f.PropertyName + '$'))
                                    .select(i => ({ Campo: i.Campo.substring(f.PropertyName.length + 1), Valor: i.Valor }));
                                editor.value = detailedData.toArray();
                            }
                            else {
                                let sourceValue = (_a = formData.that(i => i.Campo == f.PropertyName)) === null || _a === void 0 ? void 0 : _a.Valor;
                                if (sourceValue)
                                    editor.value = sourceValue;
                            }
                            if (editor.myLabel)
                                editor.myLabel.expanded = true;
                            (_b = editor.resetIDs) === null || _b === void 0 ? void 0 : _b.call(editor);
                        });
                        var autoFocusField = Sol.List.from(this._model.DetailsModel.Structure)
                            .that(f => f.SaveAndNewOptions && f.SaveAndNewOptions.AutoFocus);
                        if (autoFocusField)
                            setTimeout(() => this.details.editors.that(edt => edt.propertyName == autoFocusField.PropertyName).foco(), 300);
                    }
                    else if (this.details.requiresReload)
                        this.editItem(this.details.code, this.curEditIndex);
                    else {
                        this.successMessage.visible = true;
                        Web.System.screens.processSystemMessaje(this.systemMessage);
                    }
                }
                showMe() {
                    if (this.embbededMode) {
                        this.parent.controls.remove(this.details);
                        this.parent.controls.first().visible = true;
                        return;
                    }
                    if (this.myScreen)
                        Web.System.screens.showScreen(this.myScreen);
                    else
                        Web.System.screens.showScreen(this);
                }
            }
            Screens.Registro = Registro;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ActionBase extends Sol.Button {
                constructor() {
                    super();
                    this.engineManager = "79k8j542h";
                    this.type = Sol.ButtonType.Custom;
                }
                run() {
                    if (this.model.Fields && this.model.Fields.length > 0)
                        this.runFormBasedAction();
                    else
                        this.runInstantAction();
                }
                refresh() { }
                doFormBasedAction() {
                    const inputs = this.screen.values;
                    const doSingleModel = {
                        className: this.model.ClassName,
                        methodName: this.model.MethodName,
                        id: this.currentID,
                        inputs: inputs
                    };
                    Web.System.exec(this.engineManager, "DoSingle", doSingleModel, e => {
                        if (e.Fail)
                            this.screen.form.showError(e.ErrorMessage);
                        else {
                            this.successMessage = e.SuccessMessage;
                            this.processResponse(e);
                        }
                        this.screen.form.workComplete();
                    });
                }
                runFormBasedAction() {
                    this.model.EditingCode = this.detailsScreen.code;
                    this.screen = Web.System.screens.openScreenWithModel("ActionScreen", null, this.model);
                    this.screen.form.okButton.text = this.model.OkCaption || this.model.Name;
                    this.screen.form.cancelButton.text = this.model.CloseCaption || Sol.Environment.resources.cerrar;
                    if (this.model.RequiresRefresh)
                        this.refresh();
                    this.screen.form.onSave = () => this.doFormBasedAction();
                    this.screen.focus();
                }
                runInstantAction() {
                    if (this.model.ShowConfirmation &&
                        !confirm(Sol.Environment.resources.confirmar_operacion + (this.model.ConfirmationMessage || this.model.Name).toLowerCase() + '?'))
                        return;
                    let data = {
                        className: this.model.ClassName,
                        methodName: this.model.MethodName,
                        id: this.currentID,
                        inputs: null
                    };
                    if (this.model.LargeProcess)
                        Web.System.execLarge(this.engineManager, "DoLarge", data, e => {
                            if (e.Fail)
                                this.detailsScreen.showError(e.ErrorMessage);
                            else
                                this.processResponse(e);
                        });
                    else
                        Web.System.exec(this.engineManager, "DoSingle", data, e => {
                            if (e.Fail)
                                this.detailsScreen.showError(e.ErrorMessage);
                            else
                                this.processResponse(e);
                        });
                }
            }
            Actions.ActionBase = ActionBase;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class OpenTabAction extends Web.Actions.ActionBase {
                constructor() {
                    super(...arguments);
                    this.screenName = "Registro";
                }
                processResponse(data) { }
                run() {
                    const currentScreen = Web.System.screens.currentScreen;
                    this.code = this.code || currentScreen.code;
                    Web.System.screens.openScreen(this.screenName, this.className, null, null, null, screen => {
                        var _a;
                        const fileScreen = screen;
                        const filescreenModel = fileScreen.model;
                        if (fileScreen instanceof Web.Screens.Registro)
                            fileScreen.setModel(filescreenModel);
                        fileScreen.embbededMode = !!this.targetControl;
                        filescreenModel.Readonly = filescreenModel.Readonly || this.readonly;
                        if (filescreenModel.DataView)
                            filescreenModel.DataView.SearchBoxOpen = false;
                        fileScreen.showDetailsWhenReadonly = true;
                        fileScreen.anchorage = { PropertyName: this.associativePropertyName, FilterType: "SInteger", FilterValue: this.code };
                        (_a = fileScreen.onFileChanged) === null || _a === void 0 ? void 0 : _a.subscribe(() => {
                            this.tab.refreshCount(this.code);
                            if (this.reloadAfterSave)
                                Web.System.screens.currentDetails.reloadFields();
                        });
                        fileScreen.onCloseScreen = () => {
                            currentScreen.reloadFields();
                            return true;
                        };
                        if (this.targetControl)
                            this.targetControl.add(fileScreen);
                    }, this.code, this.associativePropertyName);
                }
            }
            Components.OpenTabAction = OpenTabAction;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let TabEditorCodeMode;
            (function (TabEditorCodeMode) {
                TabEditorCodeMode[TabEditorCodeMode["IDMode"] = 0] = "IDMode";
                TabEditorCodeMode[TabEditorCodeMode["RelatedEntityMode"] = 1] = "RelatedEntityMode";
            })(TabEditorCodeMode = Components.TabEditorCodeMode || (Components.TabEditorCodeMode = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TabEditor extends Sol.Button {
                constructor(config) {
                    super();
                    this.code = 0;
                    this.isComplex = false;
                    this.configuration = config;
                    this.showCounter = true;
                    this.onClick = () => this.meClick();
                    this.imageCode = config.Icon;
                    this.counterColor = config.CounterColor;
                    if (config.CssClass)
                        this.css.add(config.CssClass);
                }
                isEmpty() { return true; }
                validate() { return null; }
                get value() { return this._value; }
                set value(v) { this._value = v, this.setCounterValue(v); }
                embbed(target) {
                    this.targetControl = target;
                    this.meClick();
                }
                toControl() { return this; }
                foco() { }
                clear() { }
                refreshCount(anchorageCode) {
                    const data = {
                        className: this.configuration.ClassName,
                        anchorage: {
                            FilterType: "SInteger",
                            PropertyName: this.configuration.AssociativePropertyName,
                            FilterValue: anchorageCode
                        }
                    };
                    Web.System.exec("nlskd23jor", "GetCounting", data, e => this.setCounterValue(e));
                }
                meClick() {
                    const currentScreen = Web.System.screens.currentDetails;
                    const action = new Components.OpenTabAction();
                    action.code = this.configuration.CodeMode == Components.TabEditorCodeMode.RelatedEntityMode ?
                        currentScreen.relatedEntityCode : this.code;
                    action.className = this.configuration.ClassName;
                    action.associativePropertyName = this.configuration.AssociativePropertyName;
                    action.screenName = this.configuration.ScreenName;
                    action.readonly = this.readonly;
                    action.targetControl = this.targetControl;
                    action.currentCount = this.value;
                    action.reloadAfterSave = this.reloadAfterSave || this.configuration.ReloadAfterSave;
                    action.tab = this;
                    if (!this.code) {
                        currentScreen.disableReload = true;
                        currentScreen.waitForSaving(action);
                        currentScreen.onSavingError.subscribe(() => {
                            if (this.onCancelEnter)
                                this.onCancelEnter();
                        });
                    }
                    else
                        action.run();
                }
            }
            Components.TabEditor = TabEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    class ExitConfirmationDialog extends Sol.DialogBox {
        constructor() {
            super();
            this.title = Sol.Environment.resources.exitConfirmationTitle;
            this.contentArea.css.add("sol_exit_confirmation_dialog");
            this.contentArea.addCtr(Sol.Environment.resources.exitConfirmationMessage, "sol_exit_confirmation_message");
            this.contentArea.addCtr(Sol.Environment.resources.wantSave, "sol_exit_confirmation_message");
            const backButton = new Sol.Button();
            backButton.text = Sol.Environment.resources.back;
            backButton.tip = Sol.Environment.resources.backTip;
            backButton.onClick = () => this.onClosing();
            this.contentArea.add(backButton);
            const saveButton = new Sol.Button();
            saveButton.text = Sol.Environment.resources.grabar;
            saveButton.tip = Sol.Environment.resources.grabarTip;
            saveButton.onClick = () => {
                this.onSave();
                this.onClosing();
            };
            this.contentArea.add(saveButton);
            const exitButton = new Sol.Button();
            exitButton.text = Sol.Environment.resources.exitWithoutSaving;
            exitButton.tip = Sol.Environment.resources.exitWithoutSavingTip;
            exitButton.onClick = () => {
                this.onExit();
                this.onClosing();
            };
            this.contentArea.add(exitButton);
        }
    }
    Sol.ExitConfirmationDialog = ExitConfirmationDialog;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ActionFactory {
                static LoadAction(model) {
                    var bag = {};
                    bag["GenerateBankSlip"] = "ViewDocumentAction";
                    bag["GenerateCertificate"] = "DownloadAction";
                    bag["SetSystems"] = "SelectSystemsAction";
                    bag["ViewOpportunity"] = "ViewDocumentAction";
                    bag["GenerateCorrectionLetterPDF"] = "DownloadAction";
                    bag["GenerateBalancePdf"] = "DownloadAction";
                    bag["ViewBudget"] = "ViewDocumentAction";
                    bag["ViewVoucher"] = "ViewDocumentAction";
                    bag["PrintLabels"] = "ViewDocumentAction";
                    bag["ViewBill"] = "ViewDocumentAction";
                    bag["ViewLabel"] = "ViewDocumentAction";
                    bag["ViewReceipt"] = "ViewDocumentAction";
                    bag["Print"] = "ViewDocumentAction";
                    bag["ViewEnrollments"] = "OpenScreenAction";
                    bag["ViewServiceOrderHtml"] = "ViewDocumentAction";
                    bag["GeneratePDF"] = "DownloadAction";
                    bag["ApprovationLink"] = "ApprovationLinkAction";
                    bag["SendLogin"] = "LocalAction";
                    bag["GeneratePreviewScreen"] = "PreviewScreenAction";
                    bag["StartSale"] = "StartSaleAction";
                    bag["HistoryScreen"] = "HistoryScreenAction";
                    bag["ImportFromXml"] = "PurchasingXmlImportAction";
                    bag["CreateRequest"] = "ProductRegistrationCreateRequestAction";
                    var selectedActionName = model.CustomClass || bag[model.MethodName] || "GenericAction";
                    var action = eval("new Sol.Web.Actions." + selectedActionName + "()");
                    action.model = model;
                    action.imageCode = model.Icon;
                    action.text = model.Name;
                    action.tip = model.Description;
                    return action;
                }
            }
            Actions.ActionFactory = ActionFactory;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let DeliveryType;
            (function (DeliveryType) {
                DeliveryType[DeliveryType["Customer"] = 1] = "Customer";
                DeliveryType[DeliveryType["OwnCourier"] = 2] = "OwnCourier";
                DeliveryType[DeliveryType["Delivery"] = 3] = "Delivery";
                DeliveryType[DeliveryType["Email"] = 4] = "Email";
            })(DeliveryType = Components.DeliveryType || (Components.DeliveryType = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let DeliveryPayer;
            (function (DeliveryPayer) {
                DeliveryPayer[DeliveryPayer["Unset"] = 0] = "Unset";
                DeliveryPayer[DeliveryPayer["Sender"] = 1] = "Sender";
                DeliveryPayer[DeliveryPayer["Recipient"] = 2] = "Recipient";
            })(DeliveryPayer = Components.DeliveryPayer || (Components.DeliveryPayer = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DeliveryChoice extends Sol.MultipleChoice {
                constructor() {
                    super();
                    this.inlineItems = true;
                    this.onChange.subscribe(() => {
                        this.selectFields();
                        if (this.onChoose)
                            this.onChoose(this);
                    });
                }
                get selectedType() { return this.selectedCode; }
                build() {
                    super.build();
                    this.selectFields();
                }
                selectFields() {
                    var payerEditor = this.container.editors.that(cp => cp.propertyName == "Payer");
                    payerEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.Delivery;
                    var amountEditor = this.container.editors.that(cp => cp.propertyName == "QuotedAmount");
                    if (amountEditor)
                        amountEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.Delivery;
                    var amountEditor = this.container.editors.that(cp => cp.propertyName == "Amount");
                    amountEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.OwnCourier || this.selectedType == Components.DeliveryType.Delivery;
                    var carrierEditor = this.container.editors.that(cp => cp.propertyName == "CarrierCompany");
                    carrierEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.Delivery;
                    var totalPayEditor = this.container.editors.that(cp => cp.propertyName == "TotalPayments");
                    totalPayEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.OwnCourier;
                    var sumDeliveryEditor = this.container.editors.that(cp => cp.propertyName == "SumDeliveryChargeOnTotal");
                    sumDeliveryEditor.toControl().visible = (this.selectedType == Components.DeliveryType.Delivery || this.selectedType == Components.DeliveryType.OwnCourier) && payerEditor.value.Valor == Components.DeliveryPayer.Sender;
                    if (amountEditor.toControl().parent.visible)
                        amountEditor.foco();
                }
            }
            Components.DeliveryChoice = DeliveryChoice;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DetailsEditor extends Web.FieldGroupEditor {
                constructor() {
                    super();
                    this.details = new Web.Screens.DetailsScreen();
                    this.isComplex = true;
                    this._readonly = false;
                    this._savable = false;
                    this.details.disableMinimizedControls = true;
                    this.details.showTitle = false;
                    this.details.myForm.footer.visible = false;
                    this.details.topOffSet = 0;
                    this.details.onBuildComplete = () => this.editors = this.details.editors;
                    this.add(this.details);
                }
                get formState() { return this.details.formState; }
                set formState(value) { this.details.formState = value; }
                get readonly() { return this._readonly; }
                set readonly(value) {
                    this._readonly = value;
                    if (value)
                        this.details.editors.forEach(f => f.readonly = value);
                }
                get savable() { return this._savable; }
                set savable(value) {
                    this._savable = value;
                    this.details.editors.forEach(f => f.savable = value);
                }
                get value() {
                    let values = Sol.List.from(this.details.values);
                    values.forEach(v => v.Campo = this.propertyName + '$' + v.Campo);
                    values.add({ Campo: this.propertyName + "$ID", Valor: this.details.code });
                    return values.toArray();
                }
                set value(value) { this.setValue(value); }
                foco() { }
                isEmpty() { return this.details.editors.all(c => c.isEmpty()); }
                clear() { }
                getEditor(propertyName) {
                    return this.details.getEditor(propertyName);
                }
                showFilledFields() { this.details.showFilledFields(); }
                toControl() { return this; }
                validate() {
                    const errors = this.editors.select(edt => edt.validate()).where(e => !!e);
                    return errors.hasItems() ? errors.join("\r\n") : null;
                }
                build() {
                    super.build();
                    this.details.model = this.model;
                }
                setValue(value) {
                    this.details.loadData(value);
                    if (this.myLabel)
                        this.myLabel.expanded = !this.isEmpty();
                }
            }
            Components.DetailsEditor = DetailsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DeliveryEditor extends Components.DetailsEditor {
                get screen() { return this.parent.parent; }
                get addressFields() { return this.details.getEditor("AddressDisplay"); }
                get customer() {
                    const editor = this.screen.getEditor("Destinatario");
                    if (!editor || !(editor instanceof Web.Commercial.Customers.CustomerSelector))
                        return null;
                    return editor.selectedCode;
                }
                get amount() {
                    return this.details.editors.that(edt => edt.propertyName == "Amount").numericValue;
                }
                get selectedPayer() {
                    return parseInt(this.details.editors.that(edt => edt.propertyName == "Payer").selectedCode);
                }
                get selectedType() {
                    return this.details.editors.that(edt => edt instanceof Components.DeliveryChoice).selectedType;
                }
                get sumDeliveryChargeOnTotal() {
                    return this.details.getEditor("SumDeliveryChargeOnTotal").checked;
                }
                get totalizableAmount() {
                    return ((this.selectedType == Components.DeliveryType.Delivery && this.selectedPayer == Components.DeliveryPayer.Sender)
                        || this.selectedType == Components.DeliveryType.OwnCourier) && this.sumDeliveryChargeOnTotal ? this.amount : 0;
                }
                get cost() { return 0; }
                get isSummable() { return true; }
                get margin() {
                    return (this.selectedType == Components.DeliveryType.Delivery && !this.sumDeliveryChargeOnTotal) ||
                        this.selectedType == Components.DeliveryType.OwnCourier ? -this.amount : 0;
                }
                get total() { return this.totalizableAmount; }
                build() {
                    super.build();
                    this.css.add("sol_delivery_editor");
                    setTimeout(() => {
                        this.details.editors.that(edt => edt.propertyName == "Amount").onChange = () => this.changeTotal();
                        this.details.editors.that(edt => edt.propertyName == "Payer").onChange = () => this.changeTotal();
                        this.details.editors.that(edt => edt instanceof Components.DeliveryChoice).onChoose = () => this.changeTotal();
                        this.details.editors.that(edt => edt.propertyName == "SumDeliveryChargeOnTotal").onChange = () => this.changeTotal();
                    }, 300);
                    this.details.onBuildComplete = () => this.selectFields();
                }
                setValue(value) {
                    super.setValue(value);
                    setTimeout(() => this.addressFields.loadAddress(this.customer), 300);
                }
                updateAddress(code) {
                    this.addressFields.loadAddress(code);
                }
                changeTotal() {
                    this.selectFields();
                    if (this.onTotalsChanged)
                        this.onTotalsChanged();
                }
                selectFields() {
                    this.addressFields.visible = (this.selectedType == Components.DeliveryType.OwnCourier || this.selectedType == Components.DeliveryType.Delivery) && this.customer > 0;
                    this.addressFields.loadAddress(this.customer);
                    var sumDeliveryEditor = this.details.getEditor("SumDeliveryChargeOnTotal");
                    sumDeliveryEditor.toControl().visible = this.selectedType == Components.DeliveryType.OwnCourier || (this.selectedType == Components.DeliveryType.Delivery && this.selectedPayer == Components.DeliveryPayer.Sender);
                    var amountEditor = this.details.getEditor("Amount");
                    amountEditor.numericValue = this.selectedType == Components.DeliveryType.Delivery && this.selectedPayer == Components.DeliveryPayer.Recipient ? 0 : amountEditor.numericValue;
                    amountEditor.readonly = this.selectedType == Components.DeliveryType.Delivery && this.selectedPayer == Components.DeliveryPayer.Recipient;
                    var quantityEditor = this.details.getEditor("Quantity");
                    quantityEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.Delivery;
                    var packageTypeEditor = this.details.getEditor("PackageType");
                    packageTypeEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.Delivery;
                    var grossWeightEditor = this.details.getEditor("GrossWeight");
                    grossWeightEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.Delivery;
                    var netWeightEditor = this.details.getEditor("NetWeight");
                    netWeightEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.Delivery;
                    var trackingCodeEditor = this.details.getEditor("TrackingCode");
                    trackingCodeEditor.toControl().parent.visible = this.selectedType == Components.DeliveryType.Delivery;
                }
            }
            Components.DeliveryEditor = DeliveryEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DefaultValueSelector extends Sol.Control {
                constructor() {
                    super("span");
                    this.autoSave = true;
                    this.css.add("sol_default_value");
                    this.text = "&#xf005;";
                    this.tip = Sol.Environment.resources.setDefault;
                    this.onClick = () => this.saveDefault();
                }
                saveDefault() {
                    this.css.add("sol_default_value_saving");
                    if (this.autoSave)
                        Web.System.exec("7pd0b4fg", "SaveUserDefault", {
                            classType: this.className,
                            propertyName: this.editor.propertyName,
                            value: JSON.stringify(this.editor.value)
                        }, () => {
                            this.css.remove("sol_default_value_saving");
                            this.css.add("sol_default_value_saved");
                            setTimeout(() => { this.css.remove("sol_default_value_saved"); }, 3000);
                        });
                    if (this.onSave)
                        this.onSave(this);
                }
            }
            Components.DefaultValueSelector = DefaultValueSelector;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Discounts;
            (function (Discounts) {
                class IPromotionModel {
                }
                Discounts.IPromotionModel = IPromotionModel;
            })(Discounts = Commercial.Discounts || (Commercial.Discounts = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Discounts;
            (function (Discounts) {
                class ApplicableDiscountEditor extends Web.Components.DataView {
                    constructor() {
                        super();
                        this.showSearchBox = false;
                        this.fixedRows = false;
                        this.showChecks = false;
                        this.allowNew = false;
                    }
                    build() {
                        this.availableColumns.forEach(cl => cl.EditorModel.ReadOnly = true);
                        super.build();
                    }
                }
                Discounts.ApplicableDiscountEditor = ApplicableDiscountEditor;
            })(Discounts = Commercial.Discounts || (Commercial.Discounts = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ApplicableDiscount", model => {
    const applicableDiscountEditor = new Sol.Web.Commercial.Discounts.ApplicableDiscountEditor();
    Sol.Web.Editors.fillDataViewStructure(applicableDiscountEditor, model.Structure);
    return applicableDiscountEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Discounts;
            (function (Discounts) {
                class DiscountChoice extends Sol.MultipleChoice {
                    constructor() {
                        super();
                        this.inlineItems = true;
                        this.onChange.subscribe(() => this.selectFields());
                    }
                    get valueEditor() { return this.container.editors.that(cp => cp.propertyName == "DiscountValue"); }
                    get percentEditor() { return this.container.editors.that(cp => cp.propertyName == "Percentage"); }
                    updateFields() {
                        this.valueEditor.readonly = this.selectedCode != 1;
                        this.percentEditor.readonly = this.selectedCode != 2;
                    }
                    selectFields() {
                        this.updateFields();
                        if (this.selectedCode == 1)
                            this.valueEditor.foco();
                        else if (this.selectedCode == 2)
                            this.percentEditor.foco();
                        if (this.onModified)
                            this.onModified();
                    }
                }
                Discounts.DiscountChoice = DiscountChoice;
            })(Discounts = Commercial.Discounts || (Commercial.Discounts = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("DiscountChoice", model => {
    const discountChoice = new Sol.Web.Commercial.Discounts.DiscountChoice();
    discountChoice.options = model.Options;
    return discountChoice;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class SelectorQuantityField extends Sol.NumericField {
                get myListItem() { return this.parent.parent; }
                constructor() {
                    super();
                    this.onFocus.subscribe(() => this.myListItem.selected = true);
                }
            }
            Screens.SelectorQuantityField = SelectorQuantityField;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("SelectorQuantityField", model => {
    let field = new Sol.Web.Screens.SelectorQuantityField();
    field.decimals = model.Decimals || 0;
    field.tamanoMaximo = model.MaxLength || field.tamanoMaximo;
    field.acceptsNegative = model.AcceptsNegative;
    if (model.Width)
        field.ancho = model.Width;
    return field;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class QuotationHistoryDialog extends Sol.DialogBox {
                    constructor() {
                        super();
                        this.grid = new Web.Components.Grid();
                        this.title = Sol.Environment.resources.quotationsHistorial;
                    }
                    load(productCode) {
                        var data = {
                            className: "Solarium.Commercial.SupplierQuotation, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            currentPage: 1,
                            rowCount: 15,
                            filters: [
                                {
                                    PropertyName: "PriceQuotation$ValidationProduct",
                                    FilterValue: productCode,
                                    FilterType: "SInteger"
                                }
                            ],
                            sortProperty: "Creación",
                            sortOrder: Web.Ordering.descending,
                            properties: ["Creación", "Price", "Expiration", "DeliveryDay", "Warranty", "Supplier", "FreightPrice", "TaxReplacement"],
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", data, response => {
                            this.grid.loadData(response);
                        });
                    }
                    build() {
                        super.build();
                        this.initializeGrid();
                    }
                    initializeGrid() {
                        this.grid.rowCount = 15;
                        this.grid.showChecks = false;
                        this.grid.columns.addMany([
                            {
                                DataType: "SDate",
                                PropertyName: "Creación",
                                Title: Sol.Environment.resources.date,
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Center
                            },
                            {
                                DataType: "SMoney",
                                PropertyName: "Price",
                                Title: Sol.Environment.resources.amount,
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Right
                            },
                            {
                                DataType: "SDate",
                                PropertyName: "Expiration",
                                Title: Sol.Environment.resources.expiration_quotation,
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Center
                            },
                            {
                                DataType: "SInteger",
                                PropertyName: "DeliveryDay",
                                Title: Sol.Environment.resources.time_payment,
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Center
                            },
                            {
                                DataType: "SText",
                                PropertyName: "Warranty",
                                Title: Sol.Environment.resources.warranty_quotation,
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Left
                            },
                            {
                                DataType: "SMoney",
                                PropertyName: "FreightPrice",
                                Title: "Valor do frete",
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Left
                            },
                            {
                                DataType: "SMoney",
                                PropertyName: "TaxReplacement",
                                Title: "Substituição tributária",
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Left
                            }
                        ]);
                        if (this.showSupplier)
                            this.grid.columns.add({
                                DataType: "Supplier",
                                PropertyName: "Supplier",
                                Title: Sol.Environment.resources.supplier,
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Left
                            });
                        this.contentArea.add(this.grid);
                    }
                }
                Products.QuotationHistoryDialog = QuotationHistoryDialog;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class CompanyGroupStockDialog extends Sol.DialogBox {
                    constructor() {
                        super();
                        this.grid = new Web.Components.Grid();
                        this.title = Sol.Environment.resources.company_group_stock;
                        this.css.add("company_group_stock_dialog");
                    }
                    load(productCode) {
                        Web.System.exec("79k8jhkh", "GetCompanyGroupProductStock", {
                            credential: Sol.Environment.credential.export(),
                            productID: productCode
                        }, e => {
                            e.forEach(i => this.grid.addRow(i));
                        });
                    }
                    build() {
                        super.build();
                        this.initializeGrid();
                    }
                    initializeGrid() {
                        this.grid.showChecks = false;
                        this.grid.columns.addMany([
                            {
                                DataType: "SText",
                                PropertyName: "Company",
                                Title: Sol.Environment.resources.subsidiary,
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Left
                            },
                            {
                                DataType: "SNumber",
                                PropertyName: "CurrentStock",
                                Title: Sol.Environment.resources.stock,
                                ShowTitle: true,
                                Visible: true,
                                Alignment: Sol.Alignment.Right
                            },
                        ]);
                        this.contentArea.add(this.grid);
                    }
                }
                Products.CompanyGroupStockDialog = CompanyGroupStockDialog;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let ProductScreenViewMode;
            (function (ProductScreenViewMode) {
                ProductScreenViewMode[ProductScreenViewMode["Category"] = 0] = "Category";
                ProductScreenViewMode[ProductScreenViewMode["Search"] = 1] = "Search";
            })(ProductScreenViewMode = Screens.ProductScreenViewMode || (Screens.ProductScreenViewMode = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                let ProductsEditorPriceMode;
                (function (ProductsEditorPriceMode) {
                    ProductsEditorPriceMode[ProductsEditorPriceMode["Normal"] = 0] = "Normal";
                    ProductsEditorPriceMode[ProductsEditorPriceMode["Cost"] = 1] = "Cost";
                    ProductsEditorPriceMode[ProductsEditorPriceMode["None"] = 2] = "None";
                })(ProductsEditorPriceMode = Products.ProductsEditorPriceMode || (Products.ProductsEditorPriceMode = {}));
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var ProductClassification;
(function (ProductClassification) {
    ProductClassification[ProductClassification["Product"] = 1] = "Product";
    ProductClassification[ProductClassification["Equipment"] = 2] = "Equipment";
    ProductClassification[ProductClassification["Service"] = 3] = "Service";
    ProductClassification[ProductClassification["Software"] = 4] = "Software";
})(ProductClassification || (ProductClassification = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let ProductSelectorScrapBookOption;
            (function (ProductSelectorScrapBookOption) {
                ProductSelectorScrapBookOption[ProductSelectorScrapBookOption["Department"] = 0] = "Department";
                ProductSelectorScrapBookOption[ProductSelectorScrapBookOption["Category"] = 1] = "Category";
            })(ProductSelectorScrapBookOption = Screens.ProductSelectorScrapBookOption || (Screens.ProductSelectorScrapBookOption = {}));
            class ProductSelectorScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.className = "Solarium.Commercial.Product, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.categoriesButton = new Sol.Button();
                    this.categoryDisplay = new Sol.Control("span");
                    this.categoryNavigation = new Sol.Control();
                    this.departmentBook = new Web.Components.Scrapbook();
                    this.categoryBook = new Web.Components.Scrapbook();
                    this.container = new Sol.Control();
                    this.criteriaArea = new Web.Components.CollectionSelector();
                    this.doneButton = new Sol.Button();
                    this.exactMatchCheck = new Sol.Check();
                    this.list = new Web.Components.ListView();
                    this.searchButton = new Sol.Button();
                    this.searchField = new Sol.Field();
                    this.startView = Screens.ProductScreenViewMode.Search;
                    this.priceMode = Web.Commercial.Products.ProductsEditorPriceMode.Normal;
                    this.showCatalog = true;
                }
                get selectedItems() {
                    return this.list.items.select(i => ({
                        code: i.code,
                        quantity: i.getEditor("Quantity").value,
                        price: i.getModelValue("EffectivePriceData"),
                        data: i.model
                    }))
                        .where(i => i.quantity > 0);
                }
                focus() {
                    this.searchField.foco();
                }
                build() {
                    super.build();
                    this.initializeTitle();
                    this.initializeToolbar();
                    this.initializeContainer();
                    this.initializeCriteriaArea();
                    this.initializeSearchField();
                    this.initializeList();
                    this.initializeScrapbooks();
                    this.initDoneButton();
                    setTimeout(() => this.search(), 300);
                }
                doneClick() {
                    let items = this.selectedItems;
                    if (items.count == 0) {
                        alert(Sol.Environment.resources.ningun_seleccionado);
                        return;
                    }
                    this.onProductSelected(items);
                }
                initializeToolbar() {
                    var toolbar = new Sol.Control();
                    toolbar.css.addMany(["sol_barra_herramientas", "sol_search_product_toolbox"]);
                    this.searchButton.text = Sol.Environment.resources.buscar;
                    this.searchButton.imageCode = "&#xf002;";
                    this.searchButton.type = Sol.ButtonType.Alternate;
                    this.searchButton.checked = this.startView == Screens.ProductScreenViewMode.Search;
                    this.searchButton.onChecked = () => this.showSearch();
                    toolbar.add(this.searchButton);
                    if (this.showCatalog) {
                        this.categoriesButton.text = Sol.Environment.resources.catalog;
                        this.categoriesButton.imageCode = "&#xf1b3;";
                        this.categoriesButton.type = Sol.ButtonType.Alternate;
                        this.categoriesButton.checked = this.startView == Screens.ProductScreenViewMode.Category;
                        if (this.startView == Screens.ProductScreenViewMode.Category)
                            this.showScrapbook();
                        this.categoriesButton.onChecked = () => this.showScrapbook();
                        toolbar.add(this.categoriesButton);
                    }
                    if (this.allowAddNew) {
                        const addNewButton = new Sol.Button();
                        addNewButton.text = this.fileScreenCaption;
                        addNewButton.imageCode = "&#xf187;";
                        addNewButton.onClick = () => Web.System.screens.openScreen("Registro", this.className);
                        toolbar.add(addNewButton);
                    }
                    this.add(toolbar);
                }
                initializeContainer() {
                    this.container.css.add("sol_search_product_screen");
                    this.add(this.container);
                }
                initializeTitle() {
                    var screenTitle = new Screens.ScreenTitle();
                    this.screenCaption = this.onlyEquipments ? Sol.Environment.resources.select_equipment : Sol.Environment.resources.select_product;
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                }
                initializeCriteriaArea() {
                    this.criteriaArea.allowAddNew = false;
                    this.criteriaArea.onChanged = () => {
                        if (!this.criteriaArea.isEmpty())
                            return;
                        this.selectedCategory = null;
                        this.search();
                    };
                    this.container.add(this.criteriaArea);
                }
                initializeSearchField() {
                    this.searchField.placeHolder = Sol.Environment.resources.typeToSearch;
                    this.searchField.css.add("sol_search_product_screen_search");
                    this.searchField.maxLength = 100;
                    this.searchField.autoWidth = false;
                    this.searchField.ancho = 500;
                    this.searchField.onKeyUp = e => {
                        if (e.key == "Enter")
                            this.list.select();
                        else if (e.key == "ArrowDown")
                            this.list.selectDown();
                        else if (e.key == "ArrowUp")
                            this.list.selectUp();
                        else
                            this.search();
                    };
                    this.container.add(this.searchField);
                    this.exactMatchCheck.estilos.agregar("display", "inline");
                    this.exactMatchCheck.caption = Sol.Environment.resources.exactSearch;
                    this.exactMatchCheck.onChange = () => this.search();
                    this.container.add(this.exactMatchCheck);
                }
                initializeList() {
                    this.list.serviceKey = "79k8jhkh";
                    this.list.serviceMethod = "FindProducts";
                    this.list.selectable = true;
                    this.list.showImage = true;
                    this.list.selectionEnabled = true;
                    this.list.pageSize = this.multipleSelection ? 0 : 50;
                    this.list.onInstantiateItem = e => this.instantiateItem(e);
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: true,
                            property: "MainPicture",
                            position: Web.Components.ListViewFieldPosition.Image
                        },
                        {
                            loadable: false,
                            property: "Quantity",
                            caption: Sol.Environment.resources.product_quantity,
                            position: Web.Components.ListViewFieldPosition.Left,
                            disabled: !this.multipleSelection,
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "SelectorQuantityField",
                                PropertyName: "Quantity",
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: false,
                                Width: 60
                            }
                        },
                        {
                            loadable: true,
                            property: "Nombre",
                            cssClass: "sol_search_product_screen_name",
                            priority: Web.Components.ListViewFieldPriority.High,
                            position: Web.Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "Brand$Nombre",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "PartNumber",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            caption: Sol.Environment.resources.main_pn,
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "DescriptionText",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            cssClass: "sol_search_product_description",
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "Category$Color",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "Category$Nombre",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            cssClass: "sol_search_product_category",
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "Category$Department$Color",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "Category$Department$Nombre",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            cssClass: "sol_search_product_category",
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: this.priceMode == Web.Commercial.Products.ProductsEditorPriceMode.Cost ? "EffectiveCost" : "EffectivePrice",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right,
                            caption: Sol.Environment.resources.product_price,
                            lineBreak: true,
                            hidden: this.priceMode == Web.Commercial.Products.ProductsEditorPriceMode.None
                        },
                        {
                            loadable: true,
                            property: "EffectivePriceData",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "EffectivePriceValue",
                            hidden: true
                        },
                        {
                            loadable: this.showCost,
                            property: "EffectiveCost",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right,
                            caption: Sol.Environment.resources.product_cost
                        },
                        {
                            loadable: false,
                            disabled: !this.showGroupCompanyStockTool,
                            property: "CompanyGroupStockButton",
                            cssClass: "sol_search_product_screen_group_stock",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right
                        },
                        {
                            loadable: true,
                            property: "CurrentStock",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right,
                            caption: Sol.Environment.resources.current_stock
                        },
                        {
                            loadable: true,
                            property: "AvailableStock",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right,
                            caption: Sol.Environment.resources.available_stock
                        },
                        {
                            loadable: false,
                            disabled: !this.showQuotationTools,
                            property: "QuotationHistorial",
                            cssClass: "sol_search_product_screen_quotation",
                            defaultText: Sol.Environment.resources.quotationsHistorial,
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: this.loadDescription,
                            property: "Description",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "EffectivePriceValue",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "PurchaseUnit",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "PurchaseUnit$Decimals",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "PurchaseUnit$Description",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right,
                            caption: Sol.Environment.resources.unit
                        },
                        {
                            loadable: true,
                            property: "PurchaseUnit$Nombre",
                            hidden: true
                        }
                    ]);
                    if (!this.multipleSelection)
                        this.list.onSelect = (data, code) => {
                            if (this.onProductSelected)
                                this.onProductSelected(Sol.List.from([{ code: code, quantity: 1, data: data, price: null }]));
                        };
                    this.container.add(this.list);
                }
                initializeScrapbooks() {
                    if (!this.showCatalog)
                        return;
                    const rootLink = new Sol.Button();
                    rootLink.type = Sol.ButtonType.Link;
                    rootLink.text = this.categoriesButton.text;
                    rootLink.onClick = () => this.loadBook(ProductSelectorScrapBookOption.Department);
                    this.categoryNavigation.visible = false;
                    this.categoryNavigation.add(rootLink);
                    this.categoryDisplay.css.add("sol_search_product_category_display");
                    this.categoryDisplay.visible = false;
                    this.categoryNavigation.add(this.categoryDisplay);
                    this.add(this.categoryNavigation);
                    this.departmentBook.visible = false;
                    this.departmentBook.onItemSelected = e => this.selectDepartment(e);
                    this.add(this.departmentBook);
                    this.categoryBook.onItemSelected = e => this.selectCategory(e);
                    this.categoryBook.visible = false;
                    this.add(this.categoryBook);
                }
                initDoneButton() {
                    let wrapper = this.container.addCtr(null, "sol_search_product_done_wrapper");
                    this.doneButton.text = "Concluído";
                    this.doneButton.visible = this.multipleSelection;
                    this.doneButton.accessKey = 'C';
                    this.doneButton.onClick = () => this.doneClick();
                    wrapper.add(this.doneButton);
                }
                instantiateItem(item) {
                    const catColor = item.getModelValue("Category$Color");
                    const catDisplay = item.getDisplay("Category$Nombre");
                    if (catColor != "#000000")
                        catDisplay.estilos.definir("border-left-color", catColor);
                    catDisplay.visible = !!item.getModelValue("Category$Nombre");
                    const depColor = item.getModelValue("Category$Department$Color");
                    const depDisplay = item.getDisplay("Category$Department$Nombre");
                    if (depColor != "#000000")
                        depDisplay.estilos.definir("border-left-color", depColor);
                    depDisplay.visible = !!item.getModelValue("Category$Department$Nombre");
                    const companyGroupStockDisplay = item.getDisplay("CompanyGroupStockButton");
                    if (companyGroupStockDisplay) {
                        companyGroupStockDisplay.tip = Sol.Environment.resources.company_group_stock;
                        companyGroupStockDisplay.onClick = () => {
                            if (this.companyGroupStockCurrentDialog)
                                this.companyGroupStockCurrentDialog.onClose();
                            const dialog = new Web.Commercial.Products.CompanyGroupStockDialog();
                            dialog.onClose = () => this.parent.controls.remove(dialog);
                            this.parent.add(dialog);
                            dialog.load(item.code);
                            this.companyGroupStockCurrentDialog = dialog;
                            return false;
                        };
                    }
                    const quotationDisplay = item.getDisplay("QuotationHistorial");
                    if (!quotationDisplay)
                        return;
                    quotationDisplay.clickResult = false;
                    quotationDisplay.onClick = () => {
                        const dialog = new Web.Commercial.Products.QuotationHistoryDialog();
                        dialog.onClose = () => this.parent.controls.remove(dialog);
                        this.parent.add(dialog);
                        dialog.load(item.code);
                    };
                    this.configQuantityDecimals(item);
                }
                configQuantityDecimals(item) {
                    let quantityField = item.getEditor("Quantity");
                    if (!quantityField)
                        return;
                    quantityField.decimals = item.getModelValue("PurchaseUnit$Decimals");
                }
                loadBook(option, departmentFilter = 0) {
                    const className = option == ProductSelectorScrapBookOption.Department ? "SalesDepartment" : "Category";
                    const imagePropName = (option == ProductSelectorScrapBookOption.Department ? "Department" : "Category") + "Image$Identificador";
                    const targetBook = option == ProductSelectorScrapBookOption.Department ? this.departmentBook : this.categoryBook;
                    this.departmentBook.visible = this.departmentBook == targetBook;
                    this.categoryBook.visible = this.categoryBook == targetBook;
                    this.categoryDisplay.visible = this.categoryBook == targetBook;
                    if (option == ProductSelectorScrapBookOption.Department && this.departmentBook.pictures.hasItems())
                        return;
                    targetBook.controls.empty();
                    this.categoryNavigation.visible = true;
                    const data = {
                        className: "Solarium.Commercial." + className + ", Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 1,
                        rowCount: 1000,
                        filters: [],
                        sortProperty: "Position, Nombre",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "Nombre", "Color", imagePropName],
                        pageInfo: false
                    };
                    const filters = new Sol.List();
                    if (departmentFilter)
                        filters.add({
                            PropertyName: "Department",
                            FilterValue: departmentFilter,
                            FilterType: "SInteger"
                        });
                    if (this.onlyOnSaleProducts)
                        filters.add({
                            PropertyName: "OnSale",
                            FilterValue: 1,
                            FilterType: "SBoolean"
                        });
                    filters.add({
                        PropertyName: "Discontinued",
                        FilterValue: 0,
                        FilterType: "SBoolean"
                    });
                    data.filters = filters.toArray();
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        for (let row = 0; row < model.Data.length; row++) {
                            const rowData = Sol.List.from(model.Data[row]);
                            if (!departmentFilter && this.onlyEquipments) {
                                const isEquipment = rowData.any(cmp => cmp.Valor == "Equipamentos");
                                if (!isEquipment)
                                    continue;
                            }
                            const code = model.Codes[row];
                            const description = rowData.that(cmp => cmp.Campo == "Nombre").Valor;
                            const color = rowData.that(cmp => cmp.Campo == "Color").Valor;
                            const imageCode = rowData.that(cmp => cmp.Campo == imagePropName).Valor;
                            targetBook.addItem(code, description, color, imageCode);
                        }
                    });
                }
                search() {
                    this.list.filters = [];
                    if (!this.searchField.isEmpty())
                        this.list.filters.push({
                            PropertyName: this.exactMatchCheck.checked ? "GeneralExactFilter" : "GeneralFilter",
                            FilterValue: this.searchField.value,
                            FilterType: ""
                        });
                    this.list.filters.push({
                        PropertyName: "Discontinued",
                        FilterValue: 0,
                        FilterType: "SBoolean"
                    });
                    if (this.onlyEquipments)
                        this.list.filters.push({
                            PropertyName: "ProductClassification",
                            FilterValue: ProductClassification.Equipment,
                            FilterType: "SInteger"
                        });
                    if (this.selectedCategory)
                        this.list.filters.push({
                            PropertyName: "Category",
                            FilterValue: this.selectedCategory,
                            FilterType: "Category"
                        });
                    if (this.onlyOnSaleProducts)
                        this.list.filters.push({
                            PropertyName: "OnSale",
                            FilterValue: true,
                            FilterType: "SBoolean"
                        });
                    this.list.clear();
                    this.list.search({
                        clientID: this.clientCode,
                        currentPage: this.list.currentPage,
                        rowCount: this.list.pageSize,
                        filters: this.list.filters,
                        sortProperty: this.list.orderByProperty,
                        properties: this.list.properties,
                        pageInfo: true
                    });
                }
                selectDepartment(item) {
                    this.departmentBook.visible = false;
                    this.categoryBook.visible = true;
                    this.loadBook(ProductSelectorScrapBookOption.Category, item.code);
                    this.categoryDisplay.text = item.description;
                }
                selectCategory(item) {
                    this.selectedCategory = item.code;
                    this.criteriaArea.clear();
                    this.criteriaArea.options = [{
                            Code: item.code.toString(),
                            Description: item.description,
                            Color: item.color,
                            Checked: true
                        }];
                    this.criteriaArea.loadOptions();
                    this.showSearch();
                    this.search();
                }
                showScrapbook() {
                    this.searchButton.checked = false;
                    this.container.visible = false;
                    this.departmentBook.visible = true;
                    this.loadBook(ProductSelectorScrapBookOption.Department);
                }
                showSearch() {
                    this.searchButton.checked = true;
                    this.categoriesButton.checked = false;
                    this.container.visible = true;
                    this.departmentBook.visible = false;
                    this.categoryBook.visible = false;
                    this.categoryNavigation.visible = false;
                    this.searchField.foco();
                }
            }
            Screens.ProductSelectorScreen = ProductSelectorScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Discounts;
            (function (Discounts) {
                class IProductPromotionModel {
                }
                Discounts.IProductPromotionModel = IProductPromotionModel;
            })(Discounts = Commercial.Discounts || (Commercial.Discounts = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ApprovedCheck extends Sol.Check {
                constructor() {
                    super();
                    this.breakInForm = false;
                    this.css.add("sol_approved_check");
                    this.allowSaveValueAsDefault = false;
                }
            }
            Components.ApprovedCheck = ApprovedCheck;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class QuotationDialogOption extends Sol.Control {
                    constructor(model, showCost, showFinalPrice, showSupplierName) {
                        super();
                        this.conditionField = new Sol.Field();
                        this.warrantyField = new Sol.Field();
                        this.supplierNameField = new Sol.Field();
                        this.supplierStateField = new Sol.Field();
                        this.taxRegimeField = new Sol.Field();
                        this.situationField = new Sol.Field();
                        this.originField = new Sol.Field();
                        this.deliveryField = new Sol.Field();
                        this.deliveryCostField = new Sol.Field();
                        this.costField = new Sol.Field();
                        this.expirationField = new Sol.Field();
                        this.notesField = new Sol.TextField();
                        this.loginUserField = new Sol.Field();
                        this.salePriceField = new Sol.Field();
                        this.approvedCheck = new Web.Components.ApprovedCheck();
                        this.css.add("sol_products_list_ro_area_option");
                        this.approvedCheck.caption = Sol.Environment.resources.approved;
                        this.approvedCheck.checked = model.IsApproved;
                        this.approvedCheck.onClick = () => this.onPriceApproved(model);
                        this.add(this.approvedCheck);
                        const costWrapper = new Sol.FieldWrapper();
                        const costLabel = new Sol.Label();
                        costLabel.text = "Custo:";
                        this.costField.value = model.Price;
                        this.costField.readonly = true;
                        this.costField.textBold = true;
                        costWrapper.add(costLabel);
                        costWrapper.add(this.costField);
                        if (showCost)
                            this.add(costWrapper);
                        var deliveryCostWrapper = new Sol.FieldWrapper();
                        var deliveryCostLabel = new Sol.Label();
                        deliveryCostLabel.text = Sol.Environment.resources.deliveryCost + ":";
                        this.deliveryCostField.value = model.DeliveryCost;
                        this.deliveryCostField.readonly = true;
                        deliveryCostWrapper.add(deliveryCostLabel);
                        deliveryCostWrapper.add(this.deliveryCostField);
                        if (showCost)
                            this.add(deliveryCostWrapper);
                        var supplierNameWrapper = new Sol.FieldWrapper();
                        var supplierNameLabel = new Sol.Label();
                        supplierNameLabel.text = Sol.Environment.resources.supplier + ":";
                        this.supplierNameField.value = model.SupplierName;
                        this.supplierNameField.readonly = true;
                        supplierNameWrapper.add(supplierNameLabel);
                        supplierNameWrapper.add(this.supplierNameField);
                        if (showSupplierName)
                            this.add(supplierNameWrapper);
                        var supplierStateWrapper = new Sol.FieldWrapper();
                        var supplierStateLabel = new Sol.Label();
                        supplierStateLabel.text = Sol.Environment.resources.supplierStateQuotation + ":";
                        this.supplierStateField.value = model.SuppliterState;
                        this.supplierStateField.readonly = true;
                        supplierStateWrapper.add(supplierStateLabel);
                        supplierStateWrapper.add(this.supplierStateField);
                        this.add(supplierStateWrapper);
                        const taxRegimeWrapper = new Sol.FieldWrapper();
                        const taxRegimeLabel = new Sol.Label();
                        taxRegimeLabel.text = "Reg. Trib.:";
                        this.taxRegimeField.value = model.SuppliterTaxRegime;
                        this.taxRegimeField.readonly = true;
                        taxRegimeWrapper.add(taxRegimeLabel);
                        taxRegimeWrapper.add(this.taxRegimeField);
                        this.add(taxRegimeWrapper);
                        var conditionWrapper = new Sol.FieldWrapper();
                        var conditionLabel = new Sol.Label();
                        conditionLabel.text = Sol.Environment.resources.condition_quotation + ":";
                        this.conditionField.value = model.PurchaseCondition;
                        this.conditionField.readonly = true;
                        conditionWrapper.add(conditionLabel);
                        conditionWrapper.add(this.conditionField);
                        this.add(conditionWrapper);
                        var situationWrapper = new Sol.FieldWrapper();
                        var situationLabel = new Sol.Label();
                        situationLabel.text = Sol.Environment.resources.situationQuotation + ":";
                        this.situationField.value = model.ProductSituation;
                        this.situationField.readonly = true;
                        situationWrapper.add(situationLabel);
                        situationWrapper.add(this.situationField);
                        this.add(situationWrapper);
                        var originWrapper = new Sol.FieldWrapper();
                        var originLabel = new Sol.Label();
                        originLabel.text = Sol.Environment.resources.originQuotation + ":";
                        this.originField.value = model.ProductOrigin;
                        this.originField.readonly = true;
                        originWrapper.add(originLabel);
                        originWrapper.add(this.originField);
                        this.add(originWrapper);
                        var warrantyWrapper = new Sol.FieldWrapper();
                        var warrantyLabel = new Sol.Label();
                        warrantyLabel.text = Sol.Environment.resources.warranty_quotation + ":";
                        this.warrantyField.value = model.Warranty;
                        this.warrantyField.readonly = true;
                        warrantyWrapper.add(warrantyLabel);
                        warrantyWrapper.add(this.warrantyField);
                        this.add(warrantyWrapper);
                        var loginUserWrapper = new Sol.FieldWrapper();
                        var loginUserLabel = new Sol.Label();
                        loginUserLabel.text = Sol.Environment.resources.usuario + ":";
                        this.loginUserField.value = model.Username;
                        this.loginUserField.readonly = true;
                        loginUserWrapper.add(loginUserLabel);
                        loginUserWrapper.add(this.loginUserField);
                        this.add(loginUserWrapper);
                        var deliveryWrapper = new Sol.FieldWrapper();
                        var deliveryLabel = new Sol.Label();
                        deliveryLabel.text = Sol.Environment.resources.delivery_quotation + ":";
                        this.deliveryField.value = model.DeliveryTime + " dias";
                        this.deliveryField.readonly = true;
                        deliveryWrapper.add(deliveryLabel);
                        deliveryWrapper.add(this.deliveryField);
                        this.add(deliveryWrapper);
                        var expirationWrapper = new Sol.FieldWrapper();
                        var expirationLabel = new Sol.Label();
                        expirationLabel.text = Sol.Environment.resources.expiration_quotation + ":";
                        this.expirationField.value = model.ExpirationDate;
                        this.expirationField.readonly = true;
                        expirationWrapper.add(expirationLabel);
                        expirationWrapper.add(this.expirationField);
                        this.add(expirationWrapper);
                        const salePriceWrapper = new Sol.FieldWrapper();
                        const salePriceLabel = new Sol.Label();
                        salePriceLabel.text = Sol.Environment.resources.salePrice + ":";
                        this.salePriceField.value = model.FinalPrice;
                        this.salePriceField.readonly = true;
                        this.salePriceField.textBold = true;
                        salePriceWrapper.add(salePriceLabel);
                        salePriceWrapper.add(this.salePriceField);
                        if (showFinalPrice)
                            this.add(salePriceWrapper);
                        const notesLabel = new Sol.Label();
                        notesLabel.text = Sol.Environment.resources.notes + ":";
                        this.notesField.value = model.ValidatorNotes;
                        this.notesField.readonly = true;
                        this.notesField.css.add("sol_texto_large_field");
                        notesLabel.editor = this.notesField;
                        this.add(notesLabel);
                        this.add(this.notesField);
                    }
                }
                Products.QuotationDialogOption = QuotationDialogOption;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                let YesNoEnumeration;
                (function (YesNoEnumeration) {
                    YesNoEnumeration[YesNoEnumeration["NotSet"] = 0] = "NotSet";
                    YesNoEnumeration[YesNoEnumeration["Yes"] = 1] = "Yes";
                    YesNoEnumeration[YesNoEnumeration["No"] = 2] = "No";
                })(YesNoEnumeration = Products.YesNoEnumeration || (Products.YesNoEnumeration = {}));
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class PurchaseInfoDialog extends Sol.DialogBox {
                    constructor(item) {
                        super();
                        this.supplierCombo = new Web.Components.DataCombo();
                        this.deliveryTimeField = new Sol.Field();
                        this.arrivalDateField = new Sol.DateField();
                        this.orderNumberField = new Sol.Field();
                        this.changeButton = new Sol.Button();
                        this.item = item;
                        this.showBlocker = false;
                        this.title = "Informações sobre a compra";
                        this.contentArea.css.add("sol_products_list_ro_area");
                        const supplierWrapper = new Sol.FieldWrapper();
                        const supplierLabel = new Sol.Label();
                        this.supplierCombo.className = "Solarium.Commercial.Supplier, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.supplierCombo.displayProperty = "EntidadRelacionada$Nombre";
                        this.supplierCombo.preFilters = [
                            {
                                FilterType: "SBoolean",
                                FilterValue: true,
                                PropertyName: "VisibleToConsultants"
                            }
                        ];
                        supplierLabel.text = "Fornecedor:";
                        supplierLabel.editor = this.supplierCombo;
                        supplierWrapper.add(supplierLabel);
                        supplierWrapper.add(this.supplierCombo);
                        this.contentArea.add(supplierWrapper);
                        this.supplierCombo.refresh();
                        const deliveryTimeWrapper = new Sol.FieldWrapper();
                        const deliveryTimeLabel = new Sol.Label();
                        deliveryTimeLabel.text = "Prazo de entrega:";
                        deliveryTimeLabel.editor = this.deliveryTimeField;
                        deliveryTimeWrapper.add(deliveryTimeLabel);
                        deliveryTimeWrapper.add(this.deliveryTimeField);
                        this.contentArea.add(deliveryTimeWrapper);
                        const arrivalWrapper = new Sol.FieldWrapper();
                        const arrivalLabel = new Sol.Label();
                        arrivalLabel.text = "Previsão de chegada:";
                        arrivalLabel.editor = this.arrivalDateField;
                        arrivalWrapper.add(arrivalLabel);
                        arrivalWrapper.add(this.arrivalDateField);
                        this.contentArea.add(arrivalWrapper);
                        const orderWrapper = new Sol.FieldWrapper();
                        const orderLabel = new Sol.Label();
                        orderLabel.text = "Nº pedido:";
                        orderLabel.editor = this.orderNumberField;
                        orderWrapper.add(orderLabel);
                        orderWrapper.add(this.orderNumberField);
                        this.contentArea.add(orderWrapper);
                        this.changeButton.text = "OK";
                        this.changeButton.onClick = () => this.updateItem();
                        this.contentArea.add(this.changeButton);
                        this.load();
                    }
                    load() {
                        Web.System.exec("79k8jhkh", "GetPurchaseInfo", { itemID: this.item.code }, model => {
                            this.supplierCombo.selectedCode = this.getItemValue("PurchaseDetails$Supplier") || model.SupplierID;
                            this.deliveryTimeField.value = this.getItemValue("PurchaseDetails$SupplierTime") || model.DeliveryTime;
                            this.arrivalDateField.value = this.getItemValue("PurchaseDetails$ArrivalDate") || model.ArrivalDate;
                            this.orderNumberField.value = this.getItemValue("PurchaseDetails$OrderNumber") || model.OrderNumber;
                        });
                    }
                    updateItem() {
                        this.setItemValue("PurchaseDetails$Supplier", this.supplierCombo.value);
                        this.setItemValue("PurchaseDetails$SupplierTime", this.deliveryTimeField.value);
                        this.setItemValue("PurchaseDetails$ArrivalDate", this.arrivalDateField.value);
                        this.setItemValue("PurchaseDetails$OrderNumber", this.orderNumberField.value);
                        this.onChange();
                    }
                    setItemValue(propertyName, value) {
                        const itemData = this.item.hiddenProperties.that(hp => hp.Campo == propertyName);
                        if (itemData)
                            itemData.Valor = value;
                        else
                            this.item.hiddenProperties.add({ Campo: propertyName, Valor: value });
                    }
                    getItemValue(propertyName) {
                        var _a;
                        return (_a = this.item.hiddenProperties.that(hp => hp.Campo == propertyName)) === null || _a === void 0 ? void 0 : _a.Valor;
                    }
                }
                Products.PurchaseInfoDialog = PurchaseInfoDialog;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class MarginCalculator {
                    constructor(item, companyCode, customerCode) {
                        this.companyCode = companyCode;
                        this.customerCode = customerCode;
                        this.quantity = item.getEditor("Quantity");
                        this.cost = item.getEditor("Cost");
                        this.totalCost = item.getEditor("TotalCost");
                        this.marginPercent = item.getEditor("MarginPercent");
                        this.margin = item.getEditor("Margin");
                        this.price = item.getEditor("Price");
                        this.total = item.getEditor("Total");
                        this.taxes = item.getEditor("Taxes");
                        if (this.taxes) {
                            this.taxes.onRequestCalculation = () => this.calculate(true);
                        }
                        var productData = item.getModelValue("Product");
                        if (productData)
                            this.product = productData.Valor;
                        if (this.quantity)
                            this.quantity.onModified = () => {
                                this.updateTotal();
                                this.updateTotalCost();
                                this.updateMargin();
                                this.updateMarginPercent();
                                if (this.onQuantityChanged)
                                    this.onQuantityChanged();
                            };
                        if (this.cost)
                            this.cost.onChange = () => {
                                this.updateTotal();
                                this.updateTotalCost();
                                this.updateMargin();
                                this.updateMarginPercent();
                            };
                        if (this.marginPercent) {
                            this.marginPercent.value < 0 ? this.marginPercent.css.add("sol_negative_margin") : this.marginPercent.css.remove("sol_negative_margin");
                            this.marginPercent.onModified = () => {
                                this.price.numericValue = this.cost.numericValue + (this.cost.numericValue * (this.marginPercent.value / 100));
                                this.updateTotal();
                                this.updateMargin();
                            };
                        }
                        if (this.margin) {
                            this.margin.numericValue < 0 ? this.margin.css.add("sol_negative_margin") : this.margin.css.remove("sol_negative_margin");
                            this.margin.onChange = () => {
                                if (this.quantity.value == 0)
                                    this.price.numericValue = 0;
                                else
                                    this.price.numericValue = this.cost.numericValue + (this.margin.numericValue / this.quantity.value);
                                this.updateTotal();
                                this.updateMarginPercent();
                            };
                        }
                        if (this.price)
                            this.price.onChange = () => {
                                this.updateTotal();
                                this.updateTotalCost();
                                this.updateMargin();
                                this.updateMarginPercent();
                            };
                        if (this.taxes)
                            this.taxes.onModified = () => {
                                this.updateMargin(false);
                                this.updateMarginPercent();
                            };
                    }
                    calculate(showDialog = false) {
                        var _a;
                        if (!this.taxes)
                            return;
                        var taxCost = ((_a = this.totalCost) === null || _a === void 0 ? void 0 : _a.numericValue) || 0;
                        var taxPrice = this.taxes.visible ? this.total.numericValue : 0;
                        this.taxes.calculate(this.product, taxCost, taxPrice, this.companyCode, this.customerCode, () => {
                            this.updateMargin(false);
                            this.updateMarginPercent();
                            if (this.onTotalsChanged)
                                this.onTotalsChanged();
                            if (showDialog)
                                this.taxes.showDialog();
                        });
                    }
                    updateMargin(calcTaxes = true) {
                        var taxesValue = this.taxes ? this.taxes.decimalValue : 0;
                        if (this.margin) {
                            this.margin.numericValue = ((this.price.numericValue - this.cost.numericValue) * this.quantity.value) - taxesValue;
                            this.margin.numericValue < 0 ? this.margin.css.add("sol_negative_margin") : this.margin.css.remove("sol_negative_margin");
                        }
                        if (this.taxes && this.totalCost && calcTaxes) {
                            var taxCost = this.totalCost.numericValue;
                            var taxPrice = this.total.numericValue;
                            this.taxes.calculate(this.product, taxCost, taxPrice, this.companyCode, this.customerCode, null);
                        }
                    }
                    ;
                    updateTotal() {
                        this.total.numericValue = this.price.numericValue * this.quantity.value;
                        if (this.onTotalsChanged)
                            this.onTotalsChanged();
                    }
                    ;
                    updateTotalCost() {
                        if (this.totalCost)
                            this.totalCost.numericValue = this.cost.numericValue * this.quantity.value;
                    }
                    updateMarginPercent() {
                        if (!this.marginPercent)
                            return;
                        this.marginPercent.value = this.total.numericValue == 0 ? 0 : 100 - (1 - (this.margin.numericValue / this.total.numericValue)) * 100;
                        this.marginPercent.value < 0 ? this.marginPercent.css.add("sol_negative_margin") : this.marginPercent.css.remove("sol_negative_margin");
                    }
                    ;
                }
                Products.MarginCalculator = MarginCalculator;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            let UnitType;
            (function (UnitType) {
                UnitType[UnitType["Product"] = 1] = "Product";
                UnitType[UnitType["Service"] = 2] = "Service";
            })(UnitType = Commercial.UnitType || (Commercial.UnitType = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class QuotationsButton extends Sol.Button {
                    constructor() {
                        super();
                        this.text = Sol.Environment.resources.quotations;
                        this.imageCode = "&#xf080;";
                        this.onClick = () => this.showDialog();
                    }
                    showDialog() {
                        const dialog = new Products.QuotationHistoryDialog();
                        dialog.showSupplier = true;
                        dialog.onClose = () => this.parent.controls.remove(dialog);
                        this.parent.add(dialog);
                        dialog.load(this.code);
                    }
                }
                Products.QuotationsButton = QuotationsButton;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class TotalCalculator extends Sol.CurrencyField {
                    constructor() {
                        super();
                    }
                    updateTotal() {
                        this.numericValue = this.quantityField.numericValue * this.priceField.numericValue;
                    }
                    build() {
                        super.build();
                        this.quantityField = this.container.editors.that(p => p.propertyName == "Quantity");
                        this.priceField = this.container.editors.that(p => p.propertyName == "Price");
                        if (!this.quantityField || !this.priceField)
                            return;
                        this.quantityField.onChange = () => this.updateTotal();
                        this.priceField.onChange = () => this.updateTotal();
                    }
                }
                Products.TotalCalculator = TotalCalculator;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("TotalCalculator", () => new Sol.Web.Commercial.Products.TotalCalculator());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            class QuantityField extends Sol.Control {
                constructor() {
                    super();
                    this.loadDisplay = new Sol.Control("li");
                    this.mainField = new Sol.NumericField();
                    this.nameDisplay = new Sol.Control("li");
                    this.popup = new Sol.Popup();
                    this.resultsDisplay = new Sol.Control("li");
                    this.searchField = new Sol.Field();
                    this.unitField = new Sol.Field();
                    this.unitType = Commercial.UnitType.Product;
                    this.savable = true;
                    this.useWrapper = true;
                    this.css.addMany(["sol_campo", "sol_qty_field"]);
                    this.add(this.mainField);
                    const unitArea = this.addCtr("", "sol_qty_field_unit", "span");
                    this.unitField.maxLength = 3;
                    this.unitField.tip = "Unidade";
                    this.unitField.onClick = () => false;
                    this.unitField.onInput.subscribe(() => this.unitInput());
                    unitArea.onClick = () => {
                        this.popup.visible = !this.popup.visible;
                        if (this.popup.visible) {
                            this.unitInput();
                            this.searchField.foco();
                        }
                    };
                    unitArea.add(this.unitField);
                    this.popup.css.add("sol_qty_field_popup");
                    this.nameDisplay.css.add("sol_qty_field_name");
                    this.popup.add(this.nameDisplay);
                    const searchItem = this.popup.addCtr(null, null, "li");
                    this.searchField.placeHolder = Sol.Environment.resources.typeToSearch;
                    this.searchField.onInput.subscribe(() => this.searchInput());
                    searchItem.add(this.searchField);
                    this.loadDisplay.visible = false;
                    this.loadDisplay.text = Sol.Environment.resources.searching;
                    this.popup.add(this.loadDisplay);
                    this.popup.add(this.resultsDisplay);
                    this.popup.visible = false;
                    this.add(this.popup);
                }
                get unitClassFilter() { return this.unitType == Commercial.UnitType.Product ? "ProductUnit" : "ServiceUnit"; }
                get unitError() { return this._unitError; }
                set unitError(value) {
                    this._unitError = value;
                    if (value)
                        this.unitField.css.add("sol_field_error");
                    else
                        this.unitField.css.remove("sol_field_error");
                }
                get acceptsNegative() { return this.mainField.acceptsNegative; }
                set acceptsNegative(value) { this.mainField.acceptsNegative = true; }
                get numericValue() { return this.mainField.numericValue; }
                set numericValue(v) { this.mainField.numericValue = v; }
                get readonly() { return this._readonly; }
                set readonly(value) {
                    this._readonly = value;
                    this.mainField.readonly = value;
                    this.unitField.readonly = value || this.unitBlocked;
                }
                get onChange() { return this._onChange; }
                set onChange(fn) {
                    this._onChange = fn;
                    setTimeout(() => { this.mainField.onModified = () => fn(this.mainField); }, 300);
                }
                set onModified(fn) {
                    this.mainField.onModified = fn;
                }
                get onSet() { return this.mainField.onSet; }
                set onSet(v) { this.mainField.onSet = v; }
                get onValueModified() { return this.mainField.onValueModified; }
                set onValueModified(v) { this.mainField.onValueModified = v; }
                get unitBlocked() { return this._unitBlocked; }
                set unitBlocked(value) {
                    this._unitBlocked = value;
                    this.unitField.readonly = value;
                    this.searchField.visible = !value;
                }
                get value() {
                    if (this.selectedValue) {
                        this.selectedValue.Quantity = this.numericValue;
                        this.selectedValue.UnitType = this.unitType;
                    }
                    return this.selectedValue;
                }
                set value(v) {
                    this.setUnit(v);
                }
                clear() {
                    this.mainField.clear();
                }
                foco() { this.mainField.foco(); }
                isEmpty() { return this.mainField.isEmpty(); }
                setOne(flag) {
                    if (flag) {
                        this.mainField.value = 1;
                        this.setDefaultUnit();
                    }
                    this.readonly = flag;
                }
                toControl() { return this; }
                validate() {
                    if (this.unitError)
                        return "A unidade do campo " + this.caption + " está incorreta ou não está cadastrada.";
                    if (this.unitField.isEmpty() && this.numericValue > 0)
                        return "Informe a unidade do campo " + this.caption;
                    return null;
                }
                searchInput() {
                    var _a;
                    this.popup.ancho = this.mainField.ancho;
                    this.resultsDisplay.controls.empty();
                    this.loadDisplay.visible = true;
                    (_a = this.ajax) === null || _a === void 0 ? void 0 : _a.abort();
                    const data = {
                        className: `Solarium.Commercial.${this.unitClassFilter}, Solarium.Commercial, Version = 1.0.0.0, Culture=neutral, PublicKeyToken=null`,
                        currentPage: 1,
                        rowCount: 5,
                        filters: [{ FilterType: "SText", FilterValue: this.searchField.value, PropertyName: "AbbreviationWithName" }],
                        sortProperty: "Nombre",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "AbbreviationWithName", "Nombre", "Description", "Decimals"],
                        pageInfo: false
                    };
                    this.ajax = Web.System.exec("i3n48smak", "Search", data, model => {
                        this.loadDisplay.visible = false;
                        for (var i = 0; i < model.Codes.length; i++) {
                            const data = model.Data[i];
                            const dataCollection = Sol.List.from(data);
                            const item = new Sol.Control();
                            item.css.add("sol_qty_field_popup_item");
                            const textValue = dataCollection.that(cmp => cmp.Campo.indexOf("AbbreviationWithName") > -1).Valor;
                            const abbreviation = dataCollection.that(cmp => cmp.Campo.indexOf("Nombre") > -1).Valor;
                            const description = dataCollection.that(cmp => cmp.Campo.indexOf("Description") > -1).Valor;
                            const decimals = dataCollection.that(cmp => cmp.Campo.indexOf("Decimals") > -1).Valor;
                            const unitModel = {
                                UnitID: model.Codes[i],
                                Abbreviation: abbreviation,
                                Name: description,
                                Decimals: decimals,
                                Quantity: null,
                                UnitType: this.unitType
                            };
                            item.text = textValue;
                            item.onClick = () => {
                                this.setUnit(unitModel);
                                this.searchField.clear();
                                this.popup.visible = false;
                            };
                            this.resultsDisplay.add(item);
                        }
                    });
                }
                setDefaultUnit() {
                    this.unitField.value = "Un";
                    this.unitError = false;
                    this.unitInput();
                }
                setUnit(unit) {
                    this.selectedValue = unit;
                    this.unitType = unit.UnitType;
                    this.mainField.decimals = unit.Decimals;
                    if (unit.Quantity)
                        this.mainField.numericValue = unit.Quantity;
                    this.unitField.value = unit.Abbreviation;
                    this.nameDisplay.text = `${unit.Name} (${unit.Abbreviation})`;
                    this.unitError = false;
                }
                unitInput() {
                    if (this.ajax)
                        this.ajax.abort();
                    this.unitError = false;
                    const request = { unit: this.unitField.value, className: this.unitClassFilter };
                    this.ajax = Web.System.exec("79k8jhkh", "FindUnit", request, e => {
                        if (e.Fail)
                            this.unitError = true;
                        else
                            this.setUnit(e.Data);
                        this.nameDisplay.visible = !e.Fail;
                    });
                }
            }
            Commercial.QuantityField = QuantityField;
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("SQuantity", () => new Sol.Web.Commercial.QuantityField());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class BaseItemSelector extends Sol.Control {
                    constructor() {
                        super();
                        this.fileButton = new Sol.Button();
                        this.nameDisplay = new Sol.Control("span");
                        this.partnumberDisplay = new Components.Displays.ColorizedDisplay();
                        this.pnField = new Sol.Field();
                        this.searchButton = new Sol.LensIcon();
                        this.iconDisplay = new Sol.Control("i");
                        this.mainField = new Sol.Control();
                        this.clearButton = new Sol.ClearIcon();
                        this.editButton = new Sol.Button();
                        this.quotationsButton = new Web.Commercial.Products.QuotationsButton();
                        this.onValueModified = new Sol.EventHandler();
                        this.isComplex = true;
                        this.showCatalog = true;
                        this._showEditButton = true;
                        this._showFileButton = true;
                        this.css.add("sol_product_selector");
                        this.initializeMainField();
                        this.initializeSearchButton();
                        this.initializeEditButton();
                        this.initializeFileButton();
                    }
                    get errorState() { return this._errorState; }
                    set errorState(value) {
                        this._errorState = value;
                        value === Sol.EditorErrorState.Error ? this.mainField.css.add("sol_field_error") : this.mainField.css.remove("sol_field_error");
                    }
                    get selectedPartnumber() { return this._selectedPartnumber; }
                    set selectedPartnumber(value) {
                        this._selectedPartnumber = value;
                        this.partnumberDisplay.setValue({ Campo: value, Color: "#3d872d", Valor: null });
                        this.partnumberDisplay.visible = !(!value);
                    }
                    get readonly() { return this._readonly; }
                    set readonly(value) {
                        this._readonly = value;
                        this.searchButton.visible = !value;
                        this.clearButton.visible = !this.isEmpty() && !value;
                    }
                    get selectedName() { return this._selectedName; }
                    set selectedName(value) {
                        this._selectedName = value;
                        this.nameDisplay.text = value;
                    }
                    get showEditButton() { return this._showEditButton; }
                    set showEditButton(value) {
                        this._showEditButton = value;
                        this.editButton.visible = value;
                    }
                    get showFileButton() { return this._showFileButton; }
                    set showFileButton(value) {
                        this._showFileButton = value;
                        this.fileButton.visible = value;
                    }
                    get value() { return this.selectedCode; }
                    set value(v) {
                        if (v > 0) {
                            this.loadItem(v);
                            return;
                        }
                        var valueModel = v;
                        this.selectedCode = valueModel.Valor;
                        this.selectedName = valueModel.Campo;
                        this.selectedPartnumber = valueModel.PartNumber;
                        this.clearButton.visible = !this.isEmpty() && !this.readonly && !this.required;
                        this.editButton.enabled = !this.isEmpty();
                        this.quotationsButton.code = this.selectedCode;
                        this.quotationsButton.enabled = !this.isEmpty();
                        this.configureRowIcon(valueModel.Icon, valueModel.IconTip);
                        this.onValueChanged();
                    }
                    get onLeave() { return this.pnField.onLeave; }
                    set onLeave(v) { this.pnField.onLeave = v; }
                    get onFocus() { return this.pnField.onFocus; }
                    set onFocus(v) { this.pnField.onFocus = v; }
                    clear() {
                        this.selectedCode = null;
                        this.selectedName = "";
                        this.selectedPartnumber = "";
                        this.clearButton.visible = false;
                        this.editButton.enabled = false;
                        this.quotationsButton.enabled = false;
                        this.onValueChanged();
                    }
                    foco() {
                        if (this.configuration && this.configuration.AllowPartNumberInput)
                            this.pnField.foco();
                    }
                    isEmpty() { return !this.selectedCode; }
                    toControl() { return this; }
                    validate() { return null; }
                    build() {
                        var _a;
                        super.build();
                        this.initializeQuotationsButton();
                        this.initializePartNumberField();
                        const showButtonLabels = !this.hideButtonLabels && this.parent.tagName != "td";
                        if (!showButtonLabels) {
                            this.editButton.tip = this.editButton.text;
                            this.editButton.text = "";
                            this.fileButton.tip = this.fileButton.text;
                            this.fileButton.text = "";
                            this.quotationsButton.tip = this.quotationsButton.text;
                            this.quotationsButton.text = "";
                        }
                        this.searchButton.visible = !((_a = this.configuration) === null || _a === void 0 ? void 0 : _a.HideSearchButton) && !this.readonly;
                    }
                    onValueChanged() { }
                    updatePriceField(priceValue) {
                        if (!this.container)
                            return;
                        const priceField = this.container.editors.that(e => e.propertyName == "Price");
                        if (!priceField)
                            return;
                        if (!priceField.numericValue)
                            priceField.numericValue = priceValue;
                        const totalField = this.container.editors.that(e => e.propertyName == "Total");
                        if (totalField && totalField instanceof Web.Commercial.Products.TotalCalculator)
                            totalField.updateTotal();
                        const quantityField = this.container.editors.that(e => e.propertyName == "Quantity");
                        if (quantityField)
                            quantityField.foco();
                    }
                    updateQuantityField(unit) {
                        if (!this.container)
                            return;
                        const quantityField = this.container.editors.that(e => e.propertyName == "Quantity");
                        if (!quantityField || !(quantityField instanceof Web.Commercial.QuantityField))
                            return;
                        quantityField.value = unit;
                        quantityField.unitBlocked = true;
                    }
                    configureRowIcon(icon, tip) {
                        this.iconDisplay.visible = icon != Selectors.ProductIcon.NotSet;
                        if (icon == Selectors.ProductIcon.NotSet)
                            return;
                        const iconState = icon == Selectors.ProductIcon.Ok ? { icon: "&#xf058;", css: "sol_product_selector_state_icon_ok", tip: tip || "Ok" } :
                            icon == Selectors.ProductIcon.Warning ? { icon: "&#xf071;", css: "sol_product_selector_state_icon_warning", tip: tip || "Informações divergentes" } :
                                { icon: "&#xf067;", css: "sol_product_selector_state_icon_new", tip: tip || "Produto novo" };
                        this.iconDisplay.text = iconState.icon;
                        this.iconDisplay.css.addMany(["sol_product_selector_state_icon", iconState.css]);
                        this.iconDisplay.tip = iconState.tip;
                    }
                    detailsSaved(screen) {
                        this.value = screen.datumModel;
                        Web.System.screens.closeCurrentScreen();
                    }
                    edit() {
                        const detailsScreen = new Web.Screens.DetailsScreen();
                        detailsScreen.model = {
                            Actions: null,
                            ClassName: this.className,
                            IsProcess: false,
                            Structure: this.structure,
                            CurrentID: 0
                        };
                        detailsScreen.code = this.selectedCode;
                        detailsScreen.screenCaption = this.selectedName;
                        detailsScreen.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                        detailsScreen.onSaved.subscribe(e => this.detailsSaved(e));
                        detailsScreen.myScreen = Web.System.screens.currentScreen;
                        Web.System.screens.addScreen(detailsScreen);
                        Web.System.screens.showScreen(detailsScreen);
                        detailsScreen.foco();
                        detailsScreen.load(this.value);
                    }
                    initializeMainField() {
                        this.mainField.css.add("sol_campo");
                        this.partnumberDisplay.visible = false;
                        this.mainField.onClick = () => this.foco();
                        this.mainField.add(this.iconDisplay);
                        this.mainField.add(this.partnumberDisplay);
                        this.mainField.add(this.nameDisplay);
                        this.clearButton.text = 'x';
                        this.clearButton.visible = false;
                        this.clearButton.onClick = () => this.clear();
                        this.add(this.mainField);
                        this.add(this.clearButton);
                    }
                    initializeSearchButton() {
                        this.searchButton.onClick = () => this.searchItem();
                        this.add(this.searchButton);
                    }
                    initializeEditButton() {
                        this.editButton.enabled = false;
                        this.editButton.text = Sol.Environment.resources.abrir;
                        this.editButton.imageCode = "&#xf044;";
                        this.editButton.onClick = () => this.edit();
                        this.add(this.editButton);
                    }
                    initializeFileButton() {
                        this.fileButton.text = Sol.Environment.resources.file;
                        this.fileButton.imageCode = "&#xf187;";
                        this.fileButton.onClick = () => Web.System.screens.openScreen("Registro", this.className);
                        this.add(this.fileButton);
                    }
                    initializePartNumberField() {
                        if (!this.configuration || !this.configuration.AllowPartNumberInput)
                            return;
                        this.pnField.disableEnter = true;
                        this.mainField.controls.insert(0, this.pnField);
                        this.pnField.onKeyDown = e => this.pnFieldKeyDown(e);
                    }
                    initializeQuotationsButton() {
                        if (!this.configuration || !this.configuration.ShowQuotationsButton)
                            return;
                        this.quotationsButton.enabled = false;
                        this.add(this.quotationsButton);
                    }
                    pnFieldKeyDown(e) {
                        if (e.key != "Enter")
                            return;
                        const data = {
                            className: this.className,
                            currentPage: 1,
                            rowCount: 1,
                            filters: [{
                                    PropertyName: "PartNumberFilter",
                                    FilterValue: this.pnField.value,
                                    FilterType: "SText"
                                }],
                            sortProperty: "ID",
                            sortOrder: Web.Ordering.ascending,
                            properties: this.propertyList.toArray(),
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", data, model => {
                            if (model.Codes.length == 0)
                                return;
                            this.itemSelected(model.Data[0], model.Codes[0], false);
                        }, null);
                        this.pnField.clear();
                    }
                    loadItem(id) {
                        const data = {
                            className: this.className,
                            currentPage: 1,
                            rowCount: 1,
                            filters: [{
                                    PropertyName: "ID",
                                    FilterValue: id,
                                    FilterType: "SInteger"
                                }],
                            sortProperty: "ID",
                            sortOrder: Web.Ordering.ascending,
                            properties: this.propertyList.toArray(),
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", data, model => {
                            if (model.Codes.length == 0)
                                return;
                            this.itemSelected(model.Data[0], model.Codes[0], false);
                        });
                    }
                }
                Selectors.BaseItemSelector = BaseItemSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class ProductSelector extends Web.Components.Selectors.BaseItemSelector {
                    constructor() {
                        super(...arguments);
                        this.priceMode = Products.ProductsEditorPriceMode.Normal;
                        this.className = "Solarium.Commercial.Product, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.propertyList = Sol.List.from(["ID", "PartNumber", "Nombre", "EffectivePrice", "EffectivePriceData", "EffectivePriceValue", "Category"]);
                    }
                    searchItem() {
                        const screen = new Web.Screens.ProductSelectorScreen();
                        screen.loadDescription = this.propertyList.contains("Description");
                        screen.allowAddNew = this.showFileButton;
                        screen.fileScreenCaption = Sol.Environment.resources.crear;
                        screen.onlyEquipments = this.onlyEquipments;
                        screen.onlyOnSaleProducts = this.onlyOnSaleProducts;
                        screen.showQuotationTools = this.showQuotationTools;
                        screen.showCatalog = this.showCatalog;
                        screen.priceMode = this.priceMode;
                        Web.System.screens.addScreen(screen);
                        Web.System.screens.showScreen(screen);
                        screen.onProductSelected = prods => this.itemSelected(prods.first().data, prods.first().code, true);
                    }
                    itemSelected(data, code, closeScreen) {
                        var _a, _b, _c, _d;
                        const collec = Sol.List.from(data);
                        this.selectedCode = code;
                        this.selectedName = collec.that(d => d.Campo == "Nombre").Valor;
                        this.selectedPartnumber = collec.that(d => d.Campo == "PartNumber").Valor;
                        this.clearButton.visible = !this.readonly;
                        this.editButton.enabled = !this.readonly;
                        this.quotationsButton.code = code;
                        this.quotationsButton.enabled = !this.readonly && this.showQuotationTools;
                        this.updatePriceField(parseFloat(collec.that(d => d.Campo == "EffectivePriceValue").Valor));
                        this.updateQuantityField({
                            UnitID: (_a = collec.that(d => d.Campo == "PurchaseUnit")) === null || _a === void 0 ? void 0 : _a.Valor,
                            Abbreviation: (_b = collec.that(d => d.Campo == "PurchaseUnit$Nombre")) === null || _b === void 0 ? void 0 : _b.Valor,
                            Decimals: (_c = collec.that(d => d.Campo == "PurchaseUnit$Decimals")) === null || _c === void 0 ? void 0 : _c.Valor,
                            Name: (_d = collec.that(d => d.Campo == "PurchaseUnit$Description")) === null || _d === void 0 ? void 0 : _d.Valor,
                            UnitType: Commercial.UnitType.Product
                        });
                        this.onValueChanged();
                        if (closeScreen)
                            Web.System.screens.closeCurrentScreen();
                        this.onValueModified.invoke();
                    }
                }
                Products.ProductSelector = ProductSelector;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("Product", model => {
    const productSelector = new Sol.Web.Commercial.Products.ProductSelector();
    productSelector.structure = model.Structure;
    productSelector.configuration = model.Configuration;
    return productSelector;
});
Sol.Web.Editors.registerFilter("Product", model => {
    const productSelector = new Sol.Web.Commercial.Products.ProductSelector();
    productSelector.hideButtonLabels = true;
    productSelector.showEditButton = false;
    productSelector.showFileButton = false;
    model.Settings = null;
    return productSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class QuotationDialog extends Sol.DialogBox {
                    constructor(item) {
                        super();
                        this.CLASS_TYPE = "Solarium.Commercial.PriceQuotation, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.quotationIdWrapper = new Sol.FieldWrapper();
                        this.quotationStatusWrapper = new Sol.FieldWrapper();
                        this.noQuotationMessage = new Sol.Control();
                        this.changeButton = new Sol.Button();
                        this.openQuotationButton = new Sol.Button();
                        this.printPdfButton = new Sol.Button();
                        this.quotationIdField = new Sol.Field();
                        this.quotationStatus = new Sol.Control("span");
                        this.productSelector = new Products.ProductSelector();
                        this.descriptionField = new Sol.Field();
                        this.equipmentField = new Sol.Field();
                        this.purposeCombo = new Web.Components.DataCombo();
                        this.configCombo = new Sol.Combo();
                        this.tagField = new Sol.Field();
                        this.notesField = new Sol.TextField();
                        this.optionsArea = new Sol.Control();
                        this.item = item;
                        this.showBlocker = false;
                        this.title = Sol.Environment.resources.quotation_information;
                        this.estilos.agregar("width", "95%");
                        this.contentArea.css.add("sol_products_list_ro_area");
                        const id = this.item.code;
                        var productIdWrapper = new Sol.FieldWrapper();
                        var productIdLabel = new Sol.Label();
                        productIdLabel.text = Sol.Environment.resources.product_category;
                        productIdLabel.editor = this.productSelector;
                        this.productSelector.onlyOnSaleProducts = true;
                        this.productSelector.showFileButton = false;
                        this.productSelector.showEditButton = false;
                        productIdWrapper.add(productIdLabel);
                        productIdWrapper.add(this.productSelector);
                        this.contentArea.add(productIdWrapper);
                        var productDescWrapper = new Sol.FieldWrapper();
                        var productDescLabel = new Sol.Label();
                        productDescLabel.text = Sol.Environment.resources.description + ":";
                        productDescLabel.editor = this.descriptionField;
                        this.descriptionField.css.add("sol_texto_large_field");
                        productDescWrapper.add(productDescLabel);
                        productDescWrapper.add(this.descriptionField);
                        this.contentArea.add(productDescWrapper);
                        var equipmentWrapper = new Sol.FieldWrapper();
                        var equipmentLabel = new Sol.Label();
                        equipmentLabel.text = Sol.Environment.resources.equipment + ":";
                        equipmentLabel.editor = this.equipmentField;
                        equipmentWrapper.add(equipmentLabel);
                        equipmentWrapper.add(this.equipmentField);
                        this.contentArea.add(equipmentWrapper);
                        var purposeWrapper = new Sol.FieldWrapper();
                        var purposeLabel = new Sol.Label();
                        purposeLabel.text = Sol.Environment.resources.propose + ':';
                        purposeLabel.editor = this.purposeCombo;
                        this.purposeCombo.className = "Solarium.Commercial.QuotationPurpose, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.purposeCombo.refresh();
                        purposeWrapper.add(purposeLabel);
                        purposeWrapper.add(this.purposeCombo);
                        this.contentArea.add(purposeWrapper);
                        var originalConfigWrapper = new Sol.FieldWrapper();
                        var originalConfigLabel = new Sol.Label();
                        originalConfigLabel.text = Sol.Environment.resources.original_configuration;
                        originalConfigLabel.editor = this.configCombo;
                        this.configCombo.loadOptions([
                            { Code: "0", Description: "Não Especificado" },
                            { Code: "1", Description: "Original" },
                            { Code: "2", Description: "Compatível" }
                        ]);
                        originalConfigWrapper.add(originalConfigLabel);
                        originalConfigWrapper.add(this.configCombo);
                        this.contentArea.add(originalConfigWrapper);
                        var tagWrapper = new Sol.FieldWrapper();
                        var tagLabel = new Sol.Label();
                        tagLabel.text = Sol.Environment.resources.tag_serial + ':';
                        tagLabel.editor = this.tagField;
                        tagWrapper.add(tagLabel);
                        tagWrapper.add(this.tagField);
                        this.contentArea.add(tagWrapper);
                        var notesLabel = new Sol.Label();
                        notesLabel.text = Sol.Environment.resources.notes + ':';
                        notesLabel.editor = this.notesField;
                        this.notesField.css.add("sol_texto_large_field");
                        this.contentArea.add(notesLabel);
                        this.contentArea.add(this.notesField);
                        this.changeButton.text = "Atualizar";
                        this.changeButton.visible = false;
                        this.changeButton.onClick = () => this.updateItem();
                        this.contentArea.add(this.changeButton);
                        const quotationLabel = new Sol.Label();
                        quotationLabel.text = Sol.Environment.resources.quotations;
                        quotationLabel.css.add("sol_detalles_complex_title");
                        quotationLabel.estilos.agregar("font-size", "110%");
                        this.contentArea.add(quotationLabel);
                        const quotationIdLabel = new Sol.Label();
                        quotationIdLabel.text = Sol.Environment.resources.quotationId;
                        this.quotationIdField.readonly = true;
                        this.quotationIdField.textBold = true;
                        quotationIdLabel.editor = this.quotationIdField;
                        this.quotationIdWrapper.add(quotationIdLabel);
                        this.quotationIdWrapper.add(this.quotationIdField);
                        this.contentArea.add(this.quotationIdWrapper);
                        const quotationStatusLabel = new Sol.Label();
                        quotationStatusLabel.text = Sol.Environment.resources.product_quotation_status;
                        quotationStatusLabel.estilos.agregar("margin-bottom", "5px");
                        this.quotationStatus.css.add("sol_colorized_display");
                        this.quotationStatus.estilos.agregar("color", "#fff");
                        this.quotationStatusWrapper.add(quotationStatusLabel);
                        this.quotationStatusWrapper.add(this.quotationStatus);
                        this.contentArea.add(this.quotationStatusWrapper);
                        this.noQuotationMessage.text = "Produto ainda não enviado para cotação";
                        this.noQuotationMessage.visible = false;
                        this.contentArea.add(this.noQuotationMessage);
                        this.contentArea.add(this.optionsArea);
                        this.openQuotationButton.text = "Abrir cotação";
                        this.openQuotationButton.imageCode = '&#xf044;';
                        this.openQuotationButton.tip = 'Abrir Cotação';
                        this.openQuotationButton.visible = false;
                        this.openQuotationButton.onClick = () => this.editQuotation(this.QuotationID);
                        this.contentArea.add(this.openQuotationButton);
                        this.printPdfButton.visible = false;
                        this.printPdfButton.imageCode = '&#xf1c1;';
                        this.printPdfButton.text = "Versão para impressão";
                        this.printPdfButton.tip = "Imprimir a cotação";
                        this.printPdfButton.onClick = () => this.downloadPDF(this.QuotationID);
                        this.contentArea.add(this.printPdfButton);
                        this.loadQuotation();
                    }
                    downloadPDF(ID) {
                        Web.System.exec("79k8jhkh", "PrintPriceQuotation", { quotationID: ID }, e => {
                            if (e.Fail)
                                alert(e.ErrorMessage);
                            else
                                window.open(e.FileLink, "_blank");
                        });
                    }
                    editQuotation(quotationID) { Web.System.edit(this.CLASS_TYPE, quotationID); }
                    loadQuotation() {
                        Web.System.exec("79k8jhkh", "GetQuotationInfo", { itemID: this.item.code }, model => {
                            this.QuotationID = Number(model.QuotationID);
                            this.quotationIdWrapper.visible = !!model.QuotationID;
                            this.quotationStatusWrapper.visible = !!model.QuotationID;
                            this.quotationStatus.estilos.definir("background-color", model.QuotationStatusColor);
                            this.noQuotationMessage.visible = !model.QuotationID;
                            this.changeButton.visible = !model.QuotationID;
                            this.openQuotationButton.visible = !!model.QuotationID;
                            this.printPdfButton.visible = !!model.QuotationID;
                            this.quotationIdField.value = model.QuotationID;
                            this.quotationStatus.text = model.QuotationStatus;
                            this.productSelector.value = this.getItemValue("UnknownProductDetails$Product") || model.ProductID;
                            this.descriptionField.value = this.getItemValue("UnknownProductDetails$Description") || model.ProductDescription;
                            this.equipmentField.value = this.getItemValue("UnknownProductDetails$Equipment") || model.Equipment;
                            this.purposeCombo.selectedCode = this.getItemValue("UnknownProductDetails$Purpose") || model.PurposeID.toString();
                            this.configCombo.value = this.getItemValue("UnknownProductDetails$QuotationOriginalConfiguration") || model.OriginalConfiguration;
                            this.tagField.value = this.getItemValue("UnknownProductDetails$QuotationProductTag") || model.Tag;
                            this.notesField.value = this.getItemValue("UnknownProductDetails$QuotationNotesProduct") || model.Notes;
                            this.productSelector.readonly = !!model.QuotationID;
                            this.descriptionField.readonly = !!model.QuotationID;
                            this.equipmentField.readonly = !!model.QuotationID;
                            this.purposeCombo.readonly = !!model.QuotationID;
                            this.configCombo.readonly = !!model.QuotationID;
                            this.tagField.readonly = !!model.QuotationID;
                            this.notesField.readonly = !!model.QuotationID;
                            const options = Sol.List.from(model.Options);
                            this.optionsArea.controls.empty();
                            if (options.hasItems())
                                this.optionsArea.addCtr("Valores sugeridos:", "sol_detalles_complex_title", "label");
                            this.optionsArea.addMany(options.select(o => {
                                const option = new Products.QuotationDialogOption(o, this.showCost, this.showFinalPrice, this.showSupplierName);
                                option.onPriceApproved = m => this.onPriceApproved(m);
                                return option;
                            }));
                        });
                    }
                    updateItem() {
                        this.setItemValue("UnknownProductDetails$Product", this.productSelector.value);
                        this.setItemValue("UnknownProductDetails$Description", this.descriptionField.value);
                        this.setItemValue("UnknownProductDetails$Equipment", this.equipmentField.value);
                        this.setItemValue("UnknownProductDetails$Purpose", this.purposeCombo.value);
                        this.setItemValue("UnknownProductDetails$QuotationOriginalConfiguration", this.configCombo.value);
                        this.setItemValue("UnknownProductDetails$QuotationProductTag", this.tagField.value);
                        this.setItemValue("UnknownProductDetails$QuotationNotesProduct", this.notesField.value);
                        this.onChange();
                    }
                    setItemValue(propertyName, value) {
                        const itemData = this.item.hiddenProperties.that(hp => hp.Campo == propertyName);
                        if (itemData)
                            itemData.Valor = value;
                        else
                            this.item.hiddenProperties.add({ Campo: propertyName, Valor: value });
                    }
                    getItemValue(propertyName) {
                        var _a;
                        return (_a = this.item.hiddenProperties.that(hp => hp.Campo == propertyName)) === null || _a === void 0 ? void 0 : _a.Valor;
                    }
                }
                Products.QuotationDialog = QuotationDialog;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class ProductsList extends Web.Components.ListView {
                    constructor() {
                        super();
                        this.currentCompany = Sol.Environment.credential.empresa;
                        this.showCost = true;
                        this.showQuotationTools = false;
                        this.showIntegerQuantity = false;
                        this.showDescription = true;
                        this.showWarranty = false;
                        this.showExternalCodeField = false;
                        this.showExternalCodeField2 = false;
                        this._showTaxesField = false;
                        this.className = "Solarium.Commercial.Product, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.showImage = true;
                        this.onInstantiateItem = i => this.instantiateItem(i);
                    }
                    get showTaxesField() { return this._showTaxesField; }
                    set showTaxesField(value) {
                        this._showTaxesField = value;
                        this.items.forEach(item => item.getEditor("Taxes").toControl().parent.visible = value);
                    }
                    get totalMargin() {
                        if (!this.showCost)
                            return 0;
                        return this.items.sum(item => item.getEditor("Margin").numericValue || 0);
                    }
                    get totalCost() {
                        if (!this.showCost)
                            return 0;
                        return this.items.sum(item => item.getEditor("Cost").numericValue * item.getEditor("Quantity").value);
                    }
                    get total() {
                        return this.items.sum(item => item.getEditor("Total").numericValue);
                    }
                    addItemFromData(data, code) {
                        var _a;
                        let dataList = Sol.List.from(data);
                        if (!dataList.any(d => d.Campo == "Product$Nombre")) {
                            let productData = dataList.that(d => d.Campo == "Product");
                            dataList.add({ Campo: "Product$Nombre", Valor: (_a = productData === null || productData === void 0 ? void 0 : productData.Valor) === null || _a === void 0 ? void 0 : _a.Campo });
                        }
                        let item = super.addItemFromData(dataList.toArray(), code);
                        let calculator = item.data;
                        setTimeout(() => calculator.updateTotal(), 500);
                        return item;
                    }
                    refreshCalcs(companyCode) {
                        this.currentCompany = companyCode;
                        this.items.forEach(item => {
                            const calculator = item.data;
                            calculator.customerCode = this.currentCustomer;
                            calculator.companyCode = companyCode;
                            calculator.calculate();
                        });
                    }
                    build() {
                        super.build();
                        this.configuration = Sol.List.from([
                            {
                                loadable: true,
                                property: "Product$ThumbnailImage",
                                position: Web.Components.ListViewFieldPosition.Image
                            },
                            {
                                loadable: false,
                                property: "DeleteCommand",
                                defaultText: Sol.Environment.resources.eliminar,
                                position: Web.Components.ListViewFieldPosition.Right,
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                cssClass: "sol_products_list_remove"
                            },
                            {
                                loadable: false,
                                property: "EditCommand",
                                defaultText: this.editProductCaption,
                                position: Web.Components.ListViewFieldPosition.Right,
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                cssClass: "sol_products_list_edit"
                            },
                            {
                                loadable: true,
                                property: "Product$Brand$Logo",
                                position: Web.Components.ListViewFieldPosition.Left,
                                hiddenWhenEmpty: true,
                                editor: {
                                    DataType: "Imagen",
                                    PropertyName: "Product$Brand$Logo",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: true,
                                    ReadOnly: true,
                                    Settings: { imageWidth: 28, imageHeight: 28 }
                                }
                            },
                            {
                                loadable: true,
                                property: "Product$PartNumber",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                cssClass: "sol_products_list_part_number",
                                hiddenWhenEmpty: true
                            },
                            {
                                loadable: true,
                                property: "Product$Nombre",
                                priority: Web.Components.ListViewFieldPriority.High,
                                position: Web.Components.ListViewFieldPosition.Left,
                                defaultText: "Mercadoria não especificada"
                            },
                            {
                                loadable: true,
                                property: "Product",
                                hidden: true
                            },
                            {
                                loadable: true,
                                property: "IsFixedPrice",
                                hidden: true
                            },
                            {
                                loadable: false,
                                disabled: !this.showDescription,
                                property: "Description",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                lineBreak: true,
                                cssClass: "sol_products_list_description",
                                editor: {
                                    DataType: "SLargeText",
                                    PropertyName: "Description",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: 2,
                                    ReadOnly: this.readonly,
                                    MaxLength: 250,
                                    Tip: Sol.Environment.resources.product_description
                                }
                            },
                            {
                                loadable: false,
                                property: "Quantity",
                                lineBreak: true,
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_quantity,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SNumber",
                                    PropertyName: "Quantity",
                                    Title: Sol.Environment.resources.product_quantity,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: 3,
                                    MaxLength: 10,
                                    ReadOnly: this.readonly,
                                    Width: 80
                                }
                            },
                            {
                                loadable: true,
                                disabled: !this.showCost,
                                property: "Cost",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_cost,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SMoney",
                                    PropertyName: "Cost",
                                    Title: Sol.Environment.resources.product_cost,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: this.unitPriceDecimals > 2 ? this.unitPriceDecimals : 2,
                                    ReadOnly: this.readonly
                                }
                            },
                            {
                                loadable: true,
                                disabled: !this.showCost,
                                property: "TotalCost",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_cost_total,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SMoney",
                                    PropertyName: "TotalCost",
                                    Title: Sol.Environment.resources.product_cost_total,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: 2,
                                    ReadOnly: true
                                }
                            },
                            {
                                loadable: true,
                                property: "Price",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_price,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SMoney",
                                    PropertyName: "Price",
                                    Title: Sol.Environment.resources.product_price,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: this.unitPriceDecimals > 2 ? this.unitPriceDecimals : 2,
                                    ReadOnly: this.readonly
                                }
                            },
                            {
                                loadable: false,
                                property: "Taxes",
                                disabled: !this.showTaxesField,
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.taxes,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "Taxes",
                                    PropertyName: "Taxes",
                                    Title: Sol.Environment.resources.taxes,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: true,
                                    ReadOnly: true
                                }
                            },
                            {
                                loadable: false,
                                property: "Total",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_total,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SMoney",
                                    PropertyName: "Total",
                                    Title: Sol.Environment.resources.product_total,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: 2,
                                    ReadOnly: true
                                }
                            },
                            {
                                loadable: false,
                                disabled: !this.showCost,
                                property: "MarginPercent",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_margin + " (%)",
                                editor: {
                                    AllowChangeCurrency: false,
                                    AcceptsNegative: true,
                                    DataType: "SPercent",
                                    PropertyName: "MarginPercent",
                                    Title: Sol.Environment.resources.product_margin,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: 2,
                                    ReadOnly: this.readonly
                                }
                            },
                            {
                                loadable: false,
                                disabled: !this.showCost,
                                property: "Margin",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_margin_real,
                                editor: {
                                    AllowChangeCurrency: false,
                                    AcceptsNegative: true,
                                    DataType: "SMoney",
                                    PropertyName: "Margin",
                                    Title: Sol.Environment.resources.product_margin_real,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: 2,
                                    ReadOnly: this.readonly
                                }
                            },
                            {
                                loadable: false,
                                disabled: !this.showWarranty,
                                property: "Warranty",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_warranty,
                                editor: {
                                    DataType: "SText",
                                    PropertyName: "Warranty",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    ReadOnly: this.readonly,
                                    MaxLength: 30,
                                    TItle: Sol.Environment.resources.product_warranty
                                }
                            },
                            {
                                loadable: false,
                                disabled: !this.showIntegerQuantity,
                                lineBreak: true,
                                property: "Quantity",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.product_quantity,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SInteger",
                                    PropertyName: "Quantity",
                                    Title: Sol.Environment.resources.product_quantity,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    MaxLength: 10,
                                    ReadOnly: this.readonly,
                                    Width: 80,
                                    DefaultValue: 1
                                }
                            },
                            {
                                loadable: false,
                                property: "ExternalCode",
                                disabled: !this.showExternalCodeField,
                                lineBreak: !this.showExternalCodeField2,
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: this.externalCodeFieldCaption,
                                editor: {
                                    DataType: "SInteger",
                                    PropertyName: "ExternalCode",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    ReadOnly: false,
                                    Title: this.externalCodeFieldCaption
                                }
                            },
                            {
                                loadable: false,
                                property: "ExternalCode2",
                                disabled: !this.showExternalCodeField2,
                                lineBreak: true,
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: this.externalCodeFieldCaption2,
                                editor: {
                                    DataType: "SInteger",
                                    PropertyName: "ExternalCode2",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    ReadOnly: false,
                                    Title: this.externalCodeFieldCaption2
                                }
                            },
                            {
                                loadable: true,
                                disabled: !this.showQuotationTools,
                                property: "CreateQuotation",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                lineBreak: true,
                                editor: {
                                    DataType: "SBoolean",
                                    PropertyName: "CreateQuotation",
                                    Title: this.quotationLabel,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    ReadOnly: false
                                }
                            },
                            {
                                loadable: false,
                                disabled: !this.showQuotationTools,
                                property: "PurchasingStatus",
                                lineBreak: true,
                                Title: Sol.Environment.resources.product_quotation_status,
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left
                            },
                            {
                                loadable: false,
                                disabled: !this.showQuotationTools,
                                property: "QuotationInformation",
                                cssClass: "sol_products_list_ro_button",
                                defaultText: "Informações da Cotação",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left
                            },
                            {
                                loadable: false,
                                disabled: !this.showPurchaseInfo,
                                property: "PurchaseInformation",
                                cssClass: "sol_products_list_ro_button",
                                defaultText: "Informações sobre a Compra",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left
                            },
                            {
                                loadable: true,
                                property: "UnknownProductDetails",
                                hidden: true
                            }
                        ]);
                    }
                    calculateTaxes(item) {
                        var calculator = item.data;
                        calculator.calculate();
                    }
                    configureDeleteItem(item) {
                        const deleteCommand = item.getDisplay("DeleteCommand");
                        deleteCommand.onClick = () => {
                            this.removeItem(item);
                            if (this.onTotalsChanged)
                                this.onTotalsChanged();
                            if (this.onDelete)
                                this.onDelete();
                        };
                    }
                    configureEditItem(item) {
                        let editCommand = item.getDisplay("EditCommand");
                        editCommand.visible = this.allowEditProduct;
                        editCommand.onClick = () => {
                            let productID = item.getModelValue("Product").Valor;
                            let callback = (scr) => {
                                scr.closingAlertEnabled = false;
                                scr.onSaved.subscribe(() => {
                                    var _a;
                                    let partNumber = (_a = scr.getEditor("PartNumber")) === null || _a === void 0 ? void 0 : _a.value;
                                    let name = scr.getEditor("Nombre").value;
                                    let pnDisplay = item.getDisplay("Product$PartNumber");
                                    if (pnDisplay)
                                        pnDisplay.text = partNumber;
                                    item.getDisplay("Product$Nombre").text = name;
                                });
                            };
                            Web.System.edit("1573542248", productID, callback);
                        };
                    }
                    configurePriceCalculations(item) {
                        const calculator = new Products.MarginCalculator(item, this.currentCompany, this.currentCustomer);
                        calculator.onTotalsChanged = () => this.onTotalsChanged();
                        calculator.onQuantityChanged = () => { if (this.onQuantityChanged)
                            this.onQuantityChanged(); };
                        item.data = calculator;
                        const taxesEditor = item.getEditor("Taxes");
                        if (taxesEditor)
                            taxesEditor.toControl().parent.visible = this.showTaxesField;
                    }
                    configurePurchasingTools(item) {
                        const purchasingStatusModel = item.getModelValue("PurchasingStatus");
                        const quotationId = purchasingStatusModel === null || purchasingStatusModel === void 0 ? void 0 : purchasingStatusModel.Valor;
                        const unknownID = item.getModelValue("UnknownProductDetails");
                        const deleteButton = item.getDisplay("DeleteCommand");
                        quotationId ? deleteButton.visible = false : deleteButton.visible = true;
                        const quotationCheck = item.getEditor("CreateQuotation");
                        if (quotationCheck)
                            quotationCheck.visible = !quotationId;
                        const quotationInfo = item.getDisplay("QuotationInformation");
                        if (quotationInfo) {
                            quotationInfo.visible = !!quotationId || !!unknownID;
                            quotationInfo.onClick = () => this.openQuotationDialog(item);
                        }
                        const purchaseInfo = item.getDisplay("PurchaseInformation");
                        if (purchaseInfo)
                            purchaseInfo.onClick = () => this.openPurchaseDialog(item);
                    }
                    configurePriceField(item) {
                        var fixedPrice = item.getModelValue("IsFixedPrice");
                        var price = item.getEditor("Price");
                        price.readonly = fixedPrice || this.readonly;
                    }
                    configureQuantityField(item) {
                        let decimals = item.getModelValue("Product$ProductUnit$Decimals") || 0;
                        let qtyField = item.getEditor("Quantity");
                        qtyField.decimals = decimals;
                    }
                    getItemExtraData(item) {
                        var result = new Sol.List();
                        if (item["quote"])
                            result.addMany(item["quote"]);
                        return result.toArray();
                    }
                    instantiateItem(item) {
                        item.onGettingExtraData = i => this.getItemExtraData(i);
                        this.configureDeleteItem(item);
                        this.configureEditItem(item);
                        this.configurePurchasingTools(item);
                        this.configurePriceCalculations(item);
                        this.configureQuantityField(item);
                        this.configurePriceField(item);
                    }
                    openPurchaseDialog(item) {
                        const purchaseDialog = new Products.PurchaseInfoDialog(item);
                        purchaseDialog.onChange = () => this.controls.remove(purchaseDialog);
                        this.add(purchaseDialog);
                    }
                    openQuotationDialog(item) {
                        const quotationDialog = new Products.QuotationDialog(item);
                        quotationDialog.showCost = this.showCost;
                        quotationDialog.showFinalPrice = this.showFinalPrice;
                        quotationDialog.showSupplierName = this.showSupplierName;
                        quotationDialog.onChange = () => this.controls.remove(quotationDialog);
                        quotationDialog.onPriceApproved = m => this.approvePrice(item, m, quotationDialog);
                        this.add(quotationDialog);
                    }
                    approvePrice(item, priceInfo, dialog) {
                        Web.System.exec("79k8jhkh", "ApproveSupplierQuotation", { itemID: item.code, priceID: priceInfo.SupplierQuotationID });
                        this.controls.remove(dialog);
                        const costField = item.getEditor("Cost");
                        const salePriceField = item.getEditor("Price");
                        if (costField) {
                            costField.numericValue = priceInfo.NumericPrice;
                            costField.onChange();
                        }
                        salePriceField.numericValue = priceInfo.NumericFinalPrice;
                        salePriceField.onChange();
                    }
                }
                Products.ProductsList = ProductsList;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class UnknownProductDialog extends Sol.DialogBox {
                    constructor() {
                        super(...arguments);
                        this.productSelector = new Products.ProductSelector();
                        this.configCombo = new Sol.Combo();
                        this.equipmentField = new Sol.Field();
                        this.purposeCombo = new Sol.Combo();
                        this.tagField = new Sol.Field();
                        this.descriptionField = new Sol.TextField();
                        this.notesField = new Sol.TextField();
                        this.quantityField = new Sol.NumericField();
                        this.filesUpload = new Web.Components.Uploads.Upload();
                        this.showProductFiend = false;
                        this.errorMessage = new Sol.ScreenMessage();
                    }
                    build() {
                        super.build();
                        this.showBlocker = false;
                        this.css.add("sol_products_editor_unknown_dialog");
                        this.title = Sol.Environment.resources.product_unknown;
                        this.contentArea.css.add("sol_products_editor_dialog");
                        this.contentArea.add(this.errorMessage);
                        this.errorMessage.visible = false;
                        const productLabel = new Sol.Label();
                        productLabel.text = Sol.Environment.resources.product + ':';
                        productLabel.editor = this.productSelector;
                        this.productSelector.myLabel = productLabel;
                        this.productSelector.required = this.showProductFiend;
                        this.productSelector.onlyOnSaleProducts = true;
                        this.productSelector.showFileButton = false;
                        this.productSelector.showEditButton = false;
                        if (this.showProductFiend) {
                            this.contentArea.add(productLabel);
                            this.contentArea.add(this.productSelector);
                        }
                        const templateLabel = new Sol.Label();
                        templateLabel.text = Sol.Environment.resources.description + ':';
                        templateLabel.editor = this.descriptionField;
                        this.contentArea.add(templateLabel);
                        this.descriptionField.myLabel = templateLabel;
                        this.descriptionField.required = true;
                        this.contentArea.add(this.descriptionField);
                        const quantityLabel = new Sol.Label();
                        quantityLabel.text = Sol.Environment.resources.product_quantity + ':';
                        quantityLabel.editor = this.quantityField;
                        this.contentArea.add(quantityLabel);
                        this.quantityField.required = true;
                        this.contentArea.add(this.quantityField);
                        const equipmentLabel = new Sol.Label();
                        equipmentLabel.text = Sol.Environment.resources.equipment;
                        equipmentLabel.editor = this.equipmentField;
                        this.contentArea.add(equipmentLabel);
                        this.equipmentField.myLabel = equipmentLabel;
                        this.equipmentField.required = true;
                        this.equipmentField.maxLength = 50;
                        this.contentArea.add(this.equipmentField);
                        const purposeLabel = new Sol.Label();
                        purposeLabel.text = Sol.Environment.resources.propose + ':';
                        purposeLabel.editor = this.purposeCombo;
                        this.contentArea.add(purposeLabel);
                        this.purposeCombo.myLabel = purposeLabel;
                        this.purposeCombo.required = true;
                        this.contentArea.add(this.purposeCombo);
                        const configLabel = new Sol.Label();
                        configLabel.text = Sol.Environment.resources.original_configuration;
                        configLabel.editor = this.configCombo;
                        this.contentArea.add(configLabel);
                        this.configCombo.required = true;
                        this.configCombo.myLabel = configLabel;
                        this.contentArea.add(this.configCombo);
                        const tagLabel = new Sol.Label();
                        tagLabel.text = Sol.Environment.resources.tag_serial + ':';
                        tagLabel.editor = this.tagField;
                        this.contentArea.add(tagLabel);
                        this.tagField.maxLength = 21;
                        this.tagField.myLabel = tagLabel;
                        this.tagField.required = this.showProductFiend;
                        this.contentArea.add(this.tagField);
                        const notesLabel = new Sol.Label();
                        notesLabel.text = Sol.Environment.resources.notes + ':';
                        notesLabel.editor = this.tagField;
                        this.contentArea.add(notesLabel);
                        this.notesField.myLabel = notesLabel;
                        this.contentArea.add(this.notesField);
                        const productFileLabel = new Sol.Label();
                        productFileLabel.text = Sol.Environment.resources.product_file + ':';
                        productFileLabel.editor = this.filesUpload;
                        this.contentArea.add(productFileLabel);
                        this.contentArea.add(this.filesUpload);
                        var footer = new Sol.Control();
                        footer.css.add("sol_products_editor_dialog_footer");
                        const cancelButton = new Sol.Button();
                        cancelButton.text = Sol.Environment.resources.cancelar;
                        cancelButton.onClick = () => this.visible = false;
                        footer.add(cancelButton);
                        const okButton = new Sol.Button();
                        okButton.text = "OK";
                        okButton.onClick = () => {
                            if (!this.onValidate())
                                return false;
                            this.onDone(this);
                        };
                        footer.add(okButton);
                        this.contentArea.add(footer);
                    }
                    clear() {
                        this.productSelector.clear();
                        this.descriptionField.clear();
                        this.purposeCombo.clear();
                        this.configCombo.clear();
                        this.equipmentField.clear();
                        this.tagField.clear();
                        this.notesField.clear();
                        this.filesUpload.clear();
                    }
                    onValidate() {
                        this.errorMessage.visible = false;
                        return this.validateField(this.productSelector) &&
                            this.validateField(this.descriptionField) &&
                            this.validateField(this.equipmentField) &&
                            this.validateField(this.purposeCombo) &&
                            this.validateField(this.configCombo) &&
                            this.validateField(this.tagField);
                    }
                    validateField(editor) {
                        if (editor.required && editor.isEmpty()) {
                            this.errorMessage.text = Sol.Environment.resources.empty_field + editor.myLabel.text;
                            this.errorMessage.visible = true;
                            return false;
                        }
                        return true;
                    }
                }
                Products.UnknownProductDialog = UnknownProductDialog;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class ProductsEditor extends Sol.Control {
                    constructor() {
                        super();
                        this.addButton = new Sol.Button();
                        this.list = new Products.ProductsList();
                        this.dialog = new Products.UnknownProductDialog();
                        this.totalQuantityText = new Sol.Control("span");
                        this.partNumberSearchIcon = new Sol.Control("span");
                        this.partNumberSearchField = new Sol.Field();
                        this.priceMode = Products.ProductsEditorPriceMode.Normal;
                        this.propertyList = ["ID", "Nombre", "EffectiveCostData", "EffectivePriceData", "MainPicture", "Category", "IsFixedPrice", "PartNumber", "ProductUnit$Decimals", "Brand$Logo", "Brand$Logo$Extensión", "Brand$Logo$Identificador", "Brand$Logo$Nombre", "Brand$Logo$Tamaño"];
                        this.isComplex = true;
                        this.onProductAdded = new Sol.EventHandler();
                        this.onProductDeleted = new Sol.EventHandler();
                        this.onQuantityChanged = new Sol.EventHandler();
                        this.css.add("sol_products_editor");
                    }
                    get cost() { return this.list.totalCost; }
                    isEmpty() { return this.list.isEmpty(); }
                    get isMultiCompany() { return true; }
                    get isSummable() { return true; }
                    get margin() { return this.list.totalMargin; }
                    get readonly() { return this._readonly; }
                    set readonly(value) {
                        this._readonly = value;
                        this.list.readonly = value;
                        this.addButton.visible = !value;
                        this.partNumberSearchIcon.visible = !value;
                        this.partNumberSearchField.visible = !value;
                    }
                    get productDiscountData() {
                        return this.list.items.select(p => {
                            var model = new Commercial.Discounts.IProductPromotionModel();
                            var productID = p.getModelValue("Product");
                            model.ProductID = (productID === null || productID === void 0 ? void 0 : productID.Valor) || productID;
                            model.Quantity = p.getEditor("Quantity").value;
                            model.Price = p.getEditor("Price").numericValue;
                            return model;
                        }).toArray();
                    }
                    get total() { return this.list.total; }
                    get value() { return this.list.values; }
                    set value(v) {
                        this.list.values = v;
                        setTimeout(() => {
                            if (this.onTotalsChanged)
                                this.onTotalsChanged();
                            this.updateTotalQuantity();
                        }, 500);
                    }
                    changeCompany(companyCode) { this.list.refreshCalcs(companyCode); }
                    foco() { }
                    resetIDs() { this.list.resetIDs(); }
                    setCompany(c) { }
                    toControl() { return this; }
                    validate() { return null; }
                    build() {
                        super.build();
                        this.subscriteSaleTypeChanges();
                        this.subscribeCustomerChanges();
                        this.initializeDialog();
                        this.initializeList();
                        this.initializeAddButton();
                        this.initializeAddUnknown();
                        this.initializePartNumberSearch(this.configuration.PartNumberPlaceholder);
                        this.initializeStatusBar();
                        this.onlyOnSaleProducts = this.configuration.OnlyOnSaleProducts;
                    }
                    addProducts(products) {
                        let filters = [{ PropertyName: "IDsFilter", FilterValue: products.select(p => p.code).toArray(), FilterType: null }];
                        let req = this.getRequest(filters);
                        this.searchAndLoad(req, products);
                    }
                    addProduct(partnumber) {
                        let filters = [{ PropertyName: "PartNumberFilter", FilterValue: partnumber, FilterType: "SText" }];
                        let req = this.getRequest(filters);
                        this.searchAndLoad(req);
                    }
                    getCustomerCode() {
                        var _a;
                        return ((_a = this.container.editors.that(edt => edt.propertyName == "Destinatario")) === null || _a === void 0 ? void 0 : _a.selectedCode) || 0;
                    }
                    getRequest(filters) {
                        return {
                            className: this.list.className,
                            currentPage: 0,
                            rowCount: 0,
                            filters: filters,
                            sortProperty: "Nombre",
                            sortOrder: Web.Ordering.ascending,
                            properties: this.propertyList,
                            pageInfo: false
                        };
                    }
                    initializeAddButton() {
                        this.addButton.text = Sol.Environment.resources.anadir_item;
                        this.addButton.css.add("sol_products_editor_addButton");
                        this.addButton.imageCode = '&#xf187;';
                        this.addButton.atributos.agregar("accesskey", "a");
                        this.addButton.tip = "Alt+A";
                        this.addButton.onClick = () => this.selectProduct();
                        this.add(this.addButton);
                    }
                    initializeAddUnknown() {
                        if (!this.configuration.AllowUnknowProducts)
                            return;
                        let addUnknownButton = new Sol.Button();
                        addUnknownButton.text = Sol.Environment.resources.product_unknown;
                        addUnknownButton.imageCode = '&#xf128;';
                        addUnknownButton.onClick = () => {
                            this.dialog.clear();
                            this.dialog.visible = true;
                        };
                        this.add(addUnknownButton);
                    }
                    initializeDialog() {
                        this.dialog.visible = false;
                        this.dialog.purposeCombo.loadOptions(this.configuration.PurposeOptions);
                        this.dialog.configCombo.loadOptions(this.configuration.OriginalConfigOptions);
                        this.dialog.showProductFiend = this.configuration.ShowProductFiendInUnknowProductDialog;
                        this.add(this.dialog);
                        this.dialog.onDone = () => {
                            var itemData = [{ Campo: "Description", Valor: this.dialog.descriptionField.value },
                                { Campo: "CreateQuotation", Valor: true },
                                { Campo: "Quantity", Valor: this.dialog.quantityField.value }];
                            var itemAdded = this.list.addItemFromData(itemData, 0);
                            itemAdded["quote"] = [{ Campo: "UnknownProductDetails$Product", Valor: this.dialog.productSelector.selectedCode },
                                { Campo: "UnknownProductDetails$Description", Valor: this.dialog.descriptionField.value },
                                { Campo: "UnknownProductDetails$Purpose", Valor: this.dialog.purposeCombo.selectedCode },
                                { Campo: "UnknownProductDetails$Equipment", Valor: this.dialog.equipmentField.value },
                                { Campo: "UnknownProductDetails$QuotationOriginalConfiguration", Valor: this.dialog.configCombo.value },
                                { Campo: "UnknownProductDetails$QuotationNotesProduct", Valor: this.dialog.notesField.value },
                                { Campo: "UnknownProductDetails$QuotationProductTag", Valor: this.dialog.tagField.value },
                                { Campo: "UnknownProductDetails$UnknownProductFiles", Valor: this.dialog.filesUpload.value }];
                            this.dialog.visible = false;
                        };
                    }
                    initializeList() {
                        this.list.itemPropertyName = "Product";
                        this.list.allowEditProduct = this.configuration.AllowAddNew;
                        this.list.editProductCaption = this.configuration.EditProductCaption;
                        this.list.showTaxesField = this.configuration.HasTaxesModule;
                        this.list.showDescription = this.configuration.ShowDescriptionField;
                        this.list.showWarranty = this.configuration.ShowWarrantyField;
                        this.list.showExternalCodeField = this.configuration.ShowExternalCodeField;
                        this.list.externalCodeFieldCaption = this.configuration.ExternalCodeFieldCaption;
                        this.list.showExternalCodeField2 = this.configuration.ShowExternalCodeField2;
                        this.list.externalCodeFieldCaption2 = this.configuration.ExternalCodeFieldCaption2;
                        this.list.showCost = this.configuration.ShowCost;
                        this.list.unitPriceDecimals = this.configuration.UnitPriceDecimals;
                        this.list.showQuotationTools = this.configuration.ShowQuotationTools;
                        this.list.quotationLabel = this.configuration.QuotationLabel;
                        this.list.showPurchaseInfo = this.configuration.ShowPurchaseInfoAboutSaleItem;
                        this.list.showFinalPrice = this.configuration.ShowQuotationFinalPrice;
                        this.list.showSupplierName = this.configuration.ShowSupplierName;
                        this.list.onTotalsChanged = () => { if (this.onTotalsChanged)
                            this.onTotalsChanged(); };
                        this.list.onDelete = () => this.onProductDeleted.invoke();
                        this.list.onQuantityChanged = () => {
                            this.updateTotalQuantity();
                            this.onQuantityChanged.invoke();
                        };
                        this.add(this.list);
                    }
                    initializePartNumberSearch(caption) {
                        this.partNumberSearchIcon.css.add("sol_products_editor_pn_search_icon");
                        this.partNumberSearchIcon.text = "&#xf02a;";
                        this.add(this.partNumberSearchIcon);
                        this.partNumberSearchField.css.add("sol_products_editor_pn_search_field");
                        this.partNumberSearchField.placeHolder = "Adicionar por " + caption.toLowerCase() + "...";
                        this.partNumberSearchField.onKeyDown = e => this.searchProductByPartNumber(e);
                        this.partNumberSearchField.disableEnter = true;
                        this.add(this.partNumberSearchField);
                    }
                    initializeStatusBar() {
                        const bar = new Sol.Control();
                        bar.css.add("sol_products_editor_bar");
                        const totalQuantityTitle = new Sol.Label();
                        totalQuantityTitle.text = Sol.Environment.resources.totalQuantity + ":";
                        bar.add(totalQuantityTitle);
                        this.totalQuantityText.text = "0";
                        bar.add(this.totalQuantityText);
                        this.add(bar);
                    }
                    searchAndLoad(req, products = null) {
                        Web.System.exec("i3n48smak", "Search", req, model => {
                            var _a, _b, _c;
                            if (!((_a = model.Data) === null || _a === void 0 ? void 0 : _a.length)) {
                                alert("Produto não encontrado.");
                                return;
                            }
                            let priceField = this.priceMode == Products.ProductsEditorPriceMode.Cost ? "EffectiveCostData" : "EffectivePriceData";
                            var product;
                            var code;
                            var price;
                            for (var i = 0; i < model.Data.length; i++) {
                                product = Sol.List.from(model.Data[i]);
                                code = product.that(d => d.Campo == "ID").Valor;
                                price = ((_b = products === null || products === void 0 ? void 0 : products.that(p => p.code == code)) === null || _b === void 0 ? void 0 : _b.price) || product.that(d => d.Campo == priceField).Valor;
                                let item = [
                                    { Campo: "Product", Valor: code },
                                    { Campo: "Quantity", Valor: ((_c = products === null || products === void 0 ? void 0 : products.that(p => p.code == code)) === null || _c === void 0 ? void 0 : _c.quantity) || 1 },
                                    { Campo: "Product$ProductUnit$Decimals", Valor: product.that(d => d.Campo == "ProductUnit$Decimals").Valor },
                                    { Campo: "Product$Nombre", Valor: product.that(d => d.Campo == "Nombre").Valor },
                                    { Campo: "Product$Category", Valor: product.that(d => d.Campo == "Category").Valor },
                                    { Campo: "Product$MainPicture", Valor: product.that(d => d.Campo == "MainPicture").Valor },
                                    { Campo: "Price", Valor: price },
                                    { Campo: "Total", Valor: price },
                                    { Campo: "Cost", Valor: product.that(d => d.Campo == "EffectiveCostData").Valor },
                                    { Campo: "TotalCost", Valor: product.that(d => d.Campo == "EffectiveCostData").Valor },
                                    { Campo: "Product$PartNumber", Valor: product.that(d => d.Campo == "PartNumber").Valor },
                                    { Campo: "Product$Brand$Logo", Valor: product.that(d => d.Campo == "Brand$Logo").Valor },
                                    { Campo: "IsFixedPrice", Valor: product.that(d => d.Campo == "IsFixedPrice").Valor }
                                ];
                                const listItem = this.list.addItemFromData(item, 0);
                                const quantityEditor = listItem.getEditor("Quantity");
                                if (quantityEditor) {
                                    const calculator = listItem.data;
                                    setTimeout(() => calculator.calculate(), 400);
                                    if (this.onTotalsChanged)
                                        this.onTotalsChanged();
                                    setTimeout(() => this.updateTotalQuantity(), 400);
                                }
                            }
                            this.onProductAdded.invoke();
                        });
                    }
                    searchProductByPartNumber(e) {
                        if (!(e.which == 13 || e.key === "Enter"))
                            return true;
                        this.addProduct(this.partNumberSearchField.textValue);
                        this.partNumberSearchField.clear();
                        this.partNumberSearchField.foco();
                        return false;
                    }
                    selectProduct() {
                        const selectorScreen = new Web.Screens.ProductSelectorScreen();
                        selectorScreen.showQuotationTools = this.configuration.ShowQuotationTools;
                        selectorScreen.showGroupCompanyStockTool = this.configuration.ShowGroupCompanyStockTool;
                        selectorScreen.showCost = this.configuration.ShowCost;
                        selectorScreen.allowAddNew = this.configuration.AllowAddNew;
                        selectorScreen.fileScreenCaption = this.configuration.FileScreenCaption;
                        selectorScreen.onlyOnSaleProducts = this.configuration.OnlyOnSaleProducts;
                        selectorScreen.multipleSelection = this.configuration.MultipleProductSelection;
                        if (this.configuration.OpenProductSelectionInCategories)
                            selectorScreen.startView = Web.Screens.ProductScreenViewMode.Category;
                        let saleOperationCombo = this.container.getEditor("SaleOperation");
                        this.priceMode = (saleOperationCombo === null || saleOperationCombo === void 0 ? void 0 : saleOperationCombo.selectedCode) == '3' ? Products.ProductsEditorPriceMode.Cost : Products.ProductsEditorPriceMode.Normal;
                        selectorScreen.priceMode = this.priceMode;
                        let clientSelector = this.container.getEditor("Destinatario");
                        selectorScreen.clientCode = clientSelector === null || clientSelector === void 0 ? void 0 : clientSelector.selectedCode;
                        Web.System.screens.addScreen(selectorScreen);
                        Web.System.screens.showScreen(selectorScreen);
                        selectorScreen.focus();
                        selectorScreen.onProductSelected = products => {
                            this.addProducts(products);
                            Web.System.screens.closeCurrentScreen();
                        };
                    }
                    subscriteSaleTypeChanges() {
                        const saleTypeSelect = this.container.editors.that(edt => edt.propertyName == "BillingType");
                        if (!saleTypeSelect)
                            return;
                        saleTypeSelect.onChange.subscribe(() => this.saleTypeChanged());
                        saleTypeSelect.onSet.subscribe(() => this.saleTypeChanged());
                    }
                    subscribeCustomerChanges() {
                        const customerSelector = this.container.editors.that(edt => edt.propertyName == "Destinatario");
                        if (customerSelector) {
                            customerSelector.onItemSelected = () => this.customerChanged();
                            customerSelector.onValueSet = () => this.customerChanged();
                        }
                    }
                    customerChanged() {
                        this.list.currentCustomer = this.getCustomerCode();
                        this.list.refreshCalcs(this.list.currentCompany);
                    }
                    saleTypeChanged() {
                        const saleTypeSelect = this.container.editors.that(edt => edt.propertyName == "BillingType");
                        this.list.showTaxesField = this.configuration.HasTaxesModule && saleTypeSelect.selectedCode == 1;
                        this.list.refreshCalcs(this.list.currentCompany);
                    }
                    updateTotalQuantity() {
                        const total = this.list.items.sum(i => i.getEditor("Quantity").value);
                        this.totalQuantityText.text = total.toString();
                    }
                    clear() { }
                }
                Products.ProductsEditor = ProductsEditor;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ProductsEditor", model => {
    var productsEditor = new Sol.Web.Commercial.Products.ProductsEditor();
    productsEditor.configuration = model.Configuration;
    return productsEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class BankAccountCombo extends Components.DataCombo {
                refresh(callback = null) {
                    this.controls.empty();
                    this.filters.empty();
                    if (this.sourcePropertyName) {
                        const screen = Web.System.screens.currentScreen;
                        const selector = screen.getEditor(this.sourcePropertyName);
                        if (!(selector === null || selector === void 0 ? void 0 : selector.selectedCode))
                            return;
                        this.filters.add({
                            FilterType: "",
                            PropertyName: "RelationFilter",
                            FilterValue: selector.selectedCode
                        });
                    }
                    super.refresh(callback);
                }
            }
            Components.BankAccountCombo = BankAccountCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class InstallmentsEditor extends Components.DataView {
                constructor() {
                    super();
                    this.css.add("sol_installments_editor");
                    this.showSearchBox = false;
                    this.fixedRows = false;
                    this.showChecks = false;
                    this.isComplex = false;
                    this.readonly = true;
                    this.onRowCreated = row => this.configureRow(row);
                }
                configureRow(row) {
                    const modeCombo = row.getEditor("PaymentMode");
                    const daysEditor = row.getEditor("Days");
                    const dueDateEditor = row.getEditor("DueDate");
                    const cardCompanyCombo = row.getEditor("PaymentCardCompany");
                    const bankCombo = row.getEditor("BankAccount");
                    const amountEditor = row.getEditor("Amount");
                    modeCombo.onChange = () => {
                        const selectedMode = parseInt(modeCombo.selectedCode);
                        if (cardCompanyCombo)
                            cardCompanyCombo.visible = Sol.List.from([7, 8, 10]).contains(selectedMode);
                        if (cardCompanyCombo && !cardCompanyCombo.visible)
                            cardCompanyCombo.selectedCode = "0";
                        if (this.myEditor.isCashSale(selectedMode)) {
                            daysEditor.numericValue = 0;
                            daysEditor.onChange();
                        }
                        if (bankCombo)
                            bankCombo.visible = this.myEditor.isBankOperation(selectedMode);
                    };
                    daysEditor.onChange = () => dueDateEditor.dateValue = this.myEditor.baseDate.addDays(daysEditor.numericValue);
                    amountEditor.onChange = () => {
                        const rowIndex = this.rows.indice(row);
                        if (rowIndex == this.rows.count - 1)
                            return;
                        const amountSet = this.rows.take(rowIndex + 1).sum(r => r.getEditor("Amount").numericValue);
                        const remainingInstallments = this.rows.count - rowIndex - 1;
                        const remaingValue = this.myEditor.remaining - amountSet;
                        this.rows.skip(rowIndex + 1).forEach(r => r.getEditor("Amount").numericValue = remaingValue / remainingInstallments);
                    };
                }
            }
            Components.InstallmentsEditor = InstallmentsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class BankInfoDisplayItem extends Sol.Control {
                constructor(label) {
                    super();
                    this.labelControl = new Sol.Label();
                    this.contentControl = new Sol.Control("span");
                    this.labelControl.text = label + ':';
                    this.add(this.labelControl);
                    this.add(this.contentControl);
                }
                get content() { return this.contentControl.text; }
                set content(value) { this.contentControl.text = value; }
            }
            Components.BankInfoDisplayItem = BankInfoDisplayItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class BankInfoDisplay extends Sol.Control {
                constructor() {
                    super();
                    this.bankItem = new Components.BankInfoDisplayItem(Sol.Environment.resources.bank);
                    this.pixItem = new Components.BankInfoDisplayItem("Chave Pix");
                    this.agencyItem = new Components.BankInfoDisplayItem(Sol.Environment.resources.agency);
                    this.accountItem = new Components.BankInfoDisplayItem(Sol.Environment.resources.account);
                    this.isComplex = false;
                    this.css.add("sol_info_display sol_bank_info_display");
                    const title = new Sol.Control("h5");
                    title.text = Sol.Environment.resources.bank_info;
                    this.controls.addMany([title, this.bankItem, this.pixItem, this.agencyItem, this.accountItem]);
                }
                clear() { }
                foco() { }
                isEmpty() { return false; }
                loadInfo(code, mode) {
                    Web.System.exec("7djdsplq", "GetBankInfo", { code: code }, e => this.updateDisplay(e, mode));
                }
                toControl() { return this; }
                validate() { return null; }
                updateDisplay(e, mode) {
                    this.visible = !e.Fail;
                    this.bankItem.content = e.BankName;
                    this.pixItem.content = e.PixKey;
                    this.agencyItem.content = e.Branch;
                    this.accountItem.content = e.Account;
                    this.pixItem.visible = mode == Components.PaymentMode.PIX;
                    this.agencyItem.visible = mode != Components.PaymentMode.PIX;
                    this.accountItem.visible = mode != Components.PaymentMode.PIX;
                }
            }
            Components.BankInfoDisplay = BankInfoDisplay;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PaymentEditor extends Components.DetailsEditor {
                constructor() {
                    super();
                    this.financialTemplateCombo = new Components.DataCombo();
                    this.billingDateEnabled = true;
                    this.blockWhenBillingDateIsSet = true;
                    this.defaultInstallmentDays = 7;
                    this.css.add("sol_payments_editor");
                    this.details.enableTotalCalculation = false;
                    this.details.onBuildComplete = () => this.configureFields();
                    this.details.onFormLoaded.subscribe(() => this.configureFinancialTemplateVisibility());
                }
                get advanceEditor() { return this.getEditor("Advance"); }
                get discount() { return this.screen.getEditor("Discount"); }
                get creditField() { return this.screen.getEditor("Credit"); }
                get isForwardSale() { return !this.isCashSale(this.paymentMode); }
                get modeCombo() { return this.getEditor("PaymentMode"); }
                get financialDisplay() { return this.getEditor("ShowFinancialScreen"); }
                get cardCompanyCombo() { return this.getEditor("PaymentCardCompany"); }
                get paymentTypeEditor() { return this.getEditor("PaymentType"); }
                get remainingBalanceEditor() { return this.getEditor("RemainingBalance"); }
                get screen() { return Web.System.screens.currentDetails; }
                get timeInDaysEditor() { return this.getEditor("TimeInDays"); }
                get totalEditor() { return this.details.getEditor("Total"); }
                get bankAccountEditor() { return this.getEditor("BankAccount"); }
                get installmentsTable() { return this.getEditor("Installments"); }
                get bankAccountInfo() { return this.details.getEditor("BankInfoDisplay"); }
                get billingDateEditor() { return this.getEditor("BillingDate"); }
                get isBilled() { return this.paymentTypeEditor.selectedType != Components.PaymentType.notSet && !this.billingDateEditor.isEmpty(); }
                get isTotalSubscriber() { return true; }
                get paymentMode() { return this.modeCombo.selectedCode; }
                get paymentType() { return this.paymentTypeEditor.selectedCode; }
                get baseDate() { return this.billingDateEditor.isEmpty() ? new Date() : this.billingDateEditor.dateValue; }
                get remaining() {
                    var total = this.totalEditor.numericValue;
                    if (this.advanceEditor)
                        total -= this.advanceEditor.numericValue;
                    var creditField = this.screen.getEditor("Credit");
                    if (creditField)
                        total -= creditField.numericValue;
                    return total;
                }
                calculateInstallments() {
                    var _a;
                    if (Web.System.screens.currentScreen instanceof Web.Screens.DetailsScreen &&
                        Web.System.screens.currentScreen.isLoading)
                        return;
                    const credit = ((_a = this.creditField) === null || _a === void 0 ? void 0 : _a.numericValue) || 0;
                    if (credit)
                        this.paymentTypeEditor.setSelectedIndex(Components.PaymentType.installments);
                    if (this.paymentType != Components.PaymentType.installments)
                        return;
                    const installmentsCountEditor = this.details.getEditor("InstallmentsCount");
                    const installmentsTable = this.details.getEditor("Installments");
                    var installmentCount = installmentsCountEditor.numericValue;
                    var days = this.calculateDays(installmentCount);
                    var installments = [];
                    if (installmentCount) {
                        for (var i = 0; i < installmentCount; i++)
                            installments.push(Number((this.remaining / installmentCount).toFixed(2)));
                        const currentDays = installmentsTable.getColumnValues("Days").select(d => parseInt(d));
                        if (currentDays.count == installmentCount)
                            days = currentDays;
                        const installmentsSum = Sol.List.from(installments).sum(n => n);
                        if (installmentsSum != this.remaining)
                            installments[installmentCount - 1] += this.remaining - installmentsSum;
                    }
                    const items = new Sol.List();
                    if (credit)
                        items.add([
                            { Campo: "ID", Valor: 0 },
                            { Campo: "PaymentMode", Valor: Components.PaymentMode.creditAmount },
                            { Campo: "PaymentCardCompany", Valor: null },
                            { Campo: "BankAccount", Valor: null },
                            { Campo: "Amount", Valor: "BRL" + credit },
                            { Campo: "Days", Valor: 0 },
                            { Campo: "DueDate", Valor: this.baseDate.formatear() }
                        ]);
                    items.addMany(Sol.List.range(1, installmentCount)
                        .select(i => {
                        var _a, _b;
                        return [
                            { Campo: "ID", Valor: 0 },
                            { Campo: "PaymentMode", Valor: this.modeCombo.value },
                            { Campo: "PaymentCardCompany", Valor: (_a = this.cardCompanyCombo) === null || _a === void 0 ? void 0 : _a.value },
                            { Campo: "BankAccount", Valor: (_b = this.bankAccountEditor) === null || _b === void 0 ? void 0 : _b.value },
                            { Campo: "Amount", Valor: "BRL" + installments[i - 1] },
                            { Campo: "Days", Valor: days.item(i - 1) },
                            { Campo: "DueDate", Valor: this.baseDate.addDays(days.item(i - 1)).formatear() }
                        ];
                    }));
                    installmentsTable.value = items.toArray();
                }
                isCashSale(mode) {
                    return Sol.List.from([2, 7, 8, 9, 10]).contains(mode);
                }
                isBankOperation(mode) {
                    return Sol.List.from([Components.PaymentMode.PIX, Components.PaymentMode.transfer, Components.PaymentMode.deposit, Components.PaymentMode.bankSlip]).contains(mode);
                }
                onTotalPublished(message) {
                    var totalEditor = this.details.getEditor("Total");
                    if (totalEditor.numericValue.toFixed(2) == message.total.toFixed(2))
                        return;
                    totalEditor.numericValue = message.total;
                    this.updateRemainingValue();
                    this.calculateInstallments();
                }
                showBankInfo(code) {
                    if (!this.bankAccountEditor)
                        return;
                    this.bankAccountInfo.visible = !this.bankAccountEditor.isEmpty() && this.paymentType != Components.PaymentType.notSet;
                    if (this.bankAccountInfo.visible)
                        this.bankAccountInfo.loadInfo(code, this.paymentMode);
                }
                configureFields() {
                    this.configureBillingDateField();
                    this.configureDiscountCalculation();
                    this.configureBankAccountField();
                    this.configureRemainingBalanceField();
                    this.configureInstallments();
                    this.configureFinancialTemplateCombo();
                    this.configureMainTotalInput();
                    this.totalEditor.savable = true;
                }
                configureMainTotalInput() {
                    var _a;
                    const mainTotal = Web.System.screens.currentDetails.getEditor("Total");
                    (_a = mainTotal === null || mainTotal === void 0 ? void 0 : mainTotal.onValueModified) === null || _a === void 0 ? void 0 : _a.subscribe(() => this.onTotalPublished({ total: mainTotal.numericValue, margin: 0 }));
                }
                configureRemainingBalanceField() {
                    this.advanceEditor.onChange = () => {
                        this.updateRemainingValue();
                        this.calculateInstallments();
                    };
                }
                configureBillingDateField() {
                    this.billingDateEditor.readonly = !this.billingDateEnabled;
                    this.billingDateEditor.onValueChanged = () => this.configureTimeInDaysField();
                    this.billingDateEditor.onChange = () => {
                        var _a;
                        (_a = this.timeInDaysEditor) === null || _a === void 0 ? void 0 : _a.onChange();
                        this.calculateInstallments();
                    };
                }
                configureBankAccountField() {
                    var _a;
                    this.bankAccountInfo.visible = false;
                    if (!this.bankAccountEditor)
                        return;
                    this.bankAccountEditor.sourcePropertyName = (_a = this.configuration) === null || _a === void 0 ? void 0 : _a.BankAccountSourceProperty;
                    this.bankAccountEditor.onChange = () => {
                        this.showBankInfo(parseInt(this.bankAccountEditor.selectedCode));
                        this.installmentsTable.rows.forEach(row => row.getEditor("BankAccount").value = this.bankAccountEditor.value);
                    };
                }
                setValue(value) {
                    super.setValue(value);
                    this.updateRemainingValue();
                    this.readonly = this.blockWhenBillingDateIsSet && !this.billingDateEditor.isEmpty();
                    if (this.bankAccountEditor)
                        setTimeout(() => this.showBankInfo(parseInt(this.bankAccountEditor.selectedCode)), 500);
                    if (this.financialDisplay)
                        this.financialDisplay.visible = this.paymentType != Components.PaymentType.notSet && !this.billingDateEditor.isEmpty();
                }
                calculateDays(installmentCount) {
                    var forwardSaleFactor = this.isForwardSale ? 1 : 0;
                    return Sol.List.range(1, installmentCount).select(i => i * this.defaultInstallmentDays * forwardSaleFactor);
                }
                configureDiscountCalculation() {
                    if (!this.discount)
                        return;
                    this.modeCombo.onValueModified.subscribe(() => this.discount.getDiscounts());
                    this.paymentTypeEditor.onChange.subscribe(() => this.discount.getDiscounts());
                }
                configureInstallments() {
                    if (this.configuration && this.configuration.InstallmentDays)
                        this.defaultInstallmentDays = this.configuration.InstallmentDays;
                    const installmentsCountEditor = this.details.getEditor("InstallmentsCount");
                    installmentsCountEditor.onChange = () => this.calculateInstallments();
                    this.installmentsTable.myEditor = this;
                    this.installmentsTable.setColumnReadonly("DueDate", false);
                    this.installmentsTable.onAddingItem = () => {
                        installmentsCountEditor.numericValue++;
                        this.calculateInstallments();
                    };
                    this.installmentsTable.onDeletingRow = () => {
                        installmentsCountEditor.numericValue--;
                        this.calculateInstallments();
                    };
                    this.modeCombo.onValueModified.subscribe(() => this.paymentModeChanged());
                    if (this.cardCompanyCombo)
                        this.cardCompanyCombo.onChange = () => this.installmentsTable.rows.forEach(row => row.getEditor("PaymentCardCompany").value = this.cardCompanyCombo.value);
                }
                configureTimeInDaysField() {
                    this.details.getEditor("TimeInDays").readonly = this.billingDateEditor.value && this.billingDateEditor.readonly;
                }
                configureFinancialTemplateCombo() {
                    if (this.configuration && this.configuration.TemplateMode)
                        return;
                    const financialTemplateWrapper = new Sol.FieldWrapper();
                    const financialTemplateLabel = new Sol.Label();
                    financialTemplateLabel.text = Sol.Environment.resources.financial_template;
                    this.financialTemplateCombo.className = "Solarium.Financial.FinancialTemplate, Solarium.Financial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.financialTemplateCombo.preFilters = [{ PropertyName: "Active", FilterType: "SBoolean", FilterValue: 1 }];
                    financialTemplateWrapper.add(financialTemplateLabel);
                    financialTemplateWrapper.add(this.financialTemplateCombo);
                    this.details.controls.insert(0, financialTemplateWrapper);
                    financialTemplateWrapper.visible = false;
                    this.financialTemplateCombo.onChange = () => this.loadFinancialTemplate();
                    this.financialTemplateCombo.onUpdated = () => this.configureFinancialTemplateVisibility();
                    this.financialTemplateCombo.refresh();
                }
                configureFinancialTemplateVisibility() {
                    this.financialTemplateCombo.parent.visible = this.financialTemplateCombo.items.count > 1 && !this.billingDateEditor.dateValue;
                }
                loadFinancialTemplate() {
                    const code = typeof this.financialTemplateCombo.selectedItem.code === "string" ?
                        parseInt(this.financialTemplateCombo.selectedItem.code) : this.financialTemplateCombo.selectedItem.code;
                    if (!code)
                        return;
                    Web.System.exec("79k77hjdsh", "LoadFinancialTemplate", {
                        credential: Sol.Environment.credential.export(),
                        code: code
                    }, e => {
                        if (!e)
                            return;
                        var data = Sol.List.from(e);
                        data.that(i => i.Campo == "Total").Valor = this.details.getEditor("Total").value;
                        this.value = data.toArray();
                        if (data.that(i => i.Campo == "InstallmentsCount").Valor > 0) {
                            this.calculateInstallments();
                        }
                        this.paymentTypeEditor.onChange.invoke();
                    });
                }
                paymentModeChanged() {
                    const hasDaysSet = this.installmentsTable.rows.sum(row => row.getEditor("Days").numericValue) > 0;
                    const needRecalculateDays = hasDaysSet != this.isForwardSale;
                    const days = this.calculateDays(this.installmentsTable.rows.count).toArray();
                    var index = 0;
                    this.installmentsTable.rows.forEach(row => {
                        const selectedMode = this.paymentMode;
                        row.getEditor("PaymentMode").selectedCode = selectedMode.toString();
                        if (row.getEditor("PaymentCardCompany"))
                            row.getEditor("PaymentCardCompany").visible = Sol.List.from([7, 8, 10]).contains(selectedMode);
                        row.getEditor("BankAccount").visible = Sol.List.from([9, 6, 4, 5]).contains(selectedMode);
                        if (needRecalculateDays) {
                            const daysEditor = row.getEditor("Days");
                            daysEditor.numericValue = days[index++];
                            daysEditor.onChange();
                        }
                    });
                }
                updateRemainingValue() {
                    this.remainingBalanceEditor.numericValue = this.remaining;
                }
            }
            Components.PaymentEditor = PaymentEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Discounts;
            (function (Discounts) {
                class DiscountEditor extends Web.Components.DetailsEditor {
                    constructor() {
                        super(...arguments);
                        this.currentCompany = Sol.Environment.credential.empresa;
                    }
                    get applicableDiscountEditor() { return this.details.editors.that(cp => cp.propertyName == "ApplicableDiscount"); }
                    get choice() { return this.details.editors.that(cp => cp.propertyName == "DiscountType"); }
                    get valueEditor() { return this.details.editors.that(cp => cp.propertyName == "DiscountValue"); }
                    get percentEditor() { return this.details.editors.that(cp => cp.propertyName == "Percentage"); }
                    get products() { return this.screen.getEditor("Products"); }
                    get payment() { return this.screen.getEditor("Payment"); }
                    get screen() { return this.parent.parent; }
                    get cost() { return 0; }
                    get isMultiCompany() { return true; }
                    get isSummable() { return true; }
                    get margin() { return 0; }
                    get total() { return 0; }
                    changeCompany(companyCode) {
                        this.currentCompany = companyCode;
                        this.getDiscounts();
                    }
                    getDiscounts() {
                        const data = {
                            CompanyID: this.currentCompany,
                            Products: this.products ? this.products.productDiscountData : null,
                            PaymentMode: this.payment ? this.payment.paymentMode : Web.Components.PaymentMode.notSet,
                            PaymentType: this.payment ? this.payment.paymentType : Web.Components.PaymentType.notSet
                        };
                        Web.System.exec("79k8jhkh", "VerifyDiscountsToDatumModel", data, e => this.setApplicableDiscounts(e));
                    }
                    getDiscountValue(total) {
                        return this.applicableDiscountEditor.total + this.getManualDiscount(total);
                    }
                    setCompany(companyCode) { }
                    validate() {
                        if (this.isSupervisor || !this.maxPercentageDiscount)
                            return null;
                        let dealTotal = this.screen.totalWithoutDelivery;
                        if (!dealTotal)
                            return null;
                        let manualDiscount = this.getManualDiscount(dealTotal);
                        if (((100 / dealTotal) * manualDiscount) > this.maxPercentageDiscount) {
                            let message = Sol.Environment.resources.discountExceeded.replace("{0}", this.maxPercentageDiscount.toFixed(2));
                            setTimeout(() => Web.System.requestSupervisorKey(message + ". " + Sol.Environment.resources.supervisorKey, () => {
                                this.isSupervisor = true;
                                this.details.localSaving = this.details.lastLocalSaving;
                                this.details.hideMessages();
                            }), 100);
                            return message;
                        }
                        return null;
                    }
                    build() {
                        this.css.add("sol_discount_editor");
                        super.build();
                        setTimeout(() => {
                            this.valueEditor.readonly = true;
                            this.percentEditor.readonly = true;
                            this.choice.onModified = () => this.onTotalsChanged();
                            this.valueEditor.onChange = () => this.onTotalsChanged();
                            this.percentEditor.onModified = () => this.onTotalsChanged();
                            this.applicableDiscountEditor.onDeletingRow = () => this.onTotalsChanged();
                            this.applicableDiscountEditor.onInstantiateRow = () => this.onTotalsChanged();
                            if (this.products) {
                                this.products.onProductAdded.subscribe(() => this.getDiscounts());
                                this.products.onQuantityChanged.subscribe(() => this.getDiscounts());
                                this.products.onProductDeleted.subscribe(() => this.getDiscounts());
                            }
                            this.updatePromotionsVisibility();
                        }, 300);
                    }
                    setValue(value) {
                        super.setValue(value);
                        this.choice.updateFields();
                        this.updatePromotionsVisibility();
                    }
                    getManualDiscount(total) {
                        var manualDiscount;
                        if (this.choice.selectedCode == 0)
                            manualDiscount = 0;
                        else if (this.choice.selectedCode == 1)
                            manualDiscount = Math.min(this.valueEditor.numericValue, total);
                        else if (this.choice.selectedCode == 2)
                            manualDiscount = Math.min(total * this.percentEditor.value / 100, total);
                        return manualDiscount;
                    }
                    setApplicableDiscounts(discounts) {
                        if (!this.applicableDiscountEditor || discounts.length === 0)
                            return;
                        this.applicableDiscountEditor.value = discounts;
                        this.myLabel.expanded = true;
                        this.updatePromotionsVisibility();
                        this.onTotalsChanged();
                    }
                    updatePromotionsVisibility() {
                        this.applicableDiscountEditor.visible = this.applicableDiscountEditor.rowCount > 0;
                        this.applicableDiscountEditor.myLabel.visible = this.applicableDiscountEditor.visible;
                    }
                }
                Discounts.DiscountEditor = DiscountEditor;
            })(Discounts = Commercial.Discounts || (Commercial.Discounts = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("DiscountEditor", model => {
    const discountEditor = new Sol.Web.Commercial.Discounts.DiscountEditor();
    discountEditor.model = model.ScreenModel;
    return discountEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class DetailsLeftPanel extends Sol.Control {
                constructor() {
                    super();
                    this.fieldInfo = new Screens.FieldInfo();
                    this.css.add("sol_detalles_left");
                }
                clearFieldInfo() {
                    this.fieldInfo.clear();
                }
                setFieldInfo(name, info, required, readonly) {
                    this.fieldInfo.setInfo(name, info, required, readonly);
                }
                createTitle(text) {
                    const titleDisplay = new Sol.Control("h5");
                    titleDisplay.text = text;
                    this.add(titleDisplay);
                }
                build() {
                    super.build();
                    if (this.title)
                        this.createTitle(this.title);
                    if (this.description)
                        this.add(Sol.Control.create(this.description));
                    this.add(this.fieldInfo);
                }
            }
            Screens.DetailsLeftPanel = DetailsLeftPanel;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ConcurrencyAlert extends Sol.Control {
                constructor() {
                    super();
                    this.overwriteButton = new Sol.Button();
                    this.css.add("sol_concurrency_alert");
                    var errorMessage = new Sol.Control();
                    errorMessage.text = Sol.Environment.resources.concurrencyAlert1;
                    this.add(errorMessage);
                    var question = new Sol.Control();
                    question.text = Sol.Environment.resources.concurrencyAlert2;
                    this.add(question);
                    var reloadButton = new Sol.Button();
                    reloadButton.type = Sol.ButtonType.Custom;
                    reloadButton.text = Sol.Environment.resources.reload;
                    reloadButton.onClick = () => {
                        if (this.onReload)
                            this.onReload(this);
                    };
                    this.add(reloadButton);
                    this.overwriteButton.type = Sol.ButtonType.Custom;
                    this.overwriteButton.text = ", " + Sol.Environment.resources.overwrite;
                    this.overwriteButton.onClick = () => {
                        if (this.onOverwrite)
                            this.onOverwrite(this);
                    };
                    this.add(this.overwriteButton);
                    var orText = new Sol.Control("span");
                    orText.text = Sol.Environment.resources.or;
                    this.add(orText);
                    var cancelButton = new Sol.Button();
                    cancelButton.type = Sol.ButtonType.Custom;
                    cancelButton.text = Sol.Environment.resources.cancelar;
                    cancelButton.onClick = () => {
                        if (this.onCancel)
                            this.onCancel(this);
                    };
                    this.add(cancelButton);
                }
                get allowOverwrite() { return this.overwriteButton.visible; }
                set allowOverwrite(v) { this.overwriteButton.visible = v; }
            }
            Screens.ConcurrencyAlert = ConcurrencyAlert;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ScreenMessageList extends Sol.Control {
                constructor() {
                    super();
                    this.css.add("sol_mensaje_area");
                }
                clear() { this.controls.empty(); }
                load(messages) {
                    this.controls.empty();
                    Sol.List.from(messages).forEachReverse(msg => {
                        const message = new Sol.ScreenMessage();
                        message.caption = msg.Title;
                        message.description = msg.Description;
                        message.type = msg.MessageType;
                        this.add(message);
                    });
                }
            }
            Screens.ScreenMessageList = ScreenMessageList;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class DetailsScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.actions = new Sol.List();
                    this.blockActions = false;
                    this.concurrencyAlert = new Screens.ConcurrencyAlert();
                    this.decisions = new Sol.List();
                    this.closingAlertFlag = true;
                    this.messageList = new Screens.ScreenMessageList();
                    this.showSuccessMessage = false;
                    this.uploadingMessage = new Sol.ScreenMessage();
                    this.saveButton = new Sol.Button();
                    this.saveAndNewButton = new Sol.Button();
                    this.screenTitle = new Screens.ScreenTitle();
                    this.leftPanel = new Screens.DetailsLeftPanel();
                    this.succesMessage = new Sol.ScreenMessage();
                    this.toolbar = new Web.Components.Toolbar();
                    this.useDefaultValueSelectors = true;
                    this.canMinimize = false;
                    this.closingAlertEnabled = true;
                    this.code = 0;
                    this.createNewAfterSaving = false;
                    this._currentCompanyID = Sol.Environment.credential.empresa;
                    this.editors = new Sol.List();
                    this.enableTotalCalculation = true;
                    this.formState = Screens.FormState.Insertion;
                    this.myForm = new Sol.Form();
                    this.labels = new Sol.List();
                    this.lastUpdate = null;
                    this.loadSubtype = false;
                    this.relatedEntityCode = 0;
                    this.savingConfirmationMessage = new Sol.ScreenMessage();
                    this.showCancelButton = true;
                    this.showOKButton = true;
                    this.saveAndCloseCaption = Sol.Environment.resources.grabar_cerrar;
                    this._showSaveButton = true;
                    this._showSaveAndNew = true;
                    this.showTitle = true;
                    this.topOffSet = 10;
                    this.totalizationBarPosition = Screens.TotalizationBarPosition.Bottom;
                    this.onFormLoaded = new Sol.EventHandler();
                    this.onClose = new Sol.EventHandler();
                    this.onSaved = new Sol.EventHandler();
                    this.onLocalSaved = new Sol.EventHandler();
                    this.onNavigate = new Sol.EventHandler();
                    this.onSaveAndNew = new Sol.EventHandler();
                    this.onSavingError = new Sol.EventHandler();
                }
                get anchorageCode() { var _a; return ((_a = this.anchorage) === null || _a === void 0 ? void 0 : _a.FilterValue) || 0; }
                get cancelButtonCaption() { return this.myForm.cancelButton.text; }
                set cancelButtonCaption(value) { this.myForm.cancelButton.text = value; }
                get className() { return this._model.ClassName; }
                get currentCompanyID() { return this._currentCompanyID; }
                set currentCompanyID(value) {
                    this._currentCompanyID = value;
                }
                get okCaption() { return this.myForm.okButton.text; }
                set okCaption(value) {
                    this.myForm.okButton.text = value;
                    this.myForm.okButton.accessKey = value[0];
                }
                get showSaveButton() { return this._showSaveButton; }
                set showSaveButton(value) {
                    this._showSaveButton = value;
                    this.saveButton.visible = value;
                }
                get showSaveAndNew() { return this._showSaveAndNew; }
                set showSaveAndNew(value) {
                    this._showSaveAndNew = value;
                    this.saveAndNewButton.visible = value;
                }
                get totalWithoutDelivery() {
                    const deliveryField = this.getEditorByPropertyName("DeliveryDetails");
                    var total = this.getSummableFields().sum(i => i.total);
                    return total - (!deliveryField ? 0 : deliveryField.total);
                }
                get values() { return this.getValues(); }
                ;
                clear() {
                    this.hideMessages();
                    this.editors.forEach(cp => cp.clear());
                    this.code = 0;
                    this.lastUpdate = null;
                }
                foco() {
                    var vEditor = this.editors.cast().that(edt => !edt.readonly);
                    if (vEditor)
                        vEditor.foco();
                }
                getEditor(propertyName) {
                    return this.editors.that(e => e.propertyName === propertyName);
                }
                getLabel(propertyName) {
                    return this.labels.that(e => e.editor.propertyName === propertyName);
                }
                load(codigo, forceReadOnly = false, properties = null) {
                    this.code = codigo;
                    this.hideMessages();
                    this.closingAlertFlag = false;
                    var loader;
                    if (!properties)
                        loader = this.showLoader(Sol.Environment.resources.cargando, 0);
                    var messageErrorLoad = new Sol.ScreenMessage();
                    this.decisions.forEach(control => this.toolbar.controls.remove(control));
                    this.decisions.empty();
                    this.actions.forEach(action => {
                        action.currentID = codigo;
                        action.visible = true;
                    });
                    let data = {
                        className: this._model.ClassName,
                        code: codigo,
                        subtype: this.loadSubtype,
                        propertyList: properties
                    };
                    Web.System.exec("sn9d23vs7d", "Load", data, model => {
                        if (forceReadOnly)
                            model.ReadOnly = true;
                        if (this.myScreen)
                            model.ReadOnly = model.ReadOnly || this.myScreen.model.Readonly;
                        loader === null || loader === void 0 ? void 0 : loader.hide();
                        if (model.Fail) {
                            this.toolbar.visible = false;
                            this.myForm.visible = false;
                            messageErrorLoad.type = Sol.MessageType.Error;
                            messageErrorLoad.caption = Sol.Environment.resources.error_form;
                            this.controls.insert(1, messageErrorLoad);
                            return;
                        }
                        this.relatedEntityCode = model.RelatedEntityCode;
                        this.messageList.load(model.Messages);
                        this.loadDecisions(model.Decisions);
                        this.lastUpdate = model.LastUpdate;
                        const hiddenFields = Sol.List.from(model.HiddenFields);
                        this.editors.where(edt => hiddenFields.contains(edt.propertyName)).forEach(edt => {
                            if (edt.useWrapper)
                                edt.parent.visible = false;
                            else
                                edt.visible = false;
                        });
                        this.loadData(model.Data, model);
                        this.editors.forEach(c => c.readonly = (c.readonly || model.ReadOnly || Sol.List.from(model.BlockedFields).contains(c.propertyName)) &&
                            !Sol.List.from(model.UnblockedFields).contains(c.propertyName));
                        this.editors
                            .where(ed => ed instanceof Web.Components.DetailsEditor)
                            .cast()
                            .forEach(ed => ed.editors.forEach(c => c.readonly = (c.readonly || model.ReadOnly || Sol.List.from(model.BlockedFields).contains(ed.propertyName + '$' + c.propertyName)) &&
                            !Sol.List.from(model.UnblockedFields).contains(ed.propertyName + '$' + c.propertyName)));
                        let readOnly = (model.ReadOnly || this.readonlyScreen) && this.editors.all(c => c.readonly);
                        if (this.editors.any(edt => edt instanceof Sol.Field && edt.alwaysEditable))
                            readOnly = false;
                        this.editors.where(edt => edt.readonly && !!edt.myLabel).forEach(edt => edt.myLabel.showRequiredIcon = false);
                        this.toolbar.visible = this.toolbar.controls.hasItems();
                        if (!this.customTitle)
                            this.screenCaption = (readOnly ? Sol.Environment.resources.view : Sol.Environment.resources.editar);
                        if (this.entityName)
                            this.screenCaption += this.entityName;
                        this.cancelButtonCaption = readOnly ? Sol.Environment.resources.cerrar : Sol.Environment.resources.cancelar;
                        this.saveButton.visible = !readOnly && this.showSaveButton;
                        this.saveButton.enabled = true;
                        this.saveAndNewButton.visible = !readOnly && this.showSaveAndNew;
                        this.myForm.okButton.visible = !readOnly && this.showOKButton;
                        this.screenCaption = model.Title || this.screenCaption;
                        this.screenTitle.text = this.screenCaption;
                        Web.System.screens.refreshNavigation();
                        Sol.List.from(model.ActionVisibilities)
                            .where(avs => this.actions.any(act => act.model.MethodName == avs.MethodName))
                            .forEach(avs => this.actions.that(act => act.model.MethodName == avs.MethodName).visible = avs.IsVisible);
                        if (this.showSuccessMessage) {
                            this.succesMessage.visible = true;
                            this.showSuccessMessage = false;
                        }
                        this.isReadOnly = readOnly;
                    });
                }
                reload() { this.load(this.code); }
                reloadFields() {
                    const properties = Sol.List.from(this.structure)
                        .where(item => item.Reloadable)
                        .select(item => item.PropertyName)
                        .toArray();
                    if (this.code && properties.length > 0)
                        this.load(this.code, false, properties);
                }
                loadData(data, responseModel = null) {
                    this.isLoading = true;
                    this.readData(this, data, responseModel);
                    this.showFilledFields();
                    this.loadedSerializeValues = null;
                    setTimeout(() => this.storeState(), 3000);
                    this.onFormLoaded.invoke(data);
                    this.isLoading = false;
                }
                setEditorValue(propertyName, value) {
                    const field = this.getEditor(propertyName);
                    if (field)
                        field.value = value;
                }
                readData(target, data, responseModel = null) {
                    Sol.List.from(data).forEach(dt => {
                        var _a, _b;
                        if (dt.Campo === "ID")
                            target.code = dt.Valor;
                        var editor = target.editors.that(cp => cp.propertyName == dt.Campo);
                        if (!editor)
                            return;
                        var model = Sol.List.from(target.structure).that(f => f.PropertyName == dt.Campo);
                        if (!model)
                            return;
                        editor.readonly = editor.readonly || model.ReadOnlyAtEdition || ((_a = dt.State) === null || _a === void 0 ? void 0 : _a.IsReadonly) === true;
                        if ((model.HideIfEmpty && editor.isEmpty()) || ((_b = dt.State) === null || _b === void 0 ? void 0 : _b.IsVisible) === false) {
                            editor.visible = false;
                            let label = target.labels.that(l => l.editor == editor);
                            if (label)
                                label.visible = false;
                            if (editor.group)
                                editor.group.GroupDisplay.visible = target.editors.where(e => { var _a; return ((_a = e.group) === null || _a === void 0 ? void 0 : _a.UID) == editor.group.UID && e.visible; }).hasItems();
                        }
                        editor.value = dt.Valor;
                        if (editor instanceof Web.Components.DataCombo && editor.autoLoad)
                            editor.refresh();
                    });
                    Sol.List.from(data).forEach(dt => {
                        var editor = target.editors.that(cp => cp.propertyName == dt.Campo);
                        if (!editor)
                            return;
                        var model = Sol.List.from(target.structure).that(f => f.PropertyName == dt.Campo);
                        if (!model)
                            return;
                        if (model.Visibility == Sol.FieldVisibility.HiddenIfReadonlyAndEmpty && editor.readonly && editor.isEmpty()) {
                            editor.visible = false;
                            var editorLabel = target.labels.that(l => l.editor == editor);
                            if (editorLabel)
                                editorLabel.visible = false;
                        }
                    });
                }
                onCloseScreen() {
                    super.onCloseScreen();
                    if (!this.isChanged || !this.closingAlertFlag || !this.closingAlertEnabled) {
                        this.onClose.invoke();
                        return true;
                    }
                    const exitConfirmation = new Sol.ExitConfirmationDialog();
                    Web.System.screens.add(exitConfirmation);
                    exitConfirmation.visible = true;
                    exitConfirmation.onSave = () => {
                        this.localSaving = true;
                        this.saveForm();
                    };
                    exitConfirmation.onExit = () => {
                        this.closingAlertFlag = false;
                        exitConfirmation.visible = false;
                        Web.System.screens.controls.remove(exitConfirmation);
                        Web.System.screens.closeCurrentScreen();
                    };
                    return false;
                }
                saveForm() {
                    this.hideMessages();
                    this.myForm.save();
                }
                showError(message, relatedEditor, messageCode) {
                    if (!message)
                        return;
                    this.myForm.showError(message, relatedEditor, messageCode);
                }
                showSucessMessage(message) {
                    if (!message)
                        return;
                    this.succesMessage.caption = message;
                    this.succesMessage.visible = true;
                }
                showFilledFields() {
                    this.labels.where(label => !!label).forEach(label => {
                        label.expanded = label.editor.visibleByBehaviour !== false && !label.editor.isEmpty();
                        if (label.editor instanceof Web.Components.DetailsEditor)
                            label.editor.showFilledFields();
                    });
                }
                toControl() { return this; }
                build() {
                    super.build();
                    this._model = this.model;
                    this.structure = this._model.Structure;
                    this.css.add("sol_detalles");
                    this.screenTitle.text = this.screenCaption;
                    if (this.canMinimize) {
                        const MINUS = '&#xf146;';
                        const PLUS = '&#xf0fe;';
                        var minimizeButton = new Sol.Button();
                        minimizeButton.css.add("sol_detalles_minimize_button");
                        minimizeButton.text = MINUS;
                        minimizeButton.onClick = () => {
                            this.myForm.visible = !this.myForm.visible;
                            minimizeButton.text = this.myForm.visible ? MINUS : PLUS;
                        };
                        this.add(minimizeButton);
                    }
                    if (this.showTitle)
                        this.add(this.screenTitle);
                    this.add(this.toolbar);
                    this.add(this.messageList);
                    if (this.showLeftPanel && !Sol.Environment.isMobile && this._model.Description) {
                        this.leftPanel.title = this._model.Name;
                        this.leftPanel.description = this._model.Description;
                        this.add(this.leftPanel);
                    }
                    this.succesMessage.type = Sol.MessageType.Success;
                    this.succesMessage.caption = Sol.Environment.resources.grabado_ok;
                    this.succesMessage.visible = false;
                    this.myForm.add(this.succesMessage);
                    this.uploadingMessage.type = Sol.MessageType.Information;
                    this.uploadingMessage.css.add("uploading_message");
                    this.uploadingMessage.caption = Sol.Environment.resources.uploading_loading;
                    this.uploadingMessage.visible = false;
                    this.myForm.add(this.uploadingMessage);
                    this.savingConfirmationMessage.type = Sol.MessageType.Confirmation;
                    this.savingConfirmationMessage.caption = Sol.Environment.resources.wantSave;
                    this.savingConfirmationMessage.visible = false;
                    this.savingConfirmationMessage.onCancel = () => {
                        this.savingConfirmationMessage.visible = false;
                        this.disableReload = false;
                        this.onSavingError.invoke();
                    };
                    this.savingConfirmationMessage.onConfirm = () => {
                        this.localSaving = true;
                        this.saveForm();
                    };
                    this.myForm.add(this.savingConfirmationMessage);
                    this.concurrencyAlert.visible = false;
                    this.concurrencyAlert.onReload = () => this.load(this.code);
                    this.concurrencyAlert.onOverwrite = () => {
                        this.lastUpdate = null;
                        this.localSaving = this.lastLocalSaving;
                        this.saveForm();
                    };
                    this.concurrencyAlert.onCancel = () => this.concurrencyAlert.visible = false;
                    this.myForm.add(this.concurrencyAlert);
                    this.saveButton.text = Sol.Environment.resources.grabar;
                    this.saveButton.onClick = () => {
                        this.localSaving = true;
                        this.saveForm();
                    };
                    this.myForm.footer.add(this.saveButton);
                    this.createSaveAndNewButton();
                    this.createNewWithSameDataButton();
                    this.createBackToTopButton();
                    this.createNavigationButtons();
                    this.myForm.okButton.text = this.saveAndCloseCaption;
                    this.myForm.okButton.visible = this.showOKButton;
                    this.myForm.cancelButton.visible = this.showCancelButton;
                    this.myForm.onSave = () => this.save();
                    this.add(this.myForm);
                    var components = Web.Editors.fillForm(this._model.Structure, this.myForm, this.toolbar, this.formState, this.className, this.code, this.disableMinimizedControls, this.totalizationBarPosition, this.groupMode || this._model.GroupMode);
                    this.editors = components.fields;
                    this.labels = components.labels;
                    this.configureDefaultButtons();
                    this.configureTotalCalculation();
                    this.configureLeftPanel();
                    this.loadDecisions(this.defaultDecisions);
                    this.loadActions();
                    this.toolbar.visible = this.toolbar.controls.any(ctr => ctr.visible);
                    if (!this.toolbar.visible && this.topOffSet)
                        this.myForm.estilos.agregar("padding-top", this.topOffSet + "px");
                    if (this._model.CurrentID)
                        this.load(this._model.CurrentID);
                    if (this.onBuildComplete)
                        this.onBuildComplete(this);
                    this.configureAutoReload();
                }
                getClassName() { return this._model.ClassName; }
                getValues() {
                    const result = this.editors
                        .where(cp => cp.savable || (!cp.readonly && !(cp instanceof Web.FieldGroupEditor)))
                        .select(cp => ({ Campo: cp.propertyName, Valor: cp.value }));
                    this.editors.where(cp => cp instanceof Web.FieldGroupEditor).forEach(cp => result.addMany(cp.value));
                    if (this.anchorage)
                        result.add({ Campo: this.anchorage.PropertyName, Valor: this.anchorage.FilterValue });
                    return result.toArray();
                }
                onSetScreenCaption() { this.screenTitle.text = this.screenCaption; }
                actionClick(e) {
                    if (this.blockActions)
                        return;
                    this.blockActions = true;
                    this.hideMessages();
                    if (this.code) {
                        if (this.isChanged && this.closingAlertFlag)
                            this.waitForSaving(e);
                        else if (e instanceof Web.Components.DecisionButton)
                            this.runDecision(e, false);
                        else
                            e.run();
                    }
                    else {
                        if (e instanceof Web.Actions.ActionBase) {
                            e.run();
                            return;
                        }
                        this.waitingAction = e;
                        this.localSaving = true;
                        this.saveForm();
                    }
                    this.blockActions = false;
                }
                actionDone(action) {
                    if (action.model.RequiresReload)
                        this.reload();
                    else {
                        if (action.errorMessage)
                            this.myForm.showError(action.errorMessage);
                        this.succesMessage.caption = action.successMessage;
                        if (action.successMessage)
                            this.succesMessage.visible = !action.errorMessage;
                    }
                }
                addDefaultSelectorToLabel(label) {
                    const defaultButton = new Web.Components.DefaultValueSelector();
                    defaultButton.className = this._model.ClassName;
                    defaultButton.editor = label.editor;
                    defaultButton.onSave = dbt => Sol.List.from(this._model.Structure)
                        .that(i => i.PropertyName == dbt.editor.propertyName)
                        .UserDefault = JSON.stringify(dbt.editor.value);
                    label.add(defaultButton);
                }
                calculateTotals() {
                    const totalField = this.getEditorByPropertyName("Total");
                    const totalCostField = this.getEditorByPropertyName("TotalCost");
                    const totalMarginField = this.getEditorByPropertyName("Margin");
                    const marginPercentField = this.getEditorByPropertyName("MarginPercent");
                    const deliveryField = this.getEditorByPropertyName("DeliveryDetails");
                    const discountEditor = this.getEditorByPropertyName("Discount");
                    const extraCost = this.getEditorByPropertyName("ExtraCost");
                    var total = this.getSummableFields().sum(i => i.total);
                    var cost = this.getSummableFields().sum(i => i.cost);
                    var margin = this.getSummableFields().sum(i => i.margin);
                    if (discountEditor) {
                        var discount = discountEditor.getDiscountValue(total - (!deliveryField ? 0 : deliveryField.total));
                        total -= discount;
                        margin -= discount;
                    }
                    if (extraCost) {
                        let extra = extraCost.numericValue;
                        extra = extra > 100 ? 100 : extra;
                        margin -= ((margin / 100) * extra);
                    }
                    const marginPercent = total == 0 ? 0 : 100 - (1 - (margin / total)) * 100;
                    if (totalField)
                        totalField.numericValue = total;
                    if (totalCostField)
                        totalCostField.numericValue = cost;
                    if (totalMarginField)
                        totalMarginField.numericValue = margin;
                    if (marginPercentField)
                        marginPercentField.value = marginPercent;
                    this.getTotalSubscribers().forEach(subscriber => subscriber.onTotalPublished({ margin: margin, total: total }));
                }
                configureAutoReload() {
                    if (!this.autoReload)
                        return;
                }
                configureDefaultButtons() {
                    if (!this.useDefaultValueSelectors)
                        return;
                    this.labels
                        .where(label => label && label.editor instanceof Sol.Combo)
                        .forEach(label => this.addDefaultSelectorToLabel(label));
                    this.editors
                        .where(edt => edt instanceof Sol.Check && !edt.readonly && edt.allowSaveValueAsDefault)
                        .forEach(check => {
                        const defaultButton = new Web.Components.DefaultValueSelector();
                        defaultButton.className = this._model.ClassName;
                        defaultButton.editor = check;
                        defaultButton.onSave = dbt => Sol.List.from(this._model.Structure)
                            .that(i => i.PropertyName == dbt.editor.propertyName)
                            .UserDefault = JSON.stringify(dbt.editor.value);
                        check.toControl().add(defaultButton);
                    });
                    Sol.List.from(this._model.Structure)
                        .where(i => i.EnableUserDefault)
                        .forEach(i => {
                        const label = this.labels.that(lbl => lbl.editor.propertyName == i.PropertyName);
                        this.addDefaultSelectorToLabel(label);
                        if (!this.code && label.editor)
                            label.editor.defaultValue = JSON.parse(i.UserDefault);
                    });
                }
                configureLeftPanel() {
                    if (!this.showLeftPanel)
                        return;
                    this.editors.forEach(editor => {
                        var _a, _b;
                        (_a = editor.onFocus) === null || _a === void 0 ? void 0 : _a.subscribe(() => this.leftPanel.setFieldInfo(editor.caption, editor.fieldModel.LargeDescription, editor.required, editor.readonly));
                        (_b = editor.onLeave) === null || _b === void 0 ? void 0 : _b.subscribe(() => this.leftPanel.clearFieldInfo());
                    });
                }
                configureTotalCalculation() {
                    if (!this.enableTotalCalculation)
                        return;
                    if (!this.getEditorByPropertyName("Total") && !this.getEditorByPropertyName("TotalCost"))
                        return;
                    const creditField = this.getEditorByPropertyName("Credit");
                    if (creditField)
                        creditField.onChange = () => this.calculateTotals();
                    const extraCostField = this.getEditorByPropertyName("ExtraCost");
                    if (extraCostField)
                        extraCostField.onValueModified.subscribe(() => this.calculateTotals());
                    this.getSummableFields().forEach(e => e.onTotalsChanged = () => setTimeout(() => this.calculateTotals(), 500));
                }
                createSaveAndNewButton() {
                    this.saveAndNewButton.text = Sol.Environment.resources.saveAndNew;
                    this.saveAndNewButton.onClick = () => {
                        this.createNewAfterSaving = true;
                        this.localSaving = false;
                        this.saveForm();
                    };
                    if (this.showSaveAndNew)
                        this.myForm.footer.add(this.saveAndNewButton);
                }
                createNewWithSameDataButton() {
                    if (!this.allowCreateWithSameData)
                        return;
                    const newWithSameDataButton = new Sol.Button();
                    newWithSameDataButton.text = Sol.Environment.resources.newWithSameData;
                    newWithSameDataButton.onClick = () => {
                        if (this.isChanged) {
                            this.savingConfirmationMessage.visible = true;
                            return;
                        }
                        this.createNewAfterSaving = true;
                        this.onSaved.invoke(this, null, this.values);
                    };
                    this.myForm.footer.add(newWithSameDataButton);
                }
                createBackToTopButton() {
                    if (this.hideBackToTopButton)
                        return;
                    let backToTopButton = new Sol.Button();
                    backToTopButton.imageCode = "&#xf062;";
                    backToTopButton.css.add("sol_detalles_nav_button");
                    backToTopButton.onClick = () => window.scrollTo({ top: 0, behavior: 'smooth' });
                    backToTopButton.tip = Sol.Environment.resources.backToTop;
                    this.myForm.footer.add(backToTopButton);
                }
                createNavigationButtons() {
                    if (!this.showNavigationButtons)
                        return;
                    let nextButton = new Sol.Button();
                    nextButton.imageCode = "&#xf04e;";
                    nextButton.css.addMany(["sol_detalles_nav_button", "sol_detalles_nav_button_next"]);
                    nextButton.onClick = () => this.navigate(Screens.DetailsNavigationDirection.Forward);
                    this.myForm.footer.add(nextButton);
                    let previousButton = new Sol.Button();
                    previousButton.imageCode = "&#xf04a;";
                    previousButton.css.addMany(["sol_detalles_nav_button", "sol_detalles_nav_button_prev"]);
                    previousButton.onClick = () => this.navigate(Screens.DetailsNavigationDirection.Backward);
                    this.myForm.footer.add(previousButton);
                }
                navigate(direction) {
                    if (this.isChanged) {
                        this.hideMessages();
                        this.savingConfirmationMessage.visible = true;
                        return;
                    }
                    this.onNavigate.invoke(direction);
                }
                getEditorByPropertyName(property) {
                    return this.editors.that(e => e.propertyName === property);
                }
                getSummableFields() {
                    return this.editors.cast().where(e => e.isSummable);
                }
                getTotalSubscribers() {
                    return this.editors.cast().where(e => e.isTotalSubscriber);
                }
                hideMessages(relatedEditor, messageCode) {
                    this.succesMessage.visible = false;
                    this.myForm.hideMessages(relatedEditor, messageCode);
                    this.uploadingMessage.visible = false;
                    this.savingConfirmationMessage.visible = false;
                    this.concurrencyAlert.visible = false;
                }
                get isChanged() {
                    return this.loadedSerializeValues && JSON.stringify(this.values).replace(/"/g, "") != this.loadedSerializeValues.replace(/"/g, "");
                }
                setModelReadonly() {
                    this.readonlyScreen = true;
                    Sol.List.from(this.model.Structure).forEach(fld => fld.ReadOnly = true);
                }
                waitForSaving(action) {
                    this.hideMessages();
                    this.waitingAction = action;
                    this.savingConfirmationMessage.visible = true;
                }
                waitForMethod(method) {
                    this.hideMessages();
                    this.waitingMethod = method;
                    this.savingConfirmationMessage.visible = true;
                }
                loadActions() {
                    Sol.List.from(this._model.Actions).forEach(actionModel => {
                        const actionButton = Web.Actions.ActionFactory.LoadAction(actionModel);
                        actionButton.visible = actionModel.ShowInInsertion;
                        actionButton.onClick = () => this.actionClick(actionButton);
                        actionButton.onDone = e => this.actionDone(e);
                        actionButton.detailsScreen = this;
                        this.toolbar.add(actionButton);
                        this.actions.add(actionButton);
                    });
                }
                loadDecisions(decisions) {
                    if (!decisions)
                        return;
                    let pos = 0;
                    this.decisions.empty();
                    for (var i = this.toolbar.controls.count - 1; i >= 0; i--)
                        if (this.toolbar.controls.item(i) instanceof Web.Components.DecisionButton)
                            this.toolbar.controls.removeItem(i);
                    Sol.List.from(decisions).orderBy(d => d.Position).forEach(decision => {
                        const decisionButton = new Web.Components.DecisionButton(this.code, decision);
                        decisionButton.onClick = () => this.actionClick(decisionButton);
                        decisionButton.parent = this;
                        this.toolbar.controls.insert(pos++, decisionButton);
                        this.decisions.add(decisionButton);
                    });
                }
                minimizeAllComplexFields() {
                    if (this.editors.where(e => e.isComplex).count <= 7)
                        return;
                    this.editors.where(e => e.isComplex).forEach(e => e.myLabel.expanded = false);
                }
                runDecision(e, confirmed) {
                    var _a;
                    this.succesMessage.visible = false;
                    this.uploadingMessage.visible = false;
                    this.savingConfirmationMessage.visible = false;
                    const decisionScreen = new Screens.DecisionScreen();
                    decisionScreen.code = this.code;
                    decisionScreen.model = e.model;
                    decisionScreen.screenCaption = e.text;
                    decisionScreen.parentScreen = this;
                    decisionScreen.confirmed = confirmed;
                    decisionScreen.disableCloseCurrentScreen = !!((_a = this.myScreen) === null || _a === void 0 ? void 0 : _a.anchorage);
                    Web.System.screens.addScreen(decisionScreen);
                    Web.System.screens.showScreen(decisionScreen);
                }
                save() {
                    this.hideMessages();
                    this.messageList.clear();
                    this.lastLocalSaving = this.localSaving;
                    if (this.editors.any(cp => cp instanceof Web.Components.Uploads.Upload && cp.isUploading)) {
                        this.uploadingMessage.visible = true;
                        window.scrollTo(0, 0);
                        this.onSavingError.invoke();
                        return;
                    }
                    var loader = this.showLoader(Sol.Environment.resources.saving);
                    let savingData = {
                        className: this.getClassName(),
                        id: this.code,
                        data: this.values,
                        lastUpdate: this.disableConcurrencyCheck ? null : this.lastUpdate
                    };
                    if (this.onSaving)
                        savingData = this.onSaving(this, savingData);
                    Web.System.exec("3b5v9v45", "Save", savingData, result => {
                        var isNewRecord = !this.code;
                        loader.hide();
                        this.myForm.workComplete();
                        this.blockActions = false;
                        if (!result.Fail) {
                            this.code = result.ID;
                            this.editors.cast().where(edt => edt.isCodeBasedComponent).forEach(edt => edt.contextCode = result.ID);
                            this.editors.where(edt => edt instanceof Web.Components.TabEditor).cast().forEach(edt => edt.code = result.ID);
                            Sol.Environment.credential.load(result.Credencial);
                            this.datumModel = result.ModeloDato;
                            if (!this.localSaving)
                                this.onSaved.invoke(this, result, savingData.data);
                            if (this.localSaving) {
                                this.lastUpdate = result.SavingTime;
                                this.storeState();
                                window.scrollTo(0, 0);
                                this.succesMessage.visible = true;
                                if (this.waitingAction) {
                                    this.succesMessage.visible = false;
                                    if (this.waitingAction instanceof Web.Components.DecisionButton) {
                                        this.runDecision(this.waitingAction, true);
                                        isNewRecord = false;
                                    }
                                    else
                                        this.waitingAction.run();
                                    this.waitingAction = null;
                                    this.blockActions = false;
                                }
                                if (this.onLocalSaved)
                                    this.onLocalSaved.invoke(this);
                                if (isNewRecord && !this.disableReload) {
                                    this.requiresReload = true;
                                    this.onSaved.invoke(this, result, savingData.data);
                                }
                                if (!this.disableReload) {
                                    this.showSuccessMessage = true;
                                    this.reloadFields();
                                }
                                this.localSaving = false;
                            }
                        }
                        else if (result.ConcurrencyFail) {
                            this.concurrencyAlert.allowOverwrite = !this.decisions.hasItems();
                            this.concurrencyAlert.visible = true;
                            window.scrollTo(0, 0);
                            this.onSavingError.invoke();
                        }
                        else {
                            this.myForm.showError(result.ErrorMessage);
                            this.onSavingError.invoke();
                        }
                    });
                }
                showLoader(message, timeout = 500) {
                    var loader = new Web.Components.LoaderControl();
                    loader.caption = message;
                    loader.timeout = timeout;
                    loader.baseControl = this;
                    if (!this.disableLoader)
                        loader.show();
                    return loader;
                }
                storeState() {
                    this.loadedSerializeValues = JSON.stringify(this.values);
                    this.closingAlertFlag = true;
                }
            }
            Screens.DetailsScreen = DetailsScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class Selector extends Sol.SelectorField {
                    constructor(tagName) {
                        super(tagName);
                        this.createButton = new Sol.Button();
                        this.editButton = new Sol.Button();
                        this.forceSubtype = false;
                        this.properties = null;
                        this.allowCreateNew = false;
                        this.allowEdit = false;
                        this.mainFilterType = "SText";
                        this.isComplex = true;
                        this.resultCount = 10;
                        this.resultsOrder = null;
                        this.resultsOrdering = Web.Ordering.ascending;
                    }
                    get autoWidth() { return this.mainField.autoWidth; }
                    set autoWidth(value) { this.mainField.autoWidth = value; }
                    get fieldAutoWidth() { return this.mainField.autoWidth; }
                    set fieldAutoWidth(value) { this.mainField.autoWidth = value; }
                    get fieldWidth() { return this.mainField.ancho; }
                    set fieldWidth(value) {
                        this.mainField.autoWidth = false;
                        this.mainField.ancho = value;
                    }
                    inferValue() {
                        var _a;
                        let code = (_a = Web.System.screens.screens.that(e => e instanceof Web.Screens.DetailsScreen && e.className == this.className)) === null || _a === void 0 ? void 0 : _a.code;
                        this.value = code;
                        if (code && this.myLabel)
                            this.myLabel.expanded = true;
                    }
                    build() {
                        super.build();
                        if (this.allowCreateNew)
                            this.initializeCreateButton();
                        if (this.allowEdit)
                            this.initializeEditButton();
                    }
                    detailsSaved(screen) {
                        screen.mySelector.value = screen.code;
                        Web.System.screens.showScreen(screen.myScreen);
                    }
                    fillPopup(model) {
                        this.itemLoad.visible = false;
                        for (var i = 0; i < model.Codes.length; i++) {
                            var data = model.Data[i];
                            var dataCollection = Sol.List.from(data);
                            var item = new Sol.SelectorItem();
                            var textValue = dataCollection.that(cmp => cmp.Campo.indexOf(this.displayProperty) > -1).Valor;
                            item.code = model.Codes[i];
                            item.text = textValue.Campo || textValue;
                            item.onClick = e => this.itemClick(e);
                            item.extraData = data;
                            if (this.onInstantiateItem)
                                this.onInstantiateItem(item, dataCollection);
                            this.popup.add(item);
                        }
                        if (this.popup.controls.count > 1)
                            this.popup.controls.item(1).focused = true;
                    }
                    getFilters() {
                        var filters = new Sol.List();
                        if (this.preFilters)
                            filters.addMany(this.preFilters);
                        if (this.filterByText || this.evalEmptyFilter)
                            filters.add({
                                PropertyName: this.filterProperty || this.propertyName || this.displayProperty,
                                FilterValue: this.mainField.isEmpty() && this.evalEmptyFilter ? "[empty]" : this.mainField.value,
                                FilterType: this.mainFilterType
                            });
                        if (this.isRelation)
                            filters.add({
                                PropertyName: "Activo",
                                FilterValue: true,
                                FilterType: "SBoolean"
                            });
                        this.filterByText = true;
                        if (this.onFiltering)
                            filters.addMany(this.onFiltering());
                        return filters;
                    }
                    instantiateDetailsScreen() { return new Web.Screens.DetailsScreen(); }
                    internalValueSet(value) {
                        this.createButton.visible = !this.readonly && !this.hideNewButtonAtEdit && this.allowCreateNew;
                        this.editButton.visible = this.allowEdit && this.selectedCode > 0;
                    }
                    enableButtons(value) {
                        if (this.onStateChanged)
                            this.onStateChanged(value);
                        this.savable = value;
                        this.editButton.enabled = value;
                    }
                    search(code, cancelClickEvent) {
                        const _super = Object.create(null, {
                            search: { get: () => super.search }
                        });
                        return __awaiter(this, void 0, void 0, function* () {
                            _super.search.call(this, code, cancelClickEvent);
                            if (this.sourceMode == Sol.SelectorSourceMode.Custom)
                                return;
                            if (this.ajax)
                                this.ajax.abort();
                            this.properties = this.properties || ["ID", this.displayProperty];
                            if (code)
                                this.filterByText = false;
                            let filters = this.getFilters();
                            if (code)
                                filters.add({ FilterType: "SInteger", FilterValue: code, PropertyName: "ID" });
                            const data = {
                                cluster: this.cluster,
                                className: this.className,
                                currentPage: 1,
                                rowCount: this.resultCount,
                                filters: filters.toArray(),
                                sortProperty: this.resultsOrder,
                                sortOrder: this.resultsOrdering,
                                properties: this.properties,
                                pageInfo: false
                            };
                            this.ajax = Web.System.exec("i3n48smak", "Search", data, response => {
                                this.fillPopup(response);
                                if (code)
                                    this.itemClick(this.items.first(), cancelClickEvent);
                            });
                        });
                    }
                    setReadonly(value) {
                        super.setReadonly(value);
                        this.createButton.visible = !value && this.allowCreateNew;
                    }
                    cancelDetailsScreen(e) {
                        var detalles = e.parent;
                        var miPantalla = detalles.myScreen;
                        Web.System.screens.showScreen(miPantalla);
                    }
                    createButtonClick() {
                        const detailsScreen = this.instantiateDetailsScreen();
                        detailsScreen.model = this.miInfo.ScreenModel || this.createDetailsModel();
                        detailsScreen.showSaveAndNew = false;
                        detailsScreen.screenCaption = this.etiqueta;
                        detailsScreen.myForm.onCancel = this.cancelDetailsScreen;
                        detailsScreen.onSaved.subscribe(e => this.detailsSaved(e));
                        detailsScreen.myScreen = Web.System.screens.currentScreen;
                        detailsScreen.mySelector = this;
                        Web.System.screens.addScreen(detailsScreen);
                        const fieldValue = this.mainField.value;
                        if (fieldValue.isNumeric && fieldValue.length == 14 && fieldValue.soloDigitos().length == 14)
                            detailsScreen.setEditorValue("EntidadRelacionada$NúmeroDocumento", fieldValue);
                        else if (/[a-zA-Z]/.test(fieldValue))
                            detailsScreen.setEditorValue("EntidadRelacionada$Nombre", fieldValue);
                        Web.System.screens.showScreen(detailsScreen);
                        detailsScreen.foco();
                    }
                    createDetailsModel() {
                        return {
                            Actions: null,
                            ClassName: this.className,
                            IsProcess: false,
                            Structure: this.estructura,
                            CurrentID: 0,
                            GroupMode: Web.Screens.FieldGroupMode.Frames
                        };
                    }
                    editButtonClick() {
                        var _a;
                        const screen = this.instantiateDetailsScreen();
                        let model = this.miInfo.ScreenModel || this.createDetailsModel();
                        screen.showSaveAndNew = false;
                        screen.model = model;
                        if ((_a = Web.System.screens.currentScreen) === null || _a === void 0 ? void 0 : _a.isReadOnly)
                            screen.setModelReadonly();
                        screen.code = this._value;
                        screen.screenCaption = this.etiqueta;
                        screen.myForm.onCancel = this.cancelDetailsScreen;
                        screen.onSaved.subscribe(e => this.detailsSaved(e));
                        screen.myScreen = Web.System.screens.currentScreen;
                        screen.mySelector = this;
                        screen.loadSubtype = this.forceSubtype;
                        Web.System.screens.addScreen(screen);
                        Web.System.screens.showScreen(screen);
                        screen.foco();
                        screen.load(this._value);
                    }
                    initializeCreateButton() {
                        this.createButton.text = Sol.Environment.resources.crear;
                        this.createButton.imageCode = "&#xf067;";
                        this.createButton.onClick = () => this.createButtonClick();
                        this.add(this.createButton);
                    }
                    initializeEditButton() {
                        this.enableButtons(false);
                        this.editButton.text = Sol.Environment.resources.abrir;
                        this.editButton.imageCode = "&#xf044;";
                        this.editButton.onClick = () => this.editButtonClick();
                        this.add(this.editButton);
                    }
                }
                Selectors.Selector = Selector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class EmployeeSelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.isComplex = false;
                        this.useWrapper = true;
                        this.displayProperty = "EmployeeIDWithName";
                        this.filterProperty = "GeneralFilter";
                        this.resultsOrder = "EntidadRelacionada$Nombre";
                        this.evalEmptyFilter = true;
                    }
                }
                Selectors.EmployeeSelector = EmployeeSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class RelationBaseSelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.phonesField = new Sol.Control();
                        this.taxIdField = new Sol.Control();
                        this.emailField = new Sol.Control();
                        this.extraFieldsArea = new Sol.Control();
                        this.followups = new Components.FollowupsButton();
                        this.onClearExtraData = e => this.clearExtraData(e);
                        this.onValueSet = e => this.loadExtraFields(e);
                        this.followups.enabled = false;
                        this.followups.automaticSaving = true;
                        this.followups.enableUploads = true;
                        this.followups.className = "Solarium.SeguimientoRelación, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.followups.associativeProperty = "Relación";
                        this.displayProperty = "EntidadRelacionada$Nombre";
                        this.resultsOrder = "EntidadRelacionada$Nombre";
                        this.properties = ["ID",
                            this.displayProperty,
                            "EntidadRelacionada$NúmeroDocumento",
                            "EntidadRelacionada$Email",
                            "EntidadRelacionada$Email2",
                            "EntidadRelacionada$PhoneList"];
                        this.isRelation = true;
                        this.extraFieldsArea.visible = false;
                    }
                    get hideExtraData() { return this._hideExtraData; }
                    set hideExtraData(value) {
                        this._hideExtraData = value;
                        if (this.extraFieldsArea.visible)
                            this.extraFieldsArea.visible = false;
                    }
                    addExtraButtons() { }
                    build() {
                        super.build();
                        this.followups.contextClassName = this.className;
                        this.followups.showDeals = this.enableFollowupDealInfo;
                        this.add(this.followups);
                        this.followups.visible = !this.hideFollowUpButton;
                        this.addExtraButtons();
                        this.extraFieldsArea.css.add("sol_selector_extra_area");
                        this.add(this.extraFieldsArea);
                        this.initializeTaxIDField();
                        this.initializePhonesField();
                        this.initializeEmailField();
                    }
                    enableButtons(value) {
                        super.enableButtons(value);
                        this.followups.enabled = value;
                    }
                    itemClick(item) {
                        var _a;
                        this.extraFieldsArea.visible = !this.hideExtraData;
                        if (!item)
                            return;
                        const extras = Sol.List.from(item.extraData);
                        this.followups.code = item.code;
                        const taxId = extras.that(dt => dt.Campo == "EntidadRelacionada$NúmeroDocumento").Valor;
                        this.taxIdField.text = taxId;
                        const phones = extras.that(dt => dt.Campo == "EntidadRelacionada$PhoneList").Valor;
                        this.phonesField.text = phones;
                        const email = this.concatEmails(extras.that(dt => dt.Campo == "EntidadRelacionada$Email").Valor, (_a = extras.that(dt => dt.Campo == "EntidadRelacionada$Email2")) === null || _a === void 0 ? void 0 : _a.Valor);
                        this.emailField.text = email;
                        super.itemClick(item);
                    }
                    internalValueSet(value) {
                        super.internalValueSet(value);
                        this.extraFieldsArea.visible = !this.isEmpty() && !this.hideExtraData;
                        if (!this.isEmpty())
                            this.loadExtraFields(value);
                    }
                    clearExtraData(e) {
                        this.taxIdField.text = "";
                        this.phonesField.text = "";
                        this.emailField.text = "";
                        this.extraFieldsArea.visible = false;
                    }
                    initializeTaxIDField() {
                        const taxIdWrapper = new Sol.FieldWrapper();
                        const taxIdLabel = new Sol.Label();
                        taxIdLabel.text = Sol.Environment.resources.taxid;
                        taxIdWrapper.add(taxIdLabel);
                        this.taxIdField.css.add("sol_selector_extra_field");
                        taxIdWrapper.add(this.taxIdField);
                        this.extraFieldsArea.add(taxIdWrapper);
                    }
                    initializePhonesField() {
                        const phonesWrapper = new Sol.FieldWrapper();
                        const phonesLabel = new Sol.Label();
                        phonesLabel.text = Sol.Environment.resources.telefonos;
                        phonesWrapper.add(phonesLabel);
                        this.phonesField.css.add("sol_selector_extra_field");
                        phonesWrapper.add(this.phonesField);
                        this.extraFieldsArea.add(phonesWrapper);
                    }
                    initializeEmailField() {
                        const emailWrapper = new Sol.FieldWrapper();
                        const emailLabel = new Sol.Label();
                        emailLabel.text = "E-mail";
                        emailWrapper.add(emailLabel);
                        this.emailField.css.add("sol_selector_extra_field");
                        emailWrapper.add(this.emailField);
                        this.extraFieldsArea.add(emailWrapper);
                    }
                    loadExtraFields(model) {
                        this.extraFieldsArea.visible = !this.hideExtraData;
                        if (!model.Campo) {
                            this.search(model.Valor);
                            return;
                        }
                        this.followups.code = model.Valor;
                        this.taxIdField.text = model.TaxID;
                        this.phonesField.text = !model.Phones ? "" : model.Phones;
                        this.emailField.text = this.concatEmails(model.Email1, model.Email2);
                    }
                    concatEmails(email1, email2) {
                        let result = email1;
                        if (email1 && email2)
                            result += ", ";
                        if (email2)
                            result += email2;
                        return result;
                    }
                }
                Selectors.RelationBaseSelector = RelationBaseSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class SupplierSelector extends Selectors.RelationBaseSelector {
                    constructor() {
                        super();
                        this.corporateField = new Sol.Control();
                        this.selectedRelationCode = 0;
                        this.hideFollowUpButton = true;
                        this.displayProperty = "EntidadRelacionada$Nombre";
                        this.resultsOrder = "EntidadRelacionada$Nombre";
                        this.filterProperty = "GeneralFilter";
                        this.properties = ["ID",
                            this.displayProperty,
                            "EntidadRelacionada$NúmeroDocumento",
                            "EntidadRelacionada$Email",
                            "EntidadRelacionada$Email2",
                            "EntidadRelacionada$PhoneList",
                            "EntidadRelacionada$Dirección$City",
                            "EntidadRelacionada$Dirección$Estado$Sigla",
                            "EntidadRelacionada$CorporateName"];
                        this.onInstantiateItem = (i, d) => this.instantiate(i, d);
                        this.onItemSelected = i => this.mainField.value = i.data;
                    }
                    getFilters() {
                        var filters = super.getFilters();
                        filters.add({ FilterType: "SBoolean", FilterValue: true, PropertyName: "Activo" });
                        return filters;
                    }
                    build() {
                        super.build();
                        this.initCorporateNameField();
                    }
                    itemClick(item) {
                        if (!item)
                            return;
                        super.itemClick(item);
                        this.followups.code = item.code;
                        const extras = Sol.List.from(item.extraData);
                        this.corporateField.text = extras.that(dt => dt.Campo == "EntidadRelacionada$CorporateName").Valor;
                    }
                    loadExtraFields(model) {
                        super.loadExtraFields(model);
                        this.corporateField.text = model.CorporateName;
                    }
                    instantiate(item, data) {
                        item.data = item.text;
                        item.text = null;
                        item.addCtr(data.that(cmp => cmp.Campo == "EntidadRelacionada$Nombre").Valor, "sol_supplier_selector_item_name");
                        item.addCtr(data.that(cmp => cmp.Campo == "EntidadRelacionada$CorporateName").Valor, null);
                    }
                    initCorporateNameField() {
                        const corporateWrapper = new Sol.FieldWrapper();
                        const corporateLabel = new Sol.Label();
                        corporateLabel.text = "Razão social";
                        corporateWrapper.add(corporateLabel);
                        this.corporateField.css.add("sol_selector_extra_field");
                        corporateWrapper.add(this.corporateField);
                        this.extraFieldsArea.controls.insert(0, corporateWrapper);
                    }
                }
                Selectors.SupplierSelector = SupplierSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("SupplierSelector", model => {
    const selector = new Sol.Web.Components.Selectors.SupplierSelector();
    selector.className = model.DataTypeFullName;
    return selector;
});
Sol.Web.Editors.registerFilter("SupplierSelector", model => {
    const selector = new Sol.Web.Components.Selectors.SupplierSelector();
    selector.className = model.ClassName;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class RelationSelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.picture = new Web.EntityPicture();
                        this.showRelationDescription = true;
                        this.selectedRelationCode = 0;
                        this.className = "Solarium.Relación`2[[Solarium.Entidad, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Solarium.Entidad, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.displayProperty = "EntidadRelacionada$Nombre";
                        this.resultsOrder = "EntidadRelacionada$Nombre";
                        this.filterProperty = "GeneralFilter";
                        this.properties = ["ID", "EntidadRelacionada$Nombre", "EntidadRelacionada$NúmeroDocumento", "RelationName", "TipoRelación"];
                        this.onInstantiateItem = (i, d) => this.instantiate(i, d);
                        this.onItemSelected = i => this.itemSelected(i);
                        this.picture.visible = false;
                        this.controls.insert(0, this.picture);
                    }
                    clear() {
                        super.clear();
                        this.updatePicture(null);
                    }
                    getFilters() {
                        var filters = super.getFilters();
                        filters.add({ FilterType: "SBoolean", FilterValue: true, PropertyName: "Activo" });
                        filters.add({ FilterType: "SBoolean", FilterValue: true, PropertyName: "CompanyGroupFilter" });
                        return filters;
                    }
                    loadByCode(code) {
                        if (!code)
                            return;
                        var filters = this.getFilters();
                        filters.add({ FilterType: "SInteger", FilterValue: code, PropertyName: "ID" });
                        let data = {
                            className: this.className,
                            currentPage: 1,
                            rowCount: 1,
                            filters: filters.toArray(),
                            sortProperty: this.resultsOrder,
                            sortOrder: this.resultsOrdering,
                            properties: this.properties,
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", data, model => {
                            if (model.Codes.length == 0 || this.selectedRelationCode == code)
                                return;
                            this.selectedRelationCode = code;
                            this.fillPopup(model);
                            this.itemClick(this.items.first());
                        });
                    }
                    internalValueSet(value) {
                        super.internalValueSet(value);
                        this.updatePicture(this.selectedCode);
                    }
                    instantiate(item, data) {
                        let relationType = data.that(cmp => cmp.Campo == "RelationName").Valor;
                        if (this.showRelationDescription)
                            item.text += " (" + relationType + ")";
                        let relationCode = data.that(cmp => cmp.Campo == "TipoRelación").Valor;
                        item.relationCode = relationCode;
                        item.displayText = item.text;
                        item.text = "";
                        item.add(new Web.EntityPicture(item.code));
                        item.addCtr(item.displayText, null, "span");
                    }
                    itemSelected(item) {
                        this.selectedRelationCode = item.relationCode;
                        this.updatePicture(item.code);
                    }
                    updatePicture(code) {
                        this.picture.relationID = code;
                        this.picture.visible = !!code;
                        this.mainField.estilos.definir("padding-left", !code ? "0px" : "24px");
                    }
                }
                Selectors.RelationSelector = RelationSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class LoginSelector extends Selectors.RelationSelector {
                    constructor() {
                        super();
                        this.className = "Solarium.Login, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.isComplex = false;
                        this.isRelation = true;
                        this.useWrapper = true;
                        this.showRelationDescription = false;
                    }
                    getFilters() {
                        let filters = super.getFilters();
                        filters.add({ PropertyName: "Interno", FilterValue: false, FilterType: "SBoolean" });
                        filters.add({ PropertyName: "Activo", FilterValue: true, FilterType: "SBoolean" });
                        filters.add({ PropertyName: "Externo", FilterValue: false, FilterType: "SBoolean" });
                        return filters;
                    }
                }
                Selectors.LoginSelector = LoginSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class SystemSelector extends Sol.Combo {
                    constructor() {
                        super();
                        this.extraSubscribers = new Sol.List();
                        this.disableChangeEventOnSetValue = true;
                        this.onValueModified.subscribe(() => this.notifyChange());
                        this.onSet.subscribe(() => this.notifySet());
                    }
                    notifySet() {
                        if (this.disableNotifications)
                            return;
                        this.container
                            .editors
                            .cast()
                            .where(edt => edt.isMultiCompany)
                            .forEach(edt => edt.setCompany(parseInt(this.selectedCode)));
                        this.extraSubscribers.forEach(e => e.setCompany(parseInt(this.selectedCode)));
                    }
                    notifyChange() {
                        if (this.disableNotifications)
                            return;
                        this.container
                            .editors
                            .cast()
                            .where(edt => edt.isMultiCompany)
                            .forEach(edt => edt.changeCompany(parseInt(this.selectedCode)));
                        this.extraSubscribers.forEach(e => e.changeCompany(parseInt(this.selectedCode)));
                    }
                }
                Selectors.SystemSelector = SystemSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class OptionalDetails extends Screens.DetailsScreen {
                constructor() {
                    super();
                    this.radios = new Sol.List();
                    this.spaces = new Sol.List();
                    this.loadSubtype = true;
                }
                get toolbarSpaceButtons() { return this.toolbar.controls.where(ctr => ctr["space"]); }
                get selectedOptionIndex() {
                    return this.radios.indexWhere(rd => rd.checked);
                }
                set selectedOptionIndex(index) {
                    this.radios.item(index).checked = true;
                    this.optionClick(this.radios.item(index));
                }
                loadData(data, responseModel = null) {
                    super.loadData(data, responseModel);
                    this.loadedClassName = responseModel.ClassName;
                    var selectedRadio = this.radios.that(r => r.data.model.ClassName == this.loadedClassName);
                    selectedRadio.checked = true;
                    this.selectedOption = selectedRadio.data;
                    this.spaces.forEach(s => s.visible = false);
                    this.selectedOption.space.visible = true;
                    this.saveButton.visible = false;
                    this.showToolbarButtons();
                    Sol.List.from(data).forEach(dt => {
                        var editor = this.selectedOption.fields.that(e => e.propertyName == dt.Campo);
                        if (!editor)
                            return;
                        editor.value = dt.Valor;
                    });
                }
                setEditorValue(propertyName, value) {
                    super.setEditorValue(propertyName, value);
                    this.spaces.forEach(sp => sp.setEditorValue(propertyName, value));
                }
                setModelReadonly() {
                    super.setModelReadonly();
                    const model = this.model;
                    Sol.List.from(model.Groups).forEach(g => Sol.List.from(g.Structure).forEach(fld => fld.ReadOnly = true));
                }
                build() {
                    this._model = this.model;
                    var model = this.model;
                    var options = Sol.List.from(model.Groups);
                    var optionsArea = new Sol.Control();
                    var radiosSpace = new Sol.Control();
                    var controlsSpace = new Sol.Control();
                    var screenState = this.code ? Screens.FormState.Edition : Screens.FormState.Insertion;
                    var optionIndex = 0;
                    options.forEach(option => {
                        var optionRadio = new Sol.RadioField();
                        var space = new Sol.EditorContainer();
                        var isChecked = optionIndex == model.DefaultOption;
                        optionRadio.caption = option.Title;
                        optionRadio.group = "optional_details";
                        optionRadio.css.add("option_detail_screen_radio");
                        optionRadio.checked = isChecked;
                        optionRadio.onClick = () => this.optionClick(optionRadio);
                        radiosSpace.add(optionRadio);
                        controlsSpace.add(space);
                        var components = Web.Editors.fillForm(option.Structure, space, this.toolbar, screenState, this.className, this.code, this.disableMinimizedControls, this.totalizationBarPosition);
                        space.visible = isChecked;
                        this.radios.add(optionRadio);
                        this.spaces.add(space);
                        components.fields.forEach(cp => cp["space"] = space);
                        this.labels.addMany(components.labels.toArray());
                        this.myForm.editors.addMany(components.fields);
                        optionRadio.data = {
                            model: option,
                            fields: components.fields,
                            space: space
                        };
                        if (isChecked)
                            this.selectedOption = optionRadio.data;
                        optionIndex++;
                    });
                    const defaultSelector = new Web.Components.DefaultValueSelector();
                    defaultSelector.autoSave = false;
                    defaultSelector.onSave = () => this.saveDefaultOption();
                    radiosSpace.add(defaultSelector);
                    optionsArea.add(radiosSpace);
                    optionsArea.add(controlsSpace);
                    super.build();
                    var position = 0;
                    var addressEditor = this.myForm.controls.that(ctr => ctr instanceof Web.Geo.AddressEditor);
                    if (addressEditor)
                        position = this.myForm.controls.indice(addressEditor) - 1;
                    this.myForm.controls.insert(position, optionsArea);
                    this.myForm.onValidate = () => this.validateSelectedOption();
                }
                getClassName() { return this.selectedOption.model.ClassName || super.getClassName(); }
                getValues() {
                    return super.getValues().concat(this.selectedOption
                        .fields
                        .where(cp => !cp.readonly)
                        .select(cp => ({ Campo: cp.propertyName, Valor: cp.value }))
                        .toArray());
                }
                optionClick(radio) {
                    this.spaces.forEach(s => s.visible = false);
                    this.selectedOption = radio.data;
                    this.selectedOption.space.visible = true;
                    this.showToolbarButtons();
                }
                validateSelectedOption() {
                    return {
                        success: this.myForm.validateEmptyFields(this.selectedOption.fields) &&
                            this.myForm.validateFields(this.selectedOption.fields)
                    };
                }
                saveDefaultOption() {
                    this.model.DefaultOption = this.selectedOptionIndex;
                    Web.System.exec("7pd0b4fg", "SaveUserDefault", {
                        classType: this.className,
                        propertyName: "option",
                        value: this.selectedOptionIndex.toString()
                    });
                }
                showToolbarButtons() {
                    this.toolbarSpaceButtons.forEach(ctr => ctr.visible = ctr["space"] == this.selectedOption.space);
                }
            }
            Screens.OptionalDetails = OptionalDetails;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let ServiceSelectorScrapBookOption;
            (function (ServiceSelectorScrapBookOption) {
                ServiceSelectorScrapBookOption[ServiceSelectorScrapBookOption["Department"] = 0] = "Department";
                ServiceSelectorScrapBookOption[ServiceSelectorScrapBookOption["Category"] = 1] = "Category";
            })(ServiceSelectorScrapBookOption = Screens.ServiceSelectorScrapBookOption || (Screens.ServiceSelectorScrapBookOption = {}));
            class ComplexServiceSelectorScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.className = "Solarium.Commercial.Service, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.categoriesButton = new Sol.Button();
                    this.categoryDisplay = new Sol.Control("span");
                    this.categoryNavigation = new Sol.Control();
                    this.departmentBook = new Web.Components.Scrapbook();
                    this.categoryBook = new Web.Components.Scrapbook();
                    this.container = new Sol.Control();
                    this.criteriaArea = new Web.Components.CollectionSelector();
                    this.exactMatchCheck = new Sol.Check();
                    this.list = new Web.Components.ListView();
                    this.searchButton = new Sol.Button();
                    this.searchField = new Sol.Field();
                    this.startView = Screens.ProductScreenViewMode.Search;
                }
                focus() {
                    this.searchField.foco();
                }
                build() {
                    super.build();
                    this.initializeTitle();
                    this.initializeToolbar();
                    this.initializeContainer();
                    this.initializeCriteriaArea();
                    this.initializeSearchField();
                    this.initializeList();
                    this.initializeScrapbooks();
                    setTimeout(() => this.list.search(), 300);
                }
                initializeToolbar() {
                    var toolbar = new Sol.Control();
                    toolbar.css.addMany(["sol_barra_herramientas", "sol_search_product_toolbox"]);
                    this.searchButton.text = Sol.Environment.resources.buscar;
                    this.searchButton.imageCode = "&#xf002;";
                    this.searchButton.type = Sol.ButtonType.Alternate;
                    this.searchButton.checked = this.startView == Screens.ProductScreenViewMode.Search;
                    this.searchButton.onChecked = () => this.showSearch();
                    toolbar.add(this.searchButton);
                    this.categoriesButton.text = Sol.Environment.resources.catalog;
                    this.categoriesButton.imageCode = "&#xf1b3;";
                    this.categoriesButton.type = Sol.ButtonType.Alternate;
                    this.categoriesButton.checked = this.startView == Screens.ProductScreenViewMode.Category;
                    if (this.startView == Screens.ProductScreenViewMode.Category)
                        this.showScrapbook();
                    this.categoriesButton.onChecked = () => this.showScrapbook();
                    toolbar.add(this.categoriesButton);
                    if (this.allowAddNew) {
                        const addNewButton = new Sol.Button();
                        addNewButton.text = this.fileScreenCaption;
                        addNewButton.imageCode = "&#xf187;";
                        addNewButton.onClick = () => Web.System.screens.openScreen("Registro", this.className);
                        toolbar.add(addNewButton);
                    }
                    this.add(toolbar);
                }
                initializeContainer() {
                    this.container.css.add("sol_search_product_screen");
                    this.add(this.container);
                }
                initializeTitle() {
                    var screenTitle = new Screens.ScreenTitle();
                    this.screenCaption = Sol.Environment.resources.select_product;
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                }
                initializeCriteriaArea() {
                    this.criteriaArea.allowAddNew = false;
                    this.criteriaArea.onChanged = () => {
                        if (!this.criteriaArea.isEmpty())
                            return;
                        this.selectedCategory = null;
                        this.search();
                    };
                    this.container.add(this.criteriaArea);
                }
                initializeSearchField() {
                    this.searchField.placeHolder = Sol.Environment.resources.typeToSearch;
                    this.searchField.css.add("sol_search_product_screen_search");
                    this.searchField.maxLength = 100;
                    this.searchField.autoWidth = false;
                    this.searchField.ancho = 500;
                    this.searchField.onKeyUp = e => {
                        if (e.key == "Enter")
                            this.list.select();
                        else if (e.key == "ArrowDown")
                            this.list.selectDown();
                        else if (e.key == "ArrowUp")
                            this.list.selectUp();
                        else
                            this.search();
                    };
                    this.container.add(this.searchField);
                    this.exactMatchCheck.estilos.agregar("display", "inline");
                    this.exactMatchCheck.caption = Sol.Environment.resources.exactSearch;
                    this.exactMatchCheck.onChange = () => this.search();
                    this.container.add(this.exactMatchCheck);
                }
                initializeList() {
                    this.list.className = "Solarium.Commercial.Service, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.list.selectable = true;
                    this.list.selectionEnabled = true;
                    this.list.pageSize = 50;
                    this.list.onInstantiateItem = e => this.instantiateItem(e);
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: true,
                            property: "Nombre",
                            priority: Web.Components.ListViewFieldPriority.High,
                            position: Web.Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "ServiceCode",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            caption: Sol.Environment.resources.main_pn,
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "Category$Color",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "Category$Nombre",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            cssClass: "sol_search_product_category",
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "Category$Department$Color",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "Category$Department$Nombre",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            cssClass: "sol_search_product_category",
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "Price",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right,
                            caption: Sol.Environment.resources.product_price,
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "EffectivePriceValue",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "ServiceUnit",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "ServiceUnit$Decimals",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "ServiceUnit$Nombre",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "ServiceUnit$Description",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right,
                            caption: Sol.Environment.resources.unit
                        }
                    ]);
                    this.list.onSelect = (data, code) => {
                        if (this.onServiceSelected)
                            this.onServiceSelected(data, code);
                    };
                    this.container.add(this.list);
                }
                initializeScrapbooks() {
                    const rootLink = new Sol.Button();
                    rootLink.type = Sol.ButtonType.Link;
                    rootLink.text = this.categoriesButton.text;
                    rootLink.onClick = () => this.loadBook(ServiceSelectorScrapBookOption.Department);
                    this.categoryNavigation.visible = false;
                    this.categoryNavigation.add(rootLink);
                    this.categoryDisplay.css.add("sol_search_product_category_display");
                    this.categoryDisplay.visible = false;
                    this.categoryNavigation.add(this.categoryDisplay);
                    this.add(this.categoryNavigation);
                    this.departmentBook.onItemSelected = e => this.selectDepartment(e);
                    this.add(this.departmentBook);
                    this.categoryBook.onItemSelected = e => this.selectCategory(e);
                    this.categoryBook.visible = false;
                    this.add(this.categoryBook);
                }
                instantiateItem(item) {
                    const catColor = item.getModelValue("Category$Color");
                    const catDisplay = item.getDisplay("Category$Nombre");
                    if (catColor != "#000000")
                        catDisplay.estilos.definir("border-left-color", catColor);
                    catDisplay.visible = !!item.getModelValue("Category$Nombre");
                    const depColor = item.getModelValue("Category$Department$Color");
                    const depDisplay = item.getDisplay("Category$Department$Nombre");
                    if (depColor != "#000000")
                        depDisplay.estilos.definir("border-left-color", depColor);
                    depDisplay.visible = !!item.getModelValue("Category$Department$Nombre");
                }
                loadBook(option, departmentFilter = 0) {
                    const className = option == ServiceSelectorScrapBookOption.Department ? "ServiceDepartment" : "ServiceCategory";
                    const targetBook = option == ServiceSelectorScrapBookOption.Department ? this.departmentBook : this.categoryBook;
                    this.departmentBook.visible = this.departmentBook == targetBook;
                    this.categoryBook.visible = this.categoryBook == targetBook;
                    this.categoryDisplay.visible = this.categoryBook == targetBook;
                    if (option == ServiceSelectorScrapBookOption.Department && this.departmentBook.pictures.hasItems())
                        return;
                    targetBook.controls.empty();
                    this.categoryNavigation.visible = true;
                    const data = {
                        className: "Solarium.Commercial." + className + ", Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 1,
                        rowCount: 1000,
                        filters: [],
                        sortProperty: "Nombre",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "Nombre", "Color"],
                        pageInfo: false
                    };
                    const filters = new Sol.List();
                    if (departmentFilter)
                        filters.add({
                            PropertyName: "Department",
                            FilterValue: departmentFilter,
                            FilterType: "SInteger"
                        });
                    data.filters = filters.toArray();
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        for (var row = 0; row < model.Data.length; row++) {
                            var rowData = Sol.List.from(model.Data[row]);
                            var code = model.Codes[row];
                            var description = rowData.that(cmp => cmp.Campo == "Nombre").Valor;
                            var color = rowData.that(cmp => cmp.Campo == "Color").Valor;
                            targetBook.addItem(code, description, color, null);
                        }
                    });
                }
                search() {
                    this.list.filters = [];
                    if (!this.searchField.isEmpty())
                        this.list.filters.push({
                            PropertyName: this.exactMatchCheck.checked ? "GeneralExactFilter" : "GeneralFilter",
                            FilterValue: this.searchField.value,
                            FilterType: ""
                        });
                    if (this.selectedCategory)
                        this.list.filters.push({
                            PropertyName: "Category",
                            FilterValue: this.selectedCategory,
                            FilterType: "Category"
                        });
                    this.list.clear();
                    this.list.search();
                }
                selectDepartment(item) {
                    this.departmentBook.visible = false;
                    this.categoryBook.visible = true;
                    this.loadBook(ServiceSelectorScrapBookOption.Category, item.code);
                    this.categoryDisplay.text = item.description;
                }
                selectCategory(item) {
                    this.selectedCategory = item.code;
                    this.criteriaArea.clear();
                    this.criteriaArea.options = [{
                            Code: item.code.toString(),
                            Description: item.description,
                            Color: item.color,
                            Checked: true
                        }];
                    this.criteriaArea.loadOptions();
                    this.showSearch();
                    this.search();
                }
                showScrapbook() {
                    this.searchButton.checked = false;
                    this.container.visible = false;
                    this.departmentBook.visible = true;
                    this.loadBook(ServiceSelectorScrapBookOption.Department);
                }
                showSearch() {
                    this.searchButton.checked = true;
                    this.categoriesButton.checked = false;
                    this.container.visible = true;
                    this.departmentBook.visible = false;
                    this.categoryBook.visible = false;
                    this.categoryNavigation.visible = false;
                }
            }
            Screens.ComplexServiceSelectorScreen = ComplexServiceSelectorScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class ComplexServiceSelector extends Selectors.BaseItemSelector {
                    constructor() {
                        super(...arguments);
                        this.className = "Solarium.Commercial.Service, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.propertyList = Sol.List.from(["ID", "ServiceCode", "Nombre", "Price", "EffectivePriceValue", "Category"]);
                    }
                    searchItem() {
                        var selectorScreen = new Web.Screens.ComplexServiceSelectorScreen();
                        selectorScreen.loadDescription = this.propertyList.contains("Description");
                        selectorScreen.allowAddNew = this.showFileButton;
                        selectorScreen.fileScreenCaption = Sol.Environment.resources.crear;
                        Web.System.screens.addScreen(selectorScreen);
                        Web.System.screens.showScreen(selectorScreen);
                        selectorScreen.onServiceSelected = (data, code) => this.itemSelected(data, code, true);
                    }
                    itemSelected(data, code, closeScreen) {
                        const collec = Sol.List.from(data);
                        this.selectedCode = code;
                        this.selectedName = collec.that(d => d.Campo == "Nombre").Valor;
                        this.selectedPartnumber = collec.that(d => d.Campo == "ServiceCode").Valor;
                        this.clearButton.visible = true;
                        this.editButton.enabled = true;
                        this.updatePriceField(parseFloat(collec.that(d => d.Campo == "EffectivePriceValue").Valor));
                        this.updateQuantityField({
                            UnitID: collec.that(d => d.Campo == "ServiceUnit").Valor,
                            Abbreviation: collec.that(d => d.Campo == "ServiceUnit$Nombre").Valor,
                            Decimals: collec.that(d => d.Campo == "ServiceUnit$Decimals").Valor,
                            Name: collec.that(d => d.Campo == "ServiceUnit$Description").Valor,
                            UnitType: Web.Commercial.UnitType.Service
                        });
                        this.onValueChanged();
                        if (closeScreen)
                            Web.System.screens.closeCurrentScreen();
                        this.onValueModified.invoke();
                    }
                }
                Selectors.ComplexServiceSelector = ComplexServiceSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("Service", model => {
    let selector = new Sol.Web.Components.Selectors.ComplexServiceSelector();
    selector.structure = model.Structure;
    selector.configuration = model.Configuration;
    return selector;
});
Sol.Web.Editors.registerFilter("Service", model => {
    let selector = new Sol.Web.Components.Selectors.ComplexServiceSelector();
    selector.hideButtonLabels = true;
    selector.showEditButton = false;
    selector.showFileButton = false;
    model.Settings = null;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class ServiceSelector extends Components.Selectors.Selector {
                    constructor() {
                        super();
                        this.historyButton = new Sol.Button();
                        this.onInstantiateItem = (i, d) => this.instantiateItem(i, d);
                        this.filterProperty = "GeneralFilter";
                        this.historyButton.enabled = false;
                        this.properties = ["ID",
                            this.displayProperty,
                            "Nombre",
                            "Category",
                            "Category$Nombre",
                            "Category$Color",
                            "Category$Department",
                            "Category$Department$Nombre",
                            "Category$Department$Color"];
                    }
                    instantiateItem(item, data) {
                        const name = data.that(cmp => cmp.Campo == "Nombre").Valor;
                        const nameLabel = new Sol.Control("strong");
                        nameLabel.text = name;
                        item.add(nameLabel);
                        item.text = "";
                        item.displayText = name;
                        item.add(new Sol.LineBreak());
                        const department = data.that(cmp => cmp.Campo == "Category$Department$Nombre").Valor;
                        const departmentColor = data.that(cmp => cmp.Campo == "Category$Department$Color").Valor;
                        const classDisplay = new Sol.ObjectDisplay();
                        classDisplay.value = { Campo: department, Valor: 0, Color: departmentColor == "#000000" ? null : departmentColor };
                        classDisplay.css.add("sol_service_selector_classe");
                        item.add(classDisplay);
                        const category = data.that(cmp => cmp.Campo == "Category$Nombre").Valor;
                        const categoryColor = data.that(cmp => cmp.Campo == "Category$Color").Valor;
                        const categoryDisplay = new Sol.ObjectDisplay();
                        categoryDisplay.value = { Campo: category, Valor: 0, Color: categoryColor == "#000000" ? null : categoryColor };
                        categoryDisplay.css.add("sol_service_selector_classe");
                        item.add(categoryDisplay);
                    }
                }
                Selectors.ServiceSelector = ServiceSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class VehicleSelector extends Components.Selectors.Selector {
                    constructor() {
                        super();
                        this.css.add("sol_vehicle_selector");
                        this.onInstantiateItem = (i, d) => this.instantiateItem(i, d);
                        this.filterProperty = "Plate";
                        this.displayProperty = "Plate";
                        this.properties = ["ID",
                            this.displayProperty,
                            "Year",
                            "Plate",
                            "Brand$Color",
                            "Brand$Nombre",
                            "ModelName"];
                        this.resultsOrder = "Plate";
                    }
                    instantiateItem(item, data) {
                        const plate = data.that(cmp => cmp.Campo == "Plate").Valor;
                        item.addCtr(plate, "sol_vehicle_selector_plate");
                        item.text = "";
                        item.displayText = plate;
                        const model = data.that(cmp => cmp.Campo == "ModelName").Valor;
                        item.addCtr(model, "sol_vehicle_selector_span", "span");
                        const year = data.that(cmp => cmp.Campo == "Year").Valor;
                        item.addCtr(year, "sol_vehicle_selector_span", "span");
                        const brand = data.that(cmp => cmp.Campo == "Brand$Nombre").Valor;
                        const brandColor = data.that(cmp => cmp.Campo == "Brand$Color").Valor;
                        const brandDisplay = new Sol.ObjectDisplay();
                        brandDisplay.value = { Campo: brand, Valor: 0, Color: brandColor == "#000000" ? null : brandColor };
                        brandDisplay.css.add("sol_vehicle_selector_brand");
                        item.add(brandDisplay);
                    }
                }
                Selectors.VehicleSelector = VehicleSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class PropertySelector extends Components.Selectors.Selector {
                    constructor() {
                        super();
                        this.css.add("sol_property_selector");
                        this.onInstantiateItem = (i, d) => this.instantiateItem(i, d);
                        this.filterProperty = "Nombre";
                        this.displayProperty = "Nombre";
                        this.properties = ["ID",
                            this.displayProperty,
                            "Nombre",
                            "Category$Nombre",
                            "Category$Color",
                            "Address$StreetNumber",
                            "Address$CityState"];
                        this.resultsOrder = "Nombre";
                    }
                    instantiateItem(item, data) {
                        item.css.add("sol_property_selector_li");
                        const nombre = data.that(cmp => cmp.Campo == "Nombre").Valor;
                        item.addCtr(nombre, "sol_property_selector_nombre");
                        item.text = "";
                        item.displayText = nombre;
                        const category = data.that(cmp => cmp.Campo == "Category$Nombre").Valor;
                        const categoryColor = data.that(cmp => cmp.Campo == "Category$Color").Valor;
                        const categoryDisplay = new Sol.ObjectDisplay();
                        categoryDisplay.value = { Campo: category, Valor: 0, Color: categoryColor == "#000000" ? null : categoryColor };
                        categoryDisplay.css.add("sol_property_selector_category");
                        item.add(categoryDisplay);
                        item.add(new Sol.LineBreak());
                        const address = data.that(cmp => cmp.Campo == "Address$StreetNumber").Valor;
                        item.addCtr(address, "sol_property_selector_street");
                        const city = data.that(cmp => cmp.Campo == "Address$CityState").Valor;
                        item.addCtr(city, "sol_property_selector_city");
                    }
                }
                Selectors.PropertySelector = PropertySelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class PriceField extends Sol.CurrencyField {
                    updateMargin() {
                        this.marginField.value = (this.numericValue - this.costField.numericValue) / this.costField.numericValue * 100;
                    }
                    updatePrice() {
                        this.numericValue = (this.costField.numericValue * this.marginField.value / 100) + this.costField.numericValue;
                    }
                    build() {
                        super.build();
                        this.marginField = this.container.editors.that(p => p.propertyName == "Margin");
                        this.costField = this.container.editors.that(p => p.propertyName == "Cost");
                        if (!this.marginField || !this.costField)
                            return;
                        this.marginField.onModified = () => this.updatePrice();
                        this.costField.onChange = () => this.updatePrice();
                        this.onChange = () => this.updateMargin();
                    }
                }
                Products.PriceField = PriceField;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PriceField", model => {
    const priceField = new Sol.Web.Commercial.Products.PriceField();
    priceField.allowChangeCurrency = model.AllowChangeCurrency;
    return priceField;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class NCMSelector extends Web.Components.Selectors.Selector {
                    constructor() {
                        super();
                        this.className = "Solarium.Commercial.NCM, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.properties = ["ID", this.displayProperty, "Category"];
                        this.isComplex = false;
                        this.onInstantiateItem = (i, d) => this.instantiateItem(i, d);
                    }
                    get value() { return this.selectedText; }
                    set value(value) { this.selectedText = value; }
                    instantiateItem(item, data) {
                        const category = data.that(cmp => cmp.Campo == "Category").Valor;
                        const label = new Sol.Control();
                        label.css.add("ncm_selector_category");
                        label.text = category;
                        item.controls.insert(0, label);
                    }
                }
                Products.NCMSelector = NCMSelector;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("NCMSelector", () => new Sol.Web.Commercial.Products.NCMSelector());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SpecContainer extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.code = 0;
                }
                build() {
                    super.build();
                    this.css.add("sol_detalles_wrapper");
                    var label = new Sol.Label();
                    label.text = this.caption;
                    label.editor = this.editor;
                    label.largeDescription = this.largeDescription;
                    this.add(label);
                    this.add(this.editor.toControl());
                }
                get stringValue() {
                    return this.editor instanceof Sol.Field ? this.editor.value : this.editor.value.Campo;
                }
                setValor(v) {
                    this.editor.value = v;
                }
            }
            Components.SpecContainer = SpecContainer;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SpecificationsEditor extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.editors = new Sol.List();
                    this.isComplex = false;
                    this.keyPropertyName = "Name";
                    this.valuePropertyName = "SpecificationValue";
                    this._isLoaded = false;
                }
                get properties() { return this.controls.where(ctr => !(ctr instanceof Sol.Button)).cast(); }
                get isLoaded() { return this._isLoaded; }
                set isLoaded(v) {
                    this._isLoaded = v;
                    if (this.waitingValue)
                        this.loadValue(this.waitingValue);
                }
                get value() {
                    return this.properties.select(spec => [
                        { Campo: "ID", Valor: spec.code },
                        { Campo: this.keyPropertyName, Valor: spec.caption },
                        { Campo: this.valuePropertyName, Valor: spec.stringValue }
                    ]).toArray();
                }
                set value(v) {
                    if (!v || v.length == 0)
                        return;
                    if (this.isLoaded)
                        this.loadValue(v);
                    else
                        this.waitingValue = v;
                }
                setFields(fields) {
                    this.controls.empty();
                    this.editors.empty();
                    fields.forEach(s => {
                        var property = new Components.SpecContainer();
                        property.caption = s.Name;
                        property.largeDescription = s.FillTip;
                        if (s.Options && s.Options.length > 1) {
                            var combo = new Sol.Combo();
                            property.editor = combo;
                            combo.addBlankItem();
                            combo.addItems(Sol.List.from(s.Options).select(o => ({ Campo: o, Valor: o })).toArray());
                        }
                        else {
                            let field = new Sol.Field();
                            field.maxLength = 85;
                            property.editor = field;
                        }
                        this.add(property);
                        this.editors.add(property.editor);
                    });
                    if (this.nameSuggestionEnabled && fields.hasItems()) {
                        var fillNameButton = new Sol.Button();
                        fillNameButton.imageCode = "&#xf0d0;";
                        fillNameButton.css.add("sol_products_specifications_button");
                        fillNameButton.tip = Sol.Environment.resources.button_complete_name_tip;
                        fillNameButton.onClick = () => this.completeName();
                        this.add(fillNameButton);
                    }
                    this.isLoaded = true;
                }
                toControl() { return this; }
                completeName() {
                    var fieldName = this.container.editors.that(cp => cp.propertyName == "Nombre");
                    var fieldCategory = this.container.editors.that(cp => cp.propertyName == "Category");
                    var fieldBrand = this.container.editors.that(cp => cp.propertyName == "Brand");
                    var name = this.editors
                        .select(edt => edt instanceof Sol.Field ? edt.value : edt.value.Campo)
                        .toArray().join(" ");
                    if (fieldBrand && !fieldBrand.isEmpty())
                        name = fieldBrand.value.Campo + " " + name;
                    if (fieldCategory && !fieldCategory.isEmpty())
                        name = fieldCategory.value.Campo + " " + name;
                    fieldName.value = name;
                }
                loadValue(v) {
                    for (var i of v) {
                        var data = Sol.List.from(i);
                        var keyModel = data.that(d => d.Campo == this.keyPropertyName);
                        var valueModel = data.that(d => d.Campo == this.valuePropertyName);
                        var idModel = data.that(d => d.Campo == "ID");
                        var property = this.properties.that(p => p.caption == keyModel.Valor);
                        if (!property) {
                            var extraProperty = new Components.SpecContainer();
                            extraProperty.code = idModel.Valor;
                            extraProperty.caption = keyModel.Valor;
                            extraProperty.editor = new Sol.Field();
                            extraProperty.editor.value = valueModel.Valor;
                            this.controls.insert(this.controls.count - 1, extraProperty);
                        }
                        else {
                            property.code = idModel.Valor;
                            property.caption = keyModel.Valor;
                            property.setValor(valueModel.Valor);
                        }
                    }
                    this.waitingValue = null;
                }
                isEmpty() { return false; }
                foco() { }
                clear() { }
                validate() { return null; }
            }
            Components.SpecificationsEditor = SpecificationsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class BatchProposalSelector extends Sol.Combo {
                    build() {
                        this.disableChangeEventOnSetValue = true;
                        this.onValueModified.subscribe(() => this.batchChanged());
                        this.onSet.subscribe(() => this.batchChanged());
                        super.build();
                    }
                    batchChanged() {
                        if (!this.selectedCode)
                            return;
                        Web.System.exec("spoe34skdeo", "GetItemsFromBatch", { batchID: this.selectedCode }, response => this.container.getEditor("Items").value = response.Items);
                    }
                }
                Selectors.BatchProposalSelector = BatchProposalSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("BatchProposal", model => {
    const batchProposalEditor = new Sol.Web.Components.Selectors.BatchProposalSelector();
    batchProposalEditor.loadOptions(model.Options);
    return batchProposalEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class HistoryScreenBase extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.content = new Sol.Control();
                    this.currentPage = 1;
                    this.emptyMessage = new Sol.ScreenMessage();
                    this.grid = new Web.Components.Grid();
                    this.gridRowCount = 15;
                    this.interval = new Sol.IntervalCombo();
                    this.moreResultsButton = new Sol.Button();
                    this.searchButton = new Sol.Button();
                    this.title = new Screens.ScreenTitle();
                    this.add(this.title);
                    this.content.css.add("sol_history_screen");
                    this.add(this.content);
                    this.interval.value = { Opcion: Sol.IntervalType.ThisWeek };
                    this.content.add(this.interval);
                    this.searchButton.text = Sol.Environment.resources.buscar;
                    this.searchButton.onClick = () => this.search();
                    this.content.add(this.searchButton);
                    this.emptyMessage.type = Sol.MessageType.Information;
                    this.emptyMessage.caption = Sol.Environment.resources.no_encontrado;
                    this.emptyMessage.visible = false;
                    this.content.add(this.emptyMessage);
                }
                build() {
                    super.build();
                    this.title.text = this.screenCaption;
                    this.getObjectDetails();
                    this.initializeGrid();
                    this.initializeBackButton();
                    this.initializeMoreResultsButton();
                    this.search();
                }
                getObjectDetails() {
                    if (this.code)
                        return;
                    var detailsScreen = Web.System.screens.screens.where(scr => scr instanceof Screens.DetailsScreen).last();
                    this.code = detailsScreen.code;
                    this.className = detailsScreen.className;
                }
                initializeGrid() {
                    this.configureColumns();
                    this.grid.showChecks = false;
                    this.grid.fixedRows = false;
                    this.grid.buildHeader();
                    this.content.add(this.grid);
                }
                initializeBackButton() {
                    const backButton = new Sol.Button();
                    backButton.text = Sol.Environment.resources.back;
                    backButton.onClick = () => Web.System.screens.closeCurrentScreen();
                    this.content.add(backButton);
                }
                initializeMoreResultsButton() {
                    this.moreResultsButton.text = Sol.Environment.resources.more_results;
                    this.moreResultsButton.enabled = false;
                    this.moreResultsButton.onClick = () => {
                        this.currentPage++;
                        this.search();
                    };
                    this.content.add(this.moreResultsButton);
                }
                search() {
                    Web.System.exec(this.manager, this.methodName, this.getSearchData(), e => {
                        if (this.currentPage == 1)
                            this.grid.clear();
                        const changes = Sol.List.from(e.Changes);
                        changes.forEach(row => this.grid.addRow(row));
                        this.emptyMessage.visible = this.currentPage == 1 && !changes.hasItems();
                        this.grid.generateBlankRows(Math.max(0, this.gridRowCount - changes.count));
                        this.moreResultsButton.enabled = changes.count == this.gridRowCount;
                    });
                }
            }
            Screens.HistoryScreenBase = HistoryScreenBase;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class HistoryScreen extends Screens.HistoryScreenBase {
                constructor() {
                    super(...arguments);
                    this.manager = "i3n48smak";
                    this.methodName = "Search";
                }
                configureColumns() { this.grid.columns = this.columns; }
                getSearchData() { }
                search() {
                    let request = {
                        className: this.className,
                        currentPage: this.currentPage,
                        rowCount: this.gridRowCount,
                        filters: [{
                                PropertyName: this.propertyName,
                                FilterValue: this.code,
                                FilterType: "SInteger"
                            }],
                        sortProperty: this.sortPropertyName,
                        sortOrder: Web.Ordering.descending,
                        properties: this.columns.select(c => c.PropertyName).toArray(),
                        pageInfo: false
                    };
                    Web.System.exec(this.manager, this.methodName, request, e => {
                        if (this.currentPage == 1)
                            this.grid.clear();
                        let changes = Sol.List.from(e.Data);
                        changes.forEach(row => this.grid.addRow(row));
                        this.emptyMessage.visible = this.currentPage == 1 && !changes.hasItems();
                        this.grid.generateBlankRows(Math.max(0, this.gridRowCount - changes.count));
                        this.moreResultsButton.enabled = changes.count == this.gridRowCount;
                    });
                }
            }
            Screens.HistoryScreen = HistoryScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class MarketingLeadSelector extends Selectors.RelationBaseSelector {
                    constructor() {
                        super();
                        this.historyButton = new Sol.Button();
                        this.forceSubtype = true;
                        this.onInstantiateItem = (i, d) => this.instantiateItem(i, d);
                        this.filterProperty = "GeneralFilter";
                        this.hideFollowUpButton = true;
                        this.properties = ["ID",
                            this.displayProperty,
                            "EntidadRelacionada$NúmeroDocumento",
                            "EntidadRelacionada$Email",
                            "EntidadRelacionada$Email2",
                            "EntidadRelacionada$PhoneList",
                            "EntidadRelacionada$Dirección$City",
                            "EntidadRelacionada$Dirección$Estado$Sigla"];
                    }
                    addExtraButtons() {
                        if (this.hideHistoryButton)
                            return;
                        this.historyButton.text = Sol.Environment.resources.historyLabel;
                        this.historyButton.imageCode = "&#xf1da;";
                        this.historyButton.onClick = () => this.openHistory();
                        this.add(this.historyButton);
                    }
                    enableButtons(value) {
                        super.enableButtons(value);
                        this.historyButton.enabled = value;
                    }
                    instantiateDetailsScreen() { return new Web.Screens.OptionalDetails(); }
                    instantiateItem(item, data) {
                        const name = data.that(cmp => cmp.Campo == "EntidadRelacionada$Nombre").Valor;
                        const nameLabel = new Sol.Control("strong");
                        nameLabel.text = name;
                        item.add(nameLabel);
                        item.text = "";
                        item.displayText = name;
                        const taxId = data.that(cmp => cmp.Campo == "EntidadRelacionada$NúmeroDocumento").Valor;
                        const taxIdLabel = new Sol.Control("span");
                        taxIdLabel.css.add("customer_selector_taxid");
                        taxIdLabel.text = taxId;
                        item.add(taxIdLabel);
                        const city = data.that(cmp => cmp.Campo == "EntidadRelacionada$Dirección$City").Valor;
                        const state = data.that(cmp => cmp.Campo == "EntidadRelacionada$Dirección$Estado$Sigla").Valor;
                        const cityLabel = new Sol.Control("span");
                        cityLabel.css.add("customer_selector_city");
                        cityLabel.text = city;
                        if (city && state)
                            cityLabel.text += "-" + state;
                        item.add(cityLabel);
                    }
                    openHistory() {
                        let screen = new Web.Screens.HistoryScreen();
                        screen.screenCaption = "Histórico - " + this.selectedText;
                        screen.code = this.selectedCode;
                        screen.propertyName = "Lead";
                        screen.sortPropertyName = "ProspectingDate";
                        screen.className = "Solarium.Marketing.Prospecting, Solarium.Marketing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        screen.columns = Sol.List.from([
                            { Title: "Cliente", DataType: "Cliente", PropertyName: "Client", ShowTitle: true, Visible: true, Alignment: Sol.Alignment.Left },
                            { Title: "Data", DataType: "SDate", Alignment: Sol.Alignment.Center, PropertyName: "ProspectingDate", ShowTitle: true, Visible: true },
                            { Title: "Status", DataType: "Display", PropertyName: "ProspectingStatus", ShowTitle: true, Visible: true, Alignment: Sol.Alignment.Left },
                            { Title: "Evento", DataType: "EventType", PropertyName: "EventType", ShowTitle: true, Visible: true, Alignment: Sol.Alignment.Left },
                            { Title: "Consultor", DataType: "Consultant", PropertyName: "Consultant", ShowTitle: true, Visible: true, Alignment: Sol.Alignment.Left, Drawer: "EntityDrawer" },
                            { Title: "Resultado", DataType: "ProspectingResult", PropertyName: "Result", ShowTitle: true, Visible: true, Alignment: Sol.Alignment.Left }
                        ]);
                        Web.System.screens.addScreen(screen);
                        Web.System.screens.showScreen(screen);
                    }
                }
                Selectors.MarketingLeadSelector = MarketingLeadSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("MarketingLeadSelector", model => {
    let selector = new Sol.Web.Components.Selectors.MarketingLeadSelector();
    selector.className = model.DataTypeFullName;
    selector.allowCreateNew = true;
    selector.allowEdit = true;
    selector.configuration = model.Configuration;
    selector.estructura = model.Structure;
    selector.etiqueta = model.Title;
    selector.miInfo = model;
    return selector;
});
Sol.Web.Editors.registerFilter("MarketingLeadSelector", model => {
    let filter = new Sol.Web.Components.Selectors.MarketingLeadSelector();
    filter.className = model.ClassName;
    filter.etiqueta = model.Caption;
    filter.allowEdit = false;
    filter.hideHistoryButton = true;
    if (model.Settings)
        model.Settings["allowEdit"] = undefined;
    return filter;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ModulesEditor extends Sol.CheckList {
                constructor() {
                    super();
                    this.css.add("sol_modules_editor");
                }
                createCheck(option, groupLabel) {
                    let model = option;
                    let check = super.createCheck(option, groupLabel);
                    let picture = new Sol.Control("img");
                    if (this.showModuleIcons) {
                        picture.atributos.agregar("src", Sol.Environment.systemUrl + "/picture/" + model.ModulePicture);
                        check.controls.insert(0, picture);
                    }
                    check.addCtr(model.ExtendedDescription, null, "p");
                    return check;
                }
            }
            Components.ModulesEditor = ModulesEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ModulesEditor", () => new Sol.Web.Components.ModulesEditor());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let BirthdateComboType;
            (function (BirthdateComboType) {
                BirthdateComboType[BirthdateComboType["None"] = 0] = "None";
                BirthdateComboType[BirthdateComboType["Month"] = 1] = "Month";
                BirthdateComboType[BirthdateComboType["Age"] = 2] = "Age";
                BirthdateComboType[BirthdateComboType["Interval"] = 3] = "Interval";
            })(BirthdateComboType = Components.BirthdateComboType || (Components.BirthdateComboType = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class BirthdateComboOption extends Sol.Control {
                constructor() {
                    super("li");
                    this.captionControl = new Sol.Control("span");
                    this.checkControl = new Sol.Control("span");
                    this.checkControl.css.add("sol_combo_periodo_check_area");
                    this.captionControl.css.add("sol_combo_periodo_caption");
                    this.add(this.checkControl);
                    this.add(this.captionControl);
                }
                get caption() { return this.captionControl.text; }
                set caption(v) { this.captionControl.text = v; }
                get checked() { return this._checked; }
                set checked(v) {
                    this._checked = v;
                    this.checkControl.text = v ? "&#xf00c;" : "";
                }
                getValue() {
                    return {
                        Option: this.option,
                        Month: this.birthdateMonth,
                        MinAge: this.minAge,
                        MaxAge: this.maxAge,
                        MinDayInterval: this.minDayInterval,
                        MaxDayInterval: this.maxDayInterval,
                        MinMonthInterval: this.minMonthInterval,
                        MaxMonthInterval: this.maxMonthInterval
                    };
                }
            }
            Components.BirthdateComboOption = BirthdateComboOption;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class BirthdateCombo extends Sol.Control {
                constructor() {
                    super();
                    this.mainField = new Sol.Control("span");
                    this.popup = new Sol.Popup();
                    this.noneOption = new Components.BirthdateComboOption();
                    this.options = new Sol.List();
                    this.monthField = new Sol.MonthField();
                    this.minAgeField = new Sol.IntegerField();
                    this.maxAgeField = new Sol.IntegerField();
                    this.minDayField = new Sol.IntegerField();
                    this.minMonthField = new Sol.IntegerField();
                    this.maxDayField = new Sol.IntegerField();
                    this.maxMonthField = new Sol.IntegerField();
                    this.css.addMany(["sol_combo_periodo", "sol_birthdate_combo"]);
                    this.mainField.css.add("sol_campo");
                    this.mainField.text = Sol.Environment.resources.cualquier;
                    this.mainField.onClick = () => this.popup.visible = !this.popup.visible;
                    this.add(this.mainField);
                    this.popup.visible = false;
                    this.add(this.popup);
                    this.createNoneOption();
                    this.createBirthdateMonthOption();
                    this.createBirthdateByAgeIntervalOption();
                    this.createBirthdateByDateIntervalOption();
                }
                clear() {
                    this.selectedOption = this.noneOption;
                    this.mainField.text = this.selectedOption.caption;
                }
                foco() {
                    throw new Error("Method not implemented.");
                }
                isEmpty() {
                    return this.selectedOption.option == Components.BirthdateComboType.None;
                }
                toControl() { return this; }
                validate() {
                    if (this.selectedOption.option == Components.BirthdateComboType.Age && this.minAgeField.numericValue > this.maxAgeField.numericValue)
                        return Sol.Environment.resources.invalidAgeCombo;
                    if (this.selectedOption.option == Components.BirthdateComboType.Interval && (this.maxDayField.numericValue > 31 || this.minDayField.numericValue > 31
                        || this.maxDayField.numericValue < 1 || this.minDayField.numericValue < 1))
                        return Sol.Environment.resources.invalidDayBirthdateCombo;
                    if (this.selectedOption.option == Components.BirthdateComboType.Interval && (this.maxMonthField.numericValue > 12 || this.maxMonthField.numericValue < 1))
                        return Sol.Environment.resources.invalidMonthBirthdateCombo;
                    if (this.selectedOption.option == Components.BirthdateComboType.Interval &&
                        (this.minDayField.numericValue > this.maxDayField.numericValue && this.minMonthField.numericValue < this.maxMonthField.numericValue))
                        return Sol.Environment.resources.invalidIntervalBirthdateCombo;
                    return null;
                }
                createNoneOption() {
                    this.noneOption.caption = Sol.Environment.resources.cualquier;
                    this.noneOption.onClick = () => this.itemClick(this.noneOption);
                    this.noneOption.option = Components.BirthdateComboType.None;
                    this.noneOption.checked = true;
                    this.popup.add(this.noneOption);
                    this.selectedOption = this.noneOption;
                    this.options.add(this.noneOption);
                }
                createBirthdateMonthOption() {
                    var birthdateMonthOption = new Components.BirthdateComboOption();
                    birthdateMonthOption.caption = Sol.Environment.resources.mes;
                    birthdateMonthOption.onClick = () => this.itemClick(birthdateMonthOption);
                    birthdateMonthOption.option = Components.BirthdateComboType.Month;
                    this.popup.add(birthdateMonthOption);
                    this.options.add(birthdateMonthOption);
                    this.monthField.onChange = () => {
                        this.updateText();
                        birthdateMonthOption.birthdateMonth = this.monthField.selectedCode;
                    };
                    this.monthField.onClick = () => this.monthField.clickEvent.stopPropagation();
                    birthdateMonthOption.birthdateMonth = this.monthField.selectedCode;
                    birthdateMonthOption.add(this.monthField);
                }
                createBirthdateByAgeIntervalOption() {
                    var birthdateByAgeInterval = new Components.BirthdateComboOption();
                    birthdateByAgeInterval.caption = Sol.Environment.resources.byAgeBirthdateCombo;
                    birthdateByAgeInterval.onClick = () => this.itemClick(birthdateByAgeInterval);
                    birthdateByAgeInterval.option = Components.BirthdateComboType.Age;
                    this.popup.add(birthdateByAgeInterval);
                    this.options.add(birthdateByAgeInterval);
                    this.minAgeField.onChange = () => birthdateByAgeInterval.minAge = this.minAgeField.numericValue;
                    this.minAgeField.onClick = () => this.minAgeField.clickEvent.stopPropagation();
                    this.maxAgeField.maxValue = 120;
                    this.maxAgeField.onChange = () => birthdateByAgeInterval.maxAge = this.maxAgeField.numericValue;
                    this.maxAgeField.onClick = () => this.maxAgeField.clickEvent.stopPropagation();
                    birthdateByAgeInterval.maxAge = this.maxAgeField.numericValue;
                    birthdateByAgeInterval.add(this.minAgeField);
                    birthdateByAgeInterval.add(this.createTxt(Sol.Environment.resources.and));
                    birthdateByAgeInterval.minAge = this.minAgeField.numericValue;
                    birthdateByAgeInterval.add(this.maxAgeField);
                    birthdateByAgeInterval.add(this.createTxt(Sol.Environment.resources.years));
                }
                createBirthdateByDateIntervalOption() {
                    var birthdateByDateInterval = new Components.BirthdateComboOption();
                    birthdateByDateInterval.caption = Sol.Environment.resources.byIntervalBirthdateCombo;
                    birthdateByDateInterval.css.add("sol_birthdate_combo_interval");
                    birthdateByDateInterval.onClick = () => this.itemClick(birthdateByDateInterval);
                    birthdateByDateInterval.option = Components.BirthdateComboType.Interval;
                    this.popup.add(birthdateByDateInterval);
                    this.options.add(birthdateByDateInterval);
                    this.minDayField.maxValue = 31;
                    this.minDayField.value = "1";
                    this.minDayField.onChange = () => birthdateByDateInterval.minDayInterval = this.minDayField.numericValue;
                    this.minDayField.onClick = () => this.minDayField.clickEvent.stopPropagation();
                    this.minMonthField.maxValue = 12;
                    this.minMonthField.value = "1";
                    this.minMonthField.onChange = () => birthdateByDateInterval.minMonthInterval = this.minMonthField.numericValue;
                    this.minMonthField.onClick = () => this.minMonthField.clickEvent.stopPropagation();
                    this.maxDayField.maxValue = 31;
                    this.maxDayField.value = "31";
                    this.maxDayField.onChange = () => birthdateByDateInterval.maxDayInterval = this.maxDayField.numericValue;
                    this.maxDayField.onClick = () => this.maxDayField.clickEvent.stopPropagation();
                    this.maxMonthField.maxValue = 12;
                    this.maxMonthField.value = "12";
                    this.maxMonthField.onChange = () => birthdateByDateInterval.maxMonthInterval = this.maxMonthField.numericValue;
                    this.maxMonthField.onClick = () => this.maxMonthField.clickEvent.stopPropagation();
                    birthdateByDateInterval.minDayInterval = this.minDayField.numericValue;
                    birthdateByDateInterval.add(this.minDayField);
                    birthdateByDateInterval.add(this.createTxt("/"));
                    birthdateByDateInterval.minMonthInterval = this.minMonthField.numericValue;
                    birthdateByDateInterval.add(this.minMonthField);
                    birthdateByDateInterval.add(this.createTxt(Sol.Environment.resources.to));
                    birthdateByDateInterval.maxDayInterval = this.maxDayField.numericValue;
                    birthdateByDateInterval.add(this.maxDayField);
                    birthdateByDateInterval.add(this.createTxt("/"));
                    birthdateByDateInterval.maxMonthInterval = this.maxMonthField.numericValue;
                    birthdateByDateInterval.add(this.maxMonthField);
                }
                itemClick(option) {
                    this.selectedOption = option;
                    this.options.forEach(opt => opt.checked = false);
                    option.checked = true;
                    this.updateText();
                    this.popup.hide();
                    if (this.onModified)
                        this.onModified(this);
                }
                get value() {
                    return this.selectedOption.getValue();
                }
                set value(v) {
                    this.selectedOption = this.options.item(v.Option);
                    if (v.Month)
                        this.selectedOption.birthdateMonth = v.Month;
                    if (v.MinAge)
                        this.selectedOption.minAge = v.MinAge;
                    if (v.MaxAge)
                        this.selectedOption.maxAge = v.MaxAge;
                    if (v.MinDayInterval)
                        this.selectedOption.minDayInterval = v.MinDayInterval;
                    if (v.MaxDayInterval)
                        this.selectedOption.maxDayInterval = v.MaxDayInterval;
                    if (v.MinMonthInterval)
                        this.selectedOption.minMonthInterval = v.MinMonthInterval;
                    if (v.MaxMonthInterval)
                        this.selectedOption.maxMonthInterval = v.MaxMonthInterval;
                    this.updateText();
                }
                createTxt(text) {
                    const span = new Sol.Control("span");
                    span.text = text;
                    return span;
                }
                updateText() {
                    if (this.selectedOption.option == Components.BirthdateComboType.Month)
                        this.mainField.text = this.monthOptionText();
                    else if (this.selectedOption.option == Components.BirthdateComboType.Age)
                        this.mainField.text = this.ageOptionText();
                    else if (this.selectedOption.option == Components.BirthdateComboType.Interval)
                        this.mainField.text = this.intervalOptionText();
                    else
                        this.mainField.text = this.selectedOption.caption;
                }
                monthOptionText() {
                    return Sol.Environment.resources.periodo_de + " " + this.monthField.selectedItem.text;
                }
                ageOptionText() {
                    return this.selectedOption.caption + " " + this.selectedOption.minAge + " "
                        + Sol.Environment.resources.and + " " + this.selectedOption.maxAge + " " + Sol.Environment.resources.years;
                }
                intervalOptionText() {
                    return this.selectedOption.caption + " " + this.selectedOption.minDayInterval + "/" + this.selectedOption.minMonthInterval + " "
                        + Sol.Environment.resources.to + " " + this.selectedOption.maxDayInterval + "/" + this.selectedOption.maxMonthInterval;
                }
            }
            Components.BirthdateCombo = BirthdateCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ClientAttendance extends Sol.Control {
                constructor() { super(); }
                build() {
                    super.build();
                    this.css.addMany(["sol_dashboard_tile", "sol_dashboard_client_attendance"]);
                    const buttonList = new Sol.List();
                    const title = new Sol.Control();
                    title.css.add("sol_dashboard_tile_title");
                    title.text = "Atendimento a clientes";
                    this.add(title);
                    const customerLabel = new Sol.Label();
                    customerLabel.text = "Pesquise aqui o cliente por nome, documento, e-mail ou telefone.";
                    this.add(customerLabel);
                    const customerSelector = new Web.Commercial.Customers.CustomerSelector();
                    customerSelector.contextClass = "Solarium.Commercial.Venta, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    customerSelector.onFiltering = () => Sol.List.from([{
                            PropertyName: "GlobalFilter",
                            FilterType: "SBoolean",
                            FilterValue: true
                        }]);
                    this.add(customerSelector);
                    this.controls.addMany(Sol.List.from(this.configuration).select(tool => {
                        const crmButton = new Sol.Button();
                        crmButton.data = tool;
                        crmButton.text = Sol.Environment.resources.start + " " + tool.Caption;
                        crmButton.onClick = () => Web.System.screens.openScreen(tool.Screen, tool.ClassName, null, null, null, s => setTimeout(() => {
                            const screen = s;
                            screen.addNew();
                            if (customerSelector.selectedCode)
                                screen.details.editors.that(e => e.propertyName == "Destinatario").value = customerSelector.selectedCode;
                        }, 300));
                        buttonList.add(crmButton);
                        return crmButton;
                    }));
                }
            }
            Components.ClientAttendance = ClientAttendance;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class EstimateGadget extends Sol.Control {
                constructor() {
                    super();
                    this.dailyEstimateAmount = new Sol.CurrencyField();
                    this.weeklyEstimateAmount = new Sol.CurrencyField();
                    this.weeklyEstimateButton = new Sol.Button();
                    this.dailyEstimateButton = new Sol.Button();
                    this.css.addMany(["sol_dashboard_tile", "sol_dashboard_estimate_gadget"]);
                    const title = new Sol.Control();
                    title.css.add("sol_dashboard_tile_title");
                    title.text = "Cantadas";
                    this.add(title);
                    const dailyEstimateLabel = new Sol.Label();
                    dailyEstimateLabel.text = "Diária:";
                    this.add(dailyEstimateLabel);
                    this.add(this.dailyEstimateAmount);
                    this.dailyEstimateButton.text = "Salvar";
                    this.dailyEstimateButton.onClick = () => this.saveDailyEstimate();
                    this.add(this.dailyEstimateButton);
                    const weeklyEstimateLabel = new Sol.Label();
                    weeklyEstimateLabel.text = "Semanal:";
                    this.add(weeklyEstimateLabel);
                    this.add(this.weeklyEstimateAmount);
                    this.weeklyEstimateButton.text = "Salvar";
                    this.weeklyEstimateButton.onClick = () => this.saveWeeklyEstimate();
                    this.add(this.weeklyEstimateButton);
                    const warningTime = new Sol.Label();
                    warningTime.text = "As cantadas podem ser lançadas até às 9h30.";
                    this.add(warningTime);
                    const warningEdit = new Sol.Label();
                    warningEdit.text = "Não é possível alterar as cantadas após o lançamento.";
                    this.add(warningEdit);
                    this.loadEstimates();
                }
                loadEstimates() {
                    Web.System.exec("7985bddjh", "LoadTodayEstimates", {
                        credential: Sol.Environment.credential.export()
                    }, e => {
                        if (e.DailyAmount) {
                            this.dailyEstimateAmount.value = e.DailyAmount;
                            this.dailyEstimateAmount.readonly = true;
                            this.dailyEstimateButton.enabled = false;
                        }
                        if (e.WeeklyAmount) {
                            this.weeklyEstimateAmount.value = e.WeeklyAmount;
                            this.weeklyEstimateAmount.readonly = true;
                            this.weeklyEstimateButton.enabled = false;
                        }
                    }, null);
                }
                saveWeeklyEstimate() {
                    Web.System.exec("7985bddjh", "SaveWeeklyEstimate", {
                        credential: Sol.Environment.credential.export(),
                        amount: this.weeklyEstimateAmount.numericValue
                    }, e => {
                        if (e.Fail) {
                            alert(e.ErrorMessage);
                            this.weeklyEstimateAmount.clear();
                            return;
                        }
                        alert("Cantada semanal salva com sucesso :)");
                        this.weeklyEstimateAmount.readonly = true;
                        this.weeklyEstimateButton.enabled = false;
                    }, null);
                }
                saveDailyEstimate() {
                    Web.System.exec("7985bddjh", "SaveDailyEstimate", {
                        credential: Sol.Environment.credential.export(),
                        amount: this.dailyEstimateAmount.numericValue
                    }, e => {
                        if (e.Fail) {
                            alert(e.ErrorMessage);
                            this.dailyEstimateAmount.clear();
                            return;
                        }
                        alert("Cantada diária salva com sucesso :)");
                        this.dailyEstimateAmount.readonly = true;
                        this.dailyEstimateButton.enabled = false;
                    }, null);
                }
            }
            Components.EstimateGadget = EstimateGadget;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var PNCP;
            (function (PNCP) {
                class BudgetForecastPNCPLogEditor extends Sol.Control {
                    constructor() {
                        super("ul");
                        this.css.add("sol_lic_winners");
                    }
                    refresh() {
                        Web.System.exec("spoe33slert", "GetForecastLogs", "", models => {
                            this.controls.empty();
                            const modelList = Sol.List.from(models);
                            const table = new Sol.Control("table");
                            const header = table.addCtr(null, null, "tr");
                            header.addCtr("Data", "sol_lic_winners_center", "th");
                            header.addCtr("Ano do PCA", "sol_lic_winners_center", "th");
                            header.addCtr("Unidade", "sol_lic_winners_center", "th");
                            header.addCtr("Responsável", "sol_lic_winners_center", "th");
                            header.addCtr("Mensagem", "pncp_pca_log_message", "th");
                            header.addCtr("Enviado", "sol_lic_winners_center", "th");
                            table.addMany(modelList.select(i => {
                                const row = new Sol.Control("tr");
                                row.addCtr(i.Date, "sol_lic_winners_center", "td");
                                row.addCtr(i.Year, "sol_lic_winners_center", "td");
                                row.addCtr(i.UnitName, "sol_lic_winners_center", "td");
                                row.addCtr(i.ResponsableName, "sol_lic_winners_center", "td");
                                row.addCtr(i.ErrorMessage, "pncp_pca_log_message", "td");
                                row.addCtr(i.Fail ? "Não" : "Sim", "sol_lic_winners_center", "td");
                                return row;
                            }));
                            this.add(table);
                            if (!modelList.hasItems()) {
                                table.visible = false;
                                this.addCtr("Não existe lista de PCAs enviados salva no Sistema.", "sol_lic_vehicle_contract_title_no");
                            }
                        });
                    }
                    build() {
                        super.build();
                        this.refresh();
                    }
                    clear() { }
                    foco() { }
                    isEmpty() { return true; }
                    toControl() { return this; }
                    validate() { return null; }
                }
                PNCP.BudgetForecastPNCPLogEditor = BudgetForecastPNCPLogEditor;
            })(PNCP = Components.PNCP || (Components.PNCP = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let MultipleServiceSelectionMode;
            (function (MultipleServiceSelectionMode) {
                MultipleServiceSelectionMode[MultipleServiceSelectionMode["quantityMode"] = 0] = "quantityMode";
                MultipleServiceSelectionMode[MultipleServiceSelectionMode["repeatedItemsMode"] = 1] = "repeatedItemsMode";
            })(MultipleServiceSelectionMode = Components.MultipleServiceSelectionMode || (Components.MultipleServiceSelectionMode = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ServiceSelectorScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.container = new Sol.Control();
                    this.doneButton = new Sol.Button();
                    this.list = new Web.Components.ListView();
                    this.searchField = new Sol.Field();
                    this.priceLabel = Sol.Environment.resources.product_price;
                    this.screenCaption = Sol.Environment.resources.select_services;
                }
                get selectedItems() {
                    return this.list.items.select(i => ({
                        code: i.code,
                        quantity: i.getEditor("Quantity").value,
                        price: i.getModelValue("PriceData"),
                        data: i.model
                    }))
                        .where(i => i.quantity > 0);
                }
                build() {
                    super.build();
                    this.initializeContainer();
                    this.initializeTitle();
                    this.initializeSearchField();
                    this.initializeList();
                    this.initDoneButton();
                    setTimeout(() => this.list.search(), 300);
                }
                doneClick() {
                    let items = this.selectedItems;
                    if (items.count == 0) {
                        alert(Sol.Environment.resources.ningun_seleccionado);
                        return;
                    }
                    this.onServiceSelected(items);
                }
                initializeContainer() {
                    this.container.css.add("sol_search_product_screen");
                    this.add(this.container);
                }
                initializeTitle() {
                    const screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                }
                initializeSearchField() {
                    this.searchField.placeHolder = Sol.Environment.resources.select_service_label;
                    this.searchField.css.add("sol_search_product_screen_search");
                    this.searchField.maxLength = 100;
                    this.searchField.autoWidth = false;
                    this.searchField.ancho = 500;
                    this.searchField.onKeyUp = () => this.search();
                    this.container.add(this.searchField);
                }
                initializeList() {
                    this.list.className = "Solarium.Commercial.Service, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.list.selectable = true;
                    this.list.onInstantiateItem = e => this.instantiateItem(e);
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: false,
                            property: "Quantity",
                            caption: Sol.Environment.resources.product_quantity,
                            position: Web.Components.ListViewFieldPosition.Left,
                            disabled: !this.multipleSelection,
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "SNumber",
                                PropertyName: "Quantity",
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: false
                            }
                        },
                        {
                            loadable: true,
                            property: "Nombre",
                            priority: Web.Components.ListViewFieldPriority.High,
                            position: Web.Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "Price",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Right,
                            caption: this.priceLabel
                        },
                        {
                            loadable: true,
                            property: "PriceData",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "AdditionalInformation",
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            position: Web.Components.ListViewFieldPosition.Left,
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "ServiceUnit$Decimals",
                            hidden: true
                        },
                    ]);
                    if (!this.multipleSelection)
                        this.list.onSelect = (d, code) => {
                            if (this.onServiceSelected)
                                this.onServiceSelected(Sol.List.from([{ code: code, quantity: 1, price: null }]));
                        };
                    this.container.add(this.list);
                }
                initDoneButton() {
                    let wrapper = this.container.addCtr(null, "sol_search_product_done_wrapper");
                    this.doneButton.text = "Concluído";
                    this.doneButton.visible = this.multipleSelection;
                    this.doneButton.accessKey = 'C';
                    this.doneButton.onClick = () => this.doneClick();
                    wrapper.add(this.doneButton);
                }
                instantiateItem(item) {
                    this.configQuantityDecimals(item);
                }
                configQuantityDecimals(item) {
                    let quantityField = item.getEditor("Quantity");
                    if (!quantityField)
                        return;
                    quantityField.decimals = item.getModelValue("ServiceUnit$Decimals");
                    item.itemObjects.where(i => i.configuration.property != "Quantity").forEach(d => d.display.estilos.definir("margin-top", "5px"));
                }
                search() {
                    this.list.filters = [{ PropertyName: "GeneralFilter", FilterValue: this.searchField.value, FilterType: "" }];
                    this.list.clear();
                    this.list.search();
                }
            }
            Screens.ServiceSelectorScreen = ServiceSelectorScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ServicesList extends Components.ListView {
                constructor() {
                    super();
                    this.externalCodeFieldCaption = Sol.Environment.resources.external_code;
                    this.showScope = false;
                    this.showCost = false;
                    this.showPrice = true;
                    this.showDescription = true;
                    this.showApprovedButton = true;
                    this.showSupplier = true;
                    this.showExternalCodeField = false;
                    this.priceSymmetry = false;
                    this.quantityLabel = Sol.Environment.resources.product_quantity;
                    this.priceLabel = Sol.Environment.resources.product_price;
                    this.totalLabel = Sol.Environment.resources.product_total;
                    this.totalCostLabel = Sol.Environment.resources.product_cost_total;
                    this.costLabel = Sol.Environment.resources.product_cost;
                    this.marginLabel = Sol.Environment.resources.product_margin_real;
                    this.className = "Solarium.Commercial.Service, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.onInstantiateItem = i => this.instantiateItem(i);
                    this.showItemNumbers = true;
                }
                get approvedItems() { return this.items.where(i => (this.showApprovedButton ? i.getEditor("Approved").checked : true)); }
                get totalCost() {
                    return this.showCost ? this.approvedItems
                        .cast()
                        .sum(item => item.getEditor("Cost").numericValue * item.getEditor("Quantity").value) : 0;
                }
                get total() {
                    return this.approvedItems
                        .cast()
                        .sum(item => { var _a; return (_a = item.getEditor("Total")) === null || _a === void 0 ? void 0 : _a.numericValue; });
                }
                updateItemTotal(item) {
                    this.updateTotal(item);
                    this.updateMargin(item);
                    this.updateMarginPercent(item);
                }
                build() {
                    super.build();
                    this.configuration = Sol.List.from([
                        {
                            loadable: false,
                            property: "DeleteCommand",
                            defaultText: Sol.Environment.resources.eliminar,
                            position: Components.ListViewFieldPosition.Right,
                            priority: Components.ListViewFieldPriority.Normal,
                            cssClass: "sol_products_list_remove"
                        },
                        {
                            loadable: true,
                            property: "Service$Nombre",
                            priority: Components.ListViewFieldPriority.High,
                            position: Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "Service",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "AdditionalInformation",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            lineBreak: true
                        },
                        {
                            loadable: false,
                            disabled: !this.showDescription,
                            property: "Description",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            lineBreak: true,
                            cssClass: "sol_products_list_description",
                            editor: {
                                DataType: "SText",
                                PropertyName: "Description",
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                Decimals: 2,
                                ReadOnly: this.readonly,
                                MaxLength: 85,
                                Tip: Sol.Environment.resources.service_description
                            }
                        },
                        {
                            loadable: false,
                            property: "Quantity",
                            lineBreak: true,
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: this.quantityLabel,
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "SNumber",
                                PropertyName: "Quantity",
                                Title: this.quantityLabel,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                Decimals: 3,
                                MaxLength: 10,
                                ReadOnly: this.readonly,
                                Width: 80
                            }
                        },
                        {
                            loadable: true,
                            disabled: !this.showCost,
                            property: "Cost",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: this.costLabel,
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "SMoney",
                                PropertyName: "Cost",
                                Title: this.costLabel,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                Decimals: 2,
                                ReadOnly: this.readonly
                            }
                        },
                        {
                            loadable: true,
                            disabled: !this.showCost,
                            property: "TotalCost",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: this.totalCostLabel,
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "SMoney",
                                PropertyName: "TotalCost",
                                Title: this.totalCostLabel,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                Decimals: 2,
                                ReadOnly: true
                            }
                        },
                        {
                            loadable: true,
                            disabled: !this.showPrice,
                            property: "Price",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: this.priceLabel,
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "SMoney",
                                PropertyName: "Price",
                                Title: this.priceLabel,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                Decimals: 2,
                                ReadOnly: this.readonly
                            }
                        },
                        {
                            loadable: false,
                            disabled: !this.showPrice,
                            property: "Total",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: this.totalLabel,
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "SMoney",
                                PropertyName: "Total",
                                Title: this.totalLabel,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                Decimals: 2,
                                ReadOnly: true
                            }
                        },
                        {
                            loadable: false,
                            disabled: !this.showPrice || !this.showCost,
                            property: "MarginPercent",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: Sol.Environment.resources.product_margin + " (%)",
                            editor: {
                                AllowChangeCurrency: false,
                                AcceptsNegative: true,
                                DataType: "SPercent",
                                PropertyName: "MarginPercent",
                                Title: Sol.Environment.resources.product_margin,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                Decimals: 2,
                                ReadOnly: true
                            }
                        },
                        {
                            loadable: false,
                            disabled: !this.showPrice || !this.showCost,
                            property: "Margin",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: this.marginLabel,
                            editor: {
                                AllowChangeCurrency: false,
                                AcceptsNegative: true,
                                DataType: "SMoney",
                                PropertyName: "Margin",
                                Title: this.marginLabel,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                Decimals: 2,
                                ReadOnly: true
                            }
                        },
                        {
                            loadable: false,
                            disabled: !this.showExternalCodeField,
                            property: "ExternalCode",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: this.externalCodeFieldCaption,
                            editor: {
                                DataType: "SInteger",
                                PropertyName: "ExternalCode",
                                Title: this.externalCodeFieldCaption,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                MaxLength: 20,
                                ReadOnly: this.readonly
                            }
                        },
                        {
                            loadable: true,
                            disabled: !this.showSupplier,
                            property: "Supplier",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: "Fornecedor",
                            lineBreak: true,
                            editor: {
                                DataType: "SupplierSelector",
                                PropertyName: "Supplier",
                                DataTypeFullName: "Solarium.Commercial.Supplier, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                Title: Sol.Environment.resources.supplier,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: this.readonly
                            }
                        },
                        {
                            loadable: true,
                            disabled: !this.showScope,
                            property: "Scope",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            editor: {
                                DataType: "HTMLDialogEditor",
                                PropertyName: "Scope",
                                Title: "Escopo",
                                ReadOnly: this.readonly,
                                Required: false
                            }
                        },
                        {
                            loadable: true,
                            disabled: !this.showApprovedButton,
                            property: "Approved",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "ApprovedCheck",
                                PropertyName: "Approved",
                                Title: Sol.Environment.resources.approved,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: this.readonly
                            }
                        }
                    ]);
                }
                instantiateItem(item) {
                    const deleteCommand = item.getDisplay("DeleteCommand");
                    if (deleteCommand) {
                        deleteCommand.visible = !this.readonly;
                        deleteCommand.onClick = () => this.removeItem(item);
                    }
                    const quantity = item.getEditor("Quantity");
                    const cost = item.getEditor("Cost");
                    const marginPercent = item.getEditor("MarginPercent");
                    const margin = item.getEditor("Margin");
                    const price = item.getEditor("Price");
                    const approved = item.getEditor("Approved");
                    const serviceID = item.getModelValue("Service");
                    const supplier = item.getEditor("Supplier");
                    if (quantity)
                        quantity.onModified = () => {
                            this.updateItemTotal(item);
                            this.updateTotalCost(item);
                            this.onQuantityChanged();
                        };
                    if (cost)
                        cost.onChange = () => {
                            this.updateItemTotal(item);
                            this.updateTotalCost(item);
                        };
                    if (marginPercent)
                        marginPercent.onModified = () => {
                            price.numericValue = cost.numericValue + (cost.numericValue * (marginPercent.value / 100));
                            this.updateTotal(item);
                            this.updateMargin(item);
                        };
                    if (margin)
                        margin.onChange = () => {
                            if (quantity.value == 0)
                                price.numericValue = 0;
                            else
                                price.numericValue = cost.numericValue + (margin.numericValue / quantity.value);
                            this.updateTotal(item);
                            this.updateMarginPercent(item);
                        };
                    if (price)
                        price.onChange = () => {
                            this.updateItemTotal(item);
                            this.updateTotalCost(item);
                            if (this.priceSymmetry)
                                this.updatePrices(serviceID, price.numericValue, item);
                        };
                    if (supplier)
                        supplier.hideExtraData = true;
                    approved === null || approved === void 0 ? void 0 : approved.onValueModified.subscribe(() => this.updateTotal(item));
                }
                updateTotal(item) {
                    const quantity = item.getEditor("Quantity");
                    const price = item.getEditor("Price");
                    const total = item.getEditor("Total");
                    if (total)
                        total.numericValue = price.numericValue * quantity.value;
                    if (this.onTotalChanged)
                        this.onTotalChanged();
                }
                updateMargin(item) {
                    if (!this.showCost)
                        return;
                    const quantity = item.getEditor("Quantity");
                    const cost = item.getEditor("Cost");
                    const margin = item.getEditor("Margin");
                    const price = item.getEditor("Price");
                    if (margin)
                        margin.numericValue = (price.numericValue - cost.numericValue) * quantity.value;
                }
                updateTotalCost(item) {
                    if (!this.showCost)
                        return;
                    const quantity = item.getEditor("Quantity");
                    const cost = item.getEditor("Cost");
                    const totalCost = item.getEditor("TotalCost");
                    if (totalCost)
                        totalCost.numericValue = cost.numericValue * quantity.value;
                    if (this.onTotalChanged)
                        this.onTotalChanged();
                }
                updateMarginPercent(item) {
                    if (!this.showCost)
                        return;
                    const quantity = item.getEditor("Quantity");
                    const cost = item.getEditor("Cost");
                    const marginPercent = item.getEditor("MarginPercent");
                    const total = item.getEditor("Total");
                    if (!total)
                        return;
                    if (total.numericValue == 0 || cost.numericValue == 0 || quantity.value == 0)
                        marginPercent.value = 0;
                    else
                        marginPercent.value = ((total.numericValue / (cost.numericValue * quantity.value)) - 1) * 100;
                }
                ;
                updatePrices(serviceID, price, sourceItem) {
                    this.items
                        .where(i => i.id != sourceItem.id && i.getModelValue("Service").Valor == serviceID.Valor)
                        .forEach(i => {
                        const priceEditor = i.getEditor("Price");
                        priceEditor.numericValue = price;
                        this.updateTotal(i);
                        this.updateMargin(i);
                        this.updateMarginPercent(i);
                        this.updateTotalCost(i);
                    });
                }
            }
            Components.ServicesList = ServicesList;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ServicesEditor extends Sol.Control {
                constructor() {
                    super();
                    this.addButton = new Sol.Button();
                    this.list = new Components.ServicesList();
                    this.isComplex = true;
                    this.showApprovedButton = true;
                    this.showPrice = true;
                    this.allowAddNew = true;
                    this.onQuantityChanged = new Sol.EventHandler();
                    this.totalQuantityText = new Sol.Control("span");
                    this.css.add("sol_products_editor");
                }
                get priceSymmetry() { return this.list.priceSymmetry; }
                set priceSymmetry(value) { this.list.priceSymmetry = value; }
                toControl() { return this; }
                get cost() { return this.list.totalCost; }
                get margin() { return this.total - this.cost; }
                get isSummable() { return true; }
                get quantityLabel() { return this.list.quantityLabel; }
                set quantityLabel(value) { this.list.quantityLabel = value; }
                get priceLabel() { return this.list.priceLabel; }
                set priceLabel(value) { this.list.priceLabel = value; }
                get totalLabel() { return this.list.totalLabel; }
                set totalLabel(value) { this.list.totalLabel = value; }
                get costLabel() { return this.list.costLabel; }
                set costLabel(value) { this.list.costLabel = value; }
                get totalCostLabel() { return this.list.totalCostLabel; }
                set totalCostLabel(value) { this.list.totalCostLabel = value; }
                get marginLabel() { return this.list.marginLabel; }
                set marginLabel(value) { this.list.marginLabel = value; }
                get readonly() { return this._readonly; }
                set readonly(value) {
                    this._readonly = value;
                    this.list.readonly = value;
                    this.addButton.visible = !value;
                }
                get total() { return this.list.total; }
                foco() { }
                validate() { return null; }
                get value() { return this.list.values; }
                set value(v) {
                    this.list.values = v;
                    setTimeout(() => {
                        if (this.onTotalsChanged)
                            this.onTotalsChanged();
                        this.updateTotalQuantity();
                    }, 500);
                }
                build() {
                    super.build();
                    this.initializeList();
                    this.initializeAddButton();
                    this.initializeStatusBar();
                }
                addServices(services) {
                    let data = {
                        className: this.list.className,
                        currentPage: 1,
                        rowCount: 0,
                        filters: [{ PropertyName: "IDsFilter", FilterValue: services.select(p => p.code).toArray(), FilterType: null }],
                        sortProperty: "ID",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "Nombre", "Price"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        if (!model.Data || model.Data.length == 0)
                            return;
                        let service;
                        let code;
                        let serviceName;
                        let selectedService;
                        let quantity;
                        let clones;
                        for (var i = 0; i < model.Data.length; i++) {
                            service = Sol.List.from(model.Data[i]);
                            code = service.that(d => d.Campo == "ID").Valor;
                            serviceName = service.that(d => d.Campo == "Nombre").Valor;
                            selectedService = services.that(p => p.code == code);
                            quantity = (selectedService === null || selectedService === void 0 ? void 0 : selectedService.quantity) || 1;
                            clones = 1;
                            if (this.multipleServiceSelectionMode == Components.MultipleServiceSelectionMode.repeatedItemsMode) {
                                clones = quantity;
                                quantity = 1;
                            }
                            for (var c = 0; c < clones; c++) {
                                let item = [
                                    { Campo: "Service", Valor: { Campo: serviceName, Valor: code } },
                                    { Campo: "Quantity", Valor: quantity },
                                    { Campo: "Approved", Valor: true },
                                    { Campo: "Service$Nombre", Valor: serviceName },
                                    { Campo: "Price", Valor: (selectedService === null || selectedService === void 0 ? void 0 : selectedService.price) || service.that(d => d.Campo == "Price").Valor }
                                ];
                                let listItem = this.list.addItemFromData(item, 0);
                                this.list.updateItemTotal(listItem);
                            }
                        }
                    });
                }
                initializeAddButton() {
                    if (!this.allowAddNew)
                        return;
                    this.addButton.text = Sol.Environment.resources.anadir_item;
                    this.addButton.imageCode = '&#xf187;';
                    this.addButton.onClick = () => {
                        const screen = new Web.Screens.ServiceSelectorScreen();
                        screen.multipleSelection = this.multipleServiceSelection;
                        screen.priceLabel = this.priceLabel;
                        Web.System.screens.addScreen(screen);
                        Web.System.screens.showScreen(screen);
                        screen.onServiceSelected = srvs => {
                            this.addServices(srvs);
                            Web.System.screens.closeCurrentScreen();
                        };
                    };
                    this.add(this.addButton);
                }
                initializeList() {
                    this.list.itemPropertyName = "Service";
                    this.list.onTotalChanged = () => {
                        if (this.onTotalsChanged)
                            this.onTotalsChanged();
                    };
                    this.list.onQuantityChanged = () => {
                        this.updateTotalQuantity();
                        this.onQuantityChanged.invoke();
                    };
                    this.list.showCost = this.showCost;
                    this.list.showApprovedButton = this.showApprovedButton;
                    this.list.showSupplier = this.showSupplier;
                    this.list.showPrice = this.showPrice;
                    this.list.externalCodeFieldCaption = this.externalCodeFieldCaption;
                    this.list.showExternalCodeField = this.showExternalCode;
                    this.list.showScope = this.showScope;
                    this.list.priceSymmetry = this.priceSymmetry;
                    this.add(this.list);
                }
                initializeStatusBar() {
                    const bar = new Sol.Control();
                    bar.css.add("sol_products_editor_bar");
                    const totalQuantityTitle = new Sol.Label();
                    totalQuantityTitle.text = Sol.Environment.resources.totalQuantity + ":";
                    bar.add(totalQuantityTitle);
                    this.totalQuantityText.text = "0";
                    bar.add(this.totalQuantityText);
                    this.add(bar);
                }
                updateTotalQuantity() {
                    const total = this.list.items.sum(i => i.getEditor("Quantity").value);
                    this.totalQuantityText.text = total.toString();
                }
                isEmpty() { return false; }
                clear() { }
            }
            Components.ServicesEditor = ServicesEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var EventTypes;
            (function (EventTypes) {
                class LicitationEventSelector extends Sol.Combo {
                    constructor() {
                        super();
                        this.onSet.subscribe(() => this.LoadEventType());
                        this.onValueModified.subscribe(() => this.LoadEventType());
                    }
                    LoadEventType() {
                        Web.System.exec("spoe34skdeo", "GetEventType", { eventID: parseInt(this.selectedCode) }, model => {
                            this.container.getEditor("PublicationsType").parent.visible = model.PublicationsTypeVisible;
                            this.container.getEditor("PublicationDescription").myLabel.visible = model.PublicationDescriptionVisible;
                            this.container.getEditor("Author").myLabel.visible = model.AuthorVisible;
                            this.container.getEditor("Author").visible = model.AuthorVisible;
                            this.container.getEditor("Author").parent.visible = model.AuthorVisible;
                            this.container.getEditor("TrialDate").parent.visible = model.TrialDateVisible;
                            this.container.getEditor("Result").myLabel.visible = model.ResultVisible;
                            this.container.getEditor("Result").visible = model.ResultVisible;
                            this.container.getEditor("Result").parent.visible = model.ResultVisible;
                            this.container.getEditor("Batch").parent.visible = model.BatchVisible;
                            this.container.getEditor("ItemNumber").parent.visible = model.ItemNumberVisible;
                            this.container.getEditor("PublicationExtract").group.GroupDisplay.visible = model.PublicationExtractVisible || model.PublicationsTypeVisible || model.PublicationDescriptionVisible;
                            this.container.getEditor("PublicationExtract").parent.visible = model.PublicationExtractVisible;
                            this.container.getEditor("PublicationExtract").required = model.PublicationExtractRequired;
                        });
                    }
                }
                EventTypes.LicitationEventSelector = LicitationEventSelector;
                Sol.Web.Editors.registerEditor("LicitationEventType", model => {
                    const batSelector = new Sol.Web.Components.EventTypes.LicitationEventSelector();
                    batSelector.loadOptions(model.Options);
                    return batSelector;
                });
            })(EventTypes = Components.EventTypes || (Components.EventTypes = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Geo;
        (function (Geo) {
            class CountrySelector extends Sol.SelectorField {
                constructor() {
                    super();
                    this.selectedFlag = new Sol.Control("img");
                    this.css.add("sol_country_selector");
                    this.controls.insert(0, this.selectedFlag);
                    this.className = "Solarium.Geo.País, Solarium.Geo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.sourceMode = Sol.SelectorSourceMode.Custom;
                    this.codeProperty = "CountryID";
                    this.displayProperty = "CountryName";
                    this.onCustomSource = countryId => this.countrySearch(countryId);
                    this.mainField.autoWidth = false;
                    this.mainField.ancho = 350;
                    this.onInstantiateCustomItem = (item, data) => this.instantiateItem(item, data);
                }
                internalItemSelected(item) {
                    this.selectedFlag.atributos.definir("src", item["flagSource"]);
                }
                countrySearch(countryId) {
                    return __awaiter(this, void 0, void 0, function* () {
                        const result = yield Sol.Http.AjaxLight.postAsync("https://geo.letrearte.com/countries", {
                            lang: Sol.Environment.language,
                            term: this.selectedText,
                            id: countryId
                        });
                        return result.Data;
                    });
                }
                instantiateItem(item, data) {
                    const iso = data.CountryISO;
                    const name = data.CountryName;
                    item.displayText = item.text;
                    item.text = "";
                    var flag = new Sol.Control("img");
                    item["flagSource"] = "https://geo.letrearte.com/flag/" + iso.toLowerCase();
                    flag.atributos.agregar("src", item["flagSource"]);
                    item.add(flag);
                    var nameSpan = new Sol.Control("span");
                    nameSpan.text = name;
                    item.add(nameSpan);
                }
            }
            Geo.CountrySelector = CountrySelector;
        })(Geo = Web.Geo || (Web.Geo = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Localization;
    (function (Localization) {
        class LangBase {
            getText(key, lang = null) {
                lang = lang || this.language;
                for (var term of this.terms)
                    if (term.k === key && term.l === lang)
                        return term.v;
                return null;
            }
        }
        Localization.LangBase = LangBase;
    })(Localization = Sol.Localization || (Sol.Localization = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var PaymentGateways;
            (function (PaymentGateways) {
                class CreditCardFormLang extends Sol.Localization.LangBase {
                    constructor() {
                        super(...arguments);
                        this.terms = [
                            { l: "en", k: "cc_amount", v: "Total Value:" },
                            { l: "pt", k: "cc_amount", v: "Valor Total:" },
                            { l: "es", k: "cc_amount", v: "Valor Total:" },
                            { l: "en", k: "cc_number", v: "Card Number:" },
                            { l: "pt", k: "cc_number", v: "Nº do Cartão:" },
                            { l: "es", k: "cc_number", v: "Nº de la Tarjeta:" },
                            { l: "en", k: "cc_holder_name", v: "Holder Name:" },
                            { l: "pt", k: "cc_holder_name", v: "Nome do Titular:" },
                            { l: "es", k: "cc_holder_name", v: "Nombre del Titular:" },
                            { l: "pt", k: "cc_expiry_date", v: "Válido Até:" },
                            { l: "en", k: "cc_expiry_date", v: "Expiry Date:" },
                            { l: "es", k: "cc_expiry_date", v: "Válido Hasta:" },
                            { l: "en", k: "cc_security_code", v: "CVV:" },
                            { l: "pt", k: "cc_security_code", v: "CVV:" },
                            { l: "es", k: "cc_security_code", v: "CVV:" },
                            { l: "pt", k: "cc_holder_document", v: "CPF/CNPJ do Titular:" },
                            { l: "en", k: "cc_holder_document", v: "Holder Tax ID:" },
                            { l: "es", k: "cc_holder_document", v: "Nº Fiscal del Titular:" },
                            { l: "pt", k: "cc_main_address", v: "Linha de Endereço 1:" },
                            { l: "en", k: "cc_main_address", v: "Line Address 1:" },
                            { l: "es", k: "cc_main_address", v: "línea Dirección 1:" },
                            { l: "en", k: "cc_optional_address", v: "Address Line 2 (Optional):" },
                            { l: "pt", k: "cc_optional_address", v: "Linha de Endereço 2 (Opcional):" },
                            { l: "es", k: "cc_optional_address", v: "Línea de Dirección 2 (Opcional):" },
                            { l: "en", k: "cc_city_address", v: "City:" },
                            { l: "pt", k: "cc_city_address", v: "Cidade:" },
                            { l: "es", k: "cc_city_address", v: "Ciudad:" },
                            { l: "en", k: "cc_zip_code_address", v: "Zip Code:" },
                            { l: "pt", k: "cc_zip_code_address", v: "Código Postal:" },
                            { l: "es", k: "cc_zip_code_address", v: "Código Postal:" },
                            { l: "en", k: "cc_state_address", v: "State:" },
                            { l: "pt", k: "cc_state_address", v: "Estado:" },
                            { l: "es", k: "cc_state_address", v: "Estado:" },
                            { l: "en", k: "cc_country_address", v: "Country:" },
                            { l: "pt", k: "cc_country_address", v: "Pais:" },
                            { l: "es", k: "cc_country_address", v: "País:" },
                            { l: "en", k: "cc_button_payment", v: "Complete purchase" },
                            { l: "pt", k: "cc_button_payment", v: "Finalizar a compra" },
                            { l: "es", k: "cc_button_payment", v: "Finalizar la compra" },
                            { l: "en", k: "cc_security_code_description", v: "The security code is typically located on the back of the card." },
                            { l: "pt", k: "cc_security_code_description", v: "O código de segurança normalmente fica na parte de trás do cartão." },
                            { l: "es", k: "cc_security_code_description", v: "El código de seguridad suele estar en la parte posterior de la tarjeta." },
                            { l: "pt", k: "cc_optional_address_description", v: "Deve ser preenchido nesta ordem, separado por vírgulas: Complemento, Andar, Sala, Apto, etc." },
                            { l: "en", k: "cc_optional_address_description", v: "Should be filled out in this order, separated by commas: Complement, Floor, Room, Apartment, etc." },
                            { l: "es", k: "cc_optional_address_description", v: "Debe ser completada en este orden, separada por comas: Complemento, Piso, Sala, Apartamento, etc." },
                            { l: "pt", k: "cc_main_address_description", v: "Deve ser preenchido nesta ordem, separado por vírgula: Número, Rua e Bairro." },
                            { l: "es", k: "cc_main_address_description", v: "Debe ser completada en este orden, separada por comas: Número, Calle y Barrio." },
                            { l: "en", k: "cc_main_address_description", v: "Must be filled in this order, separated by commas: Number, Street, and Neighborhood." },
                        ];
                    }
                }
                PaymentGateways.CreditCardFormLang = CreditCardFormLang;
            })(PaymentGateways = Components.PaymentGateways || (Components.PaymentGateways = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var PaymentGateways;
            (function (PaymentGateways) {
                class CreditCardDateField extends Sol.Combo {
                    constructor() {
                        super();
                        this.css.add("sol_cc_card_date");
                        let currentYear = new Date()
                            .getFullYear();
                        for (let year = currentYear; year <= currentYear + 20; year++)
                            this.addItems([{ Campo: year.toString(), Valor: year }]);
                    }
                }
                PaymentGateways.CreditCardDateField = CreditCardDateField;
            })(PaymentGateways = Components.PaymentGateways || (Components.PaymentGateways = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var PaymentGateways;
            (function (PaymentGateways) {
                class CreditCardForm extends Sol.Control {
                    constructor(options) {
                        super();
                        this.lang = new PaymentGateways.CreditCardFormLang();
                        this.paymentButton = new Sol.Button();
                        this.brandsArea = new Sol.Control();
                        this.amountField = new Sol.CurrencyField();
                        this.numberField = new Sol.Field();
                        this.holderNameField = new Sol.Field();
                        this.securityCodeField = new Sol.Field();
                        this.holderDocumentField = new Sol.Field();
                        this.expiryMonthField = new Sol.MonthField();
                        this.expiryYearField = new PaymentGateways.CreditCardDateField();
                        this.cityField = new Sol.Field();
                        this.stateField = new Sol.Field();
                        this.zipCodeField = new Sol.Field();
                        this.mainAddressField = new Sol.Field();
                        this.optionalAddressField = new Sol.Field();
                        this.countrySelector = new Web.Geo.CountrySelector();
                        this.options = options;
                        this.entityID = options.entityID;
                        this.identifier = options.engine;
                        this.lang.language = options.language;
                        Sol.Environment.language = options.language;
                        this.css.add("sol_cc_card");
                        this.displayAmount();
                        this.addAcceptedBrands();
                        this.addNumberField();
                        this.addExpiryDateField();
                        this.addSecurityCodeField();
                        this.addHolderNameField();
                        this.addHolderDocumentField();
                        this.addMainAddress();
                        this.addOptionalAddress();
                        this.addCityAddress();
                        this.addStateAddress();
                        this.addZipCodeAddress();
                        this.addCountryAddress();
                        this.addPaymentButton();
                    }
                    get amount() { return this.amountField.numericValue; }
                    set amount(amount) { this.amountField.numericValue = amount; }
                    displayAmount() {
                        const wrapper = new Sol.FieldWrapper();
                        const amountLabel = new Sol.Label(this.lang.getText("cc_amount"));
                        this.amountField.readonly = true;
                        wrapper.add(amountLabel);
                        wrapper.add(this.amountField);
                        this.add(wrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addNumberField() {
                        const numberWrapper = new Sol.FieldWrapper();
                        const numberLabel = new Sol.Label(this.lang.getText("cc_number"));
                        this.numberField.inputType = "tel";
                        this.numberField.maxLength = 19;
                        this.numberField.required = true;
                        this.numberField.inputMode = "numeric";
                        this.numberField.autoCompleteKey = "cc-number";
                        this.numberField.inputOptions = { allowNumbers: true, specialChars: " " };
                        this.numberField.ancho = 370;
                        numberWrapper.add(numberLabel);
                        numberWrapper.add(this.numberField);
                        this.add(numberWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addHolderNameField() {
                        const holderWrapper = new Sol.FieldWrapper();
                        const holderNameLabel = new Sol.Label(this.lang.getText("cc_holder_name"));
                        this.holderNameField.maxLength = 64;
                        this.holderNameField.required = true;
                        this.holderNameField.autoCompleteKey = "cc-holder-name";
                        this.holderNameField.capitalizacion = Sol.CapitalizationMode.Uppercase;
                        this.holderNameField.inputOptions = { allowLetters: true, specialChars: " " };
                        holderWrapper.add(holderNameLabel);
                        holderWrapper.add(this.holderNameField);
                        this.add(holderWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addSecurityCodeField() {
                        const securityCodeWrapper = new Sol.FieldWrapper();
                        const securityCodeLabel = new Sol.Label(this.lang.getText("cc_security_code"));
                        this.securityCodeField.maxLength = 4;
                        this.securityCodeField.required = true;
                        this.securityCodeField.autoCompleteKey = "cc-security-code";
                        this.securityCodeField.inputOptions = { allowNumbers: true };
                        this.securityCodeField.ancho = 60;
                        securityCodeLabel.largeDescription = this.lang.getText("cc_security_code_description");
                        securityCodeWrapper.add(securityCodeLabel);
                        securityCodeWrapper.add(this.securityCodeField);
                        this.add(securityCodeWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addExpiryDateField() {
                        const ExpiryDatewrapper = new Sol.FieldWrapper();
                        const expiryYearLabel = new Sol.Label(this.lang.getText("cc_expiry_date"));
                        this.expiryMonthField.ancho = 207;
                        this.expiryYearField.required = true;
                        this.expiryMonthField.required = true;
                        ExpiryDatewrapper.add(expiryYearLabel);
                        ExpiryDatewrapper.addMany([this.expiryMonthField, this.expiryYearField]);
                        this.add(ExpiryDatewrapper);
                    }
                    addHolderDocumentField() {
                        const holderDocWrapper = new Sol.FieldWrapper();
                        const holderDocumentLabel = new Sol.Label(this.lang.getText("cc_holder_document"));
                        this.holderDocumentField.maxLength = 18;
                        this.holderDocumentField.required = true;
                        this.holderDocumentField.autoCompleteKey = "cc-holder-document";
                        this.holderDocumentField.inputOptions = { allowNumbers: true, specialChars: "./-" };
                        holderDocWrapper.add(holderDocumentLabel);
                        holderDocWrapper.add(this.holderDocumentField);
                        this.add(holderDocWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addMainAddress() {
                        const mainAddressWrapper = new Sol.FieldWrapper();
                        const mainAddressLabel = new Sol.Label(this.lang.getText("cc_main_address"));
                        this.mainAddressField.maxLength = 256;
                        this.mainAddressField.required = true;
                        this.mainAddressField.autoCompleteKey = "cc-main-address";
                        mainAddressLabel.largeDescription = this.lang.getText("cc_main_address_description");
                        this.mainAddressField.inputOptions = { allowLetters: true, allowNumbers: true, specialChars: ", " };
                        mainAddressWrapper.add(mainAddressLabel);
                        mainAddressWrapper.add(this.mainAddressField);
                        this.add(mainAddressWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addOptionalAddress() {
                        const optionalAddresswrapper = new Sol.FieldWrapper();
                        const optionalAddressLabel = new Sol.Label(this.lang.getText("cc_optional_address"));
                        this.optionalAddressField.maxLength = 128;
                        this.optionalAddressField.autoCompleteKey = "cc-optional-address";
                        optionalAddressLabel.largeDescription = this.lang.getText("cc_optional_address_description");
                        this.optionalAddressField.inputOptions = { allowLetters: true, allowNumbers: true, specialChars: ", " };
                        optionalAddresswrapper.add(optionalAddressLabel);
                        optionalAddresswrapper.add(this.optionalAddressField);
                        this.add(optionalAddresswrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addCityAddress() {
                        const cityWrapper = new Sol.FieldWrapper();
                        const cityLabel = new Sol.Label(this.lang.getText("cc_city_address"));
                        this.cityField.maxLength = 64;
                        this.cityField.required = true;
                        this.cityField.autoCompleteKey = "cc-city-address";
                        this.cityField.inputOptions = { allowLetters: true, allowNumbers: true, specialChars: " " };
                        cityWrapper.add(cityLabel);
                        cityWrapper.add(this.cityField);
                        this.add(cityWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addZipCodeAddress() {
                        const zipCodeWrapper = new Sol.FieldWrapper();
                        const zipCodeLabel = new Sol.Label(this.lang.getText("cc_zip_code_address"));
                        this.zipCodeField.maxLength = 10;
                        this.zipCodeField.required = true;
                        this.zipCodeField.autoCompleteKey = "cc-zip-code-address";
                        this.zipCodeField.inputOptions = { allowNumbers: true, specialChars: "-" };
                        zipCodeWrapper.add(zipCodeLabel);
                        zipCodeWrapper.add(this.zipCodeField);
                        this.add(zipCodeWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addStateAddress() {
                        const stateWrapper = new Sol.FieldWrapper();
                        const stateLabel = new Sol.Label(this.lang.getText("cc_state_address"));
                        this.stateField.maxLength = 2;
                        this.stateField.required = true;
                        this.stateField.autoCompleteKey = "cc-state-address";
                        this.stateField.inputOptions = { allowLetters: true };
                        this.stateField.capitalizacion = Sol.CapitalizationMode.Uppercase;
                        stateWrapper.add(stateLabel);
                        stateWrapper.add(this.stateField);
                        this.add(stateWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addCountryAddress() {
                        const countryWrapper = new Sol.FieldWrapper();
                        const countryLabel = new Sol.Label(this.lang.getText("cc_country_address"));
                        this.countrySelector.required = true;
                        countryWrapper.add(countryLabel);
                        countryWrapper.add(this.countrySelector);
                        this.add(countryWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    addAcceptedBrands() {
                        this.brandsArea.css.add("sol_cc_card_brands");
                        this.add(this.brandsArea);
                        Sol.Http.AjaxLight.exec("A7bQ9zG2rT", "GetAcceptedBrands", { identifier: this.identifier }, (brands) => { this.loadBrands(brands); });
                    }
                    addPaymentButton() {
                        const paymentWrapper = new Sol.FieldWrapper();
                        this.paymentButton.text = this.lang.getText("cc_button_payment");
                        this.paymentButton.onClick = () => this.makePayment();
                        paymentWrapper.add(this.paymentButton);
                        this.add(paymentWrapper);
                        this.add(new Sol.LineBreak());
                    }
                    toModel() {
                        let addressModel = {
                            AddressLine: this.mainAddressField.value,
                            AddressLineTwo: this.optionalAddressField.value,
                            City: this.cityField.value,
                            ZipCode: this.zipCodeField.value,
                            State: this.stateField.value,
                            Country: 31
                        };
                        let creditCardModel = {
                            Number: this.numberField.value,
                            HolderDocument: this.holderDocumentField.value,
                            SecurityCode: this.securityCodeField.value,
                            ExpMonth: this.expiryMonthField.value.Valor,
                            ExpYear: this.expiryYearField.value.Valor,
                            HolderName: this.holderNameField.value,
                            Address: addressModel
                        };
                        return creditCardModel;
                    }
                    makePayment() {
                        let mappedRequest = {
                            EntityID: this.entityID,
                            Engine: this.identifier,
                            Mode: Components.PaymentMode.creditCard,
                            CreditCardData: this.toModel()
                        };
                        Sol.Http.AjaxLight.exec("A7bQ9zG2rT", "MakePayment", { credential: Sol.Environment.credential.export(), request: mappedRequest }, (response) => {
                            if (response.Fail)
                                alert(response.ErrorMessage);
                        });
                    }
                    loadBrands(brands) {
                        this.brandsArea.addMany(Sol.List.from(brands).select(brand => {
                            const image = new Sol.Control("img");
                            image.atributos.agregar("src", brand.ImageUrl);
                            image.tip = brand.Name;
                            return image;
                        }));
                    }
                }
                PaymentGateways.CreditCardForm = CreditCardForm;
            })(PaymentGateways = Components.PaymentGateways || (Components.PaymentGateways = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var PaymentGateways;
            (function (PaymentGateways) {
                class OnlinePaymentEditor extends Sol.Control {
                    constructor() {
                        super();
                        this.details = new Web.Screens.DetailsScreen();
                        this.creditCardForm = new PaymentGateways.CreditCardForm({
                            language: "pt",
                            engine: "54d5DxvG7pA92Z8",
                            entityID: 384
                        });
                        this.build();
                        this.add(this.creditCardForm);
                    }
                    get value() {
                        let currentValues = Sol.List.from(this.details.values);
                        currentValues.forEach(value => value.Campo = this.propertyName + '$' + value.Campo);
                        return currentValues.toArray();
                    }
                    build() {
                        let total = Web.System.screens
                            .getMyDetails(this.details)
                            .getEditor("Total");
                        this.creditCardForm.amount = total.value;
                    }
                    clear() { }
                    foco() { }
                    isEmpty() { return true; }
                    toControl() { return this; }
                    validate() { return null; }
                }
                PaymentGateways.OnlinePaymentEditor = OnlinePaymentEditor;
            })(PaymentGateways = Components.PaymentGateways || (Components.PaymentGateways = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("CreditCardEditor", () => new Sol.Web.Components.PaymentGateways.OnlinePaymentEditor());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let MenuState;
            (function (MenuState) {
                MenuState[MenuState["Condensed"] = 0] = "Condensed";
                MenuState[MenuState["Expanded"] = 1] = "Expanded";
            })(MenuState = Components.MenuState || (Components.MenuState = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class BaseIcon extends Sol.Control {
                    constructor() {
                        super(...arguments);
                        this.backToHomeWhenClick = true;
                        this.icon = new Sol.Control("h1");
                        this.label = new Sol.Control();
                        this.number = new Sol.Counter();
                    }
                    get iconCode() { return this.icon.text; }
                    set iconCode(value) { this.icon.text = value; }
                    get labelText() { return this.label.text; }
                    set labelText(value) { this.label.text = value; }
                    get numberText() { return this.number.text; }
                    set numberText(value) { this.number.text = value; }
                    get numberAnimationEnabled() { return this.number.animationEnabled; }
                    set numberAnimationEnabled(value) { this.number.animationEnabled = value; }
                    build() {
                        var _a;
                        this.css.add("sol_tile");
                        if (this.sourceMenu)
                            this.icon.text = this.sourceMenu.Icono;
                        this.add(this.icon);
                        this.number.css.add("sol_tile_numero");
                        this.numberText = "0";
                        this.add(this.number);
                        this.label.css.add("sol_tile_etiqueta");
                        if (this.sourceMenu)
                            this.label.text = this.sourceMenu.Nombre;
                        this.add(this.label);
                        if ((_a = this.sourceMenu) === null || _a === void 0 ? void 0 : _a.Description) {
                            this.css.add("sol_tile_with_desc");
                            this.addCtr(this.sourceMenu.Description, "sol_tile_description");
                        }
                        this.onClick = () => this.iconClick();
                        super.build();
                    }
                    run() { this.iconClick(); }
                    iconClick() {
                        Web.System.home.closeMenu();
                        if (this.backToHomeWhenClick && !Web.System.screens.backToDashboard())
                            return;
                        if (this.sourceMenu.RequiereModel)
                            Web.System.screens.openScreen(this.sourceMenu.Pantalla, this.sourceMenu.Clase, this.sourceMenu.MensajeDeSistema, this.sourceMenu.Icono, this.label.text);
                        else
                            Web.System.screens.openScreenWithModel(this.sourceMenu.Pantalla, this.sourceMenu.Icono, null, this.sourceMenu.MensajeDeSistema, this.label.text);
                    }
                    static fromMenu(menu) {
                        var iconName = menu.Tile;
                        if (!iconName)
                            iconName = "SimpleIcon";
                        var icon = eval("new Sol.Web.Components.Icons." + iconName + "()");
                        icon.sourceMenu = menu;
                        return icon;
                    }
                }
                Icons.BaseIcon = BaseIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class SimpleIcon extends Icons.BaseIcon {
                    refresh() { }
                }
                Icons.SimpleIcon = SimpleIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ChangePassword extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.tituloPantalla = new Screens.ScreenTitle();
                    this.formulario = new Sol.Form();
                    this.etiquetaActual = new Sol.Label();
                    this.campoActual = new Sol.PasswordField();
                    this.etiquetaNueva = new Sol.Label();
                    this.campoNueva = new Sol.PasswordField();
                    this.etiquetaConfirmacion = new Sol.Label();
                    this.campoConfirmacion = new Sol.PasswordField();
                    this.mensajeExito = new Sol.ScreenMessage();
                    this.css.add("sol_change_password");
                    this.screenCaption = Sol.Environment.resources.cambiar_clave;
                    this.tituloPantalla.text = Sol.Environment.resources.cambiar_clave;
                    this.add(this.tituloPantalla);
                    var text = new Sol.Control();
                    text.text = "Digite sua nova senha e a confirme por favor. Deve possuir, pelo menos, 4 caracteres.";
                    text.css.add("sol_change_password_subtitle");
                    this.formulario.add(text);
                    var userName = new Sol.Control();
                    userName.text = "Usuário:    " + Web.System.userName;
                    userName.css.add("sol_change_password_subtitle");
                    this.formulario.add(userName);
                    this.formulario.onValidate = this.validar;
                    this.formulario.onSave = this.grabar;
                    this.formulario.onCancel = () => Web.System.screens.backToDashboard();
                    this.add(this.formulario);
                    this.mensajeExito.type = Sol.MessageType.Success;
                    this.mensajeExito.caption = Sol.Environment.resources.clave_cambio;
                    this.mensajeExito.visible = false;
                    this.formulario.add(this.mensajeExito);
                    this.etiquetaActual.text = Sol.Environment.resources.clave_actual;
                    this.etiquetaActual.editor = this.campoActual;
                    this.campoActual.required = true;
                    this.formulario.add(this.etiquetaActual);
                    this.formulario.add(this.campoActual);
                    this.etiquetaNueva.text = Sol.Environment.resources.clave_nueva;
                    this.etiquetaNueva.editor = this.campoNueva;
                    this.campoNueva.required = true;
                    this.formulario.add(this.etiquetaNueva);
                    this.formulario.add(this.campoNueva);
                    this.etiquetaConfirmacion.text = Sol.Environment.resources.clave_confirmacion;
                    this.etiquetaConfirmacion.editor = this.campoConfirmacion;
                    this.campoConfirmacion.required = true;
                    this.formulario.add(this.etiquetaConfirmacion);
                    this.formulario.add(this.campoConfirmacion);
                    this.formulario.okButton.text = Sol.Environment.resources.cambiar_clave;
                }
                get showCancel() { return this.formulario.showCancelButton; }
                set showCancel(value) { this.formulario.showCancelButton = value; }
                validar(frm) {
                    var me = frm.parent;
                    me.mensajeExito.visible = false;
                    return {
                        success: me.campoNueva.textValue === me.campoConfirmacion.textValue,
                        message: Sol.Environment.resources.clave_nueva_error
                    };
                }
                grabar(frm) {
                    var me = frm.parent;
                    var data = {
                        credential: Sol.Environment.credential.export(),
                        currentPass: me.campoActual.textValue,
                        newPass: me.campoNueva.textValue
                    };
                    Web.System.exec("hjkj28d", "ChangePassword", data, e => {
                        var response = e;
                        frm.workComplete();
                        if (!response.Fail) {
                            Sol.Environment.credential.load(response.Credencial);
                            alert(Sol.Environment.resources.clave_cambio);
                            Web.System.home.showSystemBar = true;
                            Web.System.screens.showNavigation = true;
                            Web.System.screens.backToDashboard();
                        }
                        else
                            frm.showError(response.ErrorMessage);
                    });
                }
            }
            Screens.ChangePassword = ChangePassword;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let WidgetPosition;
            (function (WidgetPosition) {
                WidgetPosition[WidgetPosition["MainArea"] = 0] = "MainArea";
                WidgetPosition[WidgetPosition["RightSide"] = 1] = "RightSide";
            })(WidgetPosition = Screens.WidgetPosition || (Screens.WidgetPosition = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SystemComboItem extends Sol.Control {
                constructor(name, id) {
                    super();
                    this.css.add("sol_system_combo_popup_item");
                    this.text = name;
                    this.systemID = id;
                }
                get focused() { return this._focused; }
                set focused(value) {
                    this._focused = value;
                    if (value)
                        this.css.add("sol_system_combo_popup_item_focused");
                    else
                        this.css.remove("sol_system_combo_popup_item_focused");
                }
            }
            Components.SystemComboItem = SystemComboItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SystemCombo extends Sol.Control {
                constructor() {
                    super();
                    this.loadDisplay = new Sol.Control("li");
                    this.resultsDisplay = new Sol.Control("li");
                    this.searchField = new Sol.Field();
                    this.popup = new Sol.Popup();
                    this.css.addMany(["sol_campo", "sol_system_combo_field"]);
                    this.addCtr("&#xf0f7;", null, "i");
                    const display = this.addCtr(Web.System.companyName, "sol_system_combo_display", "span");
                    this.onClick = () => {
                        this.popup.visible = !this.popup.visible;
                        if (this.popup.visible) {
                            this.searchInput();
                            this.searchField.foco();
                        }
                    };
                    display.addCtr("&#xf0d7", null, "i");
                    this.popup.css.add("sol_system_combo_popup");
                    const searchItem = this.popup.addCtr(null, null, "li");
                    this.searchField.placeHolder = Sol.Environment.resources.typeToSearch;
                    this.searchField.onInput.subscribe(() => this.searchInput());
                    this.searchField.onKeyDown = e => this.fieldKeyDown(e);
                    searchItem.add(this.searchField);
                    this.loadDisplay.visible = false;
                    this.loadDisplay.text = Sol.Environment.resources.searching;
                    this.popup.add(this.loadDisplay);
                    this.popup.add(this.resultsDisplay);
                    this.popup.visible = false;
                    this.add(this.popup);
                }
                get items() { return this.resultsDisplay.controls.cast(); }
                get selectedIndex() { return this.items.indexWhere(i => i.focused); }
                set selectedIndex(value) {
                    this.items.forEach(i => i.focused = false);
                    this.items.item(value).focused = true;
                }
                searchInput() {
                    var _a;
                    this.popup.ancho = this.ancho;
                    this.resultsDisplay.controls.empty();
                    this.loadDisplay.visible = true;
                    (_a = this.ajax) === null || _a === void 0 ? void 0 : _a.abort();
                    this.ajax = Web.System.exec("nlskd23jor", "FindSystems", { term: this.searchField.value }, model => {
                        this.loadDisplay.visible = false;
                        this.resultsDisplay.controls.addMany(Sol.List.from(model.Systems).select(sys => {
                            const item = new Components.SystemComboItem(sys.Name, sys.ID);
                            item.onClick = () => this.SelectSystem(item);
                            return item;
                        }));
                    });
                }
                fieldKeyDown(e) {
                    var handled;
                    if (e.which == 40) {
                        this.selectedIndex = this.selectedIndex < this.items.count - 1 ? this.selectedIndex + 1 : 0;
                        handled = true;
                    }
                    if (e.which == 38) {
                        this.selectedIndex = this.selectedIndex > 0 ? this.selectedIndex - 1 : this.items.count - 1;
                        handled = true;
                    }
                    if ((e.which == 13 || e.key === "Enter")) {
                        this.SelectSystem(this.items.item(this.selectedIndex));
                        handled = true;
                    }
                    if (e.which == 27) {
                        this.popup.hide();
                        handled = true;
                    }
                    if (handled) {
                        e.cancelBubble = true;
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                    return true;
                }
                SelectSystem(item) {
                    this.searchField.clear();
                    this.popup.visible = false;
                    this.onSystemChanged(item.systemID);
                }
            }
            Components.SystemCombo = SystemCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class MailIcon extends Icons.BaseIcon {
                    constructor() {
                        super();
                        this.onMailCounterUpdated = new Sol.EventHandler();
                        this.number.maxValue = 99;
                        this.iconCode = '&#xf1d8;';
                        this.tip = Sol.Environment.resources.messages;
                        this.css.add("sol_barra_sistema_email");
                        this.numberAnimationEnabled = false;
                        this.sourceMenu = {
                            Pantalla: "MessageScreen",
                            Clase: "Solarium.Messaging.Message, Solarium.Messaging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            Icono: "&#xf1d8;",
                            RequiereModel: true
                        };
                        setInterval(() => this.refresh(), 300000);
                    }
                    refresh() {
                        Web.System.exec("scv5qy9z", "GetUnreadCounting", null, e => this.updateValue(e));
                    }
                    markAllAsRead() {
                        Web.System.exec("scv5qy9z", "MarkAllAsRead", null, e => this.updateValue(0));
                    }
                    reset() {
                        this.updateValue(0);
                    }
                    build() {
                        super.build();
                        this.refresh();
                    }
                    updateValue(value) {
                        this.number.value = value;
                        if (this.number.html)
                            this.number.html.style.visibility = value > 0 ? "visible" : "hidden";
                        this.onMailCounterUpdated.invoke(value);
                    }
                }
                Icons.MailIcon = MailIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let ScheduleView;
            (function (ScheduleView) {
                ScheduleView[ScheduleView["Day"] = 0] = "Day";
                ScheduleView[ScheduleView["Week"] = 1] = "Week";
                ScheduleView[ScheduleView["Month"] = 2] = "Month";
                ScheduleView[ScheduleView["Relation"] = 3] = "Relation";
                ScheduleView[ScheduleView["TodayAndTomorrow"] = 4] = "TodayAndTomorrow";
            })(ScheduleView = Components.ScheduleView || (Components.ScheduleView = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let MonthViewStartDateOption;
            (function (MonthViewStartDateOption) {
                MonthViewStartDateOption[MonthViewStartDateOption["CurrentDate"] = 0] = "CurrentDate";
                MonthViewStartDateOption[MonthViewStartDateOption["FirstDayOfMonth"] = 1] = "FirstDayOfMonth";
            })(MonthViewStartDateOption = Components.MonthViewStartDateOption || (Components.MonthViewStartDateOption = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let WeekViewDisplayMode;
            (function (WeekViewDisplayMode) {
                WeekViewDisplayMode[WeekViewDisplayMode["Fluid"] = 0] = "Fluid";
                WeekViewDisplayMode[WeekViewDisplayMode["Grid"] = 1] = "Grid";
            })(WeekViewDisplayMode = Components.WeekViewDisplayMode || (Components.WeekViewDisplayMode = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScheduleEventDialog extends Sol.DialogBox {
                constructor() {
                    super();
                    this.eventForm = new Components.ScheduleForm();
                    this.title = Sol.Environment.resources.new_event;
                    this.eventForm.showBackButton = false;
                    this.eventForm.onSaved = () => this.formSaved();
                    this.contentArea.add(this.eventForm);
                    this.css.add("sol_schedule_event_Dialog");
                }
                focus() {
                    this.eventForm.focus();
                }
                loadEntity(relationID) {
                    this.eventForm.loadEntity(relationID);
                }
                loadEvent(code) {
                    this.title = Sol.Environment.resources.edit_event;
                    this.eventForm.loadEvent(code);
                }
                formSaved() {
                    var _a, _b;
                    (_a = this.schedule) === null || _a === void 0 ? void 0 : _a.refresh();
                    (_b = this.schedule) === null || _b === void 0 ? void 0 : _b.notifyChanges();
                    this.parent.controls.remove(this);
                }
            }
            Components.ScheduleEventDialog = ScheduleEventDialog;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScheduleParticipant extends Sol.Control {
                constructor(model) {
                    super();
                    this.addCtr(model.ParticipantName, null);
                }
            }
            Components.ScheduleParticipant = ScheduleParticipant;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScheduleEvent extends Sol.Control {
                constructor(model, schedule, showDate) {
                    super();
                    this.dateRemark = new Sol.DateField();
                    this.hourRemark = new Sol.TimeField();
                    this.doneButton = new Sol.Button();
                    this.scheduleClass = "Solarium.Schedule.Scheduling, Solarium.Schedule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.css.add("event");
                    this.mySchedule = schedule;
                    this.code = model.ID;
                    if (model.IsLate)
                        this.css.add("event_late");
                    if (model.IsDone)
                        this.css.add("event_done");
                    if (model.IsEditable)
                        this.css.add("event_editable");
                    if (schedule.currentView == Components.ScheduleView.Relation)
                        this.css.add("relation");
                    var dateBox = new Sol.Control();
                    dateBox.css.add("date_box");
                    dateBox.visible = model.IsLate ? true : showDate;
                    this.add(dateBox);
                    var dayNumber = new Sol.Control("span");
                    dayNumber.css.add("date_number");
                    dayNumber.text = model.Day.toString();
                    dateBox.add(dayNumber);
                    var month = new Sol.Control();
                    month.css.add("date_month");
                    month.text = model.Month;
                    dateBox.add(month);
                    var weekDay = new Sol.Control();
                    weekDay.css.add("week_day");
                    weekDay.text = model.WeekDay;
                    dateBox.add(weekDay);
                    if (model.StartHour)
                        this.addCtr(model.StartHour, "start_hour", "span");
                    if (model.EventName) {
                        let eventName = Sol.Control.create(model.EventName, "event_name", "span");
                        if (model.EventColor != "#000000")
                            eventName.estilos.agregar("border-color", model.EventColor);
                        if (model.ContextClassHash) {
                            eventName.tip = Sol.Environment.resources.abrir;
                            eventName.css.add("event_name_clickable");
                            eventName.onClick = () => Web.System.edit(model.ContextClassHash.toString(), model.ID);
                        }
                        this.add(eventName);
                    }
                    this.addMany(Sol.List.from(model.Participants).select(p => new Components.ScheduleParticipant(p)));
                    let titleControl = this.addCtr(model.Title, "event_title");
                    if (model.IsEditable)
                        titleControl.onClick = () => this.edit();
                    if (model.RelationName)
                        this.addCtr(model.RelationName + ": " + model.EntityName, null, "p");
                    if (model.Condensed)
                        return;
                    if (model.Description) {
                        let descriptionDisplay = this.addCtr(model.Description, "event_description", "p");
                        if (model.IsEditable)
                            descriptionDisplay.onClick = () => this.edit();
                    }
                    if (!model.ShowTools)
                        return;
                    if (!model.IsDone) {
                        this.doneButton.css.add("button_done");
                        this.doneButton.type = Sol.ButtonType.Custom;
                        this.doneButton.text = Sol.Environment.resources.doneButton;
                        this.doneButton.onClick = () => this.doneEvent();
                        this.add(this.doneButton);
                        var deleteButton = new Sol.Button();
                        deleteButton.css.add("button_cancel");
                        deleteButton.type = Sol.ButtonType.Custom;
                        deleteButton.text = Sol.Environment.resources.deleteEventText;
                        deleteButton.onClick = () => this.deleteOnClick();
                        this.add(deleteButton);
                        var remarkButton = new Sol.Button();
                        remarkButton.css.add("button_remark");
                        remarkButton.type = Sol.ButtonType.Custom;
                        remarkButton.text = Sol.Environment.resources.remarkEventText;
                        this.add(remarkButton);
                        var spaceDate = new Sol.Control("span");
                        spaceDate.visible = false;
                        this.add(spaceDate);
                        remarkButton.onClick = () => spaceDate.visible = !spaceDate.visible;
                        spaceDate.add(this.dateRemark);
                        if (model.StartHour)
                            spaceDate.add(this.hourRemark);
                        var okSpaceButton = new Sol.Button();
                        okSpaceButton.css.add("ok_space_button");
                        okSpaceButton.type = Sol.ButtonType.Custom;
                        okSpaceButton.text = "Ok";
                        okSpaceButton.onClick = () => this.remarkEvent();
                        spaceDate.add(okSpaceButton);
                    }
                    else
                        this.css.add("sol_schedule_done");
                    if (model.HasFollowup) {
                        var separator = new Sol.Control("span");
                        separator.text = '|';
                        separator.css.add("separator");
                        this.add(separator);
                        const followups = new Components.FollowupsButton();
                        followups.css.add("followup_button");
                        followups.code = model.RelationID;
                        followups.className = "Solarium.SeguimientoRelación, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        ;
                        followups.associativeProperty = "Relación";
                        followups.automaticSaving = true;
                        followups.showUnread = false;
                        followups.contextClassName = model.ContextClass;
                        this.add(followups);
                    }
                }
                edit() {
                    const dialog = new Components.ScheduleEventDialog();
                    dialog.schedule = this.mySchedule;
                    dialog.loadEvent(this.code);
                    this.css.add("second_plan_event");
                    dialog.onClose = () => {
                        this.controls.remove(dialog);
                        this.css.remove("second_plan_event");
                    };
                    this.add(dialog);
                }
                deleteOnClick() {
                    this.parent.controls.remove(this);
                    let deleteModel = {
                        className: this.scheduleClass,
                        decisionID: null,
                        methodName: "DeleteMany",
                        selectionMode: Web.ActionSelectionMode.None,
                        filters: null,
                        ids: [this.code],
                        inputs: null
                    };
                    Web.System.exec("79k8j542h", "DoMultiple", deleteModel, () => { var _a; return (_a = this.mySchedule) === null || _a === void 0 ? void 0 : _a.notifyChanges(); });
                }
                remarkEvent() {
                    if (this.dateRemark.isEmpty() && this.hourRemark.isEmpty()) {
                        alert(Sol.Environment.resources.alertDateRemark);
                        return;
                    }
                    let fields = new Sol.List();
                    {
                        if (!this.dateRemark.isEmpty())
                            fields.add({ Campo: "Start", Valor: this.dateRemark.value });
                        fields.add({ Campo: "StartHour", Valor: this.hourRemark.value });
                        fields.add({ Campo: "IsRescheduling", Valor: true });
                    }
                    ;
                    let saveModel = {
                        className: this.scheduleClass,
                        id: this.code,
                        data: fields.toArray(),
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", saveModel, () => {
                        var _a, _b;
                        (_a = this.mySchedule) === null || _a === void 0 ? void 0 : _a.refresh();
                        (_b = this.mySchedule) === null || _b === void 0 ? void 0 : _b.notifyChanges();
                    });
                }
                doneEvent() {
                    let saveModel = {
                        className: this.scheduleClass,
                        id: this.code,
                        data: [{ Campo: "Done", Valor: true },
                            { Campo: "IsFinishing", Valor: true }],
                        lastUpdate: null
                    };
                    this.doneButton.enabled = false;
                    Web.System.exec("3b5v9v45", "Save", saveModel, () => {
                        var _a, _b;
                        (_a = this.mySchedule) === null || _a === void 0 ? void 0 : _a.refresh();
                        (_b = this.mySchedule) === null || _b === void 0 ? void 0 : _b.notifyChanges();
                    });
                }
            }
            Components.ScheduleEvent = ScheduleEvent;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScheduleViewBase extends Sol.Control {
            }
            Components.ScheduleViewBase = ScheduleViewBase;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class WeekView extends Components.ScheduleViewBase {
                constructor() {
                    super();
                    this.css.add("sol_schedule_week_view");
                }
                load(schedule, model) {
                    return schedule.weekViewMode == Components.WeekViewDisplayMode.Fluid ?
                        this.createFluidLayout(schedule, model) : this.createGridLayout(schedule, model);
                }
                createFluidLayout(schedule, model) {
                    const table = new Sol.Control("table");
                    const tableRow = new Sol.Control("tr");
                    const dates = Sol.List.from(model.Dates);
                    const result = new Sol.List();
                    const events = Sol.List.from(model.Events);
                    this.createHeader(false, table, dates);
                    tableRow.addMany(dates.select(date => {
                        let dateEvents = events.where(e => e.Date == date.Date);
                        let cell = new Sol.Control("td");
                        result.addMany(this.fillCell(cell, schedule, date, dateEvents.where(e => !!e.StartHour)));
                        const allDayEvents = dateEvents.where(e => !e.StartHour);
                        if (allDayEvents.hasItems()) {
                            cell.addCtr("Durante o dia", "sol_schedule_day_all");
                            result.addMany(this.fillCell(cell, schedule, date, allDayEvents));
                        }
                        return cell;
                    }));
                    table.add(tableRow);
                    this.add(table);
                    return result;
                }
                createGridLayout(schedule, model) {
                    let result = new Sol.List();
                    let table = new Sol.Control("table");
                    let dates = Sol.List.from(model.Dates);
                    let events = Sol.List.from(model.Events);
                    this.createHeader(true, table, dates);
                    let allDayEvents = events.where(e => !e.StartHour);
                    if (allDayEvents.hasItems())
                        result.addMany(this.createGridRow(schedule, "No dia", table, dates, allDayEvents));
                    let gridEvents = events.where(e => e.HasTime);
                    let hourEvents;
                    for (var hour = model.OpenHour; hour <= model.CloseHour; hour++) {
                        hourEvents = gridEvents.where(e => e.Hour === hour);
                        result.addMany(this.createGridRow(schedule, hour + ":00", table, dates, hourEvents));
                    }
                    this.add(table);
                    return result;
                }
                createGridRow(schedule, caption, table, dates, events) {
                    let result = new Sol.List();
                    let row = new Sol.Control("tr");
                    row.addCtr(caption, "sol_schedule_week_view_caption", "td");
                    row.addMany(dates.select(date => {
                        const dateEvents = events.where(e => e.Date == date.Date);
                        const cell = new Sol.Control("td");
                        result.addMany(this.fillCell(cell, schedule, date, dateEvents));
                        return cell;
                    }));
                    table.add(row);
                    return result;
                }
                createHeader(leftHeader, table, dates) {
                    let headerRow = new Sol.Control("tr");
                    if (leftHeader)
                        headerRow.addCtr(null, "sol_schedule_week_view_caption", "td");
                    headerRow.addMany(dates.select(date => {
                        const cell = new Sol.Control("td");
                        cell.addCtr(date.DayMonth, "sol_schedule_day_title");
                        cell.addCtr(date.Weekday, "sol_schedule_day_weekday");
                        if (date.HolidayName)
                            cell.addCtr(date.HolidayName, "sol_schedule_day_holiday");
                        return cell;
                    }));
                    table.add(headerRow);
                }
                fillCell(cell, schedule, date, events) {
                    const result = new Sol.List();
                    cell.addMany(events.select(e => {
                        const ev = new Components.ScheduleEvent(e, schedule, false);
                        result.add(ev);
                        return ev;
                    }));
                    if (!date.IsWorkDay)
                        cell.css.add("non_working_day");
                    return result;
                }
            }
            Components.WeekView = WeekView;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RelationView extends Components.ScheduleViewBase {
                load(schedule, model) {
                    const result = new Sol.List();
                    const events = Sol.List.from(model.Events);
                    this.addMany(events.select(e => {
                        const ev = new Components.ScheduleEvent(e, schedule, true);
                        result.add(ev);
                        return ev;
                    }));
                    if (!events.hasItems())
                        this.addCtr(Sol.Environment.resources.schedule_empty, "load_text");
                    return result;
                }
            }
            Components.RelationView = RelationView;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class MonthView extends Components.ScheduleViewBase {
                constructor() {
                    super();
                    this.css.add("sol_schedule_month_view");
                }
                load(schedule, model) {
                    const dates = Sol.List.from(model.Dates);
                    const eventList = Sol.List.from(model.Events);
                    const table = new Sol.Control("table");
                    const result = new Sol.List();
                    var weekday = dates.first().WeekDayNumber;
                    eventList.forEach(ev => ev.Condensed = true);
                    var currentRow = new Sol.Control("tr");
                    table.add(currentRow);
                    currentRow.addMany(Sol.List.range(0, 6).select(d => Sol.Control.create(new Date(2021, 12, 31)
                        .addDays(d)
                        .toLocaleString(Sol.Environment.language, { weekday: 'short' })
                        .toUpperCase()
                        .substring(0, 3), null, "th")));
                    currentRow = new Sol.Control("tr");
                    table.add(currentRow);
                    currentRow.addMany(Sol.List.range(1, weekday - 1).select(() => new Sol.Control("td")));
                    dates.forEach(date => {
                        let events = eventList.where(e => e.Date == date.Date);
                        let cell = new Sol.Control("td");
                        let dayHeader = cell.addCtr(date.DayMonth, "sol_schedule_month_view_day");
                        dayHeader.onClick = () => { var _a; return (_a = this.onDateClicked) === null || _a === void 0 ? void 0 : _a.call(this, date.Date); };
                        if (!date.IsWorkDay) {
                            cell.css.add("non_working_day");
                            if (date.HolidayName)
                                cell.addCtr(date.HolidayName, "sol_schedule_holiday_label");
                        }
                        let eventsWrapper = cell.addCtr(null, "sol_schedule_month_view_day_wrapper");
                        eventsWrapper.addMany(events.where(e => !!e.StartHour).select(e => {
                            const ev = new Components.ScheduleEvent(e, schedule, false);
                            result.add(ev);
                            return ev;
                        }));
                        const allDayEvents = events.where(e => !e.StartHour);
                        if (allDayEvents.hasItems())
                            eventsWrapper.addMany(allDayEvents.select(e => {
                                const ev = new Components.ScheduleEvent(e, schedule, false);
                                result.add(ev);
                                return ev;
                            }));
                        currentRow.add(cell);
                        if (weekday == 7) {
                            currentRow = new Sol.Control("tr");
                            table.add(currentRow);
                            weekday = 0;
                        }
                        weekday++;
                    });
                    this.add(table);
                    return result;
                }
            }
            Components.MonthView = MonthView;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DayView extends Components.ScheduleViewBase {
                constructor() {
                    super();
                    this.showDate = true;
                    this.css.add("sol_schedule_day_view");
                }
                load(schedule, model) {
                    const date = model.Dates[0];
                    const events = Sol.List.from(model.Events);
                    const result = new Sol.List();
                    this.controls.empty();
                    const container = new Sol.Control();
                    container.css.add("sol_schedule_day_container");
                    if (this.showDate) {
                        this.addCtr(date.FullDate, "sol_schedule_day_title");
                        this.addCtr(date.Weekday, "sol_schedule_day_weekday");
                    }
                    container.addMany(events.where(e => !!e.StartHour).select(e => {
                        const ev = new Components.ScheduleEvent(e, schedule, !this.showDate);
                        result.add(ev);
                        return ev;
                    }));
                    this.add(container);
                    const allDayEvents = events.where(e => !e.StartHour);
                    if (allDayEvents.hasItems()) {
                        if (this.showDate)
                            this.addCtr(Sol.Environment.resources.scheduleAllDay, "sol_schedule_day_all");
                        const allDayContainer = new Sol.Control();
                        allDayContainer.css.add("sol_schedule_day_container");
                        allDayContainer.addMany(allDayEvents.select(e => {
                            const ev = new Components.ScheduleEvent(e, schedule, !this.showDate);
                            result.add(ev);
                            return ev;
                        }));
                        this.add(allDayContainer);
                    }
                    if (!events.hasItems())
                        this.addCtr(Sol.Environment.resources.schedule_empty, "load_text");
                    return result;
                }
            }
            Components.DayView = DayView;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScheduleOptionsPanel extends Sol.Control {
                constructor() {
                    super();
                    this.providerList = new Sol.CheckList();
                    this.weekViewOptionsCombo = new Sol.Combo();
                    this.montlyViewOptionsCombo = new Sol.Combo();
                    this.css.add("sol_schedule_form");
                    this.addCtr(Sol.Environment.resources.scheduleView, null, "h5");
                    this.add(this.providerList);
                    this.addCtr(Sol.Environment.resources.scheduleViewOptions, null, "h5");
                    const weekMonthLabel = new Sol.Label(Sol.Environment.resources.scheduleWeekViewOptions);
                    weekMonthLabel.editor = this.montlyViewOptionsCombo;
                    this.weekViewOptionsCombo.add(new Sol.ComboItem(0, Sol.Environment.resources.scheduleWeekViewFluidOption));
                    this.weekViewOptionsCombo.add(new Sol.ComboItem(1, Sol.Environment.resources.scheduleWeekViewTableOption));
                    this.weekViewOptionsCombo.css.add("sol_schedule_view_combo_options");
                    this.add(weekMonthLabel);
                    this.add(this.weekViewOptionsCombo);
                    const viewMonthLabel = new Sol.Label(Sol.Environment.resources.scheduleViewMonth);
                    viewMonthLabel.editor = this.montlyViewOptionsCombo;
                    this.montlyViewOptionsCombo.add(new Sol.ComboItem(0, Sol.Environment.resources.scheduleViewMonthThirtyDays));
                    this.montlyViewOptionsCombo.add(new Sol.ComboItem(1, Sol.Environment.resources.scheduleViewMonthCurrent));
                    this.montlyViewOptionsCombo.css.add("sol_schedule_view_combo_options");
                    this.add(viewMonthLabel);
                    this.add(this.montlyViewOptionsCombo);
                    const backButton = new Sol.Button();
                    backButton.text = Sol.Environment.resources.back;
                    backButton.estilos.agregar("margin-left", "0px");
                    backButton.onClick = () => this.onCancel();
                    this.add(backButton);
                    const saveButton = new Sol.Button();
                    saveButton.text = Sol.Environment.resources.grabar;
                    saveButton.onClick = () => this.onSaved();
                    this.add(saveButton);
                }
                get monthViewStartDate() { return parseInt(this.montlyViewOptionsCombo.selectedCode); }
                set monthViewStartDate(value) { this.montlyViewOptionsCombo.selectedCode = value === null || value === void 0 ? void 0 : value.toString(); }
                get selectedProviders() { return this.providerList.selectedCodes.select(i => parseInt(i)).toArray(); }
                get weekViewMode() { return parseInt(this.weekViewOptionsCombo.selectedCode); }
                set weekViewMode(value) { this.weekViewOptionsCombo.selectedCode = value === null || value === void 0 ? void 0 : value.toString(); }
                loadProviders(options) {
                    this.providerList.options = options;
                }
                updateChecks() {
                    this.providerList.selectedCodes = Sol.List.from(this.mySchedule.selectedProviders).select(p => p.toString());
                }
            }
            Components.ScheduleOptionsPanel = ScheduleOptionsPanel;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class MessageContactDisplay extends Sol.Control {
                constructor(model) {
                    super();
                    this.model = model;
                    this.css.add("sol_message_contact");
                }
                build() {
                    const mainControl = this.model.RelationID && this.model.RelationID > 0
                        ? new Web.EntityPicture(this.model.RelationID)
                        : (() => {
                            const abbreviation = new Sol.Control();
                            abbreviation.text = this.model.Abbreviation;
                            abbreviation.css.add("sol_message_abbreviation");
                            abbreviation.estilos.agregar("background-color", this.model.Color);
                            return abbreviation;
                        })();
                    this.add(mainControl);
                    this.add(Sol.Control.create(this.model.Name, "sol_message_sender"));
                    if (this.model.Email)
                        this.add(Sol.Control.create(this.model.Email, "sol_message_description"));
                    if (this.model.Description)
                        this.add(Sol.Control.create(this.model.Description, "sol_message_description"));
                    super.build();
                }
            }
            Components.MessageContactDisplay = MessageContactDisplay;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ContactsSelector extends Sol.Control {
                constructor() {
                    super();
                    this.popup = new Sol.Popup();
                    this.searchField = new Sol.Field();
                    this.css.addMany(["sol_recipients_selector", "sol_campo"]);
                    this.searchField.placeHolder = Sol.Environment.resources.typeToSearch;
                    this.searchField.disableEnter = true;
                    this.searchField.css.empty();
                    this.searchField.onInput.subscribe(() => this.search());
                    this.searchField.onKeyUp = e => this.fieldKeyUp(e);
                    this.searchField.onKeyDown = e => this.fieldKeyDown(e);
                    this.searchField.onLeave.subscribe(() => this.checkInputText());
                    this.popup.visible = false;
                }
                get accountEditor() { var _a; return (_a = this.container) === null || _a === void 0 ? void 0 : _a.getEditor("Account"); }
                get isEmail() { var _a; return parseInt((_a = this.accountEditor) === null || _a === void 0 ? void 0 : _a.selectedCode) > 0; }
                get contacts() {
                    return this.controls.where(ctr => ctr instanceof Components.MessageContactDisplay).cast();
                }
                get value() {
                    return this.contacts.select(ct => [
                        { Campo: "ID", Valor: 0 },
                        { Campo: "Name", Valor: ct.model.Name },
                        { Campo: "Email", Valor: ct.model.Email },
                        { Campo: "Description", Valor: ct.model.Description },
                        { Campo: "Relation", Valor: ct.model.RelationID },
                        { Campo: "Color", Valor: ct.model.Color },
                        { Campo: "Profile", Valor: ct.model.Profile },
                        { Campo: "Abbreviation", Valor: ct.model.Abbreviation }
                    ])
                        .toArray();
                }
                set value(value) {
                    Sol.List.from(value).forEach(item => {
                        const data = Sol.List.from(item);
                        const model = {
                            ID: data.that(d => d.Campo == "ID").Valor,
                            Name: data.that(d => d.Campo == "Name").Valor,
                            Email: data.that(d => d.Campo == "Email").Valor,
                            Description: data.that(d => d.Campo == "Description").Valor,
                            RelationID: data.that(d => d.Campo == "Relation").Valor.Valor,
                            Color: data.that(d => d.Campo == "Color").Valor,
                            Profile: data.that(d => d.Campo == "Profile").Valor,
                            Abbreviation: data.that(d => d.Campo == "Abbreviation").Valor,
                        };
                        this.add(new Components.MessageContactDisplay(model));
                    });
                }
                addContact(model) {
                    if (!model)
                        return;
                    this.selectItem(model);
                }
                clear() { this.contacts.forEachReverse(ct => this.controls.remove(ct)); }
                isEmpty() { return !this.contacts.hasItems(); }
                foco() { this.searchField.foco(); }
                toControl() { return this; }
                build() {
                    if (!this.readonly) {
                        this.add(this.searchField);
                        this.add(this.popup);
                    }
                    if (this.accountEditor)
                        this.accountEditor.onChange = () => {
                            this.clear();
                            this.foco();
                        };
                    super.build();
                }
                addDisplayToPopup(model) {
                    const display = new Components.MessageContactDisplay(model);
                    display.onClick = () => this.selectItem(model);
                    return display;
                }
                addResults(results) {
                    results.groupBy("Section").forEach(section => {
                        let sectionArea = new Sol.Control();
                        sectionArea.addCtr(section.key, null, "h5");
                        sectionArea.css.add("sol_recipients_area");
                        sectionArea.controls.addMany(section.items.select(lg => this.addDisplayToPopup(lg)));
                        this.popup.add(sectionArea);
                    });
                }
                checkInputText() {
                    const filter = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                    if (this.isEmail && filter.test(this.searchField.value))
                        this.selectItem({
                            ID: 0,
                            Name: this.searchField.value,
                            Email: this.searchField.value
                        });
                }
                fieldKeyDown(e) {
                    if (e.key === "Backspace" && this.searchField.isEmpty() && !this.isEmpty())
                        this.controls.remove(this.contacts.last());
                }
                fieldKeyUp(e) {
                    if (e.key === "Enter")
                        this.checkInputText();
                }
                selectItem(model) {
                    this.controls.insert(this.controls.count - 2, new Components.MessageContactDisplay(model));
                    this.searchField.clear();
                    this.searchField.foco();
                    this.popup.hide();
                }
                search() {
                    if (this.ajax)
                        this.ajax.abort();
                    this.ajax = Web.System.exec("scv5qy9z", "SearchContacts", { term: this.searchField.value, emailMode: this.isEmail }, e => {
                        const results = Sol.List.from(e);
                        this.popup.clearContent();
                        if (!results.hasItems()) {
                            const emptyMessage = new Sol.Control();
                            emptyMessage.text = Sol.Environment.resources.no_encontrado;
                            this.popup.add(emptyMessage);
                        }
                        else
                            this.addResults(results);
                        this.popup.show();
                    });
                }
                validate() { return null; }
            }
            Components.ContactsSelector = ContactsSelector;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ContactsSelector", () => new Sol.Web.Components.ContactsSelector());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScheduleForm extends Sol.Control {
                constructor() {
                    super();
                    this.code = 0;
                    this.backButton = new Sol.Button();
                    this.errorMessage = new Sol.ScreenMessage();
                    this.dateField = new Sol.DateField();
                    this.endDate = new Sol.DateField();
                    this.description = new Sol.TextField();
                    this.notes = new Sol.TextField();
                    this.hour = new Sol.TimeField();
                    this.endHour = new Sol.TimeField();
                    this.typeEvent = new Components.DataCombo();
                    this.eventVisibility = new Sol.Combo();
                    this.eventVisibilityWrapper = new Sol.FieldWrapper();
                    this.saveButton = new Sol.Button();
                    this.saveAndNewButton = new Sol.Button();
                    this.titleField = new Sol.Field();
                    this.participantsField = new Components.ContactsSelector();
                    this._allowMarkOthers = false;
                    this.css.add("sol_schedule_form");
                    this.errorMessage.type = Sol.MessageType.Error;
                    this.errorMessage.visible = false;
                    this.add(this.errorMessage);
                    var dateControl = new Sol.FieldWrapper();
                    var dateLabel = new Sol.Label();
                    dateLabel.text = Sol.Environment.resources.date + ":*";
                    dateLabel.editor = this.dateField;
                    dateControl.add(dateLabel);
                    this.dateField.disableEnter = true;
                    dateControl.add(this.dateField);
                    this.add(dateControl);
                    var hourControl = new Sol.FieldWrapper();
                    var hourLabel = new Sol.Label();
                    hourLabel.text = Sol.Environment.resources.starHour + ":*";
                    hourLabel.editor = this.hour;
                    hourControl.add(hourLabel);
                    this.hour.disableEnter = true;
                    hourControl.add(this.hour);
                    this.add(hourControl);
                    var endDateControl = new Sol.FieldWrapper();
                    var endDateLabel = new Sol.Label();
                    endDateLabel.text = Sol.Environment.resources.endDate + ":";
                    endDateLabel.editor = this.endDate;
                    endDateControl.add(endDateLabel);
                    this.endDate.disableEnter = true;
                    endDateControl.add(this.endDate);
                    this.add(endDateControl);
                    var endHourControl = new Sol.FieldWrapper();
                    var endHourLabel = new Sol.Label();
                    endHourLabel.text = Sol.Environment.resources.endHour + ":";
                    endHourLabel.editor = this.endHour;
                    endHourControl.add(endHourLabel);
                    this.endHour.disableEnter = true;
                    endHourControl.add(this.endHour);
                    this.add(endHourControl);
                    var typeEventControl = new Sol.FieldWrapper();
                    var typeEventLabel = new Sol.Label();
                    typeEventLabel.text = Sol.Environment.resources.event_type;
                    typeEventLabel.editor = this.typeEvent;
                    this.typeEvent.className = "Solarium.Schedule.EventType, Solarium.Schedule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    typeEventControl.add(typeEventLabel);
                    typeEventControl.add(this.typeEvent);
                    this.typeEvent.refresh();
                    this.add(typeEventControl);
                    this.add(new Sol.LineBreak());
                    var entityControl = new Sol.FieldWrapper();
                    var entityLabel = new Sol.Label();
                    entityLabel.text = Sol.Environment.resources.event_relation + '*';
                    entityControl.add(entityLabel);
                    entityControl.add(this.participantsField);
                    this.add(entityControl);
                    var eventVisibilityLabel = new Sol.Label();
                    eventVisibilityLabel.text = Sol.Environment.resources.event_visibility;
                    eventVisibilityLabel.editor = this.eventVisibility;
                    this.eventVisibility.loadOptions([
                        { Code: "1", Description: Sol.Environment.resources.event_only_me },
                        { Code: "2", Description: Sol.Environment.resources.event_all }
                    ]);
                    this.eventVisibilityWrapper.add(eventVisibilityLabel);
                    this.eventVisibilityWrapper.add(this.eventVisibility);
                    this.add(this.eventVisibilityWrapper);
                    var titleControl = new Sol.Control();
                    titleControl.css.add("sol_detalles_wrapper_title");
                    var titleLabel = new Sol.Label();
                    titleLabel.text = Sol.Environment.resources.title + ":*";
                    this.titleField.maxLength = 50;
                    this.titleField.estilos.agregar("width", "100%");
                    titleLabel.editor = this.titleField;
                    titleControl.add(titleLabel);
                    this.titleField.disableEnter = true;
                    titleControl.add(this.titleField);
                    this.add(titleControl);
                    var descControl = new Sol.Control();
                    descControl.css.add("sol_detalles_wrapper_description");
                    var descriptionLabel = new Sol.Label();
                    descriptionLabel.text = Sol.Environment.resources.description;
                    descControl.add(descriptionLabel);
                    this.description.disableEnter = true;
                    descControl.add(this.description);
                    this.add(descControl);
                    let notesControl = new Sol.Control();
                    notesControl.css.add("sol_detalles_wrapper_description");
                    let notesLabel = new Sol.Label();
                    notesLabel.text = Sol.Environment.resources.notes;
                    notesControl.add(notesLabel);
                    this.description.disableEnter = true;
                    notesControl.add(this.notes);
                    this.add(notesControl);
                    this.backButton.text = Sol.Environment.resources.back;
                    this.backButton.estilos.agregar("margin-left", "0px");
                    this.backButton.onClick = () => this.onCancel();
                    this.add(this.backButton);
                    this.saveButton.text = Sol.Environment.resources.grabar;
                    this.saveButton.onClick = () => this.onSaveClick(false);
                    this.add(this.saveButton);
                    this.saveAndNewButton.text = Sol.Environment.resources.saveAndNew;
                    this.saveAndNewButton.onClick = () => this.onSaveClick(true);
                    this.add(this.saveAndNewButton);
                }
                set showBackButton(value) { this.backButton.visible = value; }
                ;
                get allowMarkOthers() { return this._allowMarkOthers; }
                ;
                set allowMarkOthers(value) {
                    this._allowMarkOthers = value;
                    this.eventVisibilityWrapper.visible = this._allowMarkOthers;
                }
                addContact(model) {
                    this.participantsField.addContact(model);
                }
                clear() {
                    this.dateField.setToday();
                    this.endDate.clear();
                    this.hour.clear();
                    this.endHour.clear();
                    this.typeEvent.clear();
                    this.titleField.clear();
                    this.description.clear();
                    this.notes.clear();
                    this.participantsField.clear();
                }
                focus() {
                    setTimeout(() => this.dateField.foco(), 300);
                }
                loadEntity(relationID) {
                    if (!relationID)
                        return;
                    Web.System.exec("nlskd23jor", "GetContactInfo", { relationID: relationID }, e => this.participantsField.addContact(e));
                }
                loadEvent(code) {
                    const request = {
                        className: Components.Schedule.scheduleClass,
                        code: code,
                        subtype: false
                    };
                    Web.System.exec("sn9d23vs7d", "Load", request, model => {
                        const data = Sol.List.from(model.Data);
                        this.code = code;
                        this.dateField.value = data.that(d => d.Campo == "Start").Valor;
                        this.endDate.value = data.that(d => d.Campo == "EndDate").Valor;
                        this.hour.value = data.that(d => d.Campo == "StartHour").Valor;
                        this.endHour.value = data.that(d => d.Campo == "EndHour").Valor;
                        this.participantsField.value = data.that(d => d.Campo == "Participants").Valor;
                        this.typeEvent.value = data.that(d => d.Campo == "EventType").Valor;
                        this.titleField.value = data.that(d => d.Campo == "Nombre").Valor;
                        this.description.value = data.that(d => d.Campo == "Description").Valor;
                        this.notes.value = data.that(d => d.Campo == "Notes").Valor;
                        this.eventVisibility.value = data.that(d => d.Campo == "EventVisibility").Valor;
                    });
                }
                onSaveClick(keepOpen) {
                    this.errorMessage.visible = false;
                    if (!this.validate())
                        return;
                    this.save(keepOpen);
                }
                save(keepOpen) {
                    if (!keepOpen)
                        this.saveButton.enabled = false;
                    let savingData = {
                        className: Components.Schedule.scheduleClass,
                        id: this.code,
                        data: [{ Campo: "Start", Valor: this.dateField.value },
                            { Campo: "EndDate", Valor: this.endDate.value },
                            { Campo: "StartHour", Valor: this.hour.value },
                            { Campo: "EndHour", Valor: this.endHour.value },
                            { Campo: "Participants", Valor: this.participantsField.value },
                            { Campo: "EventType", Valor: this.typeEvent.value },
                            { Campo: "EventVisibility", Valor: this.eventVisibility.value },
                            { Campo: "Nombre", Valor: this.titleField.value },
                            { Campo: "Description", Valor: this.description.value },
                            { Campo: "Notes", Valor: this.notes.value }],
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", savingData, () => {
                        if (!keepOpen) {
                            this.saveButton.enabled = false;
                            this.onSaved();
                        }
                        else {
                            this.clear();
                            this.participantsField.addContact(this.defaultContact);
                            this.loadEntity(this.relationId);
                            this.focus();
                        }
                    }, () => this.saveButton.enabled = false);
                }
                validate() {
                    if (this.titleField.isEmpty()) {
                        this.errorMessage.caption = Sol.Environment.resources.schedule_field_title_error;
                        this.errorMessage.visible = true;
                        return false;
                    }
                    if (this.dateField.isEmpty()) {
                        this.errorMessage.caption = Sol.Environment.resources.schedule_field_date_error;
                        this.errorMessage.visible = true;
                        return false;
                    }
                    if (this.participantsField.isEmpty()) {
                        this.errorMessage.caption = Sol.Environment.resources.schedule_field_participants_error;
                        this.errorMessage.visible = true;
                        return false;
                    }
                    return true;
                }
            }
            Components.ScheduleForm = ScheduleForm;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class Schedule extends Sol.Control {
                constructor(model) {
                    super();
                    this.addEventButton = new Sol.Button();
                    this.baseDateField = new Sol.DateField();
                    this.mainArea = new Sol.Control();
                    this.refreshButton = new Sol.Button();
                    this.events = new Sol.List();
                    this.form = new Components.ScheduleForm();
                    this.expandButton = new Sol.Button();
                    this.dayButton = new Sol.Button();
                    this.weekButton = new Sol.Button();
                    this.monthButton = new Sol.Button();
                    this.optionsButton = new Sol.Button();
                    this.optionsPanel = new Components.ScheduleOptionsPanel();
                    this.updateProviders = false;
                    this.showDoneButton = new Sol.Button();
                    this.forwardButton = new Sol.Button();
                    this.backwardButton = new Sol.Button();
                    this.toolboxBar = new Sol.Control();
                    this.loginSelector = new Components.Selectors.LoginSelector();
                    this.allowCreateEvent = true;
                    this.defaultContact = {
                        RelationID: Web.System.loginID,
                        Name: Web.System.userName
                    };
                    this.selectedProviders = [85339249];
                    this.showTitle = true;
                    this.scheduleTitle = Sol.Environment.resources.schedule;
                    this.css.add("sol_schedule");
                    this.mainArea.css.add("sol_schedule_main_area");
                    this.showExpandButton = false;
                    this.loginID = Web.System.loginID;
                    this.systemLoginID = Web.System.loginID;
                    this.providers = model === null || model === void 0 ? void 0 : model.Providers;
                    this.selectedProviders = model === null || model === void 0 ? void 0 : model.SelectedProviders;
                    this.currentView = model === null || model === void 0 ? void 0 : model.DefaultView;
                    this.monthViewStartDate = model === null || model === void 0 ? void 0 : model.MonthViewStartDate;
                    this.weekViewMode = model === null || model === void 0 ? void 0 : model.WeekViewOption;
                    this.showLoginSelector = model === null || model === void 0 ? void 0 : model.AllowManageOtherSchedules;
                    this.showReportButton = model === null || model === void 0 ? void 0 : model.ViewReportScreen;
                    this.baseDateField.setToday();
                }
                get loginID() { return this._loginID; }
                set loginID(value) {
                    this._loginID = value;
                    this.loginSelector.loadByCode(value);
                }
                get showLoginSelector() { return this.loginSelector.visible; }
                set showLoginSelector(value) { this.loginSelector.visible = value; }
                get monthViewStartDate() { return this._monthViewStartDate; }
                set monthViewStartDate(value) { this._monthViewStartDate = value; }
                get currentView() { return this._currentView; }
                set currentView(value) {
                    this.cancelForms();
                    this._currentView = value;
                    this.dayButton.checked = value == Components.ScheduleView.Day;
                    this.weekButton.checked = value == Components.ScheduleView.Week;
                    this.monthButton.checked = value == Components.ScheduleView.Month;
                    this.dayButton.visible = value != Components.ScheduleView.Relation;
                    this.weekButton.visible = value != Components.ScheduleView.Relation;
                    this.monthButton.visible = value != Components.ScheduleView.Relation;
                }
                ;
                get showExpandButton() { return this.expandButton.visible; }
                set showExpandButton(v) { this.expandButton.visible = v; }
                get weekViewMode() { return this._weekViewMode; }
                set weekViewMode(value) { this._weekViewMode = value; }
                notifyChanges() {
                    if (this.onChange)
                        this.onChange(this);
                }
                refresh() {
                    if (this.baseDateField.isEmpty())
                        return;
                    let baseDate = this.baseDateField.value;
                    if (this.currentView == Components.ScheduleView.Month && this.monthViewStartDate == Components.MonthViewStartDateOption.FirstDayOfMonth)
                        baseDate = baseDate.substring(0, baseDate.length - 2) + "01";
                    this.updateSchedule(baseDate);
                }
                build() {
                    this.addTitle();
                    this.initializeToolBox();
                    this.add(this.mainArea);
                    this.initializeForm();
                    this.initializeOptionsPanel();
                    this.addLoading();
                    super.build();
                }
                loadSchedule(model) {
                    this.mainArea.controls.empty();
                    this.updateProviders = false;
                    this.events.empty();
                    this.loadView(model);
                    this.form.allowMarkOthers = model.CanMarkOthers;
                }
                updateSchedule(baseDate) {
                    let data = {
                        LoginID: this.loginID,
                        RelationID: this.relationID,
                        BaseDate: baseDate,
                        View: this.currentView,
                        WeekViewMode: this.weekViewMode,
                        Providers: this.selectedProviders,
                        UpdateProviders: this.updateProviders,
                        ShowDone: this.showDoneButton.checked
                    };
                    Web.System.exec("9sw4x1Dy", "GetSchedule", data, e => this.loadSchedule(e));
                }
                addTitle() {
                    if (this.showTitle)
                        this.addCtr(this.scheduleTitle, null, "h4");
                }
                addLoading() {
                    this.mainArea.addCtr(Sol.Environment.resources.cargando, "load_text");
                }
                changeView(mode) {
                    this.currentView = mode;
                    this.refresh();
                    this.saveUserViewMode();
                }
                tabViewClick(button) {
                    this.changeView(button.data);
                }
                initializeToolBox() {
                    this.loginSelector.onValueModified.subscribe(() => this.loginID = this.loginSelector.selectedCode);
                    this.toolboxBar.add(this.loginSelector);
                    this.loginSelector.onItemSelected = item => {
                        this.optionsButton.visible = (item.code === this.systemLoginID);
                        this.defaultContact.RelationID = item.code;
                        this.defaultContact.Name = item.displayText || item.text;
                    };
                    this.dayButton.imageKey = "day";
                    this.dayButton.text = Sol.Environment.resources.scheduleDayButton;
                    this.dayButton.type = Sol.ButtonType.Alternate;
                    this.dayButton.css.add("sol_schedule_view_button sol_schedule_day_button");
                    this.dayButton.onChecked = () => this.tabViewClick(this.dayButton);
                    this.dayButton.data = Components.ScheduleView.Day;
                    this.toolboxBar.add(this.dayButton);
                    this.weekButton.imageKey = "week";
                    this.weekButton.text = Sol.Environment.resources.scheduleWeekButton;
                    this.weekButton.type = Sol.ButtonType.Alternate;
                    this.weekButton.css.add("sol_schedule_view_button");
                    this.weekButton.onChecked = () => this.tabViewClick(this.weekButton);
                    this.weekButton.data = Components.ScheduleView.Week;
                    this.toolboxBar.add(this.weekButton);
                    this.monthButton.imageKey = "month";
                    this.monthButton.text = Sol.Environment.resources.scheduleMonthButton;
                    this.monthButton.type = Sol.ButtonType.Alternate;
                    this.monthButton.css.add("sol_schedule_view_button");
                    this.monthButton.onChecked = () => this.tabViewClick(this.monthButton);
                    this.monthButton.data = Components.ScheduleView.Month;
                    this.toolboxBar.add(this.monthButton);
                    if (this.allowCreateEvent) {
                        this.addEventButton.imageCode = "&#xf067";
                        this.addEventButton.text = Sol.Environment.resources.new_event;
                        this.addEventButton.css.add("sol_schedule_button");
                        this.addEventButton.onClick = () => this.newEventClick();
                        this.toolboxBar.add(this.addEventButton);
                    }
                    this.optionsButton.imageCode = "&#xf013";
                    this.optionsButton.text = Sol.Environment.resources.options;
                    this.optionsButton.css.add("sol_schedule_button");
                    this.optionsButton.onClick = () => this.optionsClick();
                    if (this.providers)
                        this.toolboxBar.add(this.optionsButton);
                    this.backwardButton.text = "<";
                    this.backwardButton.tip = Sol.Environment.resources.backwardButton;
                    this.backwardButton.css.add("sol_schedule_button_backward");
                    this.backwardButton.onClick = () => {
                        if (this.dayButton.checked || this.weekButton.checked)
                            this.baseDateField.addDays(-1);
                        if (this.monthButton.checked)
                            this.baseDateField.addMonths(-1);
                        this.refresh();
                    };
                    this.toolboxBar.add(this.backwardButton);
                    this.baseDateField.css.add("sol_schedule_base_date");
                    this.baseDateField.onChange = () => this.refresh();
                    this.toolboxBar.add(this.baseDateField);
                    this.forwardButton.text = ">";
                    this.forwardButton.tip = Sol.Environment.resources.forwardButton;
                    this.forwardButton.css.add("sol_schedule_button_forward");
                    this.forwardButton.onClick = () => {
                        if (this.dayButton.checked || this.weekButton.checked)
                            this.baseDateField.addDays(1);
                        if (this.monthButton.checked)
                            this.baseDateField.addMonths(1);
                        this.refresh();
                    };
                    this.toolboxBar.add(this.forwardButton);
                    this.refreshButton.imageCode = "&#xf021";
                    this.refreshButton.tip = Sol.Environment.resources.refreshButton;
                    this.refreshButton.estilos.agregar("margin-left", "-1px");
                    this.refreshButton.onClick = () => this.refresh();
                    this.toolboxBar.add(this.refreshButton);
                    this.showDoneButton.imageCode = "&#xf274";
                    this.showDoneButton.type = Sol.ButtonType.Alternate;
                    this.showDoneButton.checked = true;
                    this.showDoneButton.tip = Sol.Environment.resources.scheduleShowDone;
                    this.showDoneButton.onChecked = () => this.refresh();
                    this.toolboxBar.add(this.showDoneButton);
                    if (this.showReportButton) {
                        let reportButton = new Sol.Button();
                        reportButton.imageCode = "&#xf02f;";
                        reportButton.onClick = () => Web.System.screens.openScreen("Registro", Schedule.scheduleClass);
                        this.toolboxBar.add(reportButton);
                    }
                    this.expandButton.imageCode = "&#xf0b2";
                    this.expandButton.tip = Sol.Environment.resources.expand_schedule;
                    this.expandButton.estilos.agregar("margin-left", "0px");
                    this.expandButton.onClick = () => this.initializeScheduleScreen();
                    this.toolboxBar.add(this.expandButton);
                    this.toolboxBar.css.addMany(["sol_toolbar", "sol_schedule_toolbox"]);
                    this.add(this.toolboxBar);
                }
                initializeForm() {
                    this.form.css.add("sol_schedule_form");
                    this.form.onCancel = () => this.cancelForms();
                    this.form.onSaved = () => this.formSaved();
                    this.add(this.form);
                    this.form.visible = false;
                }
                initializeOptionsPanel() {
                    this.optionsPanel.monthViewStartDate = this.monthViewStartDate;
                    this.optionsPanel.weekViewMode = this.weekViewMode;
                    this.optionsPanel.visible = false;
                    this.optionsPanel.mySchedule = this;
                    this.optionsPanel.loadProviders(this.providers);
                    this.optionsPanel.onCancel = () => this.cancelForms();
                    this.optionsPanel.onSaved = () => this.optionsSaved();
                    this.add(this.optionsPanel);
                }
                cancelForms() {
                    this.mainArea.visible = true;
                    this.form.visible = false;
                    this.optionsPanel.visible = false;
                }
                loadView(model) {
                    const factory = [() => new Components.DayView(), () => new Components.WeekView(), () => new Components.MonthView(), () => new Components.RelationView()];
                    const view = factory[this.currentView]();
                    this.events = view.load(this, model);
                    view.onDateClicked = d => this.openDay(d);
                    this.mainArea.add(view);
                }
                newEventClick() {
                    this.form.relationId = this.relationID;
                    this.form.defaultContact = this.defaultContact;
                    this.mainArea.visible = false;
                    this.optionsPanel.visible = false;
                    this.form.visible = true;
                    this.form.clear();
                    this.form.addContact(this.defaultContact);
                    this.form.loadEntity(this.relationID);
                }
                openDay(date) {
                    this.baseDateField.value = date;
                    this.changeView(Components.ScheduleView.Day);
                }
                optionsClick() {
                    this.mainArea.visible = false;
                    this.form.visible = false;
                    this.optionsPanel.visible = true;
                    this.optionsPanel.updateChecks();
                }
                formSaved() {
                    this.cancelForms();
                    this.refresh();
                    this.notifyChanges();
                }
                optionsSaved() {
                    this.updateProviders = true;
                    this.selectedProviders = this.optionsPanel.selectedProviders;
                    this.monthViewStartDate = this.optionsPanel.monthViewStartDate;
                    this.weekViewMode = this.optionsPanel.weekViewMode;
                    this.saveConfiguration();
                    this.cancelForms();
                    this.refresh();
                }
                initializeScheduleScreen() {
                    this.scheduleScreen = new Web.Screens.ScheduleScreen();
                    this.scheduleScreen.screenCaption = this.scheduleTitle;
                    Web.System.screens.addScreen(this.scheduleScreen);
                    Web.System.screens.showScreen(this.scheduleScreen);
                }
                saveUserViewMode() {
                    if (this.currentView == Components.ScheduleView.Relation)
                        return;
                    Web.System.exec("9sw4x1Dy", "SaveUserViewMode", { currentView: this.currentView });
                }
                saveConfiguration() {
                    if (this.currentView == Components.ScheduleView.Relation)
                        return;
                    Web.System.exec("9sw4x1Dy", "SaveUserConfiguration", {
                        startDateOption: this.monthViewStartDate,
                        weekViewMode: this.weekViewMode
                    });
                }
            }
            Schedule.scheduleClass = "Solarium.Schedule.Scheduling, Solarium.Schedule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
            Components.Schedule = Schedule;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ScheduleScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.css.add("sol_schedule_screen");
                    this.screenCaption = Sol.Environment.resources.schedule;
                }
                build() {
                    super.build();
                    let schedule = new Web.Components.Schedule(this.model);
                    this.add(schedule);
                    setTimeout(() => schedule.refresh(), 300);
                }
            }
            Screens.ScheduleScreen = ScheduleScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScheduleIcon extends Components.Icons.BaseIcon {
                constructor() {
                    super();
                    this.baseDateField = new Sol.DateField();
                    this.baseDateField.setToday();
                    this.number.maxValue = 99;
                    this.iconCode = '&#xf073;';
                    this.css.add("sol_barra_sistema_schedule");
                    this.numberAnimationEnabled = false;
                    this.sourceMenu = {
                        Pantalla: "Solarium.Schedule.ScheduleScreen",
                        Clase: "Solarium.Schedule.Scheduling, Solarium.Schedule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        Icono: '&#xf073;',
                        RequiereModel: true
                    };
                    setInterval(() => this.refresh(), 900000);
                }
                refresh() {
                    let baseDate = this.baseDateField.value;
                    let data = {
                        LoginID: Web.System.loginID,
                        BaseDate: baseDate,
                        View: Components.ScheduleView.TodayAndTomorrow,
                        WeekViewMode: Components.WeekViewDisplayMode.Fluid,
                        Providers: null,
                        UpdateProviders: false,
                        ShowDone: false
                    };
                    Web.System.exec("9sw4x1Dy", "GetSchedule", data, e => this.updateValue(e.EventCount));
                }
                reset() {
                    this.updateValue(0);
                }
                build() {
                    super.build();
                    this.refresh();
                }
                updateValue(value) {
                    this.number.value = value;
                    if (this.number.html)
                        this.number.html.style.visibility = value > 0 ? "visible" : "hidden";
                    if (this.number.value > 0) {
                        this.tip = "Agenda - " + this.number.value + " " + Sol.Environment.resources.schedule_todaytomorrow;
                    }
                    else {
                        this.tip = "Agenda - " + Sol.Environment.resources.schedule_todaytomorrow_empty;
                    }
                }
            }
            Components.ScheduleIcon = ScheduleIcon;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var MailIcon = Sol.Web.Components.Icons.MailIcon;
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SystemBar extends Sol.Control {
                constructor(model) {
                    super();
                    this.leftZone = new Sol.Control();
                    this.rightZone = new Sol.Control();
                    this.systemTitle = new Sol.Control("span");
                    this.mailIcon = new MailIcon();
                    this.scheduleIcon = new Components.ScheduleIcon();
                    this.usernameLabel = new Sol.Control("span");
                    this.systemSelector = new Components.SystemCombo();
                    this.leftZone.css.add("sol_barra_sistema_izquierda");
                    this.add(this.leftZone);
                    this.rightZone.css.add("sol_barra_sistema_derecha");
                    this.add(this.rightZone);
                    this.systemTitle.text = model.CompanyName;
                    this.leftZone.add(this.systemTitle);
                    if (!model.EmbedMode)
                        document.getElementsByTagName("title")[0].innerText = model.CompanyName;
                    if (model.HasSchedule) {
                        this.rightZone.add(this.scheduleIcon);
                    }
                    this.rightZone.add(this.mailIcon);
                    const userPicture = new Web.EntityPicture(model.LoginID);
                    this.rightZone.add(userPicture);
                    this.usernameLabel.text = model.User;
                    this.usernameLabel.css.add("sol_barra_sistema_usuario");
                    this.rightZone.add(this.usernameLabel);
                    if (model.HasMultipleSystems) {
                        this.systemSelector.onSystemChanged = (code) => {
                            if (!Web.System.screens.backToDashboard())
                                return;
                            Web.System.openSystem(code);
                        };
                        this.rightZone.add(this.systemSelector);
                    }
                    const supportButton = new Sol.Control("span");
                    supportButton.text = Sol.Environment.resources.soporte;
                    supportButton.css.add("sol_barra_sistema_soporte");
                    supportButton.onClick = () => this.openSupport();
                    if (model.HasSupport)
                        this.rightZone.add(supportButton);
                    if (!model.EmbedMode) {
                        const newTabButton = new Sol.Button();
                        newTabButton.tip = Sol.Environment.resources.newTab;
                        newTabButton.imageCode = "&#xf2d2;";
                        newTabButton.type = Sol.ButtonType.Custom;
                        newTabButton.css.add("sol_barra_sistema_new_tab");
                        newTabButton.onClick = () => this.openTab();
                        this.rightZone.add(newTabButton);
                        const exitLink = new Sol.Control("a");
                        exitLink.atributos.agregar("href", model.ExitUrl);
                        exitLink.text = Sol.Environment.resources.salir;
                        exitLink.css.add("sol_portada_salir");
                        exitLink.onClick = () => exitLink.clickResult = Web.System.screens.backToDashboard();
                        this.rightZone.add(exitLink);
                    }
                    this.css.add("sol_barra_sistema");
                    this.add(new Sol.LineBreak());
                }
                get onMailCounterUpdated() { return this.mailIcon.onMailCounterUpdated; }
                set onMailCounterUpdated(v) { this.mailIcon.onMailCounterUpdated = v; }
                refreshScheduleCounter() { this.scheduleIcon.refresh(); }
                markAllMailAsRead() { this.mailIcon.markAllAsRead(); }
                resetScheduleCounter() { this.scheduleIcon.reset(); }
                refreshMailCounter() { this.mailIcon.refresh(); }
                resetMailCounter() { this.mailIcon.reset(); }
                openSupport() {
                    const SCREEN = "Registro";
                    const CLASS_NAME = "Solarium.Software.Backlog, Solarium.Software, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    const ICON = "&#xf1cd;";
                    Web.System.screens.openScreen(SCREEN, CLASS_NAME, null, ICON);
                }
                openTab() {
                    Web.System.exec("hjkj28d", "GetTemporaryTicket", {}, t => Web.System.openTab(t));
                }
            }
            Components.SystemBar = SystemBar;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class SystemScreen extends Sol.Control {
                constructor(model) {
                    super();
                    this.menu = new Web.Components.SystemMenu();
                    this.screens = new Screens.ScreensZone();
                    this.model = model;
                    this.css.add("sol_system");
                    Web.System.home = this;
                    Web.System.companyName = model.CompanyName;
                    Web.System.userName = model.User;
                    Web.System.loginID = model.LoginID;
                    Web.System.commonPermissions = Sol.List.from(model.CommonPermissions);
                    Sol.Environment.defaultCurrency = model.DefaultCurrency;
                    Sol.Environment.currencies = model.Currencies;
                    this.systemBar = new Web.Components.SystemBar(model);
                    this.add(this.systemBar);
                    this.add(this.menu);
                    this.menu.favoriteIcons = model.FavoriteIcons;
                    this.menu.menus = model.Menus;
                    this.menu.home = this;
                    Web.System.screens = this.screens;
                    this.screens.css.add("sol_pantallas");
                    this.screens.systemScreen = this;
                    this.add(this.screens);
                    this.screens.menuBag = Sol.List.from(model.Menus);
                    this.screens.currentDashboardCode = model.Start.Code;
                    this.screens.openScreenWithModel("DashboardScreen", null, model.Start);
                    if (model.ForceChangePassword)
                        this.openChangePasswordScreen();
                    this.applyTheme(model.Theme);
                }
                get showSystemBar() { return this.systemBar.visible; }
                set showSystemBar(value) { this.systemBar.visible = value; }
                closeMenu() { }
                refreshMenus() {
                    Web.System.exec("5swjkiuy", "GetMenus", null, menus => {
                        this.menu.menus = menus;
                        this.menu.loadMenus();
                    });
                }
                refreshMailCounter() { this.systemBar.refreshMailCounter(); }
                resetMailCounter() { this.systemBar.resetMailCounter(); }
                applyTheme(theme) {
                    const style = document.getElementById("solThemeStyle");
                    style.innerHTML = `#sol { --mainColor: ${theme.MainColor}; --secondColor: ${theme.SecondColor}; --textColor: ${theme.TextColor}; --titleColor: ${theme.TitleColor}; `;
                }
                openChangePasswordScreen() {
                    const screen = new Screens.ChangePassword();
                    screen.showCancel = false;
                    Web.System.home.showSystemBar = false;
                    Web.System.screens.showNavigation = false;
                    Web.System.screens.addScreen(screen);
                    Web.System.screens.showScreen(screen);
                }
            }
            Screens.SystemScreen = SystemScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SystemMenu extends Sol.Control {
                constructor() {
                    super();
                    this.menuList = new Sol.Control("ul");
                    this.garbageIcon = new Components.Icons.SimpleIcon();
                    this.iconsSpace = new Sol.Control();
                    this.css.addMany(["sol_menu", "sol_no_scroll", "sol_menu_condensed"]);
                    this.menuList.css.add("sol_menu_principal");
                    this.add(this.menuList);
                }
                get items() { return this.menuList.controls.cast(); }
                get menuState() { return this._menuState; }
                set menuState(value) {
                    this._menuState = value;
                    this.css.toggleValue("sol_menu_condensed", value != Components.MenuState.Expanded);
                }
                addFavoriteIcon(icon) {
                    icon.tip = icon.text;
                    icon.draggable = true;
                    icon.onDragStart = (me, e) => this.favoriteIconDragStart(me, e);
                    this.iconsSpace.controls.insert(0, icon);
                }
                loadMenus() {
                    this.menuList.controls.empty();
                    Sol.List.from(this.menus).forEach(mn => {
                        var menu = new Components.MenuItem();
                        menu.icon = mn.Icono;
                        menu.menuText = mn.Nombre;
                        menu.systemMenu = this;
                        menu.requiresModel = mn.RequiereModel;
                        menu.menuInfo = mn;
                        this.menuList.add(menu);
                        var submenu = new Sol.Control("ul");
                        submenu.estilos.agregar("display", "block");
                        submenu.visible = false;
                        menu.add(submenu);
                        Sol.List.from(mn.Submenus).forEach(si => {
                            var menuItem = new Components.MenuItem();
                            menuItem.icon = si.Icono;
                            menuItem.menuText = si.Nombre;
                            menuItem.systemMenu = this;
                            menuItem.screenName = si.Pantalla;
                            menuItem.className = si.Clase;
                            menuItem.systemMessage = si.MensajeDeSistema;
                            menuItem.requiresModel = si.RequiereModel;
                            menuItem.menuInfo = si;
                            submenu.add(menuItem);
                        });
                    });
                }
                toggleState() {
                    this.menuState = this.menuState == Components.MenuState.Expanded ? Components.MenuState.Condensed : Components.MenuState.Expanded;
                    if (this.menuState == Components.MenuState.Condensed)
                        this.items.forEach(i => i.isExpanded = false);
                }
                build() {
                    super.build();
                    this.loadMenus();
                    this.addLogo();
                    this.addFavorites();
                }
                addFavorites() {
                    let favorites = Sol.List.from(this.favoriteIcons);
                    if (!favorites.hasItems())
                        return;
                    this.iconsSpace.css.add("sol_menu_favorites");
                    this.iconsSpace.controls.addMany(favorites.select(f => {
                        let icon = Components.Icons.BaseIcon.fromMenu(f);
                        icon.tip = icon.text;
                        icon.draggable = true;
                        icon.onDragStart = (me, e) => this.favoriteIconDragStart(me, e);
                        icon.iconCode = unescape(icon.iconCode);
                        return icon;
                    }));
                    this.garbageIcon.css.add("garbage");
                    this.garbageIcon.visible = false;
                    this.garbageIcon.labelText = Sol.Environment.resources.eliminar;
                    this.garbageIcon.iconCode = "&#xf00d;";
                    this.garbageIcon.onDragOver = (me, e) => e.preventDefault();
                    this.garbageIcon.onDrop = (me, e) => this.favoriteIconGarbageDrop(me, e);
                    this.iconsSpace.add(this.garbageIcon);
                    this.add(this.iconsSpace);
                }
                addLogo() {
                    if (!this.home.model.Logo)
                        return;
                    this.add(new Sol.ImageBox(Sol.Environment.filePath + this.home.model.Logo));
                }
                favoriteIconDragStart(me, e) {
                    var itemDragged = me;
                    e.dataTransfer.setData("sol_control", itemDragged.sourceMenu.LanguageKey);
                    this.garbageIcon.show();
                }
                favoriteIconGarbageDrop(me, e) {
                    var itemDroped = me;
                    e.preventDefault();
                    var iconKey = e.dataTransfer.getData("sol_control");
                    if (!iconKey)
                        return;
                    var iconIndex = this.iconsSpace.controls.cast().indexWhere(i => i.sourceMenu && i.sourceMenu.LanguageKey == iconKey);
                    var iconRemoved = this.iconsSpace.controls.cast().item(iconIndex);
                    this.iconsSpace.controls.removeItem(iconIndex);
                    this.garbageIcon.visible = false;
                    if (!iconRemoved.sourceMenu.ID)
                        return;
                    var doMultipleModel = {
                        className: "Solarium.UserPreferences.FavoriteIcon, Solarium.UserPreferences, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        decisionID: null,
                        methodName: "DeleteMany",
                        selectionMode: Web.ActionSelectionMode.None,
                        filters: null,
                        ids: [iconRemoved.sourceMenu.ID],
                        inputs: null
                    };
                    Web.System.exec("79k8j542h", "DoMultiple", doMultipleModel);
                }
            }
            Components.SystemMenu = SystemMenu;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class MenuItem extends Sol.Control {
                constructor() {
                    super("li");
                    this.arrow = new Sol.Control("i");
                    this.pin = new Sol.Control("i");
                    this.title = new Sol.Control();
                    this.label = new Sol.Control("span");
                    this.iconControl = new Sol.Control("i");
                    this.requiresModel = false;
                    this.add(this.title);
                    this.iconControl.onClick = () => this.iconClick();
                    this.title.onClick = () => this.menuItemClick();
                }
                get isExpanded() { return this._isExpanded; }
                set isExpanded(value) {
                    this._isExpanded = value;
                    if (this.subMenu)
                        this.subMenu.visible = value;
                    this.arrow.text = value ? '&#xf077;' : '&#xf078;';
                }
                iconClick() {
                    this.systemMenu.toggleState();
                    this.isExpanded = this.systemMenu.menuState == Components.MenuState.Expanded;
                    return false;
                }
                get subMenu() {
                    return this.controls.that(ctr => ctr.tagName == "ul");
                }
                get menuText() { return this.label.text; }
                set menuText(valor) {
                    this.label.text = valor;
                    this.iconControl.tip = valor;
                }
                build() {
                    super.build();
                    if (this.subMenu) {
                        this.arrow.css.add("flecha");
                        this.arrow.text = '&#xf078;';
                        this.title.add(this.arrow);
                    }
                    if (this.screenName && !Sol.Environment.isMobile) {
                        this.pin.css.add("pin");
                        this.pin.text = '&#xf276';
                        this.pin.tip = Sol.Environment.resources.pinmenu;
                        this.pin.onClick = () => this.pinClik(this);
                        this.title.add(this.pin);
                    }
                    this.title.add(this.label);
                    if (this.icon) {
                        if (this.icon[0] == '&')
                            this.iconControl.text = this.icon;
                        else
                            this.iconControl.estilos.definir("background-image", "url('" + Sol.Environment.systemUrl + "/picture/" + this.icon + "')");
                        this.title.add(this.iconControl);
                    }
                }
                menuItemClick() {
                    var _a;
                    this.isExpanded = !this.isExpanded;
                    if (this.screenName) {
                        this.systemMenu.toggleState();
                        if (!this.systemMenu.home.screens.backToDashboard())
                            return;
                        if (this.requiresModel)
                            this.systemMenu.home.screens.openScreen(this.screenName, this.className, this.systemMessage, this.icon, null, null, this.menuInfo.ID);
                        else
                            this.systemMenu.home.screens.openScreenWithModel(this.screenName, this.icon);
                    }
                    else if ((_a = this.menuInfo) === null || _a === void 0 ? void 0 : _a.Tile) {
                        this.systemMenu.hide();
                        const icon = eval("new Sol.Web.Components.Icons." + this.menuInfo.Tile + "()");
                        icon.run();
                    }
                }
                pinClik(item) {
                    if (this.systemMenu.iconsSpace.controls.cast()
                        .any(i => i.sourceMenu && i.sourceMenu.LanguageKey == this.menuInfo.LanguageKey))
                        return;
                    let createdIcon = Components.Icons.BaseIcon.fromMenu(this.menuInfo);
                    this.systemMenu.addFavoriteIcon(createdIcon);
                    var tileName = this.menuInfo.Tile;
                    if (!tileName)
                        tileName = "SimpleIcon";
                    var modelData = {
                        className: "Solarium.UserPreferences.FavoriteIcon, Solarium.UserPreferences, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        id: 0,
                        data: [{ Campo: "Name", Valor: this.menuInfo.LanguageKey },
                            { Campo: "ScreenName", Valor: this.menuInfo.Pantalla },
                            { Campo: "ClassName", Valor: this.menuInfo.Clase },
                            { Campo: "RequiresModel", Valor: this.menuInfo.RequiereModel },
                            { Campo: "Tile", Valor: tileName }],
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", modelData, response => createdIcon.sourceMenu.ID = response.ID);
                    return false;
                }
            }
            Components.MenuItem = MenuItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class TextTrail extends Sol.Control {
                constructor() { super("dfn"); }
            }
            Screens.TextTrail = TextTrail;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ButtonTrail extends Sol.Button {
                constructor() {
                    super();
                    this.type = Sol.ButtonType.Custom;
                }
            }
            Screens.ButtonTrail = ButtonTrail;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class LinkTrail extends Sol.Control {
                constructor() { super("a"); }
            }
            Screens.LinkTrail = LinkTrail;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ProfileModuleCombo extends Sol.Combo {
                constructor() {
                    super();
                    this.onSet.subscribe(() => this.filterPermissions());
                    this.onValueModified.subscribe(() => this.filterPermissions());
                }
                filterPermissions() {
                    const permissionList = this.container.getEditor("Permissions");
                    permissionList.filterByGroup(this.selectedCode == "-1" ? null : this.selectedItem.text);
                }
            }
            Components.ProfileModuleCombo = ProfileModuleCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class ImageGallery extends Sol.Control {
                    constructor() {
                        super(...arguments);
                        this.deleteHeader = new Sol.Control("th");
                        this.fileButton = new Sol.Button();
                        this.gallerySpace = new Sol.Control();
                        this.items = new Sol.List();
                        this.isComplex = true;
                        this.toControl = () => this;
                        this.isEmpty = () => !this.items.hasItems();
                    }
                    get identificadores() { return this.items.select(item => item.identificador).toArray(); }
                    get readonly() { return this._readonly; }
                    set readonly(value) {
                        this._readonly = value;
                        if (this.inputFile)
                            this.inputFile.visible = !value;
                        this.fileButton.visible = !value;
                        this.deleteHeader.visible = !value;
                        if (value)
                            this.css.add("sol_upload_readonly");
                        else
                            this.css.remove("sol_upload_readonly");
                    }
                    get uploadEnAndamiento() { return this.items.any(item => !item.isDone); }
                    get value() {
                        return this.items.select(item => [
                            { Campo: "ID", Valor: item.code },
                            { Campo: "Extensión", Valor: item.extension },
                            { Campo: "Nombre", Valor: item.itemName },
                            { Campo: "Identificador", Valor: item.identificador },
                            { Campo: "Tamaño", Valor: item.tamano }
                        ]).toArray();
                    }
                    set value(v) {
                        this.clear();
                        var coleccion = Sol.List.from(v);
                        coleccion.forEach(item => {
                            const uploadItem = new Uploads.UploadItem();
                            uploadItem.valor = Sol.List.from(item);
                            uploadItem.canDelete = true;
                            uploadItem.parent = this;
                            uploadItem.hideProgressBar();
                            uploadItem.isDone = true;
                            this.items.add(uploadItem);
                            this.addImage(uploadItem);
                        });
                    }
                    clear() {
                        this.items.empty();
                        this.gallerySpace.controls.empty();
                    }
                    ;
                    validate() { return null; }
                    ;
                    build() {
                        this.css.add("sol_upload");
                        this.gallerySpace.css.add("sol_detalles_complex");
                        this.add(this.gallerySpace);
                        this.crearInput();
                        this.add(this.inputFile);
                        this.fileButton.text = Sol.Environment.resources.anadir_item;
                        this.fileButton.css.add("sol_upload_agregar");
                        this.fileButton.type = Sol.ButtonType.Link;
                        this.fileButton.visible = !this.readonly;
                        this.add(this.fileButton);
                        super.build();
                    }
                    addImage(i) {
                        const image = new Sol.ImageBox();
                        image.source = i.url;
                        image.imagenWidth = this.imagenWidth;
                        image.imagenHeight = this.imagenHeight;
                        image.showDeleteButton = true;
                        image.onDelete = img => this.deleteImagen(img);
                        image.data = i;
                        this.gallerySpace.add(image);
                    }
                    crearInput() {
                        this.inputFile = new Uploads.InputUpload();
                        this.inputFile.visible = !this.readonly;
                        this.inputFile.multiple = true;
                        this.inputFile.accept = "image/*";
                        this.html.onchange = e => this.onInputChange(e);
                    }
                    deleteImagen(image) {
                        this.items.remove(image.data);
                        this.gallerySpace.controls.remove(image);
                    }
                    onInputChange(e) {
                        var tagInput = e.target;
                        var files = tagInput.files;
                        if (!tagInput.files)
                            return;
                        for (var item of files) {
                            var nuevoUpload = new Uploads.UploadItem();
                            nuevoUpload.parent = this;
                            nuevoUpload.itemName = item.name;
                            nuevoUpload.file = item;
                            nuevoUpload.onUploadComplete = () => this.addImage(nuevoUpload);
                            this.items.add(nuevoUpload);
                            nuevoUpload.process();
                        }
                    }
                    foco() { }
                    ;
                }
                Uploads.ImageGallery = ImageGallery;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class FileSignerHelpDialog extends Sol.DialogBox {
                    constructor() {
                        super();
                        this.css.add("sol_file_signer_dialog");
                        this.title = "Assinatura digital";
                        const intro = new Sol.Control("p");
                        intro.text = "Essa opção permite a você assinar um documento digitalmente com um certificado digital ICP-Brasil.";
                        this.contentArea.add(intro);
                        const a1title = new Sol.Control("h5");
                        a1title.text = "Se você tem um certificado digital do tipo A1...";
                        this.contentArea.add(a1title);
                        const a1p = new Sol.Control("p");
                        a1p.text = "Na tela inicial, clique no ícone Configurações/Certificado Digital, e faça o upload do seu arquivo de certificado digital A1. Com isso, seus documentos serão assinados com apenas um clique.";
                        this.contentArea.add(a1p);
                        const a3title = new Sol.Control("h5");
                        a3title.text = "Se você tem um certificado digital do tipo A3 em um token...";
                        this.contentArea.add(a3title);
                        const a3p = new Sol.Control("p");
                        a3p.text = "Clique na opção abaixo para disponibilizar o seu arquivo para assinatura A3. Depois, utilize o nosso assinador de arquivos (faça o download no nosso site) para completar a assinatura.";
                        this.contentArea.add(a3p);
                        const releaseButton = new Sol.Button();
                        releaseButton.type = Sol.ButtonType.Link;
                        releaseButton.text = "Disponibilizar o arquivo para assinatura A3";
                        releaseButton.onClick = () => this.realeaseFile();
                        this.contentArea.add(releaseButton);
                        const footer = new Sol.Control();
                        footer.css.add("sol_file_signer_dialog_footer");
                        const doneButton = new Sol.Button();
                        doneButton.text = "Entendido!";
                        doneButton.onClick = () => this.onClosing();
                        footer.add(doneButton);
                        this.contentArea.add(footer);
                    }
                    realeaseFile() {
                        Web.System.exec("qoeaslska", "WaitA3Signature", { fileID: this.fileID });
                        alert("Arquivo disponibilizado para assinatura A3 com sucesso!");
                        this.onClosing();
                    }
                }
                Uploads.FileSignerHelpDialog = FileSignerHelpDialog;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Uploads;
            (function (Uploads) {
                class FileSigner extends Uploads.Upload {
                    constructor() {
                        super();
                        this.showFileSize = true;
                        this.onValueSet = () => this.updateSignInfo();
                        this.onItemAdded = () => this.updateSignInfo();
                    }
                    updateSignInfo() {
                        const pdfFiles = this.files.where(i => i.code && i.extension == ".pdf");
                        if (!pdfFiles.hasItems())
                            return;
                        const data = { fileCodes: pdfFiles.where(i => !i.link).select(i => i.code).toArray() };
                        Web.System.exec("qoeaslska", "GetSignInfo", data, e => {
                            Sol.List.from(e).forEach(file => {
                                const item = this.files.that(i => i.code == file.FileCode);
                                item.signaturePanel.allowSign = file.AllowSign;
                                item.signaturePanel.setSigners(file.Signers);
                                item.signaturePanel.allowAskForSign = file.CanAskForSign;
                                item.signaturePanel.visible = true;
                            });
                        }, null);
                    }
                }
                Uploads.FileSigner = FileSigner;
            })(Uploads = Components.Uploads || (Components.Uploads = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Forms;
        (function (Forms) {
            class ProgressForm extends Forms.BaseForm {
                fillForm(structure, form, toolbar, state, contextClass, code, disableMinimizedControls, totalizationBarPos) {
                    const result = new Forms.CommonForm().fillForm(structure, form, toolbar, state, contextClass, code, disableMinimizedControls, totalizationBarPos);
                    const stepLine = new Web.Components.ProgressStepLine(result.groups);
                    stepLine.onStepSelected = () => result.fields.where(f => f.fieldModel.FormPosition != Web.FormPosition.toolBox || !!f.group)
                        .forEach(f => { var _a; return this.setFieldVisibility(f, ((_a = f.group) === null || _a === void 0 ? void 0 : _a.Caption) == stepLine.selectedGroup.Caption); });
                    form.parent.controls.insert(3, stepLine);
                    return result;
                }
                setFieldVisibility(editor, value) {
                    const targetControl = editor.parent instanceof Sol.FieldWrapper ? editor.parent : editor.toControl();
                    targetControl.visible = value;
                    if (editor.isComplex)
                        editor.myLabel.visible = value;
                }
            }
            Forms.ProgressForm = ProgressForm;
        })(Forms = Web.Forms || (Web.Forms = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Forms;
        (function (Forms) {
            class SideBarOptionComparer {
                equalsTo(x, y) { return x.name == y.name; }
            }
            Forms.SideBarOptionComparer = SideBarOptionComparer;
        })(Forms = Web.Forms || (Web.Forms = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Forms;
        (function (Forms) {
            class SideBarForm extends Forms.BaseForm {
                constructor() {
                    super(...arguments);
                    this.editors = new Sol.List();
                    this.buttons = new Sol.List();
                    this.nextButton = new Sol.Button();
                }
                get selectedIndex() { return this.buttons.indexWhere(bt => bt.checked); }
                set selectedIndex(value) { this.optionClick(this.buttons.item(value)); }
                fillForm(structure, form, toolbar, state, contextClass, code, disableMinimizedControls, totalizationBarPosition) {
                    const labels = new Sol.List();
                    const groups = new Sol.List();
                    this.myForm = form;
                    this.getFieldsForThisState(structure, state)
                        .forEach(fieldModel => {
                        var editor = this.getEditor(fieldModel, form, contextClass, code, structure);
                        if (!editor)
                            return;
                        this.editors.add(editor);
                        const label = this.getLabel(editor, fieldModel, structure, disableMinimizedControls);
                        if (label)
                            labels.add(label);
                    });
                    const sideBarOptions = this.getSideBarOptions();
                    const totalizationBar = new Sol.Control();
                    totalizationBar.css.addMany(["sol_totalization_bar", "sol_sidebar_totalization_bar"]);
                    if (this.editors.any(edt => edt.fieldModel.FormPosition == Web.FormPosition.totalization))
                        form.toControl().add(totalizationBar);
                    const sideBarForm = form.toControl().addCtr("", "sol_details_side_bar_form");
                    this.sideBar = sideBarForm.addCtr("", "sol_details_side_bar");
                    const sideBarAreas = sideBarForm.addCtr("", "sol_details_side_bar_areas");
                    var isFirst = true;
                    sideBarOptions.forEach(option => {
                        const button = this.createOption(option);
                        const area = sideBarAreas.addCtr("", null);
                        button.data = area;
                        this.fillArea(area, option, code, contextClass);
                        button.checked = isFirst;
                        area.visible = isFirst;
                        isFirst = false;
                    });
                    this.editors
                        .where(edt => edt.fieldModel.FormPosition == Web.FormPosition.toolBox && !(edt instanceof Web.Components.TabEditor))
                        .forEach(edt => this.placeEditorInToolbar(edt, edt.fieldModel, toolbar));
                    this.editors
                        .where(edt => edt.fieldModel.FormPosition == Web.FormPosition.totalization)
                        .forEach(edt => this.placeEditorInToolbar(edt, edt.fieldModel, totalizationBar));
                    form.editors = this.editors;
                    this.createNextButton(form);
                    return {
                        fields: this.editors,
                        labels: labels,
                        groups: groups
                    };
                }
                getSideBarOptions() {
                    return this.editors
                        .where(edt => edt.fieldModel.FormPosition == Web.FormPosition.form)
                        .select(edt => {
                        var _a, _b, _c;
                        return ({
                            name: (_a = edt.group) === null || _a === void 0 ? void 0 : _a.Caption,
                            position: ((_b = edt.group) === null || _b === void 0 ? void 0 : _b.Position) || 0,
                            groupInfo: edt.group,
                            UID: ((_c = edt.group) === null || _c === void 0 ? void 0 : _c.UID) || "uid-general-data"
                        });
                    })
                        .union(this.editors.where(edt => edt instanceof Web.Components.TabEditor)
                        .cast()
                        .select(tab => ({
                        name: tab.caption,
                        isTab: true,
                        position: tab.fieldModel.OrderPosition,
                        UID: tab.configuration.UID
                    }))
                        .toArray())
                        .distinct(new Forms.SideBarOptionComparer())
                        .orderBy(opt => opt.position);
                }
                createNextButton(form) {
                    this.nextButton.text = "Salvar e Avançar";
                    this.nextButton.onClick = () => this.nextClick();
                    form.footer.controls.insert(2, this.nextButton);
                }
                createOption(option) {
                    const newButton = option.isTab ?
                        this.getTabByCaption(option.name) :
                        this.createOptionButton(option);
                    newButton.type = Sol.ButtonType.Alternate;
                    newButton.onChecked = () => this.optionClick(newButton);
                    this.sideBar.add(newButton);
                    this.buttons.add(newButton);
                    newButton.atributos.agregar("uid", option.UID);
                    return newButton;
                }
                createOptionButton(option) {
                    var _a;
                    const button = new Sol.Button();
                    button.imageCode = ((_a = option.groupInfo) === null || _a === void 0 ? void 0 : _a.Icon) || "&#xf040";
                    button.text = option.name || "Dados Gerais";
                    option.button = button;
                    return button;
                }
                fillArea(area, option, code, contextClass) {
                    if (option.isTab)
                        return;
                    const optionEditors = this.getEditorsForOption(option.name);
                    optionEditors.forEach(editor => {
                        const baseControl = editor.useWrapper ? new Sol.FieldWrapper() : area;
                        baseControl.add(editor.myLabel);
                        this.placeEditor(editor, baseControl, code, contextClass);
                        if (editor.group)
                            editor.group.GroupDisplay = option.button;
                        if (editor.useWrapper)
                            area.add(baseControl);
                    });
                }
                getEditorsForOption(optionName) {
                    return this.editors.where(edt => { var _a; return edt.fieldModel.FormPosition == Web.FormPosition.form && ((_a = edt.group) === null || _a === void 0 ? void 0 : _a.Caption) == optionName; });
                }
                getTabByCaption(caption) {
                    return this.editors.that(edt => edt instanceof Web.Components.TabEditor && edt.caption == caption);
                }
                nextClick() {
                    var newIndex = this.selectedIndex + 1;
                    while (!this.buttons.item(newIndex).visible)
                        newIndex++;
                    this.selectedIndex = newIndex;
                }
                optionClick(button) {
                    this.previousIndex = this.selectedIndex;
                    this.buttons.forEach(b => {
                        b.checked = false;
                        b.data.visible = false;
                    });
                    button.checked = true;
                    const area = button.data;
                    area.visible = true;
                    this.nextButton.visible = this.myForm.okButton.visible &&
                        this.selectedIndex < this.buttons.count - 1 &&
                        this.buttons.skip(this.selectedIndex).any(b => b.visible);
                    if (this.backMode) {
                        this.backMode = false;
                        return;
                    }
                    if (button instanceof Web.Components.TabEditor) {
                        button.onCancelEnter = () => {
                            this.backMode = true;
                            this.selectedIndex = this.previousIndex;
                        };
                        area.controls.empty();
                        button.embbed(area);
                    }
                    else
                        this.getEditorsForOption(button.text).where(edt => edt.refreshable).cast().forEach(edt => edt.refresh());
                }
            }
            Forms.SideBarForm = SideBarForm;
        })(Forms = Web.Forms || (Web.Forms = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Displays;
            (function (Displays) {
                class ErrorCountDisplay extends Sol.Control {
                    constructor() {
                        super();
                        this.numberDisplay = new Sol.Control("span");
                        this.icon = new Sol.Control("i");
                        this.readonly = true;
                        this._value = 0;
                        const container = new Sol.Control();
                        container.css.add("sol_error_count_display");
                        container.add(this.icon);
                        container.add(this.numberDisplay);
                        this.add(container);
                    }
                    get value() { return this._value; }
                    set value(v) {
                        this._value = v;
                        this.numberDisplay.text = v < 100 ? v.toString() : "99+";
                        if (v <= 0)
                            this.numberDisplay.text = "";
                        this.icon.text = v > 0 ? "&#xf111;" : "&#xf164;";
                        if (v == -1)
                            this.icon.text = "&#xf128;";
                        this.icon.css.empty();
                        this.icon.css.add(v > 0 ? "error" : (v == -1 ? "unknow" : "no_error"));
                    }
                    toControl() { return this; }
                    clear() { }
                    foco() { }
                    isEmpty() { return true; }
                    validate() { return null; }
                }
                Displays.ErrorCountDisplay = ErrorCountDisplay;
            })(Displays = Components.Displays || (Components.Displays = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TaxIDField extends Sol.ExtensibleField {
                build() {
                    super.build();
                    this.mainField.ancho = null;
                    this.mainField.maxLength = 18;
                    const button = new Sol.Button();
                    button.imageCode = "&#xf002;";
                    button.tip = "Pesquisa pelo CNPJ na Receita Federal e preenche a tela com os dados obtidos";
                    button.onClick = () => this.searchCNPJ();
                    this.add(button);
                    this.mainField.onLeave.subscribe(() => this.callExistentClientCheck());
                }
                callExistentClientCheck() {
                    if (!this.checkExistentClient || !!Web.System.screens.currentDetails.code)
                        return;
                    if (this.mainField.isEmpty()) {
                        Web.System.screens.currentDetails.hideMessages();
                        this.errorState = Sol.EditorErrorState.Normal;
                        return;
                    }
                    Web.System.exec("79k8jhkh", "CheckExistentCustomer", { taxID: this.mainField.value }, response => {
                        const isFail = !!response.Fail;
                        this.errorState = isFail ? Sol.EditorErrorState.Error : Sol.EditorErrorState.Normal;
                        isFail
                            ? Web.System.screens.currentDetails.showError(response.ErrorMessage, this, "taxIDError002")
                            : Web.System.screens.currentDetails.hideMessages(this, "taxIDError002");
                    });
                }
                searchCNPJ() {
                    if (this.mainField.isEmpty()) {
                        alert("Informe um CNPJ");
                        return;
                    }
                    Web.System.exec("kslxmfhs5", "FindCNPJData", { taxID: this.mainField.value }, response => {
                        if (!response.Fail)
                            Web.System.screens.currentDetails.loadData(response.Data, { ClassName: response.ClassType });
                        else
                            alert(response.ErrorMessage);
                    });
                }
            }
            Components.TaxIDField = TaxIDField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("TaxID", () => new Sol.Web.Components.TaxIDField());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ExchangeRateField extends Sol.CurrencyField {
                constructor() {
                    super();
                    this.css.add("exchange_rate_field");
                    this.readonly = true;
                    this.savable = true;
                    let openFileScreenButton = new Sol.Button();
                    openFileScreenButton.text = "...";
                    openFileScreenButton.onClick = () => this.openScreen();
                    this.add(openFileScreenButton);
                }
                get curDate() { var _a; return ((_a = this.dateField) === null || _a === void 0 ? void 0 : _a.value) || new Date().formatear(); }
                build() {
                    var _a, _b;
                    super.build();
                    this.dateField = Web.System.screens.currentDetails.getEditor("CompletionDate");
                    (_a = this.dateField) === null || _a === void 0 ? void 0 : _a.onValueModified.subscribe(() => this.updateExchangeRate());
                    this.sourceField = Web.System.screens.currentDetails.getEditor("SourceCurrencyTotal");
                    (_b = this.sourceField) === null || _b === void 0 ? void 0 : _b.onCurrencyChanged.subscribe(() => this.updateExchangeRate());
                    if (this.sourceField)
                        this.sourceField.onChange = () => this.updateTotal();
                }
                openScreen() {
                    Web.System.screens.openScreen("Registro", "17760086", null, null, null, screen => screen.onCloseScreen = () => {
                        this.updateExchangeRate();
                        return true;
                    });
                }
                updateExchangeRate() {
                    let data = {
                        date: this.curDate,
                        currencyA: this.sourceField.selectedCurrency.ISO,
                        currencyB: Sol.Environment.defaultCurrency.ISO
                    };
                    Web.System.exec("79k8jhkh", "GetExchangeRate", data, e => {
                        this.tip = "Data da cotação: " + e.ExchangeDate;
                        this.numericValue = e.Rate;
                        this.updateTotal();
                    });
                }
                updateTotal() {
                    if (!this.sourceField)
                        return;
                    if (this.sourceField.numericValue == 0 || this.numericValue == 0)
                        return;
                    let totalField = Web.System.screens.currentDetails.getEditor("Total");
                    totalField.numericValue = this.sourceField.numericValue * this.numericValue;
                }
            }
            Components.ExchangeRateField = ExchangeRateField;
            Sol.Web.Editors.registerEditor("ExchangeRateField", () => new ExchangeRateField());
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScreenCombo extends Sol.Combo {
                constructor() {
                    super();
                    this.onValueModified.subscribe(() => this.loadItems());
                }
                loadItems() {
                    const request = { className: this.selectedCode };
                    Web.System.exec("fdavsr0324", "GetConfigurationByClassName", request, data => {
                        const fieldCombo = this.container.getEditor("Field");
                        fieldCombo.clear();
                        fieldCombo.setDataSource(data);
                        fieldCombo.loadFields();
                    });
                }
            }
            Components.ScreenCombo = ScreenCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ScreenCombo", model => {
    const screenCombo = new Sol.Web.Components.ScreenCombo();
    screenCombo.loadOptions(model.Options);
    return screenCombo;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScreenFieldCombo extends Sol.Combo {
                constructor() {
                    super();
                    this.displayMember = "CompleteFieldName";
                    this.valueMember = "PropertyName";
                    this.onValueModified.subscribe(() => this.loadFields());
                }
                loadFields() {
                    const fieldData = this.selectedItem.data;
                    this.container.getEditor("Active").value = fieldData.Available;
                    this.container.getEditor("Required").value = fieldData.IsRequired;
                    this.container.getEditor("Required").readonly = !fieldData.RequiredOptionEnabled;
                    this.container.getEditor("FilterVisible").value = fieldData.FilterVisible;
                    this.container.getEditor("FilterEditorKey").value = fieldData.FilterEditorKey;
                    this.container.getEditor("FilterPosition").value = fieldData.FilterPosition;
                    this.container.getEditor("EditorKey").value = fieldData.EditorKey;
                    this.container.getEditor("Mask").value = fieldData.Mask;
                    this.container.getEditor("Position").value = fieldData.Position;
                }
            }
            Components.ScreenFieldCombo = ScreenFieldCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ScreenFieldCombo", model => {
    const screenFieldCombo = new Sol.Web.Components.ScreenFieldCombo();
    screenFieldCombo.loadOptions(model.Options);
    return screenFieldCombo;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CreatorField extends Sol.Control {
                constructor() {
                    super();
                    this.isComplex = false;
                    this.css.addMany(["sol_campo solo_lectura solo_lectura"]);
                    this.estilos.agregar("width", "322px");
                }
                get code() { return this._code; }
                set code(v) {
                    this._code = v;
                    this.refresh();
                }
                get value() { return this.text; }
                set value(v) { this.text = v; }
                toControl() { return this; }
                isEmpty() { return !(!this.text); }
                foco() { }
                clear() { this.text = ""; }
                validate() { return null; }
                refresh() {
                    var data = {
                        credential: Sol.Environment.credential.export(),
                        className: this.className,
                        id: this.code
                    };
                    Web.System.exec("sn9d23vs7d", "GetCreator", data, model => {
                        if (model)
                            this.text = model;
                    }, null);
                }
            }
            Components.CreatorField = CreatorField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                let TileVariationSign;
                (function (TileVariationSign) {
                    TileVariationSign[TileVariationSign["None"] = 0] = "None";
                    TileVariationSign[TileVariationSign["Increasing"] = 1] = "Increasing";
                    TileVariationSign[TileVariationSign["Stable"] = 2] = "Stable";
                    TileVariationSign[TileVariationSign["Decreasing"] = 3] = "Decreasing";
                })(TileVariationSign = Reports.TileVariationSign || (Reports.TileVariationSign = {}));
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class LinkIcon extends Icons.BaseIcon {
                    refresh() { }
                    iconClick() { window.open(this.url, "_blank"); }
                }
                Icons.LinkIcon = LinkIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class DashboardSeparator extends Sol.Control {
                constructor(text) {
                    super();
                    this.css.add("sol_dashboard_separator");
                    this.text = text;
                }
            }
            Screens.DashboardSeparator = DashboardSeparator;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ReportWrapper extends Sol.Control {
                constructor() {
                    super();
                    this.css.add("sol_reports");
                    this.css.add("sol_dashboard_report");
                    this.estilos.definir("width", "95% !important");
                }
                refresh() { this.myReport.refresh(); }
            }
            Screens.ReportWrapper = ReportWrapper;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class LessonScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.timelineArea = new Sol.Control("td");
                    this.lessonArea = new Sol.Control("td");
                    this.form = new Sol.Form();
                    this.confirmationArea = new Sol.Control();
                    this.confirmationMessage = new Sol.ScreenMessage();
                    this.endCourseArea = new Sol.Control();
                    this.examCompleted = new Sol.Control("span");
                    this.gotoExamButton = new Sol.Button();
                    this.uploads = new Web.Components.Uploads.Upload();
                }
                showExamDone() {
                    this.form.controls.remove(this.gotoExamButton);
                    this.examCompleted.visible = true;
                }
                build() {
                    super.build();
                    this.css.add("lesson_screen");
                    this.myModel = this.model;
                    this.isOldLesson = this.myModel.LessonNumber != this.myModel.NextLesson;
                    this.form.onValidate = e => this.onValidate(e);
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                    this.initializeStructure();
                    this.initializeTimeline();
                    this.initializeMainArea();
                    this.initializeConfirmationArea();
                    this.initializeEndCourseArea();
                }
                initializeStructure() {
                    var mainTable = new Sol.Control("table");
                    this.add(mainTable);
                    var mainLine = new Sol.Control("tr");
                    mainTable.add(mainLine);
                    this.timelineArea.css.add("timeline_area");
                    mainLine.add(this.timelineArea);
                    mainLine.add(this.lessonArea);
                }
                initializeTimeline() {
                    var timeline = new Sol.WebComponents.VerticalTimeline();
                    timeline.itemCount = this.myModel.LessonCount;
                    timeline.currentItem = this.myModel.LessonNumber;
                    timeline.maxValue = this.myModel.NextLesson;
                    this.timelineArea.add(timeline);
                    timeline.itemClick = i => {
                        Web.System.screens.closeCurrentScreen();
                        this.parentList.openLesson(this.enrollmentID, i);
                    };
                }
                initializeMainArea() {
                    this.form.cancelButton.text = Sol.Environment.resources.back;
                    this.form.okButton.text = Sol.Environment.resources.finish_lesson;
                    this.form.okButton.visible = !this.isOldLesson;
                    this.form.onCancel = () => Web.System.screens.closeCurrentScreen();
                    this.form.onSave = () => {
                        this.confirmationTarget = Screens.ConfirmationTarget.BackToHome;
                        this.finishLessonClick();
                    };
                    this.initializeNextLessonButton();
                    this.lessonArea.add(this.form);
                    var lessonNumber = new Sol.Control("h5");
                    lessonNumber.text = Sol.Environment.resources.lesson + ' ' + this.myModel.LessonNumber.toString();
                    this.form.add(lessonNumber);
                    var introduction = new Sol.Control("p");
                    introduction.text = this.myModel.Introduction;
                    this.form.add(introduction);
                    this.initializeVideos();
                    this.initializePdfs();
                    this.initializeReadingMaterials();
                    this.initializeEvaluationArea();
                    this.initializeActivityArea();
                }
                initializeNextLessonButton() {
                    if (this.myModel.NextLesson > this.myModel.LessonCount)
                        return;
                    const nextClassButton = new Sol.Button();
                    nextClassButton.css.add("sol_next_lesson");
                    nextClassButton.text = Sol.Environment.resources.next_lesson;
                    nextClassButton.onClick = () => this.nextLessonButtonClick();
                    this.form.footer.add(nextClassButton);
                }
                nextLessonButtonClick() {
                    if (this.isOldLesson) {
                        Web.System.screens.closeCurrentScreen();
                        this.parentList.openLesson(this.enrollmentID, this.myModel.LessonNumber + 1);
                    }
                    else {
                        this.confirmationTarget = Screens.ConfirmationTarget.NextLesson;
                        this.finishLessonClick();
                    }
                }
                initializePdfs() {
                    if (!this.myModel.Pdfs)
                        return;
                    var pdfs = Sol.List.from(this.myModel.Pdfs);
                    pdfs.forEach(m => {
                        var pdfTitle = new Sol.Control("h5");
                        pdfTitle.text = m.Description;
                        this.form.add(pdfTitle);
                        var player = new Sol.WebComponents.PdfViewer();
                        player.source = "/pdf/" + m.FileCode;
                        this.form.add(player);
                        var fullScreenButton = new Sol.Button();
                        fullScreenButton.type = Sol.ButtonType.Custom;
                        fullScreenButton.text = Sol.Environment.resources.show_full_screen;
                        fullScreenButton.css.add("pdf_button");
                        fullScreenButton.onClick = () => {
                            var pdfScreen = new Screens.PdfScreen();
                            pdfScreen.model = {
                                title: m.Description,
                                url: player.source
                            };
                            Web.System.screens.addScreen(pdfScreen);
                            Web.System.screens.showScreen(pdfScreen);
                        };
                        this.form.add(fullScreenButton);
                    });
                }
                initializeVideos() {
                    if (!this.myModel.Videos || this.myModel.Videos.length == 0)
                        return;
                    var videosTitle = new Sol.Control("h5");
                    videosTitle.text = Sol.Environment.resources.videos;
                    this.form.add(videosTitle);
                    var videos = Sol.List.from(this.myModel.Videos);
                    videos.forEach(m => {
                        var description = new Sol.Control("p");
                        description.text = m.Description;
                        this.form.add(description);
                        var player = new Sol.WebComponents.VideoPlayer();
                        player.source = m.FileCode;
                        this.form.add(player);
                    });
                }
                initializeReadingMaterials() {
                    var materials = Sol.List.from(this.myModel.ReadingMaterials);
                    if (!materials.hasItems())
                        return;
                    var readingMaterialsTitle = new Sol.Control("h5");
                    readingMaterialsTitle.text = Sol.Environment.resources.reading_materials;
                    this.form.add(readingMaterialsTitle);
                    materials.forEach(m => {
                        var anchor = new Sol.Control("a");
                        anchor.text = m.Description;
                        anchor.atributos.agregar("target", "_blank");
                        anchor.atributos.agregar("href", Sol.Environment.filePath + m.FileCode);
                        anchor.css.add("lesson_screen_link");
                        this.form.add(anchor);
                    });
                }
                initializeEvaluationArea() {
                    if (!this.myModel.Exam)
                        return;
                    var evaluationTitle = new Sol.Control("h5");
                    evaluationTitle.text = Sol.Environment.resources.evaluation;
                    this.form.add(evaluationTitle);
                    var examName = new Sol.Control("span");
                    examName.text = this.myModel.Exam.ExamName;
                    examName.css.add("lesson_screen_exam_name");
                    this.form.add(examName);
                    if (!this.myModel.ExamCompleted) {
                        this.gotoExamButton.text = Sol.Environment.resources.access;
                        this.gotoExamButton.type = Sol.ButtonType.Custom;
                        this.gotoExamButton.css.add("lesson_screen_access_exam");
                        this.gotoExamButton.onClick = () => this.openExam(this.myModel.Exam);
                        this.form.add(this.gotoExamButton);
                    }
                    this.examCompleted.text = Sol.Environment.resources.exam_completed;
                    this.examCompleted.visible = this.myModel.ExamCompleted;
                    this.examCompleted.css.add("lesson_screen_exam_completed");
                    this.form.add(this.examCompleted);
                }
                initializeActivityArea() {
                    if (!this.myModel.Activity)
                        return;
                    var activityTitle = new Sol.Control("h5");
                    activityTitle.text = Sol.Environment.resources.activities;
                    this.form.add(activityTitle);
                    var activiyText = new Sol.Control("p");
                    activiyText.text = this.myModel.Activity;
                    this.form.add(activiyText);
                    this.form.add(this.uploads);
                }
                initializeConfirmationArea() {
                    this.confirmationArea.css.add("lesson_screen_confirmation");
                    this.confirmationArea.visible = false;
                    this.lessonArea.add(this.confirmationArea);
                    this.confirmationMessage.okButtonText = Sol.Environment.resources.finish;
                    this.confirmationMessage.caption = Sol.Environment.resources.finish_lesson_confirmation;
                    this.confirmationMessage.type = Sol.MessageType.Confirmation;
                    this.confirmationMessage.onConfirm = () => this.confirmationClick();
                    this.confirmationMessage.onCancel = () => this.cancelConfirmation();
                    this.confirmationArea.add(this.confirmationMessage);
                }
                initializeEndCourseArea() {
                    this.endCourseArea.css.add("lesson_screen_sucess");
                    this.endCourseArea.visible = false;
                    this.lessonArea.add(this.endCourseArea);
                    var congratulations = new Sol.Control("h5");
                    congratulations.text = Sol.Environment.resources.congratulations;
                    this.endCourseArea.add(congratulations);
                    var congratulationsText = new Sol.Control("p");
                    congratulationsText.text = Sol.Environment.resources.courseEnded;
                    this.endCourseArea.add(congratulationsText);
                    var okButton = new Sol.Button();
                    okButton.text = Sol.Environment.resources.cerrar;
                    okButton.type = Sol.ButtonType.Custom;
                    okButton.onClick = () => this.okEndCourseClick();
                    this.endCourseArea.add(okButton);
                }
                finishLessonClick() {
                    this.form.visible = false;
                    this.confirmationArea.visible = true;
                    this.confirmationMessage.visible = true;
                    this.form.workComplete();
                    Web.System.screens.scrollTop();
                }
                cancelConfirmation() {
                    this.form.visible = true;
                    this.confirmationArea.visible = false;
                }
                confirmationClick() {
                    var data = {
                        Credential: Sol.Environment.credential.export(),
                        Enrollment: this.enrollmentID,
                        Lesson: this.myModel.ID,
                        Files: this.uploads.value
                    };
                    Web.System.exec("laspoesd", "FinishLesson", data, e => {
                        if (e.Completed) {
                            this.confirmationArea.visible = false;
                            this.endCourseArea.visible = true;
                        }
                        else {
                            this.parentList.refresh();
                            Web.System.screens.closeCurrentScreen();
                            if (this.confirmationTarget == Screens.ConfirmationTarget.NextLesson)
                                this.parentList.openLesson(this.enrollmentID);
                        }
                    }, null);
                }
                okEndCourseClick() {
                    this.parentList.refresh();
                    Web.System.screens.closeCurrentScreen();
                }
                openExam(examModel) {
                    var data = {
                        Credential: Sol.Environment.credential.export(),
                        Enrollment: this.enrollmentID,
                        Exam: this.myModel.Exam.ID
                    };
                    Web.System.exec("laspoesd", "GetExam", data, e => {
                        var screen = new Screens.ExamScreen();
                        screen.screenCaption = examModel.ExamName;
                        screen.model = e;
                        screen.parentScreen = this;
                        Web.System.screens.addScreen(screen);
                        Web.System.screens.showScreen(screen);
                    }, null);
                }
                onValidate(e) {
                    var validation = { success: true, message: null };
                    if (!this.examCompleted.visible) {
                        validation.success = false;
                        validation.message = Sol.Environment.resources.exam_error;
                        window.scrollTo(0, 0);
                    }
                    return validation;
                }
            }
            Screens.LessonScreen = LessonScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class CourseList extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.table = new Sol.Control("table");
                    this.visible = false;
                    this.css.add("course_list_screen");
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = Sol.Environment.resources.my_courses;
                    this.add(screenTitle);
                }
                openLesson(enrollmentID, lessonNumber = 0) {
                    var data = {
                        Enrollment: enrollmentID,
                        LessonNumber: lessonNumber
                    };
                    Web.System.exec("laspoesd", "Lesson", data, e => {
                        var screen = new Screens.LessonScreen();
                        screen.screenCaption = e.CourseName + " - " + Sol.Environment.resources.lesson + ' ' + e.LessonNumber.toString();
                        screen.enrollmentID = enrollmentID;
                        screen.model = e;
                        screen.parentList = this;
                        Web.System.screens.addScreen(screen);
                        Web.System.screens.showScreen(screen);
                    });
                }
                refresh() {
                    this.table.controls.empty();
                    this.getList();
                }
                build() {
                    super.build();
                    this.add(this.table);
                    this.getList();
                }
                buildList(model) {
                    if (!model.Courses || model.Courses.length === 0)
                        return;
                    this.visible = true;
                    this.table.controls.empty();
                    var courses = Sol.List.from(model.Courses);
                    courses.forEach(course => {
                        var tableRow = new Sol.Control("tr");
                        this.table.add(tableRow);
                        if (course.HasPicture) {
                            var imageCell = new Sol.Control("td");
                            imageCell.ancho = 180;
                            tableRow.add(imageCell);
                            var image = new Sol.ImageBox();
                            image.source = Sol.Environment.filePath + course.Picture;
                            imageCell.add(image);
                        }
                        var contentCell = new Sol.Control("td");
                        tableRow.add(contentCell);
                        if (course.LessonsCount > 0) {
                            if (!course.IsDone) {
                                var enterButton = new Sol.Button();
                                enterButton.css.add("course_list_screen_enter");
                                var lessonNumber = new Sol.Control();
                                lessonNumber.text = Sol.Environment.resources.lesson + ' ' + course.NextLesson.toString();
                                enterButton.add(lessonNumber);
                                var startText = new Sol.Control("span");
                                startText.text = Sol.Environment.resources.start;
                                enterButton.add(startText);
                                enterButton.type = Sol.ButtonType.Custom;
                                enterButton.onClick = () => this.openLesson(course.EnrollmentID);
                                contentCell.add(enterButton);
                            }
                            else {
                                const openCourseButton = new Sol.Button();
                                openCourseButton.css.add("course_list_screen_certificate");
                                openCourseButton.text = Sol.Environment.resources.openCourse;
                                openCourseButton.type = Sol.ButtonType.Custom;
                                openCourseButton.onClick = () => this.openLesson(course.EnrollmentID, 1);
                                contentCell.add(openCourseButton);
                            }
                        }
                        var courseTitle = new Sol.Control("h4");
                        courseTitle.text = course.CourseName;
                        contentCell.add(courseTitle);
                        var detailsLine = new Sol.Control("p");
                        contentCell.add(detailsLine);
                        var requiresSeparator = false;
                        if (course.Teacher) {
                            const teacherLabel = new Sol.Control("span");
                            teacherLabel.text = Sol.Environment.resources.por + ' ' + course.Teacher;
                            detailsLine.add(teacherLabel);
                            requiresSeparator = true;
                        }
                        if (course.LessonsCount > 0) {
                            const lessonCountLabel = new Sol.Control("span");
                            lessonCountLabel.text = (requiresSeparator ? " | " : "") + course.LessonsCount.toString() + ' ' + Sol.Environment.resources.lessons;
                            detailsLine.add(lessonCountLabel);
                            requiresSeparator = true;
                        }
                        if (course.Workload) {
                            const workloadLabel = new Sol.Control("span");
                            workloadLabel.text = (requiresSeparator ? " | " : "") + course.Workload;
                            detailsLine.add(workloadLabel);
                        }
                        const descriptionParagraph = new Sol.Control("p");
                        descriptionParagraph.text = course.CourseDescription;
                        contentCell.add(descriptionParagraph);
                        const baseLine = new Sol.Control("p");
                        contentCell.add(baseLine);
                        if (course.LessonsCount > 0) {
                            const progressLabel = new Sol.Control("span");
                            progressLabel.text = Sol.Environment.resources.su_progreso + ':';
                            baseLine.add(progressLabel);
                            const progressBar = new Sol.ProgressBar();
                            progressBar.valor = course.Progress;
                            baseLine.add(progressBar);
                        }
                        const links = Sol.List.from(course.Links);
                        if (links.hasItems()) {
                            const linksArea = new Sol.Control();
                            const linksTitle = new Sol.ExpandoLabel();
                            linksTitle.caption = "Links das aulas";
                            linksTitle.associatedControl = linksArea;
                            linksTitle.expanded = false;
                            contentCell.add(linksTitle);
                            linksArea.controls.addMany(links.select(lnk => {
                                const linkWrapper = new Sol.Control();
                                linkWrapper.css.add("course_list_screen_link");
                                const linkAnchor = new Sol.Control("a");
                                linkAnchor.text = "Aula do dia " + lnk.Date;
                                linkAnchor.atributos.agregar("href", lnk.Link);
                                linkAnchor.atributos.agregar("target", "_blank");
                                linkWrapper.add(linkAnchor);
                                const linkDescription = new Sol.Control();
                                linkDescription.text = lnk.Description;
                                linkWrapper.add(linkDescription);
                                return linkWrapper;
                            }));
                            contentCell.add(linksArea);
                        }
                        const resources = Sol.List.from(course.Resources);
                        if (resources.hasItems()) {
                            const resourcesArea = new Sol.Control();
                            const resourcesTitle = new Sol.ExpandoLabel();
                            resourcesTitle.caption = "Materiais da turma";
                            resourcesTitle.associatedControl = resourcesArea;
                            resourcesTitle.expanded = false;
                            contentCell.add(resourcesTitle);
                            resourcesArea.controls.addMany(resources.select(file => {
                                const linkWrapper = new Sol.Control();
                                linkWrapper.css.add("course_list_screen_link");
                                const linkAnchor = new Sol.Control("a");
                                linkAnchor.text = file.Filename;
                                linkAnchor.atributos.agregar("href", file.Link);
                                linkAnchor.atributos.agregar("target", "_blank");
                                linkWrapper.add(linkAnchor);
                                const linkDescription = new Sol.Control();
                                linkDescription.text = file.Description;
                                linkWrapper.add(linkDescription);
                                return linkWrapper;
                            }));
                            contentCell.add(resourcesArea);
                        }
                        const menuTitle = contentCell.addCtr("Opções do curso", "sol_course_list_menu_title");
                        const menuControl = contentCell.addCtr(null, null);
                        if (course.CanEvaluateCourse) {
                            const evaluationButton = new Sol.Button();
                            evaluationButton.css.add("sol_course_list_screen_certificate_menu");
                            evaluationButton.imageCode = "&#xf044";
                            evaluationButton.text = Sol.Environment.resources.evaluateCourse;
                            evaluationButton.type = Sol.ButtonType.Custom;
                            evaluationButton.onClick = () => this.evaluateCourse(model, course.EnrollmentID);
                            menuControl.add(evaluationButton);
                        }
                        if (course.CanDownloadCertificate) {
                            const certificateButton = new Sol.Button();
                            certificateButton.css.add("sol_course_list_screen_certificate_menu");
                            certificateButton.imageCode = "&#xf0a3";
                            certificateButton.text = Sol.Environment.resources.certificate;
                            certificateButton.type = Sol.ButtonType.Custom;
                            certificateButton.onClick = () => this.getCertificate(course.EnrollmentID);
                            menuControl.add(certificateButton);
                        }
                        if (course.CanIssueEnrollmentCertificate) {
                            const enrollmentCertButton = new Sol.Button();
                            enrollmentCertButton.css.add("sol_course_list_screen_certificate_menu");
                            enrollmentCertButton.imageCode = "&#xf15c";
                            enrollmentCertButton.text = Sol.Environment.resources.enrollmentCertificate;
                            enrollmentCertButton.type = Sol.ButtonType.Custom;
                            enrollmentCertButton.onClick = () => this.getEnrollmentCertificate(course.EnrollmentID);
                            menuControl.add(enrollmentCertButton);
                        }
                        if (course.FinalEvaluation) {
                            const finalEvalButton = new Sol.Button();
                            finalEvalButton.type = Sol.ButtonType.Custom;
                            finalEvalButton.imageCode = "&#xf091;";
                            finalEvalButton.text = "Ver minha avaliação final";
                            finalEvalButton.css.add("sol_course_list_screen_certificate_menu");
                            finalEvalButton.onClick = () => this.showCourseEvaluation(course.FinalEvaluation);
                            menuControl.add(finalEvalButton);
                        }
                        menuTitle.visible = menuControl.controls.hasItems();
                    });
                    this.visible = true;
                }
                evaluateCourse(model, enrollmentID) {
                    const details = new Screens.OptionalDetails();
                    details.screenCaption = Sol.Environment.resources.evaluateCourse;
                    details.model = model.EvaluationStructure;
                    details.myScreen = this;
                    details.disableMinimizedControls = true;
                    details.css.add("sol_course_evaluation_screen");
                    details.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    details.onSaved.subscribe(() => this.saveEvaluation(details.code, enrollmentID));
                    Web.System.screens.addScreen(details);
                    Web.System.screens.showScreen(details);
                }
                getCertificate(enrollmentID) {
                    Web.System.exec("laspoesd", "GenerateCertificate", { enrollmentID: enrollmentID }, e => window.open(Sol.Environment.filePath + e.FileLink, "_blank"));
                }
                getEnrollmentCertificate(enrollmentID) {
                    Web.System.exec("laspoesd", "GetEnrollmentCertificate", { enrollmentID: enrollmentID }, e => window.open("", "_blank", "").document.write(e.Html));
                }
                getList() {
                    Web.System.exec("laspoesd", "MyCourses", null, e => this.buildList(e), () => this.visible = false);
                }
                saveEvaluation(evaluationID, enrollmentID) {
                    const request = {
                        className: "Solarium.Education.DistanceEnrollment, Solarium.Education, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        id: enrollmentID,
                        data: [{ Campo: "QualityEvaluation", Valor: evaluationID }],
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", request, () => {
                        this.refresh();
                        Web.System.screens.closeCurrentScreen();
                    });
                }
                showCourseEvaluation(text) {
                    const dialog = new Screens.EvaluationDialog();
                    dialog.evaluationText = text;
                    dialog.onClose = () => this.controls.remove(dialog);
                    this.add(dialog);
                }
            }
            Screens.CourseList = CourseList;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PostIt extends Sol.Control {
                constructor() {
                    super();
                    this.textField = new Sol.TextField();
                    this.code = 0;
                    this.css.add("sol_post_it");
                    this.themeIndex = Math.floor((Math.random() * 4) + 1);
                    ;
                    this.fontSize = 1;
                    const toolbar = new Sol.Control();
                    toolbar.css.add("sol_post_it_toolbar");
                    this.add(toolbar);
                    this.textField.autoHeight = false;
                    this.textField.onChange = () => this.save();
                    this.add(this.textField);
                    const incFontSize = new Sol.Button();
                    incFontSize.type = Sol.ButtonType.Custom;
                    incFontSize.onClick = () => this.fontSize++;
                    incFontSize.css.addMany(["sol_post_it_font_button", "sol_post_it_font_button_inc"]);
                    toolbar.add(incFontSize);
                    const decFontSize = new Sol.Button();
                    decFontSize.type = Sol.ButtonType.Custom;
                    decFontSize.onClick = () => this.fontSize--;
                    decFontSize.css.addMany(["sol_post_it_font_button", "sol_post_it_font_button_dec"]);
                    toolbar.add(decFontSize);
                    toolbar.controls.addMany(Sol.List.range(1, 4).select(i => {
                        const colorButton = new Sol.Button();
                        colorButton.type = Sol.ButtonType.Custom;
                        colorButton.onClick = () => this.themeIndex = i;
                        const buttonLabel = new Sol.Control("span");
                        buttonLabel.css.add("sol_post_it_color_label" + i);
                        colorButton.add(buttonLabel);
                        return colorButton;
                    }));
                    const deleteButton = new Sol.Button();
                    deleteButton.type = Sol.ButtonType.Custom;
                    deleteButton.onClick = () => this.deletePostIt();
                    deleteButton.css.add("sol_post_it_delete_button");
                    toolbar.add(deleteButton);
                }
                get themeIndex() { return this._themeIndex; }
                set themeIndex(value) {
                    this._themeIndex = value;
                    this.textField.css.empty();
                    this.textField.css.add("sol_post_it_theme" + value);
                }
                get fontSize() { return this._fontSize; }
                set fontSize(value) {
                    const sizes = [10, 12, 16, 24];
                    if (value < 1 || value > sizes.length)
                        return;
                    this._fontSize = value;
                    this.textField.estilos.definir("font-size", sizes[value - 1] + "px");
                }
                get postItText() { return this.textField.value; }
                set postItText(value) { this.textField.value = value; }
                deletePostIt() {
                    var deleteModel = {
                        className: "Solarium.UserPreferences.ToDoTask, Solarium.UserPreferences, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        decisionID: null,
                        methodName: "DeleteMany",
                        selectionMode: Web.ActionSelectionMode.None,
                        filters: null,
                        ids: [this.code],
                        inputs: null
                    };
                    Web.System.exec("79k8j542h", "DoMultiple", deleteModel);
                    this.destroy();
                }
                save() {
                    var savingData = {
                        className: "Solarium.UserPreferences.ToDoTask, Solarium.UserPreferences, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        id: this.code,
                        data: [{ Campo: "FontSize", Valor: this.fontSize },
                            { Campo: "Text", Valor: this.textField.value },
                            { Campo: "PostItColor", Valor: this.themeIndex }],
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", savingData, model => this.code = model.ID, null);
                }
            }
            Components.PostIt = PostIt;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ToDoList extends Sol.Control {
                constructor() {
                    super();
                    this.taskArea = new Sol.Control();
                    const title = new Sol.Control("h4");
                    title.text = Sol.Environment.resources.todoList;
                    this.add(title);
                    this.taskArea.css.add("sol_todo_list_task_area");
                    this.add(this.taskArea);
                    const addButton = new Sol.Button();
                    addButton.css.add("sol_todo_list_addbutton");
                    addButton.text = "+";
                    addButton.type = Sol.ButtonType.Custom;
                    addButton.onClick = () => this.taskArea.controls.insert(this.taskArea.controls.count - 1, new Components.PostIt());
                    this.taskArea.add(addButton);
                }
                build() {
                    this.loadPostIts();
                }
                loadPostIts() {
                    var data = {
                        className: "Solarium.UserPreferences.ToDoTask, Solarium.UserPreferences, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 1,
                        rowCount: 50,
                        filters: [],
                        sortProperty: "ID",
                        sortOrder: Web.Ordering.descending,
                        properties: ["Creación", "FontSize", "Text", "PostItColor"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        var results = Sol.List.from(model.Data);
                        var index = 0;
                        results.forEach(item => {
                            var dataValues = Sol.List.from(item);
                            var postIt = new Components.PostIt();
                            postIt.fontSize = dataValues.that(d => d.Campo == "FontSize").Valor;
                            postIt.postItText = dataValues.that(d => d.Campo == "Text").Valor;
                            postIt.themeIndex = dataValues.that(d => d.Campo == "PostItColor").Valor;
                            postIt.code = model.Codes[index++];
                            this.taskArea.controls.insert(0, postIt);
                        });
                    }, null);
                }
            }
            Components.ToDoList = ToDoList;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                let GoalType;
                (function (GoalType) {
                    GoalType[GoalType["ByQuantity"] = 0] = "ByQuantity";
                    GoalType[GoalType["ByAmount"] = 1] = "ByAmount";
                })(GoalType = Selectors.GoalType || (Selectors.GoalType = {}));
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let GoalPeriodicity;
            (function (GoalPeriodicity) {
                GoalPeriodicity[GoalPeriodicity["Period"] = 1] = "Period";
                GoalPeriodicity[GoalPeriodicity["Monthly"] = 2] = "Monthly";
            })(GoalPeriodicity = Components.GoalPeriodicity || (Components.GoalPeriodicity = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class GoalResult extends Sol.Control {
                constructor() {
                    super();
                    this.css.add("sol_goal_result");
                }
                build() {
                    super.build();
                    var title = new Sol.Control("h4");
                    title.text = this.model.Title;
                    this.add(title);
                    var content = new Sol.Control();
                    content.css.add("sol_goal_result_content");
                    var gauge = new Sol.Gauge();
                    gauge.gaugeColor = this.model.MainColor;
                    gauge.value = this.model.Percentage;
                    gauge.size = 78;
                    gauge.showPercent = true;
                    content.add(gauge);
                    var proposedText = new Sol.Control();
                    proposedText.text = Sol.Environment.resources.estimated;
                    proposedText.css.add("sol_goal_result_caption");
                    content.add(proposedText);
                    var proposedValue = new Sol.Control();
                    proposedValue.css.add("sol_goal_result_proposed");
                    proposedValue.text = this.model.Proposed;
                    content.add(proposedValue);
                    var doneText = new Sol.Control();
                    doneText.css.add("sol_goal_result_caption");
                    doneText.text = Sol.Environment.resources.accomplished;
                    content.add(doneText);
                    var doneValue = new Sol.Control();
                    doneValue.css.add("sol_goal_result_done");
                    doneValue.text = this.model.Done;
                    doneValue.estilos.agregar("color", this.model.MainColor);
                    content.add(doneValue);
                    if (this.model.Expected) {
                        var expectedText = new Sol.Control();
                        expectedText.css.add("sol_goal_result_caption");
                        expectedText.text = Sol.Environment.resources.expected;
                        content.add(expectedText);
                        var expectedValue = new Sol.Control();
                        expectedValue.css.add("sol_goal_expected_value");
                        expectedValue.text = this.model.Expected;
                        content.add(expectedValue);
                    }
                    var reportButton = new Sol.Button();
                    reportButton.type = Sol.ButtonType.Link;
                    reportButton.imageCode = "&#xf0ce;";
                    reportButton.text = Sol.Environment.resources.report;
                    reportButton.onClick = () => this.openReport();
                    content.add(reportButton);
                    this.add(content);
                }
                openReport() {
                    const reportRequestData = {
                        goalId: this.model.GoalID,
                        startDate: this.model.StartDate,
                        endDate: this.model.EndDate
                    };
                    Web.System.exec("9sw4pbyy", "GetUserReport", reportRequestData, e => {
                        this.reportScreen = new Web.Screens.ReportScreen();
                        this.reportScreen.screenCaption = this.model.Title;
                        this.reportScreen.onSearch = rep => this.refreshReport(rep);
                        if (this.model.Periodicity == Components.GoalPeriodicity.Monthly)
                            this.reportScreen.setFilterStructure([{
                                    DataType: "SMonthYear",
                                    Visibility: Sol.FieldVisibility.Always,
                                    FormPosition: Web.FormPosition.form
                                }]);
                        Web.System.screens.addScreen(this.reportScreen);
                        Web.System.screens.showScreen(this.reportScreen);
                        this.reportScreen.openReport(e);
                    });
                }
                refreshReport(report) {
                    const monthYearValue = report.customFilters.first().FilterValue;
                    const reportRequestData = {
                        goalId: this.model.GoalID,
                        startDate: monthYearValue.Start,
                        endDate: monthYearValue.End
                    };
                    Web.System.exec("9sw4pbyy", "GetUserReport", reportRequestData, e => {
                        report.customFiltersStructure[0].DefaultValue = monthYearValue;
                        this.reportScreen.openReport(e);
                    });
                }
            }
            Components.GoalResult = GoalResult;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class GoalSummary extends Sol.Control {
                build() {
                    super.build();
                    this.css.add("sol_goal_summary");
                    Web.System.exec("9sw4pbyy", "GetMyGoals", null, e => {
                        var goals = Sol.List.from(e);
                        this.controls.addMany(goals.select(g => {
                            var goalResult = new Components.GoalResult();
                            goalResult.model = g;
                            return goalResult;
                        }));
                    });
                }
            }
            Components.GoalSummary = GoalSummary;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class DashboardScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.contentWrapper = new Sol.Control();
                    this.mainArea = new Sol.Control();
                    this.sideArea = new Sol.Control();
                }
                get startFileScreen() { return this.startScreen; }
                refreshSearch() { var _a; (_a = this.startFileScreen) === null || _a === void 0 ? void 0 : _a.refreshSearch(); }
                onSetModel() {
                    super.onSetModel();
                    this.myModel = this.model;
                    this.screenCaption = this.myModel.Title;
                    this.initializeWelcomeImage();
                    this.initializeScreenStructure();
                    if (this.myModel.GroupIconsByTopic) {
                        let topics = this.getAllTopics();
                        for (var topic of topics) {
                            let iconsSpace = new Sol.Control();
                            iconsSpace.css.add("sol_icons");
                            let baseSpace = iconsSpace.addCtr(null, "sol_icons_box");
                            baseSpace.add(new Screens.DashboardSeparator(topic));
                            let hasTots = this.insertTotalizers(baseSpace, topic);
                            if (hasTots)
                                baseSpace.add(new Sol.LineBreak());
                            this.initializeIcons(baseSpace, topic);
                            this.addExternalLinks(baseSpace, topic);
                            this.initializeReports(baseSpace, topic);
                            this.mainArea.add(iconsSpace);
                        }
                    }
                    else {
                        this.initializeTotalizers();
                        let iconsSpace = this.initializeIcons(this.mainArea);
                        this.initializeMenuIcons(iconsSpace);
                        this.initializeReports(this);
                        this.addExternalLinks(this);
                    }
                    this.initializeCustomContent();
                    this.initializeWidgets();
                    this.initializeStartFileScreen();
                    this.initializeAdvertisement();
                    this.initializeRefreshButton();
                    this.configureRotation();
                    this.sideArea.visible = this.sideArea.controls.hasItems();
                }
                initializeRefreshButton() {
                    if (this.myModel.IsRotative)
                        return;
                    const refreshButton = new Sol.Button();
                    refreshButton.type = Sol.ButtonType.Link;
                    refreshButton.css.add("sol_dashboard_refresh_button");
                    refreshButton.text = Sol.Environment.resources.actualizar;
                    refreshButton.onClick = () => Web.System.screens.reloadDashboard();
                    this.add(refreshButton);
                }
                getAllTopics() {
                    let topics = Sol.List.from(this.myModel.Icons)
                        .select(i => this.getMenu(i))
                        .where(mn => !!mn)
                        .orderBy(mn => mn.TopicID)
                        .select(mn => mn.TopicName);
                    topics.addMany(Sol.List.from(this.myModel.Reports).select(rpt => rpt.Topic));
                    return topics.distinct().toArray();
                }
                initializeWelcomeImage() {
                    if (!this.myModel.WelcomeImage)
                        return;
                    var imageWrapper = new Sol.Control();
                    imageWrapper.css.add("sol_welcome_wrapper");
                    this.add(imageWrapper);
                    var welcomeImg = new Sol.ImageBox();
                    welcomeImg.source = Sol.Environment.filePath + this.myModel.WelcomeImage;
                    imageWrapper.add(welcomeImg);
                    if (this.myModel.WelcomeBackgroundColor != "#000000")
                        imageWrapper.estilos.agregar("background-color", this.myModel.WelcomeBackgroundColor);
                }
                initializeScreenStructure() {
                    this.contentWrapper.css.add("sol_dashboard_content");
                    this.mainArea.css.add("sol_dashboard_content_main");
                    this.sideArea.css.add("sol_dashboard_content_side");
                    this.contentWrapper.add(this.mainArea);
                    this.contentWrapper.add(this.sideArea);
                    this.add(this.contentWrapper);
                }
                initializeIcons(target, topic = null) {
                    if (this.myModel.IsRotative)
                        return;
                    let iconList = Sol.List.from(this.myModel.Icons);
                    let menuIconList = Sol.List.from(this.myModel.MenuIcons);
                    if (!iconList.hasItems() && !menuIconList.hasItems())
                        return;
                    let iconsSpace = new Sol.Control();
                    iconsSpace.css.add("sol_icons");
                    let baseSpace = iconsSpace;
                    let icons = iconList.select(i => this.getMenu(i)).where(mn => !!mn).orderBy(mn => mn.TopicID);
                    if (topic)
                        icons = icons.where(i => i.TopicName == topic);
                    icons.forEach(i => {
                        const tile = Web.Components.Icons.BaseIcon.fromMenu(i);
                        tile.parent = this;
                        tile.atributos.agregar("uid", i.UniqueID);
                        baseSpace.add(tile);
                        setTimeout(() => tile.refresh(), 500);
                    });
                    target.add(iconsSpace);
                    return iconsSpace;
                }
                initializeMenuIcons(target) {
                    let iconList = Sol.List.from(this.myModel.MenuIcons);
                    if (!iconList.hasItems())
                        return;
                    iconList.forEach(i => {
                        const tile = Web.Components.Icons.BaseIcon.fromMenu(i);
                        tile.parent = this;
                        tile.atributos.agregar("uid", i.UniqueID);
                        target.add(tile);
                        setTimeout(() => tile.refresh(), 500);
                    });
                }
                addExternalLinks(iconSpace, topicName = null) {
                    let externalLinks = Sol.List.from(this.myModel.ExternalLinks);
                    if (this.myModel.GroupIconsByTopic)
                        externalLinks = externalLinks.where(lk => lk.TopicName == topicName);
                    iconSpace.addMany(externalLinks.select(lk => {
                        const icon = new Web.Components.Icons.LinkIcon();
                        icon.iconCode = `&#x${lk.IconCode};`;
                        icon.labelText = lk.Nombre;
                        icon.url = lk.URL;
                        return icon;
                    }));
                }
                initializeWidgets() {
                    Sol.List.from(this.myModel.Widgets).forEach(w => {
                        let control = eval(`new ${w.Component}()`);
                        control.configuration = w.Configuration;
                        if (w.Position == Screens.WidgetPosition.MainArea)
                            this.mainArea.add(control);
                        else
                            this.sideArea.add(control);
                    });
                }
                initializeStartFileScreen() {
                    if (!this.myModel.StartFileScreen)
                        return;
                    let screenArea = new Sol.Control();
                    this.add(screenArea);
                    let loader = new Web.Components.LoaderControl();
                    loader.caption = Sol.Environment.resources.cargando;
                    loader.baseControl = screenArea;
                    loader.show();
                    let requestData = {
                        ScreenName: this.myModel.StartFileScreenType,
                        ClassName: this.myModel.StartFileScreen
                    };
                    Web.System.exec("lsperos32", "Open", requestData, e => {
                        loader.hide();
                        this.startScreen = Web.System.screens.getScreenType(this.myModel.StartFileScreenType);
                        this.startScreen.model = e;
                        screenArea.add(this.startScreen);
                        setTimeout(() => this.startScreen.onOpenScreen(), 300);
                        if (this.startScreen instanceof Screens.Registro) {
                            this.startFileScreen.myScreen = this;
                            let currentSystem = Sol.Environment.credential.empresa;
                            if (this.myModel.RefreshTime > 0) {
                                var refreshInterval = setInterval(() => {
                                    if (Sol.Environment.credential.empresa != currentSystem) {
                                        clearInterval(refreshInterval);
                                        return;
                                    }
                                    this.startFileScreen.refreshSearch();
                                }, this.myModel.RefreshTime * 1000);
                            }
                        }
                    }, () => Web.System.screens.openScreenWithModel("ErrorScreen"));
                }
                initializeAdvertisement() {
                    if (!this.myModel.ShowCompanyAdvertisement)
                        return;
                    var advertisement = new Sol.Control();
                    advertisement.text = this.myModel.AdvertisementText;
                    advertisement.css.add("sol_company_advertisement");
                    this.add(advertisement);
                }
                initializeTotalizers() {
                    var _a;
                    const tilesArea = new Sol.Control();
                    tilesArea.css.add("sol_dashboard_tile_container");
                    if (((_a = this.myModel.Reports) === null || _a === void 0 ? void 0 : _a.length) > 0)
                        this.mainArea.add(tilesArea);
                    this.insertTotalizers(tilesArea, null);
                }
                insertTotalizers(baseControl, topic) {
                    let totalizers = Sol.List.from(this.myModel.Reports)
                        .where(rpt => rpt.ReportType == Web.Components.Reports.ReportType.Totalizer ||
                        rpt.ReportType == Web.Components.Reports.ReportType.Average ||
                        rpt.ReportType == Web.Components.Reports.ReportType.ResultList)
                        .where(rpt => rpt.Topic == topic);
                    baseControl.controls.addMany(totalizers.select(rpt => {
                        let tile = new Web.Components.Reports.DashboardTile();
                        tile.code = rpt.Code;
                        tile.model = rpt;
                        tile.showRemoveButton = this.myModel.AllowCustomizeDashboards;
                        tile.screen = this;
                        tile.onRemove = () => this.removeReport(tile, tile.code);
                        tile.createFromSuggestion(this.convertReportToSuggestion(rpt), this.getFiltersFromReport(rpt));
                        return tile;
                    }));
                    return totalizers.hasItems();
                }
                convertReportToSuggestion(report) {
                    return {
                        ReportTitle: report.Title,
                        CurrencyPropertyName: report.CurrencyPropertyName,
                        IsMultiCurrency: report.IsMultiCurrency,
                        SelectedCurrency: report.SelectedCurrency,
                        PropertyName: report.PivotPropertyName,
                        ReportType: report.ReportType,
                        Type: report.ClassType,
                        ReportTypeName: report.ReportTypeName,
                        Columns: report.Columns,
                        CustomFiltersStructure: report.CustomFiltersStructure,
                        CustomFiltersTypeName: null,
                        DefaultFilters: [],
                        IsRecommended: false
                    };
                }
                getFiltersFromReport(report) {
                    return Sol.List.from(report.Filters).select(flt => ({
                        FilterType: flt.FilterType,
                        PropertyName: flt.PropertyName,
                        FilterValue: JSON.parse(flt.FilterValue)
                    }))
                        .toArray();
                }
                initializeReports(target, topic = null) {
                    target.controls.addMany(Sol.List.from(this.myModel.Reports)
                        .where(rpt => rpt.ReportType == Web.Components.Reports.ReportType.IntervalReport || rpt.ReportType == Web.Components.Reports.ReportType.QuantityReport)
                        .where(rpt => !topic || rpt.Topic == topic)
                        .select(rpt => {
                        var wrapper = new Screens.ReportWrapper();
                        if (this.myModel.IsRotative)
                            wrapper.estilos.agregar("width", "100%");
                        const report = new Web.Components.Reports.Report();
                        report.code = rpt.Code;
                        report.showRemoveButton = this.myModel.AllowCustomizeDashboards;
                        report.minimizable = !rpt.ReportOpen && !this.myModel.IsRotative;
                        report.isMonitored = !this.myModel.IsRotative;
                        report.onRemove = () => this.removeReport(wrapper, report.code);
                        report.createFromSuggestion(this.convertReportToSuggestion(rpt), this.getFiltersFromReport(rpt));
                        wrapper.myReport = report;
                        wrapper.add(report);
                        return wrapper;
                    }));
                }
                initializeCustomContent() {
                    var _a;
                    if (((_a = this.myModel.CustomContent) === null || _a === void 0 ? void 0 : _a.length) < 1)
                        return;
                    var customContentContainer = new Sol.Control();
                    customContentContainer.css.add("sol_dashboard_custom_content");
                    customContentContainer.htmlContent = this.myModel.CustomContent;
                    this.add(customContentContainer);
                }
                getMenu(iconModel) {
                    var _a;
                    let menuPath = iconModel.Icon;
                    let slashIndex = ((menuPath === null || menuPath === void 0 ? void 0 : menuPath.indexOf('/')) || 0) + 1;
                    menuPath = menuPath === null || menuPath === void 0 ? void 0 : menuPath.substring(slashIndex);
                    for (var menu of Web.System.screens.menuBag.toArray())
                        for (var submenu of menu.Submenus)
                            if (submenu.Clase == menuPath) {
                                if (iconModel.Topic) {
                                    submenu.TopicName = iconModel.Topic;
                                    submenu.TopicID = (_a = Web.System.screens.allMenus.that(b => b.TopicName == iconModel.Topic)) === null || _a === void 0 ? void 0 : _a.TopicID;
                                }
                                return submenu;
                            }
                    return null;
                }
                removeReport(controlToRemove, reportCode) {
                    this.controls.remove(controlToRemove);
                    var deleteModel = {
                        className: "Solarium.UserPreferences.DashboardReport, Solarium.UserPreferences, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        decisionID: null,
                        methodName: "DeleteMany",
                        selectionMode: Web.ActionSelectionMode.None,
                        filters: null,
                        ids: [reportCode],
                        inputs: null
                    };
                    Web.System.exec("79k8j542h", "DoMultiple", deleteModel, null, null);
                }
                configureRotation() {
                    if (!this.myModel.IsRotative)
                        return;
                    var skipOffset = this.myModel.WelcomeImage ? 2 : 1;
                    if (this.controls.count <= skipOffset)
                        return;
                    this.controls.skip(skipOffset).forEach(ctr => ctr.visible = false);
                    this.controls.skip(skipOffset).first().visible = true;
                    this.rotationIndex = skipOffset;
                    setInterval(() => {
                        this.rotationIndex = this.rotationIndex == this.controls.count - 1 ? skipOffset : this.rotationIndex + 1;
                        this.controls.skip(skipOffset).forEach(ctr => ctr.visible = false);
                        this.controls.item(this.rotationIndex).visible = true;
                        var nextIndex = this.rotationIndex == this.controls.count - 1 ? skipOffset : this.rotationIndex + 1;
                        if (this.controls.item(nextIndex) instanceof Screens.ReportWrapper)
                            this.controls.item(nextIndex).refresh();
                    }, this.myModel.RefreshTime * 1000);
                }
            }
            Screens.DashboardScreen = DashboardScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Reports;
            (function (Reports) {
                class DashboardTile extends Sol.Control {
                    constructor() {
                        super(...arguments);
                        this.amountDisplay = new Sol.Control("span");
                        this.percentDisplay = new Sol.Control("span");
                        this.percentIcon = new Sol.Control("i");
                        this.projectionDisplay = new Sol.Control();
                        this.projectionText = new Sol.Control();
                        this.model = {};
                        this.showRemoveButton = false;
                        this.showRefreshButton = true;
                    }
                    createFromSuggestion(report, filters) {
                        this.mySuggestion = report;
                        this.filters = filters;
                        this.refresh();
                    }
                    refresh() {
                        this.amountDisplay.text = "...";
                        const data = {
                            report: this.mySuggestion,
                            identifier: this.model.Identifier || "total",
                            filters: this.filters
                        };
                        Web.System.exec("hw9rh93h5", "Totalize", data, model => {
                            this.amountDisplay.text = model.Amount;
                            if (this.amountDisplay.text.length > 16)
                                this.amountDisplay.css.add("sol_dashboard_total_form_size");
                            else
                                this.amountDisplay.css.add("sol_dashboard_total_form");
                            this.percentDisplay.text = model.Variation || "&nbsp;";
                            this.percentDisplay.tip = model.VariationDescription;
                            this.projectionDisplay.text = model.Projection;
                            this.projectionDisplay.visible = !!model.Projection;
                            this.projectionText.visible = this.projectionDisplay.visible;
                            if (model.VariationSign == Reports.TileVariationSign.Increasing) {
                                this.percentIcon.text = "&#xf062;";
                                this.percentIcon.tip = model.VariationDescription;
                                this.percentIcon.css.add("sol_dashboard_percent_increase");
                            }
                            else if (model.VariationSign == Reports.TileVariationSign.Decreasing) {
                                this.percentIcon.text = "&#xf063;";
                                this.percentIcon.tip = model.VariationDescription;
                                this.percentIcon.css.add("sol_dashboard_percent_decrease");
                            }
                            else
                                this.percentIcon.css.add("sol_dashboard_percent_none");
                        });
                    }
                    build() {
                        super.build();
                        this.css.add("sol_dashboard_tile sol_dashboard_tile_report");
                        if (this.model.Color)
                            this.estilos.definir("background", this.model.Color);
                        this.initTitle();
                        this.initPercentWrapper();
                        this.initTotalForm();
                        this.initAutoRefresh();
                        if (this.screen)
                            this.onClick = () => this.openReport();
                    }
                    initTitle() {
                        var title = new Sol.Control();
                        title.css.add("sol_dashboard_tile_title");
                        if (this.model.FontColor)
                            title.estilos.definir("color", this.model.FontColor);
                        title.text = this.model.Title || this.mySuggestion.ReportTitle;
                        this.add(title);
                        if (this.showRemoveButton) {
                            var removeButton = new Sol.Control();
                            removeButton.css.add("sol_dashboard_tile_remove");
                            removeButton.text = "x";
                            removeButton.tip = Sol.Environment.resources.eliminar;
                            removeButton.onClick = () => {
                                if (this.onRemove)
                                    this.onRemove(this);
                            };
                            title.add(removeButton);
                        }
                        if (this.showRefreshButton) {
                            var refreshButton = new Sol.Control();
                            refreshButton.css.add("sol_dashboard_tile_refresh");
                            refreshButton.tip = Sol.Environment.resources.actualizar;
                            refreshButton.onClick = () => this.refresh();
                            title.add(refreshButton);
                        }
                    }
                    initPercentWrapper() {
                        var percentWrapper = new Sol.Control("span");
                        percentWrapper.css.add("sol_dashboard_percent_form");
                        this.percentDisplay.css.add("sol_dashboard_percent_value");
                        this.percentIcon.text = "&#xf062;";
                        percentWrapper.add(this.percentIcon);
                        percentWrapper.add(this.percentDisplay);
                        this.add(percentWrapper);
                    }
                    initTotalForm() {
                        this.amountDisplay.text = "...";
                        if (this.model.FontColor)
                            this.amountDisplay.estilos.definir("color", this.model.FontColor);
                        this.add(this.amountDisplay);
                        this.projectionDisplay.visible = false;
                        this.projectionDisplay.css.add("sol_dashboard_total_proj");
                        this.add(this.projectionDisplay);
                        this.projectionText.visible = false;
                        this.projectionText.css.add("sol_dashboard_total_proj_text");
                        this.projectionText.text = Sol.Environment.resources.projection;
                        this.add(this.projectionText);
                    }
                    initAutoRefresh() {
                        setInterval(() => this.refresh(), 600000);
                    }
                    openReport() {
                        let dashboardScreen = this.getDashboardScreen();
                        if (this.mySuggestion.ReportType == Reports.ReportType.ResultList) {
                            if (dashboardScreen) {
                                dashboardScreen.setFilters(this.model.Filters);
                                dashboardScreen.onOpenScreen();
                            }
                            else
                                Web.System.screens.openScreen("Registro", this.model.ClassType, null, null, null, scr => {
                                    dashboardScreen = scr;
                                    dashboardScreen.setFilters(this.model.Filters);
                                });
                        }
                        else if (dashboardScreen) {
                            dashboardScreen.setFilters(this.model.Filters);
                            dashboardScreen.onOpenScreen();
                        }
                        else {
                            let reportScreen = new Web.Screens.ReportScreen();
                            reportScreen.showPrintButton = true;
                            reportScreen.openSuggestion(this.mySuggestion);
                            Web.System.screens.addScreen(reportScreen);
                            Web.System.screens.showScreen(reportScreen);
                        }
                    }
                    getDashboardScreen() {
                        var _a;
                        return Web.System.screens.currentScreen instanceof Web.Screens.DashboardScreen &&
                            ((_a = Web.System.screens.currentScreen.startFileScreen) === null || _a === void 0 ? void 0 : _a.classType) == this.model.ClassType ?
                            Web.System.screens.currentScreen.startFileScreen : null;
                    }
                }
                Reports.DashboardTile = DashboardTile;
            })(Reports = Components.Reports || (Components.Reports = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SubgroupTitleRow extends Components.GridRow {
                constructor(caption, colspan) {
                    super();
                    this.rowType = Components.GridRowType.Subgroup;
                    this.css.add("sol_tabla_subtitle");
                    let cell = this.addCtr(caption, null, "td");
                    cell.atributos.agregar("colspan", colspan.toString());
                }
            }
            Components.SubgroupTitleRow = SubgroupTitleRow;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TableDialogEditor extends Sol.Control {
                constructor() {
                    super();
                    this.mainButton = new Sol.Button();
                    this.dialog = new Sol.FormDialog();
                    this.dataview = new Components.DataView();
                    this.css.add("sol_table_dialog");
                    this.mainButton.showCounter = true;
                    this.add(this.mainButton);
                    this.dataview.showSearchBox = false;
                    this.dataview.fixedRows = false;
                    this.dataview.showChecks = false;
                    this.dataview.showVerticalLines = true;
                    this.dialog.addToForm(this.dataview);
                    this.dialog.visible = false;
                    this.add(this.dialog);
                    this.onClick = () => this.showDialog();
                    this.dialog.onSave = () => this.saveValues();
                }
                get caption() { return this.mainButton.text; }
                set caption(value) {
                    this.mainButton.text = value;
                    this.dialog.title = value;
                }
                get readonly() { return this.dataview.readonly; }
                set readonly(value) { this.dataview.readonly = value; }
                get required() { return this.dataview.required; }
                set required(value) { this.dataview.required = value; }
                get value() { return this._value; }
                set value(value) {
                    this._value = value;
                    this.mainButton.setCounterValue(value.length);
                }
                saveValues() {
                    this.dialog.workComplete();
                    this.value = this.dataview.value;
                    this.dialog.visible = false;
                }
                showDialog() {
                    if (this.dialog.visible)
                        return;
                    this.dataview.value = this.value;
                    this.dialog.visible = true;
                }
                clear() { }
                foco() { }
                isEmpty() { return this.dataview.isEmpty(); }
                toControl() { return this; }
                validate() { return this.dataview.validate(); }
            }
            Components.TableDialogEditor = TableDialogEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class AutoNumberField extends Sol.Field {
                constructor() {
                    super(...arguments);
                    this.isCodeBasedComponent = true;
                    this.yearPropertyName = null;
                }
                build() {
                    super.build();
                    if (!this.contextCode)
                        this.suggestNumber();
                }
                suggestNumber() {
                    const data = {
                        className: this.className,
                        propertyName: this.propertyName,
                        yearProperty: this.yearPropertyName
                    };
                    Web.System.exec("nlskd23jor", "SuggestAutoNumber", data, e => this.value = e.toString());
                }
            }
            Components.AutoNumberField = AutoNumberField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("AutoNumber", (model, contextClass, code) => {
    const field = new Sol.Web.Components.AutoNumberField();
    field.className = contextClass;
    field.propertyName = model.PropertyName;
    field.contextCode = code;
    if (model.Width)
        field.ancho = model.Width;
    return field;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DualComboFilter extends Components.DualCombo {
                isEmpty() { return this.mainCombo.isEmpty(); }
                getValue() { return { sub: this.subCombo.selectedCode, main: this.mainCombo.selectedCode }; }
                setValue(v) { }
            }
            Components.DualComboFilter = DualComboFilter;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerFilter("DualCombo", () => new Sol.Web.Components.DualComboFilter());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SaleParticipationEditor extends Components.DataView {
                constructor() {
                    super();
                    this.currentMargin = 0;
                    this.showSearchBox = false;
                    this.fixedRows = false;
                    this.showChecks = false;
                }
                get isTotalSubscriber() { return true; }
                addRow(data = null) {
                    var row = super.addRow(data);
                    if (!this.disableDivision) {
                        if (this.rowCount == 1)
                            this.suggestConsultant(row);
                        this.dividePercents();
                    }
                    var percentField = row.getEditor("Participation");
                    percentField.onModified = () => this.calculateMargin(row);
                    var marginField = row.getEditor("Margin");
                    marginField.readonly = true;
                    return row;
                }
                calculateMargin(row) {
                    var percentField = row.getEditor("Participation");
                    var marginField = row.getEditor("Margin");
                    marginField.numericValue = this.currentMargin * (percentField.value / 100);
                }
                onTotalPublished(message) {
                    this.currentMargin = message.margin;
                    this.rows.forEach(row => this.calculateMargin(row));
                }
                deleteRow(row) {
                    super.deleteRow(row);
                    this.dividePercents();
                    return false;
                }
                setValor(v) {
                    this.disableDivision = true;
                    super.setValor(v);
                    this.disableDivision = false;
                }
                dividePercents() {
                    if (this.rowCount == 0)
                        return;
                    var rowPercent = 100 / this.rowCount;
                    this.rows.forEach(row => {
                        var percentField = row.getEditor("Participation");
                        percentField.value = rowPercent;
                        this.calculateMargin(row);
                    });
                }
                suggestConsultant(row) {
                    var consultantEditor = this.container.editors.that(edt => edt.propertyName == "Consultant");
                    if (!consultantEditor)
                        return;
                    var consultantField = row.getEditor("Consultant");
                    consultantField.value = consultantEditor.value;
                }
            }
            Components.SaleParticipationEditor = SaleParticipationEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CommissionedPartnerEditor extends Components.DataView {
                constructor() {
                    super();
                    this.showSearchBox = false;
                    this.fixedRows = false;
                    this.showChecks = false;
                }
                addRow(data = null) {
                    var row = super.addRow(data);
                    var marginField = row.getEditor("Commission");
                    marginField.onChange = () => this.changeTotal();
                    return row;
                }
                changeTotal() {
                    if (this.onTotalsChanged)
                        this.onTotalsChanged();
                }
                get margin() {
                    var commissionTotal = 0;
                    this.rows.forEach(r => commissionTotal += r.getEditor("Commission").numericValue);
                    return -commissionTotal;
                }
            }
            Components.CommissionedPartnerEditor = CommissionedPartnerEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class FollowUpsEditor extends Sol.Control {
                constructor() {
                    super();
                    this.messagesEditor = new Components.MessagesEditor();
                    this.isComplex = false;
                    this._code = 0;
                    this.add(this.messagesEditor);
                    this.messagesEditor.showContacts = false;
                    this.messagesEditor.showMessageTitle = false;
                }
                get code() { return this._code; }
                set code(v) {
                    this._code = v;
                    this.messagesEditor.code = v;
                    this.clear();
                    if (v)
                        setTimeout(() => this.messagesEditor.loadPage(), 300);
                }
                isEmpty() {
                    return !Sol.List.from(this.messagesEditor.value).hasItems();
                }
                validate() { return null; }
                get value() { return this.messagesEditor.value; }
                set value(v) { }
                toControl() { return this; }
                clear() { this.messagesEditor.resetEditor(); }
                build() {
                    super.build();
                    this.messagesEditor.className = this.className;
                    this.messagesEditor.associativeProperty = this.associativeProperty;
                }
                foco() { }
            }
            Components.FollowUpsEditor = FollowUpsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class SaleFollowupsButon extends Components.FollowupsButton {
                constructor() {
                    super();
                    this.readonly = true;
                    this.showContacts = false;
                    this.automaticSaving = true;
                    this.className = "Solarium.Commercial.DealFollowup, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.associativeProperty = "Negocio";
                }
                build() {
                    super.build();
                    this.text = Sol.Environment.resources.messages;
                }
                setValue(value) {
                    this.code = value;
                    this.enabled = !!this.code;
                }
            }
            Components.SaleFollowupsButon = SaleFollowupsButon;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class StatusFilter extends Sol.MultipleCombo {
                constructor() {
                    super(...arguments);
                    this.allStatusCheck = new Sol.Check();
                    this.openStatusCheck = new Sol.Check();
                    this.currentStatusCheck = new Sol.Check();
                    this.intervalFilter = new Sol.IntervalCombo();
                }
                get allDefaultOption() { return this._allDefaultOption; }
                set allDefaultOption(value) {
                    this._allDefaultOption = value;
                    this.clear();
                }
                clear() {
                    super.clear();
                    this.openStatusCheck.checked = !this.allDefaultOption;
                    this.allStatusCheck.checked = this.allDefaultOption;
                    this.currentStatusCheck.clear();
                    this.intervalFilter.clear();
                    this.refreshDisplay();
                }
                isEmpty() { return false; }
                setOptions(options) {
                    this.createTitle("Filtrar por status");
                    this.createCommonFilters();
                    this.createTitle("Status específicos");
                    this.createOptions(options);
                    this.createTitle("Opções avançadas");
                    this.createDateFilter();
                    this.createCurrentStatusFilter();
                    this.clear();
                }
                getValue() {
                    return {
                        All: this.allStatusCheck.checked,
                        Open: this.openStatusCheck.checked,
                        Codes: this.selectedCodes,
                        OnlyCurrent: this.currentStatusCheck.checked,
                        Time: this.intervalFilter.value
                    };
                }
                setValue(value) {
                    if (Array.isArray(value)) {
                        const model = value;
                        value = {
                            All: false,
                            Open: false,
                            Codes: [model[0]],
                            OnlyCurrent: true,
                            Time: { Opcion: 0, Quarter: 1, Inicio: undefined, Termino: undefined }
                        };
                    }
                    super.setValue(value.Codes);
                    this.allStatusCheck.checked = value.All;
                    this.openStatusCheck.checked = value.Open;
                    this.currentStatusCheck.checked = value.OnlyCurrent;
                    this.intervalFilter.value = value.Time;
                    this.refreshDisplay();
                }
                refreshDisplay() {
                    super.refreshDisplay();
                    if (this.allStatusCheck.checked)
                        this.mainField.text = this.allStatusCheck.caption;
                    if (this.openStatusCheck.checked)
                        this.mainField.text = this.openStatusCheck.caption;
                    if (!this.intervalFilter.isEmpty())
                        this.mainField.text += ' ' + this.intervalFilter.description;
                }
                createTitle(text) {
                    this.popup.addCtr(text, "sol_combo_multiple_section", "li");
                }
                createCommonFilters() {
                    const filterItem = new Sol.Control("li");
                    this.openStatusCheck.caption = "Em andamento";
                    this.openStatusCheck.onValueModified.subscribe(() => this.valueModified(this.openStatusCheck));
                    filterItem.add(this.openStatusCheck);
                    this.allStatusCheck.caption = Sol.Environment.resources.todos;
                    this.allStatusCheck.onValueModified.subscribe(() => this.valueModified(this.allStatusCheck));
                    filterItem.add(this.allStatusCheck);
                    this.popup.add(filterItem);
                }
                createOptions(options) {
                    const optionsItem = this.popup.addCtr(null, null, "ul");
                    this.createItems(optionsItem, options);
                }
                createCurrentStatusFilter() {
                    const filterItem = new Sol.Control("li");
                    this.currentStatusCheck.caption = "Que os status selecionados sejam o status atual";
                    this.currentStatusCheck.onChange = () => this.valueModified(this.currentStatusCheck);
                    filterItem.add(this.currentStatusCheck);
                    this.popup.add(filterItem);
                }
                createDateFilter() {
                    const dateItem = new Sol.Control("li");
                    dateItem.addCtr("Com status alterado durante:", null, "span");
                    this.intervalFilter.onModified = () => this.valueModified(this.intervalFilter);
                    dateItem.add(this.intervalFilter);
                    this.popup.add(dateItem);
                }
                evaluateChecks(sender) {
                    if (sender == this.allStatusCheck && this.allStatusCheck.checked) {
                        this.openStatusCheck.checked = false;
                        this.unselectItems();
                        this.currentStatusCheck.checked = false;
                        this.intervalFilter.clear();
                    }
                    if (sender == this.openStatusCheck && this.openStatusCheck.checked) {
                        this.allStatusCheck.checked = false;
                        this.unselectItems();
                        this.currentStatusCheck.checked = false;
                        this.intervalFilter.clear();
                    }
                    if (this.items.contains(sender) && sender.model.Checked) {
                        this.allStatusCheck.checked = false;
                        this.openStatusCheck.checked = false;
                    }
                    this.currentStatusCheck.readonly = this.allStatusCheck.checked || this.openStatusCheck.checked || !this.selectedItems.hasItems();
                    this.intervalFilter.readonly = this.currentStatusCheck.readonly;
                    if (this.currentStatusCheck.readonly) {
                        this.currentStatusCheck.checked = false;
                        this.intervalFilter.clear();
                    }
                }
                valueModified(sender) {
                    this.evaluateChecks(sender);
                    super.valueModified(sender);
                }
            }
            Components.StatusFilter = StatusFilter;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class LocalTextField extends Sol.Control {
                constructor() {
                    super();
                    this.field = new Sol.Field();
                    this.languageCombo = new Sol.Combo();
                    this.currentLang = Sol.Environment.credential.idioma;
                    this.languages = Sol.List.from(["es", "pt", "en"]);
                    this.valores = {};
                    this.isComplex = false;
                    this.useWrapper = true;
                    this.css.add("sol_campo_localizable");
                    this.add(this.field);
                    this.languageCombo.controls.addMany(this.languages.select(idioma => {
                        var comboItem = new Sol.ComboItem();
                        comboItem.text = idioma.toUpperCase();
                        comboItem.code = idioma;
                        comboItem.selected = Sol.Environment.credential.idioma === idioma;
                        return comboItem;
                    }));
                    this.languageCombo.onChange = () => this.idiomaModificado();
                    this.add(this.languageCombo);
                }
                get tamanoMaximo() { return this.field.maxLength; }
                set tamanoMaximo(valor) { this.field.maxLength = valor; }
                validate() { return null; }
                get value() {
                    this.valores[this.currentLang] = this.field.textValue;
                    return this.languages.select(idioma => ({
                        Language: idioma,
                        Text: this.valores[idioma]
                    })).toArray();
                }
                set value(v) {
                    Sol.List.from(v).forEach(texto => this.valores[texto.Language] = texto.Text);
                    this.field.textValue = this.valores[this.currentLang];
                }
                toControl() { return this; }
                isEmpty() {
                    return false;
                }
                foco() { this.field.foco(); }
                clear() { }
                idiomaModificado() {
                    this.valores[this.currentLang] = this.field.textValue;
                    this.currentLang = this.languageCombo.selectedCode;
                    this.field.textValue = this.valores[this.currentLang];
                    this.field.foco();
                }
            }
            Components.LocalTextField = LocalTextField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                let AccountType;
                (function (AccountType) {
                    AccountType[AccountType["Credit"] = 249253918] = "Credit";
                    AccountType[AccountType["Debit"] = 1622211813] = "Debit";
                })(AccountType = Selectors.AccountType || (Selectors.AccountType = {}));
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DebitCreditEditor extends Sol.Control {
                constructor() {
                    super();
                    this.debitCreditOption = new Sol.MultipleChoice();
                    this.valueField = new Sol.CurrencyField();
                    this.isComplex = false;
                    this.onModeChanged = new Sol.EventHandler();
                    this.css.add("sol_debit_credit");
                    this.debitCreditOption.inlineItems = true;
                    this.debitCreditOption.options = [
                        {
                            Code: "1",
                            Description: "A receber",
                            Checked: true
                        },
                        {
                            Code: "2",
                            Description: "A pagar",
                            Checked: false
                        }
                    ];
                    this.add(this.debitCreditOption);
                    this.add(this.valueField);
                    this.valueField.numericValue = 0;
                    this.valueField.textBold = true;
                }
                get accountType() {
                    return this.debitCreditOption.selectedCode == 1 ? Components.Selectors.AccountType.Credit : Components.Selectors.AccountType.Debit;
                }
                isEmpty() { return this.valueField.isEmpty(); }
                foco() { this.debitCreditOption.foco(); }
                toControl() { return this; }
                validate() { return null; }
                clear() {
                    this.debitCreditOption.clear();
                    this.valueField.clear();
                }
                get value() {
                    var result = this.valueField.value;
                    if (this.debitCreditOption.value.Valor == "2")
                        result = result.insert("-", 3);
                    return result;
                }
                set value(v) {
                    var isNegative = v[3] == '-';
                    v = v.replace('-', '');
                    this.valueField.value = v;
                    this.debitCreditOption.setSelectedIndex(isNegative ? 1 : 0);
                }
                ;
                build() {
                    super.build();
                    this.feeEditor = this.parent.parent.getEditor("Fees");
                    if (this.feeEditor)
                        this.feeEditor.onChange = () => this.calculateTotal();
                    this.accountAmountEditor = this.parent.parent.getEditor("AccountAmount");
                    if (this.accountAmountEditor)
                        this.accountAmountEditor.onChange = () => this.calculateTotal();
                    this.discountAmountEditor = this.parent.parent.getEditor("Discount");
                    if (this.discountAmountEditor)
                        this.discountAmountEditor.onChange = () => this.calculateTotal();
                    var paymentStatus = this.parent.parent.getEditor("PaymentStatus");
                    if (paymentStatus)
                        paymentStatus.parent.parent.visible = false;
                    this.valueField.onChange = () => this.totalChanged();
                    this.debitCreditOption.onChange.subscribe(() => {
                        if (paymentStatus && this.debitCreditOption.value.Valor == 2)
                            paymentStatus.parent.parent.visible = true;
                        this.onModeChanged.invoke();
                        this.valueField.foco();
                    });
                }
                calculateTotal() {
                    if (this.accountAmountEditor)
                        this.valueField.numericValue = this.accountAmountEditor.numericValue;
                    if (this.feeEditor)
                        this.valueField.numericValue += this.feeEditor.numericValue;
                    if (this.discountAmountEditor)
                        this.valueField.numericValue -= this.discountAmountEditor.numericValue;
                }
                totalChanged() {
                    if (this.accountAmountEditor)
                        this.accountAmountEditor.numericValue = this.valueField.numericValue;
                    if (this.feeEditor)
                        this.accountAmountEditor.numericValue -= this.feeEditor.numericValue;
                    if (this.discountAmountEditor)
                        this.valueField.numericValue -= this.discountAmountEditor.numericValue;
                }
            }
            Components.DebitCreditEditor = DebitCreditEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Questions;
            (function (Questions) {
                class MultipleChoiceQuestionEditor extends Components.DataView {
                    constructor() {
                        super();
                        this.showSearchBox = false;
                        this.fixedRows = false;
                        this.readonly = false;
                        this.showChecks = false;
                        this.availableColumns.add({
                            Title: "Correta",
                            DataType: "SBoolean",
                            ShowTitle: true,
                            EditorModel: {
                                AsociativePropertyName: null,
                                Capitalization: Sol.CapitalizationMode.None,
                                CollectionItemTitle: null,
                                DataType: "SBoolean",
                                DataTypeFullName: "Scussel.DataTypes.SBoolean, Scussel.DataTypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                Decimals: 0,
                                DefaultValue: null,
                                IsRelation: false,
                                MaxLength: null,
                                Options: null,
                                PropertyName: "AnswerTextCorrect",
                                ReadOnly: false,
                                Required: true,
                                SelectorType: Sol.SelectorType.None,
                                Structure: null,
                                StructureHasLargeFields: false,
                                Title: "Correta",
                                Visibility: Sol.FieldVisibility.Always
                            },
                            Visible: true,
                            Sortable: false,
                            PropertyName: "AnswerTextCorrect"
                        });
                        this.availableColumns.add({
                            Title: "Texto da Resposta",
                            DataType: "SText",
                            ShowTitle: true,
                            EditorModel: {
                                AsociativePropertyName: null,
                                Capitalization: Sol.CapitalizationMode.None,
                                CollectionItemTitle: null,
                                DataType: "SText",
                                DataTypeFullName: "SolMotor.DataTypes.texto, SolMotor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                Decimals: 0,
                                DefaultValue: null,
                                IsRelation: false,
                                MaxLength: 1024,
                                Options: null,
                                PropertyName: "AnswerText",
                                ReadOnly: false,
                                Required: true,
                                SelectorType: Sol.SelectorType.None,
                                Structure: null,
                                StructureHasLargeFields: false,
                                Title: "Texto da Resposta",
                                Visibility: Sol.FieldVisibility.Always
                            },
                            Visible: true,
                            Sortable: false,
                            PropertyName: "AnswerText"
                        });
                    }
                    getValor() {
                        var autoIndex = 1;
                        this.rows.forEach(row => row.code = autoIndex++);
                        return JSON.stringify(super.getValor());
                    }
                    setValor(v) {
                        if (!v)
                            return;
                        super.setValor(JSON.parse(v));
                    }
                }
                Questions.MultipleChoiceQuestionEditor = MultipleChoiceQuestionEditor;
            })(Questions = Components.Questions || (Components.Questions = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ScheduleWidget extends Sol.Control {
                constructor() {
                    super();
                    Web.System.exec("9sw4x1Dy", "GetScheduleModel", {}, model => {
                        let schedule = new Components.Schedule(model);
                        this.add(schedule);
                        schedule.refresh();
                    });
                }
            }
            Components.ScheduleWidget = ScheduleWidget;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CompactScheduleWidget extends Sol.Control {
                constructor() {
                    super();
                    this.view = new Components.DayView();
                    this.currentView = Components.ScheduleView.Month;
                    this.css.addMany(["sol_compact_schedule", "sol_dashboard_box", "sol_schedule"]);
                    let refreshButton = new Sol.Button();
                    refreshButton.type = Sol.ButtonType.Custom;
                    refreshButton.imageCode = "&#xf021;";
                    refreshButton.css.add("sol_compact_schedule_refresh");
                    refreshButton.onClick = () => this.refresh();
                    this.add(refreshButton);
                    this.addCtr(Sol.Environment.resources.schedule, "sol_dashboard_separator");
                    this.addCtr(Sol.Environment.resources.next_events, null);
                    this.view.showDate = false;
                    this.add(this.view);
                    let openScheduleButton = new Sol.Button();
                    openScheduleButton.text = "Ver a agenda completa";
                    openScheduleButton.onClick = () => Web.System.screens.openScreen("Solarium.Schedule.ScheduleScreen", Components.Schedule.scheduleClass);
                    this.add(openScheduleButton);
                    this.refresh();
                }
                notifyChanges() { }
                refresh() {
                    Web.System.exec("9sw4x1Dy", "GetNextEvents", {}, model => this.view.load(this, model));
                }
            }
            Components.CompactScheduleWidget = CompactScheduleWidget;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PlaceSchedule extends Components.Schedule {
                constructor(model) {
                    super(model);
                    this.loginSelector.visible = false;
                    this.allowCreateEvent = false;
                    this.showDoneButton.visible = false;
                }
                updateSchedule(baseDate) {
                    let data = {
                        PlaceID: this.placeID,
                        BaseDate: baseDate,
                        View: this.currentView,
                        WeekViewMode: this.weekViewMode
                    };
                    Web.System.exec("79k8jhkh", "GetPlaceSchedule", data, e => this.loadSchedule(e));
                }
            }
            Components.PlaceSchedule = PlaceSchedule;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PlaceScheduleWidget extends Sol.Control {
                constructor() {
                    super();
                    Web.System.exec("79k8jhkh", "GetServicePlaces", {}, model => Sol.List.from(model).forEach(pl => {
                        let schedule = new Components.PlaceSchedule({
                            DefaultView: Components.ScheduleView.Week,
                            MonthViewStartDate: Components.MonthViewStartDateOption.CurrentDate,
                            WeekViewOption: Components.WeekViewDisplayMode.Grid,
                            ViewReportScreen: false
                        });
                        schedule.placeID = pl.ID;
                        schedule.scheduleTitle = pl.Name;
                        this.add(schedule);
                        schedule.refresh();
                    }));
                }
            }
            Components.PlaceScheduleWidget = PlaceScheduleWidget;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class DynamicDetailsEditor extends Sol.Control {
                constructor() {
                    super();
                    this._readonly = false;
                    this.details = new Web.Screens.DetailsScreen();
                    this.emptyControl = new Sol.Control();
                    this.css.addMany(["sol_detalles_complex", "sol_dynamic_details"]);
                    this.emptyControl.text = "Esta meta não possui nenhum filtro disponível.";
                    this.emptyControl.css.add("sol_dynamic_details_empty");
                    this.add(this.emptyControl);
                    this.createNewDetailsControl();
                }
                get readonly() { return this._readonly; }
                set readonly(v) {
                    this._readonly = v;
                    this.details.editors.forEach(f => f.readonly = v);
                }
                get value() { return JSON.stringify(this.details.values); }
                set value(v) {
                    if (v)
                        this.details.loadData(JSON.parse(v));
                }
                clear() { }
                foco() { }
                isEmpty() { return this.details.editors.all(c => c.isEmpty()); }
                setStructure(structure) {
                    this.controls.remove(this.details);
                    this.createNewDetailsControl(structure);
                }
                toControl() { return this; }
                validate() { return null; }
                build() {
                    super.build();
                    this.details.model = this.model;
                }
                createNewDetailsControl(structure = null) {
                    if (!structure || structure.length == 0) {
                        this.emptyControl.visible = true;
                        return;
                    }
                    this.emptyControl.visible = false;
                    var details = new Web.Screens.DetailsScreen();
                    details.showTitle = false;
                    details.myForm.footer.visible = false;
                    details.disableMinimizedControls = true;
                    details.model = {
                        Structure: structure || []
                    };
                    this.details = details;
                    this.add(details);
                }
            }
            Components.DynamicDetailsEditor = DynamicDetailsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class EntitySelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.className = "Solarium.Entidad, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.resultsOrder = "Nombre";
                        this.filterProperty = "GeneralFilter";
                        this.isComplex = false;
                        this.properties = ["ID", this.displayProperty, "NúmeroDocumento"];
                        this.onInstantiateItem = (i, d) => this.instantiateItem(i, d);
                        this.estructura = [
                            {
                                Capitalization: Sol.CapitalizationMode.None,
                                DataType: "SText",
                                DataTypeFullName: "Scussel.DataTypes.SText, Scussel.DataTypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                FormPosition: Web.FormPosition.form,
                                HideIfEmpty: false,
                                MaxLength: 85,
                                PropertyName: "Nombre",
                                ReadOnly: false,
                                ReadOnlyAtEdition: false,
                                Required: true,
                                RequiredAtEdition: true,
                                Title: "Nome",
                                Visibility: Sol.FieldVisibility.Always
                            },
                            {
                                Capitalization: Sol.CapitalizationMode.Lowercase,
                                DataType: "SEmail",
                                DataTypeFullName: "Scussel.DataTypes.SEmail, Scussel.DataTypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                FormPosition: Web.FormPosition.form,
                                HideIfEmpty: false,
                                LargeDescription: null,
                                MaxLength: 255,
                                PropertyName: "Email",
                                ReadOnly: false,
                                ReadOnlyAtEdition: false,
                                Required: false,
                                RequiredAtEdition: false,
                                Title: "E-mail",
                                Visibility: Sol.FieldVisibility.Always
                            },
                            {
                                AsociativePropertyName: "Entidad",
                                CollectionItemTitle: null,
                                DataType: "Teléfono",
                                DataTypeFullName: "Solarium.Teléfono, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                FormPosition: Web.FormPosition.form,
                                HideIfEmpty: false,
                                PropertyName: "Teléfonos",
                                ReadOnly: false,
                                ReadOnlyAtEdition: false,
                                Required: false,
                                RequiredAtEdition: false,
                                Title: "Telefones",
                                Visibility: Sol.FieldVisibility.Always
                            },
                            {
                                Capitalization: Sol.CapitalizationMode.None,
                                DataType: "SText",
                                DataTypeFullName: "Scussel.DataTypes.SText, Scussel.DataTypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                FormPosition: Web.FormPosition.form,
                                HideIfEmpty: false,
                                MaxLength: 20,
                                PropertyName: "NúmeroDocumento",
                                ReadOnly: false,
                                ReadOnlyAtEdition: false,
                                Required: false,
                                RequiredAtEdition: false,
                                Title: "CPF",
                                Visibility: Sol.FieldVisibility.Always
                            },
                            {
                                Configuration: { ShowNumber: true, ShowComplement: true, ShowReferences: false, ShowMap: false },
                                DataType: "Dirección",
                                DataTypeFullName: "Solarium.Geo.Dirección, Solarium.Geo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                FormPosition: Web.FormPosition.form,
                                HideIfEmpty: false,
                                IsRelation: false,
                                PropertyName: "Dirección",
                                ReadOnly: false,
                                ReadOnlyAtEdition: false,
                                Required: false,
                                RequiredAtEdition: false,
                                Title: "Endereço",
                                Visibility: Sol.FieldVisibility.Always
                            }
                        ];
                    }
                    getFilters() {
                        var filters = super.getFilters();
                        filters.add({ PropertyName: "EntityFilter", FilterValue: true, FilterType: null });
                        return filters;
                    }
                    instantiateItem(item, data) {
                        const name = data.that(cmp => cmp.Campo == this.displayProperty).Valor;
                        const nameLabel = new Sol.Control("strong");
                        nameLabel.text = name;
                        item.add(nameLabel);
                        item.text = "";
                        item.displayText = name;
                        const taxId = data.that(cmp => cmp.Campo == "NúmeroDocumento").Valor;
                        const taxIdLabel = new Sol.Control("span");
                        taxIdLabel.css.add("customer_selector_taxid");
                        taxIdLabel.text = taxId;
                        item.add(taxIdLabel);
                    }
                }
                Selectors.EntitySelector = EntitySelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("Entidad", model => {
    const entitySelector = new Sol.Web.Components.Selectors.EntitySelector();
    entitySelector.className = model.DataTypeFullName;
    entitySelector.etiqueta = model.Title;
    entitySelector.miInfo = model;
    return entitySelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class BankInfoEntityDisplay extends Components.BankInfoDisplay {
                build() {
                    this.visible = false;
                    super.build();
                    this.entitySelector = this.container.getEditor("Entity");
                    this.entitySelector.onValueModified.subscribe(() => this.refresh());
                    this.entitySelector.onValueSet = () => this.refresh();
                    this.amountField = this.container.getEditor("Amount");
                    this.amountField.onModeChanged.subscribe(() => this.refresh());
                }
                refresh() {
                    this.visible = false;
                    let entityId = this.entitySelector.selectedCode;
                    if (!entityId || this.amountField.accountType == Components.Selectors.AccountType.Credit)
                        return;
                    let modeCombo = this.container.getEditor("PaymentMode");
                    Web.System.exec("7djdsplq", "GetEntityBankInfo", { entityID: entityId }, e => this.updateDisplay(e, parseInt(modeCombo.selectedCode)));
                }
            }
            Components.BankInfoEntityDisplay = BankInfoEntityDisplay;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("BankInfoEntityDisplay", () => new Sol.Web.Components.BankInfoEntityDisplay());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CalcInstallmentsButton extends Sol.Button {
                constructor() {
                    super();
                    this.imageCode = '&#xf073;';
                    this.tip = "Recalcular vencimentos";
                    this.css.add("sol_calc_installments_button");
                    this.onClick = () => this.calculate();
                }
                toControl() { return this; }
                calculate() {
                    if (this.myEditor.billingDateEditor.isEmpty()) {
                        var i = 1;
                        var days = 0;
                        this.installmentsEditor.rows.forEach(row => {
                            days = i++ * this.myEditor.defaultInstallmentDays;
                            row.getEditor("Days").numericValue = days;
                            row.getEditor("DueDate").value = new Date().addDays(days).formatear();
                        });
                    }
                }
                clear() { }
                foco() { }
                isEmpty() { return true; }
                validate() { return null; }
            }
            Components.CalcInstallmentsButton = CalcInstallmentsButton;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class FinancialScreenLink extends Sol.Button {
                constructor() {
                    super();
                    this.useWrapper = false;
                    this.type = Sol.ButtonType.Link;
                    this.text = "Ver no controle financeiro";
                    this.imageCode = "&#xf155;";
                    this.onClick = () => this.openScreen();
                }
                clear() { }
                foco() { }
                isEmpty() { return true; }
                toControl() { return this; }
                validate() { return null; }
                openScreen() {
                    Web.System.screens.openScreen("Registro", "Solarium.Financial.FinancialRecord, Solarium.Financial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null, null, null, screen => {
                        const currentDetails = Web.System.screens.currentDetails;
                        const financialScreen = screen;
                        const screenModel = financialScreen.model;
                        const filters = Sol.List.from(screenModel.DataView.Filters);
                        if (!currentDetails.code)
                            return;
                        const codeFilter = filters.that(f => f.PropertyName == "DocumentNumber");
                        if (codeFilter)
                            codeFilter.DefaultValue = currentDetails.code;
                        const companyFilter = filters.that(f => f.PropertyName == "Empresa");
                        if (companyFilter)
                            companyFilter.DefaultValue = null;
                    });
                }
            }
            Components.FinancialScreenLink = FinancialScreenLink;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PurchasePaymentEditor extends Components.PaymentEditor {
                constructor() {
                    super();
                    this.billingDateEnabled = true;
                    this.blockWhenBillingDateIsSet = false;
                }
                configureFields() {
                    super.configureFields();
                    this.installmentsTable.availableColumns.that(cl => cl.PropertyName == "Days").onEditorChange = (row, editor) => this.updateDueDateField(row, editor);
                    this.installmentsTable.availableColumns.that(cl => cl.PropertyName == "DueDate").onEditorChange = (row, editor) => this.updateDaysField(row, editor);
                }
                configureBillingDateField() {
                    super.configureBillingDateField();
                    const billingDateEditor = this.details.getEditor("BillingDate");
                    billingDateEditor.onChange = () => this.calculateDueDates();
                }
                setValue(value) {
                    super.setValue(value);
                    this.readonly = false;
                }
                calculateDueDates() {
                    this.installmentsTable.setColumnReadonly("DueDate", !this.billingDateEditor.isEmpty());
                    this.installmentsTable.rows.forEach(row => {
                        const daysField = row.getEditor("Days");
                        row.getEditor("DueDate").dateValue = this.billingDateEditor.isEmpty() ? null :
                            this.billingDateEditor.dateValue.addDays(daysField.numericValue);
                    });
                }
                updateDueDateField(row, editor) {
                    if (this.billingDateEditor.isEmpty())
                        return;
                    row.getEditor("DueDate").dateValue = this.billingDateEditor.dateValue.addDays(editor.numericValue);
                }
                updateDaysField(row, editor) {
                    if (this.billingDateEditor.isEmpty())
                        return;
                    row.getEditor("Days").numericValue = editor.isEmpty() ? 0 :
                        (editor.dateValue.getTime() - this.billingDateEditor.dateValue.getTime()) / (1000 * 3600 * 24);
                }
            }
            Components.PurchasePaymentEditor = PurchasePaymentEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RelatedCustomerEditor extends Sol.Control {
                constructor() {
                    super();
                    this.isComplex = true;
                    this.list = new Components.ListView();
                    this.css.add("sol_products_editor");
                    this.initializeAddButton();
                    this.initializeCustomerList();
                }
                toControl() { return this; }
                foco() { }
                validate() { return null; }
                get value() { return this.list.values; }
                set value(v) { this.list.values = v; }
                addCustomer(code) {
                    if (this.list.containsCode(code))
                        return;
                    this.list.filters = [{
                            PropertyName: "ID",
                            FilterValue: code,
                            FilterType: "SInteger"
                        }];
                    this.list.search();
                }
                initializeAddButton() {
                    var selector = new Components.Selectors.Selector();
                    selector.allowCreateNew = false;
                    selector.allowEdit = false;
                    selector.displayProperty = "EntidadRelacionada$Nombre";
                    selector.propertyName = "EntidadRelacionada$Nombre";
                    selector.className = "Solarium.Commercial.Cliente, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.add(selector);
                    var addButton = new Sol.Button();
                    addButton.text = Sol.Environment.resources.anadir_item;
                    addButton.imageCode = '&#xf007;';
                    addButton.onClick = () => {
                        if (!selector.value)
                            return;
                        this.addCustomer(selector.selectedCode);
                        selector.clear();
                        selector.foco();
                    };
                    this.add(addButton);
                }
                initializeCustomerList() {
                    this.list.itemPropertyName = "Cliente";
                    this.list.className = "Solarium.Commercial.Cliente, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.list.orderByProperty = "EntidadRelacionada$Nombre";
                    this.list.onInstantiateItem = i => this.instantiateItem(i);
                    this.list.configuration = Sol.List.from([]);
                    this.add(this.list);
                }
                instantiateItem(item) {
                    var deleteCommand = item.getDisplay("DeleteCommand");
                    deleteCommand.onClick = () => this.controls.remove(item);
                    var openCommand = item.getDisplay("OpenCommand");
                    openCommand.onClick = () => this.openCustomer(item.code);
                }
                openCustomer(code) {
                    var details = new Web.Screens.DetailsScreen();
                    var currentScreen = Web.System.screens.currentScreen;
                    details.model = currentScreen.model;
                    details.code = code;
                    details.myScreen = currentScreen;
                    details.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    details.entityName = details.model.Nombre;
                    Web.System.screens.addScreen(details);
                    details.screenCaption = Sol.Environment.resources.editar;
                    Web.System.screens.showScreen(details);
                    details.foco();
                    details.load(code, true);
                }
                isEmpty() { return false; }
                clear() {
                    throw new Error("Method not implemented.");
                }
            }
            Components.RelatedCustomerEditor = RelatedCustomerEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class HtmlViewer extends Sol.Control {
                constructor() {
                    super();
                    this.toolBar = new Sol.Control();
                    this.iframe = new Sol.Control("iframe");
                    this.css.add("sol_html_viewer");
                    this.toolBar.css.add("sol_html_viewer_bar");
                    this.add(this.toolBar);
                    this.add(this.iframe);
                }
                setContent(html) {
                    this.iframe.html.srcdoc = html;
                }
                build() {
                    super.build();
                    const titleControl = new Sol.Control("span");
                    titleControl.text = this.title;
                    this.toolBar.add(titleControl);
                }
            }
            Components.HtmlViewer = HtmlViewer;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class CustomerHistoryScreen extends Screens.HistoryScreenBase {
                constructor() {
                    super(...arguments);
                    this.manager = "";
                    this.methodName = "";
                }
                get myModel() { return this.model; }
                build() {
                    this.screenCaption = this.myModel.Title;
                    if (this.model.Code)
                        this.code = this.model.Code;
                    super.build();
                    this.interval.visible = false;
                    this.searchButton.visible = false;
                    this.grid.onRowClick = code => Web.System.edit(this.contextClass, code);
                }
                configureColumns() {
                    this.grid.columns = this.customHistoryColumns || Sol.List.from([
                        {
                            Title: Sol.Environment.resources.date,
                            DataType: "SDate",
                            PropertyName: "Creación",
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: "Status",
                            DataType: "SText",
                            Alignment: Sol.Alignment.Center,
                            PropertyName: "Status",
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: Sol.Environment.resources.description,
                            DataType: "SText",
                            PropertyName: "ObjectTitle",
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: "Entrega",
                            DataType: "SText",
                            PropertyName: "DeliveryDetails$DeliveryDescription",
                            ShowTitle: true,
                            Visible: this.myModel.ShowDeliveryColumn
                        },
                        {
                            Title: "Pagamento",
                            DataType: "SText",
                            PropertyName: "Payment$PaymentDescription",
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: Sol.Environment.resources.total,
                            DataType: "SMoney",
                            PropertyName: "Total",
                            ShowTitle: true,
                            Alignment: Sol.Alignment.Right,
                            Visible: this.model.ShowTotal
                        }
                    ]);
                    this.grid.columns = this.grid.columns.where(cl => cl.Visible);
                }
                search() {
                    const data = {
                        className: this.contextClass,
                        currentPage: this.currentPage,
                        rowCount: this.gridRowCount,
                        filters: [{ FilterType: "SInteger", FilterValue: this.code, PropertyName: "Destinatario" }],
                        sortProperty: "Creación",
                        sortOrder: Web.Ordering.descending,
                        properties: this.grid.columns.select(cl => cl.Visible && cl.PropertyName).toArray(),
                        pageInfo: true
                    };
                    Web.System.exec("i3n48smak", "Search", data, e => {
                        const data = Sol.List.from(e.Data);
                        var i = 0;
                        data.forEach(row => {
                            const gridRow = this.grid.addRow(row);
                            gridRow.code = e.Codes[i];
                            i++;
                        });
                        this.emptyMessage.visible = this.currentPage == 1 && !data.hasItems();
                        this.moreResultsButton.enabled = this.currentPage < e.PageCount;
                    });
                }
                getSearchData() { return null; }
            }
            Screens.CustomerHistoryScreen = CustomerHistoryScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Customers;
            (function (Customers) {
                class CustomerSelector extends Web.Components.Selectors.RelationBaseSelector {
                    constructor() {
                        super();
                        this.historyButton = new Sol.Button();
                        this.creditField = new Sol.CurrencyField();
                        this.className = "Solarium.Commercial.Cliente, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.forceSubtype = true;
                        this.onInstantiateItem = (i, d) => this.instantiateItem(i, d);
                        this.filterProperty = "GeneralFilter";
                        this.historyButton.enabled = false;
                        this.properties = ["ID",
                            this.displayProperty,
                            "EntidadRelacionada$NúmeroDocumento",
                            "EntidadRelacionada$Email",
                            "EntidadRelacionada$Email2",
                            "EntidadRelacionada$PhoneList",
                            "ConsultantName",
                            "Consultant",
                            "IsBlockedToMe",
                            "EntidadRelacionada$Dirección$City",
                            "EntidadRelacionada$Dirección$Estado$Sigla",
                            "Credit",
                            "CreditData"];
                    }
                    get customerConfig() { return this.configuration || {}; }
                    get screen() { return this.container.toControl().parent; }
                    addExtraButtons() {
                        if (this.hideHistoryButton)
                            return;
                        this.historyButton.text = Sol.Environment.resources.historyLabel;
                        this.historyButton.imageCode = "&#xf1da;";
                        this.historyButton.onClick = () => Web.System.screens.openScreen("Solarium.Commercial.Screens.CustomerHistoryScreen", this.contextClass, null, null, null, screen => {
                            const historyScreen = screen;
                            historyScreen.contextClass = this.contextClass;
                            if (historyScreen.myModel.CustomColumns)
                                historyScreen.customHistoryColumns = Sol.List.from(historyScreen.myModel.CustomColumns);
                            if (this.customHistoryColumns)
                                historyScreen.customHistoryColumns = Sol.List.from(this.customHistoryColumns);
                        }, this.selectedCode);
                        this.add(this.historyButton);
                    }
                    build() {
                        super.build();
                        this.initializeCreditField();
                        this.className = this.className || "Solarium.Commercial.Cliente, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    }
                    detailsSaved(screen) {
                        super.detailsSaved(screen);
                        this.updateSaleCredit();
                        this.updateDelivery(this.selectedCode);
                    }
                    enableButtons(value) {
                        super.enableButtons(value);
                        this.historyButton.enabled = value;
                    }
                    instantiateDetailsScreen() { return new Web.Screens.OptionalDetails(); }
                    loadExtraFields(model) {
                        super.loadExtraFields(model);
                        this.creditField.value = !model.Credit ? "" : model.Credit.toString();
                    }
                    itemClick(item) {
                        if (!item)
                            return;
                        super.itemClick(item);
                        this.followups.code = item.code;
                        const extras = Sol.List.from(item.extraData);
                        this.creditField.value = extras.that(dt => dt.Campo == "CreditData").Valor;
                        this.updateSaleCredit();
                        this.updateDelivery(item.code);
                    }
                    initializeCreditField() {
                        if (!this.customerConfig.ShowCreditField)
                            return;
                        const creditWrapper = new Sol.FieldWrapper();
                        const creditLabel = new Sol.Label();
                        creditLabel.text = Sol.Environment.resources.credit;
                        creditWrapper.add(creditLabel);
                        this.creditField.css.add("sol_selector_extra_field");
                        this.creditField.readonly = true;
                        creditWrapper.add(this.creditField);
                        this.extraFieldsArea.add(creditWrapper);
                    }
                    instantiateItem(item, data) {
                        const name = data.that(cmp => cmp.Campo == "EntidadRelacionada$Nombre").Valor;
                        const nameLabel = new Sol.Control("strong");
                        nameLabel.text = name;
                        item.add(nameLabel);
                        item.text = "";
                        item.displayText = name;
                        const taxId = data.that(cmp => cmp.Campo == "EntidadRelacionada$NúmeroDocumento").Valor;
                        const taxIdLabel = new Sol.Control("span");
                        taxIdLabel.css.add("customer_selector_taxid");
                        taxIdLabel.text = taxId;
                        item.add(taxIdLabel);
                        const consultant = data.that(cmp => cmp.Campo == "ConsultantName").Valor;
                        if (consultant) {
                            item.add(new Sol.LineBreak());
                            const consultantLabel = new Sol.Control("span");
                            consultantLabel.css.add("customer_selector_consultant");
                            consultantLabel.text = Sol.Environment.resources.attended_by + consultant;
                            item.add(consultantLabel);
                        }
                        const city = data.that(cmp => cmp.Campo == "EntidadRelacionada$Dirección$City").Valor;
                        const state = data.that(cmp => cmp.Campo == "EntidadRelacionada$Dirección$Estado$Sigla").Valor;
                        const cityLabel = new Sol.Control("span");
                        cityLabel.css.add("customer_selector_city");
                        cityLabel.text = city;
                        if (city && state)
                            cityLabel.text += "-" + state;
                        item.add(cityLabel);
                        item.blocked = data.that(cmp => cmp.Campo == "IsBlockedToMe").Valor;
                    }
                    updateSaleCredit() {
                        if (!this.container || !this.screen.getEditor)
                            return;
                        const paymentEditor = this.screen.getEditor("Payment");
                        if (!paymentEditor || paymentEditor.isBilled)
                            return;
                        const creditEditor = this.screen.getEditor("Credit");
                        if (!creditEditor)
                            return;
                        creditEditor.value = this.creditField.value;
                        creditEditor.onChange();
                    }
                    updateDelivery(code) {
                        if (!this.container || !this.screen.getEditor)
                            return;
                        const deliveryEditor = this.screen.getEditor("DeliveryDetails");
                        if (!deliveryEditor)
                            return;
                        deliveryEditor.updateAddress(code);
                    }
                }
                Customers.CustomerSelector = CustomerSelector;
            })(Customers = Commercial.Customers || (Commercial.Customers = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("Cliente", (model, cls) => {
    const customerSelector = new Sol.Web.Commercial.Customers.CustomerSelector();
    customerSelector.allowCreateNew = true;
    customerSelector.allowEdit = true;
    customerSelector.configuration = model.Configuration;
    customerSelector.estructura = model.Structure;
    customerSelector.etiqueta = model.Title;
    customerSelector.miInfo = model;
    customerSelector.contextClass = cls;
    return customerSelector;
});
Sol.Web.Editors.registerFilter("Cliente", model => {
    const customerSelector = new Sol.Web.Commercial.Customers.CustomerSelector();
    customerSelector.className = model.ClassName;
    customerSelector.etiqueta = model.Caption;
    customerSelector.allowEdit = false;
    customerSelector.hideHistoryButton = true;
    customerSelector.hideFollowUpButton = true;
    if (model.Settings)
        model.Settings["allowEdit"] = undefined;
    return customerSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Devolutions;
            (function (Devolutions) {
                class DevolutionEditor extends Web.Components.DataView {
                    constructor() {
                        super();
                        this.managerCode = "79ktyjh";
                        this.manegerMethod = "GetDevolutionInfo";
                        this.entityProperty = "Emisor";
                        this.css.add("sol_devolution_editor");
                        this.showSearchBox = false;
                        this.fixedRows = false;
                        this.showChecks = false;
                        this.isComplex = false;
                        this.readonly = true;
                    }
                    build() {
                        super.build();
                        this.initializeAddButton();
                    }
                    showError() { alert(Sol.Environment.resources.devolution_customer_error); }
                    initializeAddButton() {
                        this.onAddingItem = () => {
                            const selectorScreen = new Web.Screens.ProductSelectorScreen();
                            selectorScreen.showQuotationTools = false;
                            selectorScreen.showCost = false;
                            Web.System.screens.addScreen(selectorScreen);
                            Web.System.screens.showScreen(selectorScreen);
                            selectorScreen.focus();
                            selectorScreen.onProductSelected = prods => {
                                this.addProduct(prods.first().code);
                                Web.System.screens.closeCurrentScreen();
                            };
                        };
                    }
                    addProduct(productCode) {
                        let entityCode = this.getEntityCode();
                        if (!entityCode) {
                            this.showError();
                            return;
                        }
                        Web.System.exec(this.managerCode, this.manegerMethod, { entityCode: entityCode, productCode: productCode }, e => {
                            if (!e.Fail)
                                this.addRow([
                                    { Campo: "Product", Valor: e.Product },
                                    { Campo: "PurchaseDate", Valor: e.PurchaseDate },
                                    { Campo: "Price", Valor: e.PurchaseValue },
                                    { Campo: "Quantity", Valor: e.Quantity },
                                    { Campo: "Total", Valor: e.Total }
                                ]);
                            else
                                alert(e.ErrorMessage);
                        });
                    }
                    getEntityCode() {
                        var selector = this.container.getEditor(this.entityProperty);
                        return selector.selectedCode || 0;
                    }
                }
                Devolutions.DevolutionEditor = DevolutionEditor;
            })(Devolutions = Commercial.Devolutions || (Commercial.Devolutions = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("DevolutionEditor", model => {
    const devolutionEditor = new Sol.Web.Commercial.Devolutions.DevolutionEditor();
    devolutionEditor.readonly = model.ReadOnly;
    Sol.Web.Editors.fillDataViewStructure(devolutionEditor, model.Structure);
    return devolutionEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Devolutions;
            (function (Devolutions) {
                class PurchaseReturnEditor extends Devolutions.DevolutionEditor {
                    constructor() {
                        super();
                        this.managerCode = "o320942d";
                        this.manegerMethod = "GetPurchaseInfo";
                        this.entityProperty = "Destinatario";
                    }
                    showError() {
                        alert(Sol.Environment.resources.devolution_supplier_error);
                    }
                }
                Devolutions.PurchaseReturnEditor = PurchaseReturnEditor;
            })(Devolutions = Commercial.Devolutions || (Commercial.Devolutions = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PurchaseReturnEditor", model => {
    const devolutionEditor = new Sol.Web.Commercial.Devolutions.PurchaseReturnEditor();
    devolutionEditor.readonly = model.ReadOnly;
    Sol.Web.Editors.fillDataViewStructure(devolutionEditor, model.Structure);
    return devolutionEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class AudioPlayer extends Sol.Control {
                constructor() {
                    super("audio");
                    this.audioType = "mpeg";
                    this.readonly = true;
                    this.atributos.agregar("controls");
                }
                get value() { return this._value; }
                set value(model) {
                    this._value = model;
                    this.clear();
                    if (!model || !model.ID)
                        return;
                    let audio = new Sol.Control("source");
                    audio.atributos.agregar("src", model.ExternalLink ? model.ExternalLink : Sol.Environment.filePath + model.Identificador);
                    audio.atributos.agregar("type", "audio/" + this.audioType);
                    this.add(audio);
                }
                clear() { this.controls.empty(); }
                foco() { }
                isEmpty() { return !this._value || !this._value.ID; }
                toControl() { return this; }
                validate() { return null; }
            }
            Components.AudioPlayer = AudioPlayer;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("AudioPlayer", () => new Sol.Web.Components.AudioPlayer());
var Sol;
(function (Sol) {
    var WebComponents;
    (function (WebComponents) {
        class VideoPlayer extends Sol.Control {
            constructor() {
                super("video");
                this.screenWidth = 320;
                this.screenHeight = 240;
                this.videoType = "mp4";
            }
            build() {
                super.build();
                this.atributos.agregar("width", this.screenWidth.toString());
                this.atributos.agregar("height", this.screenHeight.toString());
                this.atributos.agregar("controls");
                var sourceControl = new Sol.Control("source");
                sourceControl.atributos.agregar("src", this.source);
                sourceControl.atributos.agregar("type", "video/" + this.videoType);
                this.add(sourceControl);
            }
        }
        WebComponents.VideoPlayer = VideoPlayer;
    })(WebComponents = Sol.WebComponents || (Sol.WebComponents = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Equipments;
            (function (Equipments) {
                class EquipmentsEditor extends Sol.Control {
                    constructor() {
                        super();
                        this.list = new Web.Components.ListView();
                        this.isComplex = false;
                        this.css.add("sol_products_editor");
                    }
                    get cost() { return 0; }
                    get isSummable() { return true; }
                    get margin() { return this.total; }
                    get total() {
                        return this.list.items.sum(i => i.getEditor("Total").numericValue);
                    }
                    get value() { return this.list.values; }
                    set value(v) { this.list.values = v; }
                    build() {
                        super.build();
                        this.initializeList();
                        this.initializeAddButton();
                        this.initializeProductsButton();
                    }
                    foco() { }
                    toControl() { return this; }
                    validate() { return null; }
                    addProduct(code) {
                        var data = {
                            className: this.list.className,
                            currentPage: 1,
                            rowCount: 1,
                            filters: [{
                                    PropertyName: "ID",
                                    FilterValue: code,
                                    FilterType: "SInteger"
                                }],
                            sortProperty: "ID",
                            sortOrder: Web.Ordering.ascending,
                            properties: ["ID", "Nombre", "EffectiveCost", "EffectivePrice", "CurrentStock", "MainPicture"],
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", data, model => {
                            if (!model.Data || model.Data.length == 0)
                                return;
                            var product = Sol.List.from(model.Data[0]);
                            var item = [
                                { Campo: "Product", Valor: code },
                                { Campo: "Product$Nombre", Valor: product.that(d => d.Campo == "Nombre").Valor },
                                { Campo: "Product$MainPicture", Valor: product.that(d => d.Campo == "MainPicture").Valor }
                            ];
                            var listItem = this.list.addItemFromData(item, 0);
                            var componentsSearch = {
                                className: "Solarium.Commercial.ProductComponent, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                currentPage: 1,
                                rowCount: 100,
                                filters: [{
                                        PropertyName: "Product",
                                        FilterValue: code,
                                        FilterType: "SInteger"
                                    }],
                                sortProperty: "ID",
                                sortOrder: Web.Ordering.ascending,
                                properties: ["ID", "Component", "Quantity"],
                                pageInfo: false
                            };
                            Web.System.exec("i3n48smak", "Search", data, componentsModel => {
                                var table = listItem.getEditor("Components");
                                Sol.List.from(componentsModel.Data).cast().forEach(dataRow => {
                                    var dataCollection = Sol.List.from(dataRow);
                                    var component = dataCollection.that(d => d.Campo == "Component").Valor;
                                    var defaultQuantity = dataCollection.that(d => d.Campo == "Quantity").Valor;
                                    table.addRow([
                                        {
                                            Campo: "ID",
                                            Valor: 0
                                        },
                                        {
                                            Campo: "Component",
                                            Valor: component
                                        },
                                        {
                                            Campo: "Quantity",
                                            Valor: defaultQuantity
                                        }
                                    ]);
                                });
                            }, null);
                        }, null);
                    }
                    initializeAddButton() {
                        const addButton = new Sol.Button();
                        addButton.text = Sol.Environment.resources.anadir_item;
                        addButton.imageCode = '&#xf187;';
                        addButton.onClick = () => {
                            var selectorScreen = new Web.Screens.ProductSelectorScreen();
                            selectorScreen.onlyEquipments = true;
                            Web.System.screens.addScreen(selectorScreen);
                            Web.System.screens.showScreen(selectorScreen);
                            selectorScreen.onProductSelected = products => {
                                this.addProduct(products.first().code);
                                Web.System.screens.closeCurrentScreen();
                            };
                        };
                        this.add(addButton);
                    }
                    initializeProductsButton() {
                        const productClassName = "Solarium.Commercial.Product, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        const productsButton = new Sol.Button();
                        productsButton.text = Sol.Environment.resources.file;
                        productsButton.imageCode = "&#xf187;";
                        productsButton.onClick = () => Web.System.screens.openScreen("Registro", productClassName);
                        this.add(productsButton);
                    }
                    initializeList() {
                        this.list.className = "Solarium.Commercial.Product, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.list.showImage = true;
                        this.list.itemPropertyName = "Product";
                        this.list.onInstantiateItem = i => this.instantiateItem(i);
                        this.list.configuration = Sol.List.from([
                            {
                                loadable: true,
                                property: "Product$MainPicture",
                                position: Web.Components.ListViewFieldPosition.Image
                            },
                            {
                                loadable: false,
                                property: "DeleteCommand",
                                defaultText: Sol.Environment.resources.eliminar,
                                position: Web.Components.ListViewFieldPosition.Right,
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                cssClass: "sol_products_list_remove"
                            },
                            {
                                loadable: true,
                                property: "Product$Nombre",
                                priority: Web.Components.ListViewFieldPriority.High,
                                position: Web.Components.ListViewFieldPosition.Left,
                                defaultText: "Mercadoria não especificada"
                            },
                            {
                                loadable: true,
                                property: "Product",
                                hidden: true
                            },
                            {
                                loadable: true,
                                caption: "Part Number",
                                property: "Product$PartNumber",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                lineBreak: true
                            },
                            {
                                loadable: false,
                                lineBreak: true,
                                property: "Chassis",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: "Chassis",
                                cssClass: "sol_products_chassis",
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SText",
                                    PropertyName: "Chassis",
                                    Title: "Chassis",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    MaxLength: 100,
                                    Width: 400,
                                    ReadOnly: false
                                }
                            },
                            {
                                loadable: false,
                                property: "SLA",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: "SLA",
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SLAType",
                                    DataTypeFullName: "Solarium.Commercial.SLAType, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                    PropertyName: "SLA",
                                    Title: "SLA",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    ReadOnly: false,
                                    SelectorType: Sol.SelectorType.Simple
                                }
                            },
                            {
                                loadable: false,
                                property: "Service",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Left,
                                caption: Sol.Environment.resources.serviceType,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "ServiceType",
                                    DataTypeFullName: "Solarium.Commercial.ServiceType, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                    PropertyName: "Service",
                                    Title: Sol.Environment.resources.serviceType,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    ReadOnly: false,
                                    SelectorType: Sol.SelectorType.Simple
                                }
                            },
                            {
                                loadable: false,
                                property: "Total",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Right,
                                caption: Sol.Environment.resources.total,
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SMoney",
                                    PropertyName: "Total",
                                    Title: Sol.Environment.resources.total,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    Decimals: 2,
                                    ReadOnly: false
                                }
                            },
                            {
                                loadable: false,
                                lineBreak: true,
                                property: "Location",
                                priority: Web.Components.ListViewFieldPriority.Normal,
                                position: Web.Components.ListViewFieldPosition.Block,
                                caption: Sol.Environment.resources.location,
                                cssClass: "sol_products_chassis",
                                editor: {
                                    AllowChangeCurrency: false,
                                    DataType: "SLargeText",
                                    PropertyName: "Location",
                                    Title: Sol.Environment.resources.location,
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnlyAtEdition: false,
                                    MaxLength: 255,
                                    ReadOnly: false
                                }
                            }
                        ]);
                        this.add(this.list);
                    }
                    instantiateItem(item) {
                        var deleteCommand = item.getDisplay("DeleteCommand");
                        deleteCommand.onClick = () => {
                            if (!confirm(Sol.Environment.resources.confirm_delete))
                                return;
                            this.list.controls.remove(item);
                        };
                        var slaCombo = item.getEditor("SLA");
                        slaCombo.refresh();
                        var serviceTypeCombo = item.getEditor("Service");
                        serviceTypeCombo.refresh();
                        var totalField = item.getEditor("Total");
                        totalField.onChange = () => this.onTotalsChanged();
                        item.controls.removeLast(1);
                        var table = new Web.Components.DataView();
                        table.showSearchBox = false;
                        table.readonly = false;
                        table.fixedRows = false;
                        table.showChecks = false;
                        table.propertyName = "Components";
                        table.onAddingItem = e => this.addComponentItem(e);
                        table.availableColumns = Sol.List.from([
                            {
                                Title: Sol.Environment.resources.components,
                                DataType: "SText",
                                ShowTitle: true,
                                EditorModel: {
                                    Title: Sol.Environment.resources.components,
                                    DataType: "Display",
                                    ShowTitle: true,
                                    Visible: true,
                                    Ordenable: false,
                                    PropertyName: "Component",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnly: false,
                                    ReadOnlyAtEdition: false
                                },
                                Alignment: 0,
                                IsCollection: false,
                                Options: null,
                                Sortable: false,
                                PropertyName: "Component",
                                Visible: true,
                                OrderingPropertyName: null,
                                Position: 1
                            },
                            {
                                Title: "Part Number",
                                DataType: "SText",
                                ShowTitle: true,
                                Alignment: 0,
                                IsCollection: false,
                                Options: null,
                                Sortable: false,
                                PropertyName: "PartNumber",
                                Visible: true,
                                OrderingPropertyName: null,
                                Position: 2
                            },
                            {
                                Title: Sol.Environment.resources.product_quantity,
                                DataType: "SInteger",
                                ShowTitle: true,
                                EditorModel: {
                                    Title: Sol.Environment.resources.product_quantity,
                                    DataType: "SInteger",
                                    ShowTitle: true,
                                    Visible: true,
                                    Ordenable: false,
                                    PropertyName: "Quantity",
                                    Required: false,
                                    RequiredAtEdition: false,
                                    ReadOnly: false,
                                    ReadOnlyAtEdition: false
                                },
                                Alignment: 0,
                                IsCollection: false,
                                Options: null,
                                OrderingPropertyName: null,
                                Visible: true,
                                Sortable: false,
                                PropertyName: "Quantity",
                                Position: 3
                            }
                        ]);
                        table.setDefaultColumns();
                        item.editors.add(table);
                        item.add(table);
                        var componentsValue = item.getModelValue("Components");
                        if (componentsValue)
                            table.value = componentsValue;
                    }
                    addComponentItem(table) {
                        var selectorScreen = new Web.Screens.ProductSelectorScreen();
                        Web.System.screens.addScreen(selectorScreen);
                        Web.System.screens.showScreen(selectorScreen);
                        selectorScreen.onProductSelected = prods => {
                            var product = Sol.List.from(prods.first().data);
                            var itemData = [
                                { Campo: "ID", Valor: 0 },
                                { Campo: "Component", Valor: { Campo: product.that(d => d.Campo == "Nombre").Valor, Valor: prods.first().code } },
                                { Campo: "PartNumber", Valor: product.that(d => d.Campo == "PartNumber").Valor },
                                { Campo: "Quantity", Valor: 1 }
                            ];
                            table.addRow(itemData);
                            Web.System.screens.closeCurrentScreen();
                        };
                    }
                    isEmpty() { return false; }
                    clear() { }
                }
                Equipments.EquipmentsEditor = EquipmentsEditor;
            })(Equipments = Commercial.Equipments || (Commercial.Equipments = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("EquipmentsEditor", () => new Sol.Web.Commercial.Equipments.EquipmentsEditor());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RelatedSupplierEditor extends Sol.Control {
                constructor() {
                    super();
                    this.list = new Components.ListView();
                    this.isComplex = true;
                    this.css.add("sol_products_editor");
                    this.initializeList();
                    this.initializeAddButton();
                }
                get value() { return this.list.values; }
                set value(v) { this.list.values = v; }
                foco() { }
                toControl() { return this; }
                validate() { return null; }
                addSupplier(code) {
                    if (this.list.containsCode(code))
                        return;
                    this.list.filters = [{
                            PropertyName: "ID",
                            FilterValue: code,
                            FilterType: "SInteger"
                        }];
                    this.list.search();
                }
                initializeAddButton() {
                    var selector = new Components.Selectors.Selector();
                    selector.allowCreateNew = false;
                    selector.allowEdit = false;
                    selector.displayProperty = "EntidadRelacionada$Nombre";
                    selector.propertyName = "EntidadRelacionada$Nombre";
                    selector.className = "Solarium.Commercial.Supplier, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.add(selector);
                    var addButton = new Sol.Button();
                    addButton.text = Sol.Environment.resources.anadir_item;
                    addButton.imageCode = '&#xf187;';
                    addButton.onClick = () => {
                        if (!selector.value)
                            return;
                        this.addSupplier(selector.selectedCode);
                        selector.clear();
                        selector.foco();
                    };
                    this.add(addButton);
                }
                initializeList() {
                    this.list.itemPropertyName = "Supplier";
                    this.list.className = "Solarium.Commercial.Supplier, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.list.orderByProperty = "EntidadRelacionada$Nombre";
                    this.list.onInstantiateItem = i => this.instantiateItem(i);
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: false,
                            property: "DeleteCommand",
                            defaultText: Sol.Environment.resources.eliminar,
                            position: Components.ListViewFieldPosition.Right,
                            priority: Components.ListViewFieldPriority.Normal,
                            cssClass: "sol_products_list_remove"
                        },
                        {
                            loadable: true,
                            property: "ID",
                            priority: Components.ListViewFieldPriority.High,
                            position: Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "EntidadRelacionada$ShortName",
                            priority: Components.ListViewFieldPriority.High,
                            position: Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "EntidadRelacionada$Nombre",
                            priority: Components.ListViewFieldPriority.Normal,
                            lineBreak: true,
                            position: Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: false,
                            property: "OpenCommand",
                            defaultText: Sol.Environment.resources.view,
                            position: Components.ListViewFieldPosition.Left,
                            priority: Components.ListViewFieldPriority.Normal,
                            cssClass: "sol_related_suppliers_open"
                        }
                    ]);
                    this.add(this.list);
                }
                instantiateItem(item) {
                    var deleteCommand = item.getDisplay("DeleteCommand");
                    deleteCommand.onClick = () => this.controls.remove(item);
                    var openCommand = item.getDisplay("OpenCommand");
                    openCommand.onClick = () => this.openSupplier(item.code);
                }
                openSupplier(code) {
                    var details = new Web.Screens.DetailsScreen();
                    var currentScreen = Web.System.screens.currentScreen;
                    details.model = currentScreen.model;
                    details.code = code;
                    details.myScreen = currentScreen;
                    details.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    details.entityName = details.model.Nombre;
                    Web.System.screens.addScreen(details);
                    details.screenCaption = Sol.Environment.resources.editar;
                    Web.System.screens.showScreen(details);
                    details.foco();
                    details.load(code, true);
                }
                isEmpty() { return false; }
                clear() { throw new Error("Method not implemented."); }
            }
            Components.RelatedSupplierEditor = RelatedSupplierEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class FileHistory extends Sol.Control {
                constructor() {
                    super();
                    this.display = new Sol.DateTimeField();
                    this.historialPopup = new Sol.Control();
                    this.historialList = new Components.ListView();
                    this.isHistorialLoaded = false;
                    this.readonly = true;
                    this.isComplex = false;
                    this.useWrapper = true;
                    var wrapper = new Sol.Control();
                    this.css.add("sol_file_history");
                    wrapper.add(this.display);
                    this.display.readonly = true;
                    var historialButton = new Sol.Button();
                    historialButton.imageCode = '&#xf017;';
                    historialButton.onClick = () => this.showHistorial();
                    wrapper.add(historialButton);
                    this.historialPopup.css.add("sol_popup");
                    this.historialPopup.ancho = 350;
                    this.historialPopup.visible = false;
                    this.historialList.configuration = Sol.List.from([
                        { property: "ChangeDate", priority: Components.ListViewFieldPriority.Normal, position: Components.ListViewFieldPosition.Left, cssClass: "sol_file_history_time" },
                        { property: "LoginName", priority: Components.ListViewFieldPriority.Normal, position: Components.ListViewFieldPosition.Left },
                        { property: "ElapsedTime", priority: Components.ListViewFieldPriority.Descriptive, position: Components.ListViewFieldPosition.Left },
                        { property: "Description", priority: Components.ListViewFieldPriority.Descriptive, position: Components.ListViewFieldPosition.Left, lineBreak: true }
                    ]);
                    this.add(wrapper);
                    this.add(this.historialPopup);
                }
                isEmpty() { return false; }
                validate() { return null; }
                get value() { return this.display.value; }
                set value(v) { this.display.value = v; }
                get defaultValue() { return this.value; }
                set defaultValue(v) { this.value = v; }
                toControl() { return this; }
                foco() { }
                clear() { }
                showHistorial() {
                    this.historialPopup.show();
                    if (this.isHistorialLoaded)
                        return;
                    var data = {
                        credential: Sol.Environment.credential.export(),
                        className: this.container.toControl().parent.model.ClassName,
                        id: this.code
                    };
                    Web.System.exec("i3n48smak", "FileHistory", data, model => {
                        var header = new Sol.Control("li");
                        header.css.add("sol_file_history_header");
                        header.text = Sol.Environment.resources.changeHistory;
                        this.historialPopup.add(header);
                        var items = model.Changes;
                        this.historialList.addItems(items);
                        this.historialPopup.add(this.historialList);
                        this.isHistorialLoaded = true;
                    }, null);
                }
            }
            Components.FileHistory = FileHistory;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class InterestingCheck extends Sol.Check {
                constructor() {
                    super();
                    this.breakInForm = false;
                    this.css.add("sol_interesting_check");
                    this.allowSaveValueAsDefault = false;
                }
            }
            Components.InterestingCheck = InterestingCheck;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let ProductOrigin;
            (function (ProductOrigin) {
                ProductOrigin[ProductOrigin["National"] = 1] = "National";
                ProductOrigin[ProductOrigin["Imported"] = 2] = "Imported";
            })(ProductOrigin = Components.ProductOrigin || (Components.ProductOrigin = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let RuleOperation;
            (function (RuleOperation) {
                RuleOperation[RuleOperation["Income"] = 1] = "Income";
                RuleOperation[RuleOperation["Revenue"] = 2] = "Revenue";
            })(RuleOperation = Components.RuleOperation || (Components.RuleOperation = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let RuleScope;
            (function (RuleScope) {
                RuleScope[RuleScope["TaxRate"] = 1] = "TaxRate";
                RuleScope[RuleScope["BasisCalculation"] = 2] = "BasisCalculation";
            })(RuleScope = Components.RuleScope || (Components.RuleScope = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RuleScopeCombo extends Sol.Combo {
                get selectedScope() {
                    return this.selectedCode == "1" ? Components.RuleScope.TaxRate : Components.RuleScope.BasisCalculation;
                }
                static getDescriptionFromCode(code) {
                    return [Sol.Environment.resources.taxRate, Sol.Environment.resources.basisCalculation][code - 1];
                }
                constructor() {
                    super();
                    this.loadOptions([
                        { Code: "1", Description: RuleScopeCombo.getDescriptionFromCode(1) },
                        { Code: "2", Description: RuleScopeCombo.getDescriptionFromCode(2) }
                    ]);
                }
            }
            Components.RuleScopeCombo = RuleScopeCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RegionTaxRow extends Sol.Control {
                constructor() {
                    super("tr");
                    this.code = 0;
                    this.regionConditionCode = 0;
                    this.ncmConditionCode = 0;
                    this.regionSelector = new Web.Geo.RegionSelector();
                    this.ncmField = new Sol.Field();
                    this.ruleScope = new Components.RuleScopeCombo();
                    this.taxPercent = new Sol.PercentField();
                    this.messageField = new Sol.TextField();
                    var regionCell = new Sol.Control("td");
                    this.regionSelector.className = "Solarium.Geo.Región, Solarium.Geo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    regionCell.add(this.regionSelector);
                    this.add(regionCell);
                    var ncmCell = new Sol.Control("td");
                    ncmCell.add(this.ncmField);
                    this.add(ncmCell);
                    var ruleScopeCell = new Sol.Control("td");
                    ruleScopeCell.add(this.ruleScope);
                    this.add(ruleScopeCell);
                    var aliquotCell = new Sol.Control("td");
                    aliquotCell.add(this.taxPercent);
                    var percent = new Sol.Control("span");
                    percent.text = " %";
                    aliquotCell.add(percent);
                    this.add(aliquotCell);
                    var messageCell = new Sol.Control("td");
                    messageCell.ancho = 250;
                    messageCell.add(this.messageField);
                    this.add(messageCell);
                    var addCell = new Sol.Control("td");
                    addCell.text = "+";
                    addCell.css.add("sol_tax_rule_button");
                    addCell.onClick = () => this.onCellAdded(this);
                    this.add(addCell);
                    var removeCell = new Sol.Control("td");
                    removeCell.text = "-";
                    removeCell.estilos.agregar("color", "red");
                    removeCell.css.add("sol_tax_rule_button");
                    removeCell.onClick = () => this.onCellRemoved(this);
                    this.add(removeCell);
                }
                clear() {
                    this.regionSelector.clear();
                    this.ncmField.clear();
                    this.ruleScope.clear();
                    this.taxPercent.clear();
                    this.messageField.clear();
                    this.regionSelector.foco();
                }
                getValue(operation) {
                    var conditions = new Sol.List();
                    conditions.add([
                        { Campo: "ID", Valor: this.regionConditionCode || 0 },
                        { Campo: "ConditionType", Valor: Components.RuleConditionType.Region },
                        { Campo: "Region", Valor: this.regionSelector.selectedCode }
                    ]);
                    if (!this.ncmField.isEmpty())
                        conditions.add([
                            { Campo: "ID", Valor: this.ncmConditionCode || 0 },
                            { Campo: "ConditionType", Valor: Components.RuleConditionType.NCM },
                            { Campo: "NCMCodes", Valor: this.ncmField.value }
                        ]);
                    return [{ Campo: "ID", Valor: this.code },
                        { Campo: "Operation", Valor: operation },
                        { Campo: "Conditions", Valor: conditions.toArray() },
                        { Campo: "IsRegionRule", Valor: true },
                        { Campo: "Scope", Valor: this.ruleScope.value },
                        { Campo: "Message", Valor: this.messageField.value },
                        { Campo: "Position", Valor: 1000000 },
                        { Campo: "TaxPercent", Valor: this.taxPercent.value }];
                }
                isEmpty() { return this.regionSelector.isEmpty(); }
                setValue(ruleData) {
                    this.code = ruleData.that(rd => rd.Campo == "ID").Valor;
                    this.ruleScope.value = ruleData.that(rd => rd.Campo == "Scope").Valor.Valor;
                    this.taxPercent.value = ruleData.that(rd => rd.Campo == "TaxPercent").Valor;
                    this.messageField.value = ruleData.that(rd => rd.Campo == "Message").Valor;
                    var conditions = ruleData.that(rd => rd.Campo == "Conditions").Valor;
                    Sol.List.from(conditions).forEach(cnd => {
                        var conditionData = Sol.List.from(cnd);
                        var code = conditionData.that(rd => rd.Campo == "ID").Valor;
                        var region = conditionData.that(rd => rd.Campo == "Region").Valor;
                        if (region && region.Valor) {
                            this.regionConditionCode = code;
                            this.regionSelector.value = region;
                            return;
                        }
                        var ncms = conditionData.that(rd => rd.Campo == "NCMCodes").Valor;
                        if (ncms) {
                            this.ncmConditionCode = code;
                            this.ncmField.value = ncms;
                            return;
                        }
                    });
                }
            }
            Components.RegionTaxRow = RegionTaxRow;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RegionTax extends Sol.Control {
                constructor() {
                    super();
                    this.originHeader = new Sol.Control("th");
                    this.ruleTable = new Sol.Control("table");
                    this.tbody = new Sol.Control("tbody");
                    this.css.addMany(["sol_campo", "sol_tax_rule_editor_form"]);
                    this.visible = false;
                    this.add(this.ruleTable);
                    this.initializeTableHeader();
                    this.ruleTable.add(this.tbody);
                    this.addRow();
                }
                get originCaption() { return this.originHeader.text; }
                set originCaption(value) { this.originHeader.text = value; }
                get value() {
                    return this.tbody
                        .controls
                        .cast()
                        .where(tr => !tr.isEmpty())
                        .select(dt => dt.getValue(this.operation))
                        .toArray();
                }
                addRow(row = null) {
                    row = row || new Components.RegionTaxRow();
                    row.onCellAdded = () => this.addRow();
                    row.onCellRemoved = () => {
                        if (this.tbody.controls.count == 1)
                            this.tbody.controls.first().clear();
                        else
                            this.tbody.controls.remove(row);
                    };
                    this.tbody.add(row);
                }
                initializeTableHeader() {
                    var header = new Sol.Control("thead");
                    var headerRow = new Sol.Control("tr");
                    headerRow.add(this.originHeader);
                    var ncmHeader = new Sol.Control("th");
                    ncmHeader.text = "NCMs";
                    headerRow.add(ncmHeader);
                    var calcHeader = new Sol.Control("th");
                    calcHeader.text = "Cálculo";
                    headerRow.add(calcHeader);
                    var percentHeader = new Sol.Control("th");
                    percentHeader.text = "Alíquota";
                    headerRow.add(percentHeader);
                    var messageHeader = new Sol.Control("th");
                    messageHeader.text = "Mensagem";
                    headerRow.add(messageHeader);
                    header.add(headerRow);
                    this.ruleTable.add(header);
                }
            }
            Components.RegionTax = RegionTax;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            let RuleConditionType;
            (function (RuleConditionType) {
                RuleConditionType[RuleConditionType["General"] = 1] = "General";
                RuleConditionType[RuleConditionType["NCM"] = 2] = "NCM";
                RuleConditionType[RuleConditionType["Region"] = 3] = "Region";
                RuleConditionType[RuleConditionType["Entity"] = 4] = "Entity";
                RuleConditionType[RuleConditionType["Origin"] = 5] = "Origin";
                RuleConditionType[RuleConditionType["GeneratesCredit"] = 6] = "GeneratesCredit";
            })(RuleConditionType = Components.RuleConditionType || (Components.RuleConditionType = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class CompanySelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.forceSubtype = true;
                        this.resultsOrder = "Nombre";
                        this.filterProperty = "GeneralFilter";
                        this.onInstantiateItem = (i, d) => this.instantiateItem(i, d);
                        this.allowCreateNew = false;
                        this.allowEdit = false;
                        this.isComplex = false;
                        this.className = "Solarium.Empresa, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.properties = ["ID", this.displayProperty, "NúmeroDocumento"];
                    }
                    getFilters() {
                        const filters = super.getFilters();
                        filters.add({ PropertyName: "EntityFilter", FilterValue: true, FilterType: null });
                        if (this.relationContextClass)
                            filters.add({ PropertyName: "RelationFilter", FilterValue: this.relationContextClass, FilterType: null });
                        return filters;
                    }
                    instantiateItem(item, data) {
                        const name = data.that(cmp => cmp.Campo == "Nombre").Valor;
                        const nameLabel = new Sol.Control("strong");
                        nameLabel.text = name;
                        item.add(nameLabel);
                        item.text = "";
                        item.displayText = name;
                        const taxId = data.that(cmp => cmp.Campo == "NúmeroDocumento").Valor;
                        const taxIdLabel = new Sol.Control("span");
                        taxIdLabel.css.add("customer_selector_taxid");
                        taxIdLabel.text = taxId;
                        item.add(taxIdLabel);
                    }
                }
                Selectors.CompanySelector = CompanySelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RuleCondition extends Sol.Control {
                constructor() {
                    super("span");
                    this.mainCombo = new Sol.Combo();
                    this.ncmField = new Sol.Field();
                    this.companySelector = new Components.Selectors.CompanySelector();
                    this.predicateArea = new Sol.Control("span");
                    this.originCombo = new Sol.Combo();
                    this.initializeMainCombo();
                    this.initializeNcmField();
                    this.initializeOriginCombo();
                    this.initializeCompanySelector();
                    this.intializeDeleteButton();
                }
                get ruleConditionType() { return parseInt(this.mainCombo.selectedCode); }
                getCondition() {
                    return {
                        code: 0,
                        conditionType: this.ruleConditionType,
                        ncmCodes: this.ncmField.value,
                        entityCode: this.companySelector.selectedCode,
                        entityName: this.companySelector.selectedText,
                        productOrigin: this.originCombo.selectedCode == "1" ? Components.ProductOrigin.National : Components.ProductOrigin.Imported
                    };
                }
                isEmpty() {
                    return (this.ruleConditionType == Components.RuleConditionType.NCM && this.ncmField.isEmpty()) ||
                        (this.ruleConditionType == Components.RuleConditionType.Entity && this.companySelector.isEmpty());
                }
                initializeMainCombo() {
                    this.mainCombo.loadOptions([
                        { Code: "1", Description: Sol.Environment.resources.mainRule },
                        { Code: "5", Description: Sol.Environment.resources.origin },
                        { Code: "2", Description: Sol.Environment.resources.ncmRule },
                        { Code: "4", Description: Sol.Environment.resources.entityRule },
                        { Code: "6", Description: Sol.Environment.resources.generatesCredit }
                    ]);
                    this.add(this.mainCombo);
                    this.mainCombo.onChange = () => this.mainComboOnModificado();
                }
                mainComboOnModificado() {
                    this.ncmField.visible = this.mainCombo.selectedCode == '2';
                    this.companySelector.visible = this.mainCombo.selectedCode == '4';
                    this.originCombo.visible = this.mainCombo.selectedCode == '5';
                }
                ;
                intializeDeleteButton() {
                    var deleteButton = new Sol.Control("span");
                    deleteButton.text = "x";
                    deleteButton.css.add("sol_tax_deleteButton");
                    deleteButton.onClick = () => this.onDelete(this);
                    this.add(deleteButton);
                }
                initializeNcmField() {
                    this.ncmField.placeHolder = Sol.Environment.resources.ncm_field_holder;
                    this.ncmField.autoWidth = false;
                    this.ncmField.maxLength = 1024;
                    this.ncmField.css.add("sol_tax_rule_ncm_field");
                    this.add(this.ncmField);
                    this.ncmField.visible = false;
                }
                initializeOriginCombo() {
                    this.originCombo.addItems([
                        { Campo: "Nacional", Valor: 1 },
                        { Campo: "Importada", Valor: 2 }
                    ]);
                    this.add(this.originCombo);
                    this.originCombo.visible = false;
                }
                initializeCompanySelector() {
                    this.add(this.companySelector);
                    this.companySelector.visible = false;
                }
            }
            Components.RuleCondition = RuleCondition;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RuleDetails extends Sol.Control {
                constructor(rule) {
                    super();
                    this.css.add("sol_rule_details");
                    this.rule = rule;
                    var ruleDescription = new Sol.Control("span");
                    ruleDescription.text = this.ruleDescription;
                    this.add(ruleDescription);
                    var deleteButton = new Sol.Button();
                    deleteButton.type = Sol.ButtonType.Link;
                    deleteButton.text = Sol.Environment.resources.eliminar;
                    deleteButton.onClick = () => this.parent.controls.remove(this);
                    this.add(deleteButton);
                }
                get value() {
                    var conditions = Sol.List.from(this.rule.conditions).select(c => [
                        { Campo: "ID", Valor: c.code || 0 },
                        { Campo: "ConditionType", Valor: c.conditionType },
                        { Campo: "NCMCodes", Valor: c.ncmCodes },
                        { Campo: "Entity", Valor: c.entityCode },
                        { Campo: "ProductOrigin", Valor: c.productOrigin }
                    ]).toArray();
                    return [{ Campo: "ID", Valor: this.rule.code },
                        { Campo: "Conditions", Valor: conditions },
                        { Campo: "Operation", Valor: this.rule.operation },
                        { Campo: "Scope", Valor: this.rule.ruleScope },
                        { Campo: "IsRegionRule", Valor: false },
                        { Campo: "TaxPercent", Valor: this.rule.rate },
                        { Campo: "Position", Valor: 1 },
                        { Campo: "Message", Valor: this.rule.message }];
                }
                get ruleDescription() {
                    const typeDescriptions = {
                        [Components.RuleConditionType.General]: Sol.Environment.resources.mainRule,
                        [Components.RuleConditionType.NCM]: Sol.Environment.resources.ncmRule,
                        [Components.RuleConditionType.Entity]: Sol.Environment.resources.entityRule,
                        [Components.RuleConditionType.Origin]: Sol.Environment.resources.origin,
                        [Components.RuleConditionType.GeneratesCredit]: Sol.Environment.resources.generatesCredit
                    };
                    var result = Sol.List.from(this.rule.conditions)
                        .select(c => typeDescriptions[c.conditionType].toLowerCase() + this.getConditionPredicate(c))
                        .toArray().join(" e ");
                    result = result.capitalizeFirstLetter();
                    if (this.rule.conditions[0].conditionType != Components.RuleConditionType.General)
                        result += ", ";
                    result += Components.RuleScopeCombo.getDescriptionFromCode(this.rule.ruleScope).toLowerCase();
                    result += ' ' + this.rule.rate + '%';
                    result = result.replace(/\.\.\./g, " ");
                    result += '.';
                    return result;
                }
                getConditionPredicate(condition) {
                    if (condition.conditionType == Components.RuleConditionType.NCM)
                        return condition.ncmCodes;
                    if (condition.conditionType == Components.RuleConditionType.Entity)
                        return condition.entityName;
                    if (condition.conditionType == Components.RuleConditionType.Origin)
                        return condition.productOrigin == Components.ProductOrigin.National ? "nacional" : "importado";
                    return "";
                }
            }
            Components.RuleDetails = RuleDetails;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RuleForm extends Sol.Control {
                constructor() {
                    super();
                    this.addConditionButton = new Sol.Button();
                    this.addRuleButton = new Sol.Button();
                    this.conditionsArea = new Sol.Control("span");
                    this.conditions = new Sol.List();
                    this.currentRules = new Sol.Control();
                    this.percentField = new Sol.PercentField();
                    this.ruleScope = new Components.RuleScopeCombo();
                    this.messageField = new Sol.TextField();
                    this.css.addMany(["sol_campo", "sol_tax_rule_editor_form"]);
                    this.add(this.currentRules);
                    var ruleFormLabel = new Sol.Label();
                    ruleFormLabel.text = Sol.Environment.resources.newRule + ':';
                    this.add(ruleFormLabel);
                    this.add(this.conditionsArea);
                    this.addCondition();
                    this.add(this.ruleScope);
                    this.percentField.value = 0;
                    this.add(this.percentField);
                    var percentSign = new Sol.Control("span");
                    percentSign.text = '%';
                    this.add(percentSign);
                    this.addConditionButton.text = Sol.Environment.resources.addCondition;
                    this.addConditionButton.type = Sol.ButtonType.Link;
                    this.addConditionButton.onClick = () => this.addCondition();
                    this.add(this.addConditionButton);
                    var messageLabel = new Sol.Label();
                    messageLabel.text = Sol.Environment.resources.fiscalMessage;
                    this.add(messageLabel);
                    this.add(this.messageField);
                    this.addRuleButton.text = Sol.Environment.resources.anadir_item;
                    this.addRuleButton.onClick = () => this.addRule();
                    this.add(this.addRuleButton);
                }
                get value() {
                    return this.currentRules
                        .controls
                        .cast()
                        .select(dt => dt.value)
                        .toArray();
                }
                set value(data) {
                    Sol.List.from(data).forEach(d => {
                        var ruleData = Sol.List.from(d);
                        var rule = {
                            code: ruleData.that(rd => rd.Campo == "ID").Valor,
                            conditions: Sol.List.from(ruleData.that(rd => rd.Campo == "Conditions").Valor)
                                .select(c => {
                                var conditionData = Sol.List.from(c);
                                var codition = {
                                    code: conditionData.that(rd => rd.Campo == "ID").Valor,
                                    conditionType: conditionData.that(rd => rd.Campo == "ConditionType").Valor.Valor,
                                    ncmCodes: conditionData.that(rd => rd.Campo == "NCMCodes").Valor,
                                    productOrigin: conditionData.that(rd => rd.Campo == "ProductOrigin").Valor.Valor,
                                    entityCode: conditionData.that(rd => rd.Campo == "Entity").Valor.Valor,
                                    entityName: conditionData.that(rd => rd.Campo == "Entity").Valor.Campo
                                };
                                return codition;
                            })
                                .toArray(),
                            ruleScope: ruleData.that(rd => rd.Campo == "Scope").Valor.Valor,
                            rate: ruleData.that(rd => rd.Campo == "TaxPercent").Valor,
                            message: ruleData.that(rd => rd.Campo == "Message").Valor,
                            operation: this.operation,
                        };
                        this.currentRules.add(new Components.RuleDetails(rule));
                    });
                }
                addCondition() {
                    var condition = new Components.RuleCondition();
                    this.conditions.add(condition);
                    condition.estilos.agregar("display", "block");
                    this.conditionsArea.add(condition);
                    condition.onDelete = c => this.deleteCondition(c);
                }
                deleteCondition(condition) {
                    if (this.conditions.count == 1) {
                        alert(Sol.Environment.resources.alert_condition);
                        return;
                    }
                    ;
                    this.conditions.remove(condition);
                    this.conditionsArea.controls.remove(condition);
                }
                getRule() {
                    return {
                        code: 0,
                        operation: this.operation,
                        conditions: this.conditions.select(c => c.getCondition()).toArray(),
                        ruleScope: this.ruleScope.selectedScope,
                        rate: this.percentField.value,
                        message: this.messageField.value
                    };
                }
                addRule() {
                    if (this.conditions.count > 1 && this.conditions.any(c => c.ruleConditionType == Components.RuleConditionType.General)) {
                        alert("Não é possível combinar a regra geral com outras condições.");
                        return;
                    }
                    if (this.conditions.any(c => c.isEmpty())) {
                        alert("Uma das condições não está preenchida corretamente.");
                        return;
                    }
                    this.currentRules.add(new Components.RuleDetails(this.getRule()));
                    this.conditions.empty();
                    this.conditionsArea.controls.empty();
                    this.messageField.clear();
                    this.ruleScope.clear();
                    this.percentField.value = 0;
                    this.addCondition();
                }
            }
            Components.RuleForm = RuleForm;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TaxRulesEditor extends Web.FieldGroupEditor {
                constructor() {
                    super();
                    this.code = 0;
                    this.incomeRuleForm = new Components.RuleForm();
                    this.revenueRuleForm = new Components.RuleForm();
                    this.rulesSpace = new Sol.Control();
                    this.regionIncomeTable = new Components.RegionTax();
                    this.regionRevenueTable = new Components.RegionTax();
                    this.css.addMany(["sol_detalles_complex", "sol_tax_rule_editor"]);
                    this.rulesSpace.css.add("sol_tax_rules_editor_space");
                    this.add(this.rulesSpace);
                    this.initializeButtons();
                    this.initializeIncomeRuleForm();
                    this.initializeIncomeTable();
                    this.initializeRevenueRuleForm();
                    this.initializeRevenueTable();
                }
                get value() {
                    var regionalRules = Sol.List.from(this.regionIncomeTable.value)
                        .addMany(this.regionRevenueTable.value)
                        .toArray();
                    var generalRules = Sol.List.from(this.incomeRuleForm.value)
                        .addMany(this.revenueRuleForm.value)
                        .addMany(regionalRules)
                        .toArray();
                    return [{ Campo: this.propertyName + "$ID", Valor: this.code },
                        { Campo: this.propertyName + "$Temp", Valor: 5 },
                        { Campo: this.propertyName + "$GeneralRules", Valor: generalRules }];
                }
                set value(value) {
                    var valueList = Sol.List.from(value);
                    this.code = valueList.that(i => i.Campo == "ID").Valor;
                    var generalRules = valueList.that(i => i.Campo == "GeneralRules").Valor;
                    this.incomeRuleForm.value = Sol.List.from(generalRules)
                        .where(rule => !Sol.List.from(rule).that(rd => rd.Campo == "IsRegionRule").Valor &&
                        Sol.List.from(rule).that(rd => rd.Campo == "Operation").Valor.Valor == Components.RuleOperation.Income)
                        .toArray();
                    this.revenueRuleForm.value = Sol.List.from(generalRules)
                        .where(rule => !Sol.List.from(rule).that(rd => rd.Campo == "IsRegionRule").Valor &&
                        Sol.List.from(rule).that(rd => rd.Campo == "Operation").Valor.Valor == Components.RuleOperation.Revenue)
                        .toArray();
                    Sol.List.from(generalRules).forEach(rule => {
                        var ruleData = Sol.List.from(rule);
                        if (!ruleData.that(rd => rd.Campo == "IsRegionRule").Valor)
                            return;
                        var regionRule = new Components.RegionTaxRow();
                        regionRule.setValue(ruleData);
                        var operation = ruleData.that(rd => rd.Campo == "Operation").Valor.Valor;
                        (operation == Components.RuleOperation.Income ? this.regionIncomeTable : this.regionRevenueTable).addRow(regionRule);
                    });
                }
                isEmpty() { return false; }
                toControl() { return this; }
                foco() { }
                clear() { }
                validate() { return null; }
                initializeButtons() {
                    var incomeRulesButton = new Sol.Button();
                    incomeRulesButton.imageCode = "&#xf0e3;";
                    incomeRulesButton.text = "Entradas";
                    incomeRulesButton.type = Sol.ButtonType.Alternate;
                    incomeRulesButton.checked = true;
                    incomeRulesButton.onChecked = () => {
                        this.incomeRuleForm.visible = true;
                        regionIncomeRulesButton.checked = false;
                        regionRevenueRulesButton.checked = false;
                        incomeRulesButton.checked = true;
                        revenueRulesButton.checked = false;
                        this.regionRevenueTable.visible = false;
                        this.regionIncomeTable.visible = false;
                        this.revenueRuleForm.visible = false;
                    };
                    this.rulesSpace.add(incomeRulesButton);
                    var regionIncomeRulesButton = new Sol.Button();
                    regionIncomeRulesButton.imageCode = "&#xf0e3;";
                    regionIncomeRulesButton.text = Sol.Environment.resources.region_income_rule;
                    regionIncomeRulesButton.type = Sol.ButtonType.Alternate;
                    regionIncomeRulesButton.onChecked = () => {
                        regionIncomeRulesButton.checked = true;
                        regionRevenueRulesButton.checked = false;
                        incomeRulesButton.checked = false;
                        revenueRulesButton.checked = false;
                        this.incomeRuleForm.visible = false;
                        this.regionRevenueTable.visible = false;
                        this.regionIncomeTable.visible = true;
                        this.revenueRuleForm.visible = false;
                    };
                    this.rulesSpace.add(regionIncomeRulesButton);
                    var revenueRulesButton = new Sol.Button();
                    revenueRulesButton.imageCode = "&#xf0e3;";
                    revenueRulesButton.text = "Saídas";
                    revenueRulesButton.type = Sol.ButtonType.Alternate;
                    revenueRulesButton.checked = false;
                    revenueRulesButton.onChecked = () => {
                        this.incomeRuleForm.visible = false;
                        regionIncomeRulesButton.checked = false;
                        regionRevenueRulesButton.checked = false;
                        incomeRulesButton.checked = false;
                        revenueRulesButton.checked = true;
                        this.regionRevenueTable.visible = false;
                        this.regionIncomeTable.visible = false;
                        this.revenueRuleForm.visible = true;
                    };
                    this.rulesSpace.add(revenueRulesButton);
                    var regionRevenueRulesButton = new Sol.Button();
                    regionRevenueRulesButton.imageCode = "&#xf0e3;";
                    regionRevenueRulesButton.text = Sol.Environment.resources.region_revenue_rule;
                    regionRevenueRulesButton.type = Sol.ButtonType.Alternate;
                    regionRevenueRulesButton.onChecked = () => {
                        this.regionIncomeTable.visible = false;
                        this.regionRevenueTable.visible = true;
                        regionRevenueRulesButton.checked = true;
                        regionIncomeRulesButton.checked = false;
                        revenueRulesButton.checked = false;
                        incomeRulesButton.checked = false;
                        this.incomeRuleForm.visible = false;
                        this.revenueRuleForm.visible = false;
                    };
                    this.rulesSpace.add(regionRevenueRulesButton);
                }
                initializeIncomeTable() {
                    this.regionIncomeTable.originCaption = "De";
                    this.regionIncomeTable.operation = Components.RuleOperation.Income;
                    this.add(this.regionIncomeTable);
                }
                initializeRevenueTable() {
                    this.regionRevenueTable.originCaption = "Para";
                    this.regionRevenueTable.operation = Components.RuleOperation.Revenue;
                    this.add(this.regionRevenueTable);
                }
                initializeIncomeRuleForm() {
                    this.incomeRuleForm.operation = Components.RuleOperation.Income;
                    this.rulesSpace.add(this.incomeRuleForm);
                }
                initializeRevenueRuleForm() {
                    this.revenueRuleForm.operation = Components.RuleOperation.Revenue;
                    this.revenueRuleForm.visible = false;
                    this.rulesSpace.add(this.revenueRuleForm);
                }
            }
            Components.TaxRulesEditor = TaxRulesEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class Login extends Sol.Control {
                constructor() {
                    super();
                    this.encabezado = new Sol.Control("header");
                    this.logo = new Sol.ImageBox();
                    this.textoEncabezado = new Sol.Control("p");
                    this.formulario = new Sol.Form();
                    this.languageLabel = new Sol.Label();
                    this.languageCombo = new Sol.Combo();
                    this.etiquetaDatos = new Sol.Label();
                    this.divUsuario = new Sol.Control();
                    this.iconoUsuario = new Sol.Control("i");
                    this.campoUsuario = new Sol.Field();
                    this.divContrasena = new Sol.Control();
                    this.iconoContrasena = new Sol.Control("i");
                    this.PasswordField = new Sol.PasswordField();
                    this.creditos = new Sol.Control("p");
                    this.recoverPasswordButton = new Sol.Button();
                    this.recoverPasswordScreen = new Screens.RecoverPasswordScreen();
                    this.mensajeExitoRecordatorio = new Sol.ScreenMessage();
                    this.geolocationVerificationMessage = new Sol.Control();
                    this.css.add("sol_login");
                    this.add(this.encabezado);
                    this.logo.source = "/logo";
                    this.encabezado.add(this.logo);
                    this.textoEncabezado.text = Sol.Environment.resources.bienvenida;
                    this.encabezado.add(this.textoEncabezado);
                    this.mensajeExitoRecordatorio.type = Sol.MessageType.Success;
                    this.mensajeExitoRecordatorio.caption = Sol.Environment.resources.clave_enviada;
                    this.mensajeExitoRecordatorio.visible = false;
                    this.formulario.add(this.mensajeExitoRecordatorio);
                    this.formulario.showCancelButton = false;
                    this.formulario.okButton.type = Sol.ButtonType.Custom;
                    this.formulario.okButton.text = Sol.Environment.resources.entrar;
                    this.formulario.okIcon = '&#xf090;';
                    this.formulario.onExhibido = this.formularioExhibido;
                    this.formulario.onSave = () => this.doLogin();
                    this.add(this.formulario);
                    this.initializeLanguageSelector();
                    this.etiquetaDatos.text = Sol.Environment.resources.datos_acceso + ":";
                    this.etiquetaDatos.disableAsterisk = true;
                    this.etiquetaDatos.editor = this.campoUsuario;
                    this.formulario.add(this.etiquetaDatos);
                    this.divUsuario.css.add("sol_login_campo");
                    this.formulario.add(this.divUsuario);
                    this.iconoUsuario.text = '&#xf007;';
                    this.divUsuario.add(this.iconoUsuario);
                    this.campoUsuario.atributos.agregar("maxlength", "85");
                    this.campoUsuario.required = true;
                    this.campoUsuario.atributos.agregar("autofocus");
                    this.campoUsuario.placeHolder = Sol.Environment.resources.usuario;
                    this.divUsuario.add(this.campoUsuario);
                    this.divContrasena.css.add("sol_login_campo");
                    this.formulario.add(this.divContrasena);
                    this.iconoContrasena.text = '&#xf084;';
                    this.divContrasena.add(this.iconoContrasena);
                    this.PasswordField.placeHolder = Sol.Environment.resources.contrasena;
                    this.PasswordField.required = true;
                    this.divContrasena.add(this.PasswordField);
                    this.geolocationVerificationMessage.css.add("sol_login_geo");
                    this.geolocationVerificationMessage.text = Sol.Environment.resources.verifying_geo;
                    this.geolocationVerificationMessage.visible = false;
                    this.formulario.add(this.geolocationVerificationMessage);
                    this.recoverPasswordScreen.visible = false;
                    this.recoverPasswordScreen.onCancel = () => this.cancelRecoverPasswordScreen();
                    this.recoverPasswordScreen.onSave = () => this.recoverPassword();
                    this.add(this.recoverPasswordScreen);
                    this.recoverPasswordButton.type = Sol.ButtonType.Link;
                    this.recoverPasswordButton.text = Sol.Environment.resources.recordar_clave;
                    this.recoverPasswordButton.onClick = () => this.openRecoverPasswordScreen();
                    this.add(this.recoverPasswordButton);
                    this.creditos.text = Sol.Environment.resources.sis_copyright;
                    this.creditos.text += " - " + Web.System.version;
                    this.add(this.creditos);
                }
                initializeLanguageSelector() {
                    if (Sol.Environment.uniqueLanguage)
                        return;
                    const esItem = new Sol.ComboItem();
                    const enItem = new Sol.ComboItem();
                    const ptItem = new Sol.ComboItem();
                    this.languageLabel.text = Sol.Environment.resources.idioma + ":";
                    this.languageLabel.editor = this.languageCombo;
                    this.formulario.add(this.languageLabel);
                    ptItem.text = "Português";
                    ptItem.code = "pt";
                    esItem.text = "Español";
                    esItem.code = "es";
                    enItem.text = "English";
                    enItem.code = "en";
                    ptItem.selected = Sol.Environment.credential.idioma == "pt";
                    this.languageCombo.add(ptItem);
                    esItem.selected = Sol.Environment.credential.idioma == "es";
                    this.languageCombo.add(esItem);
                    enItem.selected = Sol.Environment.credential.idioma == "en";
                    this.languageCombo.add(enItem);
                    this.languageCombo.onChange = () => this.languageChanged();
                    this.formulario.add(this.languageCombo);
                }
                doLogin(pos = null) {
                    this.mensajeExitoRecordatorio.visible = false;
                    var loginData = {
                        Username: this.campoUsuario.textValue,
                        Password: this.PasswordField.textValue,
                        Language: Sol.Environment.credential.idioma,
                        Latitude: pos ? pos.latitude : null,
                        Longitude: pos ? pos.longitude : null,
                        OnlyToken: false,
                        AccessType: Sol.AccessType.Internal
                    };
                    Web.System.exec("hjkj28d", "Login", loginData, model => {
                        if (!model.Fail) {
                            Sol.Environment.credential.load(model.Credencial);
                            Web.System.openHome(model.SystemModel);
                            this.destroy();
                        }
                        else {
                            if (model.RequiresLocation) {
                                if (!navigator.geolocation) {
                                    this.showLocationError();
                                    this.formulario.workComplete();
                                    return;
                                }
                                navigator.geolocation.getCurrentPosition(pos => this.doLoginWithPosition(pos), () => this.showLocationError());
                                this.geolocationVerificationMessage.visible = true;
                            }
                            else {
                                this.geolocationVerificationMessage.visible = false;
                                this.formulario.showError(model.ErrorMessage);
                                this.formulario.workComplete();
                            }
                        }
                    });
                }
                openRecoverPasswordScreen() {
                    this.formulario.hide();
                    this.recoverPasswordScreen.hideMessages();
                    this.recoverPasswordScreen.email.clear();
                    this.recoverPasswordScreen.show();
                    this.recoverPasswordButton.visible = false;
                    this.textoEncabezado.text = Sol.Environment.resources.recordar_clave;
                    this.mensajeExitoRecordatorio.visible = false;
                    return false;
                }
                cancelRecoverPasswordScreen() {
                    this.recoverPasswordScreen.hide();
                    this.formulario.show();
                    this.recoverPasswordButton.visible = true;
                    this.textoEncabezado.text = Sol.Environment.resources.bienvenida;
                }
                recoverPassword() {
                    var data = {
                        email: this.recoverPasswordScreen.email.textValue,
                        language: Sol.Environment.credential.idioma
                    };
                    Web.System.exec("hjkj28d", "RecoverPassword", data, e => {
                        this.recoverPasswordScreen.workComplete();
                        if (!e.Fail) {
                            this.mensajeExitoRecordatorio.visible = true;
                            this.formulario.hideMessages();
                            this.cancelRecoverPasswordScreen();
                        }
                        else
                            this.formulario.showError(e.ErrorMessage);
                    });
                }
                formularioExhibido(e) {
                    var me = e.parent;
                    me.campoUsuario.foco();
                }
                languageChanged() {
                    Sol.Http.Cookies.setCookie("sol_lang", this.languageCombo.selectedCode, 30);
                    location.reload();
                }
                doLoginWithPosition(e) {
                    this.formulario.workComplete();
                    this.doLogin(e.coords);
                }
                showLocationError() {
                    this.geolocationVerificationMessage.visible = false;
                    this.formulario.showError(Sol.Environment.resources.location_not_available);
                }
            }
            Screens.Login = Login;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ErrorScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.mensaje = new Sol.ScreenMessage();
                }
                build() {
                    super.build();
                    this.css.add("sol_pantalla");
                    this.mensaje.caption = Sol.Environment.resources.pagina_indisponible;
                    this.add(this.mensaje);
                }
            }
            Screens.ErrorScreen = ErrorScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class FieldInfo extends Sol.Control {
                constructor() {
                    super();
                    this.nameDisplay = new Sol.Control("h5");
                    this.infoDisplay = new Sol.Control();
                    this.requiredDisplay = new Sol.Control();
                    this.requiredDisplay.css.add("sol_detalles_left_required");
                    this.controls.addMany([this.nameDisplay, this.infoDisplay, this.requiredDisplay]);
                }
                clear() {
                    this.nameDisplay.text = "";
                    this.infoDisplay.text = "";
                    this.requiredDisplay.text = "";
                }
                setInfo(name, info, required, readonly) {
                    this.nameDisplay.text = name;
                    this.infoDisplay.text = info;
                    this.requiredDisplay.text = required && !readonly ? Sol.Environment.resources.required : "";
                }
            }
            Screens.FieldInfo = FieldInfo;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ProfileScreen extends Screens.Registro {
                build() {
                    const model = this.model;
                    this.anchorage = { PropertyName: "SpecificModule", FilterType: "SType", FilterValue: model.ModuleName };
                    super.build();
                }
            }
            Screens.ProfileScreen = ProfileScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class AlternateForm extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.editors = new Sol.List();
                    this.labels = new Sol.List();
                }
                get values() {
                    const result = this.editors
                        .where(cp => !cp.readonly && !(cp instanceof Web.FieldGroupEditor))
                        .select(cp => ({ Campo: cp.propertyName, Valor: cp.value }));
                    this.editors.where(cp => cp instanceof Web.FieldGroupEditor).forEach(cp => result.addMany(cp.value));
                    return result.toArray();
                }
                getEditor(propertyName) {
                    return this.editors.that(e => e.propertyName === propertyName);
                }
                toControl() { return this; }
            }
            Screens.AlternateForm = AlternateForm;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class UserDetailsScreen extends Screens.DetailsScreen {
                constructor() {
                    super(...arguments);
                    this.functionsMenu = new Sol.Control();
                    this.alternateForm = new Screens.AlternateForm();
                }
                build() {
                    super.build();
                    this.alternateForm.css.add("sol_alternate_form");
                    this.myForm.controls.add(this.alternateForm);
                    this.initializeFunctionsMenu();
                }
                initializeFunctionsMenu() {
                    if (!this.userFunctions.hasItems())
                        return;
                    this.leftPanel.createTitle(Sol.Environment.resources.userFunctions);
                    const userButton = new Sol.Button();
                    userButton.text = Sol.Environment.resources.usuario;
                    userButton.data = {
                        Name: Sol.Environment.resources.usuario,
                        ClassName: "Solarium.Login, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        IsMain: true,
                        Code: this.code
                    };
                    userButton.type = Sol.ButtonType.Custom;
                    userButton.checked = true;
                    userButton.onClick = e => this.buttonClick(e);
                    this.functionsMenu.add(userButton);
                    this.functionsMenu.controls.addMany(this.userFunctions.select(uf => {
                        const ufButton = new Sol.Button();
                        ufButton.text = uf.Name;
                        ufButton.data = uf;
                        ufButton.type = Sol.ButtonType.Custom;
                        ufButton.onClick = e => this.buttonClick(e);
                        return ufButton;
                    }));
                    this.leftPanel.add(this.functionsMenu);
                }
                buttonClick(e) {
                    if (e.checked)
                        return;
                    this.selectedFunction = e.data;
                    this.functionsMenu.controls.cast().forEach(bt => bt.checked = bt == e);
                    this.myForm.controls.forEach(ctr => ctr.visible = this.selectedFunction.IsMain);
                    this.hideMessages();
                    this.alternateForm.visible = !this.selectedFunction.IsMain;
                    if (!this.selectedFunction.IsMain)
                        this.loadSelectedFunction();
                }
                createNoFunctionForm(model) {
                    const notFoundMessage = Sol.Control.create(model.ErrorMessage);
                    this.alternateForm.add(notFoundMessage);
                    const addFunctionButton = new Sol.Button();
                    addFunctionButton.type = Sol.ButtonType.Link;
                    addFunctionButton.text = Sol.Environment.resources.createFunction;
                    addFunctionButton.onClick = () => this.addFunction();
                    this.alternateForm.add(addFunctionButton);
                }
                loadSelectedFunction() {
                    this.alternateForm.controls.empty();
                    const data = { className: this.selectedFunction.ClassName, loginID: this.code };
                    Web.System.exec("sn9d23vs7d", "LoadFromLogin", data, model => {
                        if (model.NotFound) {
                            this.createNoFunctionForm(model);
                            return;
                        }
                        this.selectedFunction.Code = model.Code;
                        if (!this.selectedFunction.Structure)
                            this.getFunctionFields();
                        else
                            this.fillAlternateForm();
                    });
                }
                addFunction() {
                    const data = { loginID: this.code, className: this.selectedFunction.ClassName };
                    Web.System.exec("hjkj28d", "CreateFunction", data, model => {
                        if (model.Fail)
                            alert(model.ErrorMessage);
                        else {
                            this.selectedFunction.Code = model.NewID;
                            this.loadSelectedFunction();
                        }
                    });
                }
                fillAlternateForm() {
                    var components = Web.Editors.fillForm(this.selectedFunction.Structure, this.alternateForm, null, Screens.FormState.Edition, this.selectedFunction.ClassName, this.selectedFunction.Code, false);
                    this.alternateForm.structure = this.selectedFunction.Structure;
                    this.alternateForm.editors = components.fields;
                    this.alternateForm.labels = components.labels;
                    this.loadFunctionData();
                    this.createFunctionFooter();
                }
                createFunctionFooter() {
                    const footer = new Sol.Control("footer");
                    this.alternateForm.saveButton = new Sol.Button();
                    this.alternateForm.saveButton.text = Sol.Environment.resources.grabar;
                    this.alternateForm.saveButton.enabled = false;
                    this.alternateForm.saveButton.onClick = () => this.saveFunctionData();
                    footer.add(this.alternateForm.saveButton);
                    this.alternateForm.add(footer);
                }
                getFunctionFields() {
                    const data = {
                        ScreenName: "DetailsScreen",
                        ClassName: this.selectedFunction.ClassName
                    };
                    Web.System.exec("lsperos32", "Open", data, model => {
                        const loginStructure = Sol.List.from(this._model.Structure);
                        const excludedProps = Sol.List.from(["ID", "LoginName", "EntidadRelacionada$LoginName"]);
                        this.selectedFunction.Structure = Sol.List.from(model.Structure)
                            .where(field => !loginStructure.any(lgfield => lgfield.PropertyName == field.PropertyName))
                            .where(field => !excludedProps.contains(field.PropertyName))
                            .toArray();
                        this.fillAlternateForm();
                    });
                }
                loadFunctionData() {
                    const data = {
                        className: this.selectedFunction.ClassName,
                        code: this.selectedFunction.Code,
                        subtype: false
                    };
                    Web.System.exec("sn9d23vs7d", "Load", data, model => {
                        this.readData(this.alternateForm, model.Data, model);
                        this.alternateForm.saveButton.enabled = true;
                    });
                }
                saveFunctionData() {
                    const savingData = {
                        className: this.selectedFunction.ClassName,
                        id: this.selectedFunction.Code,
                        data: this.alternateForm.values,
                        lastUpdate: null
                    };
                    this.alternateForm.saveButton.enabled = false;
                    Web.System.exec("3b5v9v45", "Save", savingData, result => {
                        this.alternateForm.saveButton.enabled = true;
                        if (!result.Fail) {
                            window.scrollTo(0, 0);
                            this.succesMessage.visible = true;
                        }
                        else
                            this.myForm.showError(result.ErrorMessage);
                    });
                }
            }
            Screens.UserDetailsScreen = UserDetailsScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class UsersScreen extends Screens.Registro {
                get myModel() { return this.model; }
                instantiateDetailsScreen() {
                    const screen = new Screens.UserDetailsScreen();
                    screen.userFunctions = Sol.List.from(this.myModel.UserFunctions);
                    return screen;
                }
            }
            Screens.UsersScreen = UsersScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class MessageScreen extends Screens.Registro {
                constructor() {
                    super();
                    this.css.add("sol_message_screen");
                    this.dataview.allowSelectColumns = false;
                }
                build() {
                    super.build();
                    this.dataview.canExportToExcel = false;
                }
                editItem(code) {
                    super.editItem(code, this.curEditIndex);
                    setTimeout(() => {
                        Web.System.home.refreshMailCounter();
                        this.refreshSearch();
                    }, 1000);
                }
                onMultipleActionDone() {
                    Web.System.home.refreshMailCounter();
                }
            }
            Screens.MessageScreen = MessageScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var InlineUpload = Sol.Web.Components.Uploads.InlineUpload;
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class MyPayoutsScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.monthYearField = new Sol.MonthYearField();
                    this.content = new Sol.Control();
                    this.chartArea = new Sol.Control();
                    this.list = new Sol.Control("ul");
                    this.initializeTitle();
                    this.add(this.content);
                    this.content.css.add("sol_my_payouts");
                    this.initializeMonthYearField();
                    this.initializeSearchButton();
                    this.initializeList();
                    this.initializeChart();
                }
                initializeTitle() {
                    this.screenCaption = Sol.Environment.resources.myPayouts;
                    const screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                }
                initializeMonthYearField() {
                    this.content.add(this.monthYearField);
                    this.monthYearField.setCurrentMonth();
                }
                initializeSearchButton() {
                    const searchButton = new Sol.Button();
                    searchButton.onClick = () => this.search();
                    searchButton.text = Sol.Environment.resources.abrir;
                    this.content.add(searchButton);
                    this.content.add(new Sol.LineBreak());
                }
                initializeChart() {
                    this.chartArea.css.add("sol_my_payouts_chart");
                    this.content.add(this.chartArea);
                }
                initializeList() {
                    this.content.add(this.list);
                }
                createListHeader(text) {
                    const header = new Sol.Control("li");
                    header.css.add("sol_my_payouts_header");
                    header.text = text;
                    this.list.add(header);
                }
                createTotalRow(text) {
                    const totalRow = new Sol.Control("li");
                    totalRow.css.add("sol_my_payouts_total");
                    const totalLabel = new Sol.Control("span");
                    totalLabel.text = "Total";
                    totalRow.add(totalLabel);
                    const totalValue = new Sol.Control("span");
                    totalValue.css.add("sol_my_payouts_total_value");
                    totalValue.text = text;
                    totalRow.add(totalValue);
                    this.list.add(totalRow);
                }
                drawChart(model) {
                    this.chartArea.controls.empty();
                    if (!Sol.List.from(model.ChartLabels).hasItems())
                        return;
                    const chart = new Sol.Charts.PieChart();
                    chart.labels = model.ChartLabels;
                    chart.values = model.ChartValues;
                    chart.colors = model.ChartColors;
                    chart.chartHeight = 400;
                    chart.chartWidth = 400;
                    chart.responsive = false;
                    this.chartArea.add(chart);
                    chart.showChart();
                }
                fillList(model) {
                    this.list.controls.empty();
                    const items = Sol.List.from(model.PaymentsItems);
                    const totals = Sol.List.from(model.Totals);
                    if (!items.hasItems()) {
                        const notFoundMessage = new Sol.Control("li");
                        notFoundMessage.css.add("sol_my_payouts_nfound");
                        notFoundMessage.text = "Não há pagamentos neste mês.";
                        this.list.add(notFoundMessage);
                        return;
                    }
                    var isNational = true;
                    var curCurrency;
                    if (items.any(i => i.IsNational))
                        this.createListHeader("Pagamentos Nacionais");
                    items.forEach(i => {
                        if (curCurrency && curCurrency != i.Currency)
                            this.createTotalRow(totals.that(t => t.CurrencyISO == curCurrency).FormattedValue);
                        curCurrency = i.Currency;
                        if (isNational && !i.IsNational) {
                            this.createListHeader("Pagamentos Internacionais");
                            isNational = false;
                        }
                        const item = new Sol.Control("li");
                        this.screenCaption = Sol.Environment.resources.buscar;
                        const descriptionText = new Sol.Control("span");
                        descriptionText.text = i.Description;
                        item.add(descriptionText);
                        const bankSlipButton = new Sol.Button();
                        bankSlipButton.css.add("sol_my_payouts_bank_slip_but");
                        bankSlipButton.type = Sol.ButtonType.Custom;
                        bankSlipButton.tip = "Enviar boleto para pagamento";
                        bankSlipButton.imageCode = "&#xf093;";
                        bankSlipButton.onClick = () => this.addBankSlipUpload(i.ID, item);
                        item.add(bankSlipButton);
                        if (i.RequiresApproval) {
                            const approvalButton = new Sol.Button();
                            approvalButton.css.add("sol_my_payouts_approval_button");
                            approvalButton.type = Sol.ButtonType.Custom;
                            approvalButton.text = Sol.Environment.resources.approve;
                            approvalButton.onClick = () => this.approve(i.ID, approvalButton);
                            if (i.IsApproved)
                                this.setButtonApproved(approvalButton);
                            item.add(approvalButton);
                        }
                        const amountText = new Sol.Control("span");
                        amountText.text = i.Amount;
                        amountText.css.add("sol_my_payouts_amount");
                        if (!i.RequiresApproval)
                            amountText.css.add("sol_my_payouts_amount_nra");
                        item.add(amountText);
                        if (i.AttachmentLink) {
                            const linkText = new Sol.Control("a");
                            linkText.text = this.screenCaption = Sol.Environment.resources.attachment;
                            linkText.css.add("sol_my_payouts_a");
                            linkText.atributos.agregar("href", i.AttachmentLink);
                            linkText.atributos.agregar("target", "_blank");
                            item.add(linkText);
                        }
                        if (i.Receipt) {
                            const linkRText = new Sol.Control("a");
                            linkRText.text = this.screenCaption = Sol.Environment.resources.receipt;
                            linkRText.css.add("sol_my_payouts_a");
                            linkRText.atributos.agregar("href", i.Receipt);
                            linkRText.atributos.agregar("target", "_blank");
                            item.add(linkRText);
                        }
                        if (i.Notes) {
                            const notesText = new Sol.Control("span");
                            notesText.text = i.Notes;
                            notesText.css.add("sol_my_payouts_notes");
                            item.add(notesText);
                        }
                        this.list.add(item);
                    });
                    this.createTotalRow(totals.that(t => t.CurrencyISO == curCurrency).FormattedValue);
                }
                addBankSlipUpload(id, listItem) {
                    const uploadField = new InlineUpload();
                    uploadField.onUploadComplete = e => this.bankSlipUploadComplete(id, listItem, e);
                    listItem.add(uploadField);
                }
                approve(id, button) {
                    if (!confirm("Confirma que deseja aprovar o pagamento?"))
                        return;
                    Web.System.exec("oiqw72mc", "Approve", { id: id }, () => this.setButtonApproved(button));
                }
                bankSlipUploadComplete(id, listItem, uploadField) {
                    Web.System.exec("oiqw72mc", "Upload", { id: id, file: uploadField.value }, () => {
                        listItem.controls.remove(uploadField);
                        const successMessage = new Sol.Control();
                        successMessage.css.add("sol_my_payouts_upload_success");
                        successMessage.text = "Boleto enviado com sucesso";
                        listItem.controls.add(successMessage);
                        setTimeout(() => listItem.controls.remove(successMessage), 3000);
                    });
                }
                search() {
                    const requestData = {
                        month: this.monthYearField.selectedMonth,
                        year: this.monthYearField.selectedYear
                    };
                    Web.System.exec("oiqw72mc", "GetMyPayments", requestData, e => {
                        this.fillList(e);
                        this.drawChart(e);
                    });
                }
                setButtonApproved(button) {
                    button.text = Sol.Environment.resources.approved;
                    button.enabled = false;
                    button.css.add("sol_my_payouts_approved_button");
                }
            }
            Screens.MyPayoutsScreen = MyPayoutsScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class OptionalFile extends Screens.Registro {
                constructor() {
                    super();
                    this.forceSubtype = true;
                }
                instantiateDetailsScreen() { return new Screens.OptionalDetails(); }
            }
            Screens.OptionalFile = OptionalFile;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ParametersScreen extends Screens.DetailsScreen {
                constructor() {
                    super();
                    this.showSaveAndNew = false;
                    this.showLeftPanel = true;
                    this.disableConcurrencyCheck = true;
                    this.closingAlertEnabled = false;
                    this.useDefaultValueSelectors = false;
                    this.customTitle = true;
                }
                build() {
                    const model = this.model;
                    if (model.ScreenTitle) {
                        this.screenCaption = Sol.Environment.resources.configuraciones + Sol.Environment.resources.de + model.ScreenTitle;
                        this.screenTitle.text = this.screenCaption;
                    }
                    super.build();
                    this.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    this.onSaved.subscribe(() => Web.System.screens.closeCurrentScreen());
                }
            }
            Screens.ParametersScreen = ParametersScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Education;
            (function (Education) {
                class StudentHistory extends Sol.Control {
                    constructor() {
                        super();
                        this.grid = new Components.Grid();
                        this.isComplex = true;
                    }
                    build() {
                        super.build();
                        this.createGrid();
                        this.getEnrollments();
                    }
                    createGrid() {
                        this.grid.columns.add({
                            Title: Sol.Environment.resources.initialDate,
                            DataType: "SDate",
                            PropertyName: "Course$Fecha",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.grid.columns.add({
                            Title: Sol.Environment.resources.finalDate,
                            DataType: "SDate",
                            PropertyName: "Course$FechaFinal",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.grid.columns.add({
                            Title: Sol.Environment.resources.course,
                            DataType: "SText",
                            PropertyName: "Course$Curso$Nombre",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.grid.columns.add({
                            Title: Sol.Environment.resources.class,
                            DataType: "SText",
                            PropertyName: "Course$Title",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.grid.columns.add({
                            Title: Sol.Environment.resources.status,
                            DataType: "SText",
                            PropertyName: "Status$Nombre",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.grid.showChecks = false;
                        this.grid.fixedRows = false;
                        this.add(this.grid);
                    }
                    getEnrollments() {
                        var data = {
                            className: "Solarium.Education.DistanceEnrollment, Solarium.Education, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            currentPage: 0,
                            rowCount: 100,
                            filters: [{
                                    PropertyName: "Destinatario",
                                    FilterValue: this.studentCode,
                                    FilterType: "SInteger"
                                }],
                            sortProperty: "Course$Fecha",
                            sortOrder: Web.Ordering.ascending,
                            properties: ["ID", "Status$Nombre", "Status$Color", "Course$Title", "Course$Fecha", "Course$FechaFinal", "Course$Curso$Nombre"],
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", data, model => {
                            this.grid.loadData(model);
                        }, null);
                    }
                    clear() { throw new Error("Method not implemented."); }
                    foco() { throw new Error("Method not implemented."); }
                    isEmpty() { return false; }
                    toControl() { return this; }
                    validate() { if (this.studentCode == null)
                        return "Código do estudante não informado!"; }
                }
                Education.StudentHistory = StudentHistory;
            })(Education = Components.Education || (Components.Education = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let ConfirmationTarget;
            (function (ConfirmationTarget) {
                ConfirmationTarget[ConfirmationTarget["BackToHome"] = 0] = "BackToHome";
                ConfirmationTarget[ConfirmationTarget["NextLesson"] = 1] = "NextLesson";
            })(ConfirmationTarget = Screens.ConfirmationTarget || (Screens.ConfirmationTarget = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class MultipleChoiceQuestion extends Sol.Control {
                build() {
                    super.build();
                    var optionsArray = eval(this.data);
                    var options = Sol.List.from(optionsArray);
                    options.forEach(option => {
                        var id = option[1]["Valor"];
                        var text = option[0]["Valor"];
                        var radio = new Sol.RadioField();
                        radio.caption = text;
                        radio.group = "question";
                        radio.codigo = id.toString();
                        this.add(radio);
                    });
                }
                getAnswer() {
                    return {
                        Question: this.number,
                        Answer: parseInt(this.controls.cast().that(c => c.checked).codigo)
                    };
                }
                isEmpty() {
                    return !this.controls.cast().any(radio => radio.checked);
                }
                toControl() { return this; }
            }
            Screens.MultipleChoiceQuestion = MultipleChoiceQuestion;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let QuestionType;
            (function (QuestionType) {
                QuestionType[QuestionType["MultipleChoice"] = 0] = "MultipleChoice";
            })(QuestionType = Screens.QuestionType || (Screens.QuestionType = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class EvaluationDialog extends Sol.DialogBox {
                set evaluationText(text) {
                    this.contentArea.text = text;
                }
                constructor() {
                    super();
                    this.title = "Minha avaliação";
                    this.createBlocker();
                }
            }
            Screens.EvaluationDialog = EvaluationDialog;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ExamScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.questionArea = new Sol.Control();
                    this.currentQuestion = 1;
                    this.answers = new Sol.List();
                }
                build() {
                    super.build();
                    this.myModel = this.model;
                    this.css.add("exam_screen");
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                    this.questionArea.css.add("exam_screen_question_area");
                    this.add(this.questionArea);
                    this.showQuestion();
                }
                showQuestion() {
                    var question = this.myModel.Questions[this.currentQuestion - 1];
                    this.questionArea.controls.empty();
                    var questionTitle = new Sol.Control("h5");
                    questionTitle.text = Sol.Environment.resources.question + ' ' +
                        question.QuestionNumber.toString() +
                        Sol.Environment.resources.de +
                        this.myModel.Questions.length.toString();
                    this.questionArea.add(questionTitle);
                    if (this.myModel.MinHitsText) {
                        const minHitsAdvise = new Sol.Control();
                        minHitsAdvise.css.add("exam_screen_min_hits");
                        minHitsAdvise.text = this.myModel.MinHitsText;
                        this.questionArea.add(minHitsAdvise);
                    }
                    var questionText = new Sol.Control("p");
                    questionText.text = question.Text;
                    this.questionArea.add(questionText);
                    this.questionControl = this.createQuestion(question.Type);
                    this.questionControl.number = question.QuestionNumber;
                    this.questionControl.data = question.QuestionData;
                    this.questionArea.add(this.questionControl.toControl());
                    this.emptyMessage = new Sol.ScreenMessage();
                    this.emptyMessage.caption = Sol.Environment.resources.empty_answer;
                    this.emptyMessage.type = Sol.MessageType.Error;
                    this.emptyMessage.visible = false;
                    this.questionArea.add(this.emptyMessage);
                    var nextButton = new Sol.Button();
                    nextButton.css.add("exam_screen_next_button");
                    nextButton.type = Sol.ButtonType.Custom;
                    nextButton.text = this.isLastQuestion() ? Sol.Environment.resources.finish : Sol.Environment.resources.next;
                    nextButton.onClick = () => this.next();
                    this.questionArea.add(nextButton);
                }
                showResult(result) {
                    this.questionArea.controls.empty();
                    var resultTitle = new Sol.Control("h5");
                    resultTitle.text = Sol.Environment.resources.finish_exam;
                    this.questionArea.add(resultTitle);
                    var resultText = new Sol.Control("p");
                    resultText.text = Sol.Environment.resources.hits.replace("{0}", result.Hits).replace("{1}", result.QuestionCount);
                    this.questionArea.add(resultText);
                    if (result.Approved) {
                        const approvedText = new Sol.Control("p");
                        approvedText.css.add("exam_screen_approved_exam");
                        approvedText.text = Sol.Environment.resources.approvedCourse;
                        this.questionArea.add(approvedText);
                    }
                    else {
                        const failedText = new Sol.Control("p");
                        failedText.css.add("exam_screen_failed_exam");
                        failedText.text = Sol.Environment.resources.failedCourse;
                        this.questionArea.add(failedText);
                    }
                    var closeButton = new Sol.Button();
                    closeButton.css.add("exam_screen_next_button");
                    closeButton.type = Sol.ButtonType.Custom;
                    closeButton.text = Sol.Environment.resources.cerrar;
                    closeButton.onClick = () => {
                        this.parentScreen.showExamDone();
                        Web.System.screens.closeCurrentScreen();
                    };
                    this.questionArea.add(closeButton);
                }
                next() {
                    this.emptyMessage.visible = false;
                    if (this.questionControl.isEmpty()) {
                        this.emptyMessage.visible = true;
                        return;
                    }
                    this.answers.add(this.questionControl.getAnswer());
                    if (this.isLastQuestion()) {
                        var data = {
                            Credential: Sol.Environment.credential.export(),
                            Enrollment: this.parentScreen.enrollmentID,
                            Exam: this.parentScreen.myModel.Exam.ID,
                            Answers: this.answers.toArray()
                        };
                        Web.System.exec("laspoesd", "FinishExam", data, e => this.showResult(e), null);
                    }
                    else {
                        this.currentQuestion++;
                        this.showQuestion();
                    }
                }
                isLastQuestion() {
                    return this.currentQuestion == this.myModel.Questions.length;
                }
                createQuestion(type) {
                    if (type == Screens.QuestionType.MultipleChoice)
                        return new Screens.MultipleChoiceQuestion();
                    return null;
                }
            }
            Screens.ExamScreen = ExamScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class EventAccreditation extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.successMessage = new Sol.ScreenMessage();
                    this.cityRequiredMessage = new Sol.ScreenMessage();
                    this.cityCombo = new Web.Components.Selectors.Selector();
                    this.resultsList = new Web.Components.ListView();
                    this.functionCombo = new Sol.MultipleCombo();
                    this.nameField = new Sol.Field();
                    this.professionField = new Sol.Field();
                    this.screenTitle = new Screens.ScreenTitle();
                    this.eventName = new Sol.Control("h1");
                    this.add(this.screenTitle);
                    this.eventName.css.add("event_accreditation_name");
                    this.add(this.eventName);
                    var wrapper = new Sol.Control();
                    wrapper.estilos.agregar("padding", "10px");
                    this.add(wrapper);
                    this.successMessage.caption = "Participante confirmado com sucesso!";
                    this.successMessage.type = Sol.MessageType.Success;
                    this.successMessage.visible = false;
                    this.successMessage.estilos.agregar("margin", "10px 0px");
                    wrapper.add(this.successMessage);
                    this.cityRequiredMessage.caption = "Escolha o município por favor";
                    this.cityRequiredMessage.type = Sol.MessageType.Error;
                    this.cityRequiredMessage.visible = false;
                    this.cityRequiredMessage.estilos.agregar("margin", "10px 0px");
                    wrapper.add(this.cityRequiredMessage);
                    var cityLabel = new Sol.Label();
                    cityLabel.text = "Município:";
                    wrapper.add(cityLabel);
                    this.cityCombo.className = "Solarium.Geo.Ciudad, Solarium.Geo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.cityCombo.onFiltering = () => Sol.List.from([
                        {
                            PropertyName: "Estado",
                            FilterValue: {
                                Campo: "Estado",
                                Valor: 269
                            },
                            FilterType: ""
                        },
                        {
                            PropertyName: "Nombre",
                            FilterValue: this.cityCombo.selectedText,
                            FilterType: "SLocalText"
                        }
                    ]);
                    wrapper.add(this.cityCombo);
                    var functionLabel = new Sol.Label();
                    functionLabel.text = "Cargo:";
                    functionLabel.estilos.agregar("margin-top", "4px");
                    wrapper.add(functionLabel);
                    wrapper.add(this.functionCombo);
                    wrapper.add(new Sol.LineBreak());
                    var searchButton = new Sol.Button();
                    searchButton.estilos.agregar("margin", "4px 0px 8px 0px");
                    searchButton.text = "Pesquisar";
                    searchButton.onClick = () => this.search();
                    wrapper.add(searchButton);
                    this.resultsList.className = "Solarium.Política.GestiónPública, Solarium.Government, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.resultsList.orderByProperty = "Autoridad";
                    this.resultsList.configuration = Sol.List.from([
                        {
                            loadable: false,
                            property: "SelectCommand",
                            defaultText: "Confirmar presença",
                            position: Web.Components.ListViewFieldPosition.Right,
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            cssClass: "sol_boton"
                        },
                        {
                            loadable: false,
                            property: "PrintCommand",
                            defaultText: "Imprimir Credencial",
                            position: Web.Components.ListViewFieldPosition.Right,
                            priority: Web.Components.ListViewFieldPriority.Normal,
                            cssClass: "sol_boton"
                        },
                        {
                            loadable: true,
                            property: "Autoridad",
                            priority: Web.Components.ListViewFieldPriority.High,
                            position: Web.Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "Cargo",
                            lineBreak: true,
                            position: Web.Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "Institución",
                            position: Web.Components.ListViewFieldPosition.Left,
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "Autoridad$EntidadRelacionada$ID",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "Institución$EntidadRelacionada$Dirección$Ciudad",
                            hidden: true
                        },
                        {
                            loadable: true,
                            property: "Institución$EntidadRelacionada$Dirección$Ciudad$Nombre",
                            hidden: true
                        }
                    ]);
                    this.resultsList.onInstantiateItem = i => this.instantiateItem(i);
                    wrapper.add(this.resultsList);
                    var titleRegister = new Sol.Control();
                    titleRegister.text = "Cadastro Rápido";
                    titleRegister.css.add("title_register");
                    wrapper.add(titleRegister);
                    var newPersonLabel = new Sol.Label();
                    newPersonLabel.text = "Cadastro de novo participante:";
                    newPersonLabel.estilos.agregar("margin-top", "15px");
                    wrapper.add(newPersonLabel);
                    this.nameField.maxLength = 85;
                    this.nameField.placeHolder = "Nome do participante";
                    wrapper.add(this.nameField);
                    wrapper.add(new Sol.LineBreak());
                    this.professionField.maxLength = 50;
                    this.professionField.placeHolder = "Cargo/Profissão";
                    wrapper.add(this.professionField);
                    wrapper.add(new Sol.LineBreak());
                    var newPersonButton = new Sol.Button();
                    newPersonButton.estilos.agregar("margin", "4px 0px 8px 0px");
                    newPersonButton.text = "Cadastrar";
                    newPersonButton.onClick = () => this.saveNewPerson();
                    wrapper.add(newPersonButton);
                }
                build() {
                    super.build();
                    this.myModel = this.model;
                    this.screenCaption = this.myModel.ScreenTitle;
                    this.screenTitle.text = this.screenCaption;
                    this.eventName.text = this.myModel.EventName;
                    this.functionCombo.setOptions(this.myModel.FunctionOptions);
                }
                search() {
                    this.successMessage.visible = false;
                    this.cityRequiredMessage.visible = false;
                    if (this.cityCombo.isEmpty()) {
                        this.cityRequiredMessage.visible = true;
                        return;
                    }
                    var filters = new Sol.List();
                    filters.add({
                        PropertyName: "Institución$EntidadRelacionada$Dirección$Ciudad",
                        FilterValue: this.cityCombo.value,
                        FilterType: ""
                    });
                    filters.add({
                        PropertyName: "FiltroActivos",
                        FilterValue: { Campo: "FiltroActivos", Valor: 1 },
                        FilterType: ""
                    });
                    if (!this.functionCombo.isEmpty())
                        filters.add({
                            PropertyName: "Cargo",
                            FilterValue: this.functionCombo.value,
                            FilterType: "Cargo"
                        });
                    this.resultsList.clear();
                    this.resultsList.filters = filters.toArray();
                    this.resultsList.search();
                }
                instantiateItem(item) {
                    var person = item.getModelValue("Autoridad$EntidadRelacionada$ID");
                    var occupation = item.getModelValue("Cargo");
                    var city = item.getModelValue("Institución$EntidadRelacionada$Dirección$Ciudad$Nombre");
                    var name = item.getModelValue("Autoridad");
                    var selectCommand = item.getDisplay("SelectCommand");
                    selectCommand.onClick = () => this.selectPerson(person);
                    var printCommand = item.getDisplay("PrintCommand");
                    printCommand.onClick = () => this.printAccreditation(occupation.Campo, city, name.Campo);
                }
                printAccreditation(occupation, city, name) {
                    var win = window.open("", "_blank");
                    var cssLink = new Sol.Control("link");
                    cssLink.atributos.agregar("rel", "stylesheet");
                    cssLink.atributos.agregar("type", "text/css");
                    cssLink.atributos.agregar("href", window.location.href + "theme/accreditation_label.css");
                    cssLink.abrir();
                    win.document.head.innerHTML = cssLink.html.outerHTML;
                    var label = new Sol.Control();
                    var occupationDiv = new Sol.Control();
                    var cityDiv = new Sol.Control();
                    var nameDiv = new Sol.Control();
                    occupationDiv.css.add("label_occupation");
                    cityDiv.css.add("label_city");
                    nameDiv.css.add("label_name");
                    occupationDiv.text = occupation;
                    cityDiv.text = city;
                    nameDiv.text = name;
                    label.controls.addMany([occupationDiv, cityDiv, nameDiv]);
                    label.abrir();
                    win.document.body.innerHTML = label.html.outerHTML;
                }
                selectPerson(person) {
                    this.successMessage.visible = false;
                    this.cityRequiredMessage.visible = false;
                    var savingData = {
                        className: "Solarium.Education.Enrollment, Solarium.Education, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        id: 0,
                        data: [
                            { Campo: "Emisor", Valor: Sol.Environment.credential.empresa },
                            { Campo: "Destinatario", Valor: person },
                            { Campo: "Course", Valor: this.myModel.Code },
                            { Campo: "Status", Valor: this.myModel.Status }
                        ],
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", savingData, model => {
                        var result = model;
                        if (result.Fail) {
                            alert(result.ErrorMessage);
                            return;
                        }
                        this.successMessage.visible = true;
                    }, null);
                }
                saveNewPerson() {
                    this.successMessage.visible = false;
                    this.cityRequiredMessage.visible = false;
                    if (this.nameField.isEmpty()) {
                        alert("Informe o nome por favor");
                        return;
                    }
                    if (this.professionField.isEmpty()) {
                        alert("Informe o cargo ou profissão por favor");
                        return;
                    }
                    var savingData = {
                        className: "Solarium.Persona, Solarium.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        id: 0,
                        data: [
                            { Campo: "Nombre", Valor: this.nameField.value },
                            { Campo: "Profession", Valor: this.professionField.value }
                        ],
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", savingData, result => {
                        if (result.Fail) {
                            alert(result.ErrorMessage);
                            return;
                        }
                        var savingData2 = {
                            className: "Solarium.Education.Enrollment, Solarium.Education, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            id: 0,
                            data: [
                                { Campo: "Emisor", Valor: Sol.Environment.credential.empresa },
                                { Campo: "Destinatario", Valor: result.ID },
                                { Campo: "Course", Valor: this.myModel.Code },
                                { Campo: "Status", Valor: this.myModel.Status }
                            ],
                            lastUpdate: null
                        };
                        Web.System.exec("3b5v9v45", "Save", savingData2, result2 => {
                            if (result2.Fail) {
                                alert(result.ErrorMessage);
                                return;
                            }
                            this.successMessage.visible = true;
                            this.nameField.clear();
                            this.professionField.clear();
                        }, null);
                    }, null);
                }
            }
            Screens.EventAccreditation = EventAccreditation;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class StudentPresence extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.list = new Web.Components.ListView();
                    this.classroomLabel = new Sol.Label();
                    this.classroomSelector = new Web.Components.Selectors.CourseSelector();
                    this.date = new Sol.DateField();
                    this.dateLabel = new Sol.Label();
                    this.messageCourseIsNull = new Sol.ScreenMessage();
                    this.messageError = new Sol.ScreenMessage();
                    this.screenCaption = Sol.Environment.resources.presence_list;
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                    this.add(this.messageError);
                    this.add(this.messageCourseIsNull);
                    this.hideMessages();
                    var content = new Sol.Control();
                    content.css.add("sol_presence_screen");
                    this.classroomLabel.text = Sol.Environment.resources.classroom;
                    this.classroomSelector.autoWidth = false;
                    content.add(this.classroomLabel);
                    content.add(this.classroomSelector);
                    this.dateLabel.text = Sol.Environment.resources.date;
                    content.add(this.dateLabel);
                    this.dateLabel.editor = this.date;
                    this.date.css.add("date_input");
                    this.date.setToday();
                    content.add(this.date);
                    content.add(new Sol.LineBreak);
                    var searchButton = new Sol.Button();
                    searchButton.text = Sol.Environment.resources.buscar;
                    searchButton.onClick = () => this.listStudents();
                    content.add(searchButton);
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: false,
                            property: "CheckCommand",
                            defaultText: Sol.Environment.resources.absent,
                            position: Web.Components.ListViewFieldPosition.Right,
                            priority: Web.Components.ListViewFieldPriority.High,
                            cssClass: "record_status",
                        },
                        {
                            loadable: true,
                            property: "Name",
                            position: Web.Components.ListViewFieldPosition.Left,
                            priority: Web.Components.ListViewFieldPriority.High,
                        }
                    ]);
                    this.list.onInstantiateItem = i => this.instantiateItem(i);
                    content.add(this.list);
                    this.add(content);
                }
                hideMessages() {
                    this.messageError.visible = false;
                    this.messageCourseIsNull.visible = false;
                }
                instantiateItem(item) {
                    var isPresent = item.getModelValue("IsPresent");
                    var checkCommand = item.getDisplay("CheckCommand");
                    checkCommand.text = isPresent ? Sol.Environment.resources.present : Sol.Environment.resources.absent;
                    item.checked = isPresent;
                    item.data = item.getModelValue("Presence");
                    if (isPresent)
                        checkCommand.css.add("record_status_checked");
                    checkCommand.onClick = () => {
                        item.checked = !item.checked;
                        if (item.checked) {
                            var saveModel = {
                                className: "Solarium.Education.StudentPresence, Solarium.Education, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                id: 0,
                                data: [{ Campo: "Student", Valor: item.code },
                                    { Campo: "Date", Valor: this.date.value },
                                    { Campo: "ClassRoom", Valor: this.classroomSelector.value },],
                                lastUpdate: null
                            };
                            Web.System.exec("3b5v9v45", "Save", saveModel, model => {
                                item.data = model.ID;
                                checkCommand.text = Sol.Environment.resources.present;
                                checkCommand.css.add("record_status_checked");
                            }, null);
                        }
                        else {
                            var deleteModel = {
                                className: "Solarium.Education.StudentPresence, Solarium.Education, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                decisionID: null,
                                methodName: "DeleteMany",
                                selectionMode: Web.ActionSelectionMode.None,
                                filters: null,
                                ids: [item.data],
                                inputs: null
                            };
                            Web.System.exec("79k8j542h", "DoMultiple", deleteModel, () => {
                                checkCommand.text = Sol.Environment.resources.absent;
                                checkCommand.css.remove("record_status_checked");
                            }, null);
                        }
                    };
                }
                listStudents() {
                    this.list.clear();
                    this.hideMessages();
                    if (this.classroomSelector.isEmpty()) {
                        this.messageCourseIsNull.caption = Sol.Environment.resources.empty_field + this.classroomLabel.text;
                        this.messageCourseIsNull.visible = true;
                        return;
                    }
                    if (this.date.isEmpty()) {
                        this.messageCourseIsNull.caption = Sol.Environment.resources.empty_field + this.dateLabel.text;
                        this.messageCourseIsNull.visible = true;
                        return;
                    }
                    var data = {
                        Credential: Sol.Environment.credential.export(),
                        CourseID: this.classroomSelector.selectedCode,
                        Date: this.date.value
                    };
                    Web.System.exec("laspoesd", "ListStudents", data, e => {
                        if (!e.Fail)
                            this.list.addItems(e.Students, e.IDs);
                        else {
                            this.messageError.caption = e.ErrorMessage;
                            this.messageError.visible = true;
                        }
                    }, null);
                }
            }
            Screens.StudentPresence = StudentPresence;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class StudentAttendanceSheet extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.classroomLabel = new Sol.Label();
                    this.classroomSelector = new Web.Components.Selectors.CourseSelector();
                    this.hourClass = new Sol.Control("span");
                    this.hourLabel = new Sol.Control("span");
                    this.messageError = new Sol.ScreenMessage();
                    this.messageCourseIsEmpty = new Sol.ScreenMessage();
                    this.monthYear = new Sol.MonthYearField();
                    this.sheet = new Sol.Control("table");
                    this.teacher = new Sol.Control("span");
                    this.teacherLabel = new Sol.Control("span");
                    this.screenCaption = Sol.Environment.resources.attendance_sheet;
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                    var content = new Sol.Control();
                    content.css.add("sol_presence_screen");
                    content.add(this.messageError);
                    content.add(this.messageCourseIsEmpty);
                    this.hideMessages();
                    this.classroomLabel.text = Sol.Environment.resources.classroom;
                    content.add(this.classroomLabel);
                    content.add(this.classroomSelector);
                    this.classroomSelector.autoWidth = false;
                    content.add(this.monthYear);
                    var searchButton = new Sol.Button();
                    searchButton.text = Sol.Environment.resources.buscar;
                    searchButton.onClick = () => this.attendanceSheet();
                    content.add(searchButton);
                    var contentInfoClass = new Sol.Control();
                    contentInfoClass.estilos.agregar("margin-top", "5px");
                    content.add(contentInfoClass);
                    this.teacherLabel.text = Sol.Environment.resources.teacher + ": ";
                    contentInfoClass.add(this.teacherLabel);
                    this.teacherLabel.visible = false;
                    this.teacher.css.add("info_class");
                    contentInfoClass.add(this.teacher);
                    this.hourLabel.text = "Horário: ";
                    contentInfoClass.add(this.hourLabel);
                    this.hourLabel.visible = false;
                    this.hourClass.css.add("info_class");
                    contentInfoClass.add(this.hourClass);
                    this.sheet.css.add("table_attendance");
                    content.add(this.sheet);
                    this.add(content);
                }
                hideMessages() {
                    this.messageCourseIsEmpty.visible = false;
                    this.messageError.visible = false;
                }
                refreshTable(model) {
                    this.sheet.visible = true;
                    this.sheet.controls.empty();
                    var attendances = Sol.List.from(model.Attendances);
                    let isFuture = Sol.List.from(model.Days).all(d => d.IsFuture);
                    var header = new Sol.Control("tr");
                    header.css.add("header_table");
                    var studentName = new Sol.Control("td");
                    studentName.text = Sol.Environment.resources.student;
                    header.controls.add(studentName);
                    header.controls.addMany(Sol.List.from(model.Days).select(day => this.createCell(day.Day.toString())));
                    header.add(this.createCell("P"));
                    header.add(this.createCell("F"));
                    this.sheet.add(header);
                    this.sheet.controls.addMany(Sol.List.from(model.Students).select(student => {
                        var attendance = new Sol.List();
                        var studentRow = new Sol.Control("tr");
                        studentRow.data = student.ID;
                        var studentCell = new Sol.Control("td");
                        studentCell.text = student.Name;
                        studentRow.add(studentCell);
                        studentRow.controls.addMany(Sol.List.from(model.Days)
                            .select(day => {
                            var isPresent = attendances.any(i => i.Day == day.Day && i.StudentID == student.ID);
                            if (!day.IsFuture)
                                attendance.add(isPresent);
                            return this.createCell(day.IsFuture ? ' ' : isPresent ? '·' : 'F');
                        }));
                        let p = attendance.where(p => p).count.toString();
                        var pCell = this.createCell(isFuture ? ' ' : p);
                        pCell.estilos.agregar("color", "#468621");
                        let f = attendance.where(p => !p).count.toString();
                        var fCell = this.createCell(isFuture ? ' ' : f);
                        fCell.estilos.agregar("color", "#6d1919");
                        studentRow.add(pCell);
                        studentRow.add(fCell);
                        return studentRow;
                    }));
                }
                createCell(text) {
                    var dayHeader = new Sol.Control("td");
                    dayHeader.text = text;
                    return dayHeader;
                }
                attendanceSheet() {
                    this.hideMessages();
                    if (this.classroomSelector.isEmpty()) {
                        this.messageCourseIsEmpty.caption = Sol.Environment.resources.empty_field + this.classroomLabel.text;
                        this.messageCourseIsEmpty.visible = true;
                    }
                    const data = {
                        Credential: Sol.Environment.credential.export(),
                        CourseID: this.classroomSelector.selectedCode,
                        Month: this.monthYear.selectedMonth,
                        Year: this.monthYear.selectedYear
                    };
                    Web.System.exec("laspoesd", "AttendanceSheet", data, e => {
                        if (e.Fail) {
                            this.sheet.visible = false;
                            this.messageError.caption = e.ErrorMessage;
                            this.messageError.visible = true;
                        }
                        else {
                            this.myModel = e;
                            this.teacherLabel.visible = true;
                            this.teacher.text = this.myModel.Teacher;
                            this.hourLabel.visible = true;
                            this.hourClass.text = this.myModel.Hour;
                            this.refreshTable(e);
                        }
                    }, null);
                }
            }
            Screens.StudentAttendanceSheet = StudentAttendanceSheet;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class SqlScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.main = new Sol.Control();
                    this.queryField = new Sol.TextField();
                    this.runButton = new Sol.Button();
                    this.resultArea = new Sol.Control();
                    this.screenCaption = "SQL Editor";
                    this.main.css.add("sol_sql");
                    var title = new Screens.ScreenTitle();
                    title.text = this.screenCaption;
                    this.add(title);
                    this.add(this.main);
                    const queryLabel = new Sol.Label();
                    queryLabel.text = "Enter query:";
                    this.main.add(queryLabel);
                    this.queryField.autoHeight = false;
                    this.main.add(this.queryField);
                    this.runButton.text = "Execute";
                    this.runButton.onClick = () => this.runQuery();
                    this.main.add(this.runButton);
                    const resultLabel = new Sol.Label();
                    resultLabel.text = "Result:";
                    this.main.add(resultLabel);
                    this.resultArea.css.add("sol_sql_result");
                    this.main.add(this.resultArea);
                    this.queryField.spellCheck = false;
                }
                runQuery() {
                    if (!this.queryField.selectedText) {
                        alert("The query field is empty");
                        return;
                    }
                    this.runButton.enabled = false;
                    this.resultArea.estilos.remove("color");
                    Web.System.exec("7aDjh29kh", "RunScript", { script: this.queryField.selectedText }, e => {
                        if (e.Fail) {
                            this.resultArea.estilos.definir("color", "#b50e14");
                            this.resultArea.text = e.ErrorMessage;
                        }
                        else
                            this.resultArea.htmlContent = e.HtmlResult;
                        this.runButton.enabled = true;
                    });
                }
            }
            Screens.SqlScreen = SqlScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class DBAScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.body = new Sol.Control("div");
                    this.loader = new Sol.Loader();
                    this.messageSuccess = new Sol.ScreenMessage();
                    this.messageError = new Sol.ScreenMessage();
                    this.messageSyncError = new Sol.ScreenMessage();
                    this.messageSyncSuccess = new Sol.ScreenMessage();
                    this.syncButton = new Sol.Button();
                    this.recreateViewsButton = new Sol.Button();
                    this.sqlEditorButton = new Sol.Button();
                    this.schemaAnalyzerButton = new Sol.Button();
                    this.screenCaption = "DBA Solarium";
                    this.body.css.add("sol_dba");
                    var title = new Screens.ScreenTitle();
                    title.text = this.screenCaption;
                    this.add(title);
                    this.add(this.body);
                    this.messageSyncSuccess.type = Sol.MessageType.Success;
                    this.messageSyncSuccess.caption = Sol.Environment.resources.message_success_sync_dba;
                    this.messageSyncSuccess.visible = false;
                    this.add(this.messageSyncSuccess);
                    this.messageSyncError.type = Sol.MessageType.Error;
                    this.messageSyncError.caption = Sol.Environment.resources.message_error_sync_dba;
                    this.messageSyncError.visible = false;
                    this.messageSyncError.closeWhenTap = false;
                    this.add(this.messageSyncError);
                    this.messageSuccess.type = Sol.MessageType.Success;
                    this.messageSuccess.caption = Sol.Environment.resources.message_success_dba;
                    this.messageSuccess.visible = false;
                    this.add(this.messageSuccess);
                    this.messageError.type = Sol.MessageType.Error;
                    this.messageError.caption = Sol.Environment.resources.message_error_dba;
                    this.messageError.visible = false;
                    this.add(this.messageError);
                    this.createImage();
                    this.createButtons();
                    this.add(this.loader);
                }
                hideMessages() {
                    this.messageSyncSuccess.visible = false;
                    this.messageSyncError.visible = false;
                    this.messageSuccess.visible = false;
                    this.messageError.visible = false;
                }
                createImage() {
                    var dba = new Sol.ImageBox();
                    dba.source = "/Theme/Resources/dba.jpg";
                    dba.imagenWidth = 280;
                    dba.imagenHeight = 240;
                    this.body.add(dba);
                }
                createButtons() {
                    var divSync = new Sol.Control("div");
                    divSync.css.add("sol_dba_sync");
                    divSync.text = "Sincronização";
                    this.body.add(divSync);
                    this.syncButton.imageCode = "&#xf021;";
                    this.syncButton.text = "Sincronizar banco de dados";
                    this.syncButton.onClick = () => this.syncClick("Sync");
                    divSync.add(this.syncButton);
                    this.recreateViewsButton.imageCode = "&#xf009;";
                    this.recreateViewsButton.text = "Recriar views";
                    this.recreateViewsButton.onClick = () => this.syncClick("RecreateViews");
                    divSync.add(this.recreateViewsButton);
                    this.sqlEditorButton.imageCode = "&#xf121;";
                    this.sqlEditorButton.text = "Abrir o Editor SQL";
                    this.sqlEditorButton.onClick = () => Web.System.screens.openScreenWithModel("SqlScreen", "&#xf121;", null);
                    divSync.add(this.sqlEditorButton);
                    this.schemaAnalyzerButton.imageCode = "&#xf0ce;";
                    this.schemaAnalyzerButton.text = "Schema Analyzer";
                    this.schemaAnalyzerButton.onClick = () => Web.System.screens.openScreen("Registro", "Solarium.Installation.DBObject, Solarium.Installation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                    divSync.add(this.schemaAnalyzerButton);
                }
                syncClick(method) {
                    if (confirm("Deseja prosseguir?") == true) {
                        this.hideMessages();
                        this.syncButton.enabled = false;
                        this.recreateViewsButton.enabled = false;
                        this.sqlEditorButton.enabled = false;
                        this.schemaAnalyzerButton.enabled = false;
                        this.loader.visible = true;
                        Web.System.exec("7aDjh29kh", method, null, response => {
                            if (!response.Fail)
                                this.messageSyncSuccess.visible = true;
                            else {
                                this.messageSyncError.caption = response.ErrorMessage;
                                this.messageSyncError.visible = true;
                            }
                            this.syncButton.enabled = true;
                            this.recreateViewsButton.enabled = true;
                            this.schemaAnalyzerButton.enabled = true;
                            this.sqlEditorButton.enabled = true;
                            this.loader.visible = false;
                        });
                    }
                }
            }
            Screens.DBAScreen = DBAScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class PdfScreen extends Screens.BaseScreen {
                build() {
                    super.build();
                    var model = this.model;
                    this.screenCaption = model.title;
                    this.css.add("pdf_screen");
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                    const pdfToolBar = new Sol.Control();
                    pdfToolBar.css.add("sol_barra_herramientas");
                    this.add(pdfToolBar);
                    var backButton = new Sol.Button();
                    backButton.text = Sol.Environment.resources.back;
                    backButton.type = Sol.ButtonType.Custom;
                    backButton.imageCode = '&#xf060;';
                    backButton.onClick = () => Web.System.screens.closeCurrentScreen();
                    pdfToolBar.add(backButton);
                    var pdfViewer = new Sol.WebComponents.PdfViewer();
                    pdfViewer.source = model.url;
                    this.add(pdfViewer);
                }
            }
            Screens.PdfScreen = PdfScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class MonitoringScreen extends Screens.DashboardScreen {
                initializeRefreshButton() { }
            }
            Screens.MonitoringScreen = MonitoringScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class Settings extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.css.add("sol_settings");
                    this.screenCaption = Sol.Environment.resources.configuraciones;
                    var title = new Screens.ScreenTitle();
                    title.text = this.screenCaption;
                    this.add(title);
                }
                build() {
                    super.build();
                    let model = this.model;
                    let icons = Sol.List.from(model.Icons);
                    var generalIcons = icons.where(i => i.Category == Web.SettingsCategory.General);
                    if (generalIcons.hasItems()) {
                        this.add(new Screens.DashboardSeparator(model.Headers[Web.SettingsCategory.General]));
                        generalIcons.forEach(i => {
                            var tile = Web.Components.Icons.BaseIcon.fromMenu(i);
                            tile.backToHomeWhenClick = false;
                            this.add(tile);
                        });
                    }
                    var parametersIcons = icons.where(i => i.Category == Web.SettingsCategory.Parameters);
                    if (parametersIcons.hasItems()) {
                        this.add(new Screens.DashboardSeparator(model.Headers[Web.SettingsCategory.Parameters]));
                        parametersIcons.forEach(i => {
                            var tile = Web.Components.Icons.BaseIcon.fromMenu(i);
                            tile.backToHomeWhenClick = false;
                            this.add(tile);
                        });
                    }
                    var availableFieldsIcons = icons.where(i => i.Category == Web.SettingsCategory.AvailableFields);
                    if (availableFieldsIcons.hasItems()) {
                        this.add(new Screens.DashboardSeparator(model.Headers[Web.SettingsCategory.AvailableFields]));
                        availableFieldsIcons.forEach(i => {
                            var tile = Web.Components.Icons.BaseIcon.fromMenu(i);
                            tile.backToHomeWhenClick = false;
                            this.add(tile);
                        });
                    }
                    var modulesIcons = icons.where(i => i.Category == Web.SettingsCategory.Modules);
                    if (modulesIcons.hasItems()) {
                        this.add(new Screens.DashboardSeparator(model.Headers[Web.SettingsCategory.Modules]));
                        modulesIcons.forEach(i => {
                            var tile = Web.Components.Icons.BaseIcon.fromMenu(i);
                            tile.backToHomeWhenClick = false;
                            this.add(tile);
                        });
                    }
                    var SupportIcons = icons.where(i => i.Category == Web.SettingsCategory.Support);
                    if (SupportIcons.hasItems()) {
                        this.add(new Screens.DashboardSeparator(model.Headers[Web.SettingsCategory.Support]));
                        SupportIcons.forEach(i => {
                            var tile = Web.Components.Icons.BaseIcon.fromMenu(i);
                            tile.backToHomeWhenClick = false;
                            this.add(tile);
                        });
                    }
                    this.controls.forEach(ctr => { if (ctr instanceof Web.Components.Icons.BaseIcon)
                        ctr.refresh(); });
                }
            }
            Screens.Settings = Settings;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class GroupingScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.leftSide = new Sol.Control();
                    this.deleteConfirmation = new Sol.ScreenMessage();
                    this.editionArea = new Screens.DetailsScreen();
                    this.list = new Sol.ListField();
                    this.myModel = this.model;
                }
                build() {
                    super.build();
                    this.css.add("sol_grouping_screen");
                    this.myModel = this.model;
                    this.screenCaption = this.myModel.Title;
                    this.initializeTitle();
                    this.initializeLeftSide();
                    this.initializeForm();
                    this.refreshList();
                }
                addItem() {
                    this.deleteConfirmation.visible = false;
                    this.editionArea.clear();
                    this.editionArea.foco();
                }
                deleteItem() {
                    const deleteModel = {
                        className: this.myModel.ClassName,
                        decisionID: null,
                        methodName: "DeleteMany",
                        selectionMode: Web.ActionSelectionMode.None,
                        filters: null,
                        ids: [parseInt(this.list.selectedCode)],
                        inputs: null
                    };
                    Web.System.exec("79k8j542h", "DoMultiple", deleteModel, () => {
                        this.refreshList();
                        this.addItem();
                    }, null);
                }
                initializeTitle() {
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.myModel.Title;
                    this.add(screenTitle);
                }
                initializeLeftSide() {
                    this.leftSide.css.add("sol_grouping_screen_left");
                    this.add(this.leftSide);
                    var listLabel = new Sol.Label();
                    listLabel.text = this.myModel.ListCaption + ':';
                    listLabel.editor = this.list;
                    this.leftSide.add(listLabel);
                    this.list.onChange = () => this.itemSelected();
                    this.leftSide.add(this.list);
                    this.deleteConfirmation.visible = false;
                    this.deleteConfirmation.type = Sol.MessageType.Confirmation;
                    this.deleteConfirmation.caption = Sol.Environment.resources.confirmar_operacion + ' ' + Sol.Environment.resources.eliminar.toLowerCase() + '?';
                    this.deleteConfirmation.onConfirm = () => this.deleteItem();
                    this.deleteConfirmation.onCancel = () => this.deleteConfirmation.visible = false;
                    this.leftSide.add(this.deleteConfirmation);
                    var addButton = new Sol.Button();
                    addButton.text = Sol.Environment.resources.crear;
                    addButton.onClick = () => this.addItem();
                    this.leftSide.add(addButton);
                    var deleteButton = new Sol.Button();
                    deleteButton.text = Sol.Environment.resources.eliminar;
                    deleteButton.onClick = () => this.list.selectedCode && (this.deleteConfirmation.visible = true);
                    this.leftSide.add(deleteButton);
                }
                initializeForm() {
                    this.editionArea.showTitle = false;
                    this.editionArea.myForm.showCancelButton = false;
                    this.editionArea.model = this.myModel.DetailsModel;
                    this.editionArea.showSaveButton = true;
                    this.editionArea.showOKButton = false;
                    this.editionArea.showSaveAndNew = false;
                    this.editionArea.onLocalSaved.subscribe(e => this.refreshList(e.code));
                    this.add(this.editionArea);
                }
                itemSelected() {
                    this.deleteConfirmation.visible = false;
                    this.editionArea.load(parseInt(this.list.selectedCode));
                }
                refreshList(selectedCode = null) {
                    this.list.controls.empty();
                    this.deleteConfirmation.visible = false;
                    var data = {
                        className: this.myModel.ClassName,
                        currentPage: 1,
                        rowCount: 1000,
                        filters: [],
                        sortProperty: "SpecialName",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "SpecialName"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        var counter = 0;
                        var datos = Sol.List.from(model.Data).cast();
                        ;
                        this.list.controls.addMany(datos.select(item => {
                            var fields = Sol.List.from(item);
                            var listItem = new Sol.ComboItem();
                            listItem.code = model.Codes[counter];
                            listItem.text = fields.that(d => d.Campo == "SpecialName").Valor;
                            listItem.selected = model.Codes[counter] == selectedCode;
                            counter++;
                            return listItem;
                        }));
                    }, null);
                }
            }
            Screens.GroupingScreen = GroupingScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ExternalRegistration extends Screens.BaseScreen {
                constructor(key) {
                    super();
                    var loader = new Sol.Loader();
                    var screenArea = new Sol.Control();
                    var success = new Sol.ScreenMessage();
                    success.type = Sol.MessageType.Success;
                    success.caption = Sol.Environment.resources.register_ok;
                    success.visible = false;
                    this.add(loader);
                    this.add(success);
                    this.add(screenArea);
                    var data = { key: key, lang: Sol.Environment.language };
                    Web.System.exec("437fhuc248", "Open", data, model => {
                        Sol.Environment.credential.load(model.Credencial);
                        Sol.Environment.defaultCurrency = model.DefaultCurrency;
                        var screen = new Screens.OptionalDetails();
                        screen.showTitle = false;
                        screen.showCancelButton = false;
                        screen.model = model.DetailsModel;
                        screen.myForm.okButton.text = Sol.Environment.resources.register;
                        screen.onSaved.subscribe(() => {
                            screen.visible = false;
                            success.visible = true;
                            this.finishTicket(key, screen.code);
                        });
                        screenArea.add(screen);
                        loader.visible = false;
                    }, null);
                }
                finishTicket(key, id) {
                    var data = { key: key, lang: Sol.Environment.language, id: id };
                    Web.System.exec("437fhuc248", "Finish", data, null, null);
                }
            }
            Screens.ExternalRegistration = ExternalRegistration;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class PaymentsScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.list = new Web.Components.ListView();
                    this.totalsArea = new Sol.Control();
                    this.receiptCheck = new Sol.Check();
                    this.errorMessage = new Sol.ScreenMessage();
                    this.selectAllButton = new Sol.Button();
                    this.sucessMessage = new Sol.ScreenMessage();
                    this.saveButton = new Sol.Button();
                    this.screenCaption = Sol.Environment.resources.payments;
                    this.css.add("sol_payment_screen");
                    var screenTitle = new Screens.ScreenTitle();
                    screenTitle.text = this.screenCaption;
                    this.add(screenTitle);
                    var content = new Sol.Control();
                    content.estilos.agregar("padding", "8px");
                    var payerLabel = new Sol.Label();
                    payerLabel.text = Sol.Environment.resources.payer;
                    content.add(payerLabel);
                    const payerSelector = new Web.Components.Selectors.EntitySelector();
                    payerSelector.onItemSelected = () => this.payerSelected(payerSelector.selectedCode);
                    content.add(payerSelector);
                    this.list.className = "Solarium.Financial.FinancialRecord, Solarium.Financial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.list.messageText = "Nenhuma conta em aberto encontrada.";
                    this.list.orderByProperty = "ID";
                    this.list.onInstantiateItem = i => this.instantiateItem(i);
                    this.list.onAfterSearch = () => this.afterSearch();
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: false,
                            property: "CheckCommand",
                            defaultText: Sol.Environment.resources.open,
                            position: Web.Components.ListViewFieldPosition.Left,
                            priority: Web.Components.ListViewFieldPriority.High,
                            cssClass: "record_status",
                        },
                        {
                            loadable: true,
                            property: "DueDate",
                            position: Web.Components.ListViewFieldPosition.Left,
                            priority: Web.Components.ListViewFieldPriority.High,
                        },
                        {
                            loadable: true,
                            property: "Historic",
                            position: Web.Components.ListViewFieldPosition.Left,
                            priority: Web.Components.ListViewFieldPriority.High,
                        },
                        {
                            loadable: true,
                            property: "Amount",
                            position: Web.Components.ListViewFieldPosition.Right,
                            priority: Web.Components.ListViewFieldPriority.High,
                        }
                    ]);
                    content.add(this.list);
                    content.add(this.totalsArea);
                    this.receiptCheck.caption = Sol.Environment.resources.mail_recept;
                    content.add(this.receiptCheck);
                    this.sucessMessage.type = Sol.MessageType.Success;
                    this.sucessMessage.text = Sol.Environment.resources.grabado_ok;
                    this.sucessMessage.visible = false;
                    content.add(this.sucessMessage);
                    this.errorMessage.type = Sol.MessageType.Error;
                    this.errorMessage.visible = false;
                    content.add(this.errorMessage);
                    this.selectAllButton.text = Sol.Environment.resources.todos;
                    this.selectAllButton.enabled = false;
                    this.selectAllButton.onClick = () => this.selectAll();
                    content.add(this.selectAllButton);
                    this.saveButton.text = Sol.Environment.resources.grabar;
                    this.saveButton.onClick = () => this.save();
                    content.add(this.saveButton);
                    this.add(content);
                }
                payerSelected(id) {
                    this.errorMessage.visible = false;
                    this.sucessMessage.visible = false;
                    this.list.filters = [
                        {
                            FilterType: "SBoolean",
                            PropertyName: "UnpaidFilter",
                            FilterValue: true
                        },
                        {
                            FilterType: "Entidad",
                            PropertyName: "Entity",
                            FilterValue: id
                        }
                    ];
                    this.list.clear();
                    this.list.search();
                }
                instantiateItem(item) {
                    var checkCommand = item.getDisplay("CheckCommand");
                    checkCommand.onClick = () => {
                        item.checked = !item.checked;
                        if (item.checked) {
                            checkCommand.text = Sol.Environment.resources.paid;
                            checkCommand.css.add("record_status_checked");
                        }
                        else {
                            checkCommand.text = Sol.Environment.resources.open;
                            checkCommand.css.remove("record_status_checked");
                        }
                    };
                    var amountDisplay = item.getDisplay("Amount");
                    var isDebit = amountDisplay.text.indexOf("-") > -1;
                    amountDisplay.estilos.agregar("color", isDebit ? "#b62e2e" : "#3b4872");
                    amountDisplay.text = amountDisplay.text.replace("-", "");
                }
                save() {
                    this.errorMessage.visible = false;
                    this.sucessMessage.visible = false;
                    if (!this.list.checkedItems.hasItems()) {
                        this.errorMessage.text = Sol.Environment.resources.ningun_seleccionado;
                        this.errorMessage.visible = true;
                        return;
                    }
                    this.saveButton.enabled = false;
                    var data = {
                        credential: Sol.Environment.credential.export(),
                        codes: this.list.checkedCodes,
                        sendReceipt: this.receiptCheck.value
                    };
                    Web.System.exec("79k77hjdsh", "MakePayments", data, e => {
                        if (e.Fail) {
                            this.errorMessage.text = e.ErrorMessage;
                            this.errorMessage.visible = true;
                        }
                        else
                            this.sucessMessage.visible = true;
                        this.saveButton.enabled = true;
                        this.list.clear();
                        this.list.search();
                    }, null);
                }
                selectAll() {
                    this.list
                        .items
                        .where(item => !item.checked)
                        .forEach(item => item.getDisplay("CheckCommand").onClick());
                }
                afterSearch() {
                    this.selectAllButton.enabled = !this.list.isEmpty();
                    this.totalsArea.controls.empty();
                    if (!this.list.lastTotals)
                        return;
                    this.totalsArea.controls.addMany(Sol.List.from(this.list.lastTotals.first().Totals).select(tot => {
                        const totalRow = new Sol.Control();
                        totalRow.text = tot.FormattedValue;
                        totalRow.css.add("sol_payment_screen_total");
                        return totalRow;
                    }));
                }
            }
            Screens.PaymentsScreen = PaymentsScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class FollowupScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.form = new Sol.Form();
                    this.tab = new Sol.TabControl();
                    this.schedule = new Web.Components.Schedule(null);
                    this.showSchedule = true;
                    this.uploadControl = new Web.Components.Uploads.Upload();
                    this.messagesEditor = new Web.Components.MessagesEditor();
                    this.onFormSaved = new Sol.EventHandler();
                    this.css.add("sol_seguimientos");
                    this.schedule.loginID = Web.System.loginID;
                    this.schedule.showLoginSelector = false;
                    this.schedule.showExpandButton = false;
                    this.schedule.currentView = Web.Components.ScheduleView.Relation;
                    this.schedule.onChange = () => this.messagesEditor.refresh();
                    this.form.showOkButton = false;
                    this.form.cancelButton.text = Sol.Environment.resources.back;
                    this.form.onSave = () => this.formSaved();
                    this.form.onCancel = () => {
                        this.isCanceling = true;
                        Web.System.screens.closeCurrentScreen();
                    };
                }
                get code() { return this.messagesEditor.code; }
                set code(value) {
                    this.messagesEditor.code = value;
                    this.schedule.relationID = value;
                    this.schedule.refresh();
                }
                onCloseScreen() {
                    var _a;
                    if (!this.isCanceling)
                        this.form.onSave(this.form);
                    (_a = this.myButton) === null || _a === void 0 ? void 0 : _a.countUnreadMessages();
                    return true;
                }
                build() {
                    super.build();
                    this.add(this.form);
                    this.initUploadControl();
                    this.messagesEditor.fullScreen = !this.showSchedule;
                    this.messagesEditor.onFileDropped = () => this.tab.select("files");
                    this.form.add(this.messagesEditor);
                    if (this.showSchedule)
                        this.form.add(this.schedule);
                }
                initUploadControl() {
                    if (!this.messagesEditor.enableUploads)
                        return;
                    this.messagesEditor.uploadControl = this.uploadControl;
                    this.tab.addTab("files", Sol.Environment.resources.product_file, this.uploadControl);
                    this.tab.onTabClick = t => this.tabClicked(t);
                }
                formSaved() {
                    this.form.workComplete();
                    if (this.messagesEditor.automaticSaving && this.uploadControl.isUploading) {
                        alert(Sol.Environment.resources.uploading_loading);
                        return;
                    }
                    this.onFormSaved.invoke();
                }
                tabClicked(tab) {
                    if (this.isFilesLoaded || tab.alias != "files")
                        return;
                    const FILE_COUNT = 50;
                    var properties = Sol.List.from(["ID",
                        "RelatedFile$DownloadUrl",
                        "RelatedFile$Extensión",
                        "RelatedFile$Nombre",
                        "RelatedFile$Description",
                        "RelatedFile$Tamaño",
                        "RelatedFile$Creación",
                        "RelatedFile$Entidad$Nombre",
                        "RelatedFile$Identificador"]);
                    var datos = {
                        className: this.messagesEditor.className,
                        currentPage: 1,
                        rowCount: FILE_COUNT,
                        filters: [
                            {
                                PropertyName: this.messagesEditor.associativeProperty,
                                FilterValue: {
                                    Campo: this.messagesEditor.associativeProperty,
                                    Valor: this.code
                                },
                                FilterType: ""
                            },
                            {
                                PropertyName: "OnlyFiles",
                                FilterValue: true,
                                FilterType: ""
                            }
                        ],
                        sortProperty: "FechaHora",
                        sortOrder: Web.Ordering.descending,
                        properties: properties.toArray(),
                        pageInfo: true
                    };
                    Web.System.exec("i3n48smak", "Search", datos, model => {
                        var results = Sol.List.from(model.Data);
                        results.forEach(item => Sol.List.from(item).forEach(cv => cv.Campo = cv.Campo.replace("RelatedFile$", "")));
                        this.uploadControl.value = results.toArray();
                    }, null);
                    this.isFilesLoaded = true;
                }
            }
            Screens.FollowupScreen = FollowupScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class WhatsNewIcon extends Icons.BaseIcon {
                    constructor() {
                        super();
                        this.backToHomeWhenClick = false;
                        this.sourceMenu =
                            {
                                "ID": 0,
                                "Clase": "Solarium.Software.WhatsNewObject, Solarium.Software, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                "Icono": "&#xf005;",
                                "MensajeDeSistema": null,
                                "Nombre": "Novidades do sistema",
                                "Description": null,
                                "Pantalla": "Registro",
                                "Submenus": [],
                                "Tile": "WhatsNewIcon",
                                "TopicID": 8,
                                "TopicName": "Sistema",
                                "RequiereModel": true,
                                "LanguageKey": "whats_new_screen_pl",
                                "Category": 0,
                                "UniqueID": "uid1224702143"
                            };
                    }
                    refresh() {
                        Web.System.exec("woels3ldo", "GetRecentProjectsCount", null, e => {
                            this.number.value = e;
                            this.number.estilos.definir("visibility", "visible");
                        });
                    }
                }
                Icons.WhatsNewIcon = WhatsNewIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class MyAccountScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.systemInformation = new Sol.Control();
                    this.menuBox = new Sol.Control();
                    this.css.add("sol_my_account_screen");
                }
                get myModel() { return this.model; }
                build() {
                    super.build();
                    const layoutContainer = new Sol.Control();
                    layoutContainer.css.add("sol_my_account_screen");
                    this.add(layoutContainer);
                    const accountCard = new Sol.Control();
                    accountCard.css.add("sol_my_account_card");
                    layoutContainer.add(accountCard);
                    this.displayTitle(accountCard);
                    this.displaySystemInformation(accountCard);
                    const iconsRow = new Sol.Control();
                    iconsRow.css.add("sol_my_account_icons_row");
                    accountCard.add(iconsRow);
                    this.displayWhastNewIcon(iconsRow);
                    if (this.myModel.HasContract)
                        this.createTermsOfServiceIcon(iconsRow);
                    this.displayPreApprovedLimit(layoutContainer);
                    this.displayClientSince(accountCard);
                }
                displayTitle(container) {
                    this.screenCaption = Sol.Environment.resources.myAccount;
                    var title = new Screens.ScreenTitle();
                    title.text = Sol.Environment.resources.myAccount;
                    title.estilos.agregar("margin-bottom", "10px");
                    container.add(title);
                }
                displaySystemInformation(container) {
                    this.systemInformation.css.add("sol_my_account_information");
                    container.add(this.systemInformation);
                    if (this.myModel.Logo) {
                        const logo = new Sol.ImageBox();
                        logo.source = this.myModel.Logo;
                        logo.css.add("sol_my_account_logo");
                        logo.imagenWidth = 175;
                        logo.imagenHeight = 175;
                        this.systemInformation.add(logo);
                    }
                    const systemDescription = new Sol.Control();
                    systemDescription.css.add("sol_my_account_text");
                    this.systemInformation.add(systemDescription);
                    if (this.myModel.SystemName) {
                        const systemRow = new Sol.Control();
                        systemRow.css.add("sol_my_account_row");
                        systemRow.addCtr("&#xf1ad;", "sol_my_account_icon", "i");
                        const systemName = new Sol.Control();
                        systemName.text = this.myModel.SystemName;
                        systemName.css.add("sol_my_account_text_system_name");
                        systemRow.add(systemName);
                        systemDescription.add(systemRow);
                    }
                    if (this.myModel.CorporateName) {
                        const corporateName = new Sol.Control();
                        corporateName.text = this.myModel.CorporateName;
                        systemDescription.add(corporateName);
                    }
                    if (this.myModel.Address) {
                        const addressRow = new Sol.Control();
                        addressRow.css.add("sol_my_account_row");
                        addressRow.addCtr("&#xf041;", "sol_my_account_icon", "i");
                        const addressText = new Sol.Control();
                        addressText.text = this.myModel.Address;
                        addressRow.add(addressText);
                        systemDescription.add(addressRow);
                    }
                    if (this.myModel.District && this.myModel.PostalCode) {
                        const district = new Sol.Control();
                        district.text = this.myModel.District + " - " + this.myModel.PostalCode;
                        district.css.add("sol_my_account_district");
                        systemDescription.add(district);
                    }
                    if (this.myModel.City && this.myModel.State && this.myModel.Country) {
                        const city = new Sol.Control();
                        city.text = this.myModel.City + ", " + this.myModel.State + ", " + this.myModel.Country;
                        city.css.add("sol_my_account_city");
                        systemDescription.add(city);
                    }
                    if (this.myModel.Telephone) {
                        const phoneRow = new Sol.Control();
                        phoneRow.css.add("sol_my_account_row");
                        phoneRow.addCtr("&#xf095;", "sol_my_account_icon", "i");
                        const phoneText = new Sol.Control();
                        phoneText.text = this.myModel.Telephone;
                        phoneRow.add(phoneText);
                        systemDescription.add(phoneRow);
                    }
                    if (this.myModel.Email) {
                        const emailRow = new Sol.Control();
                        emailRow.css.add("sol_my_account_row");
                        emailRow.addCtr("&#xf0e0;", "sol_my_account_icon", "i");
                        const emailText = new Sol.Control();
                        emailText.text = this.myModel.Email;
                        emailRow.add(emailText);
                        systemDescription.add(emailRow);
                    }
                    if (this.myModel.Site) {
                        const siteRow = new Sol.Control();
                        siteRow.css.add("sol_my_account_row");
                        siteRow.addCtr("&#xf0ac;", "sol_my_account_icon", "i");
                        const siteText = new Sol.Control();
                        siteText.text = this.myModel.Site;
                        siteRow.add(siteText);
                        systemDescription.add(siteRow);
                    }
                }
                displayPreApprovedLimit(container) {
                    if (!this.myModel.PreApprovedLimit)
                        return;
                    const financialArea = new Sol.Control();
                    financialArea.css.add("sol_my_account_credit_card");
                    const creditTitle = new Sol.Control();
                    creditTitle.text = "Informações de Pagamento";
                    creditTitle.css.add("sol_my_account_credit_title");
                    financialArea.add(creditTitle);
                    if (this.model.PreApprovedLimit) {
                        const creditRow = new Sol.Control();
                        creditRow.css.add("sol_my_account_row");
                        const limitLabel = new Sol.Control();
                        limitLabel.text = "Valor pré-aprovado:";
                        limitLabel.css.add("sol_my_account_credit_label");
                        const limitValue = new Sol.Control();
                        limitValue.text = this.myModel.PreApprovedLimit;
                        limitValue.css.add("sol_my_account_value");
                        creditRow.add(limitLabel);
                        financialArea.add(creditRow);
                        financialArea.add(limitValue);
                    }
                    if (this.myModel.NextDueDateCaption && this.myModel.NextDueDate) {
                        const dueDateContainer = new Sol.Control();
                        dueDateContainer.css.add("sol_my_account_row");
                        const dueDateLabel = new Sol.Control();
                        dueDateLabel.text = this.myModel.NextDueDateCaption;
                        dueDateLabel.css.add("sol_my_account_credit_label");
                        dueDateContainer.add(dueDateLabel);
                        const dueDateValue = new Sol.Control();
                        dueDateValue.text = this.myModel.NextDueDate;
                        dueDateValue.css.add("sol_my_account_value");
                        financialArea.add(dueDateContainer);
                        financialArea.add(dueDateValue);
                    }
                    if (this.myModel.PeriodicityCaption && this.myModel.Periodicity) {
                        const periodicityContainer = new Sol.Control();
                        periodicityContainer.css.add("sol_my_account_row");
                        const periodicityLabel = new Sol.Control();
                        periodicityLabel.text = this.myModel.PeriodicityCaption;
                        periodicityLabel.css.add("sol_my_account_credit_label");
                        periodicityContainer.add(periodicityLabel);
                        const periodicityValue = new Sol.Control();
                        periodicityValue.text = this.myModel.Periodicity;
                        periodicityValue.css.add("sol_my_account_value");
                        financialArea.add(periodicityContainer);
                        financialArea.add(periodicityValue);
                    }
                    container.add(financialArea);
                }
                displayClientSince(container) {
                    if (!this.myModel.ClientSince)
                        return;
                    const clientRow = new Sol.Control();
                    clientRow.css.add("sol_my_account_client_since");
                    clientRow.addCtr("&#xf005;", "sol_my_account_icon", "i");
                    const clientText = new Sol.Control();
                    clientText.css.add("sol_my_account_client_since_text");
                    clientText.text = this.myModel.ClientSinceCaption + " " + this.myModel.ClientSince;
                    clientRow.add(clientText);
                    container.add(clientRow);
                }
                createTermsOfServiceIcon(container) {
                    let contractScreenIcon = new Web.Components.Icons.SimpleIcon();
                    contractScreenIcon.backToHomeWhenClick = false;
                    contractScreenIcon.labelText = Sol.Environment.resources.serviceTerms;
                    contractScreenIcon.sourceMenu =
                        {
                            Clase: "Solarium.MyAccount.Screens.TermsOfServiceScreen, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            Nombre: Sol.Environment.resources.serviceTerms,
                            Icono: "&#xf15c;",
                            Pantalla: "Solarium.MyAccount.Screens.TermsOfServiceScreen",
                            RequiereModel: true
                        };
                    this.menuBox.add(contractScreenIcon);
                    this.menuBox.css.add("sol_my_account_menu_box");
                    container.add(this.menuBox);
                }
                displayWhastNewIcon(container) {
                    if (!this.myModel.ShowWhatsNewIcon)
                        return;
                    container.add(new Web.Components.Icons.WhatsNewIcon());
                }
            }
            Screens.MyAccountScreen = MyAccountScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class TermsOfServiceScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.agreement = new Sol.Control();
                    this.menuBox = new Sol.Control();
                    this.closeButton = new Sol.Button();
                    this.css.add("sol_contract_screen");
                }
                get myModel() { return this.model; }
                build() {
                    super.build();
                    this.createTitle();
                    this.displayAgreement();
                    this.createCloseButton();
                }
                createTitle() {
                    this.screenCaption = Sol.Environment.resources.serviceTerms;
                    var title = new Screens.ScreenTitle();
                    title.text = Sol.Environment.resources.serviceTerms;
                    this.add(title);
                }
                displayAgreement() {
                    this.agreement.css.add("sol_contract_screen_agreement");
                    this.agreement.htmlContent = this.myModel.ContractHtml;
                    this.add(this.agreement);
                }
                createCloseButton() {
                    this.closeButton.css.add("sol_contract_screen_close");
                    this.closeButton.text = Sol.Environment.resources.cerrar;
                    this.closeButton.onClick = () => Web.System.screens.closeCurrentScreen();
                    this.add(this.closeButton);
                }
            }
            Screens.TermsOfServiceScreen = TermsOfServiceScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class Icon extends Icons.BaseIcon {
                    refresh() { }
                    iconClick() {
                        Web.System.home.closeMenu();
                        if (this.backToHomeWhenClick && !Web.System.screens.backToDashboard())
                            return;
                        Web.System.screens.openScreenWithModel(this.sourceMenu.Pantalla);
                    }
                }
                Icons.Icon = Icon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class CounterIcon extends Icons.BaseIcon {
                    refresh() {
                        Web.System.exec("nlskd23jor", "GetCounting", {
                            className: this.sourceMenu.Clase
                        }, e => {
                            this.number.value = e;
                            this.number.estilos.definir("visibility", "visible");
                        });
                    }
                }
                Icons.CounterIcon = CounterIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class ServiceApprovalIcon extends Icons.BaseIcon {
                    refresh() {
                        Web.System.exec("jy5alkj23", "CountServicesForApproval", {
                            className: this.sourceMenu.Clase
                        }, e => {
                            this.number.value = e;
                            this.number.estilos.definir("visibility", "visible");
                        });
                    }
                }
                Icons.ServiceApprovalIcon = ServiceApprovalIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class ProductApprovalIcon extends Icons.BaseIcon {
                    refresh() {
                        Web.System.exec("jy5alkj23", "CountProductsForApproval", {
                            className: this.sourceMenu.Clase
                        }, e => {
                            this.number.value = e;
                            this.number.estilos.definir("visibility", "visible");
                        });
                    }
                }
                Icons.ProductApprovalIcon = ProductApprovalIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class ClearCachingIcon extends Icons.BaseIcon {
                    refresh() { }
                    iconClick() {
                        Web.System.exec("nlskd23jor", "ClearCaching", null, () => alert("Caching cleared successfully"));
                    }
                }
                Icons.ClearCachingIcon = ClearCachingIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class SupportIcon extends Icons.BaseIcon {
                    refresh() {
                        Web.System.exec("etz7dl5tv", "CountOpenTicket", {
                            credential: Sol.Environment.credential.export()
                        }, e => {
                            this.number.value = e;
                            if (e > 0)
                                this.number.estilos.definir("visibility", "visible");
                        });
                    }
                }
                Icons.SupportIcon = SupportIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Icons;
            (function (Icons) {
                class RstIcon extends Icons.BaseIcon {
                    refresh() { }
                    iconClick() {
                        if (!confirm("Do you confirm this operation?"))
                            return;
                        Web.System.exec("nlskd23jor", "Rst", {});
                        setTimeout(() => location.reload(), 3000);
                    }
                }
                Icons.RstIcon = RstIcon;
            })(Icons = Components.Icons || (Components.Icons = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class CourseSelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.tableItem = new Sol.Control("li");
                        this.popupTable = new Components.Grid();
                        this.className = "Solarium.Education.CursoFecha, Solarium.Education, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.properties = ["ID", "Curso", "Title", "Fecha", "FechaFinal"];
                        this.filterProperty = "Curso$Nombre";
                        this.displayProperty = "Curso";
                        this.resultsOrder = "Fecha";
                        this.resultsOrdering = Web.Ordering.descending;
                        this.resultCount = 1000;
                        this.tableItem.add(this.popupTable);
                        this.popupTable.showChecks = false;
                        this.popupTable.className = this.className;
                        this.popupTable.onRowClick = code => this.itemSelected(code);
                        this.popupTable.columns.add({
                            PropertyName: "Curso",
                            Title: "Curso",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.popupTable.columns.add({
                            PropertyName: "Title",
                            Title: "Turma",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.popupTable.columns.add({
                            PropertyName: "Fecha",
                            Title: "De",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.popupTable.columns.add({
                            PropertyName: "FechaFinal",
                            Title: "Até",
                            ShowTitle: true,
                            Visible: true
                        });
                        this.popup.add(this.tableItem);
                    }
                    clearPopup() { }
                    fillPopup(model) {
                        this.addIntervalFilter();
                        this.popupTable.loadData(model);
                    }
                    search(code, cancelClickEvent) {
                        const _super = Object.create(null, {
                            search: { get: () => super.search }
                        });
                        return __awaiter(this, void 0, void 0, function* () {
                            _super.search.call(this);
                            this.popup.ancho = Math.max(this.mainField.ancho, 600);
                        });
                    }
                    itemSelected(codigo) {
                        this.mainField.textValue = this.popupTable.getPropertyValueByID(this.displayProperty, codigo).Campo;
                        this.textoItemSeleccionado = this.mainField.textValue;
                        this._value = codigo;
                        this.editButton.enabled = true;
                        this.popup.visible = false;
                    }
                    addIntervalFilter() {
                        if (!this.parent.getEditor)
                            return;
                        var intervalEditor = this.parent.getEditor("Creación");
                        if (!intervalEditor)
                            return;
                        var intervalFilter = intervalEditor.value;
                        if (!intervalFilter || intervalFilter.Opcion == Sol.IntervalType.Anytime)
                            return;
                        this.onFiltering = () => Sol.List.from([{
                                PropertyName: "Fecha",
                                FilterType: "Periodo",
                                FilterValue: intervalFilter
                            }]);
                    }
                }
                Selectors.CourseSelector = CourseSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class SelectorService extends Components.DataCombo {
                    build() {
                        this.onChange = () => this.searchService();
                        super.build();
                    }
                    searchService() {
                        var data = {
                            className: "Solarium.Commercial.Service, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            currentPage: 1,
                            rowCount: 1,
                            filters: [{ PropertyName: "ID", FilterType: "SInteger", FilterValue: this.selectedCode }],
                            sortProperty: "ID",
                            sortOrder: Web.Ordering.ascending,
                            properties: ["PriceData"],
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", data, model => {
                            var price = model.Data[0][1]["Valor"];
                            this.container.editors.that(e => e.propertyName == "Total").value = price;
                        }, null);
                    }
                }
                Selectors.SelectorService = SelectorService;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class CategorySelector extends Components.DataCombo {
                    build() {
                        this.maxItems = 500;
                        this.disableChangeEventOnSetValue = true;
                        this.onValueModified.subscribe(() => this.categoryChanged());
                        this.onSet.subscribe(() => this.categoryChanged());
                        super.build();
                    }
                    categoryChanged() {
                        if (!this.selectedCode)
                            return;
                        var data = {
                            categoryID: this.selectedCode
                        };
                        Web.System.exec("79k8jhkh", "GetSpecificationByCategory", data, response => {
                            var specs = Sol.List.from(response.Specifications);
                            var specsEditor = this.container.editors.that(cp => cp.propertyName == "Specifications");
                            specsEditor.setFields(specs);
                            var ncmEditor = this.container.editors.that(i => i.propertyName == "NCM");
                            if (ncmEditor && response.DefaultNCM)
                                ncmEditor.value = parseInt(response.DefaultNCM);
                            var marginEditor = this.container.editors.that(i => i.propertyName == "Margin");
                            if (marginEditor && response.DefaultMargin) {
                                marginEditor.value = response.DefaultMargin;
                                var priceEditor = this.container.editors.that(i => i.propertyName == "Price");
                                priceEditor.updatePrice();
                            }
                        });
                    }
                }
                Selectors.CategorySelector = CategorySelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class GoalEngineSelector extends Sol.Combo {
                    constructor() {
                        super();
                        this.onChange = () => this.change();
                    }
                    get modelList() { return Sol.List.from(this.configuration); }
                    get selectedModel() { return this.modelList.that(m => m.ClassType == this.selectedCode); }
                    build() {
                        super.build();
                        var items = this.modelList.select(i => ({
                            Campo: i.Description,
                            Valor: i.ClassType
                        }));
                        this.addItems(items.toArray());
                    }
                    change() {
                        var selectedModel = this.selectedModel;
                        var quantityField = this.container.editors.that(cp => cp.propertyName == "Quantity");
                        var amountField = this.container.editors.that(cp => cp.propertyName == "Amount");
                        quantityField.toControl().parent.visible = selectedModel.GoalType == Selectors.GoalType.ByQuantity;
                        amountField.toControl().parent.visible = selectedModel.GoalType == Selectors.GoalType.ByAmount;
                        var customFiltersEditor = this.container.editors.that(cp => cp.propertyName == "CustomFilters");
                        customFiltersEditor.setStructure(selectedModel.CustomFiltersStructure);
                    }
                }
                Selectors.GoalEngineSelector = GoalEngineSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class AccountSelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.treeView = new Components.TreeView();
                        this._accountType = Selectors.AccountType.Credit;
                        this.css.add("sol_account_selector");
                        this.treeView.rootLabel = Sol.Environment.resources.account;
                        this.isComplex = false;
                        this.popup.controls.empty();
                        this.mainField.placeHolder = "";
                        this.treeView.onNodeSelected = node => this.nodeSelected(node);
                        const li = new Sol.Control("li");
                        li.add(this.treeView);
                        this.popup.add(li);
                    }
                    get accountType() { return this._accountType; }
                    set accountType(value) { this._accountType = value; }
                    build() {
                        super.build();
                        this.configureRefreshWhebDebitCreditChange();
                    }
                    search(code, cancelClickEvent) {
                        return __awaiter(this, void 0, void 0, function* () {
                            this.popup.show();
                            this.popup.ancho = this.mainField.ancho;
                            Web.System.exec("p3kewj34", "GetTree", { classHash: this.accountType }, e => {
                                this.treeView.clear();
                                this.treeView.loadData(e);
                            });
                        });
                    }
                    nodeSelected(node) {
                        this._value = node.code;
                        this.mainField.value = node.caption;
                        this.popup.hide();
                    }
                    fieldKeyDown(e) {
                        if (e.which == 8 || e.which == 46) {
                            this.clear();
                            return;
                        }
                        e.cancelBubble = true;
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                    configureRefreshWhebDebitCreditChange() {
                        const amountEditor = this.container.getEditor("Amount");
                        amountEditor.onModeChanged.subscribe(() => {
                            this.clear();
                            this.accountType = amountEditor.accountType;
                        });
                    }
                }
                Selectors.AccountSelector = AccountSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class UnitSelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.currentCompany = Sol.Environment.credential.empresa;
                        this.isMultiCompany = true;
                        this.isComplex = false;
                        this.useWrapper = true;
                        this.evalEmptyFilter = true;
                        this.displayProperty = "AbbreviationWithName";
                        this.resultsOrder = "AbbreviationWithName";
                        this.filterProperty = "GeneralFilter";
                        this.onFiltering = () => this.addExtraFilters();
                    }
                    addExtraFilters() {
                        const filters = new Sol.List();
                        filters.add({ FilterType: "SInteger", PropertyName: "Empresa", FilterValue: this.currentCompany });
                        if (this.onlyRootOptions)
                            filters.add({ FilterType: "_by_null", PropertyName: "ParentUnit", FilterValue: true });
                        return filters;
                    }
                    changeCompany(companyCode) {
                        this.currentCompany = companyCode;
                        this.clear();
                    }
                    setCompany(companyCode) {
                        this.currentCompany = companyCode;
                    }
                }
                Selectors.UnitSelector = UnitSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Collections;
            (function (Collections) {
                class CollectionEditor extends Sol.Control {
                    constructor() {
                        super();
                        this.addButton = new Sol.Button();
                        this._allowAddNew = true;
                        this._allowDelete = true;
                        this.isComplex = true;
                        this.isListComponent = true;
                        this.showItemTitle = true;
                        this.onCountChanged = new Sol.EventHandler();
                        this.css.add("sol_detalles_complex");
                    }
                    get items() {
                        return this.controls.where(c => c instanceof Web.Screens.DetailsScreen).cast();
                    }
                    get allowAddNew() { return this._allowAddNew; }
                    set allowAddNew(value) { this._allowAddNew = value; }
                    get allowDelete() { return this._allowDelete; }
                    set allowDelete(value) { this._allowDelete = value; }
                    get readonly() { return this._readonly; }
                    set readonly(value) {
                        this._readonly = value;
                        this.addButton.visible = !value && this.allowAddNew;
                    }
                    isEmpty() { return !this.items.hasItems(); }
                    validate() { return null; }
                    get value() {
                        var r = new Sol.List();
                        this.items.forEach(c => {
                            var item = new Object();
                            item.ID = c.code;
                            item.ItemIndex = c.index;
                            var itemCollection = Sol.List.from(c.values);
                            itemCollection.forEach(i => item[i.Campo] = i.Valor);
                            r.add(item);
                        });
                        return r.toArray();
                    }
                    set value(v) {
                        this.clear();
                        if (!v)
                            return;
                        Sol.List.from(v).forEach(i => {
                            const item = this.addItem();
                            item.loadData(i);
                            item.onBuildComplete = () => item.loadData(i);
                        });
                    }
                    toControl() { return this; }
                    build() {
                        super.build();
                        this.addButton.type = Sol.ButtonType.Link;
                        this.addButton.text = Sol.Environment.resources.anadir_item;
                        this.addButton.onClick = () => this.addItem().foco();
                        this.addButton.visible = !this.readonly && this.allowAddNew;
                        this.add(this.addButton);
                        if (this.defaultValue)
                            this.value = this.defaultValue;
                    }
                    addItem() {
                        var model = {
                            Actions: null,
                            ClassName: null,
                            IsProcess: false,
                            Structure: this.fields,
                            GroupMode: Web.Screens.FieldGroupMode.Frames
                        };
                        if (this.readonly)
                            model.Structure = Sol.List.from(model.Structure).select(s => {
                                s.ReadOnly = true;
                                s.ReadOnlyAtEdition = true;
                                return s;
                            }).toArray();
                        var details = new Web.Screens.DetailsScreen();
                        details.disableMinimizedControls = true;
                        details.model = model;
                        details.myForm.footer.visible = false;
                        details.showTitle = this.showItemTitle;
                        details.screenCaption = this.itemTitle;
                        details.canMinimize = this.showItemTitle;
                        details.groupMode = this.groupMode;
                        details.css.add("sol_collection_editor_item");
                        this.controls.insert(this.controls.count - 1, details);
                        this.updateNumeration();
                        if (!this.readonly && this.allowDelete) {
                            const removeButton = new Sol.Button();
                            removeButton.type = Sol.ButtonType.Link;
                            removeButton.text = Sol.Environment.resources.eliminar;
                            removeButton.onClick = () => {
                                if (!confirm(Sol.Environment.resources.confirm_delete))
                                    return;
                                this.controls.remove(details);
                                this.updateNumeration();
                            };
                            details.add(removeButton);
                        }
                        return details;
                    }
                    updateNumeration() {
                        var index = 1;
                        this.items.forEach(ctr => {
                            ctr.screenCaption = this.itemTitle + " " + index;
                            ctr.index = index++;
                        });
                        this.onCountChanged.invoke(this.items.count);
                    }
                    clear() {
                        this.controls.forEachReverse(ctr => {
                            if (ctr instanceof Web.Screens.DetailsScreen)
                                this.controls.remove(ctr);
                        });
                    }
                    foco() { }
                }
                Collections.CollectionEditor = CollectionEditor;
            })(Collections = Components.Collections || (Components.Collections = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Quality;
            (function (Quality) {
                class QualityEvaluation extends Sol.Button {
                    constructor() {
                        super();
                        this.value = 0;
                        this.isComplex = false;
                        this.imageCode = '&#xf005;';
                        this.onClick = () => Web.System.screens.openScreen("OptionalDetails", "Solarium.Quality.Evaluation, Solarium.Quality, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null, null, this.text, s => {
                            this.screen = s;
                            if (this.value)
                                this.screen.load(this.value);
                            this.screen.onSaved.subscribe(f => {
                                this.value = this.screen.code;
                                Web.System.screens.closeCurrentScreen();
                            });
                            this.screen.myForm.onCancel = f => Web.System.screens.closeCurrentScreen();
                        });
                    }
                    toControl() { return this; }
                    isEmpty() { return false; }
                    foco() { }
                    clear() { }
                    validate() { return null; }
                }
                Quality.QualityEvaluation = QualityEvaluation;
            })(Quality = Components.Quality || (Components.Quality = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class HtmlEditor extends Sol.Control {
                constructor() {
                    super("textarea");
                    this.isComplex = false;
                    this.showSourceCodeButton = true;
                    Sol.Environment.loadLibrary({
                        name: "letnote",
                        source: "/frameworks/letnote.js",
                        cssFile: "/frameworks/letnote.css"
                    });
                }
                get readonly() { return this._readonly; }
                set readonly(value) {
                    this._readonly = value;
                    if (!this.modoSol)
                        return;
                    $("#" + this.id).letnote(value ? "disable" : "enable");
                    this.html.nextElementSibling.querySelector(".note-toolbar").style.display = value ? "none" : "block";
                }
                get value() {
                    return $("#" + this.id).letnote('code');
                }
                set value(s) {
                    var editorWaiting = setInterval(() => {
                        if (typeof $ === 'undefined')
                            return;
                        if ($ && $("#" + this.id).letnote()) {
                            clearInterval(editorWaiting);
                            $("#" + this.id).letnote('code', s);
                        }
                    }, 250);
                }
                build() {
                    super.build();
                    var editorWaiting = setInterval(() => {
                        if (typeof $ === 'undefined')
                            return;
                        if ($ && $("#" + this.id).letnote()) {
                            clearInterval(editorWaiting);
                            $("#" + this.id).letnote({
                                height: "300px",
                                onImageUpload: (files, editor, welEditable) => this.sendFile(files[0], editor, welEditable)
                            });
                            if (this.readonly) {
                                $("#" + this.id).letnote("disable");
                                this.html.nextElementSibling.querySelector(".note-toolbar").style.display = "none";
                            }
                        }
                    }, 250);
                }
                sendFile(file, editor, welEditable) {
                    var data = new FormData();
                    data.append("file", file);
                    Sol.Http.Ajax.post(Sol.Environment.uploadPath, data, fileModel => editor.insertImage(welEditable, Sol.Environment.filePath + fileModel.Identifier), null);
                }
                toControl() { return this; }
                isEmpty() { return false; }
                foco() { }
                clear() { }
                validate() { return null; }
            }
            Components.HtmlEditor = HtmlEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class HTMLDialog extends Sol.FormDialog {
                constructor() {
                    super();
                    this.css.add("sol_html_dialog");
                    this.editor = new Components.HtmlEditor();
                    this.form.controls.add(this.editor);
                }
                get value() { return this.editor.value; }
                set value(val) { this.editor.value = val; }
            }
            Components.HTMLDialog = HTMLDialog;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class HTMLDialogEditor extends Sol.Button {
                constructor() {
                    super();
                    this.propertyName = "";
                    this.readonly = false;
                    this.required = false;
                    this.onFocus = new Sol.EventHandler();
                    this.onLeave = new Sol.EventHandler();
                    this._value = "";
                    this.css.add("sol_html_dialog_editor");
                    this.text = "Editar HTML";
                    this.onClick = () => this.handleClick();
                }
                get value() { return this._value; }
                set value(val) {
                    if (this._value !== val) {
                        this._value = val;
                        this.imageCode = val ? "&#xf044;" : null;
                        if (this.onValueModified && "invoke" in this.onValueModified)
                            this.onValueModified.invoke();
                        if (this.onChange && "invoke" in this.onChange)
                            this.onChange.invoke();
                    }
                }
                get caption() { return this.text; }
                set caption(val) { this.text = val; }
                handleClick() {
                    const dialog = new Sol.Web.Components.HTMLDialog();
                    dialog.value = this.value;
                    dialog.title = this.caption;
                    dialog.visible = true;
                    if (this.parent) {
                        this.parent.add(dialog);
                    }
                    dialog.onSave = () => {
                        this.value = dialog.value;
                        if (this.onSet)
                            this.onSet.invoke();
                        dialog.visible = false;
                    };
                }
                clear() { this.value = ""; }
                foco() { this.focus(); }
                isEmpty() { return this.value === null || this.value === undefined || this.value === ""; }
                toControl() { return this; }
                validate() {
                    if (this.required && this.isEmpty()) {
                        return "Este campo é obrigatório";
                    }
                    return "";
                }
            }
            Components.HTMLDialogEditor = HTMLDialogEditor;
            Sol.Web.Editors.registerEditor("HTMLDialogEditor", () => new Sol.Web.Components.HTMLDialogEditor());
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PartnerDetailsEditor extends Components.DetailsEditor {
                get amount() {
                    return this.details.editors.that(edt => edt.propertyName == "ComissionAmount").numericValue;
                }
                get discounts() {
                    return this.details.editors.that(edt => edt.propertyName == "Discounts").value;
                }
                get finalAmount() { return this.amount - (this.amount * this.discounts / 100); }
                get isSummable() { return true; }
                get cost() { return 0; }
                get margin() { return -this.amount; }
                get total() { return 0; }
                onCalcFinalAmount() {
                    var finalAmountEditor = this.details.getEditor("FinalAmount");
                    if (finalAmountEditor.numericValue == this.finalAmount)
                        return;
                    finalAmountEditor.numericValue = this.finalAmount;
                    this.changeTotal();
                }
                build() {
                    super.build();
                    this.css.add("sol_partner_details_editor");
                    setTimeout(() => {
                        this.details.editors.that(edt => edt.propertyName == "ComissionAmount").onChange = () => this.onCalcFinalAmount();
                        this.details.editors.that(edt => edt.propertyName == "Discounts").onModified = () => this.onCalcFinalAmount();
                    }, 300);
                }
                changeTotal() {
                    if (this.onTotalsChanged)
                        this.onTotalsChanged();
                }
            }
            Components.PartnerDetailsEditor = PartnerDetailsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PartnerDetailsEditor", model => {
    const partnerDetailsEditor = new Sol.Web.Components.PartnerDetailsEditor();
    partnerDetailsEditor.model = model.ScreenModel;
    return partnerDetailsEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TwoColumnsSelector extends Sol.Control {
                constructor() {
                    super();
                    this.searchField = new Sol.Field();
                    this.searchResults = new Sol.ListField();
                    this.selectedList = new Sol.ListField();
                    this.displayMember = "CustomName";
                    this.css.add("sol_two_colums");
                    this.searchField.onKeyUp = e => this.search(e);
                    this.searchField.placeHolder = Sol.Environment.resources.typeToSearch;
                    this.searchField.maxLength = 85;
                    this.add(this.searchField);
                    this.addSearchOptions();
                    this.searchResults.enableDeleteKey = true;
                    this.searchResults.onDoubleClick = () => this.addItem();
                    this.searchResults.onKeyDown = e => this.resultsKeyDown(e);
                    this.searchResults.multiple = true;
                    this.add(this.searchResults);
                    let buttonsBar = new Sol.Control();
                    buttonsBar.css.add("sol_two_colums_bar");
                    this.add(buttonsBar);
                    let addButton = new Sol.Button();
                    addButton.imageCode = "&#xf078;";
                    addButton.onClick = () => this.addItem();
                    buttonsBar.add(addButton);
                    let removeButton = new Sol.Button();
                    removeButton.imageCode = "&#xf077;";
                    removeButton.onClick = () => this.removeItem();
                    buttonsBar.add(removeButton);
                    this.selectedList.enableDeleteKey = true;
                    this.selectedList.multiple = true;
                    this.add(this.selectedList);
                }
                get value() {
                    return this.selectedList.items
                        .select(i => { return { ID: parseInt(i.code.toString()) }; })
                        .toArray();
                }
                set value(v) {
                    this.selectedList.controls.empty();
                    Sol.List.from(v).forEach(itemData => {
                        let data = Sol.List.from(itemData);
                        let comboItem = new Sol.ComboItem();
                        comboItem.code = data.that(d => d.Campo == "ID").Valor;
                        comboItem.text = data.that(d => d.Campo == this.displayMember).Valor;
                        this.selectedList.add(comboItem);
                    });
                }
                clear() { this.selectedList.controls.empty(); }
                foco() { this.searchField.foco(); }
                isEmpty() { return false; }
                toControl() { return this; }
                validate() { return null; }
                addSearchOptions() { }
                getFilters() {
                    return Sol.List.from([{ PropertyName: this.displayMember, FilterValue: this.searchField.value, FilterType: "SText" }]);
                }
                search(e) {
                    if ((e === null || e === void 0 ? void 0 : e.key) === "ArrowDown") {
                        this.searchResults.foco();
                        return;
                    }
                    if (this.lastSearch == this.searchField.value)
                        return;
                    this.searchResults.controls.empty();
                    this.lastSearch = this.searchField.value;
                    let data = {
                        className: this.className,
                        currentPage: 0,
                        rowCount: 200,
                        filters: this.getFilters().toArray(),
                        sortProperty: this.displayMember,
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", this.displayMember],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        let counter = 0;
                        let datos = Sol.List.from(model.Data).cast();
                        ;
                        this.searchResults.controls.empty();
                        this.searchResults.controls.addMany(datos.select(item => {
                            let fields = Sol.List.from(item);
                            let listItem = new Sol.ComboItem();
                            listItem.code = model.Codes[counter];
                            listItem.text = fields.that(d => d.Campo == this.displayMember).Valor;
                            counter++;
                            return listItem;
                        }));
                    });
                }
                addItem() {
                    if (!this.searchResults.selectedCode)
                        return;
                    if (this.selectedList.containsCode(this.searchResults.selectedCode))
                        return;
                    this.selectedList.controls.addMany(this.searchResults.selectedItems.select(selectedItem => {
                        let item = new Sol.ComboItem();
                        item.code = selectedItem.code;
                        item.text = selectedItem.text;
                        return item;
                    }));
                }
                removeItem() {
                    this.selectedList.removeSelected();
                }
                resultsKeyDown(e) {
                    if (e.key === "Enter")
                        this.addItem();
                }
            }
            Components.TwoColumnsSelector = TwoColumnsSelector;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("TwoColumnsSelector", model => {
    let twoColumnsSelector = new Sol.Web.Components.TwoColumnsSelector();
    twoColumnsSelector.className = model.DataTypeFullName;
    return twoColumnsSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TwoColumnsRegionSelector extends Components.TwoColumnsSelector {
                addSearchOptions() {
                    this.districtCheck = new Sol.Check(Sol.Environment.resources.barrio, true);
                    this.cityCheck = new Sol.Check(Sol.Environment.resources.ciudad, true);
                    this.stateCheck = new Sol.Check(Sol.Environment.resources.estado, true);
                    this.countryCheck = new Sol.Check(Sol.Environment.resources.pais, true);
                    this.districtCheck.onChange = () => this.refreshSearch();
                    this.cityCheck.onChange = () => this.refreshSearch();
                    this.stateCheck.onChange = () => this.refreshSearch();
                    this.countryCheck.onChange = () => this.refreshSearch();
                    let searchArea = new Sol.Control();
                    searchArea.css.add("sol_two_colums_search");
                    searchArea.addCtr(Sol.Environment.resources.search_filters, null);
                    searchArea.addMany([this.countryCheck, this.stateCheck, this.cityCheck, this.districtCheck]);
                    this.add(searchArea);
                }
                getFilters() {
                    let result = super.getFilters();
                    let regionTypes = Sol.List.from([
                        { selected: this.districtCheck.value, hash: 1321955975 },
                        { selected: this.cityCheck.value, hash: 790721975 },
                        { selected: this.stateCheck.value, hash: 1311952638 },
                        { selected: this.countryCheck.value, hash: 1346779155 }
                    ]);
                    let selectedTypes = regionTypes.where(t => t.selected).select(t => t.hash).toArray();
                    result.add({ PropertyName: "RegionTypesFilter", FilterType: null, FilterValue: selectedTypes });
                    return result;
                }
                refreshSearch() {
                    this.lastSearch = "";
                    this.search(null);
                }
            }
            Components.TwoColumnsRegionSelector = TwoColumnsRegionSelector;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("TwoColumnsRegionSelector", model => {
    let selector = new Sol.Web.Components.TwoColumnsRegionSelector();
    selector.className = model.DataTypeFullName;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var ServiceOrders;
            (function (ServiceOrders) {
                class ServiceTypeEditor extends Components.DataCombo {
                    build() {
                        super.build();
                        setTimeout(() => {
                            this.onChange = () => this.getDefaultServiceTypeData();
                        }, 300);
                    }
                    getDefaultServiceTypeData() {
                        if (this.container.toControl().parent.code)
                            return;
                        var data = {
                            className: "Solarium.ServiceOrders.ServiceType, Solarium.ServiceOrders, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                            currentPage: 1,
                            rowCount: 1,
                            filters: [{ PropertyName: "ID", FilterType: "SInteger", FilterValue: this.selectedCode }],
                            sortProperty: "ID",
                            sortOrder: Web.Ordering.ascending,
                            properties: ["Technician", "Service", "Service$PriceData"],
                            pageInfo: false
                        };
                        Web.System.exec("i3n48smak", "Search", data, model => {
                            var technician = model.Data[0][1].Valor.Valor;
                            var service = model.Data[0][2].Valor.Valor;
                            var servicePrice = model.Data[0][3].Valor;
                            var technicianCombo = this.container.editors.that(edt => edt.propertyName == "Technician");
                            var serviceEditor = this.container.editors.that(edt => edt.propertyName == "Services");
                            technicianCombo.value = technician;
                            if (service != 0) {
                                var itemData = [
                                    { Campo: "ID", Valor: 0 },
                                    { Campo: "Service", Valor: service },
                                    { Campo: "Price", Valor: servicePrice },
                                    { Campo: "Quantity", Valor: 1 },
                                    { Campo: "Total", Valor: servicePrice }
                                ];
                                serviceEditor.addRow(itemData);
                                serviceEditor.visible = true;
                            }
                        }, null);
                    }
                }
                ServiceOrders.ServiceTypeEditor = ServiceTypeEditor;
            })(ServiceOrders = Components.ServiceOrders || (Components.ServiceOrders = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class InterestsField extends Components.CalculableField {
                constructor() {
                    super();
                    this.tip = "Calcular taxa de juros";
                    this.acceptsNegative = false;
                    this.calcButton.onClick = () => this.calculator();
                }
                calculator() {
                    const ammountEditor = this.container.getEditor("AccountAmount");
                    const dueDateEditor = this.container.getEditor("DueDate");
                    const feesField = this.container.getEditor("Fees");
                    if (dueDateEditor.isEmpty()) {
                        alert("Por favor, informe o campo vencimento");
                        return;
                    }
                    const data = {
                        ammount: ammountEditor.numericValue,
                        fee: this.decimalValue,
                        dueDate: dueDateEditor.dateValue
                    };
                    Web.System.exec("79k77hjdsh", "CalcInterest", data, e => {
                        feesField.numericValue = e;
                        ammountEditor.numericValue = e + data.ammount;
                    });
                }
            }
            Components.InterestsField = InterestsField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Geo;
        (function (Geo) {
            class ZipCopeField extends Sol.ExtensibleField {
                constructor() {
                    super();
                    this.mainField.maxLength = 9;
                    this.mainField.disableEnter = true;
                    this.mainField.onKeyDown = e => this.fieldKeydown(e);
                    this.mainField.onKeyPress = e => this.fieldKeypress(e);
                    this.mainField.onKeyUp = e => this.fieldKeyup(e);
                    const button = new Sol.Button();
                    button.imageCode = "&#xf002;";
                    button.onClick = () => this.search();
                    this.add(button);
                }
                fieldKeydown(e) {
                    if (e.key !== "Enter")
                        return true;
                    e.cancelBubble = true;
                    e.preventDefault();
                    e.stopPropagation();
                    this.search();
                    return false;
                }
                fieldKeypress(e) {
                    if (!this.isBrazil)
                        return true;
                    return this.mainField.filterNumber(e);
                }
                fieldKeyup(e) {
                    if (!this.isBrazil)
                        return;
                    var cepRegex = new RegExp(/^\d{5}$/);
                    if (e.which >= 48 && e.which <= 57 && cepRegex.test(this.mainField.value))
                        this.mainField.value += '-';
                }
                search() {
                    if (!this.isBrazil || !this.isEmpty())
                        this.onSearch();
                }
            }
            Geo.ZipCopeField = ZipCopeField;
        })(Geo = Web.Geo || (Web.Geo = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Geo;
        (function (Geo) {
            class RegionSelector extends Web.Components.Selectors.Selector {
                constructor() {
                    super();
                    this.allowCreateNew = false;
                    this.allowEdit = false;
                    this.filterProperty = "CustomName";
                    this.properties = ["ID", "CustomName"];
                    this.displayProperty = "CustomName";
                    this.isComplex = false;
                }
                getFilters() {
                    var filters = super.getFilters();
                    filters.add({ PropertyName: "HideDistrictsFilter", FilterValue: true, FilterType: null });
                    return filters;
                }
            }
            Geo.RegionSelector = RegionSelector;
        })(Geo = Web.Geo || (Web.Geo = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("Región", model => {
    const regionSelector = new Sol.Web.Geo.RegionSelector();
    regionSelector.estructura = model.Structure;
    regionSelector.etiqueta = model.Title;
    regionSelector.className = model.DataTypeFullName;
    return regionSelector;
});
Sol.Web.Editors.registerFilter("Región", model => {
    const regionSelector = new Sol.Web.Geo.RegionSelector();
    regionSelector.etiqueta = model.Caption;
    regionSelector.fieldAutoWidth = false;
    regionSelector.className = model.ClassName;
    return regionSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Geo;
        (function (Geo) {
            class AddressMap extends Sol.Control {
                constructor() {
                    super("iframe");
                    this.css.add("sol_map");
                    this.atributos.agregar("frameborder", "0");
                    this.atributos.agregar("scrolling", "no");
                    this.atributos.agregar("marginheight", "0");
                    this.atributos.agregar("marginwidth", "0");
                }
                showMap(address) {
                    var term;
                    if (address.CountryName)
                        term = address.CountryName;
                    if (address.DistrictDesc)
                        term += ", " + address.DistrictDesc;
                    if (address.CiudadDesc)
                        term += ", " + address.CiudadDesc;
                    if (address.DistrictDesc)
                        term += ", " + address.DistrictDesc;
                    if (address.Calle)
                        term += ", " + address.Calle;
                    if (address.Number)
                        term += ", " + address.Number;
                    this.atributos.definir("src", "https://maps.google.com.br/maps?q=" + term + "&output=embed");
                }
            }
            Geo.AddressMap = AddressMap;
        })(Geo = Web.Geo || (Web.Geo = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Geo;
        (function (Geo) {
            class AddressEditor extends Sol.Control {
                constructor() {
                    super();
                    this.countryLabel = new Sol.Label();
                    this.countrySelector = new Geo.CountrySelector();
                    this.stateLabel = new Sol.Label();
                    this.stateSelector = new Web.Components.Selectors.Selector();
                    this.cityLabel = new Sol.Label();
                    this.citySelector = new Web.Components.Selectors.Selector();
                    this.districtLabel = new Sol.Label();
                    this.districtSelector = new Web.Components.Selectors.Selector();
                    this.streetLabel = new Sol.Label();
                    this.streetField = new Sol.Field();
                    this.zipCodeLabel = new Sol.Label();
                    this.zipCodeField = new Geo.ZipCopeField();
                    this.wrapper = new Sol.Control();
                    this.map = new Geo.AddressMap();
                    this.numberWrapper = new Sol.Control();
                    this.numberLabel = new Sol.Label();
                    this.numberField = new Sol.Field();
                    this.complementWrapper = new Sol.Control();
                    this.complementLabel = new Sol.Label();
                    this.complementField = new Sol.Field();
                    this.referencesWrapper = new Sol.Control();
                    this.referencesLabel = new Sol.ExpandoLabel;
                    this.referencesField = new Sol.TextField();
                    this.latitudeWrapper = new Sol.FieldWrapper();
                    this.latitudeLabel = new Sol.Label();
                    this.latitudeField = new Sol.NumericField();
                    this.longitudeWrapper = new Sol.FieldWrapper();
                    this.longitudeLabel = new Sol.Label();
                    this.longitudeField = new Sol.NumericField();
                    this.isComplex = true;
                    this.showMap = true;
                    this.showPostalCode = true;
                    this.showStreet = true;
                    this.showDistrict = true;
                    this.showCountry = true;
                    this.showNumber = true;
                    this.showComplement = true;
                    this.showReferences = true;
                    this.css.add("sol_address");
                    this.wrapper.ancho = 400;
                    this.wrapper.estilos.agregar("float", "left");
                    this.wrapper.estilos.agregar("max-width", "calc(100% - 10px)");
                    this.add(this.wrapper);
                    this.countryLabel.text = Sol.Environment.resources.pais + ':';
                    this.countryLabel.editor = this.countrySelector;
                    this.wrapper.add(this.countryLabel);
                    this.countrySelector.onItemSelected = () => this.countryChanged();
                    this.wrapper.add(this.countrySelector);
                    this.zipCodeLabel.text = Sol.Environment.resources.codigo_postal + ':';
                    this.wrapper.add(this.zipCodeLabel);
                    this.zipCodeField.onSearch = () => this.searchByZipCode();
                    this.wrapper.add(this.zipCodeField);
                    this.stateLabel.text = Sol.Environment.resources.estado + ':';
                    this.stateLabel.editor = this.stateSelector;
                    this.wrapper.add(this.stateLabel);
                    this.stateSelector.codeProperty = "StateID";
                    this.stateSelector.displayProperty = "StateName";
                    this.stateSelector.mainFilterType = "SLocalText";
                    this.stateSelector.className = "Solarium.Geo.Estado, Solarium.Geo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.stateSelector.onItemSelected = () => this.stateChanged();
                    this.stateSelector.sourceMode = Sol.SelectorSourceMode.Custom;
                    this.stateSelector.onCustomSource = stateId => this.stateSearch(stateId);
                    this.wrapper.add(this.stateSelector);
                    this.cityLabel.text = Sol.Environment.resources.ciudad + ':';
                    this.cityLabel.editor = this.citySelector;
                    this.wrapper.add(this.cityLabel);
                    this.citySelector.codeProperty = "CityID";
                    this.citySelector.displayProperty = "CityName";
                    this.citySelector.mainFilterType = "SLocalText";
                    this.citySelector.resultCount = 30;
                    this.citySelector.className = "Solarium.Geo.Ciudad, Solarium.Geo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.citySelector.onItemSelected = () => this.cityChanged();
                    this.citySelector.sourceMode = Sol.SelectorSourceMode.Custom;
                    this.citySelector.onCustomSource = cityId => this.citySearch(cityId);
                    this.wrapper.add(this.citySelector);
                    this.districtLabel.text = Sol.Environment.resources.barrio + ':';
                    this.districtLabel.editor = this.districtSelector;
                    this.wrapper.add(this.districtLabel);
                    this.districtSelector.codeProperty = "DistrictID";
                    this.districtSelector.displayProperty = "DistrictName";
                    this.districtSelector.mainFilterType = "SLocalText";
                    this.districtSelector.resultCount = 30;
                    this.districtSelector.className = "Solarium.Geo.District, Solarium.Geo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.districtSelector.onItemSelected = () => this.districtChanged();
                    this.districtSelector.sourceMode = Sol.SelectorSourceMode.Custom;
                    this.districtSelector.onCustomSource = districtId => this.districtSearch(districtId);
                    this.wrapper.add(this.districtSelector);
                    this.streetLabel.text = Sol.Environment.resources.calle + ':';
                    this.streetLabel.editor = this.streetField;
                    this.wrapper.add(this.streetLabel);
                    this.streetField.maxLength = 512;
                    this.streetField.onChange = () => this.streetChanged();
                    this.wrapper.add(this.streetField);
                    this.numberWrapper.css.add("sol_address_number");
                    this.numberWrapper.add(this.numberLabel);
                    this.numberWrapper.add(this.numberField);
                    this.wrapper.add(this.numberWrapper);
                    this.numberLabel.editor = this.numberField;
                    this.numberLabel.text = Sol.Environment.resources.number;
                    this.numberField.maxLength = 6;
                    this.numberField.onChange = () => this.numberChanged();
                    this.complementWrapper.css.add("sol_address_complement");
                    this.complementWrapper.add(this.complementLabel);
                    this.complementField.autoWidth = false;
                    this.complementWrapper.add(this.complementField);
                    this.wrapper.add(this.complementWrapper);
                    this.complementLabel.editor = this.complementField;
                    this.complementLabel.text = Sol.Environment.resources.complement;
                    this.complementField.maxLength = 60;
                    this.map.ancho = 435;
                    this.add(this.map);
                    this.add(new Sol.LineBreak());
                    this.referencesWrapper.css.add("sol_address_references");
                    this.referencesWrapper.add(this.referencesLabel);
                    this.referencesWrapper.add(this.referencesField);
                    this.add(this.referencesWrapper);
                    this.referencesLabel.associatedControl = this.referencesField;
                    this.referencesLabel.caption = Sol.Environment.resources.references;
                    this.referencesField.maxLength = 320;
                    this.referencesLabel.expanded = false;
                    this.latitudeLabel.text = "Latitude:";
                    this.latitudeWrapper.add(this.latitudeLabel);
                    this.latitudeField.decimals = 7;
                    this.latitudeField.tamanoMaximo = 90;
                    this.latitudeField.acceptsNegative = true;
                    this.latitudeWrapper.add(this.latitudeField);
                    this.add(this.latitudeWrapper);
                    this.longitudeLabel.text = "Longitude:";
                    this.longitudeWrapper.add(this.longitudeLabel);
                    this.longitudeField.decimals = 7;
                    this.longitudeField.tamanoMaximo = 180;
                    this.longitudeField.acceptsNegative = true;
                    this.longitudeWrapper.add(this.longitudeField);
                    this.add(this.longitudeWrapper);
                }
                get isBrazil() { return this.countrySelector.selectedText.toUpperCase().substr(0, 3) == "BRA"; }
                get value() {
                    return {
                        ID: this.code,
                        País: this.countrySelector.selectedCode,
                        CountryName: this.countrySelector.selectedText,
                        Estado: this.stateSelector.selectedCode,
                        EstadoDesc: this.stateSelector.selectedText,
                        Ciudad: this.citySelector.selectedCode,
                        CiudadDesc: this.citySelector.selectedText,
                        Barrio: this.districtSelector.selectedCode,
                        DistrictDesc: this.districtSelector.selectedText,
                        Calle: this.streetField.value,
                        CódigoPostal: this.zipCodeField.value,
                        Number: this.numberField.value,
                        Complement: this.complementField.value,
                        AddressReferences: this.referencesField.value,
                        Latitude: this.latitudeField.value,
                        Longitude: this.longitudeField.value
                    };
                }
                set value(valor) {
                    this.code = valor.ID;
                    if (valor.País)
                        this.countrySelector.value = valor.País;
                    if (valor.Estado)
                        this.stateSelector.value = valor.Estado;
                    if (valor.Ciudad)
                        this.citySelector.value = valor.Ciudad;
                    if (valor.Barrio)
                        this.districtSelector.value = valor.Barrio;
                    if (!valor.Estado && valor.EstadoDesc)
                        this.stateSelector.selectedText = valor.EstadoDesc;
                    if (!valor.Ciudad && valor.CiudadDesc)
                        this.citySelector.selectedText = valor.CiudadDesc;
                    if (!valor.Barrio && valor.DistrictDesc)
                        this.districtSelector.selectedText = valor.DistrictDesc;
                    this.streetField.value = valor.Calle;
                    this.zipCodeField.value = valor.CódigoPostal;
                    this.numberField.value = valor.Number;
                    this.complementField.value = valor.Complement;
                    this.referencesField.value = valor.AddressReferences;
                    this.referencesLabel.expanded = !this.referencesField.isEmpty();
                    this.latitudeField.value = valor.Latitude;
                    this.longitudeField.value = valor.Longitude;
                    setTimeout(() => this.refreshMap(), 2500);
                }
                clear() {
                    this.countrySelector.clear();
                    this.stateSelector.clear();
                    this.citySelector.clear();
                    this.districtSelector.clear();
                    this.streetField.clear();
                    this.zipCodeField.clear();
                    this.numberField.clear();
                    this.complementField.clear();
                    this.referencesField.clear();
                    this.latitudeField.clear();
                    this.longitudeField.clear();
                }
                foco() { }
                isEmpty() {
                    return !this.value.País &&
                        !this.value.Calle &&
                        !this.value.Estado &&
                        !this.value.Ciudad &&
                        !this.value.Estado;
                }
                toControl() { return this; }
                validate() { return null; }
                build() {
                    if (this.configuration) {
                        this.showNumber = this.configuration.ShowNumber;
                        this.showComplement = this.configuration.ShowComplement;
                        this.showGeolocationFields = this.configuration.ShowGeolocationFields;
                    }
                    super.build();
                    if (this.defaultValue)
                        this.value = this.defaultValue;
                    this.numberWrapper.visible = this.configuration ? this.configuration.ShowNumber : this.showNumber;
                    this.complementWrapper.visible = this.configuration ? this.configuration.ShowComplement : this.showComplement;
                    this.referencesWrapper.visible = this.configuration ? this.configuration.ShowReferences : this.showReferences;
                    this.latitudeWrapper.visible = this.configuration ? this.configuration.ShowGeolocationFields : this.showGeolocationFields;
                    this.longitudeWrapper.visible = this.configuration ? this.configuration.ShowGeolocationFields : this.showGeolocationFields;
                    this.map.alto = this.showNumber || this.showComplement ? 361 : 310;
                    if (!this.showCountry)
                        this.map.alto -= 66;
                    this.map.visible = this.showMap;
                    this.countrySelector.readonly = this.readonly;
                    this.zipCodeLabel.visible = this.showPostalCode;
                    this.zipCodeField.visible = this.showPostalCode;
                    this.streetLabel.visible = this.showStreet;
                    this.streetField.visible = this.showStreet;
                    this.districtLabel.visible = this.showDistrict;
                    this.districtSelector.visible = this.showDistrict;
                    this.countryLabel.visible = this.showCountry;
                    this.countrySelector.visible = this.showCountry;
                    this.stateSelector.readonly = this.readonly;
                    this.citySelector.readonly = this.readonly;
                    this.districtSelector.readonly = this.readonly;
                    this.streetField.readonly = this.readonly;
                    this.zipCodeField.readonly = this.readonly;
                    this.numberField.readonly = this.readonly;
                    this.complementField.readonly = this.readonly;
                    this.referencesField.readonly = this.readonly;
                }
                stateSearch(stateId) {
                    return __awaiter(this, void 0, void 0, function* () {
                        if (this.countrySelector.isEmpty())
                            return null;
                        const result = yield Sol.Http.AjaxLight.postAsync("https://geo.letrearte.com/states", {
                            country: this.countrySelector.selectedCode,
                            lang: Sol.Environment.credential.idioma,
                            term: this.stateSelector.selectedText,
                            id: stateId
                        });
                        return result.Data;
                    });
                }
                citySearch(cityId) {
                    return __awaiter(this, void 0, void 0, function* () {
                        if (this.stateSelector.isEmpty())
                            return null;
                        const result = yield Sol.Http.AjaxLight.postAsync("https://geo.letrearte.com/cities", {
                            state: this.stateSelector.selectedCode,
                            lang: Sol.Environment.credential.idioma,
                            term: this.citySelector.selectedText,
                            id: cityId
                        });
                        return result.Data;
                    });
                }
                districtSearch(districtId) {
                    return __awaiter(this, void 0, void 0, function* () {
                        if (this.citySelector.isEmpty())
                            return null;
                        const result = yield Sol.Http.AjaxLight.postAsync("https://geo.letrearte.com/districts", {
                            city: this.citySelector.selectedCode,
                            lang: Sol.Environment.credential.idioma,
                            term: this.districtSelector.selectedText,
                            id: districtId
                        });
                        return result.Data;
                    });
                }
                countryChanged() {
                    this.zipCodeField.clear();
                    this.stateSelector.clear();
                    this.citySelector.clear();
                    this.districtSelector.clear();
                    this.refreshMap();
                    this.zipCodeField.isBrazil = this.isBrazil;
                }
                stateChanged() {
                    this.citySelector.clear();
                    this.districtSelector.clear();
                    this.refreshMap();
                }
                cityChanged() {
                    this.districtSelector.clear();
                    this.refreshMap();
                }
                districtChanged() {
                    this.refreshMap();
                }
                streetChanged() {
                    this.refreshMap();
                }
                numberChanged() {
                    this.refreshMap();
                }
                refreshMap() {
                    if (!this.showMap)
                        return;
                    this.map.showMap(this.value);
                }
                searchByZipCode() {
                    const language = Sol.Environment.credential.idioma;
                    const postalCode = this.zipCodeField.value;
                    Sol.Http.AjaxLight.get("https://geo.letrearte.com/postalcode/" + language + "/" + postalCode.soloDigitos(), model => this.loadModel(model), null);
                }
                loadModel(model) {
                    if (!model || !model.Data.State)
                        return;
                    if (this.stateSelector.selectedCode != model.Data.State)
                        this.stateSelector.value = model.Data.State;
                    if (this.citySelector.selectedCode != model.Data.City)
                        this.citySelector.value = model.Data.City;
                    if (this.districtSelector.selectedCode != model.Data.District)
                        this.districtSelector.value = model.Data.District;
                    if (model.Data.Street)
                        this.streetField.value = model.Data.Street;
                    this.streetField.foco();
                    this.refreshMap();
                }
            }
            Geo.AddressEditor = AddressEditor;
        })(Geo = Web.Geo || (Web.Geo = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("Dirección", model => {
    var _a;
    const addressEditor = new Sol.Web.Geo.AddressEditor();
    addressEditor.configuration = model.Configuration;
    addressEditor.showMap = (_a = model.Configuration) === null || _a === void 0 ? void 0 : _a.ShowMap;
    return addressEditor;
});
Sol.Web.Editors.registerFilter("AddressFilter", () => {
    const addressFilter = new Sol.Web.Geo.AddressEditor();
    addressFilter.showMap = false;
    addressFilter.showPostalCode = false;
    addressFilter.configuration =
        {
            ShowComplement: false,
            ShowNumber: false,
            ShowReferences: false,
            ShowMap: false,
            ShowGeolocationFields: false
        };
    return addressFilter;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Geo;
        (function (Geo) {
            class BillingAddressEditor extends Geo.AddressEditor {
                constructor() {
                    super();
                    this.copyAddressButton = new Sol.Button();
                    this.copyAddressButton.type = Sol.ButtonType.Link;
                    this.copyAddressButton.css.add("billing_address_button");
                    this.copyAddressButton.text = Sol.Environment.resources.copy_billing_address;
                    this.copyAddressButton.onClick = () => this.copyAddress();
                    this.controls.insert(0, this.copyAddressButton);
                }
                copyAddress() {
                    var address = this.container.editors.that(p => p.propertyName == "EntidadRelacionada$Dirección");
                    if (address) {
                        this.value = address.value;
                        this.code = 0;
                    }
                }
            }
            Geo.BillingAddressEditor = BillingAddressEditor;
        })(Geo = Web.Geo || (Web.Geo = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("BillingAddress", model => {
    const billingAddressEditor = new Sol.Web.Geo.BillingAddressEditor();
    billingAddressEditor.configuration = model.Configuration;
    billingAddressEditor.showMap = model.Configuration.ShowMap;
    return billingAddressEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Geo;
        (function (Geo) {
            class AddressDisplay extends Sol.Control {
                constructor() {
                    super();
                    this.isComplex = false;
                    this.errorMessage = new Sol.Control();
                    this.line1 = new Sol.Control();
                    this.line2 = new Sol.Control();
                    this.references = new Sol.Control();
                    this.css.add("sol_info_display");
                    const titulo = new Sol.Control("h5");
                    titulo.text = "Endereço do cliente:";
                    this.add(titulo);
                    this.add(this.line1);
                    this.add(this.line2);
                    this.references.css.add("sol_address_display_ref");
                    this.add(this.references);
                    this.errorMessage.css.add("sol_address_display_error");
                    this.add(this.errorMessage);
                }
                clear() { }
                foco() { }
                isEmpty() { return false; }
                loadAddress(code) {
                    if (!this.visible)
                        return;
                    Web.System.exec("nlskdjor", "GetShortAddress", { id: code }, e => {
                        this.errorMessage.text = e.ErrorMessage;
                        this.errorMessage.visible = e.Fail;
                        this.line1.text = e.Line1;
                        this.line1.visible = !e.Fail;
                        this.line2.text = e.Line2;
                        this.line2.visible = !e.Fail;
                        this.references.text = e.References;
                        this.references.visible = !e.Fail;
                    });
                }
                toControl() { return this; }
                validate() { return null; }
            }
            Geo.AddressDisplay = AddressDisplay;
        })(Geo = Web.Geo || (Web.Geo = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class LocalAction extends Actions.ActionBase {
                processResponse(data) {
                    var response = data;
                    this.errorMessage = response.ErrorMessage;
                    if (!response.Fail)
                        this.successMessage = Sol.Environment.resources.exito_accion;
                    if (this.onDone)
                        this.onDone(this);
                }
            }
            Actions.LocalAction = LocalAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class DownloadAction extends Actions.ActionBase {
                processResponse(data) {
                    window.open(data.FileLink || data.Response.FileLink, "_blank");
                }
            }
            Actions.DownloadAction = DownloadAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class BoletoAction extends Actions.ActionBase {
                processResponse(data) {
                    if (data.Fail) {
                        alert(data.ErrorMessage);
                        return;
                    }
                    Web.System.exec("laspoesd", "GenerateBoleto", {
                        credential: Sol.Environment.credential.export(),
                        code: data.Code,
                    }, e => {
                        if (!e.Fail)
                            window.open("", "_blank", "").document.write(e.Html);
                    }, null);
                }
            }
            Actions.BoletoAction = BoletoAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class PreviewScreenAction extends Actions.ActionBase {
                processResponse(data) {
                    if (data.Fail) {
                        alert(data.ErrorMessage);
                        return;
                    }
                    var details = new Web.Screens.DetailsScreen();
                    details.model = data.Detalles;
                    details.screenCaption = data.Title;
                    details.showCancelButton = true;
                    details.showOKButton = false;
                    details.showSaveButton = false;
                    details.myForm.cancelButton.text = Sol.Environment.resources.cerrar;
                    details.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    Web.System.screens.addScreen(details);
                    Web.System.screens.showScreen(details);
                }
            }
            Actions.PreviewScreenAction = PreviewScreenAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ReportGoalAction extends Actions.ActionBase {
                processResponse(data) {
                    if (data.Fail) {
                        alert(data.ErrorMessage);
                        return;
                    }
                    var reportScreen = Web.System.screens.openScreenWithModel("ReportScreen", null, null, null, data.Suggestion.ReportTitle);
                    reportScreen.openSuggestion(data.Suggestion);
                }
            }
            Actions.ReportGoalAction = ReportGoalAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class RefreshPCALinkListAction extends Actions.ActionBase {
                processResponse(data) {
                    this.toolScreen.getEditor("ForecastLog").refresh();
                }
            }
            Actions.RefreshPCALinkListAction = RefreshPCALinkListAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class SelectSystemsAction extends Actions.ActionBase {
                processResponse(data) {
                    Web.System.screens.closeCurrentScreen();
                }
                refresh() {
                    const isEmployeeScreen = Web.System.screens.currentDetails.className.indexOf("Employee") > -1;
                    Web.System.exec(isEmployeeScreen ? "yyrelasder9" : "hjkj28d", isEmployeeScreen ? "GetEmployeeSystems" : "GetSystems", { id: this.currentID }, e => this.screen.fields.first().value = e);
                }
            }
            Actions.SelectSystemsAction = SelectSystemsAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class GenericAction extends Actions.ActionBase {
                processResponse(data) {
                    if (this.model.ShowConfirmation)
                        alert(Sol.Environment.resources.exito_accion);
                    if (Web.System.screens.currentScreen instanceof Web.Screens.ActionScreen)
                        Web.System.screens.closeCurrentScreen();
                    if (this.model.CloseScreen)
                        Web.System.screens.closeCurrentScreen();
                    if (this.model.RequiresRefresh)
                        Web.System.screens.currentScreen.refreshSearch();
                    if (this.model.RequiresReload)
                        this.detailsScreen.reload();
                    if (this.onDone)
                        this.onDone(this);
                    if (data.SuccessMessage)
                        this.detailsScreen.showSucessMessage(data.SuccessMessage);
                }
            }
            Actions.GenericAction = GenericAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ViewDocumentAction extends Actions.ActionBase {
                processResponse(data) {
                    window.open("", "_blank", "").document.write(data.Html);
                }
            }
            Actions.ViewDocumentAction = ViewDocumentAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ApprovationLinkAction extends Actions.ActionBase {
                processResponse(data) {
                    var message = new Sol.ScreenMessage();
                    message.type = data.Fail ? Sol.MessageType.Error : Sol.MessageType.Success;
                    message.caption = data.Message;
                    message.closeWhenTap = data.Fail;
                    this.detailsScreen.myForm.controls.insert(0, message);
                    this.enabled = false;
                }
            }
            Actions.ApprovationLinkAction = ApprovationLinkAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class PublishAction extends Actions.ActionBase {
                processResponse(data) {
                    this.toolScreen.writeResponse(data.Message || data.ErrorMessage, data.Fail);
                    Web.System.home.refreshMenus();
                }
            }
            Actions.PublishAction = PublishAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class StartSaleAction extends Actions.ActionBase {
                processResponse(data) {
                    if (!Web.System.screens.backToDashboard())
                        return;
                    Web.System.screens.openScreen("Registro", data.SalesClassName, null, null, null, screen => setTimeout(() => {
                        screen.addNew();
                        screen.details.editors.that(e => e.propertyName == "Destinatario").value = data.CustomerData;
                    }, 300));
                }
            }
            Actions.StartSaleAction = StartSaleAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class PurchaseOrderAction extends Actions.ActionBase {
                processResponse(data) {
                    if (data.Fail) {
                        alert(data.ErrorMessage);
                        return;
                    }
                    Web.System.screens.openScreen("Registro", "Solarium.Commercial.Purchasing, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null, null, "Compras");
                }
            }
            Actions.PurchaseOrderAction = PurchaseOrderAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ReadAllMessagesAction extends Actions.ActionBase {
                processResponse() {
                    Web.System.home.resetMailCounter();
                }
            }
            Actions.ReadAllMessagesAction = ReadAllMessagesAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class CustomerHistoryScreenAction extends Actions.ActionBase {
                processResponse(data) {
                    Web.System.screens.openScreen("Solarium.Commercial.Screens.CustomerHistoryScreen", data.ContextClass, null, null, null, screen => {
                        const historyScreen = screen;
                        historyScreen.contextClass = data.ContextClass;
                        historyScreen.customHistoryColumns = Sol.List.from(data.Columns);
                    }, data.ClientID);
                }
            }
            Actions.CustomerHistoryScreenAction = CustomerHistoryScreenAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class LargeProcessAction extends Actions.ActionBase {
                doFormBasedAction() {
                    const doLargeRequest = {
                        className: this.model.ClassName,
                        methodName: this.model.MethodName,
                        id: this.currentID,
                        inputs: this.screen.values
                    };
                    Web.System.execLarge(this.engineManager, "DoLarge", doLargeRequest, e => {
                        var _a;
                        (_a = this.screen) === null || _a === void 0 ? void 0 : _a.form.workComplete();
                        if (e.Fail)
                            this.screen.showError(e.ErrorMessage);
                        else
                            this.processResponse(e);
                    });
                }
                processResponse(data) {
                    if (this.model.CloseScreen)
                        Web.System.screens.closeCurrentScreen();
                    if (this.model.RequiresReload)
                        this.detailsScreen.reload();
                    data.Message ? this.detailsScreen.showSucessMessage(data.Message) :
                        this.detailsScreen.showError(data.ErrorMessage);
                }
            }
            Actions.LargeProcessAction = LargeProcessAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class SendToPCPAction extends Actions.ActionBase {
                run() {
                    Web.System.exec("ej49jksdp", "SendToPCP", { licitationID: this.currentID }, e => {
                        alert(e.ErrorMessage);
                    });
                }
                processResponse(data) { }
            }
            Actions.SendToPCPAction = SendToPCPAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class CloneObjectAction extends Actions.ActionBase {
                processResponse(data) {
                    if (data.Fail)
                        return;
                    Web.System.screens.closeCurrentScreen();
                    Web.System.screens.closeCurrentScreen();
                    Web.System.screens.currentScreen.editItem(data.CloneID, null);
                }
            }
            Actions.CloneObjectAction = CloneObjectAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class DynamicScreenAction extends Actions.ActionBase {
                processResponse(scrModel) {
                    const details = new Web.Screens.DetailsScreen();
                    details.formState = Web.Screens.FormState.Edition;
                    details.screenCaption = scrModel.ScreenTitle;
                    details.model = scrModel.DetailsModel;
                    details.code = -1;
                    details.myScreen = Web.System.screens.currentScreen;
                    details.showSaveButton = false;
                    details.showSaveAndNew = false;
                    details.showOKButton = false;
                    details.readonlyScreen = true;
                    details.cancelButtonCaption = Sol.Environment.resources.cerrar;
                    details.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    Web.System.screens.addScreen(details);
                    Web.System.screens.showScreen(details);
                    details.editors.forEach(edt => edt.readonly = true);
                    details.loadData(scrModel.Data);
                    if (this.model.RequiresReload)
                        details.onClose.subscribe(() => this.detailsScreen.reload());
                }
            }
            Actions.DynamicScreenAction = DynamicScreenAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class OpenInNewTabAction extends Actions.ActionBase {
                processResponse(e) { Web.System.openTab(e.Ticket); }
            }
            Actions.OpenInNewTabAction = OpenInNewTabAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var NFe;
            (function (NFe) {
                let InvoiceStatus;
                (function (InvoiceStatus) {
                    InvoiceStatus[InvoiceStatus["Inexistent"] = 0] = "Inexistent";
                    InvoiceStatus[InvoiceStatus["Waiting"] = 1] = "Waiting";
                    InvoiceStatus[InvoiceStatus["Signed"] = 2] = "Signed";
                    InvoiceStatus[InvoiceStatus["Sent"] = 3] = "Sent";
                    InvoiceStatus[InvoiceStatus["Approved"] = 4] = "Approved";
                    InvoiceStatus[InvoiceStatus["Rejected"] = 5] = "Rejected";
                    InvoiceStatus[InvoiceStatus["Canceled"] = 6] = "Canceled";
                    InvoiceStatus[InvoiceStatus["Processing"] = 7] = "Processing";
                })(InvoiceStatus = NFe.InvoiceStatus || (NFe.InvoiceStatus = {}));
            })(NFe = Components.NFe || (Components.NFe = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var NFe;
            (function (NFe) {
                let NFeType;
                (function (NFeType) {
                    NFeType[NFeType["Sale"] = 1] = "Sale";
                    NFeType[NFeType["Service"] = 2] = "Service";
                    NFeType[NFeType["Coupon"] = 3] = "Coupon";
                })(NFeType = NFe.NFeType || (NFe.NFeType = {}));
            })(NFe = Components.NFe || (Components.NFe = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var NFe;
            (function (NFe) {
                class NFeNumberField extends Sol.Control {
                    constructor() {
                        super();
                        this.field = new Sol.IntegerField();
                        this.css.add("sol_nfe_number_field");
                        const label = new Sol.Label();
                        label.text = "Nº da próxima Nota:";
                        label.editor = this.field;
                        this.add(label);
                        this.field.onChange = () => this.fieldChange();
                        this.add(this.field);
                    }
                    get fixedNumber() { return this.isChanged ? this.field.numericValue : null; }
                    loadCurrentNumber(code, className, nfeType) {
                        Web.System.exec("7jdwiwp", "GetNextNumber", {
                            code: code,
                            className: className,
                            nfeType: nfeType
                        }, e => this.field.numericValue = e);
                    }
                    fieldChange() {
                        this.field.html.style.color = "red";
                        this.isChanged = true;
                    }
                }
                NFe.NFeNumberField = NFeNumberField;
            })(NFe = Components.NFe || (Components.NFe = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var NFe;
            (function (NFe) {
                class NFeCorrectionLetter extends Sol.Control {
                    constructor() {
                        super();
                        this.correctionLetterList = new Components.ListView();
                        this.correctionLetterArea = new Sol.Control();
                        this.addCLButton = new Sol.Button();
                        this.sendCLButton = new Sol.Button();
                        this.cancelCLButton = new Sol.Button();
                        this.correctionLetterTextField = new Sol.TextField();
                        this.css.add("sol_nfe_screen_tools");
                        this.initializeTitle();
                        this.initializeCorrectionLetterList();
                        this.initializeCorrectionLetterArea();
                    }
                    loadItems(letters) {
                        if (letters != null)
                            Sol.List.from(letters).forEach(item => this.correctionLetterList.addItemFromData([
                                { Campo: "Date", Valor: item.Date },
                                { Campo: "CorrectionText", Valor: item.CorrectionText },
                                { Campo: "Protocol", Valor: item.Protocol },
                                { Campo: "XmlNFe", Valor: item.Xml },
                                { Campo: "Print", Valor: "Imprimir" },
                                { Campo: "DownloadXml", Valor: "Baixar" }
                            ], item.ID));
                    }
                    initializeCorrectionLetterList() {
                        this.correctionLetterList.className = "Solarium.NFe.NFeCorrectionLetter, Solarium.NFe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.correctionLetterList.orderByProperty = "Date";
                        this.correctionLetterList.onInstantiateItem = i => this.instantiateItem(i);
                        this.correctionLetterList.configuration = Sol.List.from([
                            {
                                loadable: true,
                                caption: "Data",
                                cssClass: "sol_correction_letter_list_content",
                                property: "Date",
                                position: Components.ListViewFieldPosition.Left,
                                priority: Components.ListViewFieldPriority.High
                            },
                            {
                                loadable: true,
                                caption: "Protocolo",
                                cssClass: "sol_correction_letter_list_content",
                                property: "Protocol",
                                position: Components.ListViewFieldPosition.Right,
                                priority: Components.ListViewFieldPriority.High
                            },
                            {
                                loadable: true,
                                cssClass: "sol_correction_letter_list_text",
                                property: "CorrectionText"
                            },
                            {
                                loadable: true,
                                property: "XmlNFe",
                                hidden: true
                            },
                            {
                                loadable: false,
                                cssClass: "sol_correction_letter_list_button",
                                property: "Print"
                            },
                            {
                                loadable: false,
                                cssClass: "sol_correction_letter_list_button",
                                property: "DownloadXml"
                            }
                        ]);
                        this.addCLButton.text = "Adicionar carta de correção";
                        this.addCLButton.onClick = () => this.newCorrectionLetter();
                        this.addCLButton.type = Sol.ButtonType.Link;
                        this.correctionLetterList.add(this.addCLButton);
                        this.add(this.correctionLetterList);
                    }
                    newCorrectionLetter() {
                        this.correctionLetterArea.visible = true;
                        this.correctionLetterTextField.foco();
                    }
                    initializeCorrectionLetterArea() {
                        this.correctionLetterArea.visible = false;
                        this.sendCLButton.text = "Enviar";
                        this.cancelCLButton.text = "Cancelar";
                        this.sendCLButton.onClick = () => this.sendCorrectionLetter();
                        this.cancelCLButton.onClick = () => this.cancelCorrectionLetter();
                        this.correctionLetterTextField.maxLength = 1000;
                        this.correctionLetterArea.add(this.correctionLetterTextField);
                        this.correctionLetterArea.add(this.cancelCLButton);
                        this.correctionLetterArea.add(this.sendCLButton);
                        this.correctionLetterList.add(this.correctionLetterArea);
                    }
                    cancelCorrectionLetter() {
                        this.correctionLetterArea.visible = false;
                    }
                    sendCorrectionLetter() {
                        if (this.correctionLetterTextField.value.length < 15) {
                            alert("O texto de correção deve conter pelo menos 15 caracteres.");
                            return;
                        }
                        Web.System.exec("7jdwiwp", "SendCorrectionLetter", {
                            correctionText: this.correctionLetterTextField.value,
                            digitalInvoiceID: this.myScreen.invoiceCode
                        }, e => {
                            if (e.Fail)
                                alert(e.ErrorMessage);
                            else {
                                this.correctionLetterArea.visible = false;
                                this.correctionLetterList.visible = true;
                                this.correctionLetterList.addItemFromData([
                                    { Campo: "Date", Valor: e.Date },
                                    { Campo: "CorrectionText", Valor: this.correctionLetterTextField.value },
                                    { Campo: "Protocol", Valor: e.Protocol },
                                    { Campo: "XmlNFe", Valor: e.Xml },
                                    { Campo: "Print", Valor: "Imprimir" },
                                    { Campo: "DownloadXml", Valor: "Baixar" }
                                ], e.ID);
                                this.myScreen.letters.push({
                                    ID: e.ID,
                                    Date: e.Date,
                                    Protocol: e.Protocol,
                                    CorrectionText: this.correctionLetterTextField.value,
                                    Xml: e.Xml
                                });
                            }
                        });
                        this.correctionLetterArea.visible = false;
                    }
                    initializeTitle() {
                        const title = new Sol.Control("h5");
                        title.text = "Cartas de Correção";
                        this.add(title);
                    }
                    downloadPDF(letterID) {
                        Web.System.exec("7jdwiwp", "GenerateCorrectionLetterPDF", { correctionLetterID: letterID }, e => {
                            if (e.Fail)
                                alert(e.ErrorMessage);
                            else
                                window.open(e.FileLink, "_blank");
                        });
                    }
                    downloadXml(xml) {
                        var element = document.createElement('a');
                        element.setAttribute('href', 'data:text/xml;charset=utf-8,' + encodeURIComponent(xml));
                        element.setAttribute('download', "cartadecorrecao.xml");
                        element.style.display = 'none';
                        document.body.appendChild(element);
                        element.click();
                        document.body.removeChild(element);
                    }
                    instantiateItem(item) {
                        item.getDisplay("Print").onClick = () => this.downloadPDF(item.code);
                        item.getDisplay("DownloadXml").onClick = () => this.downloadXml(item.getModelValue("XmlNFe"));
                    }
                }
                NFe.NFeCorrectionLetter = NFeCorrectionLetter;
            })(NFe = Components.NFe || (Components.NFe = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var NFe;
            (function (NFe) {
                class NFeScreen extends Web.Screens.BaseScreen {
                    constructor() {
                        super();
                        this.mainArea = new Sol.Control();
                        this.toolsArea = new Sol.Control();
                        this.viewer = new Components.HtmlViewer();
                        this.correctionLetters = new NFe.NFeCorrectionLetter();
                        this.cancelButton = new Sol.Button();
                        this.updateButton = new Sol.Button();
                        this.statusText = new Sol.Control();
                        this.generateButton = new Sol.Button();
                        this.errorList = new Sol.Control("ul");
                        this.numberLabel = new Sol.Control("span");
                        this.numberField = new NFe.NFeNumberField();
                        this.printButton = new Sol.Button();
                        this.regenerateButton = new Sol.Button();
                        this.xmlButton = new Sol.Button();
                        this.additionalDataWrapper = new Sol.Control();
                        this.additionalDataField = new Sol.TextField();
                        this.css.add("sol_pantalla");
                        this.initializeScreenTitle();
                        this.mainArea.css.add("sol_nfe_screen");
                        this.add(this.mainArea);
                        this.toolsArea.css.add("sol_nfe_screen_tools");
                        this.mainArea.add(this.toolsArea);
                        this.initializeNumberDisplay();
                        this.initializeStatusText();
                        this.initializeNumberChanger();
                        this.initializeAdditionalDataDisplay();
                        this.initializeGenerateButton();
                        this.initializeRegenerateButton();
                        this.initializePrintButton();
                        this.initializeXmlButton();
                        this.initializeCancelButton();
                        this.initializeUpdateButton();
                        this.initializeErrorList();
                        this.initializeCorrectionLetters();
                        this.viewer.title = "Pré-visualização";
                        this.mainArea.add(this.viewer);
                    }
                    get number() { return this.numberLabel.text; }
                    set number(value) { this.numberLabel.text = value; }
                    get status() { return this._status; }
                    set status(value) {
                        this._status = value;
                        this.errorList.visible = false;
                        this.changeStatusMessage();
                        this.generateButton.visible = value == NFe.InvoiceStatus.Inexistent;
                        this.regenerateButton.visible = value == NFe.InvoiceStatus.Canceled || value == NFe.InvoiceStatus.Rejected;
                        this.printButton.visible = value == NFe.InvoiceStatus.Approved;
                        this.xmlButton.visible = value == NFe.InvoiceStatus.Approved;
                        this.cancelButton.visible = value == NFe.InvoiceStatus.Approved || value == NFe.InvoiceStatus.Signed || value == NFe.InvoiceStatus.Waiting;
                        this.numberLabel.visible = value == NFe.InvoiceStatus.Approved;
                        this.updateButton.visible = value == NFe.InvoiceStatus.Processing;
                        this.numberField.visible = this.showNumberField && (this.generateButton.visible || this.regenerateButton.visible);
                        this.additionalDataWrapper.visible = (value == NFe.InvoiceStatus.Inexistent || value == NFe.InvoiceStatus.Canceled || value == NFe.InvoiceStatus.Rejected) && this.showAdditionalData;
                        this.correctionLetters.visible = this.showCorrectionLetters && value == NFe.InvoiceStatus.Approved;
                    }
                    updateStatus(showError = true) {
                        Web.System.exec("7jdwiwp", "CheckInvoiceStatus", {
                            code: this.codes[0],
                            nfeType: this.nfeType
                        }, e => {
                            this.status = e.Status;
                            this.invoiceCode = e.Code;
                            if (this.status == NFe.InvoiceStatus.Approved)
                                this.numberLabel.text = e.FormattedNumber;
                            if (this.editor) {
                                this.editor.setLabel(this.status == NFe.InvoiceStatus.Approved ? e.FormattedNumber : this.nfeType == NFe.NFeType.Service ? "Gerar NFS-e" : "Gerar NF-e");
                                this.editor.currentStatus = e.Status;
                                this.editor.invoiceCode = e.Code;
                            }
                            this.letters = e.CorrectionLetters;
                            if (this.status == NFe.InvoiceStatus.Processing)
                                setTimeout(() => this.updateStatus(), 5000);
                            if (showError && this.status == NFe.InvoiceStatus.Rejected && !!e.RejectionReason)
                                this.showErrors([{ ErrorMessage: e.RejectionReason }]);
                        });
                    }
                    build() {
                        if (this.numberField.visible)
                            this.numberField.loadCurrentNumber(this.codes[0], this.className, this.nfeType);
                        if (this.correctionLetters.visible)
                            this.correctionLetters.loadItems(this.letters);
                        this.preview();
                    }
                    initializeScreenTitle() {
                        this.screenCaption = "Nota Fiscal Eletrônica";
                        var screenTitle = new Web.Screens.ScreenTitle();
                        screenTitle.text = this.screenCaption;
                        this.add(screenTitle);
                    }
                    initializeNumberDisplay() {
                        this.numberLabel.css.add("sol_nfe_number_display");
                        this.toolsArea.add(this.numberLabel);
                    }
                    initializeAdditionalDataDisplay() {
                        this.additionalDataWrapper.css.add("sol_detalles_wrapper sol_nfe_additional_data_field");
                        const additionalDataLabel = new Sol.Label();
                        additionalDataLabel.text = Sol.Environment.resources.additional_data + ":";
                        additionalDataLabel.editor = this.additionalDataField;
                        this.additionalDataWrapper.add(additionalDataLabel);
                        this.additionalDataWrapper.add(this.additionalDataField);
                        this.toolsArea.add(this.additionalDataWrapper);
                    }
                    initializeStatusText() {
                        this.statusText.css.add("sol_nfe_screen_label");
                        this.toolsArea.add(this.statusText);
                    }
                    initializeNumberChanger() {
                        this.toolsArea.add(this.numberField);
                    }
                    initializeGenerateButton() {
                        this.generateButton.text = "Gerar";
                        this.generateButton.type = Sol.ButtonType.Link;
                        this.generateButton.css.add("sol_nfe_screen_button");
                        this.generateButton.onClick = () => this.generate();
                        this.toolsArea.add(this.generateButton);
                    }
                    initializePrintButton() {
                        this.printButton.text = "Imprimir";
                        this.printButton.type = Sol.ButtonType.Link;
                        this.printButton.css.add("sol_nfe_screen_button");
                        this.printButton.onClick = () => this.print();
                        this.toolsArea.add(this.printButton);
                    }
                    initializeRegenerateButton() {
                        this.regenerateButton.text = "Reenviar";
                        this.regenerateButton.type = Sol.ButtonType.Link;
                        this.regenerateButton.css.add("sol_nfe_screen_button");
                        this.regenerateButton.onClick = () => this.generate();
                        this.toolsArea.add(this.regenerateButton);
                    }
                    initializeXmlButton() {
                        this.xmlButton.text = "Baixar XML";
                        this.xmlButton.type = Sol.ButtonType.Link;
                        this.xmlButton.css.add("sol_nfe_screen_button");
                        this.xmlButton.onClick = () => this.downloadXml();
                        this.toolsArea.add(this.xmlButton);
                    }
                    initializeCancelButton() {
                        this.cancelButton.text = "Cancelar";
                        this.cancelButton.type = Sol.ButtonType.Link;
                        this.cancelButton.css.add("sol_nfe_screen_button");
                        this.cancelButton.onClick = () => this.cancelNFe();
                        this.toolsArea.add(this.cancelButton);
                    }
                    initializeUpdateButton() {
                        this.updateButton.text = "Atualizar";
                        this.updateButton.type = Sol.ButtonType.Link;
                        this.updateButton.css.add("sol_nfe_screen_button");
                        this.updateButton.onClick = () => this.updateNFe();
                        this.toolsArea.add(this.updateButton);
                    }
                    initializeErrorList() {
                        this.toolsArea.add(this.errorList);
                    }
                    initializeCorrectionLetters() {
                        this.correctionLetters.myScreen = this;
                        this.toolsArea.add(this.correctionLetters);
                    }
                    cancelNFe() {
                        if (!confirm("Deseja realmente cancelar a nota fiscal?"))
                            return;
                        Web.System.exec("7jdwiwp", "CancelInvoice", { code: this.invoiceCode }, e => {
                            if (e.Fail)
                                alert("Não foi possível cancelar: " + e.ErrorMessage);
                            else
                                this.updateStatus();
                        });
                    }
                    changeStatusMessage() {
                        const statusDictionary = {
                            [NFe.InvoiceStatus.Inexistent]: "Ainda não existe nota fiscal emitida.",
                            [NFe.InvoiceStatus.Waiting]: "A nota fiscal está esperando a assinatura.",
                            [NFe.InvoiceStatus.Signed]: "A nota fiscal está sendo enviada.",
                            [NFe.InvoiceStatus.Sent]: "A nota fiscal foi enviada. Estamos aguardando o retorno.",
                            [NFe.InvoiceStatus.Approved]: "A nota fiscal está aprovada.",
                            [NFe.InvoiceStatus.Rejected]: "A nota fiscal foi rejeitada.",
                            [NFe.InvoiceStatus.Canceled]: "A nota fiscal foi cancelada.",
                            [NFe.InvoiceStatus.Processing]: "A nota fiscal está sendo processada."
                        };
                        this.statusText.text = statusDictionary[this.status];
                    }
                    downloadXml() {
                        window.open("/xmlnfe?invoiceID=" + this.invoiceCode, "_blank", "");
                    }
                    generate() {
                        this.generateButton.enabled = false;
                        this.regenerateButton.enabled = false;
                        this.errorList.visible = false;
                        const data = {
                            codes: this.codes,
                            className: this.className,
                            nfeType: this.nfeType,
                            fixedNumber: this.numberField.fixedNumber,
                            additionalData: this.additionalDataField.value
                        };
                        Web.System.exec("7jdwiwp", "GenerateInvoice", data, e => {
                            this.generateButton.enabled = true;
                            this.regenerateButton.enabled = true;
                            if (e.ValidationErrors.length > 0) {
                                this.showErrors(e.ValidationErrors);
                                return;
                            }
                            this.updateStatus();
                        });
                    }
                    showErrors(errors) {
                        this.errorList.visible = false;
                        if (errors.length == 0)
                            return;
                        this.errorList.controls.empty();
                        this.errorList.controls.addMany(Sol.List.from(errors).select(error => {
                            const errorItem = new Sol.Control("li");
                            errorItem.css.add("sol_nfe_error");
                            errorItem.text = error.ErrorMessage;
                            return errorItem;
                        }));
                        this.errorList.visible = true;
                    }
                    print() {
                        this.printButton.enabled = false;
                        Web.System.exec("7jdwiwp", "ViewInvoice", { code: this.invoiceCode }, e => {
                            const w = window.open("", "_blank", "");
                            w.document.write(e.Html);
                            this.printButton.enabled = true;
                        }, () => this.printButton.enabled = true);
                    }
                    preview() {
                        Web.System.exec("7jdwiwp", "Preview", {
                            codes: this.codes,
                            className: this.className,
                            nfeType: this.nfeType,
                            numberField: this.numberField.fixedNumber
                        }, e => this.viewer.setContent(e.Html));
                    }
                    updateNFe() {
                        this.updateButton.enabled = false;
                        Web.System.exec("7jdwiwp", "GetInvoiceUpdate", { code: this.invoiceCode }, () => {
                            this.updateButton.enabled = true;
                            this.updateStatus();
                        }, () => this.updateButton.enabled = true);
                    }
                }
                NFe.NFeScreen = NFeScreen;
            })(NFe = Components.NFe || (Components.NFe = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var NFe;
            (function (NFe) {
                class NFeScreenAction extends Web.Actions.ActionBase {
                    processResponse(e) {
                        const nfeScreen = new NFe.NFeScreen();
                        nfeScreen.codes = e.Response.Codes;
                        nfeScreen.className = e.Response.Configuration.ClassName;
                        nfeScreen.showNumberField = e.Response.Configuration.ShowNumberField;
                        nfeScreen.showCorrectionLetters = e.Response.Configuration.ShowCorrectionLetters;
                        nfeScreen.showAdditionalData = e.Response.Configuration.ShowAdditionalData;
                        nfeScreen.status = NFe.InvoiceStatus.Inexistent;
                        nfeScreen.nfeType = e.Response.Configuration.NFeType;
                        nfeScreen.letters = [];
                        Web.System.screens.addScreen(nfeScreen);
                        Web.System.screens.showScreen(nfeScreen);
                    }
                }
                NFe.NFeScreenAction = NFeScreenAction;
            })(NFe = Components.NFe || (Components.NFe = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var NFe;
            (function (NFe) {
                class NFeEditor extends Sol.Button {
                    constructor() {
                        super();
                        this.isComplex = false;
                        this.imageCode = "&#xf0f6;";
                        this.tip = "Nota Fiscal Eletrônica";
                        this.onClick = () => this.clickButton();
                    }
                    get value() { return this._value; }
                    set value(value) {
                        this._value = value;
                        Web.System.exec("7jdwiwp", "CheckInvoiceStatus", {
                            code: this.code,
                            nfeType: this.configuration.NFeType
                        }, e => {
                            this.currentStatus = e.Status;
                            this.invoiceCode = e.Code;
                            this.letters = e.CorrectionLetters;
                            if (this.currentStatus == NFe.InvoiceStatus.Approved)
                                this.setLabel(e.FormattedNumber);
                        });
                    }
                    clear() { }
                    foco() { }
                    isEmpty() { return false; }
                    setLabel(value) { this.html.childNodes[1].nodeValue = value; }
                    toControl() { return this; }
                    validate() { return null; }
                    checkIfScreenIsSaved() {
                        var detailsScreen = this.container.toControl().parent;
                        if (detailsScreen.isChanged) {
                            detailsScreen.savingConfirmationMessage.visible = true;
                            detailsScreen.onLocalSaved.subscribe(() => this.clickButton());
                            return false;
                        }
                        return true;
                    }
                    clickButton() {
                        if (!this.checkIfScreenIsSaved())
                            return;
                        const nfeScreen = new NFe.NFeScreen();
                        nfeScreen.codes = [this.code];
                        nfeScreen.editor = this;
                        nfeScreen.invoiceCode = this.invoiceCode;
                        nfeScreen.className = this.configuration.ClassName;
                        nfeScreen.showNumberField = this.configuration.ShowNumberField;
                        nfeScreen.showCorrectionLetters = this.configuration.ShowCorrectionLetters;
                        nfeScreen.showAdditionalData = this.configuration.ShowAdditionalData;
                        nfeScreen.status = this.currentStatus;
                        nfeScreen.nfeType = this.configuration.NFeType;
                        nfeScreen.letters = this.letters;
                        if (this.currentStatus == NFe.InvoiceStatus.Approved)
                            nfeScreen.number = this.text;
                        if (this.currentStatus == NFe.InvoiceStatus.Processing)
                            nfeScreen.updateStatus();
                        Web.System.screens.addScreen(nfeScreen);
                        Web.System.screens.showScreen(nfeScreen);
                        nfeScreen.updateStatus(false);
                    }
                }
                NFe.NFeEditor = NFeEditor;
            })(NFe = Components.NFe || (Components.NFe = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class NfeCorrectionLetterButton extends Sol.Button {
                constructor() {
                    super();
                    this.imageCode = '&#xf1c1;';
                    this.text = "Download PDF";
                    this.tip = Sol.Environment.resources.nfeCorrrectionLetterButtonTip;
                    this.css.add("sol_nf_correction_letter_button");
                    this.onClick = () => this.downloadPDF(this.value);
                }
                toControl() { return this; }
                downloadPDF(value) {
                    Web.System.exec("7jdwiwp", "GenerateCorrectionLetterPDF", { correctionLetterID: value }, e => {
                        if (e.Fail)
                            alert(e.ErrorMessage);
                        else
                            window.open(e.FileLink, "_blank");
                    });
                }
                clear() { }
                foco() { }
                isEmpty() { return true; }
                validate() { return null; }
            }
            Components.NfeCorrectionLetterButton = NfeCorrectionLetterButton;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("NfeCorrectionLetterButton", () => new Sol.Web.Components.NfeCorrectionLetterButton());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class MessageSenderEditor extends Sol.Control {
                constructor() {
                    super();
                    this.css.add("sol_campo");
                }
                get value() { return this._valor; }
                set value(value) { this.add(new Components.MessageContactDisplay(this._valor = value)); }
                toControl() { return this; }
                clear() { }
                foco() { }
                isEmpty() { return false; }
                validate() { return null; }
            }
            Components.MessageSenderEditor = MessageSenderEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class MessageReplyAction extends Actions.ActionBase {
                processResponse(data) {
                    var _a;
                    let message = Web.System.screens.currentScreen;
                    let account = ((_a = message.getEditor("Account")) === null || _a === void 0 ? void 0 : _a.selectedCode) || "-1";
                    let sender = message.getEditor("MessageSender").value;
                    let subject = "Re: " + message.getEditor("Subject").value;
                    let messageText = message.getEditor("Content").value;
                    Web.System.screens.currentFileScreen.addNew();
                    const replyScreen = Web.System.screens.currentScreen;
                    const replyAccountCombo = replyScreen.getEditor("Account");
                    replyScreen.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    if (replyAccountCombo)
                        replyAccountCombo.selectedCode = account;
                    replyScreen.getEditor("MessageRecipients").addContact(sender);
                    replyScreen.getEditor("Subject").value = subject;
                    replyScreen.getEditor("Content").value = "<br /><br /><br />" + Sol.Environment.resources.original_message + ":<br /><br />" + messageText;
                }
            }
            Actions.MessageReplyAction = MessageReplyAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class MessageReplyToAllAction extends Actions.ActionBase {
                processResponse(data) {
                    let messageScreen = Web.System.screens.currentScreen;
                    let accountCombo = messageScreen.getEditor("Account");
                    let account = (accountCombo === null || accountCombo === void 0 ? void 0 : accountCombo.selectedCode) || "-1";
                    let accountMail = accountCombo === null || accountCombo === void 0 ? void 0 : accountCombo.selectedText;
                    let sender = messageScreen.getEditor("MessageSender").value;
                    let sourceRecipients = messageScreen.getEditor("MessageRecipients");
                    let subject = "Re: " + messageScreen.getEditor("Subject").value;
                    let messageText = messageScreen.getEditor("Content").value;
                    Web.System.screens.currentFileScreen.addNew();
                    const replyScreen = Web.System.screens.currentScreen;
                    const replyAccountCombo = replyScreen.getEditor("Account");
                    replyScreen.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    if (replyAccountCombo)
                        replyAccountCombo.selectedCode = account;
                    let recipients = replyScreen.getEditor("MessageRecipients");
                    recipients.addContact(sender);
                    sourceRecipients
                        .contacts
                        .where(ct => ct.model.Email != accountMail)
                        .forEach(ct => recipients.addContact(ct.model));
                    replyScreen.getEditor("Subject").value = subject;
                    replyScreen.getEditor("Content").value = "<br /><br /><br />" + Sol.Environment.resources.original_message + ":<br /><br />" + messageText;
                }
            }
            Actions.MessageReplyToAllAction = MessageReplyToAllAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class MessageForwardAction extends Actions.ActionBase {
                processResponse(data) {
                    const message = Web.System.screens.currentScreen;
                    const account = message.getEditor("Account").selectedCode || "-1";
                    const attachments = message.getEditor("MessageAttachments").value;
                    const subject = "ENC: " + message.getEditor("Subject").value;
                    const messageText = message.getEditor("Content").value;
                    Web.System.screens.currentFileScreen.addNew();
                    const forwardScreen = Web.System.screens.currentScreen;
                    forwardScreen.myForm.onCancel = () => Web.System.screens.closeCurrentScreen();
                    forwardScreen.getEditor("Account").selectedCode = account;
                    forwardScreen.getEditor("Subject").value = subject;
                    const attachmentsEditor = forwardScreen.getEditor("MessageAttachments");
                    attachmentsEditor.value = attachments;
                    attachmentsEditor.clearFileIds();
                    attachmentsEditor.myLabel.expanded = !attachmentsEditor.isEmpty();
                    forwardScreen.getEditor("Content").value = "<br /><br /><br /> " + Sol.Environment.resources.forwarded_message + ":<br /><br />  " + messageText;
                    forwardScreen.getEditor("MessageRecipients").foco();
                }
            }
            Actions.MessageForwardAction = MessageForwardAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class HistoryScreenAction extends Actions.ActionBase {
                run() {
                    const screen = new Web.Screens.PropertyHistoryScreen();
                    screen.screenCaption = this.model.Name;
                    screen.propertyName = this.model.PropertyName;
                    screen.showDifference = this.model.ModelType.indexOf("SNumber") > -1;
                    Web.System.screens.addScreen(screen);
                    Web.System.screens.showScreen(screen);
                }
                processResponse(data) { }
            }
            Actions.HistoryScreenAction = HistoryScreenAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class PropertyHistoryScreen extends Screens.HistoryScreenBase {
                constructor() {
                    super(...arguments);
                    this.manager = "i3n48smak";
                    this.methodName = "GetPropertyHistory";
                }
                configureColumns() {
                    this.grid.columns = Sol.List.from([
                        {
                            Title: Sol.Environment.resources.date,
                            DataType: "SDate",
                            PropertyName: "ChangeDate",
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: Sol.Environment.resources.usuario,
                            DataType: "SText",
                            PropertyName: "LoginName",
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: Sol.Environment.resources.amount,
                            DataType: "SInteger",
                            PropertyName: "NewValue",
                            Alignment: Sol.Alignment.Center,
                            ShowTitle: true,
                            Visible: true
                        }
                    ]);
                    if (this.showDifference)
                        this.grid.columns.add({
                            Title: Sol.Environment.resources.variation,
                            DataType: "SInteger",
                            PropertyName: "Difference",
                            ShowTitle: true,
                            Alignment: Sol.Alignment.Center,
                            Visible: true
                        });
                    this.grid.columns.add({
                        Title: Sol.Environment.resources.description,
                        DataType: "SText",
                        PropertyName: "Description",
                        ShowTitle: true,
                        Visible: true
                    });
                }
                getSearchData() {
                    return {
                        credential: Sol.Environment.credential.export(),
                        className: this.className,
                        id: this.code,
                        property: this.propertyName,
                        interval: this.interval.value,
                        pageCount: this.gridRowCount,
                        pageNumber: this.currentPage
                    };
                }
            }
            Screens.PropertyHistoryScreen = PropertyHistoryScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            class ParticipantTypeCombo extends Web.Components.DataCombo {
                get consultantsCombo() {
                    return this.container.getEditor("Consultant");
                }
                constructor() {
                    super();
                    this.preFilters = [{ PropertyName: "Active", FilterType: "SBoolean", FilterValue: true }];
                }
                build() {
                    super.build();
                    this.onValueModified.subscribe(() => this.updateConsultants());
                }
                updateConsultants() {
                    this.consultantsCombo.filters = Sol.List.from([
                        {
                            PropertyName: "Participation",
                            FilterType: "SInteger",
                            FilterValue: this.selectedCode
                        },
                        {
                            PropertyName: "Activo",
                            FilterType: "SBoolean",
                            FilterValue: true
                        }
                    ]);
                    this.consultantsCombo.clear();
                    this.consultantsCombo.refresh();
                }
            }
            Commercial.ParticipantTypeCombo = ParticipantTypeCombo;
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ParticipantTypeCombo", model => {
    const participantCombo = new Sol.Web.Commercial.ParticipantTypeCombo();
    participantCombo.className = model.DataTypeFullName;
    return participantCombo;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Sales;
            (function (Sales) {
                class NewCustomerEditor extends Web.FieldGroupEditor {
                    constructor() {
                        super();
                        this.customerName = new Sol.Field();
                        this.customerPhone = new Sol.PhonesEditor();
                        this.customerEmail = new Sol.EmailField();
                        this.customerAddress = new Web.Geo.AddressEditor();
                        this.leadOriginSelector = new Web.Components.DataCombo();
                        this.personTypeChoice = new Sol.MultipleChoice();
                        this.contactNameWrapper = new Sol.Control();
                        this.contactName = new Sol.Field();
                        this.contactEmailWrapper = new Sol.Control();
                        this.contactEmail = new Sol.EmailField();
                        this.taxIDLabel = new Sol.Label();
                        this.taxID = new Web.Components.TaxIDField();
                        this.createCustomerForm();
                        this.personTypeChoice.onChange.subscribe(() => this.selectFields());
                    }
                    get value() {
                        var currentValues = Sol.List.from([
                            { Campo: "ID", Valor: 0 },
                            { Campo: this.customerName.propertyName, Valor: this.customerName.textValue },
                            { Campo: "EntidadRelacionada$Email", Valor: this.customerEmail.value },
                            { Campo: "EntidadRelacionada$Dirección", Valor: this.customerAddress.value },
                            { Campo: "EntidadRelacionada$NúmeroDocumento", Valor: this.taxID.value },
                            { Campo: "ContactName", Valor: this.contactName.textValue },
                            { Campo: "ContactEmail", Valor: this.contactEmail.value },
                            { Campo: "LeadOrigin", Valor: this.leadOriginSelector.value },
                            { Campo: "Subtype", Valor: this.personTypeChoice.selectedCode },
                            { Campo: "EntidadRelacionada$Teléfonos", Valor: this.customerPhone.value }
                        ]);
                        currentValues.forEach(v => v.Campo = "QuickCustomerRegistration$" + v.Campo);
                        return currentValues.toArray();
                    }
                    set value(value) { }
                    clear() {
                        this.customerName.clear();
                        this.customerEmail.clear();
                        this.customerPhone.clear();
                        this.customerAddress.clear();
                        this.leadOriginSelector.clear();
                        this.personTypeChoice.clear();
                        this.contactName.clear();
                        this.contactEmail.clear();
                    }
                    foco() { this.customerName.foco(); }
                    isEmpty() { return this.customerName.isEmpty() || this.customerPhone.isEmpty(); }
                    validate() { return null; }
                    toControl() { return this; }
                    createCustomerForm() {
                        this.personTypeChoice.inlineItems = true;
                        this.personTypeChoice.options = [
                            { Code: "1", Description: "Pessoa Jurídica", Checked: false },
                            { Code: "2", Description: "Pessoa Física", Checked: true }
                        ];
                        this.add(this.personTypeChoice);
                        var nameWrapper = new Sol.FieldWrapper();
                        var nameLabel = new Sol.Label();
                        nameLabel.text = Sol.Environment.resources.name;
                        nameLabel.editor = this.customerName;
                        this.customerName.maxLength = 85;
                        this.customerName.required = true;
                        nameWrapper.add(nameLabel);
                        nameWrapper.add(this.customerName);
                        this.editors.add(this.customerName);
                        this.customerName.propertyName = "EntidadRelacionada$Nombre";
                        this.add(nameWrapper);
                        var taxIDWrapper = new Sol.FieldWrapper();
                        this.taxIDLabel.editor = this.taxID;
                        this.taxID.container = this;
                        this.taxIDLabel.text = "CPF";
                        taxIDWrapper.add(this.taxIDLabel);
                        taxIDWrapper.add(this.taxID);
                        this.add(taxIDWrapper);
                        var emailWrapper = new Sol.FieldWrapper();
                        var emailLabel = new Sol.Label();
                        emailLabel.text = "E-mail";
                        emailLabel.editor = this.customerEmail;
                        emailWrapper.add(emailLabel);
                        emailWrapper.add(this.customerEmail);
                        this.add(emailWrapper);
                        const originWrapper = new Sol.FieldWrapper();
                        const leadOriginLabel = new Sol.Label();
                        leadOriginLabel.text = Sol.Environment.resources.lead_origin;
                        this.leadOriginSelector.className = "Solarium.Commercial.LeadOrigin, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        originWrapper.add(leadOriginLabel);
                        originWrapper.add(this.leadOriginSelector);
                        this.add(originWrapper);
                        this.leadOriginSelector.refresh();
                        var contactNameLabel = new Sol.Label();
                        contactNameLabel.text = "Nome do contato";
                        contactNameLabel.editor = this.contactName;
                        this.contactName.maxLength = 85;
                        this.contactNameWrapper.add(contactNameLabel);
                        this.contactNameWrapper.add(this.contactName);
                        this.contactNameWrapper.css.add("sol_detalles_wrapper");
                        this.contactNameWrapper.visible = false;
                        this.add(this.contactNameWrapper);
                        var contactEmailLabel = new Sol.Label();
                        contactEmailLabel.text = "E-mail do contato";
                        contactEmailLabel.editor = this.contactEmail;
                        this.contactEmailWrapper.add(contactEmailLabel);
                        this.contactEmailWrapper.add(this.contactEmail);
                        this.contactEmailWrapper.css.add("sol_detalles_wrapper");
                        this.contactEmailWrapper.visible = false;
                        this.add(this.contactEmailWrapper);
                        var phoneLabel = new Sol.Label();
                        phoneLabel.text = Sol.Environment.resources.telefonos;
                        phoneLabel.editor = this.customerPhone;
                        this.customerPhone.required = true;
                        this.add(phoneLabel);
                        this.add(this.customerPhone);
                        this.customerAddress.showCountry = false;
                        this.customerAddress.showReferences = false;
                        this.add(this.customerAddress);
                    }
                    selectFields() {
                        this.contactNameWrapper.visible = this.personTypeChoice.selectedCode == 1;
                        this.contactEmailWrapper.visible = this.personTypeChoice.selectedCode == 1;
                        this.taxIDLabel.text = this.personTypeChoice.selectedCode == 1 ? "CNPJ" : "CPF";
                    }
                }
                Sales.NewCustomerEditor = NewCustomerEditor;
            })(Sales = Commercial.Sales || (Commercial.Sales = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("NewCustomerEditor", (model, cls, id, structure) => {
    if (id)
        return null;
    const clientSelector = Sol.List.from(structure).that(f => f.PropertyName == "Destinatario");
    return !clientSelector || clientSelector.Visibility != Sol.FieldVisibility.Always ?
        new Sol.Web.Commercial.Sales.NewCustomerEditor() : null;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Sales;
            (function (Sales) {
                class OtherCostsEditor extends Web.Components.DataView {
                    constructor() {
                        super();
                        this.showSearchBox = false;
                        this.fixedRows = false;
                        this.showVerticalLines = true;
                        this.showChecks = false;
                        this.showFieldChanges = false;
                    }
                    get isSummable() { return true; }
                    get cost() {
                        var totalCost = 0;
                        this.rows.forEach(r => totalCost += r.getEditor("Cost").numericValue);
                        return totalCost;
                    }
                    get total() { return 0; }
                    get margin() { return -this.cost; }
                    build() {
                        super.build();
                        this.grid.onInstantiateRow = row => {
                            const currencyField = row.getEditor("Cost");
                            currencyField.onValueModified.subscribe(() => this.onTotalsChanged());
                            currencyField.onSet.subscribe(() => this.onTotalsChanged());
                        };
                    }
                }
                Sales.OtherCostsEditor = OtherCostsEditor;
            })(Sales = Commercial.Sales || (Commercial.Sales = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("OtherCostsEditor", model => {
    const otherCostsEditor = new Sol.Web.Commercial.Sales.OtherCostsEditor();
    otherCostsEditor.className = model.DataTypeFullName;
    otherCostsEditor.readonly = model.ReadOnly;
    Sol.Web.Editors.fillDataViewStructure(otherCostsEditor, model.Structure);
    return otherCostsEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Services;
            (function (Services) {
                class ServiceTimeEditor extends Sol.TimeField {
                    constructor() {
                        super();
                        this.calcButton = new Sol.Button();
                        this.css.add("sol_calculable_field");
                        this.calcButton.css.add("sol_calculable_field_button");
                        this.calcButton.imageCode = "&#xf1ec;";
                        this.add(this.calcButton);
                        this.calcButton.onClick = () => this.calculate();
                    }
                    calculate() {
                        var technicianID = this.container.editors.that(edt => edt.propertyName == "Technician").selectedCode;
                        if (!technicianID) {
                            alert("Nenhum técnico selecionado.");
                            return;
                        }
                        var serviceData = this.container.editors.that(edt => edt.propertyName == "Services").value;
                        if (serviceData.length == 0) {
                            alert("Nenhum serviço informado.");
                            return;
                        }
                        var services = [];
                        serviceData.forEach(sr => {
                            var service = Sol.List.from(sr);
                            var quantity = service.where(i => i.Campo == "Quantity").first().Valor;
                            if (!quantity) {
                                alert("Informe a quantidade de cada serviço.");
                                return;
                            }
                            var model = {
                                ID: service.where(i => i.Campo == "Service").first().Valor,
                                Quantity: quantity
                            };
                            services.push(model);
                        });
                        const data = {
                            credential: Sol.Environment.credential.export(),
                            technicianID: technicianID,
                            serviceModels: services
                        };
                        var dateField = this.container.editors.that(edt => edt.propertyName == "CompletionDate");
                        Web.System.exec("79kcj30h", "CalculateCompletionTime", data, e => {
                            if (e.Fail)
                                alert(e.ErrorMessage);
                            else {
                                dateField.value = e.Date.split("T")[0];
                                this.value = e.Date.split("T")[1];
                            }
                        });
                    }
                }
                Services.ServiceTimeEditor = ServiceTimeEditor;
            })(Services = Commercial.Services || (Commercial.Services = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ServiceTimeEditor", () => new Sol.Web.Commercial.Services.ServiceTimeEditor());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Services;
            (function (Services) {
                class ServiceQuotationEditor extends Sol.Control {
                    constructor() {
                        super();
                        this.CLASS_TYPE = "Solarium.Commercial.ServiceQuotation, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.codeDisplay = new Sol.Field();
                        this.dataWrapper = new Sol.Control();
                        this.editButton = new Sol.Button();
                        this.loadDisplay = new Sol.Control("span");
                        this.statusDisplay = new Sol.ObjectDisplay();
                        this.nameDisplay = new Sol.ObjectDisplay();
                        this.empty = true;
                        this.isComplex = true;
                        this.readonly = true;
                        this.loadDisplay.text = Sol.Environment.resources.cargando;
                        this.add(this.loadDisplay);
                        this.css.add("sol_service_quotation_editor");
                        this.dataWrapper.css.add("sol_service_quotation_editor_wrapper");
                        const codeWrapper = new Sol.FieldWrapper();
                        codeWrapper.add(new Sol.Label("Código da cotação:"));
                        this.codeDisplay.readonly = true;
                        codeWrapper.add(this.codeDisplay);
                        this.dataWrapper.add(codeWrapper);
                        const statusWrapper = new Sol.FieldWrapper();
                        statusWrapper.add(new Sol.Label("Status:"));
                        statusWrapper.add(this.statusDisplay);
                        this.dataWrapper.add(statusWrapper);
                        const nameWrapper = new Sol.FieldWrapper();
                        nameWrapper.add(new Sol.Label("Descrição:"));
                        this.nameDisplay.css.addMany(["sol_service_quotation_name", "sol_campo"]);
                        nameWrapper.add(this.nameDisplay);
                        this.dataWrapper.add(nameWrapper);
                        this.dataWrapper.visible = false;
                        this.add(this.dataWrapper);
                        this.editButton.css.add("sol_service_quotation_editor_button");
                        this.editButton.imageCode = "&#xf07c;";
                        this.editButton.visible = false;
                        this.editButton.onClick = () => this.editQuotation();
                        this.dataWrapper.add(this.editButton);
                    }
                    get value() { return this._value; }
                    set value(v) {
                        this._value = v;
                        this.refresh();
                    }
                    clear() { }
                    foco() { }
                    isEmpty() { return this.empty; }
                    toControl() { return this; }
                    validate() { return null; }
                    refresh() {
                        Web.System.exec("79k8jhkh", "GetServiceQuotationInfo", { quotationID: this.value }, e => {
                            this.loadDisplay.text = e.ErrorMessage;
                            this.loadDisplay.visible = e.Fail;
                            this.editButton.visible = !e.Fail;
                            this.dataWrapper.visible = !e.Fail;
                            this.empty = !e.Fail;
                            if (!e.Fail) {
                                this.quotationID = e.QuotationCode;
                                this.codeDisplay.value = e.FormattedQuotationCode;
                                this.statusDisplay.value = e.Status;
                                this.nameDisplay.value = e.QuotationName;
                            }
                        });
                    }
                    build() {
                        super.build();
                        this.refresh();
                    }
                    editQuotation() {
                        Web.System.edit(this.CLASS_TYPE, this.quotationID, screen => {
                            screen.onSaved.subscribe(() => this.refresh());
                            screen.onLocalSaved.subscribe(() => this.refresh());
                            screen.onClose.subscribe(() => this.refresh());
                        });
                    }
                }
                Services.ServiceQuotationEditor = ServiceQuotationEditor;
            })(Services = Commercial.Services || (Commercial.Services = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ServiceQuotationEditor", () => new Sol.Web.Commercial.Services.ServiceQuotationEditor());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Services;
            (function (Services) {
                class ServiceQuotationTable extends Web.Components.DataView {
                    constructor() {
                        super();
                        this.showSearchBox = false;
                        this.fixedRows = false;
                        this.showChecks = false;
                        this.allowDelete = false;
                        this.availableColumns.add({
                            Alignment: Sol.Alignment.Left,
                            Title: "",
                            DataType: "STemplate",
                            ShowTitle: false,
                            Visible: true,
                            EditorModel: {
                                DataType: "ServiceQuotationEditor",
                                PropertyName: "QuotationDetails",
                                Visibility: Sol.FieldVisibility.Always
                            },
                            PropertyName: "QuotationDetails",
                            VerticalAlignment: Sol.VerticalAlignment.Top
                        });
                        let curScreen = Web.System.screens.currentDetails;
                        this.onAddingItem = () => {
                            if (!curScreen.code) {
                                alert("Salve primeiro a venda antes de criar uma cotação");
                                return;
                            }
                            Web.System.create("Solarium.Commercial.ServiceQuotation, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", e => {
                                e.getEditor("SaleID").value = curScreen.code;
                                e.getEditor("Customer").value = curScreen.getEditor("Destinatario").value;
                                e.onSaved.subscribe(() => this.addOrUpdateItem(e.code));
                                e.onLocalSaved.subscribe(() => this.addOrUpdateItem(e.code));
                            });
                        };
                    }
                    addOrUpdateItem(code) {
                        let curRow = this.rows.that(row => row.getEditor("QuotationDetails").value == code);
                        if (curRow)
                            curRow.getEditor("QuotationDetails").refresh();
                        else
                            this.addRow([{ Campo: "QuotationDetails", Valor: code }]);
                        this.container.parent.reloadFields();
                    }
                }
                Services.ServiceQuotationTable = ServiceQuotationTable;
            })(Services = Commercial.Services || (Commercial.Services = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ServiceQuotationTable", (model, className, code) => {
    const table = new Sol.Web.Commercial.Services.ServiceQuotationTable();
    table.readonly = model.ReadOnly;
    return table;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            class PurchaseDetailsEditor extends Web.Components.DetailsEditor {
                constructor() {
                    super();
                    this.isSummable = true;
                    this.cost = 0;
                    this.total = 0;
                    this.details.onBuildComplete = () => this.initialize();
                }
                get taxesField() { return this.getEditor("Taxes"); }
                get margin() { var _a; return (((_a = this.taxesField) === null || _a === void 0 ? void 0 : _a.numericValue) * -1) || 0; }
                initialize() {
                    if (this.taxesField && this.onTotalsChanged)
                        this.taxesField.onChange = () => this.onTotalsChanged();
                }
            }
            Commercial.PurchaseDetailsEditor = PurchaseDetailsEditor;
            Sol.Web.Editors.registerEditor("PurchaseDetailsEditor", model => {
                const purchaseDetailsEditor = new Sol.Web.Commercial.PurchaseDetailsEditor();
                purchaseDetailsEditor.model = model.ScreenModel;
                return purchaseDetailsEditor;
            });
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Taxes;
        (function (Taxes) {
            class TaxSummaryControl extends Sol.Control {
                constructor(model) {
                    super();
                    this.css.add("sol_tax_summary");
                    var taxName = new Sol.Control("h5");
                    taxName.text = model.TaxName;
                    taxName.estilos.agregar("color", model.TaxColor);
                    this.add(taxName);
                    var table = new Sol.Control("table");
                    var headerLine = new Sol.Control("tr");
                    var incomeHeader = new Sol.Control("th");
                    incomeHeader.text = "Crédito Entrada";
                    var revenueHeader = new Sol.Control("th");
                    revenueHeader.text = "Venda";
                    var basisLine = new Sol.Control("tr");
                    var incomeBasis = new Sol.Control("td");
                    incomeBasis.text = "Base de Cálculo: " + model.PurchasingIncidence.BasisCalculationText;
                    var revenueBasis = new Sol.Control("td");
                    revenueBasis.text = "Base de Cálculo: " + model.SaleIncidence.BasisCalculationText;
                    var taxLine = new Sol.Control("tr");
                    var incomeTax = new Sol.Control("td");
                    incomeTax.text = "Alíquota: " + model.PurchasingIncidence.TaxRateText;
                    var revenueTax = new Sol.Control("td");
                    revenueTax.text = "Alíquota: " + model.SaleIncidence.TaxRateText;
                    var amountLine = new Sol.Control("tr");
                    var incomeAmount = new Sol.Control("td");
                    incomeAmount.text = "Valor: " + model.PurchasingIncidence.TaxAmountText;
                    var revenueAmount = new Sol.Control("td");
                    revenueAmount.text = "Valor: " + model.SaleIncidence.TaxAmountText;
                    headerLine.add(incomeHeader);
                    headerLine.add(revenueHeader);
                    table.add(headerLine);
                    basisLine.add(incomeBasis);
                    basisLine.add(revenueBasis);
                    table.add(basisLine);
                    taxLine.add(incomeTax);
                    taxLine.add(revenueTax);
                    table.add(taxLine);
                    amountLine.add(incomeAmount);
                    amountLine.add(revenueAmount);
                    table.add(amountLine);
                    this.add(table);
                    var totalTax = new Sol.Control();
                    totalTax.css.add("sol_tax_summary_total");
                    totalTax.text = Sol.Environment.resources.total + ": " + model.TaxAmountText;
                    this.add(totalTax);
                    var messageList = Sol.List.from(model.PurchasingIncidence.LegalMessages);
                    messageList.addMany(Sol.List.from(model.SaleIncidence.LegalMessages));
                    this.controls.addMany(messageList.select(message => {
                        var messageParagraph = new Sol.Control("p");
                        messageParagraph.text = message;
                        return messageParagraph;
                    }));
                }
            }
            Taxes.TaxSummaryControl = TaxSummaryControl;
        })(Taxes = Web.Taxes || (Web.Taxes = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Taxes;
        (function (Taxes) {
            class TaxSummaryDialog extends Sol.DialogBox {
                constructor(model) {
                    super();
                    this.css.add("sol_tax_summary_dialog");
                    this.title = Sol.Environment.resources.taxDescription;
                    this.contentArea.controls.addMany(Sol.List.from(model.Taxes).select(tx => new Taxes.TaxSummaryControl(tx)));
                    var taxTotal = new Sol.Control();
                    taxTotal.css.add("sol_tax_summary_dialog_total");
                    taxTotal.text = Sol.Environment.resources.total + ": " + model.OverallTotalText;
                    this.contentArea.add(taxTotal);
                }
            }
            Taxes.TaxSummaryDialog = TaxSummaryDialog;
        })(Taxes = Web.Taxes || (Web.Taxes = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Taxes;
        (function (Taxes) {
            class TaxesField extends Web.Components.CalculableField {
                constructor() {
                    super();
                    this.mainField.readonly = false;
                    this.mainField.onChange = () => {
                        if (this.onModified)
                            this.onModified(this);
                    };
                    this.calcButton.onClick = () => this.showDialog();
                }
                calculate(product, cost, price, company, client, callback) {
                    const data = {
                        product: product,
                        cost: cost,
                        price: price,
                        companyID: company,
                        customerID: client
                    };
                    Web.System.exec("ns41o12", "CalculateTaxes", data, model => {
                        this.lastCalculation = model;
                        this.mainField.numericValue = model.OverallTotal;
                        if (this.onModified)
                            this.onModified(this);
                        if (callback)
                            callback();
                    });
                }
                showDialog() {
                    if (!this.lastCalculation) {
                        if (this.onRequestCalculation)
                            this.onRequestCalculation();
                        return;
                    }
                    var dialog = new Taxes.TaxSummaryDialog(this.lastCalculation);
                    dialog.onClose = () => this.controls.remove(dialog);
                    this.add(dialog);
                }
            }
            Taxes.TaxesField = TaxesField;
        })(Taxes = Web.Taxes || (Web.Taxes = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("Taxes", () => new Sol.Web.Taxes.TaxesField());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class CustomerScreen extends Screens.OptionalFile {
                get myModel() { return this.model; }
                instantiateDetailsScreen() {
                    const details = super.instantiateDetailsScreen();
                    details.onSaved.subscribe((e, result) => this.screenSaved(e, result));
                    return details;
                }
                screenSaved(sender, model) {
                    if (!this.myModel.EnableFollowupAfterNewClient)
                        return;
                    const dialog = new Web.Components.ScheduleEventDialog();
                    dialog.loadEntity(model.ID);
                    dialog.onClose = () => this.controls.remove(dialog);
                    this.add(dialog);
                }
            }
            Screens.CustomerScreen = CustomerScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Customers;
            (function (Customers) {
                class EditCustomerLoup extends Sol.Button {
                    constructor() {
                        super();
                        this.type = Sol.ButtonType.Custom;
                        this.imageCode = "&#xf002;";
                        this.onClick = () => this.open();
                    }
                    open() {
                        const row = this.parent.parent;
                        const screen = Web.System.screens.screens.that(sc => sc instanceof Web.Screens.Registro && sc.classType.indexOf("Cliente") > -1);
                        screen.editItem(row.code, null);
                    }
                    clear() { }
                    foco() { }
                    isEmpty() { return false; }
                    toControl() { return this; }
                    validate() { return null; }
                }
                Customers.EditCustomerLoup = EditCustomerLoup;
            })(Customers = Commercial.Customers || (Commercial.Customers = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("EditCustomerLoup", () => new Sol.Web.Commercial.Customers.EditCustomerLoup());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class ProductRegistrationSelector extends Products.ProductSelector {
                    get currentName() { return this.container.getEditor("CurrentName"); }
                    get currentDescription() { return this.container.getEditor("CurrentDescription"); }
                    get category() { return this.container.getEditor("Category"); }
                    build() {
                        super.build();
                        this.currentName.parent.visible = false;
                        this.currentName.readonly = true;
                        this.currentDescription.visible = false;
                        this.currentDescription.readonly = true;
                        this.propertyList.add("Description");
                    }
                    itemSelected(data, code, closeScreen) {
                        super.itemSelected(data, code, closeScreen);
                        var dataCollection = Sol.List.from(data);
                        this.currentName.value = this.selectedName;
                        this.currentName.parent.visible = true;
                        this.currentDescription.value = dataCollection.that(d => d.Campo == "Description").Valor;
                        this.currentDescription.visible = true;
                        Web.System.screens.currentScreen.getLabel("CurrentDescription").expanded = true;
                        this.category.value = dataCollection.that(d => d.Campo == "Category").Valor;
                    }
                }
                Products.ProductRegistrationSelector = ProductRegistrationSelector;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ProductRegistrationSelector", () => new Sol.Web.Commercial.Products.ProductRegistrationSelector());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class CategoryCombo extends Web.Components.DataCombo {
                    get departament() { return this.container.getEditor("Department"); }
                    build() {
                        super.build();
                        this.departament.onChange = () => this.refresh();
                    }
                    constructor() {
                        super();
                        this.onBeforeRefresh = () => this.categoryRefresh();
                    }
                    categoryRefresh() {
                        this.controls.empty();
                        this.filters.empty();
                        const selector = this.container.getEditor("Department");
                        this.filters.add({
                            FilterType: "SBoolean",
                            PropertyName: "Discontinued",
                            FilterValue: 0
                        });
                        if (!(selector === null || selector === void 0 ? void 0 : selector.selectedCode))
                            this.filters.add({
                                FilterType: null,
                                PropertyName: "NoResultFilter",
                                FilterValue: true
                            });
                        else
                            this.filters.add({
                                FilterType: "SInteger",
                                PropertyName: "Department",
                                FilterValue: selector.selectedCode
                            });
                    }
                }
                Products.CategoryCombo = CategoryCombo;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("CategoryCombo", model => {
    const selector = new Sol.Web.Commercial.Products.CategoryCombo();
    selector.className = model.DataTypeFullName;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CategoryDualCombo extends Components.DualCombo {
                constructor() {
                    super();
                    this.mainCombo.preFilters = [{ FilterType: "SBoolean", PropertyName: "Discontinued", FilterValue: 0 }];
                    this.subCombo.preFilters = [{ FilterType: "SBoolean", PropertyName: "Discontinued", FilterValue: 0 }];
                }
            }
            Components.CategoryDualCombo = CategoryDualCombo;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class PartnumberGridField extends Sol.Field {
                    constructor() {
                        super();
                        this.onKeyDown = e => this.keyDown(e);
                    }
                    keyDown(e) {
                        if (e.key != "Enter")
                            return;
                        const cell = this.parent;
                        const newRow = cell.grid.addRow();
                        newRow.editors.first().foco();
                    }
                }
                Products.PartnumberGridField = PartnumberGridField;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PartnumberGridField", model => {
    const pnField = new Sol.Web.Commercial.Products.PartnumberGridField();
    pnField.maxLength = model.MaxLength;
    return pnField;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Products;
            (function (Products) {
                class PartnumberField extends Sol.Field {
                    constructor() {
                        super();
                        this.disableEnter = true;
                    }
                }
                Products.PartnumberField = PartnumberField;
            })(Products = Commercial.Products || (Commercial.Products = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PartnumberField", model => {
    const partNumberFieldEditor = new Sol.Web.Commercial.Products.PartnumberField();
    partNumberFieldEditor.maxLength = model.MaxLength;
    return partNumberFieldEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Production;
            (function (Production) {
                class ProductionTableRow extends Sol.Control {
                    constructor(model) {
                        super("tr");
                        this.quantityField = new Sol.IntegerField();
                        this.itemModel = model;
                        const quantityCell = new Sol.Control("td");
                        const totalCell = new Sol.Control("td");
                        this.quantityField.numericValue = model.SuggestedProduction;
                        this.quantityField.onChange = () => {
                            totalCell.text = ((model.CurrentStock + this.quantityField.numericValue).toString());
                            this.onChange();
                        };
                        quantityCell.add(this.quantityField);
                        this.add(quantityCell);
                        this.add(this.createCell(model.PartNumber));
                        this.add(this.createCell(model.ProductName));
                        this.add(this.createCell(model.MinimunStock.toString()));
                        this.add(this.createCell(model.CurrentStock.toString()));
                        totalCell.text = ((model.CurrentStock + model.SuggestedProduction).toString());
                        this.add(totalCell);
                    }
                    get quantity() { return this.quantityField.numericValue; }
                    calculate() {
                        return Sol.List.from(this.itemModel.Ingredients)
                            .select(i => ({
                            code: i.Code,
                            name: i.Name,
                            quantity: this.quantity * i.Weight * (1 + (i.Loss / 100)),
                            stock: i.Stock,
                            typeName: i.TypeName,
                            typeColor: i.TypeColor
                        }));
                    }
                    createCell(text) {
                        const cell = new Sol.Control("td");
                        cell.text = text;
                        return cell;
                    }
                }
                Production.ProductionTableRow = ProductionTableRow;
            })(Production = Commercial.Production || (Commercial.Production = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Production;
            (function (Production) {
                class ProductionScreen extends Web.Screens.BaseScreen {
                    constructor(model) {
                        super();
                        this.ingredientsArea = new Sol.Control();
                        this.productRows = new Sol.List();
                        this.screenCaption = "Produção";
                        const title = new Web.Screens.ScreenTitle();
                        title.text = this.screenCaption;
                        this.add(title);
                        const content = new Sol.Control();
                        content.css.add("sol_production_screen");
                        const productsLabel = new Sol.Control("h4");
                        productsLabel.text = "Produtos selecionados:";
                        content.add(productsLabel);
                        const productsTable = new Sol.Control("table");
                        productsTable.css.add("sol_production_screen_products");
                        const productsTableHead = new Sol.Control("thead");
                        const productsTableHeadRow = new Sol.Control("tr");
                        productsTableHeadRow.add(this.createHeader("Quantidade"));
                        productsTableHeadRow.add(this.createHeader("Código"));
                        productsTableHeadRow.add(this.createHeader("Produto"));
                        productsTableHeadRow.add(this.createHeader("Ponto Mínimo"));
                        productsTableHeadRow.add(this.createHeader("Estoque Atual"));
                        productsTableHeadRow.add(this.createHeader("Estoque Futuro"));
                        productsTableHead.add(productsTableHeadRow);
                        const productsTableBody = new Sol.Control("tbody");
                        productsTableBody.controls.addMany(Sol.List.from(model.Items).select(i => {
                            const tableRow = new Production.ProductionTableRow(i);
                            tableRow.onChange = () => this.calculateIngredients();
                            this.productRows.add(tableRow);
                            return tableRow;
                        }));
                        productsTable.add(productsTableHead);
                        productsTable.add(productsTableBody);
                        content.add(productsTable);
                        content.add(this.ingredientsArea);
                        this.calculateIngredients();
                        this.add(content);
                    }
                    createHeader(text) {
                        const cell = new Sol.Control("th");
                        cell.text = text;
                        return cell;
                    }
                    createCell(text) {
                        const cell = new Sol.Control("td");
                        cell.text = text;
                        return cell;
                    }
                    calculateIngredients() {
                        this.ingredientsArea.controls.empty();
                        if (this.productRows.sum(row => row.quantity) <= 0)
                            return;
                        const calcs = Sol.List.concatLists(this.productRows.select(row => row.calculate())).orderBy(row => row.typeName);
                        const ingredients = calcs.select(c => c.code).distinct();
                        const ingredientsLabel = new Sol.Control("h4");
                        ingredientsLabel.text = "Ingredientes:";
                        this.ingredientsArea.add(ingredientsLabel);
                        const ingredientsTable = new Sol.Control("table");
                        ingredientsTable.css.add("sol_production_screen_ingredients");
                        var firstCalc;
                        var totalWeight;
                        var totalPreparation;
                        var currentType;
                        this.addIngredientsHeaders(ingredientsTable);
                        ingredients.forEach(code => {
                            firstCalc = calcs.that(clc => clc.code == code);
                            totalWeight = calcs.where(clc => clc.code == code).sum(clc => clc.quantity);
                            totalPreparation = Math.max(totalWeight - firstCalc.stock, 0);
                            if (currentType != firstCalc.typeName) {
                                const typeRow = new Sol.Control("tr");
                                const typeCell = new Sol.Control("td");
                                typeCell.text = firstCalc.typeName;
                                typeCell.css.add("sol_production_screen_ingredients_title");
                                typeCell.atributos.agregar("colspan", "4");
                                typeCell.estilos.agregar("background-color", firstCalc.typeColor);
                                typeRow.add(typeCell);
                                ingredientsTable.add(typeRow);
                                currentType = firstCalc.typeName;
                            }
                            const ingredientRow = new Sol.Control("tr");
                            ingredientRow.add(this.createCell(firstCalc.name));
                            ingredientRow.add(this.createCell(totalWeight.toString()));
                            ingredientRow.add(this.createCell(firstCalc.stock.toString()));
                            ingredientRow.add(this.createCell(totalPreparation.toString()));
                            ingredientsTable.add(ingredientRow);
                        });
                        this.ingredientsArea.add(ingredientsTable);
                    }
                    addIngredientsHeaders(table) {
                        const ingredientsHeader = new Sol.Control("tr");
                        ingredientsHeader.add(this.createHeader("Ingrediente"));
                        ingredientsHeader.add(this.createHeader("Total a Cozinhar"));
                        ingredientsHeader.add(this.createHeader("Total Pronto"));
                        ingredientsHeader.add(this.createHeader("COZINHAR"));
                        table.add(ingredientsHeader);
                    }
                }
                Production.ProductionScreen = ProductionScreen;
            })(Production = Commercial.Production || (Commercial.Production = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Production;
            (function (Production) {
                class ProductionAction {
                    constructor(model) {
                        const productionScreen = new Production.ProductionScreen(model);
                        Web.System.screens.addScreen(productionScreen);
                        Web.System.screens.showScreen(productionScreen);
                    }
                }
                Production.ProductionAction = ProductionAction;
            })(Production = Commercial.Production || (Commercial.Production = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Services;
            (function (Services) {
                class ServiceCategorySelector extends Sol.Web.Components.DataCombo {
                    constructor() {
                        super();
                        this.disableChangeEventOnSetValue = true;
                        this.onChange = () => this.categoryChanged();
                        this.onSet.subscribe(() => this.categoryChanged());
                    }
                    categoryChanged() {
                        if (!this.selectedCode || this.selectedCode == this.curCode)
                            return;
                        this.curCode = this.selectedCode;
                        Web.System.exec("79k8jhkh", "GetServiceCategorySpecifications", {
                            categoryID: this.selectedCode
                        }, (response) => {
                            if (!response.Fail) {
                                let editorResponse = this.container.getEditor("Specifications");
                                editorResponse.setFields(Sol.List.from(response.Specifications));
                            }
                            else
                                alert(response.ErrorMessage);
                        });
                    }
                    ;
                }
                Services.ServiceCategorySelector = ServiceCategorySelector;
            })(Services = Commercial.Services || (Commercial.Services = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ServiceCategorySelector", model => {
    let selector = new Sol.Web.Commercial.Services.ServiceCategorySelector();
    selector.className = model.DataTypeFullName;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Sales;
            (function (Sales) {
                class RecipientEmail extends Sol.EmailField {
                    constructor() {
                        super(...arguments);
                        this.recipientProperty = "Destinatario";
                    }
                    build() {
                        super.build();
                        const detailsScreen = Web.System.screens.getPreviousScreen();
                        const recipient = detailsScreen.getEditor(this.recipientProperty);
                        if (!recipient.selectedCode)
                            return;
                        Web.System.exec("nlskdjor", "GetEmail", { id: recipient.selectedCode }, e => this.value = e);
                    }
                }
                Sales.RecipientEmail = RecipientEmail;
            })(Sales = Commercial.Sales || (Commercial.Sales = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("RecipientEmail", () => new Sol.Web.Commercial.Sales.RecipientEmail());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class QuickSaleScreen extends Screens.Registro {
            }
            Screens.QuickSaleScreen = QuickSaleScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            var Leads;
            (function (Leads) {
                class LeadProfileSelector extends Sol.Combo {
                    constructor() {
                        super();
                        this.onChange = () => this.suggestConsultant();
                    }
                    build() {
                        setTimeout(() => this.suggestConsultant(), 300);
                    }
                    suggestConsultant() {
                        const loginSelector = this.container.getEditor("TargetLogin");
                        Web.System.exec("dam,43j43", "SuggestConsultant", { profileID: this.selectedCode }, result => loginSelector.value = result);
                    }
                }
                Leads.LeadProfileSelector = LeadProfileSelector;
            })(Leads = Commercial.Leads || (Commercial.Leads = {}));
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("LeadProfileSelector", model => {
    const selector = new Sol.Web.Commercial.Leads.LeadProfileSelector();
    selector.loadOptions(model.Options);
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            class PresaleEditor extends Sol.ObjectDisplay {
                constructor() {
                    super();
                    this.CLASS_HASH = "1295139957";
                    this.customClass = "sol_presale_editor";
                    this.defaultValue = {
                        Campo: "Sem pré-vendas",
                        Valor: 0,
                        Color: "#bdbdbd"
                    };
                    this.onClick = () => this.editorClick();
                }
                setValue(v) {
                    if (Number.isInteger(v) && v > 0) {
                        this.code = v;
                        this.updateInfo();
                        return;
                    }
                    super.setValue(v);
                }
                editorClick() {
                    var _a;
                    Web.System.screens.currentDetails.hideMessages();
                    if (!this.code) {
                        let saleDescription = (_a = Web.System.screens.currentDetails.getEditor("Identifier")) === null || _a === void 0 ? void 0 : _a.value;
                        let customer = Web.System.screens.currentDetails.getEditor("Destinatario").value;
                        let id = Web.System.screens.currentDetails.getEditor("ID").value;
                        Web.System.create(this.CLASS_HASH, screen => {
                            if (saleDescription)
                                screen.setEditorValue("Nombre", saleDescription);
                            screen.setEditorValue("SaleID", id);
                            screen.setEditorValue("Customer", customer);
                            screen.onSaved.subscribe(() => this.saveNewPresale(screen));
                        });
                    }
                    else
                        Web.System.edit(this.CLASS_HASH, this.code, screen => {
                            screen.closingAlertEnabled = false;
                            screen.onSaved.subscribe(() => this.updateInfo());
                        });
                }
                saveNewPresale(screen) {
                    Web.System.screens.currentDetails.showSucessMessage("Pré-vendas solicitado com sucesso");
                    this.code = screen.code;
                    this.updateInfo();
                    let saveData = {
                        className: this.className,
                        id: this.saleID,
                        data: [{ Campo: "PresaleID", Valor: this.code }],
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", saveData, e => Web.System.screens.currentDetails.lastUpdate = e.SavingTime);
                }
                updateInfo() {
                    Web.System.screens.currentDetails.reloadFields();
                    let request = {
                        className: this.CLASS_HASH,
                        code: this.code,
                        subtype: false,
                        propertyList: ["Status", "Status$Nombre", "Status$Color"]
                    };
                    Web.System.exec("sn9d23vs7d", "Load", request, model => {
                        let data = Sol.List.from(model.Data);
                        let statusInfo = data.that(d => d.Campo == "Status").Valor;
                        statusInfo.Valor = this.code;
                        this.value = statusInfo;
                    });
                }
            }
            Commercial.PresaleEditor = PresaleEditor;
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PresaleEditor", (model, className, code) => {
    let editor = new Sol.Web.Commercial.PresaleEditor();
    editor.saleID = code;
    editor.className = className;
    return editor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Commercial;
        (function (Commercial) {
            class OpenDealsButtonEditor extends Sol.Button {
                constructor() {
                    super();
                    this.showCounter = true;
                    this.imageCode = "&#xf115;";
                    this.onClick = () => Web.System.screens.openScreen("Registro", "Solarium.Commercial.Venta, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null, null, null, screen => {
                        const dealsScreen = screen;
                        dealsScreen.anchorage = {
                            FilterType: "SInteger",
                            PropertyName: "Destinatario",
                            FilterValue: Web.System.screens.currentDetails.code
                        };
                    });
                }
                get value() { return this._value; }
                set value(v) { this._value = v; this.setCounterValue(v); }
                clear() { }
                foco() { }
                isEmpty() { return null; }
                toControl() { return this; }
                validate() { return null; }
            }
            Commercial.OpenDealsButtonEditor = OpenDealsButtonEditor;
        })(Commercial = Web.Commercial || (Web.Commercial = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("OpenDealsCountEditor", () => new Sol.Web.Commercial.OpenDealsButtonEditor());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Quality;
        (function (Quality) {
            class QuestionsEditor extends Web.Components.DataView {
                constructor() {
                    super();
                    this.showSearchBox = false;
                    this.fixedRows = false;
                    this.showChecks = false;
                    this.allowNew = false;
                    this.allowDelete = false;
                }
            }
            Quality.QuestionsEditor = QuestionsEditor;
        })(Quality = Web.Quality || (Web.Quality = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("QuestionsEditor", model => {
    var questionsEditor = new Sol.Web.Quality.QuestionsEditor();
    questionsEditor.readonly = model.ReadOnly;
    model.Structure[0].ReadOnly = true;
    Sol.Web.Editors.fillDataViewStructure(questionsEditor, model.Structure);
    return questionsEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Construction;
        (function (Construction) {
            class InspectionReportEditor extends Web.Components.HtmlEditor {
                build() {
                    super.build();
                    const request = { code: Web.System.screens.currentID };
                    Web.System.exec("pm9iskws", "GetReport", request, e => this.value = e.HtmlContent);
                }
            }
            Construction.InspectionReportEditor = InspectionReportEditor;
        })(Construction = Web.Construction || (Web.Construction = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("InspectionReportEditor", () => new Sol.Web.Construction.InspectionReportEditor());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Translations;
        (function (Translations) {
            class SignatureValidation {
                constructor() {
                    var verificationForm = document.getElementById("verificationForm");
                    verificationForm.onsubmit = e => this.send();
                }
                send() {
                    const SENDING = "Pesquisando...";
                    const VERIFY = "Validar";
                    const SENDING_ERROR = "Desculpe. Houve um erro ao enviar.";
                    if (this.isSending)
                        return false;
                    this.isSending = true;
                    const code = document.getElementById("code");
                    const sendButton = document.getElementById("verificationButton");
                    const errorMessage = document.getElementById("errorMessage");
                    const successMessage = document.getElementById("verificationInfo");
                    errorMessage.style.display = 'none';
                    successMessage.style.display = 'none';
                    sendButton.textContent = SENDING;
                    sendButton.classList.add("enviando");
                    var request = {
                        credential: null,
                        manager: "98dpfc4m",
                        method: "CheckValidationCode",
                        data: JSON.stringify({ code: code.value })
                    };
                    Sol.Http.AjaxLight.post("https://solarium.letrearte.com/exec", request, e => {
                        var model = e;
                        if (!model || model.Fail)
                            errorMessage.style.display = 'block';
                        else {
                            const signerName = document.getElementById("signerName");
                            const signDate = document.getElementById("signDate");
                            const documentDescription = document.getElementById("documentDescription");
                            const fileLink = document.getElementById("fileLink");
                            signerName.innerText = model.SignerName;
                            signDate.innerText = model.SignDate;
                            documentDescription.innerText = model.DocumentDescription;
                            fileLink.href = model.FileLink;
                            successMessage.style.display = 'block';
                        }
                        sendButton.textContent = VERIFY;
                        this.isSending = false;
                    }, () => {
                        errorMessage.style.display = 'block';
                        sendButton.textContent = VERIFY;
                        this.isSending = false;
                    });
                    return false;
                }
            }
            Translations.SignatureValidation = SignatureValidation;
        })(Translations = Web.Translations || (Web.Translations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TreeViewItem extends Sol.Control {
                constructor(readonly) {
                    super("li");
                    this.check = new Sol.Control("input");
                    this.expandoButton = new Sol.Control("span");
                    this.input = new Sol.Field();
                    this.captionControl = new Sol.Control("span");
                    this.selectableArea = new Sol.Control("span");
                    this.saveButton = new Sol.Button();
                    this.cancelButton = new Sol.Button();
                    this.code = 0;
                    this.check.atributos.agregar("type", "checkbox");
                    this.createAccessLine();
                    this.add(this.check);
                    this.expandoButton.css.add("sol_tree_view_expando_button");
                    this.add(this.expandoButton);
                    if (readonly)
                        this.selectableArea.add(this.captionControl);
                    else {
                        this.input.onKeyDown = e => this.editNode(e);
                        this.input.autoResize = true;
                        this.selectableArea.add(this.input);
                    }
                    this.selectableArea.onClick = () => this.select();
                    this.createButtons();
                    this.selectableArea.css.add("sol_tree_view_selectable_area");
                    this.add(this.selectableArea);
                    this.readonly = true;
                    this._selected = false;
                }
                get caption() { return this.input.value; }
                set caption(value) {
                    this.input.value = value;
                    this.captionControl.text = value;
                }
                get expanded() { return this._expanded; }
                set expanded(value) {
                    this._expanded = value;
                    if (this.check.html)
                        this.check.html.checked = value;
                }
                get readonly() { return this.input.readonly; }
                set readonly(value) {
                    this.saveButton.visible = !value;
                    this.cancelButton.visible = !value;
                    this.input.readonly = value;
                    if (!value)
                        this.previousValue = this.caption;
                }
                get selected() { return this._selected; }
                set selected(value) {
                    this._selected = value;
                    if (value) {
                        this.selectableArea.css.add("sol_tree_view_selected_item");
                        this.focus();
                    }
                    else
                        this.selectableArea.css.remove("sol_tree_view_selected_item");
                }
                get group() { return this.controls.that(ctr => ctr instanceof Components.TreeNodeGroup); }
                build() {
                    if (this.expanded)
                        this.check.atributos.agregar("checked", "checked");
                    this.expandoButton.visible = !!this.group;
                    super.build();
                    if (!this.onDoubleClick) {
                        this.draggable = !!this.code;
                        this.onDragStart = (ctr, e) => this.dragStart(ctr, e);
                        this.onDragOver = (ctr, e) => e.preventDefault();
                        this.onDrop = (ctr, e) => this.drop(ctr, e);
                    }
                }
                createAccessLine() {
                    const span = new Sol.Control("span");
                    span.css.add("sol_tree_view_item_line");
                    this.add(span);
                }
                ;
                createButtons() {
                    this.saveButton.imageCode = "&#xf00c;";
                    this.saveButton.type = Sol.ButtonType.Custom;
                    this.saveButton.onClick = () => this.saveEdition();
                    this.cancelButton.imageCode = "&#xf00d;";
                    this.cancelButton.type = Sol.ButtonType.Custom;
                    this.cancelButton.onClick = () => this.cancelEdition();
                    this.saveButton.visible = false;
                    this.cancelButton.visible = false;
                    this.selectableArea.controls.addMany([this.saveButton, this.cancelButton]);
                }
                dragStart(item, e) {
                    e.dataTransfer.setData("treeview_item", this.code.toString());
                    e.stopPropagation();
                }
                drop(item, e) {
                    e.preventDefault();
                    e.cancelBubble = true;
                    e.stopPropagation();
                    if (!this.readonly)
                        return;
                    var propertyDrop = e.dataTransfer.getData("treeview_item");
                    if (!propertyDrop || item.code == parseInt(propertyDrop))
                        return;
                    if (this.onItemDrop)
                        this.onItemDrop(item, parseInt(propertyDrop));
                }
                addChild() {
                    const newChild = new TreeViewItem(false);
                    if (!this.group)
                        this.add(new Components.TreeNodeGroup());
                    this.expandoButton.visible = true;
                    this.expanded = true;
                    newChild.parentID = this.code;
                    newChild.readonly = false;
                    newChild.focus();
                    newChild.onCancel = () => this.removeChild(newChild);
                    newChild.parentNode = this;
                    newChild.tree = this.tree;
                    this.group.add(newChild);
                    this.tree.registerNode(newChild);
                }
                insertChild(newChild) {
                    if (!this.group)
                        this.add(new Components.TreeNodeGroup());
                    this.expandoButton.visible = true;
                    this.expanded = true;
                    newChild.parentID = this.code;
                    newChild.focus();
                    newChild.onCancel = () => this.removeChild(newChild);
                    newChild.parentNode = this;
                    newChild.tree = this.tree;
                    this.group.controls.insert(0, newChild);
                    this.tree.registerNode(newChild);
                }
                removeChild(child) {
                    if (!this.group)
                        return;
                    this.group.controls.remove(child);
                    if (!this.group.controls.hasItems()) {
                        this.controls.remove(this.group);
                        this.expandoButton.visible = false;
                    }
                }
                cancelEdition() {
                    if (this.readonly)
                        return;
                    if (this.code > 0) {
                        this.caption = this.previousValue;
                        this.readonly = true;
                        return;
                    }
                    this.focus();
                    if (this.onCancel)
                        this.onCancel();
                }
                rename() {
                    if (this.parentID == null)
                        return;
                    this.readonly = false;
                    this.focus();
                }
                saveEdition() {
                    if (!this.caption) {
                        this.cancelEdition();
                        return;
                    }
                    if (this.caption == this.previousValue) {
                        this.readonly = true;
                        return;
                    }
                    this.focus();
                    if (this.onSave)
                        this.onSave(this);
                }
                focus() {
                    setTimeout(() => this.input.foco(), 300);
                }
                selectWithNoFocus() {
                    this._selected = true;
                    this.selectableArea.css.add("sol_tree_view_selected_item");
                }
                select() {
                    if (this.onSelect)
                        this.onSelect(this);
                }
                editNode(e) {
                    switch (e.which) {
                        case 113:
                            if (!this.readonly)
                                this.rename();
                            break;
                        case 27:
                            this.cancelEdition();
                            break;
                        case 13:
                            this.saveEdition();
                            break;
                        case 107:
                        case 187:
                            this.expanded = true;
                            break;
                        case 109:
                        case 189:
                            this.expanded = false;
                            break;
                    }
                }
            }
            Components.TreeViewItem = TreeViewItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TreeNodeGroup extends Sol.Control {
                constructor() {
                    super("ul");
                }
            }
            Components.TreeNodeGroup = TreeNodeGroup;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class TreeView extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.main = new Sol.Control();
                    this.toolbox = new Sol.Control();
                    this.searchFilter = new Sol.Button();
                    this.searchBox = new Components.SearchBox();
                    this.items = new Sol.List();
                }
                get selectedNode() { return this.items.that(i => i.selected); }
                clear() {
                    this.main.controls.empty();
                    this.items.empty();
                }
                getItemByCode(code) { return this.items.that(i => i.code == code); }
                loadData(nodes) {
                    this.myNodes = Sol.List.from(nodes);
                    if (!this.myNodes.any(n => n.ID == 0))
                        this.myNodes.add({
                            ID: 0,
                            ParentID: null,
                            Nombre: this.rootLabel,
                            Level: 0,
                            Position: 0
                        });
                    this.createTree();
                }
                registerNode(node) {
                    node.onSelect = e => this.selectNode(e, true);
                    node.onSave = e => this.saveNode(e);
                    if (this.onNodeClick)
                        node.onMouseDown = () => this.onNodeClick(node);
                    else
                        node.onItemDrop = (parent, itemID) => this.itemDrop(parent, itemID);
                    this.items.add(node);
                }
                build() {
                    super.build();
                    const titleControl = new Sol.Control("h4");
                    titleControl.text = this.rootLabel;
                    this.add(titleControl);
                    this.searchFilter.imageCode = '&#xf002;';
                    this.searchFilter.type = Sol.ButtonType.Custom;
                    this.searchFilter.tip = Sol.Environment.resources.buscar;
                    this.searchFilter.css.add("sol_tree_view_search_filter");
                    titleControl.add(this.searchFilter);
                    this.searchBox.visible = false;
                    this.searchBox.onSearch = t => this.items.where(i => i.caption && i.caption.toLowerCase().indexOf(t.toLowerCase()) > -1);
                    this.searchBox.onSelect = t => this.selectNode(t, false);
                    this.add(this.searchBox);
                    this.searchFilter.onClick = () => this.searchBox.toggleVisibility();
                    this.add(this.main);
                    this.main.css.add("sol_tree_view_main");
                    if (!this.flatStyle)
                        this.main.css.add("sol_campo");
                    this.createToolbox();
                    this.css.add("sol_tree_view");
                }
                addNode() {
                    this.items.forEach(i => i.cancelEdition());
                    this.selectedNode.addChild();
                }
                createTree() {
                    this.main.controls.empty();
                    this.main.add(this.createNodes(0, null));
                    this.items.last().selected = true;
                }
                createNodes(level, parentID) {
                    const ulTag = new Components.TreeNodeGroup();
                    ulTag.controls.addMany(this.myNodes.where(node => node.Level == level && node.ParentID == parentID).select(node => {
                        const item = new Components.TreeViewItem(this.readonly);
                        item.caption = node.Nombre;
                        item.parentID = node.ParentID;
                        item.code = node.ID;
                        item.tree = this;
                        item.expanded = !node.Level;
                        item.data = node;
                        item.level = node.Level;
                        const children = this.createNodes(level + 1, node.ID);
                        if (children.controls.hasItems())
                            item.add(children);
                        children.controls.cast().forEach(c => c.parentNode = item);
                        this.registerNode(item);
                        return item;
                    }));
                    return ulTag;
                }
                createToolbox() {
                    if (this.readonly)
                        return;
                    const addButton = new Sol.Button();
                    addButton.text = Sol.Environment.resources.anadir_item;
                    addButton.onClick = () => this.addNode();
                    addButton.atributos.agregar("accesskey", "a");
                    this.toolbox.add(addButton);
                    const renameButton = new Sol.Button();
                    renameButton.text = Sol.Environment.resources.rename;
                    renameButton.onClick = () => this.selectedNode.rename();
                    this.toolbox.add(renameButton);
                    const removeButton = new Sol.Button();
                    removeButton.text = Sol.Environment.resources.eliminar;
                    removeButton.onClick = () => this.removeNode();
                    this.toolbox.add(removeButton);
                    this.toolbox.css.add("sol_tree_view_toolbox");
                    this.add(this.toolbox);
                }
                itemDrop(parentItem, itemID) {
                    const data = {
                        className: this.className,
                        itemID: itemID,
                        parentID: parentItem.code
                    };
                    Web.System.exec("p3kewj34", "Move", data, e => {
                        if (e.Fail)
                            return;
                        const item = this.items.that(i => i.code == itemID);
                        item.parentNode.removeChild(item);
                        parentItem.insertChild(item);
                    });
                }
                saveNode(node) {
                    const data = Sol.List.from([{ Campo: "Nombre", Valor: node.caption },
                        { Campo: this.parentPropertyName, Valor: node.parentID }]);
                    if (this.anchorage)
                        data.add({ Campo: this.anchorage.PropertyName, Valor: this.anchorage.FilterValue });
                    var modelData = {
                        className: this.className,
                        id: node.code,
                        data: data.toArray(),
                        lastUpdate: null
                    };
                    Web.System.exec("3b5v9v45", "Save", modelData, model => {
                        var response = model;
                        if (model.Fail) {
                            alert("Erro ao salvar");
                            return;
                        }
                        node.code = response.ID;
                        node.readonly = true;
                    }, () => alert("Erro ao salvar"));
                }
                selectNode(e, setFocus) {
                    this.items.forEach(i => i.selected = false);
                    if (setFocus) {
                        e.selected = true;
                        if (this.onNodeSelected)
                            this.onNodeSelected(e);
                    }
                    else
                        e.selectWithNoFocus();
                }
                removeNode() {
                    if (this.selectedNode.parentID == null)
                        return;
                    if (!confirm(Sol.Environment.resources.confirm_delete))
                        return;
                    var deleteNode = {
                        className: this.className,
                        decisionID: null,
                        methodName: "DeleteMany",
                        selectionMode: Web.ActionSelectionMode.None,
                        filters: null,
                        ids: [this.selectedNode.code],
                        inputs: null
                    };
                    Web.System.exec("79k8j542h", "DoMultiple", deleteNode, () => {
                        const parent = this.items.that(i => i.code == this.selectedNode.parentID);
                        parent.removeChild(this.selectedNode);
                        parent.selected = true;
                    }, () => alert("erro ao excluir"));
                }
            }
            Components.TreeView = TreeView;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class TemplateEditor extends Sol.Control {
                constructor(model) {
                    super();
                    this.htmlEditor = new Web.Components.HtmlEditor();
                    this.fieldTree = new Web.Components.TreeView();
                    this.tipMessage = new Sol.Control();
                    this.minLevel = 2;
                    let config = model.Configuration;
                    this.css.add("sol_contract_editor");
                    this.add(this.htmlEditor);
                    this.fieldTree.rootLabel = Sol.Environment.resources.campos_disponibles;
                    this.fieldTree.readonly = true;
                    this.fieldTree.flatStyle = true;
                    this.fieldTree.onNodeClick = node => this.insertField(node);
                    this.fieldTree.loadData(config.FieldTree);
                    this.add(this.fieldTree);
                    this.tipMessage.css.add("sol_contract_editor_tip");
                    this.tipMessage.text = model.Tip;
                    this.fieldTree.add(this.tipMessage);
                    this.minLevel = config.MinLevel || this.minLevel;
                }
                get value() { return this.htmlEditor.value; }
                set value(v) { this.htmlEditor.value = v; }
                clear() { this.htmlEditor.clear(); }
                foco() { this.htmlEditor.foco(); }
                isEmpty() { return this.htmlEditor.isEmpty(); }
                toControl() { return this; }
                validate() { return null; }
                insertField(item) {
                    if (this.insertBlocked || item.level < this.minLevel)
                        return;
                    const itemData = item.data;
                    var caption = itemData.Nombre;
                    if (itemData.ParentID > 0)
                        caption += " (" + item.parentNode.caption + ")";
                    const fieldElement = document.createElement("solplaceholder");
                    fieldElement.innerText = caption;
                    fieldElement.setAttribute("property", itemData.PropertyName);
                    fieldElement.classList.add("sol_contract_editor_place_holder");
                    if (itemData.IsSection)
                        fieldElement.classList.add("sol_contract_editor_section");
                    if (!this.isEditableArea(window.getSelection().focusNode))
                        return true;
                    const blankElement = document.createElement("span");
                    blankElement.innerHTML = "&nbsp;";
                    window.getSelection().getRangeAt(0).insertNode(blankElement);
                    window.getSelection().getRangeAt(0).insertNode(fieldElement);
                    const range = window.getSelection().getRangeAt(0);
                    range.selectNodeContents(blankElement);
                    range.collapse();
                    this.insertBlocked = true;
                    setTimeout(() => this.insertBlocked = false, 300);
                    if (this.isEditableArea(window.getSelection().focusNode))
                        return false;
                }
                fieldDrop(e) {
                    const itemCode = e.dataTransfer.getData("treeview_item");
                    if (!itemCode)
                        return;
                    const item = this.fieldTree.getItemByCode(parseInt(itemCode));
                    const itemData = item.data;
                    const fieldElement = document.createElement("solplaceholder");
                    var caption = itemData.Nombre;
                    if (itemData.ParentID > 0)
                        caption += " (" + item.parentNode.caption + ")";
                    fieldElement.innerText = caption;
                    fieldElement.setAttribute("property", itemData.PropertyName);
                    fieldElement.classList.add("sol_contract_editor_place_holder");
                    if (itemData.IsSection)
                        fieldElement.classList.add("sol_contract_editor_section");
                    setTimeout(() => {
                        if (!this.isEditableArea(window.getSelection().focusNode))
                            return;
                        window.getSelection().getRangeAt(0).insertNode(fieldElement);
                    }, 100);
                }
                isEditableArea(node) {
                    for (var parents = []; node; node = node.parentNode)
                        if (node instanceof Element && node.className == "note-editable")
                            return true;
                    return false;
                }
            }
            Contracts.TemplateEditor = TemplateEditor;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("TemplateEditor", model => new Sol.Web.Contracts.TemplateEditor(model));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class ContractPreview extends Web.Components.HtmlEditor {
                constructor(contractID) {
                    super();
                    this.contractID = contractID;
                    this.css.add("sol_contract_viewer");
                }
                build() {
                    super.build();
                    const templateCombo = this.container.getEditor("ContractTemplate");
                    templateCombo.onChange = () => this.showPreview(parseInt(templateCombo.selectedCode));
                    setTimeout(() => this.showPreview(parseInt(templateCombo.selectedCode)), 1500);
                }
                showPreview(templateCode) {
                    const data = { templateID: templateCode, contractID: this.contractID };
                    Web.System.exec("vvasleos", "GetPreview", data, e => this.value = e.Html);
                }
            }
            Contracts.ContractPreview = ContractPreview;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ContractPreview", (model, ctx, code) => new Sol.Web.Contracts.ContractPreview(code));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class ContractPhaseItensEditor extends Web.Components.DataView {
                constructor() {
                    super();
                    this.allowNew = false;
                    this.footer.visible = false;
                }
                loadDefaultItems() {
                    const screen = this.container.parent;
                    const contractID = screen.anchorage.FilterValue;
                    const data = {
                        className: "Solarium.Contracts.ContractItem, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 0,
                        rowCount: 0,
                        sortProperty: "Batch",
                        sortOrder: Web.Ordering.ascending,
                        filters: [{
                                PropertyName: "Contract",
                                FilterValue: contractID,
                                FilterType: "SInteger"
                            }],
                        properties: ["ID", "Batch", "ItemNumber", "Description", "CurrentQuantityData", "CurrentPrice", "CurrentTotal", "ReleasedQuantityData"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        Sol.List.from(model.Data).forEach(rec => {
                            const recList = Sol.List.from(rec);
                            recList.that(r => r.Campo == "Batch").Campo = "ItemBatch";
                            recList.that(r => r.Campo == "ItemNumber").Campo = "ItemNumber";
                            recList.that(r => r.Campo == "CurrentQuantityData").Campo = "Quantity";
                            recList.that(r => r.Campo == "CurrentTotal").Campo = "Total";
                            recList.that(r => r.Campo == "CurrentPrice").Campo = "Price";
                            recList.that(r => r.Campo == "ReleasedQuantityData").Campo = "InvoicedQuantity";
                        });
                        this.grid.loadData(model);
                        this.grid.rows.forEach(row => {
                            row.code = 0;
                            row.rowData.that(c => c.Campo == "ID").Campo = "RelatedContractItem";
                        });
                        setTimeout(() => this.refreshTotal(), 400);
                    });
                }
                getValor() {
                    return this.rows.select(ln => {
                        const rowData = ln.controls
                            .where(cl => cl.controls.hasItems() && cl.controls.item(0).propertyName)
                            .select(cl => {
                            var vEditor = cl.controls.item(0);
                            return { Campo: vEditor.propertyName, Valor: vEditor.value };
                        })
                            .union([{ Campo: "ID", Valor: ln.code }]);
                        if (!ln.code)
                            rowData.add({ Campo: "RelatedContractItem", Valor: ln.rowData.that(c => c.Campo == "RelatedContractItem").Valor });
                        return rowData.toArray();
                    })
                        .toArray();
                }
            }
            Contracts.ContractPhaseItensEditor = ContractPhaseItensEditor;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ContractPhaseItensEditor", (model, ctx, code) => {
    const editor = new Sol.Web.Contracts.ContractPhaseItensEditor();
    editor.showSearchBox = false;
    editor.fixedRows = false;
    editor.showChecks = false;
    editor.readonly = model.ReadOnly;
    Sol.Web.Editors.fillDataViewStructure(editor, model.Structure);
    if (code == 0)
        setTimeout(() => editor.loadDefaultItems(), 300);
    return editor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class PhaseInvoiceItensEditor extends Web.Components.DataView {
                constructor() {
                    super();
                    this.allowNew = false;
                    this.footer.visible = false;
                    this.onInstantiateRow = row => this.instantiateRow(row);
                }
                loadDefaultItems() {
                    const screen = this.container.parent;
                    const phaseInvoiceID = screen.anchorage.FilterValue;
                    const data = {
                        className: "Solarium.Contracts.ContractPhaseItem, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 0,
                        rowCount: 0,
                        sortProperty: "ID",
                        sortOrder: Web.Ordering.ascending,
                        filters: [{
                                PropertyName: "ContractPhase",
                                FilterValue: phaseInvoiceID,
                                FilterType: "SInteger"
                            },
                            {
                                PropertyName: "OnlyRemainingItemsFilter",
                                FilterValue: true,
                                FilterType: null
                            }],
                        properties: ["ID", "Description", "RemainingQuantityData", "PriceData", "RemainingTotalData"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        Sol.List.from(model.Data).forEach(rec => {
                            const recList = Sol.List.from(rec);
                            recList.that(r => r.Campo == "Description").Campo = "Description";
                            recList.that(r => r.Campo == "RemainingQuantityData").Campo = "Quantity";
                            recList.that(r => r.Campo == "PriceData").Campo = "Price";
                            recList.that(r => r.Campo == "RemainingTotalData").Campo = "Total";
                        });
                        this.grid.loadData(model);
                        this.grid.rows.forEach(row => {
                            row.code = 0;
                            row.rowData.that(c => c.Campo == "ID").Campo = "RelatedPhaseItem";
                        });
                        setTimeout(() => this.refreshTotal(), 400);
                    });
                }
                getValor() {
                    return this.rows.select(ln => {
                        const rowData = ln.controls
                            .where(cl => cl.controls.hasItems() && cl.controls.item(0).propertyName)
                            .select(cl => {
                            var vEditor = cl.controls.item(0);
                            return { Campo: vEditor.propertyName, Valor: vEditor.value };
                        })
                            .union([{ Campo: "ID", Valor: ln.code }]);
                        if (!ln.code)
                            rowData.add({ Campo: "RelatedPhaseItem", Valor: ln.rowData.that(c => c.Campo == "RelatedPhaseItem").Valor });
                        return rowData.toArray();
                    })
                        .toArray();
                }
                instantiateRow(row) {
                    const deliveryCombo = row.getEditor("DeliveryType");
                    deliveryCombo.onValueModified.subscribe(() => this.calculateTotals());
                    deliveryCombo.onValueModified.connect(deliveryCombo, "change");
                }
                calculateTotals() {
                    this.container.getEditor("ProvisionalTotal").numericValue = this.rows
                        .where(row => row.getEditor("DeliveryType").selectedCode == "2")
                        .sum(row => row.getEditor("Total").numericValue);
                    this.container.getEditor("ReleasedTotal").numericValue = this.rows
                        .where(row => row.getEditor("DeliveryType").selectedCode == "3")
                        .sum(row => row.getEditor("Total").numericValue);
                }
            }
            Contracts.PhaseInvoiceItensEditor = PhaseInvoiceItensEditor;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PhaseInvoiceItensEditor", (model, ctx, code) => {
    const editor = new Sol.Web.Contracts.PhaseInvoiceItensEditor();
    editor.showSearchBox = false;
    editor.fixedRows = false;
    editor.showChecks = false;
    editor.readonly = model.ReadOnly;
    Sol.Web.Editors.fillDataViewStructure(editor, model.Structure);
    if (code == 0)
        setTimeout(() => editor.loadDefaultItems(), 300);
    return editor;
});
Sol.Web.Editors.registerEditor("PhaseInvoiceItensEditor", (model, ctx, code) => {
    const editor = new Sol.Web.Contracts.PhaseInvoiceItensEditor();
    editor.showSearchBox = false;
    editor.fixedRows = false;
    editor.showChecks = false;
    editor.readonly = model.ReadOnly;
    Sol.Web.Editors.fillDataViewStructure(editor, model.Structure);
    if (code == 0)
        setTimeout(() => editor.loadDefaultItems(), 300);
    return editor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class ContractItemSelector extends Sol.Control {
                constructor() {
                    super();
                    this.batchField = new Sol.IntegerField();
                    this.itemField = new Sol.IntegerField();
                    this.descriptionDisplay = new Sol.Control("span");
                    this.css.add("sol_contract_item_selector");
                    const batchWrapper = new Sol.FieldWrapper();
                    const batchLabel = new Sol.Label();
                    batchLabel.text = "Lote";
                    batchWrapper.add(batchLabel);
                    this.batchField.ancho = 60;
                    this.batchField.onLeave.subscribe(() => this.search());
                    batchWrapper.add(this.batchField);
                    this.add(batchWrapper);
                    const itemWrapper = new Sol.FieldWrapper();
                    const itemLabel = new Sol.Label();
                    itemLabel.text = "Item";
                    itemWrapper.add(itemLabel);
                    this.itemField.ancho = 60;
                    this.itemField.onLeave.subscribe(() => this.search());
                    itemWrapper.add(this.itemField);
                    this.add(itemWrapper);
                    this.add(this.descriptionDisplay);
                }
                get value() { return this.code; }
                set value(v) {
                    const data = v;
                    this.code = data.Code;
                    this.descriptionDisplay.text = data.Description;
                    this.batchField.numericValue = data.Batch;
                    this.itemField.numericValue = data.ItemNumber;
                }
                isEmpty() { return !this.code; }
                toControl() { return this; }
                search() {
                    if (this.itemField.isEmpty())
                        return;
                    if (this.batchField.numericValue == this.batch && this.itemField.numericValue == this.itemNumber)
                        return;
                    const currentDoc = Web.System.screens.screens.that(screen => screen instanceof Web.Screens.DetailsScreen).code;
                    var data = {
                        className: "Solarium.Contracts.ContractItem, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 1,
                        rowCount: 1,
                        filters: [
                            { PropertyName: "Contract", FilterValue: currentDoc, FilterType: "SInteger" },
                            { PropertyName: "Batch", FilterValue: this.batchField.numericValue, FilterType: "SInteger" },
                            { PropertyName: "ItemNumber", FilterValue: this.itemField.numericValue, FilterType: "SInteger" },
                            { PropertyName: "IsSuppressedFilter", FilterValue: { Campo: "No", Valor: 0 }, FilterType: null }
                        ],
                        sortProperty: "ID",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "Contract", "Description", "QuantityData", "PriceData", "TotalData", "CurrentQuantityData", "PercentIncreaseQuantityData", "MaxQuantityAllowedData"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        if (!model.Data || model.Data.length == 0) {
                            this.descriptionDisplay.text = "Item não encontrado";
                            this.code = 0;
                            this.batch = 0;
                            this.itemNumber = 0;
                            this.container.getEditor("Quantity").clear();
                            this.container.getEditor("Quantity").maxValue = null;
                            this.container.getEditor("CurrentQuantity").clear();
                            this.container.getEditor("Price").clear();
                            this.container.getEditor("Total").clear();
                            this.container.getEditor("PercentIncreaseQuantity").clear();
                            return;
                        }
                        this.code = model.Codes[0];
                        this.batch = this.batchField.numericValue;
                        this.itemNumber = this.itemField.numericValue;
                        var data = Sol.List.from(model.Data[0]);
                        this.descriptionDisplay.text = data.that(d => d.Campo == "Description").Valor;
                        if (this.container.getEditor("InitialQuantity"))
                            this.container.getEditor("InitialQuantity").value = data.that(d => d.Campo == "QuantityData").Valor;
                        this.container.getEditor("CurrentQuantity").value = data.that(d => d.Campo == "CurrentQuantityData").Valor;
                        if (this.container.getEditor("PercentIncreaseQuantity"))
                            this.container.getEditor("PercentIncreaseQuantity").value = data.that(d => d.Campo == "PercentIncreaseQuantityData").Valor;
                        this.container.getEditor("Price").value = data.that(d => d.Campo == "PriceData").Valor;
                        this.container.getEditor("Total").value = data.that(d => d.Campo == "TotalData").Valor;
                        if (this.container.getEditor("Quantity"))
                            this.container.getEditor("Quantity").maxValue = data.that(d => d.Campo == "MaxQuantityAllowedData").Valor;
                    });
                }
                clear() { }
                foco() { }
                validate() { return null; }
            }
            Contracts.ContractItemSelector = ContractItemSelector;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ContractItemSelector", (model, ctx, code) => new Sol.Web.Contracts.ContractItemSelector());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class ContractFileSigner extends Web.Components.Uploads.FileSigner {
            }
            Contracts.ContractFileSigner = ContractFileSigner;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            let ImplicatedPersonType;
            (function (ImplicatedPersonType) {
                ImplicatedPersonType[ImplicatedPersonType["Login"] = 1] = "Login";
                ImplicatedPersonType[ImplicatedPersonType["Contact"] = 2] = "Contact";
            })(ImplicatedPersonType = Contracts.ImplicatedPersonType || (Contracts.ImplicatedPersonType = {}));
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class ImplicatedPersonDisplay extends Sol.Control {
                constructor(model, readOnly) {
                    super();
                    this.participationDisplay = new Sol.Control();
                    this.model = model;
                    this.readonly = readOnly;
                    this.css.add("sol_implicated_display");
                }
                build() {
                    var _a;
                    const picture = new Sol.Control("img");
                    picture.css.add("sol_implicated_img");
                    picture.atributos.agregar("src", this.model.PictureUrl);
                    this.add(picture);
                    if (!this.readonly) {
                        const deleteButton = this.addCtr('x', "sol_impl_person_delete");
                        deleteButton.onClick = () => this.parent.controls.remove(this);
                    }
                    this.addCtr(this.model.Name, "sol_implicated_people");
                    this.addCtr(this.model.EmployeeID, "sol_implicated_people");
                    this.participationDisplay.css.add("sol_implicated_type");
                    this.updateParticipationDisplay();
                    this.add(this.participationDisplay);
                    if (this.showRoles) {
                        const roleCombo = new Sol.Combo();
                        roleCombo.loadOptions(this.mySelector.roles);
                        roleCombo.selectedCode = (_a = this.model.ImplicationType) === null || _a === void 0 ? void 0 : _a.toString();
                        roleCombo.readonly = this.readonly;
                        roleCombo.onChange = () => this.model.ImplicationType = parseInt(roleCombo.selectedCode);
                        this.add(roleCombo);
                    }
                    super.build();
                }
                updateParticipationDisplay() {
                    this.participationDisplay.text = this.model.TermEndValue && Date.convert(this.model.TermEndValue) < new Date() ?
                        "Participação concluída" :
                        this.model.PersonType == Contracts.ImplicatedPersonType.Login ?
                            "Usuário(a) do Sistema" : "Contato do Contratado";
                }
            }
            Contracts.ImplicatedPersonDisplay = ImplicatedPersonDisplay;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class ImplicatedSelector extends Web.Components.Selectors.Selector {
                search(code, cancelClickEvent) {
                    return __awaiter(this, void 0, void 0, function* () {
                        if (this.readonly)
                            return;
                        if (this.ajax)
                            this.ajax.abort();
                        const contractID = Web.System.screens.currentID;
                        this.ajax = Web.System.exec("vvasleos", "SearchContacts", { term: this.mainField.value, contractID: contractID }, e => {
                            const results = Sol.List.from(e);
                            this.popup.clearContent();
                            if (!results.hasItems()) {
                                const emptyMessage = new Sol.Control();
                                emptyMessage.text = Sol.Environment.resources.no_encontrado;
                                this.popup.add(emptyMessage);
                            }
                            else {
                                this.addLoginResults(results);
                                this.addContactResults(results);
                            }
                            this.popup.show();
                        });
                    });
                }
                addLoginResults(results) {
                    const logins = results.where(r => r.PersonType == Contracts.ImplicatedPersonType.Login);
                    if (!logins.hasItems())
                        return;
                    const usersArea = new Sol.Control();
                    usersArea.add(this.addSectionTitle(Sol.Environment.resources.usuario + "s"));
                    usersArea.css.add("sol_implicated_area");
                    usersArea.controls.addMany(logins.select(lg => this.addDisplayToPopup(lg)));
                    this.popup.add(usersArea);
                }
                addContactResults(results) {
                    const contacts = results.where(r => r.PersonType == Contracts.ImplicatedPersonType.Contact);
                    if (!contacts.hasItems())
                        return;
                    const usersArea = new Sol.Control();
                    usersArea.add(this.addSectionTitle(Sol.Environment.resources.contact));
                    usersArea.css.add("sol_implicated_area");
                    usersArea.controls.addMany(contacts.select(c => this.addDisplayToPopup(c)));
                    this.popup.add(usersArea);
                }
                addSectionTitle(text) {
                    const title = new Sol.Control("h5");
                    title.text = text;
                    return title;
                }
                addDisplayToPopup(model) {
                    const display = new Contracts.ImplicatedPersonDisplay(model, true);
                    display.onClick = () => this.selectItem(model);
                    return display;
                }
                selectItem(model) {
                    this.mainField.value = model.Name;
                    this._value = model.PersonID;
                    this.mainField.foco();
                    this.popup.hide();
                }
            }
            Contracts.ImplicatedSelector = ImplicatedSelector;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ImplicatedSelector", () => new Sol.Web.Contracts.ImplicatedSelector());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class ContractHistoryScreen extends Web.Screens.HistoryScreenBase {
                constructor() {
                    super();
                    this.manager = "vvasleos";
                    this.methodName = "GetHistory";
                    this.screenCaption = "Histórico";
                    this.interval.visible = false;
                }
                configureColumns() {
                    this.grid.columns = Sol.List.from([
                        {
                            Title: Sol.Environment.resources.date,
                            DataType: "SDate",
                            PropertyName: "Date",
                            Alignment: Sol.Alignment.Left,
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: "Descrição",
                            DataType: "SText",
                            PropertyName: "Description",
                            Alignment: Sol.Alignment.Left,
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: "Total inicial",
                            DataType: "SMoney",
                            PropertyName: "StartingTotal",
                            Alignment: Sol.Alignment.Right,
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: "Total inicial atualizado",
                            DataType: "SMoney",
                            PropertyName: "UpdatedStartingTotal",
                            Alignment: Sol.Alignment.Right,
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: "Total",
                            DataType: "SMoney",
                            PropertyName: "Total",
                            Alignment: Sol.Alignment.Right,
                            ShowTitle: true,
                            Visible: true
                        },
                        {
                            Title: "Total despesa",
                            DataType: "SMoney",
                            PropertyName: "TotalExpenses",
                            Alignment: Sol.Alignment.Right,
                            ShowTitle: true,
                            Visible: true
                        }
                    ]);
                }
                getSearchData() {
                    return {
                        contractID: this.code,
                        interval: this.interval.value,
                        pageCount: this.gridRowCount,
                        pageNumber: this.currentPage
                    };
                }
            }
            Contracts.ContractHistoryScreen = ContractHistoryScreen;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ContractHistoryAction extends Actions.ActionBase {
                processResponse(data) {
                    const screen = new Web.Contracts.ContractHistoryScreen();
                    Web.System.screens.addScreen(screen);
                    Web.System.screens.showScreen(screen);
                }
            }
            Actions.ContractHistoryAction = ContractHistoryAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class InvoiceSelector extends Web.Components.DualCombo {
                constructor() {
                    super();
                    const screen = Web.System.screens.screens.that(scr => scr instanceof Web.Screens.DetailsScreen);
                    this.mainCombo.filters.add({
                        FilterType: "SInteger",
                        PropertyName: "Phase$Contract",
                        FilterValue: screen.code
                    });
                }
            }
            Contracts.InvoiceSelector = InvoiceSelector;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("InvoiceSelector", model => {
    const invoiceSelector = new Sol.Web.Contracts.InvoiceSelector();
    invoiceSelector.subClassName = model.DataTypeFullName;
    return invoiceSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            let GovernmentItemType;
            (function (GovernmentItemType) {
                GovernmentItemType[GovernmentItemType["Product"] = 1] = "Product";
                GovernmentItemType[GovernmentItemType["Service"] = 2] = "Service";
                GovernmentItemType[GovernmentItemType["Other"] = 3] = "Other";
            })(GovernmentItemType = Government.GovernmentItemType || (Government.GovernmentItemType = {}));
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class ItemTypeChoice extends Sol.MultipleChoice {
                constructor() {
                    super();
                    this.inlineItems = true;
                    this.onValueModified.subscribe(() => this.setQuantityType());
                    this.onSet.subscribe(() => this.setQuantityType());
                }
                setQuantityType() {
                    this.container
                        .editors
                        .where(e => e.propertyName.indexOf("Quantity") > -1)
                        .where(e => e instanceof Web.Commercial.QuantityField)
                        .cast()
                        .forEach(e => e.unitType = this.selectedCode == Government.GovernmentItemType.Product ? Web.Commercial.UnitType.Product : Web.Commercial.UnitType.Service);
                }
            }
            Government.ItemTypeChoice = ItemTypeChoice;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ItemTypeChoice", model => {
    const discountChoice = new Sol.Web.Government.ItemTypeChoice();
    discountChoice.options = model.Options;
    return discountChoice;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class MultipleChoiceContractItem extends Web.Government.ItemTypeChoice {
                build() {
                    super.build();
                    this.items.item(2).visible = this.showVehicleOption;
                    this.items.item(3).visible = this.showPropertyOption;
                }
            }
            Contracts.MultipleChoiceContractItem = MultipleChoiceContractItem;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("MultipleChoiceContractItem", model => {
    const choiceContractItem = new Sol.Web.Contracts.MultipleChoiceContractItem();
    choiceContractItem.options = model.Options;
    choiceContractItem.configuration = model.Configuration;
    return choiceContractItem;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class VehicleContractListEditor extends Sol.Control {
                constructor() {
                    super("ul");
                    this.isComplex = true;
                    this.css.add("sol_vehicle_contract");
                }
                build() {
                    super.build();
                    Web.System.exec("spoe35sleop", "GetVehicleContracts", { vehicleID: this.code }, models => {
                        const modelList = Sol.List.from(models);
                        this.addMany(modelList.select(m => {
                            const item = new Sol.Control("li");
                            item.css.add("sol_vehicle_contract_lic");
                            item.addCtr("Contrato Nº: " + m.ContractNumber, "sol_lic_vehicle_contract_title", "span");
                            item.addCtr("Total: " + m.Total, "sol_lic_vehicle_contract_title_right", "span");
                            item.add(new Sol.LineBreak());
                            item.addCtr("Status: " + m.Status, "", "span");
                            item.addCtr("Início do Contrato: " + m.StartDate, "sol_lic_vehicle_contract_float_right", "span");
                            item.add(new Sol.LineBreak());
                            item.addCtr(m.SupplierName, "", "span");
                            item.addCtr("Fim do Contrato: " + m.CompletionDate, "sol_lic_vehicle_contract_float_right", "span");
                            item.add(new Sol.LineBreak());
                            return item;
                        }));
                        if (!modelList.hasItems())
                            this.addCtr("Este veículo não possuí nenhum contrato associdado.", "sol_lic_vehicle_contract_title_no");
                    });
                }
                clear() { }
                foco() { }
                isEmpty() { return true; }
                toControl() { return this; }
                validate() { return null; }
            }
            Contracts.VehicleContractListEditor = VehicleContractListEditor;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class PropertyContractListEditor extends Sol.Control {
                constructor() {
                    super("ul");
                    this.isComplex = true;
                    this.css.add("sol_vehicle_contract");
                }
                build() {
                    super.build();
                    Web.System.exec("spoe35sleop", "GetPropertyContracts", { propertyID: this.code }, models => {
                        const modelList = Sol.List.from(models);
                        this.addMany(modelList.select(m => {
                            const item = new Sol.Control("li");
                            item.css.add("sol_vehicle_contract_lic");
                            item.addCtr("Contrato Nº: " + m.ContractNumber, "sol_lic_vehicle_contract_title", "span");
                            item.addCtr("Total: " + m.Total, "sol_lic_vehicle_contract_title_right", "span");
                            item.add(new Sol.LineBreak());
                            item.addCtr("Status: " + m.Status, "", "span");
                            item.addCtr("Início do Contrato: " + m.StartDate, "sol_lic_vehicle_contract_float_right", "span");
                            item.add(new Sol.LineBreak());
                            item.addCtr(m.SupplierName, "", "span");
                            item.addCtr("Fim do Contrato: " + m.CompletionDate, "sol_lic_vehicle_contract_float_right", "span");
                            item.add(new Sol.LineBreak());
                            return item;
                        }));
                        if (!modelList.hasItems())
                            this.addCtr("Este imóvel não possuí nenhum contrato associdado.", "sol_lic_vehicle_contract_title_no");
                    });
                }
                clear() { }
                foco() { }
                isEmpty() { return true; }
                toControl() { return this; }
                validate() { return null; }
            }
            Contracts.PropertyContractListEditor = PropertyContractListEditor;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Contracts;
        (function (Contracts) {
            class ContractEndDateDisplay extends Sol.DateField {
                build() {
                    const contractID = Web.System.screens.currentID;
                    Web.System.exec("vvasleos", "GetContractEndDate", { contractID }, e => this.value = e);
                    super.build();
                }
            }
            Contracts.ContractEndDateDisplay = ContractEndDateDisplay;
        })(Contracts = Web.Contracts || (Web.Contracts = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ContractEndDateDisplay", () => new Sol.Web.Contracts.ContractEndDateDisplay());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class HierarchicalScreen extends Screens.DetailsScreen {
                constructor() {
                    super(...arguments);
                    this.treeView = new Web.Components.TreeView();
                }
                build() {
                    this.myModel = this.model;
                    this.css.add("sol_hierarchical_screen");
                    this.initializeTitle();
                    this.model = this.myModel.Details;
                    this.showCancelButton = false;
                    this.showSaveAndNew = false;
                    this.showOKButton = false;
                    this.showTitle = false;
                    this.disableLoader = true;
                    this.saveButton.enabled = false;
                    this.hideBackToTopButton = true;
                    this.onLocalSaved.subscribe(() => this.formSaved());
                    if (this.myModel.AnchorageProperty)
                        this.anchorage = {
                            PropertyName: this.myModel.AnchorageProperty,
                            FilterType: "SInteger",
                            FilterValue: this.myModel.AnchorageCode
                        };
                    super.build();
                    this.initializeTreeview();
                }
                initializeTitle() {
                    this.screenCaption = this.myModel.ScreenTitle;
                    var title = new Screens.ScreenTitle();
                    title.text = this.myModel.ScreenTitle;
                    title.estilos.agregar("margin-bottom", "10px");
                    this.add(title);
                }
                initializeTreeview() {
                    this.treeView.rootLabel = this.myModel.ScreenTitle;
                    this.treeView.className = this.myModel.ClassName;
                    this.treeView.parentPropertyName = this.myModel.ParentPropertyName;
                    this.treeView.onNodeSelected = e => this.nodeSelected(e);
                    this.treeView.anchorage = this.anchorage;
                    this.controls.insert(this.controls.indice(this.myForm), this.treeView);
                    this.treeView.loadData(this.myModel.Nodes);
                }
                nodeSelected(node) {
                    this.saveButton.enabled = false;
                    if (!node.code)
                        this.clear();
                    else
                        this.load(node.code);
                }
                formSaved() {
                    const nameField = this.getEditor("Nombre");
                    this.treeView.selectedNode.caption = nameField.value;
                }
            }
            Screens.HierarchicalScreen = HierarchicalScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class ListSelectorScreen extends Screens.BaseScreen {
                constructor() {
                    super();
                    this.list = new Web.Components.ListView();
                    this.okButton = new Sol.Button();
                    this.cancelButton = new Sol.Button();
                    this.mainArea = new Sol.Control();
                }
                get myModel() { return this.model; }
                get checkedItems() {
                    this.list.items.forEach(i => i.checked = i.getEditor("CheckCommand").value);
                    return this.list.checkedItems;
                }
                get groupProperty() { return this.list.groupProperty; }
                set groupProperty(value) { this.list.groupProperty = value; }
                set emptyListMessage(value) { this.list.messageText = value; }
                get okCaption() { return this.okButton.text; }
                set okCaption(value) { this.okButton.text = value; }
                setItems(data, ids = null) {
                    this.list.addItems(data, ids);
                    this.okButton.visible = this.list.items.hasItems();
                }
                build() {
                    this.displayTitle();
                    this.initializeScreen();
                    this.initializeList();
                    super.build();
                }
                displayTitle() {
                    this.screenCaption = this.myModel.ScreenTitle;
                    var title = new Screens.ScreenTitle();
                    title.text = this.myModel.ScreenTitle;
                    title.estilos.agregar("margin-bottom", "10px");
                    this.add(title);
                }
                initializeScreen() {
                    this.mainArea.css.add("sol_list_selector_main_area");
                    this.add(this.mainArea);
                    this.mainArea.add(this.list);
                    this.cancelButton.text = "Cancelar";
                    this.cancelButton.onClick = () => Web.System.screens.closeCurrentScreen();
                    this.mainArea.add(this.cancelButton);
                    this.okButton.onClick = () => this.save();
                    this.mainArea.add(this.okButton);
                }
                initializeList() {
                    this.list.className = this.myModel.ClassName;
                    this.list.orderByProperty = "ID";
                    this.list.css.add("sol_list_selector");
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: false,
                            property: "CheckCommand",
                            defaultText: Sol.Environment.resources.open,
                            priority: Web.Components.ListViewFieldPriority.High,
                            position: Web.Components.ListViewFieldPosition.Left,
                            cssClass: "sol_list_selector_content",
                            editor: {
                                AllowChangeCurrency: false,
                                DataType: "SBoolean",
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: false,
                                PropertyName: "CheckCommand"
                            }
                        }
                    ]);
                    this.list.configuration.addMany(this.fields);
                }
                save() {
                    if (!this.checkedItems.hasItems) {
                        alert("Nenhum item selecionado");
                        return;
                    }
                    if (this.onSave)
                        this.onSave(this);
                }
            }
            Screens.ListSelectorScreen = ListSelectorScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ListSelectorAction extends Actions.ActionBase {
                processResponse(data) {
                    const screen = new Web.Screens.ListSelectorScreen();
                    screen.model = data;
                    screen.fields = this.fields;
                    Web.System.screens.addScreen(screen);
                    Web.System.screens.showScreen(screen);
                    this.setItems(screen, data);
                    screen.onSave = e => this.save(e);
                }
            }
            Actions.ListSelectorAction = ListSelectorAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class DrawerScreen extends Screens.BaseScreen {
                constructor() {
                    super(...arguments);
                    this.dateField = new Sol.DateField();
                    this.searchButton = new Sol.Button();
                    this.checkPointSelector = new Web.Components.DataCombo();
                    this.openingAmount = new Sol.CurrencyField();
                    this.closingAmount = new Sol.CurrencyField();
                    this.drawerList = new Web.Components.ListView();
                    this.salesReport = new Screens.SalesReport();
                    this.mainArea = new Sol.Control();
                    this.floatArea = new Sol.Control();
                    this.drawerListWrapper = new Sol.Control();
                    this.newDrawShiftArea = new Sol.Control();
                    this.newDrawShiftAmount = new Sol.CurrencyField();
                    this.newDrawShiftCancelButton = new Sol.Button();
                    this.newDrawShiftOkButton = new Sol.Button();
                    this.newDrawShiftAmountLabel = new Sol.Label();
                    this.descriptionField = new Sol.TextField();
                    this.userCheck = new Sol.Check();
                    this.saveOpeningAmountButton = new Sol.Button();
                }
                get myModel() { return this.model; }
                build() {
                    super.build();
                    this.displayTitle();
                    this.mainArea.css.add("drawer_screen_main_area");
                    this.add(this.mainArea);
                    this.initializeData();
                    this.mainArea.add(this.floatArea);
                    this.floatArea.css.add("drawer_screen_float_area");
                    this.salesReport.onLoad = () => this.calculateTotal();
                    this.floatArea.add(this.salesReport);
                    this.initializeDrawerList();
                    this.initializeTotalizationArea();
                    setTimeout(() => this.searchDateInfo(), 500);
                }
                displayTitle() {
                    this.screenCaption = "Caixa Diário";
                    var title = new Screens.ScreenTitle();
                    title.text = "Caixa Diário";
                    title.estilos.agregar("margin-bottom", "10px");
                    this.add(title);
                }
                initializeData() {
                    const wrapper = new Sol.FieldWrapper();
                    const dateWrapper = new Sol.FieldWrapper();
                    const dateLabel = new Sol.Label();
                    dateLabel.text = "Data:";
                    dateLabel.editor = this.dateField;
                    dateWrapper.add(dateLabel);
                    dateWrapper.add(this.dateField);
                    this.dateField.setToday();
                    this.searchButton.text = Sol.Environment.resources.buscar;
                    this.searchButton.imageCode = "&#xf002;";
                    this.searchButton.onClick = () => this.searchDateInfo();
                    dateWrapper.add(this.searchButton);
                    const checkPointWrapper = new Sol.FieldWrapper();
                    const checkPointLabel = new Sol.Label();
                    checkPointLabel.text = "Caixa:";
                    checkPointLabel.editor = this.checkPointSelector;
                    checkPointWrapper.add(checkPointLabel);
                    checkPointWrapper.add(this.checkPointSelector);
                    this.checkPointSelector.className = "Solarium.Commercial.CheckoutPoint, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    checkPointWrapper.visible = this.myModel.ShowCheckPointSelector;
                    this.checkPointSelector.required = true;
                    this.checkPointSelector.refresh();
                    const openingAmountWrapper = new Sol.FieldWrapper();
                    const openingAmountLabel = new Sol.Label();
                    openingAmountLabel.text = "Valor Inicial (Dinheiro):";
                    openingAmountLabel.editor = this.openingAmount;
                    this.saveOpeningAmountButton.imageCode = "&#xf0c7;";
                    this.saveOpeningAmountButton.onClick = () => this.addInitialDrawer();
                    openingAmountWrapper.add(openingAmountLabel);
                    openingAmountWrapper.add(this.openingAmount);
                    openingAmountWrapper.add(this.saveOpeningAmountButton);
                    this.userCheck.caption = "Exibir somente as minhas movimentações";
                    this.userCheck.css.add("drawer_screen_user_check");
                    wrapper.add(checkPointWrapper);
                    wrapper.add(dateWrapper);
                    wrapper.add(openingAmountWrapper);
                    wrapper.add(this.userCheck);
                    this.mainArea.add(wrapper);
                }
                initializeDrawerList() {
                    const drawerListTitle = new Sol.Control("h4");
                    drawerListTitle.text = "Sangrias/Reforços";
                    this.drawerListWrapper.add(drawerListTitle);
                    this.drawerList.className = "Solarium.Commercial.DrawerShift, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.drawerList.messageText = "Nenhuma movimentação encontrada.";
                    this.drawerList.onInstantiateItem = e => this.instantiateItem(e);
                    this.drawerList.configuration = Sol.List.from([
                        {
                            loadable: true,
                            property: "ShiftType",
                            position: Web.Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "DisplayAmount",
                            position: Web.Components.ListViewFieldPosition.Right
                        },
                        {
                            loadable: true,
                            property: "Description",
                            position: Web.Components.ListViewFieldPosition.Left
                        }
                    ]);
                    this.createForm();
                }
                initializeTotalizationArea() {
                    const closingAmountWrapper = new Sol.Control();
                    const closingAmountLabel = new Sol.Label();
                    closingAmountLabel.text = "Valor Final (Dinheiro):";
                    closingAmountLabel.editor = this.closingAmount;
                    closingAmountWrapper.add(closingAmountLabel);
                    this.closingAmount.acceptsNegative = true;
                    closingAmountWrapper.add(this.closingAmount);
                    closingAmountWrapper.css.addMany(["sol_detalles_wrapper", "drawer_screen_totalization_wrapper"]);
                    this.closingAmount.readonly = true;
                    this.mainArea.add(closingAmountWrapper);
                }
                calculateTotal() {
                    this.closingAmount.numericValue = this.salesReport.cashTotal + this.drawerTotal + this.openingAmount.numericValue;
                }
                createForm() {
                    const addIncrementDrawerButton = new Sol.Button();
                    addIncrementDrawerButton.text = "Adicionar reforço";
                    addIncrementDrawerButton.visible = (this.myModel.ShowCheckPointSelector && !this.checkPointSelector.value) ? false : true;
                    addIncrementDrawerButton.onClick = () => this.addIncrementDrawer();
                    const addPickUpDrawerButton = new Sol.Button();
                    addPickUpDrawerButton.text = "Adicionar sangria";
                    addPickUpDrawerButton.visible = (this.myModel.ShowCheckPointSelector && !this.checkPointSelector.value) ? false : true;
                    addPickUpDrawerButton.onClick = () => this.addPickUpDrawer();
                    this.drawerListWrapper.css.add("drawer_screen_main_area_list_wrapper");
                    this.drawerListWrapper.add(this.drawerList);
                    this.drawerListWrapper.add(addIncrementDrawerButton);
                    this.drawerListWrapper.add(addPickUpDrawerButton);
                    const newDrawShiftAmountWrapper = new Sol.FieldWrapper();
                    newDrawShiftAmountWrapper.add(this.newDrawShiftAmountLabel);
                    newDrawShiftAmountWrapper.add(this.newDrawShiftAmount);
                    const descriptionLabel = new Sol.Label();
                    descriptionLabel.text = Sol.Environment.resources.description;
                    this.newDrawShiftArea.add(newDrawShiftAmountWrapper);
                    this.newDrawShiftArea.add(descriptionLabel);
                    this.newDrawShiftArea.add(this.descriptionField);
                    this.newDrawShiftCancelButton.imageCode = "&#xf00d;";
                    this.newDrawShiftArea.add(this.newDrawShiftCancelButton);
                    this.newDrawShiftCancelButton.onClick = () => this.hideShiftArea();
                    this.newDrawShiftOkButton.imageCode = "&#xf0c7;";
                    this.newDrawShiftArea.add(this.newDrawShiftOkButton);
                    this.newDrawShiftOkButton.onClick = () => this.save();
                    this.newDrawShiftArea.visible = false;
                    this.newDrawShiftArea.css.addMany(["sol_detalles_wrapper", "drawer_screen_new_draw_shift_area"]);
                    this.drawerListWrapper.add(this.newDrawShiftArea);
                    this.floatArea.add(this.drawerListWrapper);
                }
                searchDateInfo() {
                    this.openingAmount.clear();
                    this.closingAmount.clear();
                    const data = {
                        credential: Sol.Environment.credential.export(),
                        date: this.dateField.value,
                        checkoutPointID: this.myModel.ShowCheckPointSelector ? parseInt(this.checkPointSelector.value.Valor) : 0,
                        consultant: this.userCheck.value
                    };
                    Web.System.exec("79kdsyjh", "GetDateDrawers", data, e => {
                        this.drawerList.clear();
                        if (e == null)
                            return;
                        this.drawerTotal = 0;
                        const items = Sol.List.from(e).where(i => i.ShiftTypeCode != Screens.ShiftType.Opening).select(i => {
                            this.drawerTotal += i.ShiftTypeCode == Screens.ShiftType.Pickup ? i.Amount * -1 : i.Amount;
                            return [{ Campo: "Amount", Valor: i.Amount },
                                { Campo: "DisplayAmount", Valor: i.DisplayAmount },
                                { Campo: "ShiftType", Valor: i.ShiftType },
                                { Campo: "ShiftTypeCode", Valor: i.ShiftTypeCode },
                                { Campo: "CheckoutPoint", Valor: i.CheckoutPoint },
                                { Campo: "CheckoutPointID", Valor: i.CheckoutPointID },
                                { Campo: "Description", Valor: i.Description }];
                        }).toArray();
                        const ids = Sol.List.from(e).select(i => i.ID).toArray();
                        this.saveOpeningAmountButton.enabled = !this.userCheck.value;
                        this.openingAmount.readonly = this.userCheck.value;
                        if (!this.userCheck.value) {
                            var openingShift = Sol.List.from(e).that(i => i.ShiftTypeCode == Screens.ShiftType.Opening);
                            this.openingAmount.numericValue = openingShift ? openingShift.Amount : 0;
                        }
                        this.salesReport.refreshReport(this.dateField.value, this.myModel.ShowCheckPointSelector ? parseInt(this.checkPointSelector.value.Valor) : 0, this.userCheck.checked);
                        this.drawerList.addItems(items, ids);
                    }, null);
                }
                addInitialDrawer() {
                    this.saveOpeningValue();
                }
                addPickUpDrawer() {
                    this.newDrawShiftAmountLabel.text = "Valor da Sangria:";
                    this.newDrawShiftArea.visible = true;
                    this.newDrawShiftAmount.clear();
                    this.newDrawShiftAmount.foco();
                    this.shiftType = Screens.ShiftType.Pickup;
                }
                addIncrementDrawer() {
                    this.newDrawShiftAmountLabel.text = "Valor do Reforço:";
                    this.newDrawShiftArea.visible = true;
                    this.newDrawShiftAmount.clear();
                    this.newDrawShiftAmount.foco();
                    this.shiftType = Screens.ShiftType.Increment;
                }
                validate() {
                    if (this.newDrawShiftAmount.numericValue == 0) {
                        alert(Sol.Environment.resources.empty_value);
                        return false;
                    }
                    if (this.descriptionField.isEmpty()) {
                        alert(Sol.Environment.resources.empty_field + Sol.Environment.resources.description);
                        return false;
                    }
                    return true;
                }
                hideShiftArea() {
                    this.newDrawShiftAmount.clear();
                    this.descriptionField.clear();
                    this.newDrawShiftArea.visible = false;
                }
                save() {
                    if (!this.validate())
                        return;
                    const model = {
                        ID: 0,
                        Amount: this.newDrawShiftAmount.numericValue,
                        DisplayAmount: null,
                        ShiftTypeCode: this.shiftType,
                        ShiftType: null,
                        CheckoutPointID: this.myModel.ShowCheckPointSelector ? parseInt(this.checkPointSelector.value.Valor) : 0,
                        CheckoutPoint: null,
                        Description: this.descriptionField.value,
                        Fail: null
                    };
                    const data = {
                        credential: Sol.Environment.credential.export(),
                        model: model,
                        date: this.dateField.value
                    };
                    Web.System.exec("79kdsyjh", "SaveDrawer", data, e => {
                        if (e.Fail) {
                            alert("Erro ao processar movimentação.");
                            return;
                        }
                        this.drawerList.addItemFromData([{ Campo: "Amount", Valor: e.Amount },
                            { Campo: "DisplayAmount", Valor: e.DisplayAmount },
                            { Campo: "ShiftType", Valor: e.ShiftType },
                            { Campo: "ShiftTypeCode", Valor: e.ShiftTypeCode },
                            { Campo: "CheckoutPoint", Valor: e.CheckoutPoint },
                            { Campo: "CheckoutPointID", Valor: e.CheckoutPointID },
                            { Campo: "Description", Valor: e.Description }], e.ID);
                        this.drawerTotal += e.ShiftTypeCode == Screens.ShiftType.Pickup ? e.Amount * -1 : e.Amount;
                        this.calculateTotal();
                    }, null);
                    this.hideShiftArea();
                }
                saveOpeningValue() {
                    const model = {
                        ID: 0,
                        Amount: this.openingAmount.numericValue,
                        DisplayAmount: null,
                        ShiftTypeCode: Screens.ShiftType.Opening,
                        ShiftType: null,
                        CheckoutPointID: this.myModel.ShowCheckPointSelector ? parseInt(this.checkPointSelector.value.Valor) : 0,
                        CheckoutPoint: null,
                        Description: "Valor inicial",
                        Fail: null
                    };
                    const data = {
                        credential: Sol.Environment.credential.export(),
                        model: model,
                        date: this.dateField.value
                    };
                    Web.System.exec("79kdsyjh", "SaveDrawer", data, e => {
                        if (e.Fail) {
                            alert("Erro ao processar movimentação.");
                        }
                        alert("Valor Inicial salvo com sucesso.");
                        this.openingAmount.numericValue = e.Amount;
                        this.calculateTotal();
                    }, null);
                }
                instantiateItem(item) {
                    item.getDisplay("ShiftType").css.add(item.getModelValue("ShiftTypeCode") == Screens.ShiftType.Pickup ? "drawer_shift_pick_up" : "drawer_shift_increment");
                }
            }
            Screens.DrawerScreen = DrawerScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class IDrawerScreenModel {
            }
            Screens.IDrawerScreenModel = IDrawerScreenModel;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class IDrawerShiftModel {
            }
            Screens.IDrawerShiftModel = IDrawerShiftModel;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            let ShiftType;
            (function (ShiftType) {
                ShiftType[ShiftType["Opening"] = 1] = "Opening";
                ShiftType[ShiftType["Pickup"] = 2] = "Pickup";
                ShiftType[ShiftType["Increment"] = 3] = "Increment";
            })(ShiftType = Screens.ShiftType || (Screens.ShiftType = {}));
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class SalesReport extends Web.Components.Reports.Report {
                get cashTotal() {
                    if (!this.model)
                        return 0;
                    var hasCashEntries = Sol.List.from(this.model.Rows).that(row => row.GroupID == 2);
                    return hasCashEntries ? Sol.List.from(hasCashEntries.Cells).sum(cell => cell.DecimalValue) : 0;
                }
                ;
                refreshReport(date, checkoutPoint, userCheck) {
                    this.createFromSuggestion({
                        Columns: [{ Title: "Forma de Pagamento", PropertyName: "Payment$PaymentMode", Availability: 1, Loadable: true }],
                        CurrencyPropertyName: "Total$Moneda",
                        CustomFiltersStructure: null,
                        CustomFiltersTypeName: null,
                        IsMultiCurrency: false,
                        SelectedCurrency: "BRL",
                        PropertyName: "Payment$PaymentMode",
                        ReferenceID: 0,
                        ReportTitle: "Total por Forma de Pagamento",
                        ReportType: 0,
                        ReportTypeName: "Solarium.Commercial.Reports.TotalsByPaymentModeReport, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        Type: "Solarium.Commercial.Venta, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
                    }, [{ FilterType: null, FilterValue: date, PropertyName: "reportDate" },
                        { FilterType: null, FilterValue: checkoutPoint, PropertyName: "checkoutPoint" },
                        { FilterType: null, FilterValue: userCheck, PropertyName: "userFilter" }]);
                }
                initialize(model) {
                    super.initialize(model);
                    this.onLoad();
                }
            }
            Screens.SalesReport = SalesReport;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class CommissioningViewScreen extends Screens.BaseScreen {
                build() {
                    super.build();
                    this.css.add("sol_commissioning_view_screen");
                    this.displayTitle();
                    this.displayCommissioningModel();
                }
                displayTitle() {
                    this.screenCaption = Sol.Environment.resources.commissioning_model;
                    var title = new Screens.ScreenTitle();
                    title.text = Sol.Environment.resources.commissioning_model;
                    title.estilos.agregar("margin-bottom", "10px");
                    this.add(title);
                }
                displayCommissioningModel() {
                    const main = new Sol.Control();
                    main.css.add("sol_commissioning_view_screen_content");
                    this.add(main);
                    if (!this.model.File) {
                        var content = new Sol.Control();
                        content.text = Sol.Environment.resources.commissioning_model_unavailable;
                        main.add(content);
                        return;
                    }
                    const fakeDiv = new Sol.Control();
                    fakeDiv.css.add("sol_commissioning_view_screen_content_fake_div");
                    main.add(fakeDiv);
                    const pdfViewer = new Sol.WebComponents.PdfViewer();
                    pdfViewer.hideToolbar = true;
                    pdfViewer.source = "/pdf/" + this.model.File;
                    main.add(pdfViewer);
                }
            }
            Screens.CommissioningViewScreen = CommissioningViewScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class ServiceGridSelector extends Selectors.Selector {
                    constructor() {
                        super();
                        this.resultsOrder = "Nombre";
                        this.filterProperty = "Nombre";
                        this.allowCreateNew = false;
                        this.allowEdit = false;
                        this.isComplex = false;
                        this.properties = ["PriceData"];
                        this.autoWidth = false;
                        this.css.add("sol_service_grid_selector");
                        this.onItemSelected = item => this.selectedService(item);
                    }
                    getFilters() {
                        var filters = super.getFilters();
                        filters.add({ PropertyName: "EntityFilter", FilterValue: true, FilterType: null });
                        return filters;
                    }
                    selectedService(item) {
                        const priceField = this.parent.parent.getEditor("Price");
                        const extras = Sol.List.from(item.extraData);
                        priceField.value = extras.that(dt => dt.Campo == "PriceData").Valor;
                        priceField.onChange();
                        this.parent.parent.getEditor("Quantity").foco();
                    }
                }
                Selectors.ServiceGridSelector = ServiceGridSelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ServiceSelector", model => {
    var serviceSelector = new Sol.Web.Components.Selectors.ServiceGridSelector();
    serviceSelector.className = model.DataTypeFullName;
    return serviceSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class PurchasingXmlImportAction extends Actions.ActionBase {
                processResponse() { }
                doFormBasedAction() {
                    const purchasingScreen = this.parent.parent;
                    const file = this.screen.values;
                    const inputs = purchasingScreen.values;
                    Web.System.exec("79kt222yjh", "ImportFromXml", {
                        credential: Sol.Environment.credential.export(),
                        file: file,
                        inputs: inputs
                    }, e => {
                        if (e.Fail) {
                            this.screen.form.showError(e.ErrorMessage);
                            return;
                        }
                        purchasingScreen.loadData(e.PurchasingData);
                        Web.System.screens.closeCurrentScreen();
                        purchasingScreen.getLabel("Products").expanded = true;
                        purchasingScreen.getLabel("Payment").expanded = true;
                        purchasingScreen.getLabel("DeliveryDetails").expanded = true;
                    }, () => this.screen.form.workComplete());
                }
            }
            Actions.PurchasingXmlImportAction = PurchasingXmlImportAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class ProductRegistrationCreateRequestAction extends Actions.ActionBase {
                processResponse() {
                    var product = Web.System.screens.currentScreen.getEditor("Product");
                    Web.System.screens.openScreen("Registro", "Solarium.Commercial.PriceQuotation, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", null, null, null, screen => {
                        const quotationScreen = screen;
                        quotationScreen.onOpenScreen = () => {
                            quotationScreen.addNew();
                            quotationScreen.setFormField("Product", product.value);
                        };
                    });
                }
            }
            Actions.ProductRegistrationCreateRequestAction = ProductRegistrationCreateRequestAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Screens;
        (function (Screens) {
            class PurchasingItemViewScreen extends Screens.Registro {
            }
            Screens.PurchasingItemViewScreen = PurchasingItemViewScreen;
        })(Screens = Web.Screens || (Web.Screens = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class OpenScreenAction extends Actions.ActionBase {
                processResponse(data) {
                    const currentAnchorage = Web.System.screens.currentScreen.anchorage;
                    if (!data.KeepCurrentScreen)
                        Web.System.screens.closeCurrentScreen();
                    Web.System.screens.openScreen(data.Screen, data.ClassName, null, null, null, screen => {
                        if (!(screen instanceof Web.Screens.Registro))
                            return;
                        const newScreen = screen;
                        if (data.KeepAnchorage)
                            newScreen.anchorage = currentAnchorage;
                        setTimeout(() => newScreen.setFilters(data.Filters), 500);
                    });
                }
            }
            Actions.OpenScreenAction = OpenScreenAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Actions;
        (function (Actions) {
            class EditItemAction extends Actions.ActionBase {
                processResponse(data) {
                    if (data.CloseCurrentScreen)
                        Web.System.screens.closeCurrentScreen();
                    Web.System.edit(data.TypeHash.toString(), data.Code);
                }
            }
            Actions.EditItemAction = EditItemAction;
        })(Actions = Web.Actions || (Web.Actions = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class MonthTotalizer extends Sol.CurrencyField {
                get grid() { return this.container.getEditor("Months"); }
                constructor() {
                    super();
                    this.decimals = 4;
                    this.onValueModified.subscribe(() => this.calculateTotal());
                    this.onSet.subscribe(() => this.calculateTotal());
                }
                build() {
                    super.build();
                    this.grid.onInstantiateRow = row => {
                        const quantityField = row.getEditor("Quantity");
                        quantityField.onValueModified.subscribe(() => this.calculateTotal());
                        if (quantityField.html)
                            quantityField.registerEvents();
                    };
                }
                calculateTotal() {
                    const totalField = this.container.getEditor("Total");
                    totalField.numericValue = (this.numericValue * this.grid.sum("Quantity")) || this.numericValue;
                }
            }
            Components.MonthTotalizer = MonthTotalizer;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class IntegrationItem extends Sol.Control {
                constructor(model, code) {
                    super();
                    this.sendButton = new Sol.Button();
                    this.syncButton = new Sol.Button();
                    this.validateButton = new Sol.Button();
                    this.deleteButton = new Sol.Button();
                    this.viewButton = new Sol.Button();
                    this.lastUpdateField = new Sol.Control();
                    this.lastValidateField = new Sol.Control();
                    this.resultDisplay = new Sol.Control();
                    this.mainWrapper = new Sol.Control();
                    this.buttonWrapper = new Sol.Control();
                    this.model = model;
                    this.code = code;
                    this.css.add("sol_integration_item");
                    this.addCtr(null, null, "img").atributos.agregar("src", Sol.Environment.systemUrl + "/picture/" + model.Logo);
                    this.addCtr(model.IntegrationName, "sol_integration_item_name");
                    this.buttonWrapper.add(this.resultDisplay);
                    this.buttonWrapper.css.add("sol_integration_button_wrapper");
                    if (model.AllowSend) {
                        this.sendButton.type = Sol.ButtonType.Link;
                        this.sendButton.imageCode = "&#xf061;";
                        this.sendButton.text = Sol.Environment.resources.enviar;
                        this.sendButton.onClick = () => this.send();
                        this.buttonWrapper.add(this.sendButton);
                    }
                    if (model.AllowSync) {
                        this.syncButton.type = Sol.ButtonType.Link;
                        this.syncButton.imageCode = "&#xf021;";
                        this.syncButton.text = model.SyncCaption;
                        this.syncButton.onClick = () => this.sync();
                        this.buttonWrapper.add(this.syncButton);
                    }
                    if (model.AllowValidate) {
                        this.validateButton.type = Sol.ButtonType.Link;
                        this.validateButton.imageCode = "&#xf046;";
                        this.validateButton.text = Sol.Environment.resources.validate;
                        this.validateButton.onClick = () => this.validate();
                        this.buttonWrapper.add(this.validateButton);
                    }
                    if (model.AllowView) {
                        this.viewButton.type = Sol.ButtonType.Link;
                        this.viewButton.imageCode = "&#xf06e;";
                        this.viewButton.text = Sol.Environment.resources.view;
                        this.viewButton.onClick = () => this.view();
                        this.buttonWrapper.add(this.viewButton);
                    }
                    if (model.AllowDelete) {
                        this.deleteButton.type = Sol.ButtonType.Link;
                        this.deleteButton.imageCode = "&#xf1f8;";
                        this.deleteButton.text = Sol.Environment.resources.delete;
                        this.deleteButton.onClick = () => this.delete();
                        this.buttonWrapper.add(this.deleteButton);
                    }
                    this.buttonWrapper.add(new Sol.LineBreak());
                    this.mainWrapper.add(this.buttonWrapper);
                    this.lastUpdateField.text = Sol.Environment.resources.lastUpdate + ": " + (model.LastUpdate || "Não possui envio concluído sem erros.");
                    this.lastUpdateField.css.add("sol_integration_date_wrapper");
                    this.mainWrapper.add(this.lastUpdateField);
                    if (model.ShowLastValidate) {
                        this.lastValidateField.text = Sol.Environment.resources.lastValidation + ": " + (model.LastValidation || "Não possui validação concluída sem erros.");
                        this.lastValidateField.css.add("sol_integration_date_wrapper");
                        this.mainWrapper.add(this.lastValidateField);
                    }
                    if (model.EnableAutoValidation)
                        Web.System.screens.currentDetails.onLocalSaved.subscribe(() => this.validate());
                    this.mainWrapper.css.add("sol_integration_main_wrapper");
                    this.add(this.mainWrapper);
                }
                disableButtons() {
                    this.sendButton.enabled = false;
                    this.syncButton.enabled = false;
                    this.validateButton.enabled = false;
                    this.viewButton.enabled = false;
                    this.deleteButton.enabled = false;
                    this.resultDisplay.text = "";
                    this.resultDisplay.css.empty();
                }
                enableButtons() {
                    this.sendButton.enabled = true;
                    this.syncButton.enabled = true;
                    this.validateButton.enabled = true;
                    this.viewButton.enabled = true;
                    this.deleteButton.enabled = true;
                }
                send() {
                    if (!this.checkIfFormIsSaved())
                        return;
                    this.disableButtons();
                    this.sendButton.css.add("sol_integration_item_button_loading");
                    const requestData = { integrationClass: this.model.IntegrationClass, code: this.code };
                    Web.System.exec("pql45me32", "SendObject", requestData, e => {
                        this.resultDisplay.htmlContent = e.ErrorMessage || "Enviado com sucesso";
                        this.resultDisplay.css.add(e.Fail ? "sol_integration_item_error" : "sol_integration_item_success");
                        if (!e.Fail)
                            this.lastUpdateField.text = e.Date;
                        this.sendButton.css.remove("sol_integration_item_button_loading");
                        this.enableButtons();
                    });
                }
                sync() {
                    if (!this.checkIfFormIsSaved())
                        return;
                    this.disableButtons();
                    this.syncButton.css.add("sol_integration_item_button_loading");
                    const requestData = { integrationClass: this.model.IntegrationClass, code: this.code };
                    Web.System.exec("pql45me32", "SyncObject", requestData, e => {
                        this.resultDisplay.htmlContent = e.ErrorMessage || "Atualizado com sucesso";
                        this.resultDisplay.css.add(e.Fail ? "sol_integration_item_error" : "sol_integration_item_success");
                        if (!e.Fail) {
                            this.lastUpdateField.text = e.Date;
                            Web.System.screens.currentScreen.reload();
                        }
                        this.syncButton.css.remove("sol_integration_item_button_loading");
                        this.enableButtons();
                    });
                }
                validate() {
                    if (!this.checkIfFormIsSaved())
                        return;
                    this.disableButtons();
                    this.validateButton.css.add("sol_integration_item_button_loading");
                    const requestData = { integrationClass: this.model.IntegrationClass, code: this.code };
                    Web.System.exec("pql45me32", "ValidateObject", requestData, e => {
                        this.resultDisplay.htmlContent = e.ErrorMessage || "Validado com sucesso";
                        this.resultDisplay.css.add(e.Fail ? "sol_integration_item_error" : "sol_integration_item_success");
                        if (!e.Fail)
                            this.lastValidateField.text = e.Date;
                        this.validateButton.css.remove("sol_integration_item_button_loading");
                        this.enableButtons();
                    });
                }
                view() {
                    this.disableButtons();
                    this.validateButton.css.add("sol_integration_item_button_loading");
                    const requestData = { integrationClass: this.model.IntegrationClass, code: this.code };
                    Web.System.exec("pql45me32", "ViewObject", requestData, e => {
                        if (!e.Fail)
                            window.open(e.FileLink, "_blank");
                        this.resultDisplay.text = e.Fail ? e.ErrorMessage : null;
                        this.resultDisplay.css.add(e.Fail ? "sol_integration_item_error" : "sol_integration_item_success");
                        this.validateButton.css.remove("sol_integration_item_button_loading");
                        this.enableButtons();
                    });
                }
                delete() {
                    this.disableButtons();
                    this.validateButton.css.add("sol_integration_item_button_loading");
                    const requestData = { integrationClass: this.model.IntegrationClass, code: this.code };
                    Web.System.exec("pql45me32", "DeleteObject", requestData, e => {
                        this.resultDisplay.htmlContent = e.ErrorMessage || "Excluído com sucesso";
                        this.resultDisplay.css.add(e.Fail ? "sol_integration_item_error" : "sol_integration_item_success");
                        if (!e.Fail)
                            this.lastUpdateField.text = null;
                        this.validateButton.css.remove("sol_integration_item_button_loading");
                        this.enableButtons();
                    });
                }
                checkIfFormIsSaved() {
                    const detailsScreen = Web.System.screens.getMyDetails(this);
                    if (detailsScreen.isChanged) {
                        this.resultDisplay.text = "Por favor, salve as alterações antes de continuar.";
                        this.resultDisplay.css.add("sol_integration_item_error");
                    }
                    return !detailsScreen.isChanged;
                }
            }
            Components.IntegrationItem = IntegrationItem;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class IntegrationsEditor extends Sol.Control {
                constructor() {
                    super(...arguments);
                    this.isComplex = true;
                    this.readonly = true;
                }
                clear() { }
                foco() { }
                isEmpty() { return false; }
                toControl() { return this; }
                validate() { return null; }
                build() {
                    super.build();
                    this.refreshList();
                }
                refreshList() {
                    const requestData = { className: this.className, code: this.code };
                    Web.System.exec("pql45me32", "ListObjectIntegrations", requestData, e => this.addMany(Sol.List.from(e).where(i => !!i).select(i => new Components.IntegrationItem(i, this.code))));
                }
            }
            Components.IntegrationsEditor = IntegrationsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var PricesRegistration;
            (function (PricesRegistration) {
                class ARPParticipantCombo extends Components.DataCombo {
                    constructor() {
                        super();
                        this.className = "Solarium.Government.ARP.ARPParticipant, Solarium.Government.ARP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                        this.displayProperty = "DisplayName";
                        this.valueProperty = "ID";
                        this.onBeforeRefresh = () => this.setARPFilter();
                    }
                    setARPFilter() {
                        this.filters.add({
                            FilterType: "SInteger",
                            PropertyName: "ARP",
                            FilterValue: Web.System.screens.currentDetails.code
                        });
                    }
                }
                PricesRegistration.ARPParticipantCombo = ARPParticipantCombo;
            })(PricesRegistration = Components.PricesRegistration || (Components.PricesRegistration = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ARPParticipantCombo", () => new Sol.Web.Components.PricesRegistration.ARPParticipantCombo());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class WinnerItemsCheck extends Sol.Control {
                constructor() {
                    super("th");
                    this.check = new Sol.Check();
                    this.css.add("sol_lic_winners_center");
                    this.check.checked = true;
                    this.add(this.check);
                }
                get checked() { return this.check.checked; }
                set checked(value) { this.check.checked = value; }
                get onChange() { return this.check.onChange; }
                set onChange(value) { this.check.onChange = value; }
            }
            Licitations.WinnerItemsCheck = WinnerItemsCheck;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class WinnerItemsTableItem extends Sol.Control {
                constructor(item, isARP) {
                    super("tr");
                    this.check = new Licitations.WinnerItemsCheck();
                    this.code = item.Code;
                    this.selectable = !item.ContractInfo;
                    if (item.ContractInfo)
                        this.addCtr(null, null, "td");
                    else
                        this.add(this.check);
                    this.addCtr(item.Batch.toString(), "sol_lic_winners_center", "td");
                    this.addCtr(item.Item.toString(), "sol_lic_winners_center", "td");
                    this.addCtr(item.Description, null, "td");
                    this.addCtr(item.Brand, null, "td");
                    this.addCtr(item.ItemModel, null, "td");
                    this.addCtr(item.Quantity, "sol_lic_winners_center", "td");
                    this.addCtr(item.Price, "sol_lic_winners_right", "td");
                    this.addCtr(item.ReferencePrice, "sol_lic_winners_right", "td");
                    this.addCtr(item.Total, "sol_lic_winners_right", "td");
                    this.addCtr(item.SavingPercent, "sol_lic_winners_right", "td");
                    let cell = this.addCtr(null, null, "td");
                    if (item.ContractInfo) {
                        let contractButton = new Sol.Button();
                        contractButton.text = item.ContractInfo.Description;
                        contractButton.type = Sol.ButtonType.Link;
                        contractButton.onClick = () => Web.System.edit(isARP ?
                            "Solarium.Government.ARP.ARPContract, Solarium.Government.ARP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" :
                            "Solarium.Contracts.Contract, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", item.ContractInfo.Code);
                        cell.add(contractButton);
                    }
                }
                get checked() { return this.selectable && this.check.checked; }
                set checked(value) { this.check.checked = value; }
            }
            Licitations.WinnerItemsTableItem = WinnerItemsTableItem;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class WinnerItemsTable extends Sol.Control {
                get rows() {
                    return this.controls.where(ctr => ctr instanceof Licitations.WinnerItemsTableItem).cast();
                }
                get allSelected() { return this.rows.all(i => i.checked); }
                get selectedItems() { return this.rows.where(i => i.checked).select(i => i.code).toArray(); }
                constructor(items, isARP, showCheck) {
                    super("table");
                    this.css.add("sol_lic_winners");
                    this.visible = false;
                    let header = this.addCtr(null, null, "tr");
                    let check = new Licitations.WinnerItemsCheck();
                    check.onChange = () => this.rows.forEach(r => r.checked = check.checked);
                    if (showCheck)
                        header.add(check);
                    else
                        header.addCtr(null, null, "th");
                    header.addCtr("Lote", "sol_lic_winners_center", "th");
                    header.addCtr("Item", "sol_lic_winners_center", "th");
                    header.addCtr("Descrição", null, "th");
                    header.addCtr("Marca", null, "th");
                    header.addCtr("Modelo", null, "th");
                    header.addCtr("Quantidade", "sol_lic_winners_center", "th");
                    header.addCtr("Valor", "sol_lic_winners_right", "th");
                    header.addCtr("Valor Ref.", "sol_lic_winners_right", "th");
                    header.addCtr("Total", "sol_lic_winners_right", "th");
                    header.addCtr("Deságio", "sol_lic_winners_right", "th");
                    header.addCtr("Contrato", null, "th");
                    this.addMany(Sol.List.from(items).select(i => new Licitations.WinnerItemsTableItem(i, isARP)));
                }
            }
            Licitations.WinnerItemsTable = WinnerItemsTable;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class WinnersListEditor extends Sol.Control {
                constructor() {
                    super("ul");
                    this.refreshable = true;
                    this.css.add("sol_lic_winners");
                }
                refresh() {
                    Web.System.exec("Ne766XWp9", "GetWinners", { licitationID: this.code }, e => {
                        this.controls.empty();
                        this.addMany(Sol.List.from(e.Winners).select(m => {
                            let showCheck = Sol.List.from(m.Items).any(i => !i.ContractInfo);
                            let modelID = m.ContractID;
                            let loanModelID = m.LoanContractID;
                            const item = new Sol.Control("li");
                            item.addCtr("Total: " + m.Total, "sol_lic_winners_title_right", "span");
                            const companyLabel = new Sol.ExpandoLabel();
                            companyLabel.caption = m.ParticipantName;
                            companyLabel.css.add("sol_lic_winners_title");
                            item.add(companyLabel);
                            item.addCtr("Qtd. Itens: " + m.ItemCount.toString(), "sol_lic_winners_float_right", "span");
                            item.addCtr(m.ParticipantTaxID, "", "span");
                            item.add(new Sol.LineBreak());
                            item.addCtr("Deságio: " + m.SavingPercent, "sol_lic_winners_float_right", "span");
                            item.addCtr(m.ParticipantCity, "", "span");
                            item.add(new Sol.LineBreak());
                            const table = new Licitations.WinnerItemsTable(m.Items, m.IsARP, showCheck);
                            companyLabel.associatedControl = table;
                            companyLabel.expanded = true;
                            item.add(table);
                            const sucessMessage = new Sol.ScreenMessage();
                            sucessMessage.type = Sol.MessageType.Success;
                            sucessMessage.caption = m.IsARP ? "Ata de Registro de Preço cadastrada com sucesso." : "Contrato cadastrado com sucesso.";
                            sucessMessage.visible = false;
                            item.add(sucessMessage);
                            const failMessage = new Sol.ScreenMessage();
                            failMessage.visible = false;
                            item.add(failMessage);
                            if (showCheck) {
                                const createContractButton = new Sol.Button();
                                createContractButton.text = m.IsARP ? "Cadastrar Ata" : "Cadastrar contrato";
                                createContractButton.onClick = () => {
                                    sucessMessage.visible = false;
                                    failMessage.visible = false;
                                    let allSelected = table.allSelected;
                                    let data = {
                                        licitationID: this.code,
                                        participantID: m.ParticipantID,
                                        allSelected: allSelected,
                                        itemList: allSelected ? null : table.selectedItems
                                    };
                                    Web.System.exec(m.IsARP ? "vaslarmor" : "vvasleos", m.IsARP ? "CreateARPFromLicitationWinner" : "CreateContractFromLicitationWinner", data, model => {
                                        modelID = model.ID;
                                        sucessMessage.visible = !model.Fail;
                                        failMessage.visible = model.Fail;
                                        failMessage.caption = model.ErrorMessage;
                                        this.refresh();
                                    });
                                };
                                item.add(createContractButton);
                            }
                            const sucessLoanMessage = new Sol.ScreenMessage;
                            sucessLoanMessage.type = Sol.MessageType.Success;
                            sucessLoanMessage.caption = "Contrato de comodato cadastrado com sucesso.";
                            sucessLoanMessage.visible = false;
                            item.add(sucessLoanMessage);
                            const failLoanMessage = new Sol.ScreenMessage;
                            failLoanMessage.visible = false;
                            item.add(failLoanMessage);
                            const createLoanContractButton = new Sol.Button();
                            const openLoanContractButton = new Sol.Button();
                            createLoanContractButton.text = "Cadastrar contrato de comodato";
                            createLoanContractButton.onClick = () => {
                                sucessLoanMessage.visible = false;
                                failLoanMessage.visible = false;
                                Web.System.exec("vvasleos", "CreateLoanContractFromLicitationWinner", { licitationID: this.code, participantID: m.ParticipantID }, model => {
                                    loanModelID = model.ID;
                                    sucessLoanMessage.visible = !model.Fail;
                                    failLoanMessage.visible = model.Fail;
                                    failLoanMessage.caption = model.ErrorMessage;
                                    openLoanContractButton.visible = !model.Fail;
                                    if (!model.Fail)
                                        Web.System.edit("Solarium.Contracts.Contract, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", loanModelID);
                                });
                            };
                            item.add(createLoanContractButton);
                            openLoanContractButton.text = "Abrir contrato de comodato";
                            openLoanContractButton.visible = !!loanModelID;
                            openLoanContractButton.onClick = () => {
                                sucessLoanMessage.visible = false;
                                failLoanMessage.visible = false;
                                Web.System.edit("Solarium.Contracts.Contract, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", loanModelID);
                            };
                            item.add(openLoanContractButton);
                            return item;
                        }));
                    });
                }
                clear() { }
                foco() { }
                isEmpty() { return true; }
                toControl() { return this; }
                validate() { return null; }
            }
            Licitations.WinnersListEditor = WinnersListEditor;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class LegislationSelector extends Web.Components.DataCombo {
                constructor() {
                    super();
                    this.inForceFilter = { PropertyName: "IsInForce", FilterType: "SBoolean", FilterValue: true };
                    this.onBeforeRefresh = () => this.setTypeFilter();
                    this.onSet.subscribe(() => this.setLawFilter());
                    this.onValueModified.subscribe(() => {
                        var _a, _b;
                        this.setLawFilter();
                        (_a = this.legalCodeCombo) === null || _a === void 0 ? void 0 : _a.clear();
                        (_b = this.legalCodeCombo) === null || _b === void 0 ? void 0 : _b.refresh();
                    });
                    this.preFilters = [this.inForceFilter];
                }
                get legalCodeCombo() { return this.container.getEditor("LegalCode"); }
                build() {
                    super.build();
                    this.configTypeBehaviour();
                }
                configTypeBehaviour() {
                    let typeCombo = this.container.getEditor("Type");
                    if (!typeCombo)
                        return;
                    typeCombo.onValueModified.subscribe(() => this.refresh());
                }
                setTypeFilter() {
                    if (!this.container)
                        return;
                    let typeCombo = this.container.getEditor("Type");
                    if (!typeCombo)
                        return;
                    this.curModality = parseInt(typeCombo.selectedCode);
                    this.setFilter({ PropertyName: "ModalityFilter", FilterType: "SInteger", FilterValue: this.curModality });
                }
                setLawFilter() {
                    if (!this.container)
                        return;
                    let selectedCode = parseInt(this.selectedCode);
                    if (!this.legalCodeCombo || !selectedCode)
                        return;
                    this.legalCodeCombo.setFilter({ PropertyName: "Legislation", FilterType: "SInteger", FilterValue: selectedCode });
                    this.legalCodeCombo.setFilter({ PropertyName: "ModalityFilter", FilterType: "SInteger", FilterValue: this.curModality });
                }
            }
            Licitations.LegislationSelector = LegislationSelector;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("LegislationSelector", model => {
    let selector = new Sol.Web.Licitations.LegislationSelector();
    selector.className = model.DataTypeFullName;
    return selector;
});
Sol.Web.Editors.registerFilter("LegislationSelector", model => {
    let selector = new Sol.Web.Licitations.LegislationSelector();
    selector.className = model.ClassName;
    selector.refresh();
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class LicitationDatesCalculator extends Web.Components.CalculableDateField {
                constructor() {
                    super();
                    this.ancho = 209;
                    this.mainField.ancho = 155;
                    this.calcButton.tip = "Calcula as próximas datas automaticamente";
                    this.calcButton.onClick = () => this.calcDates();
                }
                calcDates() {
                    if (this.mainField.isEmpty()) {
                        alert("Favor, preencher um data e hora inicíal para calcular as demais datas");
                        return;
                    }
                    ;
                    const screen = Web.System.screens.screens.that(sc => sc instanceof Web.Screens.DetailsScreen);
                    const request = {
                        initialDate: this.mainField.value,
                        legislationID: parseInt(screen.getEditor("LicitationLegislation").selectedCode),
                        licitationMode: parseInt(screen.getEditor("Type").selectedCode),
                        licitationObjetc: parseInt(screen.getEditor("LicitationObject").selectedCode),
                        specialEngineeringServices: Web.System.screens.currentDetails.getEditor("LAdditionalData").getEditor("SpecialEngineeringServices").value,
                        execution: parseInt(screen.getEditor("ExecutionSystem").selectedCode)
                    };
                    const starHour = this.container.getEditor("ProposalStartHour").value;
                    this.container.getEditor("ObjectionDeadlineTime").value = starHour;
                    this.container.getEditor("ProposalEndHour").value = starHour;
                    this.container.getEditor("BidsStartHour").value = starHour;
                    this.container.getEditor("BidsEndHour").value = starHour;
                    this.container.getEditor("ProposalOpeningHour").value = starHour;
                    this.container.getEditor("DeadlineClarificationHour").value = starHour;
                    Web.System.exec("spoe34skdeo", "SuggestLicitationDates", request, e => {
                        if (!e)
                            return;
                        this.container.getEditor("ObjectionDeadlineDate").value = e.ObjectionDeadlineDate;
                        this.container.getEditor("ProposalEndDate").value = e.ProposalEndDate;
                        this.container.getEditor("ProposalOpeningDate").value = e.ProposalOpeningDate;
                        this.container.getEditor("DeadlineClarificationDate").value = e.DeadlineClarificationDate;
                        this.container.getEditor("BidsStartDate").value = e.BidsStartDate;
                        this.container.getEditor("BidsEndDate").value = e.BidsEndDate;
                        if (e.ObjectionDeadlineTime)
                            this.container.getEditor("ObjectionDeadlineTime").value = e.ObjectionDeadlineTime;
                        if (e.ProposalEndHour)
                            this.container.getEditor("ProposalEndHour").value = e.ProposalEndHour;
                        if (e.BidsStartHour)
                            this.container.getEditor("BidsStartHour").value = e.BidsStartHour;
                        if (e.BidsEndHour)
                            this.container.getEditor("BidsEndHour").value = e.BidsEndHour;
                        if (e.ProposalOpeningHour)
                            this.container.getEditor("ProposalOpeningHour").value = e.ProposalOpeningHour;
                        if (e.DeadlineClarificationHour)
                            this.container.getEditor("DeadlineClarificationHour").value = e.DeadlineClarificationHour;
                    });
                }
                ;
            }
            Licitations.LicitationDatesCalculator = LicitationDatesCalculator;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class DecimalsField extends Sol.IntegerField {
                constructor() {
                    super();
                    this.onSet.subscribe(() => this.updateFields());
                    this.onValueModified.subscribe(() => this.updateFields());
                }
                updateFields() {
                    const estimateField = Web.System.screens.currentDetails.getEditor("EstimateValue");
                    if (!estimateField)
                        return;
                    estimateField.decimals = this.numericValue;
                }
            }
            Licitations.DecimalsField = DecimalsField;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class ParticipantCombo extends Web.Components.DataCombo {
                constructor() {
                    super();
                    this.className = "Solarium.Government.Licitations.LicitationParticipant, Solarium.Government.Licitations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.displayProperty = "Participant$EntidadRelacionada$Nombre";
                    this.valueProperty = "Participant$ID";
                    this.onBeforeRefresh = () => this.setLicitationFilter();
                }
                setLicitationFilter() {
                    this.filters.add({
                        FilterType: "SInteger",
                        PropertyName: "Licitation",
                        FilterValue: Web.System.screens.currentDetails.code
                    });
                }
            }
            Licitations.ParticipantCombo = ParticipantCombo;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ParticipantCombo", () => new Sol.Web.Licitations.ParticipantCombo());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class PricesRegistrationOrderEditor extends Web.Components.DataView {
                get unitSelector() { return this.container.getEditor("UnitSelector"); }
                constructor() {
                    super();
                    this.allowNew = false;
                    this.allowDelete = false;
                    this.footer.visible = false;
                    this.showSearchBox = false;
                    this.fixedRows = false;
                    this.showChecks = false;
                }
                instantiateRow(row) {
                    const reqQuantityField = row.getEditor("RequestedQuantity");
                    const quantityField = row.getEditor("Quantity");
                    reqQuantityField.unitBlocked = true;
                    quantityField.unitBlocked = true;
                    quantityField.value = reqQuantityField.value;
                    quantityField.numericValue = 0;
                }
                loadItems() {
                    if (!this.unitSelector)
                        return;
                    if (this.unitSelector.isEmpty())
                        this.grid.clear();
                    else {
                        const screen = Web.System.screens.currentDetails;
                        const data = {
                            pricesRegistrationID: screen.code,
                            unitID: this.unitSelector.selectedCode
                        };
                        Web.System.exec("galwos34", "GetUnitData", data, model => {
                            const items = Sol.List.from(model.Items);
                            const responseData = items.select(rec => {
                                const recList = new Sol.List();
                                recList.add({ Campo: "ItemCode", Valor: rec.Code });
                                recList.add({ Campo: "ItemDescription", Valor: rec.Name });
                                recList.add({ Campo: "Category", Valor: rec.Category });
                                recList.add({ Campo: "Department", Valor: rec.Department });
                                recList.add({ Campo: "RequestedQuantity", Valor: rec.RequestedQuantity });
                                recList.add({ Campo: "QuantityBalance", Valor: rec.AvailableQuantity });
                                recList.add({ Campo: "ItemID", Valor: rec.ItemID });
                                return recList.toArray();
                            }).toArray();
                            const gridResponse = {
                                Data: responseData,
                                ResultCount: responseData.length,
                                PageCount: 1,
                                Codes: items.select(i => 0).toArray(),
                                Formats: items.select(i => ({})).toArray(),
                                ModeloDato: null,
                                TotalInfo: null,
                                Fail: false,
                                ErrorMessage: null,
                                Columns: null
                            };
                            this.grid.loadData(gridResponse);
                        });
                    }
                }
                build() {
                    super.build();
                    if (!this.unitSelector)
                        return;
                    this.onInstantiateRow = row => this.instantiateRow(row);
                    this.unitSelector.onValueModified.subscribe(() => this.loadItems());
                    this.unitSelector.onSet.subscribe(() => this.loadItems());
                }
                getValor() {
                    return this.rows.select(row => {
                        const rowData = row.controls
                            .where(cl => cl.controls.hasItems() && cl.controls.item(0).propertyName)
                            .select(cl => {
                            var vEditor = cl.controls.item(0);
                            return { Campo: vEditor.propertyName, Valor: vEditor.value };
                        })
                            .union([{ Campo: "ID", Valor: row.code }, { Campo: "Item", Valor: row.getDataByPropertyName("ItemID") }]);
                        return rowData.toArray();
                    })
                        .toArray();
                }
            }
            Licitations.PricesRegistrationOrderEditor = PricesRegistrationOrderEditor;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PricesRegistrationOrderEditor", (model, ctx, code) => {
    const editor = new Sol.Web.Licitations.PricesRegistrationOrderEditor();
    editor.readonly = model.ReadOnly;
    Sol.Web.Editors.fillDataViewStructure(editor, model.Structure);
    return editor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            let LicitationType;
            (function (LicitationType) {
                LicitationType[LicitationType["pregaoEletronico"] = 1] = "pregaoEletronico";
                LicitationType[LicitationType["pregaoPresencial"] = 2] = "pregaoPresencial";
                LicitationType[LicitationType["pregaoLeiEletronico"] = 3] = "pregaoLeiEletronico";
                LicitationType[LicitationType["pregaoLeiPresencial"] = 4] = "pregaoLeiPresencial";
                LicitationType[LicitationType["adesaoAtaRegistroPrecos"] = 5] = "adesaoAtaRegistroPrecos";
                LicitationType[LicitationType["registroPrecosE"] = 6] = "registroPrecosE";
                LicitationType[LicitationType["registroPrecosP"] = 7] = "registroPrecosP";
                LicitationType[LicitationType["dispensaPresencial"] = 8] = "dispensaPresencial";
                LicitationType[LicitationType["dispensaEletronica"] = 9] = "dispensaEletronica";
                LicitationType[LicitationType["cotacao"] = 10] = "cotacao";
                LicitationType[LicitationType["regimeDiferenciadoCE"] = 11] = "regimeDiferenciadoCE";
                LicitationType[LicitationType["regimeDiferenciadoCP"] = 12] = "regimeDiferenciadoCP";
                LicitationType[LicitationType["concorrenciaLeiPresencial"] = 13] = "concorrenciaLeiPresencial";
                LicitationType[LicitationType["concorrenciaLeiEletronica"] = 14] = "concorrenciaLeiEletronica";
                LicitationType[LicitationType["concorrencia"] = 15] = "concorrencia";
                LicitationType[LicitationType["leilaoEletronico"] = 16] = "leilaoEletronico";
                LicitationType[LicitationType["leilaoPresencial"] = 17] = "leilaoPresencial";
                LicitationType[LicitationType["chamadaPublicaPNAE"] = 18] = "chamadaPublicaPNAE";
                LicitationType[LicitationType["chamamentoPublico"] = 19] = "chamamentoPublico";
                LicitationType[LicitationType["chamamentoPublicoC"] = 20] = "chamamentoPublicoC";
                LicitationType[LicitationType["concurso"] = 21] = "concurso";
                LicitationType[LicitationType["convite"] = 22] = "convite";
                LicitationType[LicitationType["lei13303Eletronico"] = 23] = "lei13303Eletronico";
                LicitationType[LicitationType["lei13303Presencial"] = 24] = "lei13303Presencial";
                LicitationType[LicitationType["manifestacaoInteresse"] = 25] = "manifestacaoInteresse";
                LicitationType[LicitationType["inexigibilidade"] = 26] = "inexigibilidade";
                LicitationType[LicitationType["regrasInternacionais"] = 27] = "regrasInternacionais";
                LicitationType[LicitationType["tomadaPrecos"] = 28] = "tomadaPrecos";
            })(LicitationType = Licitations.LicitationType || (Licitations.LicitationType = {}));
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class ManagerEntityDetails extends Web.Components.DetailsEditor {
                build() {
                    this.licType = Web.System.screens.currentDetails.getEditor("Type");
                    this.additionalData = Web.System.screens.currentDetails.getEditor("LAdditionalData");
                    this.ownBid = this.additionalData.getEditor("OrganOwnBid");
                    this.licType.onValueModified.subscribe(() => this.setMyVisibility());
                    this.licType.onSet.subscribe(() => this.setMyVisibility());
                    this.ownBid.onValueModified.subscribe(() => this.setMyVisibility());
                    this.ownBid.onSet.subscribe(() => this.setMyVisibility());
                    super.build();
                }
                setMyVisibility() {
                    this.visible = !this.ownBid.value || this.licType.value.Valor == Licitations.LicitationType.adesaoAtaRegistroPrecos;
                    this.myLabel.visible = !this.ownBid.value || this.licType.value.Valor == Licitations.LicitationType.adesaoAtaRegistroPrecos;
                }
            }
            Licitations.ManagerEntityDetails = ManagerEntityDetails;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ManagerEntityDetails", model => {
    var detailsEditor = new Sol.Web.Licitations.ManagerEntityDetails;
    detailsEditor.model = model.ScreenModel;
    return detailsEditor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class INotifyIRPMessagePreviewModel {
            }
            Government.INotifyIRPMessagePreviewModel = INotifyIRPMessagePreviewModel;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class NotifyIRPMessagePreview extends Web.Components.HtmlEditor {
                constructor() {
                    super();
                    this.readonly = true;
                }
                build() {
                    super.build();
                    this.getPreview();
                }
                getPreview() {
                    const data = { pricesRegistrationID: this.pricesRegistrationID };
                    Web.System.exec("jjhnkmlkld", "GetIRPMessagePreview", data, e => this.value = e.HtmlPreview);
                }
            }
            Government.NotifyIRPMessagePreview = NotifyIRPMessagePreview;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("NotifyIRPMessagePreview", (model, className, code) => {
    const editor = new Sol.Web.Government.NotifyIRPMessagePreview();
    editor.pricesRegistrationID = code;
    return editor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class ProposalItemSelector extends Web.Components.DualCombo {
                constructor() {
                    super();
                    const screen = Web.System.screens.screens.that(scr => scr instanceof Web.Screens.DetailsScreen);
                    this.mainCombo.filters.add({
                        FilterType: "SInteger",
                        PropertyName: "Licitation",
                        FilterValue: screen.code
                    });
                    this.onSet.subscribe(() => this.checkItemType());
                    this.onValueModified.subscribe(() => this.checkItemType());
                    this.onMainComboLoaded.subscribe(() => this.checkItemType());
                }
                checkItemType() {
                    var _a;
                    var detailsScreen = this.parent;
                    let itemID = (_a = this.subCombo.selectedCode) !== null && _a !== void 0 ? _a : detailsScreen.getEditor("Item").value;
                    Web.System.exec("spoe34skdeo", "GetProposalItemType", { itemID: itemID }, model => {
                        detailsScreen.getEditor("ItemModel").readonly = model.ItemType == 2;
                        detailsScreen.getEditor("Brand").readonly = model.ItemType == 2;
                        if (!model.QuantityModel)
                            return;
                        let quantityField = detailsScreen.getEditor("Quantity");
                        quantityField.value = model.QuantityModel;
                    });
                }
            }
            Licitations.ProposalItemSelector = ProposalItemSelector;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ProposalItemSelector", model => {
    const itemSelector = new Sol.Web.Licitations.ProposalItemSelector();
    itemSelector.subClassName = model.DataTypeFullName;
    return itemSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Licitations;
        (function (Licitations) {
            class LicitaconDisplay extends Sol.ObjectDisplay {
                constructor() {
                    super();
                    this.css.add("sol_licitacon_display");
                }
                build() {
                    super.build();
                    this.showAsField = true;
                    this.onClick = () => this.showPopup();
                    setTimeout(() => this.refresh(), 2000);
                    Web.System.screens.currentDetails.onLocalSaved.subscribe(() => this.refresh());
                }
                setValue(v) {
                    if (!v)
                        return;
                    super.setValue(v);
                }
                refresh() {
                    this.setValue({ Campo: "Atualizando...", Valor: -1, Color: "#cfcfcf" });
                    Web.System.exec("te71BifO61", this.method, { objectID: this.objectCode }, e => {
                        if (!e.Fail)
                            this.setValue({ Campo: "Apto para envio", Valor: 2, Color: "#92cc85" });
                        else {
                            this.errors = e.ErrorList;
                            this.setValue({ Campo: "Pendências encontradas", Valor: 1, Color: "#fb4323" });
                        }
                    });
                }
                showPopup() {
                    let popup = new Sol.Popup();
                    let list = new Web.Components.ListView();
                    list.configuration = Sol.List.from([
                        { property: "ErrorNumber", cssClass: "sol_licitacon_display_code" },
                        { property: "ErrorMessage" }
                    ]);
                    list.addObjectItems(this.errors);
                    popup.add(list);
                    this.add(popup);
                    popup.show();
                }
            }
            Licitations.LicitaconDisplay = LicitaconDisplay;
        })(Licitations = Web.Licitations || (Web.Licitations = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("LicitaconDisplay", (model, cl, code) => {
    let display = new Sol.Web.Licitations.LicitaconDisplay();
    display.objectCode = code;
    return display;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class RelatedProductsEditor extends Sol.Control {
                constructor() {
                    super();
                    this.list = new Components.ListView();
                    this.isComplex = true;
                    this.css.add("sol_products_editor");
                    this.initializeList();
                    this.initializeAddButton();
                }
                get value() { return this.list.values; }
                set value(v) { this.list.values = v; }
                foco() { }
                toControl() { return this; }
                validate() { return null; }
                addProduct(code) {
                    let data = {
                        className: this.list.className,
                        currentPage: 1,
                        rowCount: 1,
                        filters: [{
                                PropertyName: "ID",
                                FilterValue: code,
                                FilterType: "SInteger"
                            }],
                        sortProperty: "ID",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "PartNumber", "Nombre", "Brand", "MainPicture"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        if (!model.Data || model.Data.length == 0)
                            return;
                        var product = Sol.List.from(model.Data[0]);
                        var item = [
                            { Campo: "Related", Valor: code },
                            { Campo: "Related$PartNumber", Valor: product.that(d => d.Campo == "PartNumber").Valor },
                            { Campo: "Related$Nombre", Valor: product.that(d => d.Campo == "Nombre").Valor },
                            { Campo: "Related$MainPicture", Valor: product.that(d => d.Campo == "MainPicture").Valor },
                            { Campo: "Related$Brand", Valor: product.that(d => d.Campo == "Brand").Valor }
                        ];
                        this.list.addItemFromData(item, 0);
                    });
                }
                initializeAddButton() {
                    var addButton = new Sol.Button();
                    addButton.text = Sol.Environment.resources.anadir_item;
                    addButton.imageCode = '&#xf187;';
                    addButton.onClick = () => {
                        var selectorScreen = new Web.Screens.ProductSelectorScreen();
                        Web.System.screens.addScreen(selectorScreen);
                        Web.System.screens.showScreen(selectorScreen);
                        selectorScreen.onProductSelected = prods => {
                            this.addProduct(prods.first().code);
                            Web.System.screens.closeCurrentScreen();
                        };
                    };
                    this.add(addButton);
                }
                initializeList() {
                    this.list.itemPropertyName = "Related";
                    this.list.showImage = true;
                    this.list.imageSize = 36;
                    this.list.className = "Solarium.Commercial.Product, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.list.orderByProperty = "ID";
                    this.list.onInstantiateItem = i => this.instantiateItem(i);
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: true,
                            property: "Related$MainPicture",
                            position: Components.ListViewFieldPosition.Image
                        },
                        {
                            loadable: true,
                            property: "Related",
                            hidden: true
                        },
                        {
                            loadable: false,
                            property: "DeleteCommand",
                            defaultText: Sol.Environment.resources.eliminar,
                            position: Components.ListViewFieldPosition.Right,
                            priority: Components.ListViewFieldPriority.Normal,
                            cssClass: "sol_products_list_remove"
                        },
                        {
                            loadable: true,
                            property: "Related$PartNumber",
                            priority: Components.ListViewFieldPriority.High,
                            position: Components.ListViewFieldPosition.Left,
                            cssClass: "sol_products_list_part_number"
                        },
                        {
                            loadable: true,
                            property: "Related$Nombre",
                            priority: Components.ListViewFieldPriority.High,
                            position: Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "Related$Brand",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            lineBreak: true
                        },
                        {
                            loadable: false,
                            property: "IsCompatible",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            editor: {
                                DataType: "SBoolean",
                                PropertyName: "IsCompatible",
                                Title: Sol.Environment.resources.is_compatible,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: false
                            }
                        },
                        {
                            loadable: false,
                            property: "IsSubstitute",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            editor: {
                                DataType: "SBoolean",
                                PropertyName: "IsSubstitute",
                                Title: Sol.Environment.resources.isSubstitute,
                                Required: false,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: false
                            }
                        }
                    ]);
                    this.add(this.list);
                }
                instantiateItem(item) {
                    var deleteCommand = item.getDisplay("DeleteCommand");
                    deleteCommand.onClick = () => this.list.removeItem(item);
                }
                isEmpty() { return false; }
                clear() { }
            }
            Components.RelatedProductsEditor = RelatedProductsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ProductComponentsEditor extends Sol.Control {
                constructor() {
                    super();
                    this.list = new Components.ListView();
                    this.isComplex = true;
                    this.css.add("sol_products_editor");
                    this.initializeList();
                    this.initializeAddButton();
                }
                get value() { return this.list.values; }
                set value(v) { this.list.values = v; }
                foco() { }
                toControl() { return this; }
                validate() { return null; }
                addProduct(code) {
                    var data = {
                        className: this.list.className,
                        currentPage: 1,
                        rowCount: 1,
                        filters: [{
                                PropertyName: "ID",
                                FilterValue: code,
                                FilterType: "SInteger"
                            }],
                        sortProperty: "ID",
                        sortOrder: Web.Ordering.ascending,
                        properties: ["ID", "Nombre", "Brand", "MainPicture", "EffectivePriceData"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", data, model => {
                        if (!model.Data || model.Data.length == 0)
                            return;
                        var product = Sol.List.from(model.Data[0]);
                        var item = [
                            { Campo: "Component", Valor: code },
                            { Campo: "Component$Nombre", Valor: product.that(d => d.Campo == "Nombre").Valor },
                            { Campo: "Component$MainPicture", Valor: product.that(d => d.Campo == "MainPicture").Valor },
                            { Campo: "Component$Brand", Valor: product.that(d => d.Campo == "Brand").Valor },
                            { Campo: "Component$Price", Valor: product.that(d => d.Campo == "EffectivePriceData").Valor }
                        ];
                        this.list.addItemFromData(item, 0);
                    });
                }
                initializeAddButton() {
                    var addButton = new Sol.Button();
                    addButton.text = Sol.Environment.resources.anadir_item;
                    addButton.imageCode = '&#xf187;';
                    addButton.onClick = () => {
                        var selectorScreen = new Web.Screens.ProductSelectorScreen();
                        Web.System.screens.addScreen(selectorScreen);
                        Web.System.screens.showScreen(selectorScreen);
                        selectorScreen.onProductSelected = prods => {
                            this.addProduct(prods.first().code);
                            Web.System.screens.closeCurrentScreen();
                        };
                    };
                    this.add(addButton);
                }
                initializeList() {
                    this.list.itemPropertyName = "Component";
                    this.list.showImage = true;
                    this.list.imageSize = 36;
                    this.list.className = "Solarium.Commercial.Product, Solarium.Commercial, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    this.list.orderByProperty = "ID";
                    this.list.onInstantiateItem = i => this.instantiateItem(i);
                    this.list.configuration = Sol.List.from([
                        {
                            loadable: true,
                            property: "Component$MainPicture",
                            position: Components.ListViewFieldPosition.Image
                        },
                        {
                            loadable: true,
                            property: "Component",
                            hidden: true
                        },
                        {
                            loadable: false,
                            property: "DeleteCommand",
                            defaultText: Sol.Environment.resources.eliminar,
                            position: Components.ListViewFieldPosition.Right,
                            priority: Components.ListViewFieldPriority.Normal,
                            cssClass: "sol_products_list_remove"
                        },
                        {
                            loadable: true,
                            property: "Component$Nombre",
                            priority: Components.ListViewFieldPriority.High,
                            position: Components.ListViewFieldPosition.Left
                        },
                        {
                            loadable: true,
                            property: "Component$Brand",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            lineBreak: true
                        },
                        {
                            loadable: true,
                            property: "Quantity",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: Sol.Environment.resources.product_quantity,
                            editor: {
                                DataType: "SInteger",
                                PropertyName: "Quantity",
                                Title: Sol.Environment.resources.product_quantity,
                                Required: true,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: false,
                                DefaultValue: 1
                            }
                        },
                        {
                            loadable: true,
                            property: "Price",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: Sol.Environment.resources.product_price,
                            editor: {
                                DataType: "SMoney",
                                PropertyName: "Price",
                                Title: Sol.Environment.resources.product_price,
                                Required: true,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: false
                            }
                        },
                        {
                            loadable: true,
                            property: "Total",
                            priority: Components.ListViewFieldPriority.Normal,
                            position: Components.ListViewFieldPosition.Left,
                            caption: Sol.Environment.resources.product_total,
                            editor: {
                                DataType: "SMoney",
                                PropertyName: "Total",
                                Title: Sol.Environment.resources.product_total,
                                Required: true,
                                RequiredAtEdition: false,
                                ReadOnlyAtEdition: false,
                                ReadOnly: true
                            }
                        }
                    ]);
                    this.add(this.list);
                }
                instantiateItem(item) {
                    const deleteCommand = item.getDisplay("DeleteCommand");
                    deleteCommand.onClick = () => this.list.removeItem(item);
                    const quantityEditor = item.getEditor("Quantity");
                    const priceEditor = item.getEditor("Price");
                    const totalEditor = item.getEditor("Total");
                    priceEditor.value = item.getModelValue("Component$Price");
                    totalEditor.value = item.getModelValue("Component$Price");
                    quantityEditor.onChange = () => totalEditor.numericValue = quantityEditor.numericValue * priceEditor.numericValue;
                    priceEditor.onChange = () => totalEditor.numericValue = quantityEditor.numericValue * priceEditor.numericValue;
                }
                isEmpty() { return false; }
                clear() { }
            }
            Components.ProductComponentsEditor = ProductComponentsEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class SicafDisplay extends Sol.ObjectDisplay {
                constructor() {
                    super(...arguments);
                    this.taxIdPath = "EntidadRelacionada$NúmeroDocumento";
                }
                build() {
                    var _a;
                    super.build();
                    this.reset();
                    (_a = this.container.parent.onFormLoaded) === null || _a === void 0 ? void 0 : _a.subscribe(data => this.checkTaxID(data));
                }
                checkTaxID(data) {
                    let taxid = Sol.List.from(data).that(d => d.Campo == this.taxIdPath).Valor;
                    taxid = taxid.TaxID || taxid;
                    this.reset();
                    if (!taxid) {
                        this.clear();
                        return;
                    }
                    Web.System.exec("pklserijs", "CheckSupplier", { taxid: taxid }, e => {
                        if (e.Fail) {
                            this.showError();
                            return;
                        }
                        this.value = {
                            Campo: (e.IsActive ? "Ativo" : "Inativo") + '/' + (e.IsAuthorized ? "Habilitado" : "Não habilitado"),
                            Valor: 2,
                            Color: e.IsActive && e.IsAuthorized ? "#0c852c" : "#0c852c"
                        };
                    }, () => this.showError());
                }
                reset() {
                    this.value = {
                        Campo: "Verificando...",
                        Valor: 1,
                        Color: "#807d77"
                    };
                }
                showError() {
                    this.value = {
                        Campo: "Erro ao verificar",
                        Valor: 99,
                        Color: "#969696"
                    };
                }
            }
            Government.SicafDisplay = SicafDisplay;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class PCAOverview extends Web.Components.DataOverview {
                constructor() {
                    super();
                    this.approveButton = new Sol.Button();
                    this.css.add("sol_pca_overview");
                }
                refresh(filters) {
                    if (!filters)
                        return;
                    this.mainFilters = filters;
                    const overviewYear = Sol.List.from(filters).that(flt => flt.PropertyName == "Year").FilterValue.Valor;
                    Web.System.exec("jy5alkj23", "GetOverview", { filters: filters }, e => {
                        this.controls.empty();
                        this.overviewBody = new Sol.Control();
                        this.createStatusArea(e.StatusTotals);
                        this.overviewBody.addCtr("Visão Geral - PCA " + overviewYear, "sol_pca_overview_main_title");
                        this.createTotalField(e.FormattedOverallTotal);
                        this.createOverallCountField(e.OverallCount);
                        e.Totals.forEach(t => this.createTopLevelItem(t));
                        this.add(this.overviewBody);
                        if (e.ShowApproveButton) {
                            this.addApproveButton();
                            this.addApproveMessage();
                        }
                        this.addErrorMessage();
                        this.addSuccessMessage();
                    });
                }
                addApproveButton() {
                    this.approveButton.type = Sol.ButtonType.Normal;
                    this.approveButton.text = Sol.Environment.resources.approve;
                    this.approveButton.onClick = () => this.confirm();
                    this.approveButton.css.add("sol_pca_overview_button");
                    this.overviewBody.add(this.approveButton);
                }
                addApproveMessage() {
                    this.approveMessage = new Sol.ScreenMessage();
                    this.approveMessage.type = Sol.MessageType.Confirmation;
                    this.approveMessage.caption = Sol.Environment.resources.approveall;
                    this.approveMessage.visible = false;
                    this.approveMessage.onConfirm = () => this.approve();
                    this.approveMessage.onCancel = () => this.cancelapprove();
                    this.overviewBody.add(this.approveMessage);
                }
                addErrorMessage() {
                    this.errorMessage = new Sol.ScreenMessage();
                    this.errorMessage.visible = false;
                    this.add(this.errorMessage);
                }
                addSuccessMessage() {
                    this.successMessage = new Sol.ScreenMessage();
                    this.successMessage.type = Sol.MessageType.Success;
                    this.successMessage.caption = "Aprovado com sucesso";
                    this.successMessage.visible = this.showSuccess;
                    this.add(this.successMessage);
                }
                confirm() {
                    this.approveButton.enabled = false;
                    this.approveButton.css.add("sol_pca_overview_button_loading");
                    this.approveMessage.visible = true;
                }
                cancelapprove() {
                    this.approveMessage.visible = false;
                    this.approveButton.css.remove("sol_pca_overview_button_loading");
                    this.approveButton.enabled = true;
                }
                approve() {
                    this.approveMessage.visible = false;
                    Web.System.exec("jy5alkj23", "Approve", { filters: this.mainFilters }, e => {
                        this.errorMessage.caption = e.ErrorMessage;
                        this.showSuccess = !e.Fail;
                        this.errorMessage.visible = !this.showSuccess;
                        this.approveButton.css.remove("sol_pca_overview_button_loading");
                        this.approveButton.enabled = true;
                        if (this.showSuccess)
                            this.refresh(this.mainFilters);
                    });
                }
                createTotalField(overallTotal) {
                    const wrapper = this.overviewBody.addCtr(null, "sol_pca_overview_overall_box");
                    wrapper.addCtr("Total", null, "label");
                    wrapper.addCtr(overallTotal, null, "span");
                }
                createOverallCountField(OverallCount) {
                    const wrapper = this.overviewBody.addCtr(null, "sol_pca_overview_overall_box");
                    wrapper.addCtr("Quantidade", null, "label");
                    wrapper.addCtr(OverallCount, null, "span");
                }
                createTopLevelItem(model) {
                    const departmentSpace = new Sol.Control();
                    departmentSpace.visible = false;
                    const expando = new Sol.ExpandoLabel();
                    const topLevelWrapper = new Sol.Control();
                    topLevelWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level1"]);
                    expando.data = model;
                    expando.onExpanded.subscribe(e => this.TopLevelExpanded(e));
                    expando.caption = model.ItemName;
                    expando.associatedControl = departmentSpace;
                    topLevelWrapper.add(expando);
                    topLevelWrapper.addCtr(model.FormattedItemTotal, "sol_pca_overview_amount", "span");
                    topLevelWrapper.addCtr(model.PercentageItemTotal, "sol_pca_overview_percentage", "span");
                    this.overviewBody.add(topLevelWrapper);
                    this.overviewBody.add(departmentSpace);
                }
                TopLevelExpanded(expando) {
                    if (!expando.expanded)
                        return;
                    const model = expando.data;
                    const classNames = ["BudgetForecastProduct", "BudgetForecastService", "BudgetForecastEngineering", "BudgetForecastContract"];
                    if (classNames.indexOf(model.ClassName) > -1)
                        this.loadDepartment(expando.associatedControl, model);
                    else if (model.ClassName == "BudgetForecastVehicle")
                        this.loadVehicles(expando.associatedControl, model);
                    else
                        this.loadOthers(expando.associatedControl, model);
                }
                loadDepartment(departmentSpace, model) {
                    const departmentRequest = {
                        className: model.ClassType,
                        filters: this.mainFilters
                    };
                    Web.System.exec("jy5alkj23", "GetTopLevelData", departmentRequest, e => {
                        departmentSpace.controls.empty();
                        Sol.List.from(e).forEach(d => {
                            const categorySpace = new Sol.Control();
                            categorySpace.visible = false;
                            const departmentWrapper = new Sol.Control();
                            departmentWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level2"]);
                            const departmentExpando = new Sol.ExpandoLabel();
                            departmentExpando.data = d;
                            departmentExpando.onExpanded.subscribe(e => (model.ClassName == "BudgetForecastContract" ? this.loadContract(departmentExpando, categorySpace) : this.loadCategory(e)));
                            departmentExpando.caption = d.Name;
                            departmentWrapper.add(departmentExpando);
                            departmentWrapper.addCtr(d.Total, "sol_pca_overview_amount", "span");
                            departmentWrapper.addCtr(d.Percentage, "sol_pca_overview_percentage", "span");
                            departmentExpando.associatedControl = categorySpace;
                            departmentSpace.add(departmentWrapper);
                            departmentSpace.add(categorySpace);
                        });
                    });
                }
                loadOthers(departmentSpace, model) {
                    const propertyRequest = {
                        className: model.ClassType,
                        filters: this.mainFilters
                    };
                    Web.System.exec("jy5alkj23", "GetTopLevelData", propertyRequest, e => {
                        departmentSpace.controls.empty();
                        const headerWrapper = new Sol.Control();
                        headerWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level2", "sol_pca_overview_level2_header"]);
                        headerWrapper.addCtr("Nome", "sol_pca_overview_name_no_dep_header");
                        headerWrapper.addCtr("Responsável", "sol_pca_overview_responsable_no_dep", "span");
                        headerWrapper.addCtr("Total", "sol_pca_overview_total_no_dep", "span");
                        headerWrapper.addCtr("Data", "sol_pca_overview_month_no_dep", "span");
                        departmentSpace.add(headerWrapper);
                        Sol.List.from(e).forEach(d => {
                            const propertyWrapper = new Sol.Control();
                            propertyWrapper.css.add("sol_pca_overview_control_no_dep");
                            const mainControl = propertyWrapper.addCtr(d.Name, "sol_pca_overview_name_no_dep", "span");
                            mainControl.onClick = () => Web.System.edit(d.ClassHash.toString(), d.ObjID);
                            propertyWrapper.addCtr(d.Responsable, "sol_pca_overview_responsable_no_dep", "span");
                            propertyWrapper.addCtr(d.Total, "sol_pca_overview_total_no_dep", "span");
                            propertyWrapper.addCtr(d.Month, "sol_pca_overview_month_no_dep", "span");
                            departmentSpace.add(propertyWrapper);
                        });
                    });
                }
                loadVehicles(departmentSpace, model) {
                    const requestRequest = {
                        className: model.ClassType,
                        filters: this.mainFilters
                    };
                    Web.System.exec("jy5alkj23", "GetTopLevelData", requestRequest, e => {
                        departmentSpace.controls.empty();
                        const headerWrapper = new Sol.Control();
                        headerWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level2", "sol_pca_overview_level2_header"]);
                        headerWrapper.addCtr("Modelo", "sol_pca_overview_item_unit_header");
                        headerWrapper.addCtr("Placa", "sol_pca_overview_item_other", "span");
                        headerWrapper.addCtr("Responsável", "sol_pca_overview_item_other", "span");
                        headerWrapper.addCtr("Total", "sol_pca_overview_item_total", "span");
                        headerWrapper.addCtr("Data", "sol_pca_overview_item_month", "span");
                        departmentSpace.add(headerWrapper);
                        Sol.List.from(e).forEach(d => {
                            const requestWrapper = new Sol.Control();
                            requestWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level2"]);
                            const mainControl = requestWrapper.addCtr(d.Name, "sol_pca_overview_item_unit", "span");
                            mainControl.onClick = () => Web.System.edit(d.ClassHash.toString(), d.ObjID);
                            requestWrapper.addCtr(d.Complement, "sol_pca_overview_item_other", "span");
                            requestWrapper.addCtr(d.Responsable, "sol_pca_overview_item_other", "span");
                            requestWrapper.addCtr(d.Total, "sol_pca_overview_item_total", "span");
                            requestWrapper.addCtr(d.Month, "sol_pca_overview_item_month", "span");
                            departmentSpace.add(requestWrapper);
                        });
                    });
                }
                loadCategory(departmentExpando) {
                    if (!departmentExpando.expanded)
                        return;
                    const model = departmentExpando.data;
                    const categoryRequest = {
                        id: model.ObjID,
                        className: model.classType,
                        filters: this.mainFilters
                    };
                    Web.System.exec("jy5alkj23", "ReturnCatProperMethod", categoryRequest, e => {
                        departmentExpando.associatedControl.controls.empty();
                        Sol.List.from(e).forEach(d => {
                            const itemSpace = new Sol.Control();
                            itemSpace.visible = false;
                            const categoryWrapper = new Sol.Control();
                            categoryWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level3"]);
                            const categoryExpando = new Sol.ExpandoLabel();
                            categoryExpando.data = d;
                            categoryExpando.onExpanded.subscribe(e => this.loadGroupedItems(e, itemSpace));
                            categoryExpando.caption = d.Name;
                            categoryWrapper.add(categoryExpando);
                            categoryWrapper.addCtr(d.Total, "sol_pca_overview_amount", "span");
                            categoryWrapper.addCtr(d.Percentage, "sol_pca_overview_percentage", "span");
                            categoryExpando.associatedControl = itemSpace;
                            departmentExpando.associatedControl.add(categoryWrapper);
                            departmentExpando.associatedControl.add(itemSpace);
                        });
                    });
                }
                loadGroupedItems(categoryExpando, itemSpace) {
                    if (!categoryExpando.expanded)
                        return;
                    const model = categoryExpando.data;
                    const itemRequest = {
                        id: model.ObjID,
                        className: model.classType,
                        filters: this.mainFilters
                    };
                    Web.System.exec("jy5alkj23", "ReturnItemProperMethod", itemRequest, e => {
                        itemSpace.controls.empty();
                        Sol.List.from(e).forEach(d => {
                            const requestSpace = new Sol.Control();
                            requestSpace.visible = false;
                            const itemWrapper = new Sol.Control();
                            itemWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level4"]);
                            const itemExpando = new Sol.ExpandoLabel();
                            itemExpando.data = d;
                            itemExpando.onExpanded.subscribe(e => this.loadSpecifiedOrder(e, requestSpace));
                            itemExpando.caption = d.Name;
                            itemWrapper.add(itemExpando);
                            itemWrapper.addCtr(d.Total, "sol_pca_overview_amount", "span");
                            itemWrapper.addCtr(d.Percentage, "sol_pca_overview_percentage", "span");
                            itemExpando.associatedControl = requestSpace;
                            itemSpace.add(itemWrapper);
                            itemSpace.add(requestSpace);
                        });
                    });
                }
                loadSpecifiedOrder(itemExpando, requestSpace) {
                    if (!itemExpando.expanded)
                        return;
                    const model = itemExpando.data;
                    const orderRequest = {
                        id: model.ObjID,
                        className: model.classType,
                        filters: this.mainFilters
                    };
                    Web.System.exec("jy5alkj23", "ReturnOrderMethod", orderRequest, e => {
                        requestSpace.controls.empty();
                        const headerWrapper = new Sol.Control();
                        headerWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level5", "sol_pca_overview_level5_header"]);
                        headerWrapper.addCtr("Unidade", "sol_pca_overview_item_unit_header");
                        headerWrapper.addCtr("Quantd.", "sol_pca_overview_item_quantity", "span");
                        headerWrapper.addCtr("Preço", "sol_pca_overview_item_price", "span");
                        headerWrapper.addCtr("Total", "sol_pca_overview_item_total", "span");
                        headerWrapper.addCtr("Data", "sol_pca_overview_item_month", "span");
                        requestSpace.add(headerWrapper);
                        Sol.List.from(e).forEach(d => {
                            const orderWrapper = new Sol.Control();
                            orderWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level5"]);
                            const mainControl = orderWrapper.addCtr(d.Responsable, "sol_pca_overview_item_unit");
                            mainControl.onClick = () => Web.System.edit(d.ClassHash.toString(), d.ObjID);
                            orderWrapper.addCtr(d.Quantity, "sol_pca_overview_item_quantity", "span");
                            orderWrapper.addCtr(d.Price, "sol_pca_overview_item_price", "span");
                            orderWrapper.addCtr(d.Total, "sol_pca_overview_item_total", "span");
                            orderWrapper.addCtr(d.Month, "sol_pca_overview_item_month", "span");
                            requestSpace.add(orderWrapper);
                        });
                    });
                }
                loadContract(itemExpando, requestSpace) {
                    if (!itemExpando.expanded)
                        return;
                    const model = itemExpando.data;
                    const orderRequest = {
                        id: model.ObjID,
                        className: model.classType,
                        filters: this.mainFilters
                    };
                    Web.System.exec("jy5alkj23", "ReturnCatProperMethod", orderRequest, e => {
                        requestSpace.controls.empty();
                        const headerWrapper = new Sol.Control();
                        headerWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level3", "sol_pca_overview_level3_header"]);
                        headerWrapper.addCtr("Número do Contrato", "sol_pca_overview_item_unit_header");
                        headerWrapper.addCtr("Fornecedor", "sol_pca_overview_item_other", "span");
                        headerWrapper.addCtr("Responsável", "sol_pca_overview_item_other", "span");
                        headerWrapper.addCtr("Total", "sol_pca_overview_item_total", "span");
                        headerWrapper.addCtr("Data", "sol_pca_overview_item_month", "span");
                        requestSpace.add(headerWrapper);
                        Sol.List.from(e).forEach(d => {
                            const requestWrapper = new Sol.Control();
                            requestWrapper.css.addMany(["sol_pca_overview_level", "sol_pca_overview_level3"]);
                            const mainControl = requestWrapper.addCtr(d.Name, "sol_pca_overview_item_unit", "span");
                            mainControl.onClick = () => Web.System.edit(d.ClassHash.toString(), d.ObjID);
                            requestWrapper.addCtr(d.Complement, "sol_pca_overview_item_other", "span");
                            requestWrapper.addCtr(d.Responsable, "sol_pca_overview_item_other", "span");
                            requestWrapper.addCtr(d.Total, "sol_pca_overview_item_total", "span");
                            requestWrapper.addCtr(d.Month, "sol_pca_overview_item_month", "span");
                            requestSpace.add(requestWrapper);
                        });
                    });
                }
                createStatusArea(statusList) {
                    const statusArea = new Sol.Control();
                    statusArea.addCtr("Quantidades e Total por Status", "sol_pca_overview_status_area_title");
                    statusArea.css.add("sol_pca_overview_status_area");
                    statusArea.addMany(Sol.List.from(statusList).select(st => {
                        const statusDisplay = new Sol.Control();
                        const statusNameDisplay = statusDisplay.addCtr(st.StatusName, "sol_pca_overview_status_name");
                        statusNameDisplay.estilos.definir("border-left-color", st.StatusColor);
                        statusDisplay.addCtr(st.StatusCount.toString(), "sol_pca_overview_status_qtd");
                        statusDisplay.addCtr(st.FormattedTotal, "sol_pca_overview_status_total");
                        statusDisplay.css.add("sol_pca_overview_status_display");
                        return statusDisplay;
                    }));
                    this.overviewBody.add(statusArea);
                }
            }
            Government.PCAOverview = PCAOverview;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class IRPOverviewItem extends Sol.Control {
                constructor(model) {
                    super();
                    let itemTypeCtr = this.addCtr(model.TypeIcon, null, "i");
                    itemTypeCtr.tip = model.TypeDescription;
                    this.addCtr(model.ItemCode, null, "span");
                    this.addCtr(model.ItemDescription, null, "span");
                    this.addCtr(model.DepartmentName + " > " + model.CategoryName);
                    this.createApplicationsTable(model.ApprovedApplications);
                    this.createAnalysisDataArea(model);
                }
                createApplicationsTable(applications) {
                    if (applications.length === 0)
                        return;
                    let applicationsArea = new Sol.Control();
                    applicationsArea.addCtr("Pedidos:", null, "span");
                    let table = applicationsArea.addCtr(null, null, "table");
                    table.addMany(Sol.List.from(applications).select(app => {
                        let row = table.addCtr(null, null, "tr");
                        row.addCtr(app.Applicant, null, "td");
                        row.addCtr(app.Quantity, null, "td");
                        return row;
                    }));
                    this.add(applicationsArea);
                }
                createAnalysisDataArea(model) {
                    let analysisArea = new Sol.Control();
                    if (!!model.SecurityMargin)
                        analysisArea.add(this.createFieldWrapper("Margem de segurança", model.SecurityMargin));
                    analysisArea.add(this.createFieldWrapper("Consumo médio últ. 5 anos", model.AverageConsumption));
                    analysisArea.add(this.createFieldWrapper("Último consumo", model.LastConsumption));
                    analysisArea.add(this.createFieldWrapper("Total solicitado", model.RequestedQuantity));
                    analysisArea.add(this.createFieldWrapper("Quantitativo final estimado", model.FinalRequestedQuantity));
                    analysisArea.add(this.createFieldWrapper("Maior valor", model.HighestQuantity));
                    analysisArea.add(this.createFieldWrapper("Valor de referência", model.Price));
                    if (!!model.PriceDate)
                        analysisArea.add(this.createFieldWrapper("Data de ref. no GMAT", model.PriceDate));
                    let approvedCheck = new Web.Components.ApprovedCheck();
                    approvedCheck.caption = "Aprovação";
                    approvedCheck.checked = model.Approved;
                    approvedCheck.onClick = () => this.saveItemApproval(model.ItemID, approvedCheck.checked);
                    let approvedWrapper = new Sol.FieldWrapper();
                    approvedWrapper.add(approvedCheck);
                    analysisArea.add(approvedWrapper);
                    this.add(analysisArea);
                }
                createFieldWrapper(label, value) {
                    let fieldWrapper = new Sol.FieldWrapper();
                    fieldWrapper.add(new Sol.Label(label));
                    fieldWrapper.addCtr(value);
                    return fieldWrapper;
                }
                saveItemApproval(itemID, approved) {
                    var savingData = {
                        className: "Solarium.Government.Licitations.PricesRegistrationItem, Solarium.Government.Licitations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        id: itemID,
                        data: [{ Campo: "Approved", Valor: approved }]
                    };
                    Web.System.exec("3b5v9v45", "Save", savingData);
                }
            }
            Government.IRPOverviewItem = IRPOverviewItem;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class IRPOverview extends Web.Components.DataOverview {
                constructor() {
                    super();
                }
                refresh(filters) {
                    this.controls.empty();
                    let irpIP = Web.System.screens.currentDetails.code;
                    Web.System.exec("jjhnkmlkld", "GetItemAnalysis", { irpIP: irpIP }, e => this.controls.addMany(Sol.List.from(e.Items).select(i => new Government.IRPOverviewItem(i))));
                }
            }
            Government.IRPOverview = IRPOverview;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class CurrentContractTotal extends Sol.CurrencyField {
                build() {
                    super.build();
                    this.savable = true;
                    this.value = Web.System.screens.currentDetails.getEditor("Total").value;
                }
            }
            Components.CurrentContractTotal = CurrentContractTotal;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("CurrentContractTotal", () => new Sol.Web.Components.CurrentContractTotal());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class OpenLicitationButton extends Sol.Button {
                constructor() {
                    super();
                    this.imageCode = '&#xf02d;';
                    this.text = Sol.Environment.resources.openLicitationButton;
                    this.onClick = () => this.OpenLicitation(this.value);
                }
                toControl() { return this; }
                OpenLicitation(value) {
                    Web.System.edit("Solarium.Government.Licitations.Licitation, Solarium.Government.Licitations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", this.value);
                }
                clear() { }
                foco() { }
                isEmpty() { return true; }
                validate() { return null; }
            }
            Components.OpenLicitationButton = OpenLicitationButton;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("OpenLicitationButton", () => new Sol.Web.Components.OpenLicitationButton());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class OpenContractButton extends Sol.Button {
                constructor() {
                    super();
                    this.imageCode = '&#xf2b5;';
                    this.text = Sol.Environment.resources.openContractButton;
                    this.onClick = () => this.OpenContract(this.value);
                }
                toControl() { return this; }
                OpenContract(value) {
                    Web.System.edit("Solarium.Contracts.Contract, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", this.value);
                }
                clear() { }
                foco() { }
                isEmpty() { return true; }
                validate() { return null; }
            }
            Components.OpenContractButton = OpenContractButton;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("OpenContractButton", () => new Sol.Web.Components.OpenContractButton());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class RiskCalculator extends Sol.Combo {
                constructor() {
                    super();
                    this.valueMember = "Code";
                    this.displayMember = "Description";
                    this.onValueModified.subscribe(() => this.calculate());
                }
                calculate() {
                    const data = {
                        probability: this.getFactor("RiskProbability"),
                        impact: this.getFactor("RiskImpact")
                    };
                    Web.System.exec("pjaleisd", "CalculateLevel", data, result => this.container.getEditor("RiskLevel").value = result);
                }
                getFactor(propertyName) {
                    return parseInt(this.container.getEditor(propertyName).selectedCode);
                }
            }
            Government.RiskCalculator = RiskCalculator;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("RiskCalculator", model => {
    const calculator = new Sol.Web.Government.RiskCalculator();
    calculator.setDataSource(model.Options);
    return calculator;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class PCACopyMonthValueButton extends Sol.Button {
                constructor() {
                    super();
                    this.type = Sol.ButtonType.Normal;
                    this.imageCode = "&#xf0c5;";
                    this.tip = "Copiar essa quantidade para os meses posteriores";
                    this.onClick = () => this.copyQuantity();
                }
                get readonly() { return !this.enabled; }
                set readonly(value) { this.enabled = !value; }
                copyQuantity() {
                    let row = this.parent.parent;
                    let currentQuantity = row.getEditor("Quantity").value;
                    let table = row.myGrid;
                    let currentRow = table.rows.indice(row);
                    for (let index = currentRow + 1; index < 12; index++) {
                        let newRow = table.rows.item(index);
                        newRow.getEditor("Quantity").value = currentQuantity;
                    }
                }
                clear() { }
                foco() { }
                isEmpty() { return false; }
                toControl() { return this; }
                validate() { return null; }
            }
            Government.PCACopyMonthValueButton = PCACopyMonthValueButton;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PCACopyMonthValueButton", () => new Sol.Web.Government.PCACopyMonthValueButton());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class ReferenceTermSelector extends Web.Components.Selectors.Selector {
                addExtraIcons() {
                    this.viewButton = new Web.Components.Selectors.ViewDocumentIcon();
                    this.viewButton.estilos.agregar("margin-left", "-97px");
                    this.viewButton.tip = "Visualizar o Termo de Referência";
                    this.viewButton.visible = false;
                    this.viewButton.onClick = () => this.viewDocument();
                    this.add(this.viewButton);
                }
                enableButtons(value) {
                    super.enableButtons(value);
                    this.viewButton.visible = value;
                }
                viewDocument() {
                    const data = {
                        referenceTermID: this.selectedCode,
                        forPrinting: false
                    };
                    Web.System.exec("majwolas", "GenerateDocument", data, model => {
                        const action = new Web.Actions.ViewDocumentAction();
                        action.processResponse(model);
                    });
                }
            }
            Government.ReferenceTermSelector = ReferenceTermSelector;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ReferenceTerm", model => {
    const selector = new Sol.Web.Government.ReferenceTermSelector();
    selector.className = model.DataTypeFullName;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class IPCACalendarHtmlPreviewModel {
            }
            Government.IPCACalendarHtmlPreviewModel = IPCACalendarHtmlPreviewModel;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class PCACalendarHtmlPreview extends Web.Components.HtmlEditor {
                constructor() {
                    super();
                    this.readonly = true;
                }
                build() {
                    super.build();
                    this.getPreview();
                }
                getPreview() {
                    const data = { calendarID: this.calendarID };
                    Web.System.exec("jy5alkj23", "GetPCACalendarPreview", data, e => this.value = e.HtmlPreview);
                }
            }
            Government.PCACalendarHtmlPreview = PCACalendarHtmlPreview;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PCACalendarHtmlPreview", (model, className, code) => {
    const editor = new Sol.Web.Government.PCACalendarHtmlPreview();
    editor.calendarID = code;
    return editor;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class IRPCopyPCAValueButton extends Sol.Button {
                constructor() {
                    super();
                    this.type = Sol.ButtonType.Normal;
                    this.imageCode = "&#xf061;";
                    this.tip = "Copiar a quantidade aprovada no PCA para o pedido";
                    this.onClick = () => this.copyQuantity();
                }
                get readonly() { return !this.enabled; }
                set readonly(value) { this.enabled = !value; }
                copyQuantity() {
                    let row = this.parent.parent;
                    let lastPCAQuantity = row.getEditor("LastPCAQuantity").value;
                    row.getEditor("Quantity").value = lastPCAQuantity;
                }
                clear() { }
                foco() { }
                isEmpty() { return false; }
                toControl() { return this; }
                validate() { return null; }
            }
            Government.IRPCopyPCAValueButton = IRPCopyPCAValueButton;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("IRPCopyPCAValueButton", () => new Sol.Web.Government.IRPCopyPCAValueButton());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            let BudgetAllocationFieldType;
            (function (BudgetAllocationFieldType) {
                BudgetAllocationFieldType[BudgetAllocationFieldType["Single"] = 0] = "Single";
                BudgetAllocationFieldType[BudgetAllocationFieldType["Multi"] = 1] = "Multi";
            })(BudgetAllocationFieldType = Government.BudgetAllocationFieldType || (Government.BudgetAllocationFieldType = {}));
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class BudgetAllocationTypeSelector extends Web.Components.DataCombo {
                constructor() {
                    super();
                    this.autoSelectUniqueOption = true;
                    this.onSet.subscribe(() => this.applyMask());
                    this.onValueModified.subscribe(() => this.applyMask());
                }
                applyMask() {
                    let allocation = this.container.getEditor("Allocation");
                    let budgetaryUnit = this.container.getEditor("BudgetaryUnit");
                    let subaction = this.container.getEditor("Project");
                    let expenseNature = this.container.getEditor("ExpensesItem");
                    let resourcesSource = this.container.getEditor("ResourceSource");
                    if (!this.selectedCode) {
                        this.changeVisibility(allocation, false);
                        this.changeVisibility(budgetaryUnit, false);
                        this.changeVisibility(subaction, false);
                        this.changeVisibility(expenseNature, false);
                        this.changeVisibility(resourcesSource, false);
                        return;
                    }
                    const loadData = {
                        className: this.className,
                        code: parseInt(this.selectedCode),
                        subtype: false,
                        propertyList: ["Mask", "NatureMask", "ResourceMask", "CampType"]
                    };
                    Web.System.exec("sn9d23vs7d", "Load", loadData, model => {
                        var _a, _b, _c, _d;
                        let values = Sol.List.from(model.Data);
                        let type = (_a = values.that(v => v.Campo == "CampType")) === null || _a === void 0 ? void 0 : _a.Valor.Valor;
                        let mask = (_b = values.that(v => v.Campo == "Mask")) === null || _b === void 0 ? void 0 : _b.Valor;
                        let natureMask = (_c = values.that(v => v.Campo == "NatureMask")) === null || _c === void 0 ? void 0 : _c.Valor;
                        let resourceMask = (_d = values.that(v => v.Campo == "ResourceMask")) === null || _d === void 0 ? void 0 : _d.Valor;
                        let isSingleMode = type == Government.BudgetAllocationFieldType.Single;
                        this.changeVisibility(allocation, isSingleMode);
                        this.changeVisibility(budgetaryUnit, !isSingleMode);
                        this.changeVisibility(subaction, !isSingleMode);
                        this.changeVisibility(expenseNature, !isSingleMode);
                        this.changeVisibility(resourcesSource, !isSingleMode);
                        if (allocation)
                            allocation.mask = mask;
                        if (resourcesSource)
                            resourcesSource.mask = resourceMask;
                        if (expenseNature)
                            expenseNature.mask = natureMask;
                    });
                }
                changeVisibility(editor, visibility) {
                    if (!editor)
                        return;
                    editor.myLabel.visible = visibility;
                    editor.visible = visibility;
                }
            }
            Government.BudgetAllocationTypeSelector = BudgetAllocationTypeSelector;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("BudgetAllocationType", model => {
    const batSelector = new Sol.Web.Government.BudgetAllocationTypeSelector();
    batSelector.className = model.DataTypeFullName;
    return batSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class AmendmentChangeSelector extends Sol.Combo {
                constructor() {
                    super();
                    this.onSet.subscribe(() => this.changeVisibility());
                    this.onValueModified.subscribe(() => this.changeVisibility());
                }
                changeVisibility() {
                    if (!this.container)
                        return;
                    let changedItems = this.container.getEditor("ChangedItems");
                    let changeType = this.container.getEditor("ChangeType");
                    if (!changedItems)
                        return;
                    let isSuppressionOrIncrease = parseInt(changeType.selectedCode) == 2 || parseInt(changeType.selectedCode) == 17;
                    changedItems.myLabel.visible = isSuppressionOrIncrease;
                    changedItems.visible = isSuppressionOrIncrease;
                }
            }
            Government.AmendmentChangeSelector = AmendmentChangeSelector;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("AmendmentChangeSelector", model => {
    const amendmentSelector = new Sol.Web.Government.AmendmentChangeSelector();
    amendmentSelector.loadOptions(model.Options);
    return amendmentSelector;
});
var DetailsScreen = Sol.Web.Screens.DetailsScreen;
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class EndModeSelector extends Sol.MultipleChoice {
                get endDate() { return this.container.getEditor("EndDate"); }
                get months() { return this.container.getEditor("Months"); }
                get days() { return this.container.getEditor("Days"); }
                build() {
                    super.build();
                    this.days.onValueModified.subscribe(() => this.calculatePercentage());
                    this.days.onSet.subscribe(() => this.calculatePercentage());
                    this.endDate.onValueModified.subscribe(() => this.calculatePercentage());
                    this.endDate.onSet.subscribe(() => this.calculatePercentage());
                    this.months.onValueModified.subscribe(() => this.calculatePercentage());
                    this.months.onSet.subscribe(() => this.calculatePercentage());
                }
                calculatePercentage() {
                    const companyID = Sol.Environment.credential.empresa;
                    const poaEcossystem = Sol.List.from([1503, 776, 1914, 1940, 29, 4]);
                    const isPoaCompany = poaEcossystem.contains(companyID);
                    if (!this.container || !isPoaCompany)
                        return;
                    const screen = this.container.parent.parent.parent.parent.parent.parent.parent;
                    const contractID = screen.anchorage.FilterValue;
                    const loadData = {
                        className: "Solarium.Contracts.Contract, Solarium.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                        currentPage: 0,
                        rowCount: 0,
                        sortProperty: "ID",
                        sortOrder: Web.Ordering.ascending,
                        filters: [{
                                PropertyName: "ID",
                                FilterValue: contractID,
                                FilterType: "SInteger"
                            }],
                        properties: ["StartDate", "CompletionDate"],
                        pageInfo: false
                    };
                    Web.System.exec("i3n48smak", "Search", loadData, model => {
                        Sol.List.from(model.Data).cast().forEach(dataRow => {
                            var _a, _b;
                            var dataCollection = Sol.List.from(dataRow);
                            let startDateField = dataCollection.that(v => v.Campo == "StartDate").Valor;
                            let completionDateField = (_a = dataCollection.that(v => v.Campo == "CompletionDate")) === null || _a === void 0 ? void 0 : _a.Valor;
                            let contractStartDate = Date.prototype.convertLocal(startDateField);
                            let completionDate = Date.prototype.convertLocal(completionDateField);
                            let changeType = this.container.parent.parent.parent.getEditor("ChangeType");
                            let percentCalculation = this.container.parent.parent.parent.getEditor("PercentCalculation");
                            let endDate = this.container.getEditor("EndDate").value;
                            let months = this.container.getEditor("Months").value;
                            let days = this.container.getEditor("Days").value;
                            let amendmentCode = (_b = this.container.parent.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.code;
                            if (amendmentCode > 0)
                                return;
                            if (parseInt(changeType.selectedCode) != 15)
                                return;
                            Web.System.exec("vvasleos", "GetLastContractRenewalDate", { contractID }, newStartDate => {
                                let startDate = newStartDate ? Date.convert(newStartDate) : contractStartDate;
                                let monthsIntoDays = this.selectedCode == 2 ?
                                    Date.prototype.monthsIntoDays(completionDate, Number(months)) : Number(days);
                                let newFinalDate = this.selectedCode == 1 ?
                                    Date.convert(endDate) : completionDate.addDays(monthsIntoDays);
                                this.calculateRenewalPercentage(percentCalculation, startDate, completionDate, newFinalDate);
                            });
                        });
                    });
                }
                calculateRenewalPercentage(percentCalcCamp, start, originalEnding, newEnding) {
                    if (!newEnding || originalEnding > newEnding) {
                        percentCalcCamp.value = 0.0000;
                        return;
                    }
                    const originalPeriod = originalEnding.getTime() - start.getTime();
                    const periodRenewed = newEnding.getTime() - originalEnding.getTime();
                    const percentage = (periodRenewed / originalPeriod) * 100;
                    percentCalcCamp.value = Number(percentage.toFixed(2));
                }
            }
            Government.EndModeSelector = EndModeSelector;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("EndModeSelector", model => {
    const endModeSelector = new Sol.Web.Government.EndModeSelector();
    endModeSelector.options = model.Options;
    return endModeSelector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var Selectors;
            (function (Selectors) {
                class MultiCompanySelector extends Selectors.Selector {
                    constructor() {
                        super(...arguments);
                        this.isMultiCompany = true;
                    }
                    get systemSelector() {
                        return Web.System.screens.currentDetails.getEditor("Empresa") || Web.System.screens.currentDetails.getEditor("Emisor");
                    }
                    changeCompany(c) { this.clear(); }
                    setCompany(c) { }
                    build() {
                        super.build();
                        let systemSelector = this.systemSelector;
                        if (systemSelector)
                            systemSelector.extraSubscribers.add(this);
                    }
                    getFilters() {
                        let filters = super.getFilters();
                        let systemSelector = this.systemSelector;
                        if (systemSelector)
                            filters.add({ PropertyName: "Empresa", FilterType: "SInteger", FilterValue: systemSelector.selectedCode });
                        return filters;
                    }
                }
                Selectors.MultiCompanySelector = MultiCompanySelector;
            })(Selectors = Components.Selectors || (Components.Selectors = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("MultiCompanySelector", model => {
    let selector = new Sol.Web.Components.Selectors.MultiCompanySelector();
    selector.className = model.DataTypeFullName;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class BudgetaryUnitSelector extends Web.Components.Selectors.MultiCompanySelector {
                constructor() {
                    super();
                    this.displayProperty = "CodeNameTitle";
                    this.filterProperty = "CodeNameFilter";
                    this.useWrapper = true;
                    this.isComplex = false;
                }
            }
            Government.BudgetaryUnitSelector = BudgetaryUnitSelector;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("BudgetaryUnitSelector", model => {
    const selector = new Sol.Web.Government.BudgetaryUnitSelector();
    selector.className = model.DataTypeFullName;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class BudgetProjectSelector extends Web.Components.Selectors.MultiCompanySelector {
                constructor() {
                    super();
                    this.currentUnit = 0;
                    this.displayProperty = "CodeNameTitle";
                    this.filterProperty = "CodeNameFilter";
                    this.useWrapper = true;
                    this.isComplex = false;
                }
                build() {
                    super.build();
                    let unitSelector = this.container.getEditor("BudgetaryUnit");
                    unitSelector.onValueSet = () => this.currentUnit = unitSelector.selectedCode;
                    unitSelector.onValueModified.subscribe(() => {
                        this.currentUnit = unitSelector.selectedCode;
                        this.clear();
                    });
                }
                getFilters() {
                    let filters = super.getFilters();
                    let unit = !this.currentUnit ? -1 : this.currentUnit;
                    filters.add({ PropertyName: "BudgetaryUnit", FilterType: "SInteger", FilterValue: unit });
                    return filters;
                }
            }
            Government.BudgetProjectSelector = BudgetProjectSelector;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("BudgetProjectSelector", model => {
    let selector = new Sol.Web.Government.BudgetProjectSelector();
    selector.className = model.DataTypeFullName;
    return selector;
});
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Government;
        (function (Government) {
            class DFDPreview extends Web.Components.HtmlEditor {
                constructor(contractID) {
                    super();
                    this.contractID = contractID;
                    this.css.add("sol_contract_viewer");
                }
                build() {
                    super.build();
                    let templateCombo = this.container.getEditor("Template");
                    templateCombo.onChange = () => this.showPreview(parseInt(templateCombo.selectedCode));
                    templateCombo.onSet.subscribe(() => this.showPreview(parseInt(templateCombo.selectedCode)));
                    this.showPreview(parseInt(templateCombo.selectedCode));
                }
                showPreview(templateID) {
                    if (!templateID) {
                        this.clear();
                        return;
                    }
                    let data = { templateID: templateID, dfdID: this.contractID };
                    Web.System.exec("oieamed2d", "GetPreview", data, e => this.value = e.Html);
                }
            }
            Government.DFDPreview = DFDPreview;
        })(Government = Web.Government || (Web.Government = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("DFDPreview", (model, ctx, code) => new Sol.Web.Government.DFDPreview(code));
var Sol;
(function (Sol) {
    class NoConnectionDialog extends Sol.DialogBox {
        constructor() {
            super();
            this.title = Sol.Environment.resources.noConnectionTitle;
            this.contentArea.addCtr(Sol.Environment.resources.noConnectionMessage, "sol_no_connection_message");
            const okButton = new Sol.Button();
            okButton.text = "OK";
            okButton.onClick = () => this.onClosing();
            okButton.css.add("sol_no_connection_button");
            this.contentArea.add(okButton);
        }
    }
    Sol.NoConnectionDialog = NoConnectionDialog;
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class ClocksEditor extends Sol.MultipleField {
                constructor() {
                    super();
                    this.css.add("sol_clocks_editor");
                    this.editorProperty = "Clock";
                    this.onAddNew = () => this.createField();
                }
                deleteField(item) { this.controls.remove(item); }
                createField() { return new Sol.TimeField(); }
            }
            Components.ClocksEditor = ClocksEditor;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("ClocksEditor", () => new Sol.Web.Components.ClocksEditor());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class WorkTimeSum extends Sol.TimeStampField {
                get row() { return this.parent.parent; }
                build() {
                    super.build();
                    this.readonly = true;
                    this.savable = true;
                    this.clocksEditor = this.row.getEditor("Clocks");
                    this.clocksEditor.onValueModified.subscribe(() => this.calcTotal());
                    this.clocksEditor.onSet.subscribe(() => this.calcTotal());
                    this.clocksEditor.onDeleted.subscribe(() => this.calcTotal());
                    this.bonusEditor = this.row.getEditor("DayBonus");
                    this.bonusEditor.onValueModified.subscribe(() => this.calcTotal());
                }
                calcTotal() {
                    let data = {
                        clocks: this.clocksEditor.valueList,
                        dailyWork: this.row.getDataByPropertyName("DailyWork"),
                        bonus: this.bonusEditor.value
                    };
                    Web.System.exec("jjkeuap23", "CalculateHours", data, e => {
                        this.value = e.WorkTotal;
                        let dayBalanceField = this.row.getEditor("DayBalance");
                        dayBalanceField.value = e.DayBalance;
                        this.updateTotals();
                    });
                }
                updateTotals() {
                    let data = { sheetData: Web.System.screens.currentDetails.values };
                    Web.System.exec("jjkeuap23", "GetTimeSheetTotals", data, e => {
                        Web.System.screens.currentDetails.setEditorValue("MonthBalance", e.MonthBalance);
                        Web.System.screens.currentDetails.setEditorValue("OvertimeHundredPercent", e.OvertimeHundredPercent);
                        Web.System.screens.currentDetails.setEditorValue("OvertimeFiftyPercent", e.OvertimeFiftyPercent);
                    });
                }
            }
            Components.WorkTimeSum = WorkTimeSum;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("WorkTimeSum", () => new Sol.Web.Components.WorkTimeSum());
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class PayedHoursField extends Sol.TimeStampField {
                build() {
                    super.build();
                    this.savable = true;
                    this.onValueModified.subscribe(() => this.updateTotals());
                }
                updateTotals() {
                    let data = { sheetData: Web.System.screens.currentDetails.values };
                    Web.System.exec("jjkeuap23", "GetTimeSheetTotals", data, e => {
                        Web.System.screens.currentDetails.setEditorValue("MonthBalance", e.MonthBalance);
                        Web.System.screens.currentDetails.setEditorValue("OvertimeHundredPercent", e.OvertimeHundredPercent);
                        Web.System.screens.currentDetails.setEditorValue("OvertimeFiftyPercent", e.OvertimeFiftyPercent);
                    });
                }
            }
            Components.PayedHoursField = PayedHoursField;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
Sol.Web.Editors.registerEditor("PayedHoursField", () => new Sol.Web.Components.PayedHoursField());
var Sol;
(function (Sol) {
    var PaymentEngines;
    (function (PaymentEngines) {
        class MercadoPagoPaymentEngine extends Sol.Control {
            toControl() { return this; }
            constructor() {
                super();
                this.text = "Componente Mercado Pago";
            }
        }
        PaymentEngines.MercadoPagoPaymentEngine = MercadoPagoPaymentEngine;
    })(PaymentEngines = Sol.PaymentEngines || (Sol.PaymentEngines = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var SEI;
            (function (SEI) {
                class SEINumberField extends Sol.ExtensibleField {
                    constructor() {
                        super();
                        this.mainField.maxLength = 10;
                        this.mainField.inputOptions = { allowLetters: false, allowNumbers: true };
                        this.mainField.disableEnter = true;
                        this.mainField.onKeyDown = e => { if (e.key == "Enter")
                            this.onSearch(); };
                        let button = new Sol.Button();
                        button.imageCode = "&#xf002;";
                        button.tip = "Informe o nº do documento no SEI";
                        button.onClick = () => this.onSearch();
                        this.add(button);
                        setTimeout(() => this.mainField.foco(), 400);
                    }
                }
                SEI.SEINumberField = SEINumberField;
            })(SEI = Components.SEI || (Components.SEI = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var SEI;
            (function (SEI) {
                class SEIImportDialog extends Sol.FormDialog {
                    constructor() {
                        super();
                        this.numberField = new SEI.SEINumberField();
                        this.nameField = new Sol.Field();
                        this.processField = new Sol.Field();
                        this.documentPanel = new Sol.Control();
                        this.title = "Importar arquivo do SEI";
                        this.ancho = 614;
                        let numberWrapper = new Sol.FieldWrapper();
                        numberWrapper.add(new Sol.Label("Informe o nº do arquivo SEI:"));
                        this.numberField.onSearch = () => this.searchDocument();
                        numberWrapper.add(this.numberField);
                        this.form.add(numberWrapper);
                        let nameWrapper = new Sol.FieldWrapper();
                        nameWrapper.add(new Sol.Label("Nome:"));
                        this.nameField.readonly = true;
                        this.nameField.ancho = 270;
                        nameWrapper.add(this.nameField);
                        this.documentPanel.add(nameWrapper);
                        let processWrapper = new Sol.FieldWrapper();
                        processWrapper.add(new Sol.Label("Nº do processo:"));
                        this.processField.readonly = true;
                        this.processField.ancho = 245;
                        processWrapper.add(this.processField);
                        this.documentPanel.add(processWrapper);
                        this.documentPanel.visible = false;
                        this.form.add(this.documentPanel);
                        this.form.okButton.text = "Importar";
                        this.form.okButton.enabled = false;
                    }
                    get fileDescription() { return this.nameField.value; }
                    build() {
                        super.build();
                        this.createBlocker();
                    }
                    searchDocument() {
                        this.form.hideMessages();
                        this.documentPanel.visible = false;
                        this.nameField.value = "";
                        this.processField.value = "";
                        this.form.okButton.enabled = false;
                        this.fileUrl = null;
                        this.fileType = null;
                        this.documentNumber = null;
                        if (this.numberField.isEmpty()) {
                            this.form.showError("Informe o campo do nº do documento SEI");
                            this.numberField.foco();
                            return;
                        }
                        Web.System.exec("512gVb9g", "SearchDocument", { number: this.numberField.value }, e => {
                            if (e.Fail) {
                                this.form.showError(e.ErrorMessage);
                                this.numberField.foco();
                                return;
                            }
                            this.nameField.value = `${e.Nome} ${e.NomeArvore}`;
                            this.processField.value = e.ProcedimentoFormatado;
                            this.fileUrl = e.LinkAcesso;
                            this.fileType = e.Nome;
                            this.documentPanel.visible = true;
                            this.form.okButton.enabled = true;
                            this.documentNumber = this.numberField.textValue;
                        });
                    }
                }
                SEI.SEIImportDialog = SEIImportDialog;
            })(SEI = Components.SEI || (Components.SEI = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            var SEI;
            (function (SEI) {
                class SEIFilePlugin {
                    configure(component) {
                        this.component = component;
                        let seiButton = new Sol.Button();
                        seiButton.imageKey = "sei";
                        seiButton.tip = "Importa um arquivo do SEI";
                        seiButton.onClick = () => this.openDialog();
                        component.addToToolbar(seiButton);
                    }
                    openDialog() {
                        let dialog = new SEI.SEIImportDialog();
                        dialog.onClose = () => this.component.container.toControl().controls.remove(dialog);
                        dialog.onSave = () => this.download(dialog);
                        this.component.container.toControl().add(dialog);
                    }
                    download(dialog) {
                        let data = {
                            description: dialog.fileDescription,
                            fileType: dialog.fileType,
                            typeKey: this.component.documentTypeKey,
                            url: dialog.fileUrl,
                            docNumber: dialog.documentNumber
                        };
                        Web.System.exec("512gVb9g", "DownloadDocument", data, e => {
                            if (e.Fail)
                                return;
                            this.component.createItem(e.FileModel);
                            dialog.workComplete();
                            dialog.close();
                        });
                    }
                }
                SEI.SEIFilePlugin = SEIFilePlugin;
            })(SEI = Components.SEI || (Components.SEI = {}));
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
var Sol;
(function (Sol) {
    var Web;
    (function (Web) {
        var Components;
        (function (Components) {
            class UnreadMessagesWidget extends Sol.Control {
                constructor() {
                    super();
                    this.unreadTotal = new Sol.Label();
                    this.subtitleLabel = new Sol.Label();
                    this.rowContainer = new Sol.Control();
                    this.boxContainer = new Sol.Control();
                    this.actionsContainer = new Sol.Control();
                    this.css.addMany(["sol_compact_schedule", "sol_dashboard_box", "sol_messages_widget"]);
                    let refreshButton = new Sol.Button();
                    refreshButton.type = Sol.ButtonType.Custom;
                    refreshButton.imageCode = "&#xf021;";
                    refreshButton.css.add("sol_messages_refresh_button");
                    refreshButton.css.add("sol_messages_refresh_button");
                    refreshButton.onClick = () => Web.System.home.systemBar.refreshMailCounter();
                    this.add(refreshButton);
                    this.addCtr(Sol.Environment.resources.messagesAlert, "sol_dashboard_separator");
                    this.subtitleLabel.text = Sol.Environment.resources.messagesAlertSubtitle;
                    this.subtitleLabel.css.add("sol_messages_widget_subtitle");
                    this.add(this.subtitleLabel);
                    this.rowContainer.css.add("sol_messages_widget_row");
                    this.add(this.rowContainer);
                    const messageClassName = "Solarium.Messaging.Message, Solarium.Messaging, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null";
                    const messageScreenName = "Scussel.Models.Screens.MessageScreen";
                    this.boxContainer.css.add("sol_messages_widget_box");
                    this.rowContainer.add(this.boxContainer);
                    this.boxContainer.addCtr(Sol.Environment.resources.unreadTotal, "sol_messages_widget_legend");
                    this.unreadTotal.css.add("sol_messages_widget_total");
                    this.unreadTotal.onClick = () => Web.System.screens.openScreen(messageScreenName, messageClassName, null, null, null);
                    this.unreadTotal.estilos.agregar("cursor", "pointer");
                    this.boxContainer.add(this.unreadTotal);
                    this.boxContainer.addCtr(Sol.Environment.resources.messagesAwaiting, "sol_messages_box_footer");
                    this.actionsContainer.css.add("sol_messages_widget_actions");
                    this.rowContainer.add(this.actionsContainer);
                    this.markAllReadButton = new Sol.Button();
                    this.markAllReadButton.text = "Marcar todas como lidas";
                    this.markAllReadButton.type = Sol.ButtonType.Custom;
                    this.markAllReadButton.imageCode = "&#xf00c;";
                    this.markAllReadButton.css.add("sol_messages_button_mark_all_read");
                    this.markAllReadButton.onClick = () => {
                        Web.System.home.systemBar.markAllMailAsRead();
                    };
                    this.actionsContainer.add(this.markAllReadButton);
                    let openInboxButton = new Sol.Button();
                    openInboxButton.text = "Abrir caixa de entrada";
                    openInboxButton.type = Sol.ButtonType.Custom;
                    openInboxButton.imageCode = "&#xf01c;";
                    openInboxButton.css.add("sol_messages_button_open_inbox");
                    openInboxButton.onClick = () => Web.System.screens.openScreen(messageScreenName, messageClassName, null, null, null);
                    this.actionsContainer.add(openInboxButton);
                }
                build() {
                    Web.System.home.systemBar.onMailCounterUpdated.subscribe((value) => {
                        this.setCount(value);
                    });
                }
                setCount(count) {
                    this.messageCount = count;
                    this.unreadTotal.text = count === null || count === void 0 ? void 0 : count.toString();
                    const hasMessages = count > 0;
                    this.subtitleLabel.text = hasMessages ? Sol.Environment.resources.messagesAlertSubtitle : "Você não tem mensagens não lidas";
                    hasMessages ? this.unreadTotal.css.remove("sol_messages_widget_total_empty") : this.unreadTotal.css.add("sol_messages_widget_total_empty");
                    this.markAllReadButton.visible = hasMessages;
                }
            }
            Components.UnreadMessagesWidget = UnreadMessagesWidget;
        })(Components = Web.Components || (Web.Components = {}));
    })(Web = Sol.Web || (Sol.Web = {}));
})(Sol || (Sol = {}));
