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

Sort shopping list by urgency #30

Merged
merged 7 commits into from
Sep 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 32 additions & 8 deletions src/api/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { db } from './config';
import { getFutureDate } from '../utils';
import toast from 'react-hot-toast';
import { calculateEstimate } from '@the-collab-lab/shopping-list-utils';
import { getDaysBetweenDates } from '../utils/dates';
import { getDaysSinceLastPurchase } from '../utils/helpers';
/**
* A custom hook that subscribes to the user's shopping lists in our Firestore
* database and returns new data whenever the lists change.
Expand Down Expand Up @@ -200,14 +200,8 @@ export async function updateItem(listPath, checked, itemData) {
const today = new Date();
const currentTotalPurchases = itemData.totalPurchases;
const currentDayInterval = itemData.dayInterval;
const dateLastPurchasedJavaScriptObject = itemData.dateLastPurchased
? itemData.dateLastPurchased.toDate()
: itemData.dateCreated.toDate();

const daysSinceLastPurchase = getDaysBetweenDates(
today,
dateLastPurchasedJavaScriptObject,
);
const daysSinceLastPurchase = getDaysSinceLastPurchase(itemData);
const estimate = calculateEstimate(
currentDayInterval,
daysSinceLastPurchase,
Expand Down Expand Up @@ -242,3 +236,33 @@ export async function deleteItem(listPath, id) {
console.error('Error deleting your item', error);
}
}

export function comparePurchaseUrgency(arr) {
const groupedItems = {
Overdue: [],
Soon: [],
'Kind of soon': [],
'Not soon': [],
Inactive: [],
};
arr.forEach((item) => {
if (groupedItems[item.indicator]) {
groupedItems[item.indicator].push(item);
}
});
Object.keys(groupedItems).forEach((key) => {
groupedItems[key].sort((a, b) => (a.name > b.name ? 1 : -1));
});
return groupedItems['Overdue'].length > 0
? groupedItems['Overdue'].concat(
groupedItems['Soon'],
groupedItems['Kind of soon'],
groupedItems['Not soon'],
groupedItems['Inactive'],
)
: groupedItems['Soon'].concat(
groupedItems['Kind of soon'],
groupedItems['Not soon'],
groupedItems['Inactive'],
);
}
3 changes: 3 additions & 0 deletions src/components/ListItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export function ListItem({
totalPurchases,
dayInterval,
dateCreated,
indicator,
}) {
const handleOnChange = async (event) => {
let { checked } = event.target;
Expand Down Expand Up @@ -62,6 +63,8 @@ export function ListItem({
disabled={isChecked}
/>
<label htmlFor={`${id}`}>{name}</label>
{/* Add CSS to dynamically change bg-color for badges? */}
<p className="TimeBadge">{indicator}</p>
<button type="button" id={id} onClick={handleDelete}>
Delete
</button>
Expand Down
10 changes: 5 additions & 5 deletions src/components/SearchBar.jsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
export function SearchBar({ data, setDisplayData, setSearch, search }) {
export function SearchBar({ allData, setDisplayData, setSearch, search }) {
const handleInputChange = (e) => {
const searchTerm = e.target.value;
setSearch(searchTerm);

const filteredUsers = data.filter((item) =>
const filteredData = allData.filter((item) =>
item.name.toLowerCase().includes(searchTerm.trim().toLowerCase()),
);
setDisplayData(filteredUsers);
};

setDisplayData(filteredData);
};
const handleClear = () => {
setDisplayData(data);
setDisplayData(allData);
setSearch('');
};

Expand Down
11 changes: 11 additions & 0 deletions src/components/SingleList.css
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,14 @@
.SingleList-label {
margin-left: 0.2em;
}

.ListItem {
display: flex;
flex-direction: row;
justify-content: flex-start;
}

.TimeBadge {
margin: 8px;
font-size: small;
}
30 changes: 30 additions & 0 deletions src/utils/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { getDaysBetweenDates } from './dates';

export function getDaysSinceLastPurchase(item) {
const dateLastPurchasedJavaScriptObject = item.dateLastPurchased
? item.dateLastPurchased.toDate()
: item.dateCreated.toDate();

return getDaysBetweenDates(new Date(), dateLastPurchasedJavaScriptObject);
}

export function getIndicator(item) {
const daysSinceLastPurchase = getDaysSinceLastPurchase(item);

const daysUntilNextPurchase = getDaysBetweenDates(
item.dateNextPurchased.toDate(),
new Date(),
);

if (daysSinceLastPurchase > 60) {
return 'Inactive';
} else if (daysUntilNextPurchase < 0 && daysSinceLastPurchase < 60) {
return 'Overdue';
} else if (daysUntilNextPurchase <= 7) {
return 'Soon';
} else if (daysUntilNextPurchase > 7 && daysUntilNextPurchase < 30) {
return 'Kind of soon';
} else if (daysUntilNextPurchase >= 30) {
return 'Not soon';
}
}
15 changes: 13 additions & 2 deletions src/views/List.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
import { useEffect, useState } from 'react';
import { ListItem, SearchBar } from '../components';
import { useNavigate } from 'react-router-dom';
import { comparePurchaseUrgency } from '../api/firebase';
import { getIndicator } from '../utils/helpers';

export function List({ data, listPath }) {
const [search, setSearch] = useState('');
const [allData, setAllData] = useState([]);
const [displayData, setDisplayData] = useState([]);
const navigate = useNavigate();

useEffect(() => {
setDisplayData([...data]);
const arrayWithIndicator = data.map((item) => ({
...item,
indicator: getIndicator(item),
}));
const urgencyData = [...comparePurchaseUrgency(arrayWithIndicator)];
setAllData(urgencyData);
setDisplayData(urgencyData);
}, [data]);

return (
<>
<SearchBar
setDisplayData={setDisplayData}
data={data}
allData={allData}
setSearch={setSearch}
search={search}
/>
Expand All @@ -31,6 +40,8 @@ export function List({ data, listPath }) {
totalPurchases={item.totalPurchases}
dayInterval={item.dayInterval}
dateCreated={item.dateCreated}
dateNextPurchased={item.dateNextPurchased}
indicator={item.indicator}
/>
))}
</ul>
Expand Down
Loading