PaperBag/www/plan/plan.js

600 lines
22 KiB
JavaScript

/*jshint sub:true, esversion: 6, -W083 */
class Store {
constructor(title, storeID, state) {
this.items = [];
this.state = state || 'planning'; // states: planning/shopping/closed
let storeNum = $(".store").length+1;
this.title = title || "Store "+storeNum;
this.storeID = storeID || null;
let html = "";
html += "<div class='card store' style='width: 25rem; max-width: 90vw;'>";
html += " <div class='card-header'>"+this.title+"</div>";
html += " <div class='iconWrapper' style='float: left; margin-top: -35px; margin-left: 1px;'>";
html += " <nav aria-label='State changer'><ul class='pagination'>";
html += " <li class='page-item planningState "+(this.state === 'planning'?"active":"")+"'><span class='page-link'><img src='../icon/list-check.svg' class='ariaButton' alt='Planning state' title='Planning state' data-toggle='tooltip' tabindex=0 role='button' /></span></li>";
html += " <li class='page-item shoppingState "+(this.state === 'shopping'?"active":"")+"'><span class='page-link'><img src='../icon/basket2.svg' class='ariaButton' alt='Shopping state' title='Shopping state' data-toggle='tooltip' tabindex=0 role='button' /></span></li>";
html += " <li class='page-item closedState "+(this.state === 'closed'?"active":"")+"'><span class='page-link'><img src='../icon/check-all.svg' class='ariaButton' alt='Closed state' title='Closed state' data-toggle='tooltip' tabindex=0 role='button' /></span></li>";
html += " </ul></nav>";
html += " </div>";
html += " <div class='iconWrapper'>";
html += " <img src='../icon/pencil-square.svg' class='editStoreName ariaButton' alt='edit name' data-toggle='tooltip' title='Edit store name' tabindex=0 role='button' />";
// html += " <img src='../icon/filter-square.svg' class='sortItems ariaButton' alt='sort items' data-toggle='tooltip' title='Sort items by appearance in store' tabindex=0 role='button' />";
html += " <img src='../icon/x-circle.svg' class='removeStore ariaButton' alt='remove store' data-toggle='tooltip' title='Remove store' tabindex=0 role='button' />";
html += " </div>";
html += " <div class='card-body'>";
html += " <div class='draggable' style='width: 100%; height: 10px; border-width: 1px;'></div> <ul class='list-group list-group-flush storeItems'>";
html += " <li class='list-group-item emptyList'>No items added</li>";
html += " </ul>";
html += " <span class='addItemFormWrapper'>";
html += " <hr>";
html += " <form action='#!' class='form-row input-group input-group-sm addItemForm'>";
// html += " <input type='text' class='form-control newItemName' placeholder='New Item Name' data-toggle='tooltip' title='New Item Name' aria-label='New Item Name'>";
// html += " <input type='number' class='form-control newItemPrice' value='0' min='0' step='.01' data-toggle='tooltip' title='Price' aria-label='Price'>";
html += " <div class='form-control form-floating'>";
html += " <input type='text' id='newItemName0' class='form-control newItemName' placeholder='New Item Name' aria-label='New Item Name'>";
html += " <label for='newItemName0'>New Item Name</label>";
html += " </div>";
html += " <div class='form-control form-floating'>";
html += " <input type='number' id='newItemPrice0' class='form-control newItemPrice' value='0' min='0' step='.01' aria-label='Price'>";
html += " <label for='newItemPrice0'>Price</label>";
html += " </div>";
html += " <div class='input-group-append'>";
html += " <input type='image' class='form-control addItem' src='../icon/plus.svg' alt='+'>";
html += " </div>";
html += " </form>";
html += " </span>";
html += " </div>";
html += " <div class='card-footer subtotal'>Subtotal: <span class='priceWrapper price'>0.00</span></div>";
html += "</div>";
this.selector = $(html).appendTo("#stores");
this.selector.find(".addItemForm").on('submit', ev => {
ev.preventDefault();
this.addItem($(ev.target).find('.newItemName').val(), $(ev.target).find('.newItemPrice').val()).done(json => {
this.selector.find('.newItemPrice').val(0);
this.selector.find('.newItemName').val("").focus();
});
});
/** CHANGE STATE **/
this.selector.find('.iconWrapper .page-item').on('click', ev=>{
this.selector.find('.page-item.active').removeClass('active');
$(ev.currentTarget).addClass('active');
if($(ev.currentTarget).hasClass('planningState')){
this.setState('planning');
}
else if($(ev.currentTarget).hasClass('shoppingState')){
this.setState('shopping');
}
else if($(ev.currentTarget).hasClass('closedState')){
this.setState('closed');
}
});
this.selector.find('.editStoreName').one('click', ev => { this.editNameFn(ev); });
this.selector.find('.removeStore').on('click', ev => {
if(confirm("Are you sure you want to remove this store?")){ this.removeStore(); }
});
$(function () {
$('[data-toggle="tooltip"]').tooltip();
});
}
setState(state, animTime){
animTime = animTime || 200;
let prevState = this.state;
if(state === "planning"){
this.state = "planning";
this.selector.find('.itemAmountButtons').slideDown(animTime);
this.selector.find('.itemAmountText').slideUp(animTime);
this.selector.find('.addItemFormWrapper').slideDown(animTime);
}
if(state !== "planning"){
this.selector.find('.itemAmountButtons').slideUp(animTime);
this.selector.find('.itemAmountText:not(.oneItem)').slideDown(animTime);
this.selector.find('.addItemFormWrapper').slideUp(animTime);
}
if(state === "shopping"){
this.state = "shopping";
}
if(state !== "shopping"){
}
if(state === "closed"){
this.state = "closed";
this.selector.find('.remItem').hide();
}
if(state !== "closed"){
this.selector.find('.remItem').show();
}
if(prevState !== state){
ajaxReq({ plan: 'setState', storeID: this.storeID, state: this.state });
}
}
editNameFn(ev){
if(ev.type === 'click'){
this.selector.find('.iconWrapper').hide();
// $(ev.target).parent().hide();
let headerElem = $(ev.target).parent().parent().find(".card-header");
let orgHtml = headerElem.html();
headerElem.html("<span style='display: none;'>"+orgHtml+"</span><form action='#' class='changeNameForm'><input type='text' class='newName' value='"+orgHtml+"'><input type='image' src='../icon/pencil-square.svg'></form>");
headerElem.find(".changeNameForm").on('submit keyup', ev2 => {
if(ev2.type === "submit"){
ev2.preventDefault();
let newName = $(ev2.target).find(".newName").val();
let that = this;
this.rename(newName).done(json => {
// success
headerElem.html(newName);
that.selector.find('.iconWrapper').show();
that.selector.find('.editStoreName').one('click keyup', ev3 => { this.editNameFn(ev3); });
});
}
});
headerElem.find(".newName").on('keyup', ev3 => { this.resetEditNameFn(ev3); });
headerElem.find('input').first().focus();
// $("body").one('click', ev3 => { this.resetEditNameFn(ev3); });
}
}
resetEditNameFn(ev){
if(
(ev.type==="keyup" && ev.keyCode === 27) ||
ev.type !== "keyup"
){
// cancel
let orgHtml = this.selector.find('.card-header span').html();
this.selector.find('.card-header').html(orgHtml);
this.selector.find('.iconWrapper').show();
this.selector.find('.editStoreName').one('click keyup', ev3 => { this.editNameFn(ev3); });
}
}
addItem(text, price){
if(text.length > 0){
if(this.storeID === null){
this.getStoreID().done(json => { this.addItem(text, price); });
return $.ajax();
}
let that = this;
return ajaxReq({ plan: 'addItem', storeID: this.storeID, name: text, price: price })
.done(json => {
return that.addItemHtml(text, price, json['data']);
});
}
}
addItemHtml(text, price, itemID, amount){
amount = amount || 1;
try {
price = Number(price);
this.items.push({ text: text, price: price, itemID: itemID, amount: amount });
let html = "\n";
html += "<li class='list-group-item draggable' id='item_"+itemID+"' data-itemid='"+itemID+"' draggable='true'>";
html += " <span style='float: left;'>"+text+"</span>";
html += " <div class='priceWrapper'><span class='price'>"+(price*amount).toFixed(2)+"</span>";
html += "<img src='../icon/dash-circle.svg' alt='Remove item' class='remItem ariaButton' data-itemID='"+itemID+"' data-price='"+price+"' style='margin-right: 3px;' tabindex='0' role='button'></div>";
html += " <span class='itemAmountWrapper' style='float: left; padding: 0 10px;'>";
html += " <div class='input-group itemAmountButtons' >"; // "+(this.state !== "planning"?"style='display: none;'":'')+"
html += " <button class='btn btn-outline-danger itemAmountBtn' type='button'>-</button>";
html += " <input class='form-control itemAmount itemAmountBtn' type='number' value='"+amount+"' min='0' max='99' aria-label='Amount of item' >";
if(price !== 0) {
html += " <span class='input-group-text' style='padding-left: 3px; padding-right: 0; font-size: 12px;text-align: right;'>x<span class='price'>" + price.toFixed(2) + "</span></span>";
}
html += " <button class='btn btn-outline-success itemAmountBtn' type='button'>+</button>";
html += " </div>";
html += " <div class='itemAmountText "+(amount <= 1?"oneItem":"")+"' style='display: none;'>"; // "+(this.state !== "shopping"?"style='display: none;'":'')+"
html += " Amount: <span class='itemAmount' style='padding-left: 10px;'>"+amount+"</span>x <span class='price'>" + price.toFixed(2) + "</span>";
html += " </div>";
html += " </span>";
html += "</li>";
this.selector.find("ul.storeItems").append(html);
this.selector.find(".emptyList").hide();
this.verify();
return true;
}
catch(e){
alert("Something failed. Try again.");
console.error(e, e.stack);
}
return false;
}
remItem(pos, itemID, price){
let that = this;
if(this.state === "planning"){
return ajaxReq({ plan: 'remItem', storeID: this.storeID, itemID: itemID, price: price })
.done(json => {
// console.log("remItem return:", json);
return that.remItemHtml(itemID);
});
}
}
remItemHtml(itemID){
for(let i = 0; i < this.items.length; i++){
if(this.items[i].itemID === itemID){
this.items.splice(i,1);
break;
}
}
this.selector.find('#item_'+itemID).remove();
this.verify();
return true;
}
setItemAmount(itemID, amount){
// console.log(itemID, amount, this.items);
this.items.forEach((item, key) => {
if(item.itemID === itemID){
this.items[key].amount = amount;
this.selector.find('#item_'+itemID+" .priceWrapper .price").html(Number(amount*this.items[key].price).toFixed(2));
}
});
if(typeof this.itemAmountDelay === "undefined"){
this.itemAmountDelay = {};
}
if(typeof this.itemAmountDelay[itemID] !== "undefined"){ clearTimeout(this.itemAmountDelay[itemID]); }
this.itemAmountDelay[itemID] = setTimeout(() => {
return ajaxReq({ plan: 'updateItemAmount', storeID: this.storeID, itemID: itemID, newAmount: amount })
.done(()=>{ this.verify(); });
}, 500);
}
setItemPosition(itemID, afterID){
afterID = afterID || 0;
if(itemID !== afterID){
return ajaxReq({ plan: 'moveItem', storeID: this.storeID, itemID: itemID, afterID: afterID });
}
return false;
}
verify(){
// UPDATE TOTAL PRICE
let total = 0;
this.items.forEach(item => {
total += item.price*item.amount;
// console.log("verify - item: "+item.price+"*"+item.amount);
});
$(this.selector).find(".subtotal .price").html(total.toFixed(2));
// SHOW if-empty MESSAGE
if(this.selector.find("li").length <= 1){
this.selector.find(".emptyList").show();
}
// BIND add/remove item amount
let that = this;
this.selector.find('.itemAmountBtn').off().on('click change', function(e){
let itemid = $(this).parent().parent().parent().attr('data-itemid');
let amountElem = $(this).parent().find('.itemAmount');
let newValue = Number(amountElem.val());
if($(this).html() === "-"){
newValue--;
}
else if($(this).html() === "+"){
newValue++;
}
if(newValue > 0 && newValue < 100){
amountElem.val(newValue);
that.setItemAmount(itemid, newValue);
let textAmountElem = $(this).parent().parent().find('.itemAmountText');
textAmountElem.find('.itemAmount').html(newValue);
if(newValue === 1){
textAmountElem.addClass('oneItem');
}
else {
textAmountElem.removeClass('oneItem');
}
}
});
// DRAGGABLE
let draggingObj = null, dragPos = null;
this.selector.find('.draggable').unbind().on('dragstart dragover dragenter dragleave dragend', ev => {
// this.selector.find('.draggable').hammer().bind('swipe', ev => {
if(ev.type === 'dragover' || ev.type === 'dragenter'){
ev.preventDefault();
// console.log(ev);
$(ev.currentTarget).addClass('drag-over');
dragPos = ev.currentTarget;
}
else if(ev.type === 'dragstart'){
// console.log('drag start');
draggingObj = $(ev.target);
draggingObj.css('opacity', 0.2);
}
else if(ev.type === 'dragleave'){
$('.drag-over').removeClass('drag-over');
}
else if(ev.type === 'dragend'){
// console.log(draggingObj);
if(draggingObj === null){
console.warn('no object to move');
return;
}
// console.log("move object", draggingObj, "to", dragPos);
draggingObj.css('opacity', 1);
if( this.setItemPosition(draggingObj.attr('data-itemid'), $(dragPos).attr('data-itemid')) !== false){
if($(dragPos).attr('data-itemID') == null){
draggingObj.detach().insertAfter('.emptyList');
}
else {
draggingObj.detach().insertAfter(dragPos);
}
draggingObj = null;
}
$('.drag-over').removeClass('drag-over');
}
});
// BIND remove-buttons
$(this.selector).find(".remItem").each((key, val) => {
let that = this;
$(val).off().on('click', function(){
// console.log("remItem", $(this).hasClass("confirm"), $(this));
if($(this).hasClass("confirm")){
that.remItem(key+1, $(this).attr('data-itemid'), $(this).attr("data-price"));
try {
$(this).tooltip('dispose');
}
catch(ignore){}
}
else {
// console.log("remItem addClass");
$(".confirm").removeClass("confirm");
setTimeout(() => { $(this).addClass("confirm"); }, 10);
let newThat = this;
setTimeout(function(){ $(newThat).removeClass("confirm"); }, 5000);
}
});
});
$(this.selector).find(".ariaButton").off('keydown').on('keydown', function(e){
if(e.code === "Space" || e.code === "Enter"){
e.preventDefault();
$(this).trigger('click');
}
});
// Update the total-price
updateTotalPrice();
}
// STORE MANIPULATION
removeStore(){
this.selector.remove();
if(this.storeID != null){
ajaxReq({ plan: 'deleteStore', storeID: this.storeID, storeName: this.title, itemsLength: this.items.length })
.done(json => {
console.log("Delete store response:",json);
});
}
}
getStoreID(){
let that = this;
return ajaxReq({ plan: 'saveStore', storeName: this.title })
.done(json => {
console.log("getStore:", json);
that.storeID = json['data'];
return that.storeID;
});
}
rename(newName){
this.title = newName;
if(this.storeID !== null){
return ajaxReq({ plan: 'renameStore', storeID: this.storeID, newName: newName });
}
// Return blank ajax as a false
return $.ajax();
}
}
var stores = [];
$("#stores").html("");
$("#addStore").click(ev => {
stores.push(new Store());
});
$("#refreshAll").click(ev => {
$(".tooltip").remove();
getStores(spaceID);
});
$("body").on('click', function(ev){
if( $(".price").find( ev.target ).length === 0){
$(".confirm").removeClass("confirm");
}
});
let totalPrice = 0;
function updateTotalPrice(){
totalPrice = 0;
for(const storeKey in stores){
const store = stores[storeKey];
for(const itemKey in store.items){
totalPrice += store.items[itemKey].amount*store.items[itemKey].price;
}
}
$("#totalPrice").html(totalPrice);
}
let spaceID = 0;
function getSpaces(){
$("#stores").html("Loading...");
return ajaxReq({plan: 'spaces'}).done(json => {
let optionsHtml = "";
// console.log(json);
let spaceNum = 1;
for(const spaceI in json.data.spaces){
const space = json.data.spaces[spaceI];
if(spaceID === 0){
spaceID = space['space_id'];
}
let spaceName = space['space_name'] || "Space "+spaceNum;
optionsHtml += "<option value='"+space['space_id']+"'>"+spaceName+"</option>\n";
spaceNum++;
}
let spaceSelectElem = $("#spaceSelect");
spaceSelectElem
.html(optionsHtml)
.on('change', ev => {
spaceID = $(ev.target).val();
getStores(spaceID);
});
if(typeof json.data.lastSpace !== "undefined"){
spaceID = Number(json.data.lastSpace);
spaceSelectElem.val(spaceID);
}
});
}
getSpaces().done(() => { getStores(spaceID); });
// GET STORES
function getStores(spaceID){
spaceID = spaceID || 0;
// $("#stores").html("");
stores = [];
let options = { plan: '' };
if(spaceID !== 0){
options = { plan: '', space: spaceID }
}
$.getJSON('do.php', options)
.done(json => {
if(handleJsonErrors(json)){
return;
}
$("#stores").html("");
// console.log(json);
for(const store in json.data){
let storeKey = stores.length;
stores.push(new Store(json.data[store].name, json.data[store].plan_store_id, json.data[store].state));
for(const item in json.data[store].items){
stores[storeKey].addItemHtml(
json.data[store].items[item].name,
json.data[store].items[item].price,
json.data[store].items[item].plan_item_id,
json.data[store].items[item].amount);
}
stores[storeKey].setState(json.data[store].state, 1);
}
updateTotalPrice();
})
.fail(handleAjaxErrors);
}
function ajaxReq( data ){
if(typeof spaceID !== "undefined" && spaceID !== 0){
data.space = spaceID;
}
return $.ajax({
method: "POST",
url: "do.php",
data: data,
dataType: 'JSON'
})
.done(json => {
if(handleJsonErrors(json)){
return false;
}
return true;
})
.fail(handleAjaxErrors);
}
function handleJsonErrors(json){
if(typeof json.status != "undefined" && json.status != 0){
if(json.message === "Not logged in"){
location.href = '../login.php';
}
else {
alert(json.message);
}
return true;
}
return false;
}
function handleAjaxErrors(jqxhr, textStatus, error){
if(textStatus === "parsererror" && jqxhr.responseText != ""){
alert("An error occured:\n"+jqxhr.responseText);
}
else {
alert("An error occured:\n"+error);
}
}