Skip to content

Instantly share code, notes, and snippets.

@jesuslerma
Created June 19, 2015 21:38
Show Gist options
  • Save jesuslerma/d45e8bf10b2e8d066595 to your computer and use it in GitHub Desktop.
Save jesuslerma/d45e8bf10b2e8d066595 to your computer and use it in GitHub Desktop.
Example of js
<ul class="nav nav-tabs">
<li class="active"><a href="#sections" data-toggle="tab">Secciones</a></li>
<!-- <li><a href="#revenues" data-toggle="tab">Ingresos vs Egresos</a></li> -->
</ul>
<div class="tab-content">
<div id="sections" class="tab-pane active">
<div class="row">
<div class="span2 offset10">
<a class="btn" role="button" href="#setting_modal"
data-toggle="modal">
<i class="icon-cog"></i>
Configurar
</a>
</div>
</div>
<div class="centered">
<%= image_tag("ajax-loader.gif", :id=> "loader") %>
</div>
<div id="estado_resutados_container"></div>
</div>
<div id="revenues" class="tab-pane">
<table class="display">
<thead>
<tr>
<th><h2>Ingresos</h2></th>
</tr>
<tr>
<th></th>
<th>Enero</th>
<th>Febrero</th>
<th>Marzo</th>
<th >Abril</th>
<th >Mayo</th>
<th >Junio</th>
<th>Julio</th>
<th>Agosto</th>
<th>Septiembre</th>
<th>Octubre</th>
<th>Noviembre</th>
<th>Diciembre</th>
<th>Total</th>
</tr>
</thead>
<%@ingresos_h.each do |c|%>
<%if c[1].map{ |h| h[1].to_f}.sum != 0.0%>
<tr >
<%suma = 0%>
<td><%=c[0].split('|||')[0]%></td>
<%c[1].each do |mes|%>
<td>
<%mes_auxiliar = "01-"+mes[0].rjust(2,'0')+"-"+params[:year]
suma += mes[1].to_f%>
<%=link_to number_to_currency(mes[1]), auxiliar_de_cuentas_path(:prueba =>{:fecha_inicial => mes_auxiliar.to_date, :fecha_final => mes_auxiliar.to_date.end_of_month, :cuenta_contable_id=> c[0].split('|||')[1]})%>
</td>
<%end%>
<th>
<%=number_to_currency(suma)%>
</th>
</tr>
<%end%>
<%end%>
<tfoot>
<tr>
<td></td>
<%@suma_meses_ingresos.each do |s|%>
<th><%=number_to_currency(s[1])%></th>
<%end%>
<td></td>
</tr>
</tfoot>
</table>
<table class="display">
<thead>
<tr>
<th><h2>Egresos</h2></th>
</tr>
<tr>
<th></th>
<th>Enero</th>
<th>Febrero</th>
<th>Marzo</th>
<th >Abril</th>
<th >Mayo</th>
<th >Junio</th>
<th>Julio</th>
<th>Agosto</th>
<th>Septiembre</th>
<th>Octubre</th>
<th>Noviembre</th>
<th>Diciembre</th>
<th>Total</th>
</tr>
</thead>
<%@egresos_h.each do |c|%>
<%if c[1].map{ |h| h[1].to_f}.sum != 0.0%>
<tr >
<% suma = 0 %>
<td><%= c[0].split('|||')[0] %></td>
<%c[1].each do |mes|%>
<td>
<%mes_auxiliar = "01-"+mes[0].rjust(2,'0')+"-"+params[:year]
suma += mes[1].to_f
%>
<%=link_to number_to_currency(mes[1]), auxiliar_de_cuentas_path(:prueba =>{:fecha_inicial => mes_auxiliar.to_date, :fecha_final => mes_auxiliar.to_date.end_of_month, :cuenta_contable_id=> c[0].split('|||')[1]})%>
</td>
<%end%>
<th>
<%=number_to_currency(suma)%>
</th>
</tr>
<%end%>
<%end%>
<tfoot>
<tr>
<td></td>
<%@suma_meses_egresos.each do |s|%>
<th><%=number_to_currency(s[1])%></th>
<%end%>
<td></td>
</tr>
</tfoot>
</table>
<table class="display">
<thead>
<tr>
<th><h2>Utilidad</h2></th>
</tr>
<tr>
<th></th>
<th>Enero</th>
<th>Febrero</th>
<th>Marzo</th>
<th >Abril</th>
<th >Mayo</th>
<th >Junio</th>
<th>Julio</th>
<th>Agosto</th>
<th>Septiembre</th>
<th>Octubre</th>
<th>Noviembre</th>
<th>Diciembre</th>
</tr>
</thead>
<tr>
<td></td>
<%@suma_meses_ingresos.each do |s|%>
<td><%=number_to_currency(@suma_meses_ingresos[s[0]] - @suma_meses_egresos[s[0]])%></td>
<%end%>
</tr>
</table >
</div>
<div class="modal hide fade " id="setting_modal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">&times;</button>
<h3>Configurar Estado de Resultados</h3>
</div>
<div class="modal-body">
<form class="form-inline" id="form_add_section">
<input type="text" class="input-medium" placeholder="Sección">
<input type="text" class="input-mini" id="secuencia"
placeholder="Secuencia">
<select class="input-mini" id="tipo">
<option value="suma">Suma</option>
<option value="resta">Resta</option>
<option value="calculo">Cálculo</option>
</select>
<button type="submit" class="btn btn-primary">Agregar Sección</button>
<span class="text-error" id="error_adding_section"></span>
</form>
<div id="section_container" class="accordion">
</div>
</div>
<div class="modal-footer">
<a href="#" class="btn btn-primary">Actualizar Balanza</a>
</div>
</div>
<script type="text/template" id="section_types_template" class="template">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle collapsed" data-toggle="collapse"
data-parent="#section_container" href="#collapse-{{=id}}">
{{= section_name }}
<button type="button" class="close del-section-balanza"
aria-hidden="true" data-id="{{=id}}">
&times;
</button>
</a>
</div>
<div id="collapse-{{=id}}" class="accordion-body collapse ">
<div class="accordion-inner">
<div class="row">
<div class="span2">
<select class="input-medium">
{{=cuenta_contables}}
</select>
</div>
<div class="span2">
<a class="btn btn-primary add_cuenta_contable" data-id="{{=id}}">
Agregar
</a>
</div>
</div>
<div class="cuenta_contable_section">
{{ _.each(data, function(cuenta_contable) { }}
<div class="row">
<div class="span2">
{{= cuenta_contable.nombre}}
</div>
<div class="span2">
<a class="btn btn-danger del-cuenta-contable"
data-id="{{= cuenta_contable.id }}"
data-section-balanza-id="{{= id }}">
Eliminar
</a>
</div>
</div>
{{ }); }}
</div>
</div>
</div>
</script>
<script type="text/template" id="saldo_cuenta_contable_item" class="template">
{{ i=0;}}
{{ _.each(data, function(month) { }}
<tr data-parent-id="{{= id}}" class="row_not_collapsed">
<td >{{= Object.keys(data)[i] }}</td>
{{i=i+1}}
{{ $.each(month, function(name,value) { }}
{{ if (name !== "id") { }}
<td>
{{ year = 2015; }}
{{ if (name === "12") { }}
{{ fi = new Date(year, 11, 1); }}
{{ f_ini = fi.getUTCDate()+'/'+(fi.getMonth()+1)+'/'+fi.getFullYear() }}
{{ console.log(typeof(name)) }}
{{ } else { }}
{{ fi = new Date(year, name, 1); }}
{{ f_ini = fi.getUTCDate()+'/'+fi.getMonth()+'/'+fi.getFullYear() }}
{{ } }}
{{ ff = new Date(year, name, 0); }}
{{ f_fin = ff.getUTCDate()+'/'+(ff.getMonth() + 1)+'/'+ff.getFullYear() }}
{{ url = "/auxiliar_de_cuentas"; }}
{{ url = url + "?prueba[cuenta_contable_id]="+month.id; }}
{{ url = url + "&prueba[fecha_inicial]="+f_ini; }}
{{ url = url + "&prueba[fecha_final]="+f_fin; }}
<a href="{{=url}}">
{{= numeral(Math.abs(value.total)).format('$0,0.00') }}
</a>
</td>
{{ } }}
{{ }); }}
</tr>
{{ }); }}
</script>
<script type="text/template" id="micro_template" class="template">
<table class="display table table-hover">
<thead>
<tr>
<th ></th>
<th>Enero</th>
<th>Febrero</th>
<th>Marzo</th>
<th>Abril</th>
<th>Mayo</th>
<th>Junio</th>
<th>Julio</th>
<th>Agosto</th>
<th>Septiembre</th>
<th>Octubre</th>
<th>Noviembre</th>
<th>Diciembre</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{{ _.each(data, function(section) { }}
<tr class="section_row section" data-id="{{= section.id}}">
<td >
{{ if (section.tipo === "suma") { }}
(+) {{= section.nombre }}
{{ } else if (section.tipo === "resta") { }}
(-) {{= section.nombre }}
{{ } else if (section.tipo === "calculo") { }}
(=) {{= section.nombre }}
{{ } }}
</td>
<td ><%= image_tag("ajax-loader.gif", :id=> "loader") %></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
</tr>
{{ }); }}
</tbody>
</table>
</script>
<script type="text/template" id="estado_resultadostemplate" class="template">
<table class="display table table-hover">
<thead>
<tr>
<th ></th>
<th>Enero</th>
<th>Febrero</th>
<th>Marzo</th>
<th>Abril</th>
<th>Mayo</th>
<th>Junio</th>
<th>Julio</th>
<th>Agosto</th>
<th>Septiembre</th>
<th>Octubre</th>
<th>Noviembre</th>
<th>Diciembre</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{{ i=0;}}
{{ _.each(data, function(month) { }}
<tr class="section" data-id="{{= month['id'] }}" data-collapsed="true">
<td >
(
{{ if(month['tipo'] === 'suma') { }}
<b>+</b>
{{ } else if(month['tipo'] === 'resta') { }}
<b>-</b>
{{ } else { }}
<b>=</b>
{{ } }}
)
{{= Object.keys(data)[i] }}
</td>
{{i=i+1}}
{{$.each(month, function(name,value) { }}
<td>
{{if (name !== "tipo" && name !== "id") {}}
{{= numeral(Math.abs(value)).format('$0,0.00') }}
{{ } }}
</td>
{{ }); }}
</tr>
{{ }); }}
</tbody>
</table>
</script>
var EstadoResultadosSnippet;
EstadoResultadosSnippet = (function () {
'use strict';
var init, bind;
var getSections, prtSection, displayError, hideError;
var hdlAddSection, hdlAddCuentaContable, hdlClickRow, hdlDelSectionBalanza;
var hdlDelCuentaContable, hdlDelSectionBalanza;
var clearCollapsed;
var fillCollapsed, fillEmtpyRows, fillEmptyTable, fillCalculos;
var getEstadoResultados;
var scsEstadoResultados, errEstadoResultados, scsAddCuentaContable, errAddCuentaContable;
var sections, counter;
init = function () {
bind();
counter = 0;
sections = [];
CategoriaEmpresa.loadCategories();
getSections();
SectionBalanza.init();
//getEstadoResultados();
};
getEstadoResultados = function () {
Empresa.getEstadoResultados(
window._rfc,
2015,
scsEstadoResultados,
errEstadoResultados);
};
scsEstadoResultados = function (data) {
var template, templateData;
$('#loader').hide();
_.templateSettings = {
interpolate: /\{\{\=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
templateData = {
data: data
}
console.log(Object.keys(templateData.data)[0])
template = _.template(
$( "script#estado_resultadostemplate").html()
);
$('#estado_resutados_container').append(template(templateData));
$('#estado_resutados_container').on('click', '.section', hdlClickRow);
};
errEstadoResultados = function (data) {
alert('Lo sentimos, no se pudo obtener el estado de resultados');
};
getSections = function () {
SectionBalanza.getSectionBalanzas(
window._rfc,
function (data) {
sections = data;
$.each(sections, function (idx, el) {
prtSection(sections[idx]);
});
fillEmptyTable(sections);
},
function () {
alert('No se pudo obtener la configuración del estado de resultados')
});
};
fillEmptyTable = function (data) {
var template, templateData;
$('#loader').hide();
_.templateSettings = {
interpolate: /\{\{\=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
templateData = {
data: data
};
template = _.template(
$( "script#micro_template").html()
);
$('#estado_resutados_container').append(template(templateData));
$('#estado_resutados_container').on('click', '.section', hdlClickRow);
fillEmtpyRows(data);
};
fillEmtpyRows = function (data) {
var sumatoria = [0,0,0,0,0,0,0,0,0,0,0,0, 0, 0];
var secciones = [];
var total_sections = data.length;
$.each(data, function(idx, section) {
SectionBalanza.getSaldos(
section.id,
{year: 2015},
function (data) {
var elem, td, i = 0, j = 0;
elem = $("tr[data-id='"+section.id+"']")[0];
section.estado_resultados = data;
secciones.push(section);
/*for (i = 1; i < 14; i = i + 1) {
sumatoria[i] = sumatoria[i] + data[i.toString()];
};*/
for (i = 1; i < 14; i = i + 1) {
/*if (section.tipo === "calculo") {
$($(elem).find('td')[i]).html(
numeral(Math.abs(sumatoria[i])).format('$0,0.00')
);
} else*/
if (section.tipo !== "calculo") {
$($(elem).find('td')[i]).html(
numeral(Math.abs( data[i.toString()])).format('$0,0.00')
);
}
}
if (secciones.length === total_sections) {
fillCalculos(secciones);
}
},
function () {
alert('Lo sentimos, no se pudo recuperar el saldo de la cuenta '+
section.nombre);
}
);
});
};
fillCalculos = function (data) {
var sorted_data = _.sortBy(data, 'secuencia');
var sumatoria = [0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var i = 0;
$.each(sorted_data, function (idx, section) {
var elem = $("tr[data-id='"+section.id+"']")[0];
for (i = 1; i < 14; i = i + 1) {
if ( section.tipo === "resta") {
sumatoria[i] = sumatoria[i] - section.estado_resultados[i.toString()];
} else {
sumatoria[i] = sumatoria[i] + section.estado_resultados[i.toString()];
}
if ( section.tipo === "calculo") {
$($(elem).find('td')[i]).html(
numeral(Math.abs(sumatoria[i])).format('$0,0.00')
);
// Determinar si el total es perdida o ganancia y pintarlo de un color particular.
if(sumatoria[i] >= 0.0){
$($(elem).find('td')[i]).addClass("text-info"); // bootstrap's class.
}else{
$($(elem).find('td')[i]).addClass("text-error");
}
}
};
});
};
prtSection = function (section) {
$('#section_container').unbind();
var value, template, templateData, data;
//las cuentas padre tienen como característica que el padre id es nulo
_.templateSettings = {
interpolate: /\{\{\=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
template = _.template(
$( "script#section_types_template").html()
);
templateData = {
section_name: section.nombre,
data: section.cuenta_contables,
id: section.id,
cuenta_contables: CategoriaEmpresa.prepareCategories()
};
$('#section_container').append(template(templateData));
$('#section_container').on('click', '.add_cuenta_contable',
hdlAddCuentaContable);
$('#section_container').on('click', '.del-cuenta-contable',
hdlDelCuentaContable);
$('#section_container').on('click', '.del-section-balanza',
hdlDelSectionBalanza);
};
bind = function () {
$('#form_add_section').submit(hdlAddSection);
};
displayError = function (text) {
$('#error_adding_section').html(text);
};
hideError = function () {
$('#error_adding_section').html('');
};
hdlDelSectionBalanza = function (event) {
var that;
if(confirm('¿Esta seguro que desea eliminar esta sección?')) {
that = this;
SectionBalanza.deleteSectionBalanzas($(this).data('id'),
function () {
$(that).parent().parent().parent().remove();
},
function () {
alert('Lo sentimos no se pudo eliminar la sección.')
}
);
}
};
hdlDelCuentaContable = function (event) {
var sbid, ccid, parent;
ccid = $(this).data('id');
sbid = $(this).data('section-balanza-id');
parent = $(this).parent().parent();
SectionBalanza.deleteCuentaContable(sbid, ccid,
function (data) {
$(parent).remove();
},
function () {
alert('Lo sentimos, no se pudo eliminar la cuenta contable.')
});
};
hdlClickRow = function (event) {
var sbid, that, collapsed;
collapsed = $(this).data('collapsed');
sbid = $(this).data('id');
that = $(this);
if (collapsed) {
$(this).data('collapsed', false);
fillCollapsed(that);
} else {
clearCollapsed(sbid);
$(this).data('collapsed', true);
}
};
clearCollapsed = function (section_id) {
var elems;
elems = $("tr[data-parent-id='"+section_id+"']");
console.log(elems)
$.each(elems, function (elem) {
$(elems).remove();
})
};
fillCollapsed = function (that) {
var sbid, templateData, template, templateSettings;
sbid = that.data('id');
SectionBalanza.getSaldoCuentaContables(
sbid,
function (data) {
console.log(data);
_.templateSettings = {
interpolate: /\{\{\=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
templateData = {
data: data.data,
id: sbid
}
template = _.template(
$( "script#saldo_cuenta_contable_item").html()
);
that.after(template(templateData));
},
function () {
alert("Lo sentimos no se pudo obtener el saldo de las subcuentas");
}
);
};
hdlAddSection = function (event) {
var section, nombre, new_section, secuencia, tipo;
event.preventDefault();
nombre = $( "#form_add_section > input:first" ).val();
secuencia = $( "#form_add_section > #secuencia" ).val();
tipo = $( "#form_add_section > #tipo" ).val();
if (nombre === ""){
displayError("Debe de ingresar un valor en el campo");
return false;
}
new_section = {
nombre: nombre,
secuencia: secuencia,
tipo: tipo,
empresa_rfc: window._rfc
};
SectionBalanza.createSectionBalanza(
new_section,
function (data) {
hideError();
section = {
nombre: nombre,
id: data.id,
cuentas: []
};
prtSection(section);
},
function () {
alert('Hubo un error tratando de crear la sección')
}
);
};
hdlAddCuentaContable = function () {
var section_balanza_id, cuenta_contable_id, parent, accordion;
section_balanza_id = $(this).data('id');
parent = $(this).parent().parent();
console.log(accordion)
cuenta_contable_id = $($(parent).find('select')[0]).val();
if (cuenta_contable_id === "") {
alert('Por favor seleccione una cuenta contable para continuar');
return false;
}
data = {
cuenta_contable_id: cuenta_contable_id
};
SectionBalanza.addCuentaContable(section_balanza_id, data,
scsAddCuentaContable, errAddCuentaContable);
};
scsAddCuentaContable = function (data) {
var accordion, sbid;
var i = 0, textToInsert = [];
sbid = data.section_balanza_id;
accordion = $('#collapse-'+sbid+' .cuenta_contable_section')[0];
textToInsert[i++] = '<div class="row">';
textToInsert[i++] = '<div class="span2">';
textToInsert[i++] = data.nombre;
textToInsert[i++] = '</div>';
textToInsert[i++] = '<div class="span2">';
textToInsert[i++] = '<a class="btn btn-danger del-cuenta-contable"';
textToInsert[i++] = 'data-id="'+data.id+'" data-section-balanza-id="'+sbid+'">';
textToInsert[i++] = 'Eliminar';
textToInsert[i++] = '</a>';
textToInsert[i++] = '</div>';
textToInsert[i++] = '</div>';
$(accordion).append(textToInsert.join(''));
};
errAddCuentaContable = function () {
alert('Lo sentimos no se pudo agregar la cuenta contable')
};
return {
init: init,
};
}());
$(document).on('ready', function () {
var container = document.getElementById('estado_resultadostemplate');
if (typeof window._rfc !== 'undefined')
if ( Utils.existsInDom(container))
EstadoResultadosSnippet.init();
});
var SectionBalanza;
SectionBalanza = (function () {
var init;
var createSectionBalanza, addCuentaContable, deleteCuentaContable;
var getCuentaContables, getSectionBalanzas, deleteSectionBalanzas;
var getSaldoCuentaContables;
var url;
init = function () {
url = '/api/v2/section_balanzas';
};
getSaldos = function (id, params, scs, err) {
$.ajax({
url: url+'/'+id+'/saldos',
data: params,
type: 'GET',
success: scs,
error: err
});
};
createSectionBalanza = function (params, scs, err) {
$.ajax({
url: url,
type: 'POST',
data : {
authenticity_token: window._token,
section_balanza: params},
success: scs,
error: err
});
};
addCuentaContable = function (id, data, scs, err) {
$.ajax({
url: url + '/' + id + '/cuenta_contables',
type: 'POST',
data : {
authenticity_token: window._token,
cuenta_contable: data},
success: scs,
error: err
});
};
deleteCuentaContable = function (id_section, id_cuenta, scs, err) {
$.ajax({
url: url + '/'+id_section +'/cuenta_contables/' + id_cuenta,
type: 'DELETE',
data : {
authenticity_token: window._token,
},
success: scs,
error: err
});
};
deleteSectionBalanzas = function (id_section, scs, err) {
$.ajax({
url: url + '/'+id_section,
type: 'DELETE',
data : {
authenticity_token: window._token,
},
success: scs,
error: err
});
};
getCuentaContables = function (id, scs, err) {
$.ajax({
url: url+'/'+id+'/cuenta_contables',
type: 'GET',
success: scs,
error: err
});
};
getSaldoCuentaContables = function (id, scs, err) {
$.ajax({
url: url+'/'+id+'/saldo_cuenta_contables',
type: 'GET',
success: scs,
error: err
});
};
getSectionBalanzas = function (empresa_rfc, scs, err) {
$.ajax({
url: Empresa.getUrl()+'/'+empresa_rfc+'/section_balanzas',
type: 'GET',
success: scs,
error: err
});
};
return {
init:init,
getSectionBalanzas: getSectionBalanzas,
getCuentaContables: getCuentaContables,
deleteCuentaContable: deleteCuentaContable,
addCuentaContable: addCuentaContable,
createSectionBalanza: createSectionBalanza,
deleteSectionBalanzas:deleteSectionBalanzas,
getSaldoCuentaContables: getSaldoCuentaContables,
getSaldos: getSaldos
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment