Skip to content

Commit

Permalink
feat: use socket io for scan result
Browse files Browse the repository at this point in the history
close #77 close #78
  • Loading branch information
pociej committed Jun 18, 2024
1 parent 5d04055 commit e1f370e
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 22 deletions.
17 changes: 15 additions & 2 deletions backend/src/services/file/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { fileURLToPath } from "url";
import { v4 as uuidv4 } from "uuid";
import { mkdir } from "node:fs/promises";
import { debugLog } from "../../utils.js";
import { jwtDecode } from "jwt-decode";

const DIR_NAME = fileURLToPath(new URL("../../../../temp", import.meta.url));
export const fileService = fastifyPlugin(
Expand Down Expand Up @@ -55,9 +56,21 @@ export const fileService = fastifyPlugin(
reply.send({ message: "File uploaded" });
},
});
fastify.get("/scan-result", { websocket: true }, (socket) => {

fastify.io.of(`/scan-result`).on("connection", async (socket) => {
const user = jwtDecode<{
_id: string;
}>(socket.handshake.auth.token);
if (!user._id) {
throw new Error(`Wrong token`);
}
if (!user) {
throw new Error(
`User not found with id ${socket.handshake.auth.token}`
);
}
container.cradle.fileService.resultStream.subscribe((result) => {
socket.send(JSON.stringify(result));
socket.emit("event", JSON.stringify(result));
});
});

Expand Down
61 changes: 54 additions & 7 deletions frontend/src/components/homePage/events/event.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,13 +206,19 @@ const NewInvoiceEvent = (event: {
<Card bordered={true}>
<Card.Body>
<Card.Title>New Invoice</Card.Title>
<div>
<div>
Agreement ID: <ShortLink id={event.payload.agreementId}></ShortLink>
</div>
<div>
Invoice ID: <ShortLink id={event.payload.invoiceId}></ShortLink>
</div>
<div className="flex gap-2">
<div className="stat-title">Invoice ID</div>:{" "}
<ShortLink id={event.payload.invoiceId}></ShortLink>
</div>
<div className="flex gap-2">
<div className="stat-title">Agreement ID: </div>:{" "}
<ShortLink id={event.payload.agreementId}></ShortLink>
</div>
<div className="flex gap-2">
<div className="stat-title">Amount</div>:{" "}
<GLMAmountStat
amount={formatBalance(parseEther(event.payload.amount))}
></GLMAmountStat>
</div>
</Card.Body>
</Card>
Expand Down Expand Up @@ -314,6 +320,45 @@ const FileScanOk = (event: {
);
};

const NewDebitNoteEvent = (event: {
kind: Event.NEW_DEBIT_NOTE;
payload: Payload[Event.NEW_DEBIT_NOTE];
}) => {
return (
<>
{event.payload.paymentDueDate ? (
<Card bordered={true}>
<Card.Body>
<Card.Title>New Payable Debit Note</Card.Title>
<div className="flex gap-2">
<div className="stat-title">ID:</div>
<div>
<ShortLink id={event.payload.debitNoteId}></ShortLink>
</div>
</div>
<div className="flex gap-2">
<div className="stat-title">Agreement ID:</div>
<div>
<ShortLink id={event.payload.agreementId}></ShortLink>
</div>
</div>
<div className="flex gap-2">
<div className="stat-title">Amount </div>
<div>
<GLMAmountStat
amount={formatBalance(
parseEther(event.payload.totalAmountDue)
)}
></GLMAmountStat>
</div>
</div>
</Card.Body>
</Card>
) : null}
</>
);
};

export const EventCard = (event: EventType) => {
return (
<motion.div variants={variants} initial="hidden" animate="visible">
Expand Down Expand Up @@ -341,6 +386,8 @@ export const EventCard = (event: EventType) => {
return <FileScanError {...event} />;
case Event.FILE_SCAN_OK:
return <FileScanOk {...event} />;
case Event.NEW_DEBIT_NOTE:
return <NewDebitNoteEvent {...event} />;
}
})()}
</motion.div>
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/components/molecules/Uploader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ export const FileUploader = () => {
const [isUploading, setIsUploading] = useState(false);

useEffect(() => {
console;
console.log("files size", files.size);
if (files.size > 0) {
setIsUploading(true);
} else {
setIsUploading(false);
}
}, [files.size]);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
Expand Down
5 changes: 4 additions & 1 deletion frontend/src/components/providers/fileUploader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
useContext,
PropsWithChildren,
useCallback,
useEffect,
} from "react";

import useSWRMutation from "swr/mutation";
Expand All @@ -16,7 +17,9 @@ export const useUploadedFiles = () => {
const setProgress = (id: string, progress: number) => {
files.set(id, progress);
};

useEffect(() => {
console.log("useUploadedFiles", files.size);
}, []);
const removeFile = useCallback((id: string) => {
files.delete(id);
}, []);
Expand Down
34 changes: 24 additions & 10 deletions frontend/src/hooks/useScanResults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ import { fileStatus } from "types/file";
import { Event } from "types/events";
import { match } from "ts-pattern";
import { useFileUploader } from "components/providers/fileUploader";
import debug from "debug";
import { io } from "socket.io-client";
import { useEffect, useRef } from "react";
import { useLocalStorage } from "./useLocalStorage";
const log = debug("useScanResults");

export const useScanResults = () => {
log("useScanResults");
const { emit, events$, clean } = useEvents({
key: "scanResults",
eventKind: (s: any) => {
Expand All @@ -18,18 +24,26 @@ export const useScanResults = () => {

const { removeFile } = useFileUploader();

useSWRSubscription("scanResult", (key, { next }) => {
const eventSource = new WebSocket(
`${import.meta.env.VITE_BACKEND_WS_URL}/scan-result`
);
const socketRef = useRef(
io(`${import.meta.env.VITE_BACKEND_WS_URL}/scan-result`, {
autoConnect: false,
})
);

eventSource.addEventListener("message", (event) => {
const file = JSON.parse(event.data);
removeFile(file.id);
emit(file, file.result);
});
const [accessToken] = useLocalStorage("accessToken");

return () => eventSource.close();
useEffect(() => {
if (accessToken) {
socketRef.current.auth = { token: accessToken };
socketRef.current.connect();
console.log("connecting ");
socketRef.current.on("event", (event) => {
log("message", event);
const file = JSON.parse(event);
removeFile(file.id);
emit(file, file.result);
});
}
});

return {
Expand Down
7 changes: 6 additions & 1 deletion frontend/src/types/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@ export type Payload = {
txHash: `0x${string}`;
};

[Event.NEW_DEBIT_NOTE]: {};
[Event.NEW_DEBIT_NOTE]: {
agreementId: string;
debitNoteId: string;
totalAmountDue: string;
paymentDueDate: string;
};
};

export type EventType = EventWithPayload<Payload>;
Expand Down

0 comments on commit e1f370e

Please sign in to comment.