Skip to content

Instantly share code, notes, and snippets.

@MaizerGomes
Created September 26, 2016 11:44
Show Gist options
  • Save MaizerGomes/695fb9832b55ff7c2712e7e2749f0b73 to your computer and use it in GitHub Desktop.
Save MaizerGomes/695fb9832b55ff7c2712e7e2749f0b73 to your computer and use it in GitHub Desktop.
/**
* Created by Maizer on 26/09/2016.
*/
var eKutivaFn = {
helpers: {
count: function count(mixedVar, mode) {
// discuss at: http://locutus.io/php/count/
// original by: Kevin van Zonneveld (http://kvz.io)
// input by: Waldo Malqui Silva (http://waldo.malqui.info)
// input by: merabi
// bugfixed by: Soren Hansen
// bugfixed by: Olivier Louvignes (http://mg-crea.com/)
// improved by: Brett Zamir (http://brett-zamir.me)
// example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE')
// returns 1: 6
// example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE')
// returns 2: 6
var key
var cnt = 0
if (mixedVar === null || typeof mixedVar === 'undefined') {
return 0
} else if (mixedVar.constructor !== Array && mixedVar.constructor !== Object) {
return 1
}
if (mode === 'COUNT_RECURSIVE') {
mode = 1
}
if (mode !== 1) {
mode = 0
}
for (key in mixedVar) {
if (mixedVar.hasOwnProperty(key)) {
cnt++
if (mode === 1 && mixedVar[key] &&
(mixedVar[key].constructor === Array ||
mixedVar[key].constructor === Object)) {
cnt += count(mixedVar[key], 1)
}
}
}
return cnt
},
explode: function explode(delimiter, string, limit) {
// discuss at: http://locutus.io/php/explode/
// original by: Kevin van Zonneveld (http://kvz.io)
// example 1: explode(' ', 'Kevin van Zonneveld')
// returns 1: [ 'Kevin', 'van', 'Zonneveld' ]
if (arguments.length < 2 ||
typeof delimiter === 'undefined' ||
typeof string === 'undefined') {
return null
}
if (delimiter === '' ||
delimiter === false ||
delimiter === null) {
return false
}
if (typeof delimiter === 'function' ||
typeof delimiter === 'object' ||
typeof string === 'function' ||
typeof string === 'object') {
return {
0: ''
}
}
if (delimiter === true) {
delimiter = '1'
}
// Here we go...
delimiter += ''
string += ''
var s = string.split(delimiter)
if (typeof limit === 'undefined') return s
// Support for limit
if (limit === 0) limit = 1
// Positive limit
if (limit > 0) {
if (limit >= s.length) {
return s
}
return s
.slice(0, limit - 1)
.concat([s.slice(limit - 1)
.join(delimiter)
])
}
// Negative limit
if (-limit >= s.length) {
return []
}
s.splice(s.length + limit)
return s
},
number_format: function (number, decimals, decPoint, thousandsSep) {
number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number
var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
var s = ''
var toFixedFix = function (n, prec) {
var k = Math.pow(10, prec)
return '' + (Math.round(n * k) / k)
.toFixed(prec)
}
// @todo: for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
},
extenso: function (c) {
c = c.toString();
var ex = [
["zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"],
["dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"],
["cem", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"],
["mil", "milhão", "bilhão", "trilhão", "quadrilhão", "quintilhão", "sextilhão", "setilhão", "octilhão", "nonilhão", "decilhão", "undecilhão", "dodecilhão", "tredecilhão", "quatrodecilhão", "quindecilhão", "sedecilhão", "septendecilhão", "octencilhão", "nonencilhão"]
];
var a, n, v, i, n = c.replace(c ? /[^.\d]/g : /\D/g, "").split("."), e = " e ", $ = "metical", d = "centavo", sl;
for (var f = n.length - 1, l, j = -1, r = [], s = [], t = ""; ++j <= f; s = []) {
j && (n[j] = (("." + n[j]) * 1).toFixed(2).slice(2));
if (!(a = (v = n[j]).slice((l = v.length) % 3).match(/\d{3}/g), v = l % 3 ? [v.slice(0, l % 3)] : [], v = a ? v.concat(a) : v).length) continue;
for (a = -1, l = v.length; ++a < l; t = "") {
if (!(i = v[a] * 1)) continue;
i % 100 < 20 && (t += ex[0][i % 100]) ||
i % 100 + 1 && (t += ex[1][(i % 100 / 10 >> 0) - 1] + (i % 10 ? e + ex[0][i % 10] : ""));
s.push((i < 100 ? t : !(i % 100) ? ex[2][i == 100 ? 0 : i / 100 >> 0] : (ex[2][i / 100 >> 0] + e + t)) +
((t = l - a - 2) > -1 ? " " + (i > 1 && t > 0 ? ex[3][t].replace("ão", "ões") : ex[3][t]) : ""));
}
a = ((sl = s.length) > 1 ? (a = s.pop(), s.join(" ") + e + a) : s.join("") || ((!j && (n[j + 1] * 1 > 0) || r.length) ? "" : ex[0][0]));
a && r.push(a + (c ? (" " + (v.join("") * 1 > 1 ? j ? d + "s" : (/0{6,}$/.test(n[0]) ? "de " : "") + $.replace("l", "is") : j ? d : $)) : ""));
}
return r.join(e);
},
request: {
validate: function (el) {
var index;
var errors = [];
for (index = 0; index < el.length; ++index) {
if (!eKutivaFn.helpers.request.input(el[index])) {
errors.push(el[index]);
eKutivaFn.helpers.flasher('O campo <b>' + el[index].toUpperCase().replace('_', ' ') + '</b> é obrigatório!', 'danger');
}
}
return errors.length === 0;
},
input: function (input, defaults) {
if (!defaults) defaults = '';
var val = $('[name="' + input + '"]').val();
if (val == '') val = $('#' + input).val();
if (val == '') val = defaults;
return val;
},
data: function (input, prop, defaults) {
if (!defaults) defaults = '';
var val = $("#" + input).data(prop);
if (val == '') val = $('[name="' + input + '"]').data(prop);
if (val == '') val = defaults;
return val;
}
},
money: function (value) {
value = value.toString();
var result = Number(value.replace(',', ''));
if (isNaN(result)) return Number("0");
return result;
},
redirect_to: function (url, noBase) {
if (!url) {
window.location.href = eKutivaFn.helpers.makeURL('login');
} else {
if (noBase) {
window.location.href = url;
} else {
window.location.href = eKutivaFn.helpers.makeURL(url);
}
}
},
removeLine: function (line, callback) {
callback(line).parentNode.parentNode.remove();
},
processRequest: function (request) {
if (request.status === 401) {
eKutivaFn.helpers.redirect_to();
return false;
} else if (request.status === 404) {
eKutivaFn.helpers.flasher('Dados não encontrados!', 'danger');
return false;
} else if (request.status === 500) {
eKutivaFn.helpers.flasher('Aconteceu um erro!', 'danger');
return false;
}
return true;
},
getToken: function () {
var key = $('[name="_token"]').val();
if (!key) key = $('meta[name="_token"]').attr('content');
return key;
},
makeURL: function (url) {
return '/ekuescola/' + url;
},
confirmer: function (message, classe) {
if (!classe) classe = 'success';
bootbox.confirm({
size: 'small',
title: 'Atenção necessária!',
message: message,
buttons: {
'cancel': {
label: 'Não',
},
'confirm': {
label: 'Sim',
className: 'btn-' + classe + ' pull-right'
}
},
callback: function (result) {
if (!result) {
return false;
}
}
});
},
flasher: function (message, type) {
if (message !== null && typeof message === 'object' && message.status > 399) {
if (!eKutivaFn.helpers.processRequest(message)) return false;
if (!type) type = 'danger';
var errors = $.parseJSON(message.responseText);
$.each(errors, function (index, value) {
$.gritter.add({
title: 'Erro',
position: 'bottom-right',
text: value,
class_name: type
});
});
} else if (message !== null && typeof message === 'object') {
if (!type) type = 'success';
var messages = $.parseJSON(message.responseText);
$.each(messages, function (index, value) {
$.gritter.add({
title: 'Notificação',
position: 'bottom-right',
text: value,
class_name: type
});
});
} else {
if (!type) type = 'success';
$.gritter.add({
title: 'Notificação',
position: 'bottom-right',
text: message,
class_name: type
});
}
},
createLabel: function (name, value) {
var field = '';
field = '<label for="' + name + '">' + value + '</label>';
return field;
},
createSelectField: function (name, options) {
var field = '';
field = '<select name="' + name + '" id="' + name + '" class="form-control">' +
eKutivaFn.helpers.select(options) + '</select>';
return field;
},
createTextField: function (name, value, type, options) {
var field = '';
if (!value) value = '';
if (!options) options = '';
// if (hidden) type = 'hidden';
if (!type) type = 'text';
field = '<input ' + options + ' type="' + type + '" name="' + name + '" id="' + name + '" class="form-control" value="' + value + '"/>';
return field;
},
select: function (options) {
var result = '';
if (options !== null && typeof options === 'object') {
$.each(options, function (index, value) {
result += '<option value="' + value.id + '">' + value.name + '</option>';
});
}
return result;
}
},
scientificFields: {
disciplines: function (id) {
$.get('/ekuescola/scientificfields/' + id, function (result) {
$('[name="discipline_id"]').html(eKutivaFn.helpers.select(result));
});
}
},
curriculum: {
getDisciplines: function (curriculumID, courseID) {
if (!courseID || courseID === 0) return;
$.get(eKutivaFn.helpers.makeURL('curricularplans/' + curriculumID + '/' + courseID), function (result) {
$('#result').html(result);
});
},
createDiscipline: function () {
$.get(eKutivaFn.helpers.makeURL('curricularplans/create'), function (result) {
$('#result').html(result);
});
},
storeDiscipline: function () {
var formData = $("#newDiscipline").serialize() + "&_token=" + eKutivaFn.helpers.getToken();
$.post('/ekuescola/curricularplans', formData, function (result, status, xhr) {
eKutivaFn.helpers.flasher(xhr);
$('#refresher').click();
}).fail(function (xhr, status, error) {
eKutivaFn.helpers.flasher(xhr, 'danger');
});
}
},
myschool: {
getGrades: function (type) {
var formData = $("#mygrades").serialize() + "&_token=" + eKutivaFn.helpers.getToken() + "&type=" + type;
$.post(eKutivaFn.helpers.makeURL('mygrades'), formData, function (result, status, xhr) {
$('#result').empty().html(result);
}).fail(function (xhr, status, error) {
eKutivaFn.helpers.flasher(xhr, 'danger');
});
},
getPayments: function (type) {
var formData = $("#mypayments").serialize() + "&_token=" + eKutivaFn.helpers.getToken() + "&type=" + type;
$.post(eKutivaFn.helpers.makeURL('mypayments'), formData, function (result, status, xhr) {
$('#result').empty().html(result);
}).fail(function (xhr, status, error) {
eKutivaFn.helpers.flasher(xhr, 'danger');
});
},
},
payments: {
index: function () {
var studentId = eKutivaFn.helpers.request.input('student_id');
eKutivaFn.student.getIdByCode(studentId, function (id) {
eKutivaFn.helpers.redirect_to('students/' + id + '/payments');
});
},
recalculateTotal: function (line) {
var helpers = eKutivaFn.helpers;
var ammount = helpers.money(line.parentNode.previousSibling.textContent);
var total = helpers.money(helpers.request.input('total'));
total = total - ammount;
$("#total").val(total);
$("#total_words").text(helpers.extenso(total));
return line;
},
getTypes: function (obj) {
var tipo = obj.value;
var student = eKutivaFn.helpers.request.input('student_id');
var ammount = $("#payment_ammount").empty();
var desc = $("#payment_description").empty();
var helpers = eKutivaFn.helpers;
if (tipo == '') return;
switch (tipo) {
case 'fee':
this.getFees(student, function (fees) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', fees));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge));
})
});
break;
case 'enrollment':
desc.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', ''));
ammount.html(helpers.createTextField('charge_description', 'Inscrição Semestral', 'hidden'));
break;
case 'emolument':
this.getEmoluments(function (emoluments) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', emoluments));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge));
})
});
break;
case 'invoice':
this.getInvoices(student, function (invoices) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', invoices));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge, null, 'readonly'));
})
});
break;
case 'advance':
desc.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', ''));
ammount.html(helpers.createTextField('charge_description', 'Adiantamento de Valores', 'hidden'));
break;
}
},
addPayment: function () {
var helpers = eKutivaFn.helpers;
if (!helpers.request.validate(['charge_ammount', 'payment_types', 'charge_description'])) return false;
var ammount = helpers.money(helpers.request.input('charge_ammount'));
var total = helpers.money(helpers.request.input('total'));
var tipo_pagamento = $("#payment_types option:selected").text();
var tipo_pagamento_id = helpers.request.input('payment_types');
if (tipo_pagamento_id == 'enrollment' || tipo_pagamento_id == 'advance' || tipo_pagamento_id == 'other') {
var descritive = helpers.request.input('charge_description');
var descritive_id = helpers.request.input('charge_description');
} else {
var descritive = $("#charge_description option:selected").text();
var descritive_id = helpers.request.input('charge_description').split('|')[0];
}
var linha = '<tr>';
linha += '<td>' + tipo_pagamento + '<input type="hidden" name="payment_type[]" value="' + tipo_pagamento_id + '"></td>';
linha += '<td>' + descritive + '<input type="hidden" name="payment_descritive_id[]" value="' + descritive_id + '"><input type="hidden" name="payment_descritive[]" value="' + descritive + '"></td>';
linha += '<td class="text-right">' + ammount + '<input type="hidden" name="payment_ammount[]" value="' + ammount + '"></td>';
linha += '<td class="text-center"><a title="Eliminar" class="label label-danger" href="javascript:;" onclick="eKutivaFn.helpers.removeLine(this, eKutivaFn.payments.recalculateTotal);"><i class="fa fa-times"></i></a></td>';
linha += '<tr>';
var soma = total + ammount;
$("#total").val(soma);
$("#total_words").text(helpers.extenso(soma));
$("#table").append(linha);
// helpers.flasher('Valor total de ' + helpers.extenso(soma).toUpperCase(), 'warning');
},
getEmoluments: function (callback) {
$.get(eKutivaFn.helpers.makeURL('emoluments'), function (result, status, xhr) {
callback(result);
}).fail(function (xhr, status, error) {
eKutivaFn.helpers.flasher(xhr, 'danger');
});
},
getFines: function (callback) {
$.get(eKutivaFn.helpers.makeURL('fines'), function (result, status, xhr) {
callback(result);
}).fail(function (xhr, status, error) {
eKutivaFn.helpers.flasher(xhr, 'danger');
});
},
getFees: function (id, callback) {
var url = 'students/' + id + '/charges?type=unpaid';
if (!id) url = 'fees';
$.get(eKutivaFn.helpers.makeURL(url), function (result, status, xhr) {
callback(result);
}).fail(function (xhr, status, error) {
eKutivaFn.helpers.flasher(xhr, 'danger');
});
},
getInvoices: function (id, callback) {
$.get(eKutivaFn.helpers.makeURL('students/' + id + '/invoices?type=unpaid'), function (result, status, xhr) {
callback(result);
}).fail(function (xhr, status, error) {
eKutivaFn.helpers.flasher(xhr, 'danger');
});
}
},
charges: {
index: function () {
var studentId = eKutivaFn.helpers.request.input('student_id');
eKutivaFn.student.getIdByCode(studentId, function (id) {
eKutivaFn.helpers.redirect_to('students/' + id + '/charges');
});
},
getTypes: function (obj) {
var tipo = obj.value;
// var student = eKutivaFn.helpers.request.input('student_id');
var ammount = $("#payment_ammount").empty();
var desc = $("#payment_description").empty();
var payments = eKutivaFn.payments;
var helpers = eKutivaFn.helpers;
if (tipo == '') return;
switch (tipo) {
case 'fee':
payments.getFees(null, function (fees) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', fees));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge, null, 'readonly'));
})
});
break;
case 'other':
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', ''));
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createTextField('charge_description'));
break;
case 'emolument':
payments.getEmoluments(function (emoluments) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', emoluments));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge, null, 'readonly'));
})
});
break;
case 'fine':
payments.getFines(function (fines) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', fines));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge, null, 'readonly'));
})
});
break;
}
},
},
invoices: {
index: function () {
var studentId = eKutivaFn.helpers.request.input('student_id');
eKutivaFn.student.getIdByCode(studentId, function (id) {
eKutivaFn.helpers.redirect_to('students/' + id + '/invoices');
});
},
getTypes: function (obj) {
var tipo = obj.value;
var student = eKutivaFn.helpers.request.input('student_id');
var ammount = $("#payment_ammount").empty();
var desc = $("#payment_description").empty();
var payments = eKutivaFn.payments;
var helpers = eKutivaFn.helpers;
if (tipo == '') return;
switch (tipo) {
case 'fee':
payments.getFees(student, function (fees) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', fees));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge, null, 'readonly'));
})
});
break;
case 'newfee':
payments.getFees(null, function (fees) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', fees));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge, null, 'readonly'));
})
});
break;
case 'other':
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', ''));
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createTextField('charge_description'));
break;
case 'emolument':
payments.getEmoluments(function (emoluments) {
desc.html(helpers.createLabel('charge_description', 'Descrição') + helpers.createSelectField('charge_description', emoluments));
$("#charge_description").on('change', function (e) {
var val = helpers.request.input('charge_description').split('|');
var charge = helpers.money(val[1]);
ammount.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', charge, null, 'readonly'));
})
});
break;
case 'advance':
desc.html(helpers.createLabel('charge_ammount', 'Valor') + helpers.createTextField('charge_ammount', ''));
ammount.html(helpers.createTextField('charge_description', 'Adiantamento de Valores', 'hidden'));
break;
}
},
},
student: {
getIdByCode: function (code, callback) {
$.post(eKutivaFn.helpers.makeURL('student/getID'), {
_token: eKutivaFn.helpers.getToken(),
code: code
}, function (result, status, xhr) {
callback(result.id);
}).fail(function (xhr, status, error) {
eKutivaFn.helpers.flasher(xhr, 'danger');
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment