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

Update the usecase, usecases files and test case #838

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
99 changes: 64 additions & 35 deletions next_webapp/src/app/[locale]/statistics/page.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
"use client";
import React, { useState, useEffect } from "react";
import React, {useEffect, useState} from "react";
import Header from "../../../components/Header";
import Footer from "../../../components/Footer";
import { useTranslations } from "next-intl";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from "chart.js";
import { Bar } from "react-chartjs-2";
import {useTranslations} from "next-intl";
import {BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip,} from "chart.js";
import {Bar} from "react-chartjs-2";
import {CATEGORY, SEARCH_MODE, SearchParams} from "@/app/types";

ChartJS.register(
CategoryScale,
Expand All @@ -23,39 +16,75 @@ ChartJS.register(
Legend
);

const Statistics = () => {
// Dummy Array
const caseStudies = [
{ id: 1, tag: "Safety and Well-being", publishNumber: "4", popularity: "11%", trimester: "1" },
{ id: 2, tag: "Environment and Sustainability", publishNumber: "5", popularity: "40%", trimester: "2" },
{ id: 3, tag: "Business and activity", publishNumber: "8", popularity: "90%", trimester: "3" },
{ id: 4, tag: "Safety and Well-being", publishNumber: "4", popularity: "11%", trimester: "2" },
{ id: 5, tag: "Environment and Sustainability", publishNumber: "5", popularity: "90%", trimester: "3" },
{ id: 6, tag: "Business and activity", publishNumber: "8", popularity: "70%", trimester: "1" },
{ id: 7, tag: "Safety and Well-being", publishNumber: "4", popularity: "11%", trimester: "2" },
{ id: 8, tag: "Environment and Sustainability", publishNumber: "5", popularity: "20%", trimester: "2" },
{ id: 9, tag: "Business and activity", publishNumber: "8", popularity: "60%", trimester: "1" },
];
async function searchStatistics(searchParams: SearchParams) {
const response = await fetch("/api/statistics", {
method: "GET",
headers: {
"Content-Type": "application/json",
}
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

return await response.json();
}


const Statistics = () => {
const [caseStudies, setCaseStudies] = useState([]);
// State for storing the filtered results and all filters
const [filteredStudies, setFilteredStudies] = useState(caseStudies);

useEffect(() => {
fetchStatistics()
}, [])

const fetchStatistics = async () => {
try {
const data = await searchStatistics({searchTerm: "",
searchMode: SEARCH_MODE.TITLE,
category: CATEGORY.EV});
setCaseStudies(data);
console.log('data received! ' + data.toString());
} catch (error) {
console.log('request called!');
} finally {
console.log('request called finally!');
}
};

const [tagFilter, setTagFilter] = useState("");
const [trimesterFilter, setTrimesterFilter] = useState("");
const [pagefilter, setPageFilter] = useState("5");
const [search, setSearchTerm] = useState("");

// Effect to handle filtering based on tag and trimester
useEffect(() => {
let filtered = caseStudies;
if (tagFilter) {
filtered = filtered.filter((study: {tag: string}) => study.tag === tagFilter);
}
if (trimesterFilter) {
filtered = filtered.filter((study: {trimester: string}) => study.trimester === trimesterFilter);
}
setFilteredStudies(filtered);
}, [tagFilter, trimesterFilter]);

// Distinct tags for the dropdown
const tags = Array.from(new Set(caseStudies.map((study) => study.tag)));
const trimesters = Array.from(new Set(caseStudies.map((study) => study.trimester)));
const tags = Array.from(new Set(caseStudies.map((study: {tag: string}) => study.tag)));
// Distinct trimesters for the dropdown
const trimesters = Array.from(new Set(caseStudies.map((study: {trimester: string}) => study.trimester)));

// Effect to handle filtering based on tag and trimester
useEffect(() => {
let filtered = caseStudies;
if (tagFilter) {
filtered = filtered.filter((study) => study.tag === tagFilter);
filtered = filtered.filter((study: {tag: string}) => study.tag === tagFilter);
}
if (trimesterFilter) {
filtered = filtered.filter((study) => study.trimester === trimesterFilter);
filtered = filtered.filter((study: {trimester: string}) => study.trimester === trimesterFilter);
}
setFilteredStudies(filtered);
}, [tagFilter, trimesterFilter]);
Expand All @@ -68,17 +97,17 @@ const Statistics = () => {
const npage = Math.ceil(filteredStudies.length / recordsPage);

// Sort caseStudies by popularity
const sortedStudiesByPopularity = [...caseStudies].sort((a, b) => {
const sortedStudiesByPopularity = [...caseStudies].sort((a: {popularity: string}, b: {popularity: string}) => {
const popularityA = parseFloat(a.popularity.replace('%', ''));
const popularityB = parseFloat(b.popularity.replace('%', ''));
return popularityB - popularityA; // Descending order
});


// Counting the values of trimester to plot on the graph
const tri1 = caseStudies.filter((item) => item.trimester === "1").length;
const tri2 = caseStudies.filter((item) => item.trimester === "2").length;
const tri3 = caseStudies.filter((item) => item.trimester === "3").length;
const tri1 = caseStudies.filter((item: {trimester: string}) => item.trimester === "1").length;
const tri2 = caseStudies.filter((item: {trimester: string}) => item.trimester === "2").length;
const tri3 = caseStudies.filter((item: {trimester: string}) => item.trimester === "3").length;

// Store the required variables for plotting the graph
const data1 = {
Expand Down Expand Up @@ -229,12 +258,12 @@ const Statistics = () => {
</thead>
<tbody>
{records
.filter((item) => {
.filter((item: {tag: string}) => {
return search.toLowerCase() === ""
? item
: item.tag.toLowerCase().includes(search);
})
.map((study, index) => (
.map((study: {id: string, tag: string, publishNumber: string, popularity: string }, index) => (
<tr
key={study.id}
className={index % 2 === 0 ? "bg-gray-100" : "bg-white"}
Expand Down
44 changes: 44 additions & 0 deletions next_webapp/src/app/api/statistics/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import handleRequest from '../../../mongodb/CaseStudies';

export async function GET(request: Request) {
try {
const reqCount = {
method: 'GET',
query: {}
};

const resStats = {
status({statusCode}: { statusCode: any }) {
this.statusCode = statusCode;
return this;
},
json({data}: { data: any }) {
this.data = data
console.log('Response for count request:', data);
},
end({message}: { message: any }) {
this.message = message
console.log('Response ended:', message);
},
statusCode: 400,
data: {},
message: ""
};

await handleRequest(reqCount, resStats);
const statusCode = resStats.statusCode | 200;
const data = resStats.data ;

// Returning the response data
return new Response(JSON.stringify(data), {
status: statusCode,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error('Error handling request:', error);
return new Response(JSON.stringify({ message: 'Failed to fetch statistics' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}
36 changes: 36 additions & 0 deletions next_webapp/src/mongodb/CaseStudies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const dbConnect = require('../../lib/mongodb');
const CaseStudy = require('./CaseStudy');

async function handleRequest(req, res) {
await dbConnect();

const { method } = req;

switch (method) {
case 'GET':
console.log('Called all studies');
try {
// Retrieve all case studies without the _id field
const caseStudies = await CaseStudy.find({})
.select('-_id'); // Exclude the _id field

res.status(200).json({ success: true, data: caseStudies });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
break;
case 'POST':
try {
const useCase = await CaseStudy.create(req.body);
res.status(201).json({ success: true, data: useCase });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
break;
default:
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${method} Not Allowed`);
}
}

module.exports = handleRequest;
27 changes: 27 additions & 0 deletions next_webapp/src/mongodb/CaseStudy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const mongoose = require('mongoose');

// Define the schema for the CaseStudy collection
const CaseStudySchema = new mongoose.Schema({
tag: {
type: String,
required: [true, 'Please provide a tag for this use case.'],
maxlength: [30, 'Tag cannot be more than 30 characters']
},
publishNumber: {
type: String,
required: [true, 'Please provide a publish number for this use case.']
},
popularity: {
type: String,
required: [true, 'Please provide a popularity percentage for this use case.'],
match: [/^\d{1,3}%$/, 'Popularity must be a percentage in the format XX%']
},
trimester: {
type: String,
required: [true, 'Please provide a trimester for this use case.'],
match: [/^[1-3]$/, 'Trimester must be one of "1", "2", or "3"']
}
});

// Export the model, using 'CaseStudy' if it doesn't already exist
module.exports = mongoose.models.CaseStudy || mongoose.model('CaseStudy', CaseStudySchema);
23 changes: 0 additions & 23 deletions next_webapp/src/mongodb/UseCase.js

This file was deleted.

64 changes: 0 additions & 64 deletions next_webapp/src/mongodb/UseCases.js

This file was deleted.

Loading
Loading