Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Import from bucket for global items #1156

Merged
merged 18 commits into from
Aug 24, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 67 additions & 20 deletions packages/app/components/item/ImportForm.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
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 '../../hooks/useTheme';
import * as DocumentPicker from 'expo-document-picker';
import { useImportPackItem } from 'app/hooks/packs/useImportPackItem';
import { useImportItem } from 'app/hooks/items/useImportItem';
import { useImportFromBucket } from 'app/hooks/items/useImportFromBucket';
import useResponsive from 'app/hooks/useResponsive';

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

const data = [
{ label: 'CSV', value: '.csv', key: '.csv' },
{ label: 'Other', value: '*', key: '*' },
const options = [
{ label: 'Rei', value: 'rei', key: 'Rei' },
{ label: 'Sierra', value: 'sierra', key: 'Sierra' },
{ label: 'Cabelas', value: 'cabelas', key: 'Cabelas' },
{ label: 'Moosejaw', value: 'moosejaw', key: 'Moosejaw' },
{ label: 'Backcountry', value: 'backcountry', key: 'Backcountry' },
];

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

export const ImportForm: FC<ImportFormProps> = ({
packId,
ownerId,
Expand All @@ -41,31 +47,57 @@ 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);
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 +112,25 @@ 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 });
}
} else {
handleImportFromBucket(
{ directory: selectedType.value, ownerId },
() => {
setIsImporting(false);
closeModalHandler();
},
);
}
} catch (err) {
console.error('Error importing file:', err);
} finally {
closeModalHandler();
setIsImporting(false);
}
};

