Skip to content

Refactor file upload and toast notifications #472

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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 0 additions & 1 deletion opensaas-sh/app_diff/deletions
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
src/client/static/open-saas-banner-dark.png
src/client/static/open-saas-banner-light.png
src/landing-page/components/Hero.tsx
src/landing-page/contentSections.ts
src/payment/lemonSqueezy/checkoutUtils.ts
src/payment/lemonSqueezy/paymentDetails.ts
src/payment/lemonSqueezy/paymentProcessor.ts
Expand Down
21 changes: 20 additions & 1 deletion opensaas-sh/app_diff/main.wasp.diff
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,26 @@
httpRoute: (POST, "/payments-webhook")
}
//#endregion
@@ -281,7 +279,6 @@
@@ -245,6 +243,18 @@
fn: import { deleteFile } from "@src/file-upload/operations",
entities: [User, File]
}
+
+job deleteFilesJob {
+ executor: PgBoss,
+ perform: {
+ fn: import { deleteFilesJob } from "@src/file-upload/workers"
+ },
+ schedule: {
+ cron: "0 0 * * *" // every day at midnight
+ // cron: "* * * * *" // every minute. useful for debugging
+ },
+ entities: [File]
+}
//#endregion

//#region Analytics
@@ -291,7 +301,6 @@
component: import AdminCalendar from "@src/admin/elements/calendar/CalendarPage"
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
--- template/app/migrations/20250731133938_drop_upload_url_from_file/migration.sql
+++ opensaas-sh/app/migrations/20250731133938_drop_upload_url_from_file/migration.sql
@@ -0,0 +1,8 @@
+/*
+ Warnings:
+
+ - You are about to drop the column `uploadUrl` on the `File` table. All the data in the column will be lost.
+
+*/
+-- AlterTable
+ALTER TABLE "File" DROP COLUMN "uploadUrl";
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
--- template/app/migrations/20250806121259_add_s3_key_file/migration.sql
+++ opensaas-sh/app/migrations/20250806121259_add_s3_key_file/migration.sql
@@ -0,0 +1,11 @@
+/*
+ Warnings:
+
+ - You are about to drop the column `key` on the `File` table. All the data in the column will be lost.
+ - Added the required column `s3Key` to the `File` table without a default value. This is not possible if the table is not empty.
+
+*/
+-- AlterTable
+DELETE FROM "File";
+ALTER TABLE "File" DROP COLUMN "key",
+ADD COLUMN "s3Key" TEXT NOT NULL;
64 changes: 36 additions & 28 deletions opensaas-sh/app_diff/package-lock.json.diff

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

2 changes: 1 addition & 1 deletion opensaas-sh/app_diff/package.json.diff
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
"@aws-sdk/client-s3": "^3.523.0",
"@aws-sdk/s3-presigned-post": "^3.750.0",
@@ -36,6 +41,7 @@
"react-apexcharts": "1.4.1",
"react-dom": "^18.2.0",
"react-hook-form": "^7.60.0",
"react-hot-toast": "^2.4.1",
+ "react-icons": "^5.5.0",
"react-router-dom": "^6.26.2",
"stripe": "18.1.0",
Expand Down
24 changes: 24 additions & 0 deletions opensaas-sh/app_diff/src/client/App.tsx.diff
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
--- template/app/src/client/App.tsx
+++ opensaas-sh/app/src/client/App.tsx
@@ -4,6 +4,7 @@
import './Main.css';
import NavBar from './components/NavBar/NavBar';
import { demoNavigationitems, marketingNavigationItems } from './components/NavBar/constants';
+import { useIsLandingPage } from './hooks/useIsLandingPage';
import CookieConsentBanner from './components/cookie-consent/Banner';
import { Toaster } from '../components/ui/toaster';

