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

bug fix #1383

Merged
merged 3 commits into from
Dec 13, 2023
Merged

bug fix #1383

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
141 changes: 73 additions & 68 deletions components/TestimonyCard/ViewTestimony.tsx
Original file line number Diff line number Diff line change
@@ -1,64 +1,72 @@
import { NoResults } from "components/search/NoResults"
import { PaginationButtons } from "components/table"
import { TFunction, useTranslation } from "next-i18next"
import { useState } from "react"
import { Card as BootstrapCard, Col, Row } from "react-bootstrap"
import styled from "styled-components"
import { Card as MapleCard } from "../Card"
import { useAuth } from "../auth"
import { Testimony, UsePublishedTestimonyListing } from "../db"
import { SortTestimonyDropDown } from "./SortTestimonyDropDown"
import { Tab, Tabs } from "./Tabs"
import { TestimonyItem } from "./TestimonyItem"
import { useState, useEffect } from 'react';
import { NoResults } from "components/search/NoResults";
import { PaginationButtons } from "components/table";
import { TFunction, useTranslation } from "next-i18next";
import { Card as BootstrapCard, Col, Row } from "react-bootstrap";
import styled from "styled-components";
import { Card as MapleCard } from "../Card";
import { useAuth } from "../auth";
import { Testimony, UsePublishedTestimonyListing } from "../db";
import { SortTestimonyDropDown } from "./SortTestimonyDropDown";
import { Tab, Tabs } from "./Tabs";
import { TestimonyItem } from "./TestimonyItem";

const Container = styled.div`
font-family: Nunito;
`
`;

const Head = styled(BootstrapCard.Header)`
background-color: var(--bs-blue);
color: white;
font-size: 22px;
`

const ViewTestimony = (
props: UsePublishedTestimonyListing & {
search?: boolean
onProfilePage?: boolean
className?: string
isOrg?: boolean
}
) => {
`;

const ViewTestimony = (props: UsePublishedTestimonyListing & {
search?: boolean,
onProfilePage?: boolean,
className?: string,
isOrg?: boolean
}) => {
const {
items,
setFilter,
onProfilePage = false,
className,
pagination,
isOrg
} = props

const { user } = useAuth()
} = props;

const { user } = useAuth();
const [totalTestimonies, setTotalTestimonies] = useState<number>(0);

// Updated useEffect
useEffect(() => {
if (user?.uid) {
fetch(`/api/users/${user.uid}/testimony/countTestimonies`)
.then(response => response.json())
.then(data => {
if (data && data.count !== undefined) {
setTotalTestimonies(data.count);
}
})
.catch(error => {
console.error("Failed to count user testimonies", error);
});
}
}, [user?.uid]);

const testimony = items.result ?? []
const [orderBy, setOrderBy] = useState<string>()
const [activeTab, setActiveTab] = useState(1)
const testimony = items.result ?? [];
const [orderBy, setOrderBy] = useState<string>();
const [activeTab, setActiveTab] = useState(1);

const handleTabClick = (e: Event, value: number) => {
setActiveTab(value)
}
setActiveTab(value);
};

const handleFilter = (filter: string | undefined) => {
if (filter === "organization") {
setFilter({ authorRole: "organization" })
}
if (filter === "user") {
setFilter({ authorRole: "user" })
}
if (filter === "") {
setFilter({ authorRole: "" })
}
}

setFilter({ authorRole: filter ?? '' });
};

const tabs = [
<Tab
key="at"
Expand All @@ -81,15 +89,15 @@ const ViewTestimony = (
value={3}
action={() => handleFilter("organization")}
/>
]
];

const { t } = useTranslation("testimony")
const { t } = useTranslation("testimony");

return (
<Container>
<MapleCard
className={className}
headerElement={<Head>{isOrg ? "Our Testimonies" : "Testimonies"}</Head>}
headerElement={<Head>{isOrg ? t("Our Testimonies") : t("Testimonies")}</Head>}
body={
<BootstrapCard.Body>
{!onProfilePage && (
Expand All @@ -107,7 +115,7 @@ const ViewTestimony = (
{onProfilePage && (
<Row className="justify-content-between mb-4">
<ShowPaginationSummary
testimony={testimony}
totalItems={totalTestimonies}
pagination={pagination}
t={t}
/>
Expand Down Expand Up @@ -154,37 +162,34 @@ const ViewTestimony = (
}
/>
</Container>
)
}
);
};

export default ViewTestimony
export default ViewTestimony;

function ShowPaginationSummary({
testimony,
totalItems,
pagination,
t
}: {
testimony: Testimony[]
pagination: { currentPage: number; itemsPerPage: number }
t: TFunction
totalItems: number;
pagination: { currentPage: number; itemsPerPage: number };
t: TFunction;
}) {
if (testimony.length < 1) {
return null
if (totalItems < 1) {
return <div>{t("viewTestimony.noTestimonies")}</div>;
}
const { currentPage, itemsPerPage } = pagination

const currentPageStart = (currentPage - 1) * itemsPerPage
let currentPageEnd = currentPage * itemsPerPage
if (currentPageEnd > testimony.length) {
currentPageEnd = currentPageStart + (testimony.length % itemsPerPage)

const { currentPage, itemsPerPage } = pagination;
const currentPageStart = (currentPage - 1) * itemsPerPage;
let currentPageEnd = currentPageStart + itemsPerPage;
if (currentPageEnd > totalItems) {
currentPageEnd = totalItems;
}
const totalItems = testimony.length

return (
<Col className="d-flex align-items-center">
{t("viewTestimony.showing")} {currentPageStart + 1}&ndash;{currentPageEnd}{" "}
{t("viewTestimony.outOf")}
{totalItems}
</Col>
)
<div>
{t("viewTestimony.showing")} {currentPageStart + 1}–{currentPageEnd} {t("viewTestimony.outOf")} {totalItems}
</div>
);
}
36 changes: 36 additions & 0 deletions pages/api/users/[uid]/testimony/countTestimonies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { initializeApp, cert, getApps } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore';
import type { NextApiRequest, NextApiResponse } from 'next';

// Initialize the Firebase app if it hasn't been initialized
if (!getApps().length) {
initializeApp({
credential: cert({
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
}),
// The database URL is not always needed here, but if you have one, you can add it.
// databaseURL: "https://your-project-id.firebaseio.com",
});
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { uid } = req.query; // 'uid' is the user ID from the URL

if (!uid) {
return res.status(400).json({ error: 'User ID is required' });
}

// Get the Firestore instance
const firestore = getFirestore();

try {
const testimoniesRef = firestore.collection('users').doc(uid as string).collection('publishedTestimony');
const snapshot = await testimoniesRef.get();
res.status(200).json({ count: snapshot.size });
} catch (error) {
console.error("Error fetching testimony count for user:", uid, error);
res.status(500).json({ error: 'Internal Server Error' });
}
}
Loading