pantry-track/application/shoppinglists/static/js/shoppingListViewHandler.js
2025-08-18 17:18:43 -05:00

87 lines
3.0 KiB
JavaScript

document.addEventListener('DOMContentLoaded', async function() {
let shopping_list = await fetchShoppingList()
await replenishForm(shopping_list)
list_items = shopping_list.sl_items
if(shopping_list.sub_type == "calculated"){
list_items = await fetchItemsFullCalculated()
}
await replenishLineTable(list_items)
})
async function replenishForm(shopping_list){
document.getElementById('listName').innerHTML = shopping_list.name
document.getElementById('listCreationDate').innerHTML = shopping_list.creation_date
document.getElementById('listDescription').innerHTML = shopping_list.description
}
async function replenishLineTable(sl_items){
let listItemsTableBody = document.getElementById('listItemsTableBody')
listItemsTableBody.innerHTML = ""
console.log(sl_items)
for(let i = 0; i < sl_items.length; i++){
let tableRow = document.createElement('tr')
let checkboxCell = document.createElement('td')
checkboxCell.innerHTML = `<label><input class="uk-checkbox" type="checkbox" ${sl_items[i].list_item_state ? 'checked' : ''}></label>`
checkboxCell.onclick = async function (event) {
await updateListItemState(sl_items[i].list_item_uuid, event.target.checked)
}
namefield = sl_items[i].item_name
if(sl_items[i].links.hasOwnProperty('main')){
namefield = `<a href=${sl_items[i].links.main} target='_blank'>${sl_items[i].item_name}</a>`
}
let nameCell = document.createElement('td')
nameCell.innerHTML = namefield
let qtyuomCell = document.createElement('td')
qtyuomCell.innerHTML = `${sl_items[i].qty} ${sl_items[i].uom.fullname}`
checkboxCell.checked = sl_items[i].list_item_state
tableRow.append(checkboxCell, nameCell, qtyuomCell)
listItemsTableBody.append(tableRow)
}
}
async function fetchShoppingList() {
const url = new URL('/shopping-lists/api/getList', window.location.origin);
url.searchParams.append('list_uuid', list_uuid);
const response = await fetch(url);
data = await response.json();
return data.shopping_list;
}
async function fetchSLItem(sli_id) {
const url = new URL('/shopping-lists/api/getListItem', window.location.origin);
url.searchParams.append('sli_id', sli_id);
const response = await fetch(url);
data = await response.json();
return data.list_item;
}
async function fetchItemsFullCalculated() {
const url = new URL('/shopping-lists/api/getSKUItemsFull', window.location.origin);
const response = await fetch(url);
data = await response.json();
return data.list_items;
}
async function updateListItemState(list_item_uuid, state){
console.log(list_item_uuid, state)
const response = await fetch(`/shopping-lists/api/setListItemState`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
list_item_uuid: list_item_uuid,
list_item_state: state
}),
});
}