You are absolutely right. My apologies, in the last correction, I removed the projectlead field from the main query to fix the UNION error, but didn't add it back in.
The problem is project.projectlead is undefined because it's not being selected in the main projectQuery.
Let's fix this by adding a LEFT JOIN to the projectmembership table in the main query. This is a much cleaner approach as it removes the need for the second userProjectMemberships query entirely.
Here is the corrected and optimized code:
javascript
router.get(
"/charity-projects/:ukcharitynumber",
authMiddleware,
async (req, res) => {
try {
console.log("Fetching transactions and project updates for charity...");
const { fetchByCharityId, fetchByTransactionId } = req.query;
const userId = getRequestingUserId(req.user);
const ukcharitynumber = req.params.ukcharitynumber;
const allowedRoles = [
"Charity Head", "Charity Admin", "Operations Head",
"Operations Admin", "Fundraising Head", "Fundraising Admin",
];
// Step 1: Fetch IDs of all projects the user has access to
const userProjectIds = knex("projectmembership")
.where("userid", userId)
.select("projectid");
const authorizedCharityProjects = knex("project as proj")
.innerJoin("charitymembership as chm", "proj.charityid", "chm.charityid")
.where("chm.userid", userId)
.whereRaw("chm.roles && ?", [allowedRoles])
.select("proj.id");
const accessibleProjectIdsQuery = knex.from(function () {
this.union([userProjectIds, authorizedCharityProjects]).as("accessibleProjects");
});
// --- KEY CHANGE IS HERE ---
// Step 2: Fetch project details, LEFT JOINING the user's membership status
const projectQuery = knex("project as proj")
.distinct("proj.id as projectid")
.select(
"proj.title as projecttitle",
"proj.currentamount",
"proj.isactive",
"cha.charityname",
"proj.currency",
"pm.projectlead" // Select the projectlead status for the current user
)
.innerJoin("charity as cha", "cha.ukcharitynumber", "proj.charityid")
// Left join on the user's specific membership for each project
.leftJoin({ pm: "projectmembership" }, function() {
this.on("pm.projectid", "=", "proj.id")
.andOnVal("pm.userid", "=", userId);
})
.where("cha.ukcharitynumber", ukcharitynumber)
.whereIn("proj.id", accessibleProjectIdsQuery);
const projects = await projectQuery;
// Now, each `project` object in this array will have a `projectlead` property
// which is `true`, `false`, or `null` (if the user is not a member).
if (!projects.length) {
return res.status(404).json({
message: "No projects found for this charity that you can view.",
});
}
// The separate `userProjectMemberships` query is no longer needed.
const projectIds = projects.map((p) => p.projectid);
// Step 3: Fetch transactions (no changes here)
let transactionQuery = knex("transaction as tra")
.select(
"tra.id", "tra.category as category", "tra.reason as whatfor",
"tra.title as whatbrought", "tra.amount", "tra.currency", "tra.proof",
"tra.isTransactionActive", "tra.datetime", "tra.projectid",
"tra.reviewerid", "tra.approved", "tra.reviewernote as reviewerNote",
"usr.firstname as firstName", "usr.lastname as lastName",
"reviewer.firstname as reviewerFirstName", "reviewer.lastname as reviewerLastName"
)
.innerJoin("user as usr", "usr.id", "tra.userid")
.leftJoin("user as reviewer", "reviewer.id", "tra.reviewerid")
.orderBy("tra.datetime", "desc");
if (fetchByTransactionId) {
transactionQuery.andWhere("tra.id", fetchByTransactionId);
} else {
transactionQuery.whereIn("tra.projectid", projectIds);
}
const transactions = await transactionQuery;
// Step 4: Fetch project updates (no changes here)
const projectUpdates = await knex("projectupdate")
.whereIn("projectid", projectIds)
.select("*"); // Select all fields for simplicity
// Step 5: Group everything together
const groupedProjects = projects
.map((project) => {
const projectTransactions = transactions.filter(
(t) => t.projectid === project.projectid
);
const updates = projectUpdates.filter(
(u) => u.projectid === project.projectid
);
if (fetchByTransactionId && projectTransactions.length === 0) return null;
// --- LOGIC IS NOW SIMPLIFIED ---
// `project.projectlead` is `true`, `false`, or `null` from our query.
const isProjectLead = project.projectlead === true;
const isProjectReporter = project.projectlead === false;
return {
projectid: project.projectid,
name: project.projecttitle,
budget: project.currentamount,
currency: project.currency,
isactive: project.isactive,
charityname: project.charityname,
projectlead: isProjectLead, // Now a clean boolean
projectReporter: isProjectReporter, // And this is also correct
transactions: projectTransactions.map((t) => ({
id: t.id,
category: t.category,
user: `${t.firstName} ${t.lastName}`,
reviewer:
t.reviewerFirstName && t.reviewerLastName
? {
firstName: t.reviewerFirstName,
lastName: t.reviewerLastName,
}
: null,
reviewerNote: t.reviewerNote,
amount: t.amount,
whatfor: t.whatfor,
whatbrought: t.whatbrought,
currency: t.currency,
proof: t.proof,
status:
t.approved === true
? "Accepted"
: t.approved === false
? "Rejected"
: "Pending",
transaction_details: t.whatfor,
isTransactionActive: t.isTransactionActive,
datetime: t.datetime,
time: new Date(t.datetime).toLocaleTimeString("en-GB"),
})),
projectUpdates: updates,
};
})
.filter(Boolean);
// Final response
res.status(200).json({
charityname: projects[0]?.charityname || "Unknown Charity",
projects: groupedProjects,
});
} catch (error) {
console.error(
"Failed to fetch transactions and updates for charity:",
error
);
res.status(500).json({
error: "Failed to fetch transactions and updates for charity",
});
}
}
);
Summary of Changes:
Modified projectQuery:
We added a .leftJoin() to projectmembership (aliased as pm).
The join condition is composite: it matches on projectid AND the current userId. This is crucial because it ensures we only get the membership status for the user making the request.
We added pm.projectlead to the .select() statement. For projects where the user is a member, this will be true or false. For projects they can see via charity role but aren't a member of, this will be null.
Removed Redundant Query: The separate userProjectMemberships query is no longer needed, making the code more efficient (one less database roundtrip).
Simplified Final Mapping:
The logic to determine projectlead and projectReporter is now much cleaner inside the .map() loop.
projectlead: project.projectlead === true; ensures you always return a proper boolean (true or false).
projectReporter: project.projectlead === false; correctly identifies reporters based on your business logic.
User
edit this component for best practices and make it readable. ideally projectlead shd be able to accept and reject transactions and project reporters should be able to edit transactions. there are some cases that if the userid is the creator for this transaction they must be able to perform some actions. is project reporter is false do not display the ""DropDownVertical icon". But in status === rejected, project reporter === false shd just view the rejection notice nothing more "import React, { useState, useRef } from "react";
import "../../transactionManageDesktop/transactionListDesktop.css";
import { useClickAway } from "react-use";
import { archiveTransaction, TransactionProps } from "../helper";
import TransactionManageGreenButton from "@/components/Icons/SVG/Transaction_Manage_green_button.svg";
import TransactionManageRedButton from "@/components/Icons/SVG/Transaction_Manage_red_button.svg";
import DropDownVertical from "@/components/Icons/SVG/Dropdown.svg";
import toast from "react-hot-toast";
import getStatusButton from "@/scenes/transactionManageDesktop/getStatusButton";
import {
handleUndoTransaction,
handleRejectTransaction,
handleApproveTransaction,
} from "@/scenes/transactionManage/helper";
import RejectionNoteModal from "@/scenes/transactionManageDesktop/RejectionNoteModal";
import { useSelector } from "react-redux";
import { RootState } from "@/redux/store";
import ConfirmDelete from "@/scenes/transactionManageDesktop/ConfirmDelete";
import EditTransactionModal from "../editTransactionModal";
Of course. This component has a lot of state, complex conditional rendering, and tangled logic, making it a perfect candidate for refactoring.
Here is a revised version that follows best practices for readability, state management, and separation of concerns.
Key Improvements in the Refactored Code:
Simplified State Management: Replaced 8 useState hooks with a single state object (modal) to manage which modal is open and for which transaction. This eliminates confusion and potential state conflicts.
Clearer User Capabilities: Created boolean constants (canApproveReject, canEdit, canArchive, etc.) at the top. This makes the rendering logic much easier to read and understand why a user can perform an action.
Centralized Modals: All modals (EditTransactionModal, ConfirmDelete, RejectionNoteModal) are now rendered once at the bottom of the component. Their visibility is controlled by the single modal state, preventing duplicate code.
Render Functions for Clarity: The massive if/else if block is broken down into smaller, focused render functions (renderPendingActions, renderAcceptedActions, etc.). This dramatically improves readability.
Dynamic Dropdown Menu: A single, reusable renderDropdown function is used to create the dropdown menu based on the actions available to the current user, reducing code duplication.
Adherence to Business Rules: The logic now strictly follows the requirements:
Project Leads can Accept/Reject.
Project Reporters can Edit (if they are the owner).
Transaction Owners can Archive.
The dropdown icon (⋮) only appears if there are actions available in it.
For Rejected status, non-reporters can only view the rejection note without a dropdown.
if (status === "Pending" && tx.isTransactionActive) {
// 1) If the user is a project lead…
if (isProjectLead) {
// 1a) …and they OWN this transaction
if (isTxOwner) {
return (
{/* 1) Approve button */}
<button
className="approve-button"
onClick={() => handleTransactionStatusChange(true)}
>
Your parent component (TransactionListDesktop.tsx or similar) will need a slight adjustment to pass the new props. Specifically, it needs to handle the state updates.
tsx
// In your parent component (e.g., TransactionListDesktop.tsx)
const [tsxList, setTsxList] = useState<TransactionProps[]>([]);
// ... fetch initial list
const handleTransactionUpdate = (updatedTx: Partial<TransactionProps> & { id: number }) => {
setTsxList(prevList =>
prevList.map(tx => tx.id === updatedTx.id ? { ...tx, ...updatedTx } : tx)
);
};
const handleTransactionArchive = (txId: number) => {
setTsxList(prevList => prevList.filter(tx => tx.id !== txId));
};
// Inside your .map() loop:
<ReviewMenu
key={tx.id}
tx={tx}
isProjectLead={project.projectlead} // Assuming these come from project data
isProjectReporter={project.projectReporter}
token={token}
onTransactionUpdate={handleTransactionUpdate}
onTransactionArchive={handleTransactionArchive}
/>
This new structure is far more maintainable, readable, and less prone to bugs.