@@ -13,11 +14,8 @@
*/
export default function App() {
const location = useLocation();
- const isMarketingPage = useMemo(() => {
- return location.pathname === '/' || location.pathname.startsWith('/pricing');
- }, [location]);
-
- const navigationItems = isMarketingPage ? marketingNavigationItems : demoNavigationitems;
+ const isLandingPage = useIsLandingPage();
+ const navigationItems = isLandingPage ? marketingNavigationItems : demoNavigationitems;

const shouldDisplayAppNavBar = useMemo(() => {
return (
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
--- template/app/src/client/components/NavBar/constants.ts
+++ opensaas-sh/app/src/client/components/NavBar/constants.ts
@@ -9,7 +9,6 @@
@@ -9,12 +9,12 @@

export const marketingNavigationItems: NavigationItem[] = [
{ name: 'Features', to: '/#features' },
- { name: 'Pricing', to: routes.PricingPageRoute.to },
...staticNavigationItems,
] as const;

export const demoNavigationitems: NavigationItem[] = [
{ name: 'AI Scheduler', to: routes.DemoAppRoute.to },
{ name: 'File Upload', to: routes.FileUploadRoute.to },
+ { name: 'Pricing', to: routes.PricingPageRoute.to },
...staticNavigationItems,
] as const;
27 changes: 23 additions & 4 deletions opensaas-sh/app_diff/src/file-upload/fileUploading.ts.diff
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
--- template/app/src/file-upload/fileUploading.ts
+++ opensaas-sh/app/src/file-upload/fileUploading.ts
@@ -1,5 +1,5 @@
-import { createFile } from 'wasp/client/operations';
@@ -1,5 +1,7 @@
+import type { User } from 'wasp/entities';
import axios from 'axios';
+import { createFile } from 'wasp/client/operations';
import { ALLOWED_FILE_TYPES, MAX_FILE_SIZE_BYTES } from './validation';
+import { PrismaClient } from '@prisma/client';

export type FileWithValidType = Omit<File, 'type'> & { type: AllowedFileType };
type AllowedFileTypes = (typeof ALLOWED_FILE_TYPES)[number];
export type FileWithValidType = File & { type: AllowedFileTypes };
@@ -51,3 +53,17 @@
function isFileWithAllowedFileType(file: File): file is FileWithValidType {
return ALLOWED_FILE_TYPES.includes(file.type as AllowedFileTypes);
}
+
+export async function checkIfUserHasReachedFileUploadLimit({ userId, prismaFileDelegate }: { userId: User['id']; prismaFileDelegate: PrismaClient['file'] }) {
+ const numberOfFilesByUser = await prismaFileDelegate.count({
+ where: {
+ user: {
+ id: userId,
+ },
+ },
+ });
+ if (numberOfFilesByUser >= 2) {
+ return true;
+ }
+ return false;
+}
41 changes: 18 additions & 23 deletions opensaas-sh/app_diff/src/file-upload/operations.ts.diff
Original file line number Diff line number Diff line change
@@ -1,39 +1,34 @@
--- template/app/src/file-upload/operations.ts
+++ opensaas-sh/app/src/file-upload/operations.ts
@@ -1,14 +1,14 @@
@@ -1,6 +1,5 @@
-import * as z from 'zod';
-import { HttpError } from 'wasp/server';
import { type File } from 'wasp/entities';
+import { HttpError } from 'wasp/server';
import {
type CreateFile,
type GetAllFilesByUser,
type GetDownloadFileSignedURL,
@@ -8,6 +7,8 @@
type CreateFileUploadUrl,
type AddFileToDb,
} from 'wasp/server/operations';
+import { checkIfUserHasReachedFileUploadLimit } from './fileUploading';
+import * as z from 'zod';

-import { getUploadFileSignedURLFromS3, getDownloadFileSignedURLFromS3 } from './s3Utils';
import { ensureArgsSchemaOrThrowHttpError } from '../server/validation';
+import { getDownloadFileSignedURLFromS3, getUploadFileSignedURLFromS3 } from './s3Utils';
import { ALLOWED_FILE_TYPES } from './validation';

const createFileInputSchema = z.object({
@@ -37,6 +37,18 @@
userId: context.user.id,
});
import {
getUploadFileSignedURLFromS3,
@@ -37,6 +38,14 @@
throw new HttpError(401);
}

+ const numberOfFilesByUser = await context.entities.File.count({
+ where: {
+ user: {
+ id: context.user.id,
+ },
+ },
+ const userFileLimitReached = await checkIfUserHasReachedFileUploadLimit({
+ userId: context.user.id,
+ prismaFileDelegate: context.entities.File,
+ });
+
+ if (numberOfFilesByUser >= 2) {
+ throw new HttpError(403, 'Thanks for trying Open SaaS. This demo only allows 2 file uploads per user.');
+ if (userFileLimitReached) {
+ throw new HttpError(403, 'This demo only allows 2 file uploads per user.');
+ }
+
await context.entities.File.create({
data: {
name: fileName,
const { fileType, fileName } = ensureArgsSchemaOrThrowHttpError(createFileInputSchema, rawArgs);

return await getUploadFileSignedURLFromS3({
15 changes: 0 additions & 15 deletions opensaas-sh/app_diff/src/file-upload/s3Utils.ts.diff

This file was deleted.

32 changes: 32 additions & 0 deletions opensaas-sh/app_diff/src/file-upload/workers.ts.diff
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
--- template/app/src/file-upload/workers.ts
+++ opensaas-sh/app/src/file-upload/workers.ts
@@ -0,0 +1,29 @@
+import type { DeleteFilesJob } from 'wasp/server/jobs';
+import { deleteFileFromS3 } from './s3Utils';
+
+export const deleteFilesJob: DeleteFilesJob<never, void> = async (_args, context) => {
+ const filesToDelete = await context.entities.File.findMany({
+ where: {
+ createdAt: {
+ lt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest we do

const last7Days = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7);

So it's more clear what is the limit. Or even better:

const dayInMiliseconds = 1000 * 60 * 60 * 24;
const timeLimitToDeleteFiles = Date.now() - 7 * dayInMiliseconds;

Something along those lines.

+ },
+ },
+ select: { s3Key: true, id: true },
+ });
+
+ for (const file of filesToDelete) {
+ try {
+ await deleteFileFromS3({ s3Key: file.s3Key });
+ } catch (err) {
+ console.error(`Failed to delete S3 file with key ${file.s3Key}:`, err);
+ }
+ }
+
+ const deletedFiles = await context.entities.File.deleteMany({
+ where: {
+ id: { in: filesToDelete.map((file) => file.id) },
+ },
+ });
Comment on lines +17 to +29
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is fine, but it would be better done in a Prisma transaction:

try {
  await prisma.$transaction(async (tx) => {
    await tx.file.delete(...)
    await deleteFileFromS3(...)
  })
} catch (err) {
  // If something went wrong with deleting the file from S3, the file won't be deleted from the database
}

I'm not sure if we this is too fancy @FranjoMindek

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We use prisma transactions elsewhere in the code so I think its fine to use it here too.

+
+ console.log(`Deleted ${deletedFiles.count} files`);
+};
Loading