Skip to content

Commit a45f001

Browse files
committed
managed to get backend calls to count to work
1 parent 74eba4a commit a45f001

4 files changed

Lines changed: 97 additions & 2 deletions

File tree

client/src/components/ui/backend/organization_call_backend.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ import { generateMockMember } from "@/mocks/Members_Details_Interface_Mocks";
88

99
// tha main URL
1010
export const BASE_INVENTORY_URL = "http://localhost:8000/api/inventory/";
11+
export const COUNT_ITEMS_DUE_THIS_WEEK_URL =
12+
"http://localhost:8000/api/inventory/countDueThisWeek/";
13+
14+
export interface django_count_response_interface {
15+
count: number;
16+
}
1117

1218
// change when backend is ready
1319
const isDev: boolean = false;
@@ -42,6 +48,21 @@ export const getItems = async (
4248
}
4349
};
4450

51+
export const getITemsDueThisWeek =
52+
async (): Promise<django_count_response_interface> => {
53+
const response = await fetch(`${COUNT_ITEMS_DUE_THIS_WEEK_URL}`);
54+
55+
// 2. Check if the request was successful
56+
if (!response.ok) throw new Error("Failed to fetch");
57+
58+
// 3. Parse the JSON data
59+
// because fetcah returns a response, it isnt the data yet,
60+
// its just the response header,
61+
// you will need to use .json() to get the data
62+
// it converts raw bytes to Javascript objects
63+
return await response.json(); // Returns the list from Django
64+
};
65+
4566
// --- POST: Create a new item ---
4667
// .stringify, flattens the object
4768
// headers: { 'Content-Type': 'application/json' } determine, how the data will be dealt with by the server

client/src/components/ui/backend/organization_clean_backend_calls.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,13 @@ import { Member_Details_Interface } from "@/components/ui/card_organization_memb
66
import type { Inventory_Details_Interface } from "../card_organization_inventory_details_modal";
77
import {
88
BASE_INVENTORY_URL,
9+
COUNT_ITEMS_DUE_THIS_WEEK_URL,
910
createItem,
1011
createMember,
1112
deleteItem,
13+
django_count_response_interface,
1214
getItems,
15+
getITemsDueThisWeek,
1316
getMembers,
1417
updateItem,
1518
updateMember,
@@ -45,6 +48,14 @@ export interface organization_clean_backend_calls_return_boolean_members_interfa
4548
refresh: KeyedMutator<boolean>; // Optional refresh function
4649
}
4750

51+
export interface organization_clean_backend_calls_return_number_interface {
52+
data: number;
53+
loading: boolean;
54+
error: Error | null;
55+
isSuccess: boolean;
56+
refresh: KeyedMutator<django_count_response_interface>; // Optional refresh function
57+
}
58+
4859
/*
4960
This is the class that will call the backend to get the item data / set the item data / update the item data/ delete the item data
5061
@@ -152,6 +163,28 @@ export const useOrganizationBackendGetItems = (
152163
return res;
153164
};
154165

166+
export const useOrganizationBackendCountItemsDueThisWeek =
167+
(): organization_clean_backend_calls_return_number_interface => {
168+
const { data, error, isLoading, mutate } = useSWR(
169+
COUNT_ITEMS_DUE_THIS_WEEK_URL, // The "Key" (Unique identifier)
170+
getITemsDueThisWeek, // The "Fetcher" (Your function)
171+
{
172+
refreshInterval: 30, // Poll every 30 seconds 30000ms
173+
revalidateOnFocus: true, // Refresh when r clicks back into the tab
174+
},
175+
);
176+
177+
const res: organization_clean_backend_calls_return_number_interface = {
178+
data: data?.count || 0,
179+
loading: isLoading,
180+
error: error,
181+
isSuccess: !isLoading && !error,
182+
refresh: mutate, // SWR calls its refresh function "mutate"
183+
};
184+
185+
return res;
186+
};
187+
155188
// This is now a standard function, NOT a hook
156189
// if it is a hook, it will not work, a hook means swr
157190
export const createItemClean = async (

client/src/pages/organization_dashboard.tsx

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { useState } from "react";
66

77
import {
88
organization_clean_backend_calls_return_interface,
9+
organization_clean_backend_calls_return_number_interface,
10+
useOrganizationBackendCountItemsDueThisWeek,
911
useOrganizationBackendGetItems,
1012
} from "@/components/ui/backend/organization_clean_backend_calls";
1113
import Inventory_Details_Modal, {
@@ -18,6 +20,8 @@ import Statistics_Card from "../components/ui/card_organization_statistics";
1820
import Header from "../components/ui/navbar_organization";
1921

2022
const Organization_Dashboard = () => {
23+
// calling backend starts //
24+
2125
// this is for calling the data for the modal
2226
const {
2327
data,
@@ -31,6 +35,24 @@ const Organization_Dashboard = () => {
3135
console.log("Error state:", error);
3236
console.log("Refresh function:", refresh);
3337

38+
// this is for calling the data for the modal
39+
const {
40+
data: countItemsDueThisWeekData,
41+
loading: countItemsDueThisWeekLoading,
42+
error: countItemsDueThisWeekError,
43+
refresh: countItemsDueThisWeekRefresh,
44+
}: organization_clean_backend_calls_return_number_interface = useOrganizationBackendCountItemsDueThisWeek();
45+
46+
console.log(
47+
"Data from useOrganizationBackendCountItemsDueThisWeek:",
48+
countItemsDueThisWeekData,
49+
);
50+
console.log("Loading state:", countItemsDueThisWeekLoading);
51+
console.log("Error state:", countItemsDueThisWeekError);
52+
console.log("Refresh function:", countItemsDueThisWeekRefresh);
53+
54+
// calling backend ends //
55+
3456
// This is for the overlay modal
3557
const [isModalOpen, setIsModalOpen] = useState(false);
3658
const [selectedItemData, setSelectedItemData] =
@@ -93,7 +115,7 @@ const Organization_Dashboard = () => {
93115
/>
94116
<Statistics_Card
95117
title="Inventory Due"
96-
value={2}
118+
value={countItemsDueThisWeekData}
97119
delta="-10 this week"
98120
status="down"
99121
/>

server/inventory/views.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
from rest_framework import viewsets
77
from .models import InventoryItem
88
from .serializers import InventoryItemSerializer
9+
from rest_framework.decorators import action
10+
from rest_framework.response import Response
11+
from django.utils import timezone
12+
from datetime import timedelta
913

1014
class InventoryItemViewSet(viewsets.ModelViewSet):
1115
serializer_class = InventoryItemSerializer
@@ -35,4 +39,19 @@ def get_queryset(self):
3539
# class InventoryItemViewSet(viewsets.ModelViewSet):
3640
# # This tells the view where to get the data and how to translate it
3741
# queryset = InventoryItem.objects.all()
38-
# serializer_class = InventoryItemSerializer
42+
# serializer_class = InventoryItemSerializer
43+
44+
# url = GET /api/inventory/countDueThisWeek/
45+
@action(detail=False, methods=['get'])
46+
def countDueThisWeek(self, request):
47+
# 1. Define the time range
48+
now = timezone.now()
49+
one_week_later = now + timedelta(days=7)
50+
51+
# 2. Filter and count in the database (efficient!)
52+
count = InventoryItem.objects.filter(
53+
dueOn__range=[now, one_week_later]
54+
).count()
55+
56+
# 3. Return a simple response
57+
return Response({'count': count})

0 commit comments

Comments
 (0)