Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Np mj sort items soon integers #66

Draft
wants to merge 13 commits into
base: master
Choose a base branch
from
Draft
24 changes: 24 additions & 0 deletions src/lib/estimates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Calculate a weighted estimate for the interval until the next purchase
* Current purchase a tiny bit less weight than all previous purchases
* @param {Number} lastEstimate The last stored purchase interval estimate
* @param {Number} latestInterval The interval between the most recent and previous purchases
* @param {Number} numberOfPurchases Total number of purchases for the item
*/
const calculateEstimate = (lastEstimate, latestInterval, numberOfPurchases) => {
if (isNaN(lastEstimate)) {
lastEstimate = 14;
}

// fake interval to see if variable is added to database - need to store prev and current buy day to calculate difference
if (isNaN(latestInterval)) {
latestInterval = 10;
}
// FIXME algorithm doesn't work when there's only 1 purchase in the database
let previousFactor = lastEstimate * numberOfPurchases;
let latestFactor = latestInterval * (numberOfPurchases - 1);
let totalDivisor = numberOfPurchases * 2 - 1;
return (previousFactor + latestFactor) / totalDivisor;
};

export default calculateEstimate;
11 changes: 9 additions & 2 deletions src/listContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,14 @@ const ListContextProvider = props => {
};

//we use .set to add the time the item was purchased to an already existing document we search for the item.id
const addDatePurchased = (item, lastDatePurchased) => {
itemsRef.doc(item.id).set({ ...item, lastDatePurchased });
const addDatePurchased = (item, lastDatePurchased, numberOfPurchases) => {
itemsRef
.doc(item.id)
.set({ ...item, lastDatePurchased, numberOfPurchases });
};

const addCalculatedEstimate = (item, calculatedEstimate) => {
itemsRef.doc(item.id).set({ ...item, calculatedEstimate });
};

return (
Expand All @@ -85,6 +91,7 @@ const ListContextProvider = props => {
validToken,
shoppingList,
setShoppingList,
addCalculatedEstimate,
fetchList,
isDuplicate,
addItem,
Expand Down
2 changes: 2 additions & 0 deletions src/pages/AddItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,5 @@ const AddItem = () => {
};

export default AddItem;

//MJ: testing to make sure that I pulled the branch correctly.
72 changes: 52 additions & 20 deletions src/pages/List.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,64 @@
import React, { useContext } from 'react';
import NavTabs from '../components/NavTabs';
import Loading from '../components/Loading';
// import ErrorMessage from '../components/ErrorMessage';
import useListToken, { getCurrentToken } from '../useListToken';
import { FirestoreCollection } from 'react-firestore';
import { ListContext } from '../listContext';
import useListToken from '../useListToken';
import { FirestoreCollection } from 'react-firestore';
import Loading from '../components/Loading';
import ErrorMessage from '../components/ErrorMessage';
import HomePageButton from '../components/HomePageButton';
import calculateEstimate from '../lib/estimates.js';
import latestInterval from '../lib/estimates.js';
import dayjs from 'dayjs';
import './List.css';

const today = dayjs();

function isLessThan24hrs(datePurchased) {
let purchaseDateCalc = dayjs(datePurchased);
return today.diff(purchaseDateCalc, 'hour') <= 24;
}

const List = props => {
const { shoppingList, setShoppingList, addDatePurchased } = useContext(
ListContext,
);
const { token } = useListToken;
const today = dayjs();
const {
shoppingList,
setShoppingList,
addDatePurchased,
addCalculatedEstimate,
} = useContext(ListContext);
const { token } = useListToken();

function isLessThan24hrs(datePurchased) {
let purchaseDateCalc = dayjs(datePurchased);
return today.diff(purchaseDateCalc, 'hour') <= 24;
}
//when an item has been created but not yet purchased.
//we are checking if the last date it was purchased is less than 24hrs using isLessThan24hrs function
function isChecked(lastDatePurchased) {
return !!lastDatePurchased && isLessThan24hrs(lastDatePurchased);
}

// let count = 1;
//we are adding the item.id as well as the date purchased when clicking on the checkbox
function handlePurchasedChange(item) {
const datePurchased = item.lastDatePurchased ? null : Date.now();
addDatePurchased(item, datePurchased);
const numberOfPurchases = item.numberOfPurchases
? item.numberOfPurchases + 1
: 1;
console.log('Item before:', item);
addDatePurchased(item, datePurchased, numberOfPurchases);

let lastEstimate = item.nextExpectedPurchase
? item.nextExpectedPurchase
: 14;

let prevDate = item.lastDatePurchased ? item.lastDatePurchased : null;

console.log('prevDate:', prevDate);
console.log('currentDate:', datePurchased);
console.log('lastEstimate:', lastEstimate);

const calculatedEstimate = calculateEstimate(
lastEstimate,
latestInterval,
numberOfPurchases,
);
console.log('the calculateEstimate ran:', calculatedEstimate);
addCalculatedEstimate(item, calculatedEstimate);
console.log('Item after:', item);
}

return (
Expand All @@ -38,19 +69,20 @@ const List = props => {
// Sort the data
sort="name"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What else might you pass here besides name? Are the items always in alphabetical order—why?

// Only fetch the items associated with the token saved in localStorage
filter={['token', '==', token || getCurrentToken() || 'no token set']}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Careful here @MonicaDJohnson. This is a breaking change when the user doesn't already have a token saved in localStorage. I know this is from the branch this PR is based on, but just a heads up.

filter={['token', '==', token]}
// isLoading = is a Boolean that represents the loading status for the firebase query. true until an initial payload from Firestore is received.
// data = an Array containing all of the documents in the collection. Each item will contain an id along with the other data contained in the document.
render={({ isLoading, data }) => {
// if (!isLoading && data.length === 0) {
// return <ErrorMessage />;
// }
if (!isLoading && data.length === 0) {
return <ErrorMessage />;
}

if (!isLoading) {
setShoppingList(data);
}

return isLoading ? (
// TODO: Make a display list function is listContext.js
<Loading />
) : (
<ul className="shopping-list">
Expand Down