You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

444 lines
14 KiB

var active_timer = 100;
var calculation = [];
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function truncator(numToTruncate, intDecimalPlaces) {
var numPower = Math.pow(10, intDecimalPlaces); // "numPowerConverter" might be better
return ~~(numToTruncate * numPower)/numPower;
}
function init_edit(partID) {
$('table#details tr#type td p').hide();
$('#type-dropdown').show();
$('table#details tr#partno td p').hide();
$('input[name=partno-input]').show();
// $('#magical_autofill').show();
$('table#details tr#description td p').hide();
$('input[name=description-input]').show();
$('table#details tr#datasheet td input').closest().show();
$('table#details tr#datasheet td input').show();
$('#duplicate-button').closest('div').hide();
$('#delete-button').closest('div').hide();
$('tr#datasheet').show();
$('input[name=notes-input]').show();
$('table#details tr#notes td p').hide();
$('input[name=voltage-input]').show();
$('table#details tr#voltage td p').hide();
$('input[name=current-input]').show();
$('table#details tr#current td p').hide();
$('input[name=sleepcurrent-input]').show();
$('table#details tr#sleepcurrent td p').hide();
$('input[name=txrx-input]').show();
$('input[name=txrx-head]').show();
$('table#details tr#txrx td p').hide();
// var newButton = '<div class="round-button-left"><a href="#" onclick="save(' + partID + ')"><i class="fa fa-check" aria-hidden="true"></i></a></div>';
// $('.round-button-left').replaceWith(newButton);
$('#edit-button').html('<i class="fa fa-check" aria-hidden="true"></i>');
$('#edit-button').off('click').on('click', function(){
save(partID);
});
}
function new_entry() {
$('table#details tr#type td p').text('');
$('table#details tr#partno td p').text('');
$('table#details tr#description td p').text('');
$('table#details tr#partno td input').val('');
$('table#details tr#description td input').val('');
$('input[name=datasheet-url-input]').val('');
container_onchange();
init_edit(-1);
overlay_in();
}
function calculate() {
let total = 0;
count = Object.keys(calculation).length;
for(let m = 0; m < count; m++) {
let jsonParameters = calculation[m];
let obj = Object.keys(jsonParameters);
let values = Object.values(jsonParameters);
$.getJSON(rootURL + 'getpartinfo/' + jsonParameters["partid"], function(data) {
// $('table#calculations tr#results td p').text(data.partno+" "+jsonParameters["energy"]+" J over "+jsonParameters["period"]+" seconds");
// $('table#calculations tr#results td p').show();
total+= truncator(jsonParameters["energy"],5);
if($('table#calculations tr#'+jsonParameters["partid"]).length == 0) {
$('table#calculations').append('<tr id='+jsonParameters["partid"]+'><td><p>'+data.partno+" "+truncator(jsonParameters["energy"],5)+" J over "+jsonParameters["period"]+' seconds</p></td></tr>');
$('table#calculations tr#'+jsonParameters["partid"]+' td p').show();
}
$('#results td p').text("Total: "+truncator(total,5)+" J");
});
}
calculateoverlay_in();
}
function end_edit() {
$('table#details tr#type td p').text($('table#details tr#type td select option:checked').text());
$('table#details tr#type td p').show();
$('#type-dropdown').hide();
$('table#details tr#partno td p').text($('table#details tr#partno td input').val());
$('table#details tr#partno td p').show();
$('table#details tr#partno td input').hide();
// $('#magical_autofill').hide();
$('table#details tr#description td p').text($('table#details tr#description td input').val());
$('table#details tr#description td p').show();
$('table#details tr#description td input').hide();
$('tr#datasheet').hide();
$('input[name=notes-input]').hide();
$('table#details tr#notes td p').show();
$('#duplicate-button').closest('div').show();
$('#delete-button').closest('div').show();
$('#edit-button').html('<i class="fa fa-pencil" aria-hidden="true"></i>');
// var newButton = '<div class="round-button-left"><a href="#" id="edit-button"><i class="fa fa-pencil" aria-hidden="true"></i></a></div>';
// $('.round-button-left').replaceWith(newButton);
}
function save(partID) {
if (!$('#type-dropdown').val()) {
alert('Please select a component type.');
return;
}
var type_id_v = $('#type-dropdown').val();
var partno_v = $('input[name=partno-input]').val();
var description_v = $('input[name=description-input]').val();
var datasheet = $('table#details tr#datasheet td input')[0].files;
var datasheet_url_v = $('input[name=datasheet-url-input]').val();
var notes_v = $('input[name=notes-input]').val();
var total = [];
var mapped = {};
$('.parameter-content').find('input').each(function(index,elem){
//8 console.log(elem.value);
total.push(elem.value);
mapped[elem.name] = elem.value;
});
//console.log(mapped);
if(partno_v.length == 0){
alert('Please enter a part number.');
return;
}
if(description_v.length > 200) {
alert('Description too long (max 200 characters).');
return;
}
if(description_v.length == 0) {
alert('Please enter a description.');
return;
}
var data = new FormData();
if (datasheet.length == 1) {
if(! datasheet[0]['name'].match(/^[\w\-]+\.pdf$/g)) {
alert('Invalid filename. Please match /^[\w\-]+\.pdf$/g');
return;
}
if (datasheet[0]['size'] > 20 * 1000000) {
alert('File too large. Must be < 20MB.');
return;
}
data.append('datasheet-file', datasheet[0]);
} else if (datasheet_url_v.length > 0) {
data.append('datasheet-url', datasheet_url_v);
}
data.append('partno', partno_v);
data.append('type_id', type_id_v);
data.append('description', description_v);
data.append('notes', notes_v);
data.append('parameters', JSON.stringify(mapped));
$.ajax({
// Your server script to process the upload
url: rootURL + 'alter/' + partID,
type: 'POST',
data: data,
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
success: function(data) {
var datasheet_par = '<p id="datasheet-info"><i class="fa fa-check"></i></p>';
$('#datasheet-info').replaceWith(datasheet_par); // Fix addressing
$('#edit-button').click(function() {
init_edit(JSON.parse(data).part_id);
});
},
error: function() {
alert("Couldn't update the part information. Please retry.");
}
});
end_edit();
perform_query();
}
function text_filter(string) {
if (string != null)
return string;
else
return '';
}
function delete_entry(partID) {
if (partID < 0)
return;
if (!confirm('Delete the selected entry?'))
return;
$.ajax({
url: rootURL + 'delete/' + partID,
type: 'GET',
cache: false,
contentType: false,
processData: false,
success: function() {
overlay_out();
perform_query();
},
fail: function() {
console.log('An error occurred while deleting the entry');
},
});
}
function calculate_entry(partID,jsonParameters) {
if (partID < 0)
return;
if (!confirm('Add selected entry to calculation?'))
return;
if(jsonParameters != null) {
// for(var k = 0; k < count; k++) {
var obj = Object.keys(jsonParameters);
var values = Object.values(jsonParameters);
var voltage = 0;
var activepower = 0;
var sleeppower = 0;
var single_period = 0;
//console.log(obj);
for (var key in obj) {
var value = obj[key];
var numbers = values[key]
//console.log(key+":"+value+":"+numbers);
if(value.includes('voltage')) {
voltage = values[key];
}
else if(value.includes('current')) {
if(value.includes('sleep')) {
sleeppower = Number(values[key]);
}
else {
activepower+=Number(values[key]);
}
}
else if(value.includes('mode')) {
single_period=Number(values[key])+Number(single_period);
if(value.includes('sleep')) {
sleeppower=sleeppower*Number(values[key]);
}
else {
activepower=activepower*Number(values[key]);
}
}
else {
console.log("Unconfigured: "+value+":"+values[key]);
}
}
jsonParameters["energy"]=voltage*(sleeppower+activepower);
jsonParameters["period"]=single_period;
jsonParameters["partid"]=partID;
calculation.push(jsonParameters);
}
overlay_out();
}
function show_part_info(partID) {
$.getJSON(rootURL + 'getpartinfo/' + partID, function(data) {
$('img#map').attr('src', 'parts/map/' + data.type_id);
$('#type-dropdown').empty();
$.getJSON('/getTypes', function(json) {
$.each(json, function(type_id, type_name) {
$('#type-dropdown').append('<option value="' + type_id + '">' + type_name + '</option>');
if (data.type_id == type_id) {
$('table#details tr#type td p').text(text_filter(type_name)); // name is the type friendly name
}
});
$('#type-dropdown').val(data.type_id);
});
$('table#details tr#partno td p').text(text_filter(data.partno));
$('table#details tr#partno td input').val(text_filter(data.partno));
$('table#details tr#description td p').text(text_filter(data.description));
$('table#details tr#description td input').val(text_filter(data.description));
$('table#details tr#notes td p').text(text_filter(data.notes));
$('input[name=notes-input]').val(text_filter(data.notes));
if(data.parameters != null) {
var jsonParameters = JSON.parse(data.parameters);
var count = Object.keys(jsonParameters).length;
// for(var k = 0; k < count; k++) {
var obj = Object.keys(jsonParameters);
var values = Object.values(jsonParameters);
for (var key in obj) {
var value = obj[key];
if(value.includes("input") && $('table#details tr#'+value.substring(0,value.indexOf("-"))).children().length == 0 ) {
$('table#details').append('<tr id='+value.substring(0,value.indexOf("-"))+'><td><p></p><input type="text" name='+value+' class="pinfo-input"></td></tr>')
$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td p').text(capitalizeFirstLetter(value.substring(0,value.indexOf("-"))));
$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td p').show();
$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td input').val(values[key]);
$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td input').show();
}
else {
$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td p').text(capitalizeFirstLetter(value.substring(0,value.indexOf("-"))));
$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td p').show();
$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td input').val(values[key]);
$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td input').show();
}
}
}
// }
// Resetting file input. Super dirty hack. Disgusting
var $el = $('#datasheet-finput');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();
if (data.datasheet != null) {
$('tr#datasheet-head').html($('<td>DATASHEET: <a href="' + data.datasheet + '" target="_blank"><i class="fa fa-file-text" aria-hidden="true"></i></a></td>'));
$('input[name=datasheet-url-input]').val(data.datasheet);
}
else {
$('tr#datasheet-head td').text('DATASHEET: ');
$('input[name=datasheet-url-input]').val('');
}
$('#edit-button').off('click').on('click', function() {
init_edit(partID);
});
$('#delete-button').off('click').on('click', function() {
delete_entry(partID);
});
$('#calculate-add-button').off('click').on('click', function() {
for (var key in obj) {
var value = obj[key];
jsonParameters[value]=$('table#details tr#'+value.substring(0,value.indexOf("-"))+' td input').val();
}
calculate_entry(partID,jsonParameters);
});
overlay_in();
}).fail(function() {
console.log( "Fetching part info failed" );
});
}
function perform_query() {
$('#no-results').stop();
$('#no-results').css("opacity", 0);
$('#no-results').hide();
var query = $('.search-bar').val();
var data = {
l:$('#type').is(':checked'),
p:$('#partno').is(':checked'),
d:$('#description').is(':checked')
};
filter = '0';
$("#results").find("tr:not(:first)").remove(); // Delete all table rows
var queryPromise = $.getJSON(rootURL + 'query/' + filter + '/' + query, data, function(data) {
for(var i = 0; i < data.length; i++) {
var newRow = $('<tr onclick="show_part_info(' + data[i].id + ')"></tr>');
newRow.append($('<td id="type"></td>').text(text_filter(data[i].type_descriptor)));
newRow.append($('<td id="partno"></td>').text(text_filter(data[i].partno)));
newRow.append($('<td id="description"></td>').text(text_filter(data[i].description)));
$('#results').append(newRow);
}
if(data.length == 0) {
$('#no-results').show();
$('#no-results').animate({opacity:1},2000);
}
}).fail(function() {
$('#no-results').show();
$('#no-results').animate({opacity:1},2000);
console.log( "Query failed" );
});
//});
}
function container_onchange() {
var selected_container_id = $('#type-dropdown').val();
// if (selected_container_id > 0) {
//$('#type-dropdown').empty();
$.getJSON('/getTypes', function(data) {
$.each(data, function(type_id, type_name) {
$('#type-dropdown').append('<option value="' + type_id + '">' + type_name + '</option>');
if (data.type_id == type_id) {
$('table#details tr#type td p').text(text_filter(type_name)); // name is the type friendly name
}
});
});
// }
}
function octopartFetch(){
$('#magic-autofill-button').attr('disabled', 'disabled');
$.getJSON(rootURL + 'fetchOctopartSnippet/' + $('#partno-input').val()).done(function(json){
$('#magic-autofill-button').removeAttr('disabled');
if (json['result']=='ok'){
$('#description-input').val(json['snippet']);
}else{
$('#description-input').val('');
$('#description-input').attr('placeholder', json['result']);
}
}).fail(function() {
$('#magic-autofill-button').removeAttr('disabled');
});
}
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$('.search-bar').on('keyup', function() {
clearTimeout(active_timer);
active_timer = setTimeout(perform_query, 100);
});
$('.checkbox').change( function() {
if ( !$('#type').is(':checked')
&& !$('#partno').is(':checked')
&& !$('#description').is(':checked')
&& !$('#has-docs').is(':checked'))
$(this).prop('checked', true);
else
perform_query();
});
// $('#partno-input').bind('blur',function() {
// if($('#partno-input').val().length > 0){
// octopartFetch();
// }
// });
});