const cuentas = { id: '#cuentas', categorias: [], get: function() { return { parent: () => { let parent = $(this.id) if (parent.length === 0) { const table = $('
').attr('class', 'ui striped table').append( $('').append( $('').append( $('').html('Cuenta') ).append( $('').attr('class', 'right aligned').html('Saldo') ) ) ) parent = $('').attr('id', this.id) table.append(parent) $('h1.header').after(table) } return parent }, categorias: () => { return $.ajax({ url: _urls.api + '/categorias', method: 'GET', dataType: 'json' }).then((data) => { if (data.categorias === null || data.categorias.length == 0) { return } this.categorias = data.categorias }).then(() => { this.draw().categorias() }) }, cuentas: (categoria_id) => { return $.ajax({ url: _urls.api + '/categoria/' + categoria_id + '/cuentas', method: 'GET', dataType: 'json' }).then((data) => { if (data.cuentas === null || data.cuentas.length == 0) { return } const idx = this.categorias.findIndex(el => { if (el.id == categoria_id) { return true } }) this.categorias[idx].cuentas = data.cuentas }).then(() => { this.draw().cuentas(categoria_id) }) } } }, remove: function() { return { cuentas: (categoria_id) => { const idx = this.categorias.findIndex(el => { if (el.id == categoria_id) { return true } }) const parent = $("[data-id='" + categoria_id + "']") for (let i = 0; i < this.categorias[idx].cuentas.length; i ++) { parent.next().remove() } } } }, draw: function() { return { categorias: () => { const parent = this.get().parent() $.each(this.categorias, (i, el) => { const button = $('').attr('class', 'ui mini compact icon button').append( $('').attr('class', 'plus icon') ).click((e) => { const plus = button.find('.plus') if (plus.length == 0) { console.debug(e.target) this.remove().cuentas(el.id) button.find('i.icon').removeClass('minus').addClass('plus') } else { console.debug(e.target) this.get().cuentas(el.id) button.find('i.icon').removeClass('plus').addClass('minus') } }) const f = $('').attr('data-id', el.id).append( $('').append( $('
').append(button).append(el.nombre) ) ).append( $('').attr('class', 'right aligned').html(el.saldoFormateado) ) parent.append(f) }) }, cuentas: (categoria_id) => { const idx = this.categorias.findIndex(el => { if (el.id == categoria_id) { return true } }) const parent = $("[data-id='" + categoria_id + "']") $.each(this.categorias[idx].cuentas, (i, el) => { parent.after( $('').attr('class', 'item').append( $('').append( $('').attr('href', _urls.base + 'cuenta/' + el.id).html(el.nombre) ) ).append( $('').attr('class', 'right aligned').html(el.saldoFormateado) ) ) }) } } }, setup: async function() { this.get().categorias() } }