Skip to content

Feature/uploadthing integration#20

Closed
mzcoder-hub wants to merge 14 commits intoOpensyte:mainfrom
mzcoder-hub:feature/uploadthing-integration
Closed

Feature/uploadthing integration#20
mzcoder-hub wants to merge 14 commits intoOpensyte:mainfrom
mzcoder-hub:feature/uploadthing-integration

Conversation

@mzcoder-hub
Copy link

🚀 Add Organization Address Field & UploadThing Integration

📋 Overview

This PR introduces two major enhancements to the OpenSyte platform:

  1. Organization Address Field: Adds comprehensive address management for organizations
  2. UploadThing Integration: Replaces the custom file upload system with UploadThing service for improved reliability and performance

✨ Features

🏢 Organization Address Management

  • Database Schema: Added address field to the Organization model
  • UI Forms: Address input fields in all organization management forms
  • Invoice Integration: Organization address now appears in invoice emails
  • Full CRUD Support: Create, read, update operations for organization addresses

📤 UploadThing Integration

  • Modern Upload Service: Replaces custom upload implementation with UploadThing
  • Improved UX: Better loading states, error handling, and upload progress
  • Type Safety: Full TypeScript support with proper error handling
  • Documentation: Comprehensive setup and usage documentation

🔧 Technical Changes

Database & Schema

  • Added address: String? field to Organization model
  • Updated Zod schemas for type safety
  • Maintained backward compatibility

Frontend Components

Organization Forms Updated:

  • add-organization-dialog.tsx - Address field in creation form
  • edit-organization-dialog.tsx - Address field in editing form
  • organization-info-form.tsx - Address display and editing

New Upload Component:

  • uploadthing-image-upload.tsx - Modern upload component with improved UX
  • Replaced legacy image-upload.tsx component

Backend API

Organization Router:

  • Updated create/update schemas to include address field
  • Enhanced tRPC procedures to handle address data
  • Added address to all organization response objects

Invoice Integration:

  • Updated invoice email template to display organization address
  • Address appears in the "From" section of invoice emails
  • Backward compatible with organizations without addresses

Infrastructure

UploadThing Setup:

  • route.ts - API endpoint
  • uploadthing.ts - Client configuration
  • uploadthing.ts - Server configuration with file validation
  • Environment variable configuration

📁 Files Changed

Added Files

docs/guides/uploadthing-integration.md         # Setup documentation
src/app/api/uploadthing/route.ts               # UploadThing API endpoint
src/components/ui/uploadthing-image-upload.tsx # New upload component
src/lib/uploadthing.ts                         # Client config
src/server/uploadthing.ts                      # Server config

Modified Files

