|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import ListCard from "@/components/ListCard"; |
| 4 | +import MessageCard from "@/components/MessageCard"; |
| 5 | +import QRCodeScanner from "@/components/QRCodeScanner"; |
| 6 | +import { UserTile } from "@/components/user/UserTile"; |
| 7 | +import { UserService } from "@/services/UserService"; |
| 8 | +import { getUserFromQRCode } from "@/utils/utils"; |
| 9 | +import { ReactNode, useEffect, useState } from "react"; |
| 10 | + |
| 11 | +interface CompanyPromoteScannerProps { |
| 12 | + cannonToken: string; |
| 13 | + company: Company; |
| 14 | +} |
| 15 | + |
| 16 | +export default function CompanyPromoteScanner({ |
| 17 | + cannonToken, |
| 18 | + company, |
| 19 | +}: CompanyPromoteScannerProps) { |
| 20 | + const [topCard, setTopCard] = useState<ReactNode | undefined>(); |
| 21 | + const [bottomCard, setBottomCard] = useState<ReactNode | undefined>(); |
| 22 | + const [statusCard, setStatusCard] = useState<ReactNode | undefined>(); |
| 23 | + let cardsTimeout: NodeJS.Timeout; |
| 24 | + |
| 25 | + async function handleQRCodeScanned(data: string) { |
| 26 | + const scannedUser = getUserFromQRCode(data); |
| 27 | + cardsTimeout && clearTimeout(cardsTimeout); |
| 28 | + |
| 29 | + if (scannedUser) { |
| 30 | + setBottomCard(<UserTile user={scannedUser} />); |
| 31 | + if ( |
| 32 | + await UserService.promote(cannonToken, scannedUser.id, { |
| 33 | + role: "company", |
| 34 | + company: { |
| 35 | + company: company.id, |
| 36 | + edition: "32", // FIXME: Use dynamic value |
| 37 | + }, |
| 38 | + }) |
| 39 | + ) { |
| 40 | + setStatusCard( |
| 41 | + <MessageCard type="success" content="User successfully promoted!" />, |
| 42 | + ); |
| 43 | + } else { |
| 44 | + setStatusCard( |
| 45 | + <MessageCard |
| 46 | + type="danger" |
| 47 | + content="Error on promoting user. Try again!" |
| 48 | + />, |
| 49 | + ); |
| 50 | + } |
| 51 | + } else { |
| 52 | + setBottomCard(<MessageCard type="danger" content="Invalid QR-Code" />); |
| 53 | + } |
| 54 | + |
| 55 | + cardsTimeout = setTimeout(() => { |
| 56 | + setBottomCard(null); |
| 57 | + setStatusCard(null); |
| 58 | + }, 10 * 1000); // 10 seconds |
| 59 | + } |
| 60 | + |
| 61 | + useEffect(() => { |
| 62 | + setBottomCard((card) => ( |
| 63 | + <div className="flex flex-col justify-start gap-y-1"> |
| 64 | + {statusCard} |
| 65 | + {card} |
| 66 | + </div> |
| 67 | + )); |
| 68 | + }, [statusCard]); |
| 69 | + |
| 70 | + useEffect(() => { |
| 71 | + setTopCard( |
| 72 | + <ListCard |
| 73 | + title={company.name} |
| 74 | + img={company.img} |
| 75 | + link={`/companies/${company.id}`} |
| 76 | + />, |
| 77 | + ); |
| 78 | + }, [company]); |
| 79 | + |
| 80 | + return ( |
| 81 | + <QRCodeScanner |
| 82 | + onQRCodeScanned={handleQRCodeScanned} |
| 83 | + topCard={topCard} |
| 84 | + bottomCard={bottomCard} |
| 85 | + /> |
| 86 | + ); |
| 87 | +} |
0 commit comments