PaperBag/www/plan/product.js

96 lines
3.4 KiB
JavaScript

/*
Function productSearchEvent( event )
This function is intended to run on `onKeyUp` and `onChange` events for a text-input.
*/
function productSearchEvent(event){
const itemNameElem = $(event.target);
let search = itemNameElem.val();
let formElem = itemNameElem.closest('form');
if(formElem.find('.itemSearchDropdown').length === 0){
formElem.append('<div class="itemSearchDropdown" style="display: none;"></div>');
}
const searchDropdown = formElem.find('.itemSearchDropdown');
searchDropdown.hide().html('');
let productSearch = new ProductSearch(itemNameElem, searchDropdown);
if(search.length > 2){
productSearch.search(search);
}
else {
searchDropdown.hide().html('');
}
}
let apiProductSearchTimer; // used for the product search timeout
class ProductSearch {
constructor(textInput, dropdownElem) {
this.textInput = textInput;
this.dropdownElem = dropdownElem;
}
search(search){
// apiProductSearchTimer declared in upper scope
clearTimeout(apiProductSearchTimer);
apiProductSearchTimer = setTimeout(()=>{
$.getJSON('/api/v1/product/'+search).done(json => {
this.dropdownElem.hide().html('');
for (const resultKey in json.data) {
const result = json.data[resultKey];
let searchResHtml = "";
if(typeof result.price !== "undefined"){
let priceAge = priceAgeFormat(result.price.age);
searchResHtml =
"<li data-name='"+result.name+"' data-price='"+(result.price.price || 0)+"'>" +
" <div style='flex: 65%;'>"+result.name+"</div>" +
" <div style='flex: 35%;'><span class='priceWrapper price' style='color: "+priceAge.color+"' title='"+priceAge.text+"\n"+(result.price.updated || '')+"'>"+(result.price.price.toFixed(2))+"</span></div>" +
"</li>";
}
else {
searchResHtml =
"<li data-name='"+result.name+"' data-price='0'>" +
" <div style='float: left;'>"+result.name+"</div>" +
"</li>";
}
this.dropdownElem.show().append(searchResHtml);
}
this.dropdownElem.find('li').on('click', ev => { this.priceClick(ev); });
});
}, 500);
}
priceClick(ev){
let clickedResult = $(ev.currentTarget);
let prodName = clickedResult.attr('data-name');
let prodPrice = clickedResult.attr('data-price');
console.log(prodName, prodPrice);
this.textInput.val(prodName)
this.textInput.parent().parent().find('.newItemPrice').val(prodPrice);
this.dropdownElem.hide().html('');
}
}
function priceAgeFormat(age){
let price = {};
if(age <= 4) {
price.color = "var(--bs-success)";
price.text = "Price is updated within the last 4 days";
}
else if(age <= 14) {
price.color = "var(--bs-warning)";
price.text = "Price is updated within the last 2 weeks";
}
else {
price.color = "var(--bs-danger)";
price.text = "Price was last updated more than 2 weeks ago";
}
return price;
}