Skip to content

Commit

Permalink
add endpoint init
Browse files Browse the repository at this point in the history
  • Loading branch information
pinocchio-life-like committed Jul 26, 2024
1 parent a5a820e commit 7f73e5b
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 89 deletions.
163 changes: 90 additions & 73 deletions packages/app/components/item/ImportForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Papa from 'papaparse';
import { InformUser } from 'app/utils/ToastUtils';
import { useAddPackItem } from 'app/hooks/packs/useAddPackItem';
import { useAddItem } from 'app/hooks/items';
import { useImportPackItem } from 'app/hooks/packs/useImportPackItem';

interface ImportFormProps {
showSubmitButton?: boolean;
Expand Down Expand Up @@ -42,6 +43,7 @@ export const ImportForm: FC<ImportFormProps> = ({
const { currentTheme } = useTheme();
const { addPackItem } = useAddPackItem();
const { handleAddNewItem } = useAddItem();
const { importPackItem } = useImportPackItem();

const [selectedType, setSelectedType] = useState<SelectedType>({
label: 'CSV',
Expand All @@ -64,8 +66,6 @@ export const ImportForm: FC<ImportFormProps> = ({
return;
}

console.log(res);

let fileContent;

if (selectedType.value === '.csv') {
Expand All @@ -82,79 +82,96 @@ export const ImportForm: FC<ImportFormProps> = ({
fileContent = await response.text();
}

Papa.parse(fileContent, {
header: true,
complete: (result) => {
const expectedHeaders = [
'Name',
'Weight',
'Unit',
'Quantity',
'Category',
];
// Get headers from the parsed result
const parsedHeaders = result.meta.fields;
try {
// Check if all expected headers are present
const allHeadersPresent = expectedHeaders.every((header) =>
parsedHeaders.includes(header),
);
if (!allHeadersPresent) {
throw new Error(
'CSV does not contain all the expected Item headers',
);
}
const data = result.data.map((item, index) => {
return {
id: `${Date.now().toString()}${index}`,
name: item.Name,
weight: Number(item.Weight),
unit: item.Unit,
quantity: Number(item.Quantity),
type: item.Category,
packId: packId,
ownerId: ownerId,
};
});
if (currentpage === 'items') {
// data.forEach((item, index) => {
// if (index < data.length - 1) {
// handleAddNewItem(item, () => {
// InformUser({
// title: 'Items imported successfully',
// placement: 'bottom',
// duration: 3000,
// style: { backgroundColor: 'green' },
// });
// });
// }
// });
} else {
importPackItem({ content: fileContent, packId, ownerId });
}

console.log('fileContent:', typeof fileContent);

console.log(data);
// Papa.parse(fileContent, {
// header: true,
// complete: (result) => {
// const expectedHeaders = [
// 'Name',
// 'Weight',
// 'Unit',
// 'Quantity',
// 'Category',
// ];
// // Get headers from the parsed result
// const parsedHeaders = result.meta.fields;
// try {
// // Check if all expected headers are present
// const allHeadersPresent = expectedHeaders.every((header) =>
// parsedHeaders.includes(header),
// );
// if (!allHeadersPresent) {
// throw new Error(
// 'CSV does not contain all the expected Item headers',
// );
// }
// const data = result.data.map((item, index) => {
// return {
// id: `${Date.now().toString()}${index}`,
// name: item.Name,
// weight: Number(item.Weight),
// unit: item.Unit,
// quantity: Number(item.Quantity),
// type: item.Category,
// packId: packId,
// ownerId: ownerId,
// };
// });

if (currentpage === 'items') {
data.forEach((item, index) => {
if (index < data.length - 1) {
handleAddNewItem(item, () => {
InformUser({
title: 'Items imported successfully',
placement: 'bottom',
duration: 3000,
style: { backgroundColor: 'green' },
});
});
}
});
} else {
data.forEach((item, index) => {
if (index < data.length - 1) {
addPackItem(item);
}
});
}
} catch (error) {
InformUser({
title:
'CSV does not contain the expected Item headers or data must be corrupt',
placement: 'bottom',
duration: 3000,
style: { backgroundColor: 'red' },
});
} finally {
closeModalHandler();
}
},
error: (error) => {
console.error('Error parsing CSV:', error);
},
});
// if (currentpage === 'items') {
// data.forEach((item, index) => {
// if (index < data.length - 1) {
// handleAddNewItem(item, () => {
// InformUser({
// title: 'Items imported successfully',
// placement: 'bottom',
// duration: 3000,
// style: { backgroundColor: 'green' },
// });
// });
// }
// });
// } else {
// data.forEach((item, index) => {
// if (index < data.length - 1) {
// addPackItem(item);
// }
// });
// }
// } catch (error) {
// InformUser({
// title:
// 'CSV does not contain the expected Item headers or data must be corrupt',
// placement: 'bottom',
// duration: 3000,
// style: { backgroundColor: 'red' },
// });
// } finally {
// closeModalHandler();
// }
// },
// error: (error) => {
// console.error('Error parsing CSV:', error);
// },
// });
}
} catch (err) {
console.error('Error importing file:', err);
Expand Down
17 changes: 1 addition & 16 deletions packages/app/hooks/packs/useImportPackItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@ import { queryTrpc } from '../../trpc';

export const useImportPackItem = () => {
const utils = queryTrpc.useContext();

// Use mutation for adding an item
const mutation = queryTrpc.addItem.useMutation({
const mutation = queryTrpc.importItems.useMutation({
onMutate: async (newItem) => {
// Check if newItem is not void
if (!newItem) {
throw new Error('Item data is not available.');
}

// Snapshot the previous value before the mutation

const previousPack = utils.getPackById.getData({
packId: newItem.packId,
});
Expand Down Expand Up @@ -45,22 +40,12 @@ export const useImportPackItem = () => {
previousPack,
};
},

onError: (err, newItem, context) => {
// if (context.previousPack) {
// utils.getPackById.setData(
// { packId: newItem.packId },
// context.previousPack,
// );
// }
},
onSuccess: () => {
utils.getPackById.invalidate();
utils.getPacks.invalidate();
},
});

// Return the mutate function and other relevant properties
return {
mutation,
importPackItem: mutation.mutate,
Expand Down
6 changes: 6 additions & 0 deletions packages/validations/src/validations/itemRoutesValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ export const addItem = z.object({
id: z.string().optional(),
});

export const importItem = z.object({
content: z.string(),
packId: z.string(),
ownerId: z.string(),
});

export type Item = z.infer<typeof addItem>;

export const editItem = z.object({
Expand Down
42 changes: 42 additions & 0 deletions server/src/controllers/item/importItems.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { protectedProcedure } from '../../trpc';
import { addItemService } from '../../services/item/item.service';
import * as validator from '@packrat/validations';

export const importItems = async (c) => {
try {
const { name, weight, quantity, unit, packId, type, ownerId } =
await c.req.json();

const result = await addItemService(
name,
weight,
quantity,
unit,
packId,
type,
ownerId,
);
return c.json({ result }, 200);
} catch (error) {
return c.json({ error: `${error.message}` }, 500);
}
};

export function importItemsRoute() {
return protectedProcedure
.input(validator.importItem)
.mutation(async (opts) => {
console.log('opsssssssssssssssssssssssts', opts.input);
// const result = await addItemService(
// name,
// weight,
// quantity,
// unit,
// packId,
// type,
// ownerId,
// opts.ctx.executionCtx,
// );
return 'result';
});
}
1 change: 1 addition & 0 deletions server/src/controllers/item/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './addGlobalItemToPack';
export * from './addItem';
export * from './importItems';
export * from './addItemGlobal';
export * from './deleteGlobalItem';
export * from './deleteItem';
Expand Down
2 changes: 2 additions & 0 deletions server/src/routes/trpcRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import {
addGlobalItemToPackRoute,
addItemGlobalRoute,
addItemRoute,
importItemsRoute,
deleteGlobalItemRoute,
deleteItemRoute,
editGlobalItemAsDuplicateRoute,
Expand Down Expand Up @@ -149,6 +150,7 @@ export const appRouter = trpcRouter({
getItemById: getItemByIdRoute(),
searchItemsByName: searchItemsByNameRoute(),
addItem: addItemRoute(), // Done
importItems: importItemsRoute(), // Done
editItem: editItemRoute(), // Done
deleteItem: deleteItemRoute(), // Done
addItemGlobal: addItemGlobalRoute(), // Done
Expand Down

0 comments on commit 7f73e5b

Please sign in to comment.