Skip to content

Commit

Permalink
profile context integration with view plants and add detaisl
Browse files Browse the repository at this point in the history
  • Loading branch information
SashankBalusu committed Dec 7, 2024
1 parent d84231b commit ee84673
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 96 deletions.
77 changes: 18 additions & 59 deletions app/add-details/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,65 +2,24 @@

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { UUID } from 'crypto';
import { insertUserPlants } from '@/api/supabase/queries/userPlants';
import PlantDetails from '@/components/PlantDetails';
import { Plant, UserPlant } from '@/types/schema';

const plants: Plant[] = [
{
id: 'cfed129c-1cdf-4089-89d2-83ae2fb2f83d',
plant_name: 'cabbage',
us_state: 'string',
harvest_season: 'SPRING',
water_frequency: 'string',
weeding_frequency: 'string',
indoors_start: 'string',
indoors_end: 'string',
outdoors_start: 'string',
outdoors_end: 'string',
transplant_start: 'string',
transplant_end: 'string',
harvest_start: 'string',
harvest_end: 'string',
beginner_friendly: true,
plant_tips: 'string',
img: 'string',
difficulty_level: 'HARD',
sunlight_min_hours: 1,
sunlight_max_hours: 1,
},
{
id: '8f25fca8-6e86-486b-9a2b-79f68efa3658',
plant_name: 'tomato',
us_state: 'string',
harvest_season: 'SPRING',
water_frequency: 'string',
weeding_frequency: 'string',
indoors_start: 'string',
indoors_end: 'string',
outdoors_start: 'string',
outdoors_end: 'string',
transplant_start: 'string',
transplant_end: 'string',
harvest_start: 'string',
harvest_end: 'string',
beginner_friendly: true,
plant_tips: 'string',
img: 'string',
difficulty_level: 'HARD',
sunlight_min_hours: 1,
sunlight_max_hours: 1,
},
];
const user_id: UUID = '0802d796-ace8-480d-851b-d16293c74a21';
import { UserPlant } from '@/types/schema';
import { useAuth } from '@/utils/AuthProvider';
import { useProfile } from '@/utils/ProfileProvider';

export default function Home() {
const { profileData, profileReady, plantsToAdd } = useProfile();
const { userId } = useAuth();
const router = useRouter();

if (profileReady && !profileData) {
router.push('/view-plants');
}
const [currentIndex, setCurrentIndex] = useState<number>(1);
const [details, setDetails] = useState<Partial<UserPlant>[]>(
plants.map(plant => ({ plant_id: plant.id, user_id: user_id })),
plantsToAdd.map(plant => ({ plant_id: plant.id, user_id: userId! })),
);
const router = useRouter();

const getDefaultDate = () => new Date().toISOString().substring(0, 10);

Expand All @@ -71,15 +30,15 @@ export default function Home() {
// Set curr date in details to default date if not on submission page
if (
(!currentDetail || !currentDetail.date_added) &&
currentIndex <= plants.length
currentIndex <= plantsToAdd.length
) {
updateInput('date_added', getDefaultDate());
}
// For valid moves, move to next page
if (
steps !== 0 &&
currentIndex + steps > 0 &&
currentIndex + steps <= plants.length + 1
currentIndex + steps <= plantsToAdd.length + 1
) {
setCurrentIndex(prevIndex => prevIndex + steps);
}
Expand All @@ -103,31 +62,31 @@ export default function Home() {
}

async function updateDB() {
await insertUserPlants(user_id, details);
await insertUserPlants(userId!, details);
router.push('/view-plants');
}

return (
<div>
{currentIndex !== plants.length + 1 && (
{currentIndex !== plantsToAdd.length + 1 && (
<div>
<PlantDetails
plant={plants[currentIndex - 1]}
plant={plantsToAdd[currentIndex - 1]}
date={details[currentIndex - 1].date_added || getDefaultDate()}
plantingType={details[currentIndex - 1].planting_type || 'SELECT'}
onDateChange={date => updateInput('date_added', date)}
onPlantingTypeChange={type => updateInput('planting_type', type)}
/>
<button onClick={() => move(-1)}>Back</button>
<p>
{currentIndex} / {plants.length}
{currentIndex} / {plantsToAdd.length}
</p>
<button disabled={disableNext()} onClick={() => move(1)}>
Next
</button>
</div>
)}
{currentIndex === plants.length + 1 && (
{currentIndex === plantsToAdd.length + 1 && (
<div>
<button onClick={() => move(-1)}>Back</button>
<button onClick={updateDB}>Submit</button>
Expand Down
102 changes: 66 additions & 36 deletions app/view-plants/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import { useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { UUID } from 'crypto';
import {
getAllPlants,
getMatchingPlantForUserPlant,
Expand All @@ -21,6 +20,7 @@ import {
SeasonEnum,
SunlightEnum,
} from '@/types/schema';
import { useAuth } from '@/utils/AuthProvider';
import {
checkDifficulty,
checkGrowingSeason,
Expand Down Expand Up @@ -62,7 +62,9 @@ const growingSeasonOptions: DropdownOption<SeasonEnum>[] = [

export default function Page() {
const router = useRouter();
const { hasPlot } = useProfile();
const { hasPlot, profileData, profileReady, setPlantsToAdd } = useProfile();
const { userId } = useAuth();

const [viewingOption, setViewingOption] = useState<'myPlants' | 'all'>(
hasPlot ? 'myPlants' : 'all',
);
Expand All @@ -78,44 +80,45 @@ export default function Page() {
DropdownOption<SeasonEnum>[]
>([]);
const [searchTerm, setSearchTerm] = useState<string>('');
const user_id: UUID = '0802d796-ace8-480d-851b-d16293c74a21';
const [selectedPlants, setSelectedPlants] = useState<Plant[]>([]);
const [ownedPlants, setOwnedPlants] = useState<OwnedPlant[]>([]);
// TODO: replace this with state from ProfileContext
const userState = 'TENNESSEE';
const userState = profileData?.us_state ?? 'TENNESSEE';

// Fetch All Plants
useEffect(() => {
(async () => {
const plantList = await getAllPlants();
// Filter by user's state, since they can only access when onboarded
// TODO: add userState to dependency array?
// Sort alphabetically first
const result = plantList
.filter(plant => plant.us_state === userState)
.sort((a, b) => a.plant_name.localeCompare(b.plant_name));
setPlants(result);
})();
}, []);
// Only fetch plants when profile is ready and we have a state
if (profileReady && userState) {
(async () => {
const plantList = await getAllPlants();
const result = plantList
.filter(plant => plant.us_state === userState)
.sort((a, b) => a.plant_name.localeCompare(b.plant_name));
setPlants(result);
})();
}
}, [profileReady, userState]);

// Fetch User Plants for My Garden tab
useEffect(() => {
const fetchUserPlants = async () => {
const fetchedUserPlants = await getCurrentUserPlantsByUserId(user_id);
// Only fetch user plants if we have a valid userId
if (userId) {
const fetchUserPlants = async () => {
const fetchedUserPlants = await getCurrentUserPlantsByUserId(userId);

const ownedPlants: OwnedPlant[] = await Promise.all(
fetchedUserPlants.map(async userPlant => {
const plant = await getMatchingPlantForUserPlant(userPlant);
return {
userPlantId: userPlant.id,
plant,
};
}),
);
setOwnedPlants(ownedPlants);
};
fetchUserPlants();
}, []);
const ownedPlants: OwnedPlant[] = await Promise.all(
fetchedUserPlants.map(async userPlant => {
const plant = await getMatchingPlantForUserPlant(userPlant);
return {
userPlantId: userPlant.id,
plant,
};
}),
);
setOwnedPlants(ownedPlants);
};
fetchUserPlants();
}
}, [userId]);

const clearFilters = () => {
setSelectedGrowingSeason([]);
Expand Down Expand Up @@ -171,14 +174,37 @@ export default function Page() {
}
}
function handleAddPlants() {
//TODO: route to add details with proper information
router.push('/add-details'); // use CONFIG later
setPlantsToAdd(selectedPlants);

router.push('/add-details');
}

function handleCancelAddMode() {
setSelectedPlants([]);
setInAddMode(false);
}
// Not logged in
if (!userId) {
return (
<div>
<p>Login to view all plants</p>
<button onClick={() => router.push('/login')}>Log In</button>
</div>
);
}

// Not onboarded
if (profileReady && !profileData) {
return (
<div>
<H1>Complete Your Profile</H1>
<p>Please complete your onboarding to access view plants</p>
<button onClick={() => router.push('/onboarding')}>
Go To Onboarding
</button>
</div>
);
}

const plantPluralityString = selectedPlants.length > 1 ? 'Plants' : 'Plant';

Expand Down Expand Up @@ -274,15 +300,18 @@ export default function Page() {
</PlantGridContainer>
) : (
<div>
<button onClick={() => setViewingOption('all')}>
Add Plants
</button>
<p>No plants match your current filters.</p>
</div>
)}
</div>
)}
{viewingOption === 'all' && (
<>
filteredPlantList.length === 0 ? (
<div>
<p>No plants match your current filters.</p>
</div>
) : (
<PlantGridContainer>
{filteredPlantList.map(plant => (
<PlantCard
Expand All @@ -295,6 +324,7 @@ export default function Page() {
/>
))}
</PlantGridContainer>
)
{inAddMode && (
<AddButton
$backgroundColor={
Expand Down
9 changes: 8 additions & 1 deletion utils/ProfileProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,18 @@ import {
fetchProfileById,
upsertProfile,
} from '@/api/supabase/queries/profiles';
import { Profile } from '@/types/schema';
import { Plant, Profile } from '@/types/schema';
import { useAuth } from './AuthProvider';

export interface ProfileContextType {
profileData: Profile | null;
profileReady: boolean;
hasPlot: boolean | null;
plantsToAdd: Plant[];
setProfile: (completeProfile: Profile) => Promise<void>; // Now expects full Profile
loadProfile: () => Promise<void>;
setHasPlot: (plotValue: boolean | null) => void;
setPlantsToAdd: (plants: Plant[]) => void;
}

const ProfileContext = createContext<ProfileContextType | undefined>(undefined);
Expand All @@ -43,6 +45,7 @@ export default function ProfileProvider({ children }: ProfileProviderProps) {
const [profileData, setProfileData] = useState<Profile | null>(null);
const [profileReady, setProfileReady] = useState<boolean>(false);
const [hasPlot, setHasPlot] = useState<boolean | null>(null);
const [plantsToAdd, setPlantsToAdd] = useState<Plant[]>([]);

const loadProfile = useCallback(async () => {
if (!userId) {
Expand Down Expand Up @@ -87,6 +90,8 @@ export default function ProfileProvider({ children }: ProfileProviderProps) {
profileData,
profileReady,
hasPlot,
plantsToAdd,
setPlantsToAdd,
setProfile,
loadProfile,
setHasPlot: updateHasPlot,
Expand All @@ -95,6 +100,8 @@ export default function ProfileProvider({ children }: ProfileProviderProps) {
profileData,
profileReady,
hasPlot,
plantsToAdd,
setPlantsToAdd,
setProfile,
loadProfile,
setHasPlot,
Expand Down

0 comments on commit ee84673

Please sign in to comment.