Expand All @@ -100,19 +142,24 @@ 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>
);
Expand Down
2 changes: 1 addition & 1 deletion packages/app/components/item/ImportItemGlobal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const ImportItemGlobal = () => {
const ownerId = authUser?.id;

if (!authUser) {
return null; // or some fallback
return null;
}

const { setIsModalOpen } = useModal();
Expand Down
65 changes: 65 additions & 0 deletions packages/app/hooks/items/useImportFromBucket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { useCallback } from 'react';
import { queryTrpc } from 'app/trpc';
import { useOfflineQueue } from 'app/hooks/offline';
import { useItemsUpdater } from './useItemsUpdater';

interface State {
items?: Array<{ id: string }>;
}

export const useImportFromBucket = () => {
const utils = queryTrpc.useContext();
const { mutateAsync } = queryTrpc.importFromBucket.useMutation();
const { isConnected, addOfflineRequest } = useOfflineQueue();
const updateItems = useItemsUpdater();

const handleImportFromBucket = useCallback(
async ({ directory, ownerId }, onSuccess) => {
if (isConnected) {
try {
const data = await mutateAsync({ directory, ownerId });
const newItems = Array.isArray(data) ? data : [];
updateItems((prevState: State = {}) => {
const prevItems = Array.isArray(prevState.items)
? prevState.items
: [];
return {
...prevState,
items: [...newItems, ...prevItems],
};
});

utils.getItemsGlobally.invalidate();
utils.getItemsGlobally.refetch();
onSuccess();
} catch (error) {
console.error('Error fetching items:', error);
}
} else {
addOfflineRequest('importFromBucket', { directory, ownerId });

updateItems((prevState: State = {}) => {
onSuccess();
const prevItems = Array.isArray(prevState.items)
? prevState.items
: [];

return {
...prevState,
items: [
{
directory,
ownerId,
global: true,
},
...prevItems,
],
};
});
}
},
[updateItems, isConnected, mutateAsync, utils, addOfflineRequest],
);

return { handleImportFromBucket };
};
26 changes: 16 additions & 10 deletions packages/app/hooks/items/useImportItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,33 @@ export const useImportItem = () => {
const updateItems = useItemsUpdater();

const handleImportNewItems = useCallback(
(newItem) => {
(newItem, onSuccess) => {
if (isConnected) {
return mutate(newItem, {
onSuccess: () => {
updateItems((prevState: State = {}) => {
const prevItems = Array.isArray(prevState.items)
? prevState.items
: [];
return {
...prevState,
items: [newItem, ...prevItems], // Use the data returned from the server
};
});
utils.getItemsGlobally.invalidate();
onSuccess();
},
onError: (error) => {
console.error('Error adding item:', error);
},
});
}

addOfflineRequest('addItemGlobal', newItem);

updateItems((prevState: State = {}) => {
const prevItems = Array.isArray(prevState.items) ? prevState.items : [];

return {
...prevState,
items: [newItem, ...prevItems],
};
});
// Optionally, handle offline case here if needed
},
[updateItems],
[updateItems, isConnected, mutate, utils, addOfflineRequest],
);

return { handleImportNewItems };
Expand Down
11 changes: 5 additions & 6 deletions packages/app/hooks/packs/useImportPackItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ export const useImportPackItem = () => {
if (!newItem) {
throw new Error('Item data is not available.');
}

},
onSuccess: (data, newItem, context) => {
const previousPack = utils.getPackById.getData({
packId: newItem.packId,
});
Expand All @@ -32,14 +33,12 @@ export const useImportPackItem = () => {
newQueryData as any,
);

return {
previousPack,
};
},
onSuccess: () => {
utils.getPackById.invalidate();
utils.getPacks.invalidate();
},
onError: (error, newItem, context) => {
console.error('Error adding item:', error);
},
});

return {
Expand Down
3 changes: 3 additions & 0 deletions packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@react-native-community/geolocation": "^3.0.6",
"@react-native-community/netinfo": "11.1.0",
"@react-native-google-signin/google-signin": "^9.0.2",
"@react-native-picker/picker": "^2.7.7",
"@react-navigation/drawer": "^6.6.6",
"@react-navigation/native": "^6.1.6",
"@react-navigation/native-stack": "^6.9.12",
Expand Down Expand Up @@ -120,6 +121,7 @@
"react-native-google-places-autocomplete": "^2.5.1",
"react-native-paper": "^5.10.6",
"react-native-paper-dates": "^0.18.12",
"react-native-picker-select": "^9.2.0",
"react-native-reanimated": "~3.6.2",
"react-native-safe-area-context": "4.8.2",
"react-native-screens": "~3.29.0",
Expand All @@ -131,6 +133,7 @@
"react-native-webview": "13.6.4",
"react-redux": "^9.0.4",
"react-responsive": "^9.0.2",
"react-select": "^5.8.0",
"redux-persist": "^6.0.0",
"serve": "^14.2.0",
"server": "*",
Expand Down
41 changes: 41 additions & 0 deletions packages/ui/src/CascadedDropdown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { RSelect } from '@packrat/ui';
import React from 'react';
import { View, Platform } from 'react-native';

interface DropdownComponentProps {
width?: string | number;
style?: any;
placeholder?: any;
native?: boolean;
// zeego?: boolean;
[x: string]: any; // for the rest of the props
}

export const CascadedDropdownComponent: React.FC<DropdownComponentProps> = ({
width,
style = {},
placeholder,
// zeego = false,
...props
}) => {
const isWeb = Platform.OS === 'web';

return (
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
width: '100%',
}}
>
<RSelect
placeholder={placeholder || 'Select'}
native={!isWeb}
// zeego={zeego}
{...props}
/>
</View>
);
};

export default CascadedDropdownComponent;
1 change: 1 addition & 0 deletions packages/ui/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export { Container } from './Container';
export { MainContentWeb } from './MainContentWeb';
export { ContextMenu, RContextMenu } from './RContextMenu';
export { DropdownComponent } from './Dropdown';
export { CascadedDropdownComponent } from './CascadedDropdown';
// export { DropdownMenu, ExampleDropdown } from './RDropdown/DropdownBase';
export { RSkeleton } from './RSkeleton';

Expand Down
3 changes: 3 additions & 0 deletions packages/validations/src/index.d.ts
pinocchio-life-like marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './validations';
export * from './utils';
export { ZodSchema } from 'zod';
4 changes: 4 additions & 0 deletions packages/validations/src/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/validations/src/index.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/validations/src/utils.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { ZodSchema, z } from 'zod';
export type ValidationType<T extends ZodSchema> = z.infer<T>;
2 changes: 2 additions & 0 deletions packages/validations/src/utils.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading