Skip to content

Commit

Permalink
Merge branch 'andrew_testing' into Add-biometric-authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
Isthisanmol authored Sep 2, 2024
2 parents 7368cdf + be67b87 commit f9f1570
Show file tree
Hide file tree
Showing 9 changed files with 170 additions and 29 deletions.
98 changes: 74 additions & 24 deletions packages/app/modules/item/components/ImportForm.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React, { useState, FC } from 'react';
import React, { useState, useEffect, FC } from 'react';
import { View, Platform } from 'react-native';
import { DropdownComponent, RButton, RText } from '@packrat/ui';
import { RButton, RText, CascadedDropdownComponent } from '@packrat/ui';
import useTheme from 'app/hooks/useTheme';
import * as DocumentPicker from 'expo-document-picker';
import { useImportPackItem } from 'app/modules/pack';
import { useImportItem } from '../hooks';
import { useImportItem, useImportFromBucket } from '../hooks';
import { useImportPackItem } from '../../pack/hooks';
import useResponsive from 'app/hooks/useResponsive';

interface ImportFormProps {
Expand All @@ -27,11 +27,16 @@ interface SelectedType {
value: string;
}

const data = [
{ label: 'CSV', value: '.csv', key: '.csv' },
{ label: 'Other', value: '*', key: '*' },
const options = [
{ label: 'bucket 1', value: 'bucket 1', key: 'bucket 1' },
{ label: 'bucket 2', value: 'bucket 2', key: 'bucket 1' },
{ label: 'bucket 3', value: 'bucket 3', key: 'bucket 1' },
{ label: 'bucket 4', value: 'bucket 4', key: 'bucket 1' },
{ label: 'bucket 5', value: 'bucket 5', key: 'bucket 1' },
];

const csvOption = [{ label: 'CSV', value: '.csv', key: '.csv' }];

export const ImportForm: FC<ImportFormProps> = ({
packId,
ownerId,
Expand All @@ -41,31 +46,59 @@ export const ImportForm: FC<ImportFormProps> = ({
const { currentTheme } = useTheme();
const { handleImportNewItems } = useImportItem();
const { importPackItem } = useImportPackItem();
const { handleImportFromBucket } = useImportFromBucket();
const { xxs } = useResponsive();

const [selectedType, setSelectedType] = useState<SelectedType>({
label: 'CSV',
value: '.csv',
});

const [buttonText, setButtonText] = useState('Import Item');
const [isImporting, setIsImporting] = useState(false);

useEffect(() => {
let interval: NodeJS.Timeout;
if (isImporting) {
interval = setInterval(() => {
setButtonText((prev) => {
if (prev.endsWith('...')) {
return 'Importing';
} else {
return prev + '.';
}
});
}, 500);
} else {
setButtonText('Import Item');
clearInterval(interval);
}

return () => clearInterval(interval);
}, [isImporting]);

const handleSelectChange = (selectedValue: string) => {
const newValue = data.find((item) => item.value === selectedValue);
const newValue = [...csvOption, ...options].find(
(item) => item.value === selectedValue,
);
if (newValue) setSelectedType(newValue);
};

const handleItemImport = async () => {
setIsImporting(true);
try {
const res = await DocumentPicker.getDocumentAsync({
type: [selectedType.value],
});
if (selectedType.value === '.csv') {
const res = await DocumentPicker.getDocumentAsync({
type: [selectedType.value],
});

if (res.canceled) {
return;
}
if (res.canceled) {
setIsImporting(false);
return;
}

let fileContent;
let fileContent;

if (selectedType.value === '.csv') {
if (Platform.OS === 'web') {
if (res.assets && res.assets.length > 0) {
const file = res.assets[0];
Expand All @@ -80,15 +113,27 @@ export const ImportForm: FC<ImportFormProps> = ({
}

if (currentpage === 'items') {
handleImportNewItems({ content: fileContent, ownerId });
handleImportNewItems({ content: fileContent, ownerId }, () => {
setIsImporting(false);
closeModalHandler();
});
} else {
importPackItem({ content: fileContent, packId, ownerId });
setIsImporting(false);
closeModalHandler();
}
} else {
handleImportFromBucket(
{ directory: selectedType.value, ownerId },
() => {
setIsImporting(false);
closeModalHandler();
},
);
}
} catch (err) {
console.error('Error importing file:', err);
} finally {
closeModalHandler();
setIsImporting(false);
}
};

Expand All @@ -100,20 +145,25 @@ export const ImportForm: FC<ImportFormProps> = ({
justifyContent: 'space-between',
width: '100%',
marginBottom: 10,
zIndex: 1,
}}
>
<DropdownComponent
<CascadedDropdownComponent
value={selectedType}
data={data}
data={[
...(currentpage !== 'items'
? csvOption
: [...csvOption, ...options]),
]}
onValueChange={handleSelectChange}
placeholder={`Select file type: ${selectedType.label}`}
native={true}
style={{ width: '100%' }}
/>
</View>
<RButton onClick={handleItemImport}>
<RText style={{ color: currentTheme.colors.text }}>Import Item</RText>
<RButton onClick={handleItemImport} disabled={isImporting}>
<RText style={{ color: currentTheme.colors.text }}>{buttonText}</RText>
</RButton>
</View>
);
};
};
1 change: 1 addition & 0 deletions packages/app/modules/item/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export { useItemId } from './useItemId';
export { useItem } from './useItem';
export { useItemRow } from './useItemRow';
export { useImportItem } from './useImportItem';
export { useImportFromBucket } from './useImportFromBucket';
8 changes: 6 additions & 2 deletions packages/app/modules/item/screens/ItemsScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@ import {
RText,
} from '@packrat/ui';
import useResponsive from 'app/hooks/useResponsive';
import { useAuthUser } from 'app/modules/auth';

export function ItemsScreen() {
const { limit, handleLimitChange, page, handlePageChange } = usePagination();
const { data, isFetching, isError } = useItems({ limit, page });
const styles = useCustomStyles(loadStyles);
const [value, setValue] = useState('Food');

const authUser = useAuthUser();
const role = authUser?.role;

// for zeego = {false} options will be:
// const optionValues = ['Food', 'Water', 'Essentials'];

Expand Down Expand Up @@ -94,9 +98,9 @@ export function ItemsScreen() {
<BaseModal title="Add a global Item" trigger="Add Item">
<AddItemGlobal />
</BaseModal>
<BaseModal title="Import global Item" trigger="Import Item">
{ role === 'admin' && <BaseModal title="Import global Item" trigger="Import Item">
<ImportItemGlobal />
</BaseModal>
</BaseModal>}
</View>
</RStack>
{!isError && data?.items && Array.isArray(data.items) && (
Expand Down
2 changes: 1 addition & 1 deletion server/src/controllers/item/importFromBucket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const importFromBucket = async (c) => {
);

if (!latestFileName) {
throw new Error('No files found in the backcountry directory');
throw new Error('No files found in the supposed directory');
}

const fileData = await fetchFromS3(
Expand Down
64 changes: 64 additions & 0 deletions server/src/controllers/item/importNotifiedETL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import {
bulkAddItemsGlobalService,
parseCSVData,
fetchFromS3,
} from '../../services/item/item.service';
import { User } from '../../drizzle/methods/User';

export const importNotifiedETL = async (c) => {
const params = c.req.query();
const file_name = params.file_key;

const endpoint = c.env.BUCKET_ENDPOINT;
const bucket = c.env.BUCKET_NAME;
const method = 'GET';
const region = c.env.BUCKET_REGION;
const service = c.env.BUCKET_SERVICE;
const accessKeyId = c.env.BUCKET_ACCESS_KEY_ID;
const secretKey = c.env.BUCKET_SECRET_KEY;
const sessionToken = c.env.BUCKET_SESSION_TOKEN;
const algorithm = c.env.AWS_SIGN_ALGORITHM;
const x_amz_token = c.env.X_AMZ_SECURITY_TOKEN;

const userClass = new User();
const users = await userClass.getAdminId();

let ownerId = '';

if (users && users.length > 0) {
ownerId = users[0].id;
console.log('User ID:', ownerId);
} else {
console.log('No users found.');
}

try {
const fileData = await fetchFromS3(
`${endpoint}/${bucket}/${file_name}`,
method,
service,
region,
accessKeyId,
secretKey,
sessionToken,
algorithm,
x_amz_token,
);

const itemsToInsert = await parseCSVData(fileData, ownerId);

const insertedItems = await bulkAddItemsGlobalService(
itemsToInsert,
c.executionCtx,
);

return c.json({
message: 'Items inserted successfully',
data: insertedItems,
});

} catch (err) {
console.error('Error:', err);
return c.json({ error: 'An error occurred' });
}
};
1 change: 1 addition & 0 deletions server/src/controllers/item/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from './getItemsGlobally';
export * from './searchItemsByName';
export * from './getSimilarItems';
export * from './importFromBucket';
export * from './importNotifiedETL';
9 changes: 9 additions & 0 deletions server/src/drizzle/methods/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ export class User {
.get();
}

async getAdminId() {
return DbClient.instance
.select()
.from(UserTable)
.where(eq(UserTable.role, "admin"))
.limit(1)
.get();
}

generateUsernameFromEmail(email) {
return email ? email.split('@')[0] : 'defaultuser';
}
Expand Down
8 changes: 8 additions & 0 deletions server/src/routes/itemRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
importItemsGlobal,
getSimilarItems,
importFromBucket,
importNotifiedETL,
} from '../controllers/item/index';
import * as validator from '@packrat/validations';
import { tryCatchWrapper } from '../helpers/tryCatchWrapper';
Expand Down Expand Up @@ -45,6 +46,13 @@ router.get(
tryCatchWrapper(importFromBucket),
);

router.get(
'/importNotifiedETL',
// authTokenMiddleware,
// zodParser(validator.importNotifiedETL, 'query'),
tryCatchWrapper(importNotifiedETL),
);

router.get(
'/i/:id',
authTokenMiddleware,
Expand Down
8 changes: 6 additions & 2 deletions server/src/services/item/importFromBucketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,15 @@ export async function parseCSVData(fileData: string, ownerId: string) {
continue;
}

if (isNaN(Number(item.weight)) || Number(item.weight) <= 0) {
continue;
}

itemsToInsert.push({
name: item.name,
weight: item.claimed_weight || 0,
weight: item.weight || 0,
quantity: item.quantity || 1,
unit: item.claimed_weight_unit || 'g',
unit: item.weight_unit || 'g',
type: 'Essentials',
ownerId,
});
Expand Down

0 comments on commit f9f1570

Please sign in to comment.