Skip to content

Commit

Permalink
[refactor] cleanup new qr scanner logic.
Browse files Browse the repository at this point in the history
  • Loading branch information
ronniebeggs committed Apr 25, 2024
1 parent 3f97291 commit d5ef199
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 84 deletions.
85 changes: 8 additions & 77 deletions src/app/(BottomTabNavigation)/QRCodeScanner/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,8 @@ import Arrow from '../../../../assets/black-right-arrow.svg';
import CheckIcon from '../../../../assets/green-check.svg';
import ErrorIcon from '../../../../assets/warning.svg';
import { CaseContext } from '../../../context/CaseContext';
import {
getAllCaseIds,
getCaseById,
getCaseIdsFromUserId,
getCaseOrError,
} from '../../../supabase/queries/cases';
import { Case, CaseUid } from '../../../types/types';
import { getScannedData } from '../../../supabase/queries/cases';
import { Case } from '../../../types/types';

enum permissions {
UNDETERMINED,
Expand All @@ -31,11 +26,8 @@ enum permissions {

function QRCodeScannerScreen() {
const [hasPermission, setHasPermission] = useState(permissions.UNDETERMINED);
const [validIds, setValidIds] = useState<CaseUid[]>([]);
const [userIds, setUserIds] = useState<CaseUid[]>([]);
const [scannedCase, setScannedCase] = useState<Case>();
const [borderStyle, setBorderStyle] = useState(styles.notScanned);
const [isActive, setIsActive] = useState<boolean>(false);
const [recentScan, setRecentScan] = useState<string>('');
const [scannerState, setScannerState] = useState<
'valid' | 'invalid' | 'scanned' | ''
Expand Down Expand Up @@ -78,45 +70,15 @@ function QRCodeScannerScreen() {
),
};

const getAllCasesAndValidCases = async () => {
const allCases = await getAllCaseIds();
setValidIds(allCases);
const userCases = await getCaseIdsFromUserId('NO_ID');
setUserIds(userCases);
};

const getBarCodeScannerPermissions = async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
setHasPermission(
status === 'granted' ? permissions.GRANTED : permissions.DENIED,
);
};

// const setValidBarcodeStyle = () => {
// if (!isActive) {
// setBorderStyle(styles.validScan);
// setIsActive(true);
// setTimeout(() => {
// setBorderStyle(styles.notScanned);
// setIsActive(false);
// }, 1500);
// }
// };

// const setInvalidBarcodeStyle = async () => {
// if (!isActive) {
// setBorderStyle(styles.invalidScan);
// setIsActive(true);
// setTimeout(() => {
// setBorderStyle(styles.notScanned);
// setIsActive(false);
// }, 1500);
// }
// };

useEffect(() => {
getBarCodeScannerPermissions();
getAllCasesAndValidCases();
}, []);

useEffect(() => {
Expand All @@ -138,12 +100,15 @@ function QRCodeScannerScreen() {

const debouncedFetchData = useCallback(debounce(resetScanner, 1500), []);

// function called after every `BarCodeScanningResult` event triggered by scanner
const handleBarCodeScanned = (result: BarCodeScanningResult) => {
if (result.data !== recentScan) {
// process the barcode data if different from previous scans
processBarCodeData(result.data);
}
setRecentScan(result.data);

// trigger scanner feedback depending on scanning result
switch (scannerState) {
case 'invalid': {
Toast.show({
Expand Down Expand Up @@ -174,12 +139,9 @@ function QRCodeScannerScreen() {
};

const processBarCodeData = async (data: string) => {
const result = await getCaseOrError(data);

console.log(result);
const result = await getScannedData(data);

if (result.error) {
console.log('This code is invalid');
setScannerState('invalid');
setScannedCase(undefined);
setBorderStyle(styles.invalidScan);
Expand All @@ -188,53 +150,22 @@ function QRCodeScannerScreen() {

if (result.data) {
const newCase: Case = result.data.case;
// console.log(allCases);
// console.log(newCase);

// check whether the case has already been scanned
for (const existingCase of allCases) {
if (existingCase.id === newCase.id) {
console.log("You've already scanned this QR code");
setScannerState('scanned');
setScannedCase(undefined);
setBorderStyle(styles.invalidScan);
return;
}
}

console.log('should be good to go!');
// valid case scanned if this point reached
setScannedCase(newCase);
setScannerState('valid');
setBorderStyle(styles.validScan);
}

// const caseId = result.data;

// if (!validIds.includes(caseId)) {
// setUserCase(undefined);
// setInvalidBarcodeStyle();
// Toast.show({
// type: 'error',
// text1: 'Sorry! This QR code is invalid.',
// visibilityTime: 1500,
// });
// } else if (userIds.includes(caseId)) {
// setUserCase(undefined);
// setInvalidBarcodeStyle();
// Toast.show({
// type: 'error',
// text1: "You've already scanned this QR code.",
// visibilityTime: 1500,
// });
// } else {
// const caseData: Case = await getCaseById(caseId);
// setUserCase(caseData);
// setValidBarcodeStyle();
// Toast.show({
// type: 'success',
// text1: 'QR code successfully scanned',
// visibilityTime: 1500,
// });
// }
};

const routeToAddCase = () => {
Expand Down
22 changes: 15 additions & 7 deletions src/supabase/queries/cases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export async function getCaseById(caseId: CaseUid): Promise<Case> {
}
}

type Response =
type ScannerQueryResponse =
| {
data: { case: Case };
error: null;
Expand All @@ -81,24 +81,32 @@ type Response =
error: any;
};

// Fetch a single case using its ID
export async function getCaseOrError(caseId: CaseUid): Promise<Response> {
/**
* Query supabase according to the QR code scanner result.
* @param scannedData
* @returns `Case` or indicate that none exists.
*/
export async function getScannedData(
scannedData: string,
): Promise<ScannerQueryResponse> {
try {
const { data } = await supabase.from('cases').select().eq('caseId', caseId);
const { data } = await supabase
.from('cases')
.select()
.eq('caseId', scannedData);
if (!data) {
throw new Error('case not found');
}
const caseData: Case = await formatCase(data[0]);
const res: Response = {
const res: ScannerQueryResponse = {
data: {
case: caseData,
},
error: null,
};
return res;
} catch (error) {
// console.warn('(getCaseById)', error);
const res: Response = {
const res: ScannerQueryResponse = {
data: null,
error,
};
Expand Down

0 comments on commit d5ef199

Please sign in to comment.