Skip to content

Commit

Permalink
started working on updateItem function at firebase.js, implemented ge…
Browse files Browse the repository at this point in the history
…tDaysBetweenDates at dates.js
  • Loading branch information
borjaMarti committed Mar 5, 2024
1 parent a7494dd commit 53f7bbc
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 2 deletions.
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"npm": ">=8.19.0"
},
"dependencies": {
"@the-collab-lab/shopping-list-utils": "^2.2.0",
"firebase": "^10.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
25 changes: 23 additions & 2 deletions src/api/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import {
} from 'firebase/firestore';
import { useEffect, useState } from 'react';
import { db } from './config';
import { getFutureDate, isMoreThanADayAgo } from '../utils';
import {
getFutureDate,
getDaysBetweenDates,
isMoreThanADayAgo,
} from '../utils';
import { calculateEstimate } from '@the-collab-lab/shopping-list-utils';

/**
* A custom hook that subscribes to the user's shopping lists in our Firestore
Expand Down Expand Up @@ -184,8 +189,24 @@ export async function updateItem(listPath, itemId) {
const itemDocumentRef = doc(listCollectionRef, itemId);
const item = await getDoc(itemDocumentRef);
const itemTotalPurchases = item.data().totalPurchases;
const dateLastPurchased = item.data().dateLastPurchased.toDate();
const prevDateNextPurchased = item.data().dateNextPurchased.toDate();
const now = new Date();
const daysSinceLastPurchase = getDaysBetweenDates(now, dateLastPurchased); // First buy: 0.
const prevEstimate = getDaysBetweenDates(
prevDateNextPurchased,
dateLastPurchased,
);
const nextEstimate = calculateEstimate(
prevEstimate,
daysSinceLastPurchase,
itemTotalPurchases,
);
const dateNextPurchased = getFutureDate(nextEstimate);

await updateDoc(itemDocumentRef, {
dateLastPurchased: new Date(),
dateLastPurchased: now,
dateNextPurchased: dateNextPurchased,
totalPurchases: itemTotalPurchases + 1,
});
return itemDocumentRef;
Expand Down
11 changes: 11 additions & 0 deletions src/utils/dates.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,14 @@ export const isMoreThanADayAgo = (date) => {
const diff = now - dateInMiliseconds;
return ONE_DAY_IN_MILLISECONDS < diff;
};

/**
* .
* @example
* //
*
* @param {Date} date
*/
export function getDaysBetweenDates(dateFuture, datePast = dateFuture) {
return Math.ceil((dateFuture.getTime() - datePast.getTime()) / 86400000);
}

0 comments on commit 53f7bbc

Please sign in to comment.