Skip to content

Commit

Permalink
Merge pull request #115 from brolag/feature/code-cleanup
Browse files Browse the repository at this point in the history
Feature/code cleanup
  • Loading branch information
JoelVR17 authored Feb 24, 2025
2 parents 965d297 + 1dc4e08 commit 6f87f2d
Show file tree
Hide file tree
Showing 10 changed files with 416 additions and 297 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,7 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts

# instructions
instructions/
instructions/*
7 changes: 6 additions & 1 deletion src/@types/escrow.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CreatedAt, UpdatedAt } from "./dates.entity";
import type { CreatedAt, UpdatedAt } from "./dates.entity";

export type MilestoneStatus = "completed" | "approved" | "pending";

Expand Down Expand Up @@ -87,3 +87,8 @@ export type EditMilestonesPayload = {
escrow: EscrowPayload;
signer: string;
};

export interface BalanceItem {
address: string;
balance: number;
}
43 changes: 36 additions & 7 deletions src/components/modules/escrow/hooks/my-escrows.hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
useGlobalAuthenticationStore,
useGlobalBoundedStore,
} from "@/core/store/data";
import { useState, useEffect, useMemo } from "react";
import { useState, useEffect, useMemo, useRef, useCallback } from "react";

interface useMyEscrowsProps {
type: string;
Expand All @@ -19,6 +19,9 @@ const useMyEscrows = ({ type }: useMyEscrowsProps) => {
const [expandedRows, setExpandedRows] = useState<string[]>([]);
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(15);
const [isLoading, setIsLoading] = useState(false);
const fetchingRef = useRef(false);
const lastFetchKey = useRef("");

const totalPages = Math.ceil(totalEscrows / itemsPerPage);

Expand All @@ -31,15 +34,40 @@ const useMyEscrows = ({ type }: useMyEscrowsProps) => {
);
}, [escrows, currentPage, itemsPerPage]);

const memoizedFetchEscrows = useCallback(async () => {
if (!address || fetchingRef.current) return;
const fetchKey = `${address}-${type}`;
if (fetchKey === lastFetchKey.current) return;
try {
fetchingRef.current = true;
lastFetchKey.current = fetchKey;
setIsLoading(true);
await fetchAllEscrows({ address, type });
} catch (error) {
console.error("[MyEscrows] Error fetching escrows:", error);
} finally {
setIsLoading(false);
fetchingRef.current = false;
}
}, [address, type, fetchAllEscrows]);

useEffect(() => {
const fetchEscrows = async () => {
if (address) {
fetchAllEscrows({ address, type });
}
let timeoutId: NodeJS.Timeout;

const debouncedFetch = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
memoizedFetchEscrows();
}, 100);
};

fetchEscrows();
}, []);
debouncedFetch();

return () => {
clearTimeout(timeoutId);
fetchingRef.current = false;
};
}, [memoizedFetchEscrows]);

const toggleRowExpansion = (rowId: string) => {
setExpandedRows((prev) =>
Expand All @@ -66,6 +94,7 @@ const useMyEscrows = ({ type }: useMyEscrowsProps) => {
itemsPerPageOptions,
toggleRowExpansion,
expandedRows,
isLoading,
};
};

Expand Down
75 changes: 75 additions & 0 deletions src/components/modules/escrow/services/escrow.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type {
Escrow,
EscrowPayload,
BalanceItem,
} from "@/@types/escrow.entity";
import {
getAllEscrowsByUser,
updateEscrow,
addEscrow,
} from "../server/escrow.firebase";
import { getBalance } from "./get-balance.service";

export const fetchAllEscrows = async ({
address,
type = "approver",
}: {
address: string;
type: string;
}): Promise<Escrow[]> => {
const escrowsByUser = await getAllEscrowsByUser({ address, type });
const contractIds = escrowsByUser.data.map(
(escrow: Escrow) => escrow.contractId,
);

if (!Array.isArray(contractIds)) {
throw new Error("contractIds is not a valid array.");
}

const response = await getBalance(address, contractIds);
const balances = response.data as BalanceItem[];

return Promise.all(
escrowsByUser.data.map(async (escrow: Escrow) => {
const matchedBalance = balances.find(
(item) => item.address === escrow.contractId,
);

const plainBalance = matchedBalance ? matchedBalance.balance : 0;
const currentBalance = escrow.balance ? Number(escrow.balance) : 0;

if (currentBalance !== plainBalance) {
await updateEscrow({
escrowId: escrow.id,
payload: { balance: String(plainBalance) },
});
escrow.balance = String(plainBalance);
}

return escrow;
}),
);
};

export const addNewEscrow = async (
payload: EscrowPayload,
address: string,
contractId: string,
): Promise<Escrow | undefined> => {
const response = await addEscrow({ payload, address, contractId });
return response?.data;
};

export const updateExistingEscrow = async ({
escrowId,
payload,
}: {
escrowId: string;
payload: Partial<EscrowPayload>;
}): Promise<Escrow | undefined> => {
const response = await updateEscrow({
escrowId,
payload: { ...payload, balance: String(payload.balance || 0) },
});
return response?.data;
};
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,11 @@ const EditMilestonesDialog = ({
<TooltipInfo content="Key stages or deliverables for the escrow." />
</FormLabel>
{milestones.map((milestone, index) => (
<>
<div key={index} className="flex items-center space-x-4">
<div
key={`milestone-${index}`}
className="flex flex-col gap-4"
>
<div className="flex items-center space-x-4">
{milestone.flag ? (
<Badge className="uppercase max-w-24">Approved</Badge>
) : (
Expand Down Expand Up @@ -117,7 +120,7 @@ const EditMilestonesDialog = ({
Add Item
</Button>
)}
</>
</div>
))}
</div>
</div>
Expand Down
Loading

0 comments on commit 6f87f2d

Please sign in to comment.