prisma/schema.prisma                           # Address field added
prisma/generated/zod/index.ts                  # Updated schemas
src/components/organizations/*.tsx              # Address form fields
src/components/settings/organization-info-form.tsx # Address display
src/server/api/routers/organization.ts         # Address API handling
src/server/api/routers/finance/invoice.ts      # Address in emails
src/server/email/templates/invoice-email.tsx   # Address display
.env.example                                   # UploadThing env vars
package.json                                   # UploadThing deps
next.config.js                                 # UploadThing config

Removed Files

src/app/api/upload/route.ts                    # Legacy upload API
src/components/ui/image-upload.tsx             # Legacy upload component
src/hooks/use-file-upload.ts                   # Legacy upload hook

🧪 Testing

  • ✅ Organization creation with address
  • ✅ Organization editing and address updates
  • ✅ Address display in organization settings
  • ✅ Address rendering in invoice emails
  • ✅ File upload functionality with UploadThing
  • ✅ Backward compatibility with existing organizations
  • ✅ Error handling for missing addresses

📚 Documentation

  • Added comprehensive UploadThing integration guide
  • Updated environment variable documentation
  • Included setup instructions and troubleshooting

🔄 Migration Notes

Database

  • The address field is optional, ensuring backward compatibility
  • Existing organizations will have null address values
  • No data migration required

Environment Variables

New required variables for UploadThing:

UPLOADTHING_TOKEN=your_token_here

Breaking Changes

  • Legacy upload components removed
  • Custom upload API endpoints removed
  • Applications using old upload system need to update to UploadThing

🎯 Impact

User Experience

  • Improved: Professional invoice emails now include organization addresses
  • Enhanced: Better file upload experience with progress indicators
  • Consistent: Unified address management across all organization forms

Developer Experience

  • Simplified: Reduced custom upload code maintenance
  • Reliable: UploadThing provides enterprise-grade file handling
  • Typed: Full TypeScript support for better development experience

📋 Checklist

  • Database schema updated
  • Frontend forms updated
  • Backend API updated
  • Email templates updated
  • TypeScript types generated
  • Environment variables documented
  • Legacy code removed
  • Documentation added
  • Manual testing completed

🚀 Deployment Notes

  1. Update environment variables with UploadThing credentials
  2. Run database schema sync: bun run db:push
  3. Restart application to load new configurations
  4. Verify file upload functionality in development

Commits:

  • 3829eea - feat: add organization address field
  • 1827270 - feat: implement UploadThing integration for file uploads

- Enhanced currency formatting in invoice preview and email templates
- Added proper IDR formatting (no decimals, thousands separators) using Intl.NumberFormat
- Updated formatCurrency and formatDecimal utility functions in server utils
- Improved invoice preview dialog with organization logo display and responsive design
- Added comprehensive currency formatting utilities in /lib/currency-utils.ts
- Updated backend invoice email generation to use proper IDR formatting
- Enhanced organization logo support across invoice preview and email templates
- Added image upload functionality for organization logos
- Created responsive invoice preview dialog with print/download capabilities
- Updated invoice router to include organization data in API responses

The changes ensure IDR amounts display as '1.000.000' instead of '1000000.00'
while maintaining proper formatting for other currencies like USD, EUR, etc.
- Remove trailing whitespace
- Improve line breaks for better readability
- Apply consistent spacing and formatting
- No functional changes, only style improvements
- Add address field to Organization model in Prisma schema
- Update organization creation and editing forms to include address input
- Add address field to organization info form with textarea component
- Update tRPC organization router to handle address field in create/update operations
- Update invoice email template to display organization address
- Regenerate Zod schemas to include new address field
- Ensure address is properly handled in both frontend forms and backend API
- Replace custom file upload with UploadThing service
- Add UploadThing configuration and API routes
- Create new uploadthing-image-upload component with improved UX
- Update environment variables for UploadThing integration
- Remove legacy upload route and image-upload component
- Add comprehensive error handling and loading states
- Support organization logos and other file uploads
- Add documentation for UploadThing integration setup

Breaking changes:
- Removed src/app/api/upload/route.ts (replaced with UploadThing)
- Removed src/components/ui/image-upload.tsx (replaced with uploadthing version)
- Removed src/hooks/use-file-upload.ts (no longer needed)

New files:
- src/app/api/uploadthing/route.ts - UploadThing API endpoint
- src/lib/uploadthing.ts - UploadThing client configuration
- src/server/uploadthing.ts - UploadThing server configuration
- src/components/ui/uploadthing-image-upload.tsx - New upload component
- docs/guides/uploadthing-integration.md - Integration documentation
@dager-mohamed
Copy link
Member

will review, wait!

@dager-mohamed
Copy link
Member

please migrate the db changes, I will test it ASAP

@dager-mohamed
Copy link
Member

also you should delete your prev PR #18

@mzcoder-hub
Copy link
Author

mzcoder-hub commented Sep 19, 2025

please migrate the db changes, I will test it ASAP

sorry i got an email that needed no add to prisma wheres the comment?

also you should delete your prev PR #18

okay ill delete it

@dager-mohamed
Copy link
Member

sorry i got an email that needed no add to prisma wheres the comment?

Never mind, I deleted the comment

@dager-mohamed
Copy link
Member

and please make sure to run bun run format:write after you finish

@dager-mohamed
Copy link
Member

and please remove the organization-logo & user-avatar, since we don't need them

@mzcoder-hub
Copy link
Author

and please remove the organization-logo & user-avatar, since we don't need them

on my way to fix it wait like 5-10 minutes, and is it in the prisma too ? or just the just in the uploadthing ?

@dager-mohamed
Copy link
Member

and is it in the prisma too ? or just the just in the uploadthing ?

No, I meant to delete them from the public folder. Please take your time, don't be in a hurry. Maybe I will review it in another day, so make sure to test your changes very well

@mzcoder-hub
Copy link
Author

and is it in the prisma too ? or just the just in the uploadthing ?

No, I meant to delete them from the public folder. Please take your time, don't be in a hurry. Maybe I will review it in another day, so make sure to test your changes very well

its fine im waiting for your reply btw ahaha. i just make re-code and delete so its fine

@mzcoder-hub
Copy link
Author

and is it in the prisma too ? or just the just in the uploadthing ?

No, I meant to delete them from the public folder. Please take your time, don't be in a hurry. Maybe I will review it in another day, so make sure to test your changes very well

theres error in the nextjs build why is that ?

@mzcoder-hub
Copy link
Author

🐛 Fix: Environment Variable Loading Issues

This PR resolves critical environment variable loading issues that were preventing the application from starting properly.

🔧 Issues Fixed

  1. Better Auth Configuration Issues

    • ERROR [Better Auth]: You are using the default secret
    • WARN [Better Auth]: Social provider google is missing clientId or clientSecret
  2. Resend Email Service Initialization

    • Error: Missing API key. Pass it to the constructor 'new Resend("re_123")'

💡 Root Cause

The main issue was in the WorkflowExecutionEngine class where EmailService was being instantiated immediately as a class property:

// ❌ BEFORE - Immediate instantiation
export class WorkflowExecutionEngine {
  private emailService = new EmailService(); // Fails if env vars not loaded
  // ...
}

This caused the EmailService constructor to run before environment variables were fully loaded, leading to the Resend API key error.

🛠️ Changes Made

1. Enhanced Environment Schema (env.js)

// Added missing Better Auth and Google OAuth variables
BETTER_AUTH_SECRET: z.string().min(1, "BETTER_AUTH_SECRET is required"),
BETTER_AUTH_URL: z.string().url().optional().default("http://localhost:3000"),
GOOGLE_CLIENT_ID: z.string().min(1, "GOOGLE_CLIENT_ID is required"),
GOOGLE_CLIENT_SECRET: z.string().min(1, "GOOGLE_CLIENT_SECRET is required"),

2. Better Auth Configuration (auth.ts)

// Added proper secret and baseURL configuration
export const auth = betterAuth({
  database: prismaAdapter(prisma, { provider: "postgresql" }),
  secret: process.env.BETTER_AUTH_SECRET!,
  baseURL: process.env.BETTER_AUTH_URL,
  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  },
});

3. Lazy EmailService Initialization (workflow-engine.ts)

// ✅ AFTER - Lazy initialization
export class WorkflowExecutionEngine {
  private emailService?: EmailService; // Optional, created on demand
  
  private getEmailService(): EmailService {
    if (!this.emailService) {
      this.emailService = new EmailService(); // Only create when needed
    }
    return this.emailService;
  }
}

✅ Testing

  • Development server starts without environment variable errors
  • Better Auth configuration loads correctly
  • Email service initializes properly when needed
  • No TypeScript compilation errors

🚀 Benefits

  1. Reliable Startup: Environment variables are guaranteed to be loaded before services are instantiated
  2. Better Error Handling: Clear validation of required environment variables
  3. Performance: EmailService only created when workflows actually need to send emails
  4. Maintainability: Proper separation of concerns and lazy loading pattern

📝 Environment File Updates

The .env file structure has been cleaned up and organized:

# Better Auth
BETTER_AUTH_SECRET=...
BETTER_AUTH_URL=http://localhost:3000

# Google OAuth  
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...

# Resend
RESEND_API_KEY=...
RESEND_FROM_EMAIL=...
RESEND_FROM_NAME=...

This PR ensures a smooth development experience and prevents the environment variable loading race conditions that were causing startup failures.

- Add missing Better Auth environment variables to env.js schema
- Configure Better Auth with secret and baseURL from environment
- Implement lazy initialization for EmailService in WorkflowEngine
- Fix Resend API key loading order issue preventing server startup

Fixes startup errors:
- Better Auth default secret warning
- Google OAuth missing credentials warning
- Resend API key initialization failure

The WorkflowEngine now uses lazy initialization to prevent EmailService
from being instantiated before environment variables are loaded.
@mzcoder-hub mzcoder-hub force-pushed the feature/uploadthing-integration branch from 15e3159 to 747d434 Compare September 19, 2025 10:05
@dager-mohamed
Copy link
Member

Hey man, sorry i can't accept your PR now because we are changing some things in the project, i really recommend working on the other issues in github i made, it is going to be helpful!

@mzcoder-hub
Copy link
Author

Hey man, sorry i can't accept your PR now because we are changing some things in the project, i really recommend working on the other issues in github i made, it is going to be helpful!

Did you have discussion forum like discord or something my be i need more frequence discussion. I need to ask about the workflow too

@mzcoder-hub mzcoder-hub deleted the feature/uploadthing-integration branch September 22, 2025 02:06
@mzcoder-hub mzcoder-hub restored the feature/uploadthing-integration branch September 22, 2025 02:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants