# CI/CD Pipelines
Source: https://docs.rmitnct.club/ci-cd-pipelines
Understanding NCTHub CI/CD pipelines and automated workflows.
**Prerequisite**: You should have read the [Monorepo
Architecture](/monorepo-architecture) page to understand the basic structure
of the codebase.
## Overview
NCTHub uses GitHub Actions for continuous integration and continuous deployment (CI/CD) across our monorepo. These automated workflows help us maintain code quality, run tests, and deploy our applications to various environments.
This page documents the key CI/CD pipelines used in the NCTHub platform and how they support our development workflow.
## Workflow Categories
Our GitHub Actions workflows are organized into several categories:
### 1. Application Deployments
Automated deployments to Vercel for our Next.js applications:
* Production deployments (from `production` branch)
* Preview deployments (from push events to non-production branches)
### 2. Database Migrations
Supabase database migration workflows for different environments:
* Production database migrations
* Staging database migrations
* Type generation verification
### 3. Package Publishing
Workflows that publish our shared packages to NPM, GitHub Packages, and JSR:
* Types package
* UI package
* Supabase client package
* ESLint config package
* TypeScript config package
* AI package
### 4. Quality Assurance
Workflows that ensure code quality:
* Unit tests
* Prettier formatting checks
* CodeQL security scanning
* CodeCov code coverage reporting
## Key Workflows
### Application Deployments
We use Vercel for deploying our Next.js applications. The main deployment workflows are:
#### Production Deployments
When code is pushed to the `production` branch, applications are automatically deployed to production:
```yaml theme={null}
name: Vercel Platform Production Deployment
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PLATFORM_PROJECT_ID }}
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.PRODUCTION_SUPABASE_URL }}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.PRODUCTION_SUPABASE_ANON_KEY }}
SUPABASE_SERVICE_KEY: ${{ secrets.PRODUCTION_SUPABASE_SERVICE_KEY }}
on:
push:
branches:
- production
workflow_dispatch:
jobs:
Deploy-Production:
runs-on: ubuntu-latest
steps:
# Setup and optimization steps...
- name: Check for newer commits
id: check_commits
run: |
git fetch origin production
LATEST_COMMIT=$(git rev-parse origin/production 2>/dev/null || echo "")
CURRENT_COMMIT=${GITHUB_SHA}
if [ -n "$LATEST_COMMIT" ] && [ "$LATEST_COMMIT" != "$CURRENT_COMMIT" ]; then
echo "Newer commit found on production branch. Skipping build."
echo "skip_build=true" >> $GITHUB_OUTPUT
else
echo "This is the latest commit. Proceeding with build."
echo "skip_build=false" >> $GITHUB_OUTPUT
fi
# Deployment steps, only run if no newer commits found
- name: Pull Vercel Environment Information
if: steps.check_commits.outputs.skip_build != 'true'
run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }}
- name: Build Project Artifacts
if: steps.check_commits.outputs.skip_build != 'true'
run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }}
- name: Deploy Project Artifacts to Vercel
if: steps.check_commits.outputs.skip_build != 'true'
run: vercel deploy --archive=tgz --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }}
```
We have separate production deployment workflows for each application:
* `vercel-production-hub.yaml` - Main web app
All production workflows follow the same pattern but deploy to different Vercel projects, each with its own environment variables and project ID.
#### Preview Deployments
For non-production branches, we create preview deployments that allow developers to see their changes live before merging:
```yaml theme={null}
name: Vercel Platform Preview Deployment
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PLATFORM_PROJECT_ID }}
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
on:
push:
branches-ignore:
- production
workflow_dispatch:
jobs:
Deploy-Preview:
runs-on: ubuntu-latest
steps:
# Setup and optimization steps...
- name: Check for newer commits
id: check_commits
run: |
CURRENT_BRANCH=${GITHUB_REF#refs/heads/}
git fetch origin $CURRENT_BRANCH
# Skip if newer commits exist on the same branch
# ... (commit checking logic)
# Deployment steps, with conditional execution
- name: Pull Vercel Environment Information
if: steps.check_commits.outputs.skip_build != 'true'
run: vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }}
- name: Build Project Artifacts
if: steps.check_commits.outputs.skip_build != 'true'
run: vercel build --token=${{ secrets.VERCEL_TOKEN }}
- name: Deploy Project Artifacts to Vercel
if: steps.check_commits.outputs.skip_build != 'true'
run: vercel deploy --archive=tgz --prebuilt --token=${{ secrets.VERCEL_TOKEN }}
```
Preview deployments are set up for all our applications, providing a temporary deployment URL for each branch.
### Database Migrations
We use Supabase for our database, and have automated workflows for managing database migrations:
#### Production Database Migrations
```yaml theme={null}
name: Supabase CI
on:
# push:
# branches:
# - production
workflow_dispatch:
jobs:
deploy:
name: Migrate production database
timeout-minutes: 15
runs-on: ubuntu-latest
env:
SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
SUPABASE_DB_PASSWORD: ${{ secrets.PRODUCTION_DB_PASSWORD }}
PRODUCTION_PROJECT_ID: ${{ secrets.PRODUCTION_PROJECT_ID }}
PRODUCTION_DB_URL: ${{ secrets.PRODUCTION_DB_URL }}
steps:
- uses: actions/checkout@v4
- uses: supabase/setup-cli@v1
with:
version: latest
- name: Deploy migrations to production
run: |
cd apps/db
supabase link --project-ref ${{ env.PRODUCTION_PROJECT_ID }}
supabase db push
```
This workflow is manually triggered (via `workflow_dispatch`) to deploy database migrations to production environment. This gives us control over when migrations are applied to production.
#### Supabase Type Verification
We ensure that generated TypeScript types match our database schema:
```yaml theme={null}
name: Supabase CI
on:
push:
workflow_dispatch:
jobs:
deploy:
name: Verify generated types
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: supabase/setup-cli@v1
with:
version: latest
- run: supabase init
- run: supabase db start
- name: Verify generated types match Postgres schema
run: |
supabase gen types typescript --local > schema.gen.ts
if ! git diff --ignore-space-at-eol --exit-code --quiet schema.gen.ts; then
echo "Detected uncommitted changes after build. See status below:"
git diff
exit 1
fi
```
This workflow runs on every push, ensuring that our TypeScript types are always in sync with the database schema.
### Package Publishing
We publish several packages to make our code reusable across projects. Here's an example workflow for the types package:
```yaml theme={null}
name: Release @ncthub/types package
on:
pull_request:
types: [closed]
paths:
- 'packages/types/package.json'
- 'packages/types/jsr.json'
workflow_dispatch:
jobs:
check-version-bump:
if: github.event.pull_request.merged == true && contains(github.event.pull_request.title, 'chore(@ncthub/types)')
runs-on: ubuntu-latest
outputs:
should_release: ${{ steps.check.outputs.should_release }}
steps:
- id: check
run: echo "should_release=true" >> $GITHUB_OUTPUT
build:
needs: check-version-bump
if: needs.check-version-bump.outputs.should_release == 'true'
runs-on: ubuntu-latest
# Build steps
publish-jsr:
needs: [build]
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
# Setup steps
- name: Publish package to JSR
working-directory: packages/types
run: bunx jsr publish
publish-npm:
needs: [build]
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
steps:
# Setup steps
- name: Publish package
working-directory: packages/types
run: bun publish
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
```
Our package publishing workflows follow a pattern:
1. Check for a version bump in the package.json and ensure the PR title follows our convention
2. Build and test the package
3. Publish to multiple registries (JSR, GitHub Packages, NPM)
We have similar workflows for other packages:
* `release-ui-package.yaml`
* `release-ai-package.yaml`
* `release-supabase-package.yaml`
* `release-eslint-config-package.yaml`
* `release-typescript-config-package.yaml`
### Quality Assurance
We use several workflows to ensure code quality:
#### Unit Tests
```yaml theme={null}
name: Test
on:
push:
branches: ['main']
pull_request:
jobs:
build:
name: Unit Tests
timeout-minutes: 15
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [22]
env:
# Use Vercel Remote Caching
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
# Configure environment variables
NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL }}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_ANON_KEY }}
SUPABASE_SERVICE_KEY: ${{ secrets.SUPABASE_SERVICE_KEY }}
steps:
# Setup steps
- name: Test
run: bun run test
```
This workflow runs on every push to main and on all pull requests, ensuring our tests pass.
#### Prettier Formatting
We enforce consistent code formatting with Prettier using an automated workflow that can create PRs for formatting fixes:
```yaml theme={null}
name: Prettier Format Check
on:
push:
workflow_dispatch:
jobs:
format:
name: Prettier Check
timeout-minutes: 10
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
strategy:
matrix:
node-version: [23]
steps:
# Setup steps
- name: Check Prettier formatting
id: check-format
run: bun format:check || echo "format_failed=true" >> $GITHUB_OUTPUT
- name: Apply Prettier fixes
if: steps.check-format.outputs.format_failed == 'true'
run: bun format
- name: Check for changes
if: steps.check-format.outputs.format_failed == 'true'
id: git-check
run: |
if [[ -n $(git status --porcelain) ]]; then
echo "changes=true" >> $GITHUB_OUTPUT
else
echo "changes=false" >> $GITHUB_OUTPUT
fi
- name: Create Pull Request
if: steps.git-check.outputs.changes == 'true'
id: create-pr
uses: peter-evans/create-pull-request@v7
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: 'style: apply prettier formatting'
title: 'style: apply prettier formatting for ${{ github.ref_name }}'
body: |
This PR fixes code formatting issues using Prettier.
Auto-generated by the Prettier Format Check workflow.
branch: fix/prettier-formatting-${{ github.ref_name }}
base: ${{ github.ref_name }}
delete-branch: true
```
This workflow not only checks code formatting but also:
1. Automatically applies Prettier fixes if formatting issues are found
2. Creates a pull request with the fixes
3. Adds informative comments to existing PRs if formatting issues are detected
## Workflow Organization
Our GitHub Actions workflows are all defined in the `.github/workflows` directory of the repository. They follow a consistent naming convention:
### Application Deployment Workflows
* `vercel-production-*.yaml`: Production deployment workflows for each application
* Example: `vercel-production-hub.yaml`
* `vercel-preview-*.yaml`: Preview deployment workflows for each application
* Example: `vercel-preview-hub.yaml`
### Database Workflows
* `supabase-production.yaml`: Production database migrations
* `supabase-staging.yaml`: Staging database migrations
* `supabase-types.yaml`: TypeScript type verification
### Package Publishing Workflows
* `release-*-package.yaml`: Package publishing workflows
* Example: `release-ui-package.yaml`, `release-types-package.yaml`
### Quality Assurance Workflows
* `turbo-unit-tests.yaml`: Unit test workflow
* `prettier-check.yaml`: Code formatting workflow
* `codecov.yaml`: Code coverage reporting
* `codeql.yml`: Security scanning
### Other Utilities
* `check-and-bump-versions.yaml`: Automated dependency version management
* `external-internal-packages.yaml`: Managing external vs internal dependencies
## Common Workflow Patterns
Our workflows follow several common patterns:
### 1. Conditional Execution
Many workflows check if they should run based on certain conditions:
```yaml theme={null}
- name: Check for newer commits
id: check_commits
run: |
# Logic to determine if build should be skipped
echo "skip_build=false" >> $GITHUB_OUTPUT
- name: Next step
if: steps.check_commits.outputs.skip_build != 'true'
run: echo "Only runs if no newer commits were found"
```
### 2. Dependency Caching
Most workflows use caching to speed up builds:
```yaml theme={null}
- name: Cache turbo build setup
uses: actions/cache@v4
with:
path: .turbo
key: ${{ runner.os }}-turbo-${{ github.sha }}
restore-keys: |
${{ runner.os }}-turbo-
- name: Setup bun
uses: oven-sh/setup-bun@v2
with:
bun-version: '1.3.14'
- name: Use Node.js 25
uses: actions/setup-node@v4
with:
node-version: 25
```
### 3. PR-based Publishing
Package releases are triggered by merged PRs with specific title patterns:
```yaml theme={null}
on:
pull_request:
types: [closed]
paths:
- 'packages/types/package.json'
# ...
jobs:
check-version-bump:
if: github.event.pull_request.merged == true && contains(github.event.pull_request.title, 'chore(@ncthub/types)')
# ...
```
## Environment Variables and Secrets
Our workflows use several environment variables and secrets stored in GitHub:
* `VERCEL_TOKEN`: For deploying to Vercel
* `VERCEL_ORG_ID`: Vercel organization ID
* `VERCEL_*_PROJECT_ID`: Project-specific Vercel IDs
* `SUPABASE_ACCESS_TOKEN`: For authenticating with Supabase
* `*_SUPABASE_URL`, `*_SUPABASE_ANON_KEY`, `*_SUPABASE_SERVICE_KEY`: Environment-specific Supabase credentials
* `NPM_TOKEN`: For publishing to NPM
* `TIPTAP_PRO_TOKEN`: For accessing Tiptap Pro packages
* `TURBO_TOKEN` and `TURBO_TEAM`: For Turborepo remote caching
Never hard-code sensitive information in workflow files. Always use GitHub
Secrets for API tokens, passwords, and other sensitive data.
## Remote Caching with Turborepo
We leverage Turborepo's remote caching feature in our CI pipelines to speed up builds:
```yaml theme={null}
env:
# Use Vercel Remote Caching
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
```
This allows our CI jobs to reuse cached build artifacts from previous runs, significantly reducing build times. For large monorepos like ours, this can reduce CI times from 20+ minutes to just a few minutes when the cache is warm.
## Best Practices
When working with our CI/CD pipelines, follow these best practices:
### 1. Test Workflows Locally
Before creating a new workflow, test it locally using [act](https://github.com/nektos/act) or similar tools.
```bash theme={null}
# Install act
brew install act
# Run a specific workflow locally
act -W .github/workflows/your-workflow.yaml
```
### 2. Keep Workflows Focused
Each workflow should have a single responsibility. Split complex workflows into smaller, more focused ones.
### 3. Reuse Common Steps
Use composite actions or job templates to reuse common steps across workflows.
### 4. Monitor Workflow Performance
Regularly check workflow runs for performance issues and optimize as needed:
1. Use GitHub's workflow visualization to identify bottlenecks
2. Implement caching for dependencies and build artifacts
3. Run jobs in parallel when possible
4. Skip unnecessary steps with conditional execution
### 5. Document Workflow Changes
When making significant changes to workflows, document them in pull request descriptions and update this documentation.
## Troubleshooting
### Common Issues
#### 1. Workflow Timeouts
If a workflow times out, it might be due to:
* Inefficient build process
* Missing cache configuration
* Network issues with external services
Try adding or improving caching strategies and optimizing build steps.
#### 2. Failed Deployments
When deployments fail, check:
* Build logs for errors
* Environment variable configuration
* Access tokens and permissions
#### 3. Authentication Issues
For authentication problems with NPM, GitHub Packages, or Vercel:
* Verify token permissions
* Ensure tokens are not expired
* Check that the token is correctly configured in GitHub Secrets
## Creating New Workflows
When creating a new workflow, use this checklist:
1. **Naming Convention**: Follow the established naming patterns
2. **Trigger Conditions**: Define when the workflow should run
3. **Environment Variables**: Include all necessary secrets and variables
4. **Optimizations**: Add caching and conditional execution
5. **Error Handling**: Include appropriate error handling and notifications
6. **Documentation**: Add comments within the workflow file and update documentation
## Further Resources
* [GitHub Actions Documentation](https://docs.github.com/en/actions)
* [Vercel CLI Documentation](https://vercel.com/docs/cli)
* [Supabase CLI Documentation](https://supabase.com/docs/guides/cli)
* [Turborepo Documentation](https://turbo.build/repo/docs/ci)
* [bun Workspace Documentation](https://bun.sh/docs/install/workspaces)
# Development
Source: https://docs.rmitnct.club/development
Learn how to preview changes locally.
**Prerequisite**: You should have installed [Node.js](https://nodejs.org)
(version 20 or higher).
## Installation
Step 1. Install [bun](https://bun.sh/docs/installation) on your machine (if you don't already have it yet), by running the following command:
**macOS/Linux:**
```bash theme={null}
curl -fsSL https://bun.sh/install | bash
```
**Windows:**
```bash theme={null}
powershell -c "irm bun.sh/install.ps1 | iex"
```
## Why Bun?
We chose bun as our runtime and package manager based on its [design goals](https://bun.sh/docs#design-goals), which align perfectly with our platform's needs:
* **4x Faster Startup**: Bun processes start significantly faster than Node.js, improving development experience and CI/CD performance
* **Built-in TypeScript & JSX Support**: No need for additional transpilation setup - bun natively executes `.ts`, `.tsx`, and `.jsx` files
* **All-in-One Toolkit**: Combines runtime, package manager, bundler, test runner, and script runner in a single executable
* **Web Standards Compatibility**: Implements modern Web APIs like `fetch`, `WebSocket`, and `ReadableStream` out of the box
* **Node.js Compatibility**: Drop-in replacement for Node.js with full compatibility for existing projects
* **Better Performance**: Powered by JavaScriptCore engine with reduced memory usage and faster execution
These benefits make bun an ideal choice for our monorepo architecture and development workflow.
Step 2. **Configure Tiptap Pro Registry:**
This step is no longer needed.
Step 3. After configuring Tiptap Pro registry, you can install all dependencies by running the following command:
```bash standard theme={null}
bun install
```
```bash short-hand theme={null}
bun i
```
To complete the initial setup, please restart your IDE so that it can recognize the newly installed dependencies. Additionally, some recommended VS Code Extensions may only work after restarting your IDE.
If you're using VS Code, you can install following the recommended extensions
that will help you with the development process:
[ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint),
[Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode),
[Vitest](https://marketplace.visualstudio.com/items?itemName=vitest.explorer),
[Tailwind CSS
IntelliSense](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss),
[Version
Lens](https://marketplace.visualstudio.com/items?itemName=pflannery.vscode-versionlens),
[Error
Lens](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens),
[Pretty TypeScript
Errors](https://marketplace.visualstudio.com/items?itemName=YoavBls.pretty-ts-errors),
[Material Icon
Theme](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme).
## Development
### Start Next.js apps
To develop all apps and packages (without requiring a local setup), run the following command:
```bash bun theme={null}
bun dev
```
This command will start all Next.js apps in development mode. You can access
the apps by visiting the following URL: [http://localhost:7803](http://localhost:7803)
### Start Local Supabase Instance
To start a local supabase instance (database), run the following command:
```bash bun theme={null}
bun sb:start
```
This command will start a local supabase instance on your machine. You can
access the supabase instance by visiting the following URL:
[http://localhost:8003](http://localhost:8003)
You need to have Docker installed and running on your machine to start a local
supabase instance.
### Stop Local Supabase Instance
To stop the local supabase instance, run the following command:
```bash standard theme={null}
bun sb:stop
```
```bash short-hand theme={null}
bun stop
```
### Better Development Experience
In case you want to run all local development servers, run the following command:
```bash bun theme={null}
bun devx
```
Running `devx` will:
1. Stop the currently running supabase instance and save current data as backup (if there is any)
2. Install all dependencies
3. Start a new supabase instance (using backed up data)
4. Start all Next.js apps in development mode
If you want to have the same procedure without the backup, you can run `bun devrs` instead. This will:
1. Stop the currently running supabase instance (if there is any)
2. Install all dependencies
3. Start a new supabase instance (with clean data from seed.sql)
4. Start all Next.js apps in development mode
In case you don't want to run a local supabase instance, you can run `bun dev`
instead.
### Local development
#### Seed accounts
There are 5 seed accounts that are already set up for local development:
1. [local@tuturuuu.com](mailto:local@tuturuuu.com)
2. [user1@tuturuuu.com](mailto:user1@tuturuuu.com)
3. [user2@tuturuuu.com](mailto:user2@tuturuuu.com)
4. [user3@tuturuuu.com](mailto:user3@tuturuuu.com)
5. [user4@tuturuuu.com](mailto:user4@tuturuuu.com)
You can use any of these accounts to log in to the app and quickly test the functionality of the app, since they are already set up with the necessary data.
#### Authentication
A local mail server (**InBucket**) is automatically set up by Supabase to handle authentication emails.
You can access the mail server by visiting the following URL:
[http://localhost:8004](http://localhost:8004)
## Build
To build all apps and packages, run the following command:
```bash bun theme={null}
bun run build
```
## Test
To run all tests, run the following command:
```bash bun theme={null}
bun run test
```
Tests are still a work in progress. We're currently working on adding tests to all packages to ensure the best quality possible.
## Git Conventions
NCTHub uses standardized conventions for Git commits and branch naming. For more information, see the [Git Conventions](/git-conventions) guide to learn how to format your commits and branch names to align with our workflow.
# Documenting
Source: https://docs.rmitnct.club/documenting
Learn how to contribute to our documentation.
**Prerequisite**: You should have installed [Node.js](https://nodejs.org)
(version 20 or higher) and cloned the [NCTHub
Monorepo](https://github.com/rmit-nct/hub) to your local machine.
Step 1. Install Mintlify on your local machine:
```bash bun theme={null}
bun i -g mintlify
```
```bash npm theme={null}
npm i -g mintlify
```
```bash yarn theme={null}
yarn global add mintlify
```
Step 2. Go to the docs are located (navigate to `apps/docs`) and run the following command:
```bash theme={null}
mintlify dev
```
The documentation website is now available at `http://localhost:3000`.
Use `cd apps/docs` to navigate to the docs folder.
### Custom Ports
Mintlify uses port 3000 by default. You can use the `--port` flag to customize the port Mintlify runs on. For example, use this command to run in port 3333:
```bash theme={null}
mintlify dev --port 3333
```
You will see an error like this if you try to run Mintlify in a port that's already taken:
```md theme={null}
Error: listen EADDRINUSE: address already in use :::3000
```
## Mintlify Versions
Each CLI is linked to a specific version of Mintlify. Please update the CLI if your local website looks different than production.
```bash bun theme={null}
bun i -g mintlify@latest
```
```bash npm theme={null}
npm i -g mintlify@latest
```
```bash yarn theme={null}
yarn global add mintlify@latest
```
# Git Conventions
Source: https://docs.rmitnct.club/git-conventions
Learn how NCTHub uses Conventional Commits and Branch naming to improve development workflow.
**Prerequisite**: You should be familiar with basic Git operations and
understand the [Monorepo Architecture](/monorepo-architecture) of our
codebase.
## Overview
NCTHub follows standardized conventions for Git commits and branch naming to improve collaboration, automate releases, and maintain a clean, navigable repository history. We use two main specifications:
1. [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for structured commit messages
2. [Conventional Branch](https://conventional-branch.github.io/) for consistent branch naming
These conventions help automate our CI/CD workflows, generate changelogs, and make our development process more efficient.
## Conventional Commits
### What are Conventional Commits?
Conventional Commits is a specification for adding human and machine-readable meaning to commit messages. It provides a set of rules for creating an explicit commit history, making it easier to write automated tools on top of.
The basic structure of a conventional commit is:
```
[optional scope]:
[optional body]
[optional footer(s)]
```
### Types
NCTHub uses the following commit types:
| Type | Description | Example |
| ---------- | ----------------------------------------------- | ------------------------------------------------ |
| `feat` | New feature or enhancement | `feat: add dark mode support` |
| `fix` | Bug fix | `fix: prevent crash when user data is undefined` |
| `docs` | Documentation changes | `docs: update installation instructions` |
| `style` | Code style changes (formatting, no code change) | `style: format code with prettier` |
| `refactor` | Code refactoring | `refactor: simplify authentication logic` |
| `perf` | Performance improvements | `perf: optimize database queries` |
| `test` | Add or fix tests | `test: add unit tests for auth middleware` |
| `build` | Changes affecting build system or dependencies | `build: update dependency to fix security issue` |
| `ci` | Changes to CI configuration files and scripts | `ci: add workflow for staging deployments` |
| `chore` | Routine tasks, maintenance | `chore: update package.json metadata` |
### Scopes
Scopes provide additional context about which part of the codebase is affected. In our monorepo structure, we often use package or app names as scopes:
```
feat(web): add new dashboard layout
fix(ui): correct button alignment in mobile view
chore(types): update supabase database types
```
### Breaking Changes
Breaking changes must be indicated by adding a `!` after the type/scope or by using a `BREAKING CHANGE:` footer:
```
feat(api)!: require authentication for all endpoints
BREAKING CHANGE: All API endpoints now require authentication tokens.
```
### Examples
Here are some examples of conventional commits used in our codebase:
```
feat(web): add new calendar integration
fix(supabase): correct permission issue in auth policy
docs(readme): update development setup instructions
style: apply consistent formatting with prettier
refactor(utils): simplify date formatting functions
perf(queries): optimize workspace user loading
test(auth): add tests for token verification
build(deps): update Next.js to v14
ci(vercel): add automatic preview deployments
chore(release): publish packages
```
## Conventional Branches
### What are Conventional Branches?
Conventional Branch refers to a structured naming convention for Git branches that makes it easier to identify branches by type and purpose.
The basic structure is:
```
/
```
### Branch Types
NCTHub uses the following branch types:
| Type | Description | Example |
| --------- | ----------------------- | ------------------------------- |
| `main` | Main development branch | `main` |
| `feature` | For new features | `feature/user-dashboard` |
| `bugfix` | For bug fixes | `bugfix/login-error` |
| `hotfix` | For urgent fixes | `hotfix/security-vulnerability` |
| `release` | For preparing releases | `release/v1.2.0` |
| `chore` | For maintenance tasks | `chore/update-dependencies` |
### Naming Rules
1. Use lowercase alphanumeric characters and hyphens
2. Keep names concise but descriptive
3. Include ticket/issue numbers when applicable
4. Avoid special characters (except hyphens)
### Examples
```
feature/workspace-sharing
bugfix/file-upload-error
hotfix/auth-vulnerability
release/v2.5.0
chore/update-react-18
feature/issue-123-user-profile
```
## How These Conventions Improve Our Workflow
### 1. Automated Changelog Generation
Our conventional commits are used to automatically generate changelogs for releases. Different commit types are categorized accordingly:
```markdown theme={null}
# Changelog
## Features
- add dark mode support (#123)
- add calendar integration (#124)
## Bug Fixes
- prevent crash when user data is undefined (#125)
## Documentation
- update installation instructions (#126)
```
### 2. Semantic Versioning
Conventional commits help determine the next semantic version for packages:
* `fix:` commits trigger a PATCH increment (1.0.0 → 1.0.1)
* `feat:` commits trigger a MINOR increment (1.0.0 → 1.1.0)
* Commits with `BREAKING CHANGE` trigger a MAJOR increment (1.0.0 → 2.0.0)
### 3. Automated Package Publishing
In our CI workflows, package publishing is automatically triggered when a PR with specific commit types is merged. For example, our `release-types-package.yaml` workflow triggers when:
```yaml theme={null}
on:
pull_request:
types: [closed]
paths:
- 'packages/types/package.json'
# ...
jobs:
check-version-bump:
if: github.event.pull_request.merged == true && contains(github.event.pull_request.title, 'chore(@ncthub/types)')
# ...
```
### 4. Better Code Reviews
With conventional commits and branches, it's easier to understand the purpose of a pull request at a glance:
* A PR from `feature/user-dashboard` with commits like `feat: add user stats widget` clearly indicates a new feature
* A PR from `bugfix/auth-issue` with commits like `fix: prevent token expiration error` indicates a bug fix
### 5. Simplifying Navigation
Conventional branch names make it easier to navigate the repository history and find specific changes. For example:
```bash theme={null}
# Find all feature branches
git branch --list "feature/*"
# Find branches related to authentication
git branch --list "*auth*"
```
## Tools and Enforcement
We use a dedicated CI/CD check to enforce our Git conventions:
### Branch Naming Check
We use a GitHub Action workflow to verify that branch names follow our convention:
```yaml theme={null}
name: Branch Name Check
on:
push:
branches-ignore:
- main
- production
jobs:
check-branch-name:
name: Check branch name
runs-on: ubuntu-latest
steps:
- name: Check branch name
run: |
BRANCH_NAME=${GITHUB_REF#refs/heads/}
if ! [[ $BRANCH_NAME =~ ^(feature|bugfix|hotfix|release|chore)/.+ ]]; then
echo "❌ Branch name '$BRANCH_NAME' doesn't follow the conventional branch format."
echo "Branch name should be in format: type/description"
echo "Allowed types: feature, bugfix, hotfix, release, chore"
exit 1
else
echo "✅ Branch name follows convention: $BRANCH_NAME"
fi
```
## Best Practices
### Writing Good Commit Messages
1. Use the imperative mood ("add" not "added" or "adds")
2. Capitalize the first letter of the description
3. Do not end the description with a period
4. Keep the description under 72 characters
5. Use the body to explain the what and why, not the how
Example of a well-formatted commit:
```
feat(auth): Add multi-factor authentication support
Implement TOTP-based multi-factor authentication to improve security.
The implementation follows the RFC 6238 standard.
Closes #123
```
### Branch Management
1. Create branches from the latest `main` branch
2. Keep branches focused on a single task or issue
3. Regularly rebase long-lived branches on `main` to avoid merge conflicts
4. Delete branches after they've been merged
### Pull Request Workflow
1. Create a branch with the appropriate type based on the work
2. Make commits using conventional commit messages
3. Push the branch and create a pull request
4. Use conventional commit style for the PR title
5. After approval and merge, delete the branch
## Conclusion
Following these Git conventions helps us maintain a clean, understandable repository history, automate release processes, and improve collaboration across the team. By standardizing both commit messages and branch names, we create a more efficient development workflow.
For more information, refer to the official documentation for [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) and [Conventional Branch](https://conventional-branch.github.io/).
# Introduction
Source: https://docs.rmitnct.club/introduction
Welcome to the home of NCTHub Documentation.
## Setting up
The first step to getting started with NCTHub is to set up your development environment.
Learn how to set up your development environment.
# Examples
Source: https://docs.rmitnct.club/learn/examples/index
Practical examples and code samples for the NCT Hub platform
This section contains practical examples and code samples demonstrating how to use various components and features of the NCT Hub platform for club management, AI integration, and student development.
## Component Examples
### WorkspaceWrapper
Examples showing how to use the WorkspaceWrapper component in different scenarios.
The main [WorkspaceWrapper documentation](/platform/components/workspace-wrapper) includes comprehensive code examples demonstrating various usage patterns.
## Usage Patterns
### Server Components
```tsx theme={null}
// Basic server component with WorkspaceWrapper
export default async function MyPage({
searchParams,
}: {
searchParams: Promise<{ wsId: string }>;
}) {
return (
{({ workspace, wsId }) =>
;
}
```
### API Routes
```tsx theme={null}
// API route with workspace validation
export async function GET(
request: Request,
{ params }: { params: Promise<{ wsId: string }> }
) {
const { wsId } = await params;
const workspace = await getWorkspace(wsId);
if (!workspace) {
return Response.json({ error: 'Workspace not found' }, { status: 404 });
}
return Response.json({ workspace });
}
```
## Best Practices
### Error Handling
```tsx theme={null}
// Proper error handling in components
export default async function MyPage({ searchParams }) {
return (
}>
{({ workspace, wsId }) => {
try {
return ;
} catch (error) {
return ;
}
}}
);
}
```
### Loading States
```tsx theme={null}
// Proper loading state handling
export default async function MyPage({ searchParams }) {
return (
}
>
{({ workspace, wsId }) => (
}>
)}
);
}
```
### Type Safety
```tsx theme={null}
// Proper TypeScript usage
interface PageProps {
searchParams: Promise<{ wsId: string }>;
}
interface WorkspaceData {
workspace: Workspace & { role: WorkspaceUserRole; joined: boolean };
wsId: string;
}
export default async function MyPage({ searchParams }: PageProps) {
return (
{({ workspace, wsId }: WorkspaceData) => (
)}
);
}
```
## Common Patterns
### Dashboard Pages
Most dashboard pages follow this pattern:
1. Use WorkspaceWrapper for workspace resolution
2. Fetch additional data based on workspace
3. Render components with proper loading states
4. Handle permissions and access control
### Settings Pages
Settings pages typically:
1. Validate user permissions
2. Show different UI based on user role
3. Handle form submissions with proper validation
4. Provide clear feedback to users
### API Endpoints
API endpoints should:
1. Validate workspace access
2. Handle errors gracefully
3. Return appropriate HTTP status codes
4. Include proper error messages
## Contributing Examples
When adding new examples:
1. Use realistic, practical scenarios
2. Include proper TypeScript types
3. Show error handling
4. Include both server and client examples
5. Update this index page
# Learn & Experiment
Source: https://docs.rmitnct.club/learn/index
Examples, experiments, and learning resources for NCT Hub development and AI integration.
Level up your NCT Hub expertise through curated examples, experiments, and learning resources designed for club management, AI integration, and student development.
## Learning Paths
* **Examples** – Browse practical snippets and starter code in the [Examples Library](/learn/examples/index).
## NCT Hub Development Flow
```mermaid theme={null}
sequenceDiagram
participant Student
participant NCT Hub
participant AI Tools
participant Club Community
Student->>NCT Hub: Join club activities
NCT Hub->>AI Tools: Leverage AI for learning
AI Tools->>Student: Enhanced educational experience
Student->>Club Community: Share knowledge & projects
Club Community-->>NCT Hub: Feed insights back to platform
```
## Key Learning Areas
### Club Management
* Member onboarding and role management
* Event planning and coordination
* Project tracking and collaboration
* Financial management and analytics
### AI Integration
* Chat-based assistance for students
* Automated content generation
* Smart scheduling and notifications
* Educational content personalization
### Student Development
* Skill-building through hands-on projects
* Peer collaboration and mentorship
* Real-world project experience
* Industry-relevant technology exposure
Stay curious—share findings, improve docs, and help us expand what the NCT Hub ecosystem can do. For detailed platform architecture, visit the [Hub section](/platform/index). Need development help? Check out [Development](/development).
# Local Supabase Development
Source: https://docs.rmitnct.club/local-supabase-development
Learn how to work with Supabase locally in the NCT Hub development workflow.
**Prerequisite**: You should have installed
[Docker](https://www.docker.com/products/docker-desktop/) and followed the
[Development](/development) setup guide.
## Overview
NCT Hub utilizes Supabase for database management and authentication. This guide explains how to work efficiently with Supabase in the local development workflow.
## Basic Commands
### Starting Supabase
To start a local Supabase instance tailored for NCT Hub:
```bash theme={null}
bun sb:start
```
This command launches a local Supabase instance on your machine, accessible at [http://localhost:8003](http://localhost:8003).
### Stopping Supabase
To stop the local Supabase instance:
```bash theme={null}
bun sb:stop
```
### Checking Status
To view the current URLs and status of your local Supabase instance:
```bash theme={null}
bun sb:status
```
## Development Workflow
### Recommended Startup
When developing for NCT Hub, you have several options to start your environment:
1. **Standard Approach**: Start Next.js apps and Supabase separately.
```bash theme={null}
bun dev # Starts all Next.js apps
bun sb:start # Starts Supabase
```
2. **Enhanced Development Experience**: Use the `devx` command for a streamlined setup.
```bash theme={null}
bun devx
```
This command:
* Stops any running Supabase instance and saves current data as backup
* Installs all dependencies
* Starts a new Supabase instance (using backed up data)
* Starts all Next.js apps in development mode
3. **Fresh Database Setup**: When switching branches with potential schema changes.
```bash theme={null}
bun sb:devrs
```
This command:
* Stops any running Supabase instance (without backup)
* Installs all dependencies
* Starts a new Supabase instance
* Resets the database to use the latest schema
* Starts all Next.js apps in development mode
Use `bun sb:devrs` when switching between branches that might have different
database migrations to ensure your local database schema matches the branch
you're working on.
### Syncing With Schema Changes
If you're keeping your Next.js server running but need to reset your database to match the current branch's schema:
```bash theme={null}
bun sb:reset
```
This command will reset your local database to use the latest schema definitions and automatically regenerate TypeScript types.
## Database Schema Management
### Making Schema Changes
There are two approaches to modifying the database schema:
#### 1. Using the Supabase UI
1. Navigate to your local Supabase Studio at [http://localhost:8003](http://localhost:8003)
2. Make your changes through the UI
3. Generate a migration file:
```bash theme={null}
bun sb:diff
```
This creates a migration file based on the differences between your current schema and the previous state.
Be cautious when using `sb:diff` for schema changes. If you rename columns or
tables, the migration will drop the old ones and create new ones, which can
result in data loss in production environments.
#### 2. Creating Manual Migrations
For more control, you can create empty migration files and populate them manually:
```bash theme={null}
bun sb:new
```
This creates a new empty migration file in `apps/db/supabase/migrations` that you can edit to include your desired schema changes.
### Applying Migrations
After creating a migration, apply it to your local database:
```bash theme={null}
bun sb:up
```
This same process is used to keep our production database up-to-date with the
schema defined in the `production` branch.
### Generating TypeScript Types
After schema changes, regenerate the TypeScript types to keep your code in sync with the database schema:
```bash theme={null}
bun sb:typegen
```
Alternatively, you can use the shorthand:
```bash theme={null}
bun typegen
```
This step is automatically performed when running `bun sb:reset`, making it
useful when catching up with a new branch's schema.
### Using Generated TypeScript Types
The Supabase-generated TypeScript types are available at `packages/types/src/supabase.ts`. These types are accessible to all apps that have the `@ncthub/types` package installed.
You can use these types to ensure type safety when working with Supabase data:
```typescript theme={null}
import type { Database } from '@ncthub/types/supabase';
// Type-safe access to tables
const { data, error } = await supabase
.from<
Database['public']['Tables']['workspace_members']['Row']
>('workspace_members')
.select('*')
.eq('ws_id', workspaceId);
// Type-safe access to specific columns
const { data: workspace } = await supabase
.from('workspaces')
.select('id, name, handle')
.eq('id', workspaceId)
.single();
// TypeScript knows the structure of 'workspace' with proper types
const workspaceName: string = workspace?.name;
```
### Short-hand Type Access
For more convenient access to common table types, NCT Hub also provides short-hand type definitions in `packages/types/src/db.ts`. These are easier to use and remember than the full database type paths:
```typescript theme={null}
import type { WorkspaceCourse, WorkspaceRole } from '@ncthub/types/db';
// Use short-hand types directly
const { data: roles } = await supabase
.from('workspace_roles')
.select('*')
.eq('ws_id', workspaceId);
// Type is now WorkspaceRole[]
roles?.forEach((role: WorkspaceRole) => {
console.log(role.name, role.permissions);
});
// Short-hand types can also include extended properties
const course: WorkspaceCourse = {
id: 'course-id',
ws_id: 'workspace-id',
name: 'Course Name',
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
href: '/courses/course-id', // Extended property not in the database
};
```
You can add your own short-hand types to `db.ts` for tables you frequently work with. This is especially useful for tables that have complex structures or need additional client-side properties.
This ensures that your code correctly interacts with the database schema, reducing runtime errors and improving development experience.
## Migration Files
All migration files are stored in `apps/db/supabase/migrations`. These files:
* Contain SQL commands that create and modify the database schema
* Are executed in order based on the timestamp prefix in their filenames
* Include descriptive names after the timestamp to help developers understand their purpose
When contributing new migrations in a Pull Request, always add them after the
latest migration file from the `main` branch. This maintains the correct
execution order and prevents issues when syncing the production database.
## Local Authentication
A local mail server (**InBucket**) is automatically set up by Supabase to handle authentication emails. You can access it at [http://localhost:8004](http://localhost:8004).
With InBucket, you can:
* Receive all authentication emails sent by your local Supabase instance
* Test any email combination without needing actual mail delivery
* View password reset links, confirmation emails, and other authentication flows
* Troubleshoot email templates and content
This makes it easy to test different authentication scenarios without configuring a real email service or waiting for actual email delivery.
Five seed accounts are pre-configured for local development:
1. [local@tuturuuu.com](mailto:local@tuturuuu.com)
2. [user1@tuturuuu.com](mailto:user1@tuturuuu.com)
3. [user2@tuturuuu.com](mailto:user2@tuturuuu.com)
4. [user3@tuturuuu.com](mailto:user3@tuturuuu.com)
5. [user4@tuturuuu.com](mailto:user4@tuturuuu.com)
These accounts are already set up with the necessary data, allowing you to quickly test the app's functionality. However, you can register any new email address and the authentication emails will be captured by InBucket for you to inspect.
## Further Information
For more details about Supabase CLI usage, refer to the [Supabase CLI documentation](https://supabase.com/docs/guides/local-development/cli/getting-started).
## Row Level Security (RLS)
Row Level Security (RLS) is a powerful Postgres feature that allows you to control access to rows in a database table based on the user making the request. In NCT Hub, we use RLS extensively to ensure data security.
### Enabling RLS
RLS should be enabled on all tables in exposed schemas (like `public`). When creating tables through the Supabase UI, RLS is enabled by default. For tables created using SQL, you need to explicitly enable RLS:
```sql theme={null}
alter table . enable row level security;
```
### Creating RLS Policies
Policies define the conditions under which users can access or modify data. Here are some common patterns used in NCT Hub:
#### Organization-based Access
In NCT Hub, most resources belong to an organization (workspace). Here's how to create policies for organization-based access:
```sql theme={null}
-- Allow users to select data from their organizations
create policy "Users can view data from their organizations"
on public.table_name
for select
to authenticated
using (
auth.uid() in (
select user_id from public.workspace_members
where workspace_id = table_name.workspace_id
)
);
-- Allow organization admins to insert data
create policy "Organization admins can insert data"
on public.table_name
for insert
to authenticated
with check (
auth.uid() in (
select user_id from public.workspace_members
where workspace_id = table_name.workspace_id
and role = 'admin'
)
);
-- Allow organization admins to update data
create policy "Organization admins can update data"
on public.table_name
for update
to authenticated
using (
auth.uid() in (
select user_id from public.workspace_members
where workspace_id = table_name.workspace_id
and role = 'admin'
)
)
with check (
auth.uid() in (
select user_id from public.workspace_members
where workspace_id = table_name.workspace_id
and role = 'admin'
)
);
-- Allow organization admins to delete data
create policy "Organization admins can delete data"
on public.table_name
for delete
to authenticated
using (
auth.uid() in (
select user_id from public.workspace_members
where workspace_id = table_name.workspace_id
and role = 'admin'
)
);
```
#### Role-based Access
For more granular control based on user roles:
```sql theme={null}
-- Allow members with specific permission to access a resource
create policy "Members with view_projects permission can view projects"
on public.projects
for select
to authenticated
using (
exists (
select 1 from public.workspace_member_permissions
where user_id = auth.uid()
and workspace_id = projects.workspace_id
and permission = 'view_projects'
)
);
```
### Performance Optimization for RLS
For better performance in your RLS policies:
1. **Wrap function calls in subqueries**:
```sql theme={null}
-- Instead of this
using (auth.uid() = user_id);
-- Use this
using ((select auth.uid()) = user_id);
```
2. **Use security definer functions** for complex access logic:
```sql theme={null}
create or replace function private.can_access_workspace(workspace_uuid uuid)
returns boolean
language plpgsql
security definer
as $$
begin
return exists (
select 1 from public.workspace_members
where user_id = auth.uid()
and workspace_id = workspace_uuid
);
end;
$$;
-- Use the function in your policy
create policy "Users can access workspace data"
on public.table_name
for select
to authenticated
using (private.can_access_workspace(workspace_id));
```
3. **Add explicit filters** in your queries even when you have RLS:
```typescript theme={null}
// Even though RLS will filter by workspace_id, adding the filter explicitly improves performance
const { data } = await supabase
.from('projects')
.select()
.eq('workspace_id', workspaceId);
```
### Testing RLS Policies
To test your RLS policies during local development:
1. Create a SQL file in `apps/db/supabase/tests` with your test cases
2. Use the `bun sb:test` command to run the tests
Example test file:
```sql theme={null}
-- Test normal user can view their own workspace
BEGIN;
SET LOCAL ROLE authenticated;
-- Mock the auth.uid() function
CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID LANGUAGE SQL AS 'SELECT ''user1-uuid''::UUID';
-- Should return data
SELECT is(
(SELECT count(*) FROM public.projects WHERE workspace_id = 'workspace1-uuid'),
1,
'User should be able to see their workspace project'
);
-- Should return no data
SELECT is(
(SELECT count(*) FROM public.projects WHERE workspace_id = 'workspace2-uuid'),
0,
'User should not be able to see projects from other workspaces'
);
ROLLBACK;
```
## Database Triggers
Triggers in Postgres allow you to automatically execute a function when a specified database event occurs (INSERT, UPDATE, DELETE). In NCT Hub, we use triggers for various purposes like:
* Maintaining audit logs
* Syncing data between tables
* Enforcing complex business rules
### Creating Triggers
Here's how to create a trigger in your NCT Hub development workflow:
1. First, create a trigger function:
```sql theme={null}
create or replace function public.handle_new_user()
returns trigger
language plpgsql
security definer
as $$
begin
-- Create a personal workspace for the new user
insert into public.workspaces (id, name, created_by)
values (gen_random_uuid(), new.email || '''s workspace', new.id);
-- Make the user an admin of their personal workspace
insert into public.workspace_members (workspace_id, user_id, role)
values (
(select id from public.workspaces where created_by = new.id),
new.id,
'admin'
);
return new;
end;
$$;
```
2. Then, create the trigger:
```sql theme={null}
create trigger on_auth_user_created
after insert on auth.users
for each row
execute function public.handle_new_user();
```
### Common Triggers in NCT Hub
#### Audit Logging
```sql theme={null}
create or replace function private.audit_log_changes()
returns trigger
language plpgsql
security definer
as $$
begin
insert into public.audit_logs (
table_name,
record_id,
action,
old_data,
new_data,
performed_by
)
values (
TG_TABLE_NAME,
coalesce(new.id, old.id),
TG_OP,
case when TG_OP = 'DELETE' or TG_OP = 'UPDATE' then row_to_json(old) else null end,
case when TG_OP = 'INSERT' or TG_OP = 'UPDATE' then row_to_json(new) else null end,
coalesce(auth.uid(), '00000000-0000-0000-0000-000000000000'::uuid)
);
return coalesce(new, old);
end;
$$;
-- Apply this trigger to a table
create trigger projects_audit_trigger
after insert or update or delete
on public.projects
for each row
execute function private.audit_log_changes();
```
#### Automated Timestamps
```sql theme={null}
create or replace function public.update_timestamp()
returns trigger
language plpgsql
as $$
begin
new.updated_at = now();
return new;
end;
$$;
-- Apply to a table
create trigger update_projects_timestamp
before update
on public.projects
for each row
execute function public.update_timestamp();
```
### Testing Triggers
You can test triggers by running SQL commands in the local Supabase instance and verifying the results:
```sql theme={null}
-- Insert a test user
insert into auth.users (id, email)
values ('test-uuid', 'test@example.com');
-- Verify the trigger created a workspace
select * from public.workspaces where created_by = 'test-uuid';
-- Verify the user is an admin of the workspace
select * from public.workspace_members
where user_id = 'test-uuid' and role = 'admin';
```
## Seeding Your Database
Database seeding is the process of populating your database with initial data. In NCT Hub, we use seeding to:
1. Create test users and workspaces for local development
2. Initialize lookup tables with standard values
3. Ensure a consistent starting point for all developers
### Seed Files Location
In NCT Hub, seed files are stored in `apps/db/supabase/seed.sql`. This file is automatically executed when you run `bun sb:reset` or start a fresh Supabase instance.
### Real Examples from NCT Hub's Seed File
Let's look at some real examples from NCT Hub's seed.sql file:
#### 1. Authentication Users
The seed file creates five default test users with pre-set passwords:
```sql theme={null}
-- Populate auth users
INSERT INTO
"auth"."users" (
"instance_id",
"id",
"aud",
"role",
"email",
"encrypted_password",
"email_confirmed_at",
/* other fields... */
)
VALUES
(
'00000000-0000-0000-0000-000000000000',
'00000000-0000-0000-0000-000000000001',
'authenticated',
'authenticated',
'local@tuturuuu.com',
crypt('password123', gen_salt('bf')),
'2023-02-18 23:31:13.017218+00',
/* other values... */
),
/* additional users... */
```
All seed users have the same password: `password123`, making it easy to log in for testing.
#### 2. Workspaces
The seed creates several workspaces for testing different scenarios:
```sql theme={null}
-- Populate workspaces
insert into
public.workspaces (id, name, handle, creator_id)
values
(
'00000000-0000-0000-0000-000000000000',
'NCT Hub',
'ncthub',
'00000000-0000-0000-0000-000000000001'
),
(
'00000000-0000-0000-0000-000000000001',
'Prototype All',
'prototype-all',
null
),
/* additional workspaces... */
```
#### 3. Workspace Members and Roles
The seed also sets up relationships between users and workspaces with different roles:
```sql theme={null}
-- Populate workspace_members
insert into
public.workspace_members (user_id, ws_id, role)
values
(
'00000000-0000-0000-0000-000000000001',
'00000000-0000-0000-0000-000000000000',
'OWNER'
),
(
'00000000-0000-0000-0000-000000000002',
'00000000-0000-0000-0000-000000000000',
'ADMIN'
),
(
'00000000-0000-0000-0000-000000000003',
'00000000-0000-0000-0000-000000000000',
'MEMBER'
),
/* additional members... */
```
#### 4. Workspace Features Configuration
The seed file configures workspace features using secrets:
```sql theme={null}
-- Populate workspace_secrets
insert into
public.workspace_secrets (ws_id, name, value)
values
(
'00000000-0000-0000-0000-000000000000',
'ENABLE_CHAT',
'true'
),
(
'00000000-0000-0000-0000-000000000000',
'ENABLE_EDUCATION',
'true'
),
/* additional features... */
```
#### 5. Domain-specific Data
The seed includes domain-specific data for different workspace types. For example, healthcare data:
```sql theme={null}
-- Populate healthcare_vitals
insert into
public.healthcare_vitals (id, ws_id, name, unit)
values
(
'00000000-0000-0000-0000-000000000001',
'00000000-0000-0000-0000-000000000003',
'Nhiệt độ',
'°C'
),
(
'00000000-0000-0000-0000-000000000002',
'00000000-0000-0000-0000-000000000003',
'Chiều cao',
'cm'
),
/* additional vitals... */
```
### Creating Seed Data
Here's how to create and modify seed data:
1. Edit the `apps/db/supabase/seed.sql` file
2. Add SQL statements to insert your data
3. Run `bun sb:reset` to apply the seed data
Example seed data format:
```sql theme={null}
-- Create a new user group
INSERT INTO public.workspace_user_groups (id, name, ws_id)
VALUES
('your-uuid-here', 'New Group', 'workspace-uuid-here')
ON CONFLICT (id) DO NOTHING;
-- Add a new workspace feature
INSERT INTO public.workspace_secrets (ws_id, name, value)
VALUES
('workspace-uuid-here', 'ENABLE_NEW_FEATURE', 'true')
ON CONFLICT (ws_id, name) DO UPDATE
SET value = EXCLUDED.value;
```
### Creating a Custom Seed File
Sometimes you might want to create a custom seed file for specific testing scenarios:
1. Create a new SQL file in the `apps/db/supabase` directory
2. Add your custom seed data
3. Run it with the Supabase CLI:
```bash theme={null}
bun supabase db reset --db-url=postgresql://postgres:postgres@localhost:54322/postgres
psql postgresql://postgres:postgres@localhost:54322/postgres -f apps/db/supabase/my_custom_seed.sql
```
### Exporting Current Data as Seed
You can also export your current database data to use as seed data:
```bash theme={null}
# Export only data (not schema) to seed.sql
bun supabase db dump --db-url=postgresql://postgres:postgres@localhost:54322/postgres --data-only > apps/db/supabase/new_seed.sql
```
This is helpful when you've set up data manually and want to preserve it for future development environments.
### Recommended Seeding Workflow
For NCT Hub development, we recommend:
1. Start with a fresh database: `bun sb:reset`
2. Make changes through the UI or your app
3. When you're satisfied, export the data: `bun supabase db dump --data-only > apps/db/supabase/new_seed.sql`
4. Edit the generated SQL to keep only what you need
5. Update the main `seed.sql` file with your changes
6. Test by running `bun sb:reset` again
## AI Integration with Vercel AI SDK
NCT Hub uses Vercel's AI SDK for its AI features, utilizing structured data generation capabilities that integrate with Supabase. This section covers how to work with AI features in the development workflow.
### Overview of AI SDK in NCT Hub
The AI SDK standardizes integrating various AI models across supported providers into NCT Hub applications. It enables structured data generation, tool calling, and streaming responses to create rich AI-powered features.
The main libraries used are:
* `ai` - Core Vercel AI SDK package
* `@ai-sdk/google` - Provider-specific integration for Google models
* `@ncthub/supabase` - Supabase client with NCT Hub-specific utilities
### Generating Structured Data
NCT Hub uses the AI SDK's structured data generation capabilities to create typed responses from AI models. This approach ensures type safety and consistent data structures for features like:
* Flashcards generation
* Quiz generation
* Learning plans
* Task management
#### Example: Flashcard Generation
The structured data pattern used in NCT Hub follows this workflow:
1. Define a schema using Zod
2. Connect to Supabase for authentication and workspace validation
3. Generate structured data using the AI SDK
4. Stream the response to the client
Here's an example from NCT Hub's codebase:
```typescript theme={null}
// 1. Define the schema
import { z } from 'zod';
export const flashcardSchema = z.object({
flashcards: z.array(
z.object({
front: z.string().describe('Question. Do not use emojis or links.'),
back: z.string().describe('Answer. Do not use emojis or links.'),
})
),
});
// 2. Setup API endpoint
export async function POST(req: Request) {
const sbAdmin = await createAdminClient();
const { wsId, context } = await req.json();
// Validate user and workspace permissions
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return new Response('Unauthorized', { status: 401 });
// Check workspace feature flag
const { count, error } = await sbAdmin
.from('workspace_secrets')
.select('*', { count: 'exact', head: true })
.eq('ws_id', wsId)
.eq('name', 'ENABLE_CHAT')
.eq('value', 'true');
if (error) return new Response(error.message, { status: 500 });
if (count === 0)
return new Response('You are not allowed to use this feature.', {
status: 401,
});
// 3. Generate structured data using AI SDK
const result = streamObject({
model: google('gemini-2.0-flash-001', {
safetySettings: [
// Safety settings configuration...
],
}),
prompt: `Generate 10 flashcards with the following context: ${context}`,
schema: flashcardSchema,
});
// 4. Stream the response to the client
return result.toTextStreamResponse();
}
```
### Available Models
NCT Hub supports multiple AI models through Vercel AI SDK. You can define which models are available in your application by updating the `models.ts` file in the `packages/ai` directory:
```typescript theme={null}
export const models = [
{
value: 'gemini-2.0-flash-001',
label: 'gemini-2.0-flash',
provider: 'Google',
description: 'Gemini 2.0 Flash delivers next-gen features...',
context: 1000000,
},
// Add other models here...
];
export const defaultModel = models.find(
(model) =>
model.value === 'gemini-2.0-flash-001' && model.provider === 'Google Vertex'
);
```
### Creating Custom Schema Types
To create new structured data types for AI generation, add your schema definition to the `packages/ai/src/object/types.ts` file:
```typescript theme={null}
export const myNewSchema = z.object({
items: z.array(
z.object({
name: z.string().describe('Name of the item'),
description: z.string().describe('Description of the item'),
priority: z.enum(['high', 'medium', 'low']).describe('Priority level'),
})
),
});
```
### Integration with Supabase
NCT Hub's AI features leverage Supabase for:
1. **Authentication** - Validating users before making AI requests
2. **Authorization** - Checking workspace permissions via `workspace_secrets`
3. **Feature Flags** - Using `workspace_secrets` to enable/disable AI features per workspace
4. **Storage** - Storing AI-generated content for later use
To enable AI features for a workspace, ensure the appropriate flags are set in the `workspace_secrets` table:
```sql theme={null}
-- Enable AI chat features for a workspace
INSERT INTO public.workspace_secrets (ws_id, name, value)
VALUES ('your-workspace-id', 'ENABLE_CHAT', 'true');
-- Enable AI document features for a workspace
INSERT INTO public.workspace_secrets (ws_id, name, value)
VALUES ('your-workspace-id', 'ENABLE_DOCS', 'true');
```
### Testing AI Features Locally
When testing AI features in your local environment:
1. Ensure you have the required API keys set in your `.env.local` file:
```
GOOGLE_GENERATIVE_AI_API_KEY=your-api-key
```
2. Verify the workspace has the necessary feature flags enabled in your local database
```sql theme={null}
SELECT * FROM workspace_secrets WHERE ws_id = 'your-workspace-id' AND name = 'ENABLE_CHAT';
```
3. Use the AI-enabled accounts from the seed data (`local@tuturuuu.com`) as they often have additional permissions
### Error Handling
When integrating AI features, implement proper error handling to account for:
1. Missing API keys
2. Model unavailability
3. Invalid user input
4. Exceeded token limits
Example error handling pattern used in NCT Hub:
```typescript theme={null}
try {
// AI SDK code here
} catch (error: any) {
console.log(error);
return NextResponse.json(
{
message: `## Edge API Failure\nCould not complete the request. Please view the **Stack trace** below.\n\`\`\`bash\n${error?.stack}`,
},
{
status: 200,
}
);
}
```
# Monorepo Architecture
Source: https://docs.rmitnct.club/monorepo-architecture
Understanding NCT Hub monorepo architecture and the benefits of using Turborepo.
**Prerequisite**: You should have followed the [Development](/development)
setup guide to understand the basic structure of the codebase.
## What is a Monorepo?
A monorepo is a single repository containing multiple distinct projects with well-defined relationships. This approach differs from a polyrepo strategy where each project has its own separate repository.
> "A monorepo is a single repository containing multiple distinct projects, with well-defined relationships."
> — [monorepo.tools](https://monorepo.tools/)
It's important to note that a monorepo is not the same as a monolith. A monolith is a single, tightly coupled application, while a monorepo can contain many independent applications, libraries, and tools that can be deployed separately.
## Why NCT Hub Uses a Monorepo
NCT Hub's platform is built as a monorepo (`@rmit-nct/hub`) for several key reasons:
### 1. Code Sharing Without Overhead
Our monorepo structure makes it easy to share code across different applications and services without the overhead of publishing packages. Core components, utilities, and business logic can be shared across multiple applications without duplicating code.
```
platform/
├── apps/
│ ├── web/ # Main web application
│ ├── docs/ # Documentation site (Mintlify)
│ └── ... # Other applications
└── packages/
├── ai/ # Shared AI functions & configurations
├── ui/ # Shared UI components
├── types/ # Shared TypeScript types
├── utils/ # Shared utilities
├── supabase/ # Supabase client and utilities
└── ... # Other shared packages
```
### 2. Atomic Changes Across Projects
When making changes that affect multiple parts of the platform, we can make those changes in a single commit. This ensures that all parts of the system remain compatible with each other, reducing integration issues.
For example, when updating a database schema:
1. We can update the Supabase schema in `apps/db/supabase/migrations`
2. Update the TypeScript types in `packages/types/src/supabase.ts`
3. Update all affected applications in the same pull request
### 3. Consistent Developer Experience
A monorepo allows us to standardize tooling, testing, and deployment processes across all projects. This creates a consistent development experience regardless of which part of the platform a developer is working on.
All developers use the same:
* Package manager (bun)
* Build system (Turborepo)
* Code style guidelines (enforced by ESLint and Prettier)
* Testing framework
* CI/CD pipelines
### 4. Simplified Dependency Management
Managing dependencies in a monorepo is simpler because we can ensure all projects use the same versions of shared dependencies, avoiding version conflicts.
## Why We Chose Turborepo
NCT Hub uses [Turborepo](https://turborepo.org/) as its build system for several reasons:
### 1. Incremental Builds with Caching
Turborepo provides intelligent caching of build artifacts. This means that if a file hasn't changed, Turborepo will use the cached result instead of rebuilding it, significantly reducing build times.
```bash theme={null}
# Only builds what changed since the last build
bun run build
```
### 2. Parallel Task Execution
Turborepo automatically parallelizes tasks, maximizing the use of available CPU cores.
```bash theme={null}
# Runs lint across all packages in parallel
bun lint
```
### 3. Task Orchestration
Turborepo understands dependencies between packages and ensures tasks are run in the correct order.
```bash theme={null}
# In turbo.json
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", ".next/**"]
}
}
}
```
### 4. Remote Caching
For CI/CD pipelines, Turborepo supports remote caching, which means build artifacts can be shared across different environments.
## Monorepo Structure
Our monorepo is organized into several main directories:
### apps/
Contains all deployable applications. Each application is a standalone project that can be deployed independently.
```
apps/
├── web/ # Main web application
├── docs/ # Documentation site (Mintlify)
└── db/ # Database migrations and scripts
```
### packages/
Contains shared libraries and utilities that are used by multiple applications.
```
packages/
├── ui/ # Shared UI components
├── types/ # Shared TypeScript types including Supabase types
├── utils/ # Shared utilities
├── ai/ # AI-related utilities
└── supabase/ # Supabase client and utilities
```
## Development Workflow
When working in our monorepo, you'll typically:
1. Clone the repository: `git clone https://github.com/rmit-nct/hub.git`
2. Install dependencies: `bun install`
3. Start the development servers: `bun dev` or `bun devx` (with Supabase)
For more detailed instructions on development workflow, see the [Development](/development) and [Local Supabase Development](/local-supabase-development) guides.
## Best Practices
When working in our monorepo, follow these best practices:
### 1. Keep Projects Modular
Even though all code lives in one repository, maintain clear boundaries between projects. Each package or app should have a well-defined purpose and API.
### 2. Use Workspace References
When one project depends on another within the monorepo, use workspace references:
```json theme={null}
{
"dependencies": {
"@ncthub/ui": "workspace:*",
"@ncthub/types": "workspace:*"
}
}
```
### 3. Think About Build Order
Be mindful of dependencies between packages. If package B depends on package A, ensure that changes to package A trigger rebuilds of package B.
### 4. Use Correct Scope for Changes
* For changes that affect a single application, focus your changes there
* For changes that affect multiple applications, consider extracting common code to a shared package
* For global changes (like tooling updates), ensure you test across all affected projects
## Common Challenges and Solutions
### Challenge: Long Build Times
**Solution:** Turborepo's caching mechanism helps, but also:
* Be selective about what you build during development
* Use `bun --filter` to focus on specific packages
```bash theme={null}
# Only build the web app and its dependencies
bun --filter web... build
```
### Challenge: Dependency Management
**Solution:**
* Regularly update dependencies
* Bun automatically detects workspace packages from the root `package.json` workspaces field
* Consider using `bun dedupe` to eliminate duplicate dependencies
### Challenge: CI/CD Pipeline Complexity
**Solution:**
* Use GitHub Actions workflows that are specific to the affected parts of the codebase
* Leverage Turborepo's `--filter` and `--since` flags to only build what's changed
## Further Resources
* [monorepo.tools](https://monorepo.tools/): Comprehensive information about monorepos
* [Turborepo Documentation](https://turbo.build/repo/docs): Official Turborepo documentation
* [Bun Workspace](https://bun.sh/docs/install/workspaces): How bun handles monorepos
# Neo Chess
Source: https://docs.rmitnct.club/platform/applications/neo-chess
Multiplayer chess game with AI opponents and real-time gameplay
Neo Chess is NCT Hub's multiplayer chess game featuring real-time gameplay, AI opponents, and competitive features designed to engage club members in strategic thinking and friendly competition.
## Overview
Neo Chess provides an interactive chess experience that combines traditional chess gameplay with modern web technologies, real-time synchronization, and AI-powered opponents for solo play.
## Key Features
### **Multiplayer Gameplay**
* **Real-time Matches** – Play against other club members with live move synchronization
* **Matchmaking System** – Find opponents based on skill level and availability
* **Spectator Mode** – Watch ongoing matches between other players
* **Game History** – Track your matches and performance over time
### **AI Opponents**
* **Multiple Difficulty Levels** – Choose from beginner to expert AI opponents
* **Adaptive AI** – AI opponents that adjust to your playing style
* **Training Mode** – Practice against AI without affecting your rating
* **Puzzle Challenges** – Solve chess puzzles and tactical problems
### **Competitive Features**
* **Rating System** – Track your chess rating and improvement
* **Leaderboards** – See top players in the club
* **Tournaments** – Participate in club chess tournaments
* **Achievements** – Unlock badges for various accomplishments
### **Visual Design**
* **Custom Chess Pieces** – Beautiful, detailed chess piece designs
* **Dark/Light Themes** – Choose your preferred board theme
* **Animations** – Smooth piece movements and transitions
* **Responsive Design** – Play on desktop, tablet, or mobile devices
## Technical Implementation
### Game Architecture
```mermaid theme={null}
flowchart TB
subgraph "Client Side"
Board["Chess Board UI"]
Pieces["Chess Pieces"]
Moves["Move Validation"]
UI["Game Interface"]
end
subgraph "Real-time Sync"
Supabase["Supabase Realtime"]
WebSocket["WebSocket Connection"]
end
subgraph "AI Engine"
ChessJS["Chess.js Engine"]
AI["AI Opponent Logic"]
Minimax["Minimax Algorithm"]
end
subgraph "Database"
Games["Game States"]
Users["Player Data"]
Stats["Statistics"]
end
Board --> Moves
Moves --> Supabase
Supabase --> WebSocket
WebSocket --> Board
AI --> ChessJS
ChessJS --> Minimax
Minimax --> AI
Supabase --> Games
Games --> Users
Users --> Stats
```
### Chess Piece Assets
The game uses custom-designed chess pieces stored in the public folder:
#### White Pieces
* `w_king.png` - White King
* `w_queen.png` - White Queen
* `w_rook.png` - White Rook
* `w_bishop.png` - White Bishop
* `w_knight.png` - White Knight
* `w_pawn.png` - White Pawn
#### Black Pieces
* `b_king.png` - Black King
* `b_queen.png` - Black Queen
* `b_rook.png` - Black Rook
* `b_bishop.png` - Black Bishop
* `b_knight.png` - Black Knight
* `b_pawn.png` - Black Pawn
### Real-time Synchronization
```typescript theme={null}
// Real-time game state updates
const channel = supabase
.channel(`chess-game-${gameId}`)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'chess_games',
filter: `id=eq.${gameId}`,
},
(payload) => {
updateGameState(payload.new);
}
)
.subscribe();
```
### AI Implementation
```typescript theme={null}
// AI move generation using minimax algorithm
function getBestMove(game: Chess, depth: number): string {
const moves = game.moves();
let bestMove = '';
let bestScore = -Infinity;
for (const move of moves) {
game.move(move);
const score = minimax(game, depth - 1, false);
game.undo();
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
}
return bestMove;
}
```
## Game Modes
### **Quick Match**
* **Random Opponent** – Get matched with an available player
* **Time Controls** – Choose from blitz, rapid, or classical time controls
* **Rating Range** – Play against opponents of similar skill level
### **AI Practice**
* **Difficulty Selection** – Choose from 5 difficulty levels
* **Analysis Mode** – Get hints and move suggestions
* **Puzzle Training** – Solve tactical puzzles and endgames
### **Club Tournaments**
* **Scheduled Events** – Participate in club-organized tournaments
* **Swiss System** – Fair tournament pairing system
* **Prizes** – Compete for club recognition and achievements
### **Analysis Mode**
* **Game Review** – Analyze your completed games
* **Move Evaluation** – See computer evaluation of moves
* **Learning Resources** – Access chess tutorials and guides
## User Interface
### Game Board
* **Drag & Drop** – Intuitive piece movement
* **Legal Move Highlighting** – Visual indicators for valid moves
* **Move History** – Track all moves in algebraic notation
* **Position Evaluation** – Real-time position assessment
### Game Controls
* **Timer Display** – Show remaining time for both players
* **Move Indicators** – Visual feedback for piece movements
* **Game Status** – Current game state and phase
* **Chat System** – Communicate with opponent (optional)
### Settings Panel
* **Theme Selection** – Choose board and piece colors
* **Sound Controls** – Enable/disable move sounds
* **Animation Speed** – Adjust piece movement speed
* **Difficulty Settings** – For AI opponents
## Database Schema
### Chess Games Table
```sql theme={null}
CREATE TABLE chess_games (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
white_player_id UUID REFERENCES users(id),
black_player_id UUID REFERENCES users(id),
game_state JSONB NOT NULL,
moves TEXT[] DEFAULT '{}',
status TEXT DEFAULT 'active',
time_control JSONB,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
```
### Player Statistics Table
```sql theme={null}
CREATE TABLE chess_player_stats (
user_id UUID PRIMARY KEY REFERENCES users(id),
rating INTEGER DEFAULT 1200,
games_played INTEGER DEFAULT 0,
games_won INTEGER DEFAULT 0,
games_lost INTEGER DEFAULT 0,
games_drawn INTEGER DEFAULT 0,
best_rating INTEGER DEFAULT 1200,
last_played TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
```
## API Endpoints
### Game Management
```typescript theme={null}
// Create new game
POST /api/chess/games
{
"opponentId": "uuid",
"timeControl": "blitz|rapid|classical",
"color": "white|black|random"
}
// Make move
POST /api/chess/games/{gameId}/move
{
"move": "e2e4",
"timestamp": "2025-01-10T10:00:00Z"
}
// Get game state
GET /api/chess/games/{gameId}
```
### Player Statistics
```typescript theme={null}
// Get player stats
GET /api/chess/stats/{userId}
// Get leaderboard
GET /api/chess/leaderboard?limit=10&timeframe=monthly
```
## Integration with NCT Hub
### Member System
* **Automatic Registration** – All NCT Hub members can play
* **Profile Integration** – Chess stats appear in member profiles
* **Achievement System** – Chess achievements integrate with club badges
### Club Events
* **Tournament Organization** – Club admins can organize chess tournaments
* **Event Integration** – Chess tournaments appear in club calendar
* **Member Engagement** – Track member participation in chess activities
### Analytics
* **Game Statistics** – Track club-wide chess engagement
* **Popular Time Slots** – Identify peak playing times
* **Member Retention** – Monitor chess player activity over time
## Future Enhancements
### Planned Features
* **Video Analysis** – Record and analyze games
* **Opening Explorer** – Database of chess openings
* **Endgame Trainer** – Practice endgame scenarios
* **Mobile App** – Native mobile application
* **Streaming Integration** – Stream games to club members
### Community Features
* **Chess Clubs** – Form sub-groups within NCT Hub
* **Mentorship Program** – Pair experienced players with beginners
* **Chess Lessons** – Structured learning program
* **Problem Solving** – Daily chess puzzles and challenges
## Related Resources
* [Platform Overview](/platform/index) – Understanding the complete platform architecture
* [Member Management](/platform/features/user-management) – Managing club members and roles
* [Analytics Dashboard](/platform/features/command-center-dashboard) – Tracking game analytics and engagement
* [Neo Crush](/platform/applications/neo-crush) – Another NCT Hub game application
# Neo Crush
Source: https://docs.rmitnct.club/platform/applications/neo-crush
Multiplayer puzzle game with real-time competition and colorful gameplay
Neo Crush is NCT Hub's multiplayer puzzle game featuring colorful gems, strategic gameplay, and real-time competition. Players match gems to clear the board while competing against other club members in fast-paced, engaging rounds.
## Overview
Neo Crush combines the addictive gameplay of match-3 puzzle games with multiplayer competition, creating an engaging social gaming experience that brings NCT Hub members together through friendly competition and collaborative play.
## Key Features
### **Multiplayer Gameplay**
* **Real-time Competition** – Play against other club members simultaneously
* **Live Leaderboards** – See rankings update in real-time during matches
* **Tournament Mode** – Participate in organized competitions
* **Spectator Support** – Watch other players' games in progress
### **Colorful Gem System**
* **Seven Gem Types** – Each with unique colors and properties:
* **Red** - Classic fire gems
* **Orange** - Energetic citrus gems
* **Yellow** - Bright sun gems
* **Green** - Natural forest gems
* **Blue** - Cool ocean gems
* **Purple** - Mystical royal gems
* **Pink** - Sweet candy gems
### **Competitive Features**
* **Score Tracking** – Monitor your performance and improvement
* **Achievement System** – Unlock badges for various accomplishments
* **Seasonal Rankings** – Compete in monthly leaderboards
* **Club Championships** – Participate in NCT Hub tournaments
### **Game Mechanics**
* **Match-3 Gameplay** – Classic puzzle mechanics with modern twists
* **Power-ups** – Special gems that create explosive effects
* **Combo System** – Chain matches for massive point multipliers
* **Time Pressure** – Strategic gameplay under time constraints
## Technical Implementation
### Game Architecture
```mermaid theme={null}
flowchart TB
subgraph "Client Side"
Grid["Game Grid UI"]
Gems["Gem Rendering"]
Physics["Match Detection"]
Score["Score System"]
end
subgraph "Real-time Sync"
Supabase["Supabase Realtime"]
WebSocket["WebSocket Connection"]
Leaderboard["Live Leaderboard"]
end
subgraph "Game Logic"
Engine["Game Engine"]
Matches["Match Detection"]
Combos["Combo System"]
Effects["Visual Effects"]
end
subgraph "Database"
Games["Game Sessions"]
Scores["Player Scores"]
Stats["Statistics"]
Achievements["Achievements"]
end
Grid --> Gems
Gems --> Physics
Physics --> Score
Score --> Supabase
Supabase --> WebSocket
WebSocket --> Leaderboard
Leaderboard --> Grid
Engine --> Matches
Matches --> Combos
Combos --> Effects
Supabase --> Games
Games --> Scores
Scores --> Stats
Stats --> Achievements
```
### Gem Asset System
The game uses high-quality gem assets stored in the public folder:
#### Gem Colors
* `red.png` - Vibrant red fire gems
* `orange.png` - Bright orange citrus gems
* `yellow.png` - Glowing yellow sun gems
* `green.png` - Rich green forest gems
* `blue.png` - Deep blue ocean gems
* `purple.png` - Royal purple gems
* `pink.png` - Sweet pink candy gems
### Real-time Synchronization
```typescript theme={null}
// Real-time score updates and leaderboard
const gameChannel = supabase
.channel(`neo-crush-game-${gameId}`)
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'game_scores',
},
(payload) => {
updateLeaderboard(payload.new);
}
)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'neo_crush_games',
filter: `id=eq.${gameId}`,
},
(payload) => {
updateGameState(payload.new);
}
)
.subscribe();
```
### Match Detection Algorithm
```typescript theme={null}
// Detect matches in the game grid
function findMatches(grid: Gem[][], minLength: number = 3): Match[] {
const matches: Match[] = [];
// Check horizontal matches
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length - minLength + 1; col++) {
const color = grid[row][col].color;
let matchLength = 1;
while (
col + matchLength < grid[row].length &&
grid[row][col + matchLength].color === color
) {
matchLength++;
}
if (matchLength >= minLength) {
matches.push({
type: 'horizontal',
row,
startCol: col,
length: matchLength,
color,
});
}
}
}
// Check vertical matches (similar logic)
// ...
return matches;
}
```
## Game Modes
### **Quick Play**
* **Solo Practice** – Play against yourself to improve skills
* **Daily Challenges** – Special puzzles with unique objectives
* **Tutorial Mode** – Learn game mechanics and strategies
* **Free Play** – Unlimited gameplay without competition
### **Multiplayer Modes**
* **Real-time Battles** – Compete against other players simultaneously
* **Turn-based Matches** – Take turns in strategic gameplay
* **Team Competitions** – Work together with other club members
* **Club Tournaments** – Organized competitions with prizes
### **Competitive Play**
* **Ranked Matches** – Earn rating points through competitive play
* **Seasonal Leagues** – Compete in monthly ranking systems
* **Achievement Hunts** – Complete specific challenges for rewards
* **Speed Rounds** – Fast-paced matches with time pressure
### **Learning Modes**
* **Strategy Guide** – Learn advanced techniques and combos
* **Pattern Recognition** – Practice identifying match opportunities
* **Combo Training** – Master chain reactions and multipliers
* **Power-up Tutorials** – Understand special gem effects
## User Interface
### Game Grid
* **Drag & Drop** – Intuitive gem swapping mechanics
* **Visual Feedback** – Highlighted valid moves and potential matches
* **Smooth Animations** – Polished gem movements and effects
* **Grid Indicators** – Show possible match locations
### Score Display
* **Current Score** – Real-time point tracking
* **Multiplier Display** – Show current combo multiplier
* **High Score** – Personal best and club records
* **Progress Bar** – Visual representation of game progress
### Leaderboard
* **Live Updates** – Real-time ranking changes
* **Player Avatars** – Visual identification of competitors
* **Score Tracking** – Current round scores and total points
* **Club Rankings** – NCT Hub member standings
### Game Controls
* **Pause/Resume** – Control game flow
* **Settings Panel** – Adjust graphics and audio
* **Help System** – Access tutorials and tips
* **Social Features** – Chat and emoji reactions
## Database Schema
### Game Sessions Table
```sql theme={null}
CREATE TABLE neo_crush_games (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
game_type TEXT NOT NULL, -- 'quick_play', 'multiplayer', 'tournament'
status TEXT DEFAULT 'active', -- 'active', 'completed', 'paused'
max_players INTEGER DEFAULT 1,
time_limit INTEGER, -- seconds
created_at TIMESTAMP DEFAULT NOW(),
ended_at TIMESTAMP
);
```
### Player Scores Table
```sql theme={null}
CREATE TABLE neo_crush_scores (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
game_id UUID REFERENCES neo_crush_games(id),
user_id UUID REFERENCES users(id),
score INTEGER NOT NULL,
gems_matched INTEGER DEFAULT 0,
combos_created INTEGER DEFAULT 0,
power_ups_used INTEGER DEFAULT 0,
rank INTEGER,
created_at TIMESTAMP DEFAULT NOW()
);
```
### Player Statistics Table
```sql theme={null}
CREATE TABLE neo_crush_player_stats (
user_id UUID PRIMARY KEY REFERENCES users(id),
total_games INTEGER DEFAULT 0,
total_score BIGINT DEFAULT 0,
high_score INTEGER DEFAULT 0,
average_score INTEGER DEFAULT 0,
gems_matched BIGINT DEFAULT 0,
combos_created INTEGER DEFAULT 0,
win_streak INTEGER DEFAULT 0,
best_win_streak INTEGER DEFAULT 0,
rating INTEGER DEFAULT 1000,
last_played TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
```
## API Endpoints
### Game Management
```typescript theme={null}
// Create new game
POST /api/neo-crush/games
{
"gameType": "multiplayer|quick_play|tournament",
"maxPlayers": 4,
"timeLimit": 300
}
// Submit score
POST /api/neo-crush/games/{gameId}/score
{
"score": 1250,
"gemsMatched": 45,
"combosCreated": 3,
"powerUpsUsed": 1
}
// Get leaderboard
GET /api/neo-crush/leaderboard?timeframe=daily|weekly|monthly&limit=50
```
### Player Statistics
```typescript theme={null}
// Get player stats
GET /api/neo-crush/stats/{userId}
// Get game history
GET /api/neo-crush/games/history/{userId}?limit=20
// Update achievement progress
POST /api/neo-crush/achievements/progress
{
"achievementId": "uuid",
"progress": 75
}
```
## Game Mechanics
### Scoring System
* **Base Points** – Points for each gem matched
* **Combo Multipliers** – Increasing multipliers for chain reactions
* **Power-up Bonuses** – Extra points for special gem effects
* **Time Bonuses** – Additional points for quick matches
* **Perfect Games** – Bonus points for no-miss rounds
### Power-up System
* **Bomb Gems** – Clear surrounding gems in explosion
* **Lightning Gems** – Destroy entire rows or columns
* **Rainbow Gems** – Match any color gem
* **Time Extensions** – Add extra seconds to the timer
* **Score Multipliers** – Temporarily increase point values
### Combo Mechanics
* **Chain Reactions** – Cascading matches from falling gems
* **Multiplier Progression** – Increasing multipliers for longer chains
* **Special Combinations** – Unique patterns for massive scores
* **Power-up Synergy** – Combining power-ups for maximum effect
## Integration with NCT Hub
### Member Engagement
* **Daily Challenges** – Encourage regular club member participation
* **Social Features** – Share achievements and high scores
* **Club Events** – Organize NCT Hub gaming tournaments
* **Member Recognition** – Highlight top performers
### Analytics Integration
* **Engagement Metrics** – Track member participation in gaming
* **Performance Analytics** – Monitor game statistics and trends
* **Social Interaction** – Measure community engagement through gaming
* **Retention Tracking** – Monitor long-term member activity
### Achievement System
* **Club Badges** – Special achievements for NCT Hub members
* **Skill Progression** – Track improvement over time
* **Community Goals** – Collaborative achievements for the entire club
* **Event Participation** – Recognition for tournament participation
## Future Enhancements
### Planned Features
* **Mobile Optimization** – Enhanced touch controls for mobile devices
* **Voice Chat** – Real-time communication during multiplayer matches
* **Custom Themes** – NCT Hub branded gem designs and backgrounds
* **AI Opponents** – Practice against computer-controlled players
### Community Features
* **Guild System** – Form gaming teams within NCT Hub
* **Mentorship Program** – Experienced players help newcomers
* **Streaming Integration** – Broadcast matches to club members
* **Cross-platform Play** – Play across different devices
### Advanced Gameplay
* **Puzzle Mode** – Solve predetermined gem arrangements
* **Boss Battles** – Special challenging rounds with unique mechanics
* **Seasonal Events** – Limited-time content and special rewards
* **Custom Levels** – User-generated content and challenges
## Related Resources
* [Platform Overview](/platform/index) – Understanding the complete platform architecture
* [Member Management](/platform/features/user-management) – Managing club members and roles
* [Analytics Dashboard](/platform/features/command-center-dashboard) – Tracking game analytics and engagement
* [Neo Chess](/platform/applications/neo-chess) – Another NCT Hub game application
# API Route Patterns
Source: https://docs.rmitnct.club/platform/architecture/api-routes
Implementing and organizing API routes in the NCT Hub platform
The NCT Hub platform uses Next.js App Router API routes with consistent patterns for versioning, authentication, error handling, and workspace isolation. The API is designed to support both club management operations and external integrations.
## Route Organization
### Directory Structure
```
apps/web/src/app/api/
├── v1/ # Versioned public API
│ ├── aurora/ # Aurora AI system endpoints
│ ├── calendar/ # Calendar integration
│ ├── infrastructure/ # Infrastructure management
│ ├── users/ # User management
│ └── workspaces/ # Workspace operations
├── ai/ # AI-specific endpoints
│ ├── chat/ # Multi-provider chat (Anthropic, OpenAI, Google)
│ └── objects/ # AI object generation (flashcards, quizzes)
├── auth/ # Authentication endpoints
│ ├── callback/ # OAuth callbacks
│ ├── me/ # Current user info
│ ├── otp/ # One-time passwords
│ └── logout/ # Session management
├── meet-together/ # Event scheduling
│ └── plans/ # Meet Together plans
├── students/ # Student management
├── users/ # User operations
├── workspaces/ # Workspace management
└── [wsId]/ # Workspace-scoped endpoints
├── crawlers/ # Data crawling
├── datasets/ # AI datasets
├── finance/ # Financial tracking
├── members/ # Member management
└── tasks/ # Task management
```
## Versioned Public API
### Pattern: `/api/v1/*`
Use for public-facing APIs that external clients consume.
```typescript theme={null}
// app/api/v1/workspaces/route.ts
import { createClient } from '@ncthub/supabase/server';
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
// GET /api/v1/workspaces
export async function GET(request: NextRequest) {
try {
const supabase = createClient();
// Check authentication
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Fetch user's workspaces
const { data: workspaces, error } = await supabase
.from('workspace_members')
.select(
`
ws_id,
role,
workspaces (
id,
name,
logo_url
)
`
)
.eq('user_id', user.id)
.eq('pending', false);
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json({
data: workspaces?.map((w) => w.workspaces),
});
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
// POST /api/v1/workspaces
const createWorkspaceSchema = z.object({
name: z.string().min(1).max(100),
logo_url: z.string().url().optional(),
});
export async function POST(request: NextRequest) {
try {
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Validate request body
const body = await request.json();
const parsed = createWorkspaceSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid input', details: parsed.error.issues },
{ status: 400 }
);
}
// Create workspace
const { data: workspace, error } = await supabase
.from('workspaces')
.insert({
name: parsed.data.name,
logo_url: parsed.data.logo_url,
})
.select()
.single();
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
// Add creator as owner
await supabase.from('workspace_members').insert({
ws_id: workspace.id,
user_id: user.id,
role: 'owner',
});
return NextResponse.json({ data: workspace }, { status: 201 });
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
## Workspace-Scoped API
### Pattern: `/api/[wsId]/*`
Use for workspace-specific operations with automatic workspace context.
```typescript theme={null}
// app/api/[wsId]/tasks/route.ts
import { hasPermission } from '@/lib/permissions';
import { createClient } from '@ncthub/supabase/server';
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
// GET /api/[wsId]/tasks
export async function GET(
request: NextRequest,
{ params }: { params: { wsId: string } }
) {
try {
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Check workspace membership
const isMember = await isWorkspaceMember(user.id, params.wsId);
if (!isMember) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Parse query parameters
const searchParams = request.nextUrl.searchParams;
const listId = searchParams.get('listId');
const completed = searchParams.get('completed');
// Build query
let query = supabase
.from('workspace_tasks')
.select('*')
.eq('ws_id', params.wsId);
if (listId) query = query.eq('list_id', listId);
if (completed !== null) query = query.eq('completed', completed === 'true');
const { data: tasks, error } = await query;
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json({ data: tasks });
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
// POST /api/[wsId]/tasks
const createTaskSchema = z.object({
name: z.string().min(1).max(255),
description: z.string().optional(),
listId: z.string(),
priority: z.number().int().min(0).max(5).optional(),
dueDate: z.string().datetime().optional(),
});
export async function POST(
request: NextRequest,
{ params }: { params: { wsId: string } }
) {
try {
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Check permission
const canCreate = await hasPermission(user.id, params.wsId, 'manage_tasks');
if (!canCreate) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Validate input
const body = await request.json();
const parsed = createTaskSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid input', details: parsed.error.issues },
{ status: 400 }
);
}
// Create task
const { data: task, error } = await supabase
.from('workspace_tasks')
.insert({
ws_id: params.wsId,
name: parsed.data.name,
description: parsed.data.description,
list_id: parsed.data.listId,
priority: parsed.data.priority,
due_date: parsed.data.dueDate,
created_by: user.id,
})
.select()
.single();
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json({ data: task }, { status: 201 });
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
// DELETE /api/[wsId]/tasks/[taskId]
export async function DELETE(
request: NextRequest,
{ params }: { params: { wsId: string; taskId: string } }
) {
try {
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const canDelete = await hasPermission(user.id, params.wsId, 'manage_tasks');
if (!canDelete) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { error } = await supabase
.from('workspace_tasks')
.delete()
.eq('id', params.taskId)
.eq('ws_id', params.wsId); // Ensure workspace isolation
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
## AI Endpoints
### Pattern: `/api/ai/*`
Use for AI-specific operations with model selection and token tracking.
```typescript theme={null}
// app/api/ai/chat/route.ts
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { createClient } from '@ncthub/supabase/server';
import { streamText } from 'ai';
import { NextRequest } from 'next/server';
import { z } from 'zod';
export const runtime = 'edge';
export const maxDuration = 60;
const chatRequestSchema = z.object({
messages: z.array(
z.object({
role: z.enum(['user', 'assistant', 'system']),
content: z.string(),
})
),
model: z.string().optional(),
});
export async function POST(request: NextRequest) {
try {
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return new Response('Unauthorized', { status: 401 });
}
// Validate input
const body = await request.json();
const parsed = chatRequestSchema.safeParse(body);
if (!parsed.success) {
return new Response('Invalid input', { status: 400 });
}
// Check AI feature flag
const { data: workspace } = await supabase
.from('workspace_secrets')
.select('value')
.eq('ws_id', body.wsId)
.eq('name', 'ENABLE_AI')
.single();
if (workspace?.value !== 'true') {
return new Response('AI not enabled for workspace', { status: 403 });
}
const google = createGoogleGenerativeAI({
apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY,
});
const model = parsed.data.model || 'gemini-2.0-flash-exp';
const result = streamText({
model: google(model),
messages: parsed.data.messages,
onFinish: async ({ usage }) => {
// Track token usage
await supabase.from('workspace_ai_executions').insert({
ws_id: body.wsId,
model,
input_tokens: usage.promptTokens,
output_tokens: usage.completionTokens,
total_cost: calculateCost(model, usage),
});
},
});
return result.toDataStreamResponse();
} catch (error) {
console.error('AI chat error:', error);
return new Response('Internal server error', { status: 500 });
}
}
function calculateCost(
model: string,
usage: { promptTokens: number; completionTokens: number }
): number {
// Pricing per million tokens
const pricing: Record = {
'gemini-2.0-flash-exp': { input: 0, output: 0 }, // Free tier
'gemini-2.0-pro-exp': { input: 0, output: 0 }, // Free tier
};
const price = pricing[model] || { input: 0, output: 0 };
return (
(usage.promptTokens / 1_000_000) * price.input +
(usage.completionTokens / 1_000_000) * price.output
);
}
```
## Authentication Endpoints
### Pattern: `/api/auth/*`
Use edge runtime for auth endpoints.
```typescript theme={null}
// app/api/auth/otp/route.ts
import { createClient } from '@ncthub/supabase/server';
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
export const runtime = 'edge';
const otpRequestSchema = z.object({
email: z.string().email(),
});
export async function POST(request: NextRequest) {
try {
const supabase = createClient();
const body = await request.json();
const parsed = otpRequestSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid email' }, { status: 400 });
}
const { error } = await supabase.auth.signInWithOtp({
email: parsed.data.email,
options: {
emailRedirectTo: `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`,
},
});
if (error) {
return NextResponse.json({ error: error.message }, { status: 400 });
}
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
## Error Response Standards
### Standard Error Format
```typescript theme={null}
interface ErrorResponse {
error: string;
details?: any;
code?: string;
}
```
### HTTP Status Codes
* `200` - Success
* `201` - Created
* `204` - No Content
* `400` - Bad Request (validation errors)
* `401` - Unauthorized (not authenticated)
* `403` - Forbidden (not authorized)
* `404` - Not Found
* `409` - Conflict
* `422` - Unprocessable Entity
* `429` - Too Many Requests
* `500` - Internal Server Error
### Error Handling Pattern
```typescript theme={null}
export async function POST(request: NextRequest) {
try {
// Implementation
} catch (error) {
console.error('API error:', error);
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: 'Validation failed', details: error.errors },
{ status: 400 }
);
}
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
## Middleware Pattern
### Permission Middleware
```typescript theme={null}
// lib/api/middleware.ts
import { hasPermission } from '@/lib/permissions';
import { createClient } from '@ncthub/supabase/server';
import { NextRequest, NextResponse } from 'next/server';
type Handler = (
req: NextRequest,
context: { params: any; user: any }
) => Promise;
export function withAuth(handler: Handler) {
return async (req: NextRequest, context: any) => {
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return handler(req, { ...context, user });
};
}
export function withPermission(permission: string, handler: Handler) {
return withAuth(async (req, context) => {
const wsId = context.params.wsId;
const allowed = await hasPermission(context.user.id, wsId, permission);
if (!allowed) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
return handler(req, context);
});
}
```
### Usage
```typescript theme={null}
// app/api/[wsId]/tasks/route.ts
import { withPermission } from '@/lib/api/middleware';
export const POST = withPermission(
'manage_tasks',
async (req, { params, user }) => {
// Implementation with guaranteed permission
}
);
```
## CORS Configuration
```typescript theme={null}
// app/api/v1/workspaces/route.ts
export async function OPTIONS(request: NextRequest) {
return new NextResponse(null, {
status: 200,
headers: {
'Access-Control-Allow-Origin': process.env.ALLOWED_ORIGIN || '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
}
```
## Rate Limiting
```typescript theme={null}
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '10 s'), // 10 requests per 10 seconds
});
export async function POST(request: NextRequest) {
const identifier = request.headers.get('x-forwarded-for') || 'anonymous';
const { success } = await ratelimit.limit(identifier);
if (!success) {
return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 });
}
// Continue with request
}
```
## Best Practices
### ✅ DO
1. **Always validate input**
```typescript theme={null}
const parsed = schema.safeParse(body);
if (!parsed.success) return error(400);
```
2. **Check authentication first**
```typescript theme={null}
const { data: { user } } = await supabase.auth.getUser();
if (!user) return error(401);
```
3. **Verify workspace permissions**
```typescript theme={null}
const allowed = await hasPermission(user.id, wsId, 'manage_tasks');
if (!allowed) return error(403);
```
4. **Use edge runtime for auth**
```typescript theme={null}
export const runtime = 'edge';
```
5. **Set max duration for long operations**
```typescript theme={null}
export const maxDuration = 60; // seconds
```
### ❌ DON'T
1. **Don't expose sensitive errors**
```typescript theme={null}
// ❌ Bad
return NextResponse.json({ error: error.stack });
```
2. **Don't skip workspace isolation**
```typescript theme={null}
// ❌ Bad: Can access any workspace
.delete().eq('id', taskId)
// ✅ Good: Workspace-scoped
.delete().eq('id', taskId).eq('ws_id', wsId)
```
3. **Don't use user client for mutations**
```typescript theme={null}
// ❌ Bad: Bypasses RLS
const supabase = createAdminClient();
```
## Related Documentation
* [Authentication](/platform/architecture/authentication)
* [Authorization](/platform/architecture/authorization)
* [tRPC](/platform/architecture/trpc)
* [Data Fetching](/platform/architecture/data-fetching)
# Authentication Patterns
Source: https://docs.rmitnct.club/platform/architecture/authentication
Authentication implementation patterns in the NCT Hub platform
The NCT Hub platform uses Supabase Auth for user authentication with support for email/password, OAuth providers, one-time passwords (OTP), and session management. The system is designed to handle club member authentication, external integrations, and secure API access.
## Authentication Flow
```
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Client │──1──>│ Supabase │──2──>│ Database │
│ (Browser/App)│ │ Auth │ │ (RLS) │
└──────────────┘ └──────────────┘ └──────────────┘
│ │ │
│<─────────3───────────│ │
│ Session Token │ │
│ │ │
│──────4──────────────────────────────────────>│
│ Authenticated Request (w/ session) │
│<─────────────────────────────────────────────│
│ Data (filtered by RLS) │
```
1. User signs in via Supabase Auth
2. Supabase validates credentials against database
3. Client receives session token
4. Subsequent requests include session token for RLS
## Sign Up
### Basic Email/Password Sign Up
```typescript theme={null}
'use server';
import { createClient } from '@ncthub/supabase/next/server';
import { redirect } from 'next/navigation';
export async function signUp(formData: FormData) {
const supabase = await createClient();
const email = formData.get('email') as string;
const password = formData.get('password') as string;
const displayName = formData.get('displayName') as string;
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
display_name: displayName,
},
emailRedirectTo: `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`,
},
});
if (error) {
return { error: error.message };
}
redirect('/onboarding');
}
```
### Client Component
```tsx theme={null}
'use client';
import { signUp } from './actions';
import { useState } from 'react';
export function SignUpForm() {
const [error, setError] = useState(null);
async function handleSubmit(formData: FormData) {
const result = await signUp(formData);
if (result?.error) {
setError(result.error);
}
}
return (
);
}
```
## Sign In
### Email/Password Sign In
```typescript theme={null}
'use server';
import { createClient } from '@ncthub/supabase/server';
import { redirect } from 'next/navigation';
export async function signIn(formData: FormData) {
const supabase = createClient();
const email = formData.get('email') as string;
const password = formData.get('password') as string;
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
return { error: error.message };
}
redirect('/dashboard');
}
```
### OAuth Sign In
```typescript theme={null}
'use server';
import { createClient } from '@ncthub/supabase/server';
export async function signInWithOAuth(provider: 'google' | 'github') {
const supabase = createClient();
const { data, error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${process.env.NEXT_PUBLIC_APP_URL}/auth/callback`,
},
});
if (error) {
return { error: error.message };
}
return { url: data.url };
}
```
Client Component:
```tsx theme={null}
'use client';
import { signInWithOAuth } from './actions';
export function OAuthButtons() {
async function handleOAuthSignIn(provider: 'google' | 'github') {
const result = await signInWithOAuth(provider);
if (result.url) {
window.location.href = result.url;
}
}
return (
);
}
```
## Procedure Types
### `publicProcedure`
No authentication required. Use for public endpoints.
```typescript theme={null}
export const publicRouter = router({
status: publicProcedure.query(() => {
return { status: 'ok' };
}),
});
```
### `protectedProcedure`
Requires authentication. Provides `ctx.user` in handler.
```typescript theme={null}
export const protectedRouter = router({
profile: protectedProcedure.query(({ ctx }) => {
return { userId: ctx.user.id }; // ctx.user is guaranteed
}),
});
```
Implementation in `apps/web/src/trpc/init.ts`:
```typescript theme={null}
const isAuthed = t.middleware(async ({ ctx, next }) => {
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
throw new Error('Unauthorized');
}
return next({
ctx: {
user, // Add user to context
},
});
});
export const protectedProcedure = t.procedure.use(isAuthed);
```
## Input Validation with Zod
Always validate inputs using Zod schemas:
```typescript theme={null}
import { z } from 'zod';
const createTaskSchema = z.object({
wsId: z.string().min(1, 'Workspace ID required'),
name: z.string().min(1, 'Name required').max(255, 'Name too long'),
priority: z.number().int().min(0).max(5).default(0),
dueDate: z.date().optional(),
tags: z.array(z.string()).optional(),
});
export const tasksRouter = router({
create: protectedProcedure
.input(createTaskSchema)
.mutation(async ({ input }) => {
// input is fully typed and validated
// ...
}),
});
```
### Common Zod Patterns
```typescript theme={null}
// UUID validation
z.string().uuid();
// Email validation
z.string().email();
// URL validation
z.string().url();
// Enum
z.enum(['pending', 'in_progress', 'completed']);
// Date
z.date(); // or z.string().datetime() for ISO strings
// Optional with default
z.string().default('default-value');
// Nested objects
z.object({
user: z.object({
id: z.string().uuid(),
name: z.string(),
}),
});
// Arrays
z.array(z.string());
// Union types
z.union([z.string(), z.number()]);
// Transform
z.string().transform((val) => val.toLowerCase());
// Refine (custom validation)
z.string().refine((val) => val.includes('@'), {
message: 'Must be an email',
});
```
## Error Handling
### Throwing Errors
```typescript theme={null}
import { TRPCError } from '@trpc/server';
export const tasksRouter = router({
get: protectedProcedure
.input(z.object({ taskId: z.string().uuid() }))
.query(async ({ input }) => {
const supabase = createClient();
const { data, error } = await supabase
.from('workspace_tasks')
.select('*')
.eq('id', input.taskId)
.single();
if (error) {
throw new TRPCError({
code: 'NOT_FOUND',
message: `Task ${input.taskId} not found`,
cause: error,
});
}
return data;
}),
});
```
### Error Codes
* `BAD_REQUEST` - Invalid input
* `UNAUTHORIZED` - Not authenticated
* `FORBIDDEN` - Authenticated but not authorized
* `NOT_FOUND` - Resource not found
* `INTERNAL_SERVER_ERROR` - Server error
* `TIMEOUT` - Request timeout
* `CONFLICT` - Resource conflict
### Handling Errors Client-Side
```tsx theme={null}
'use client';
import { trpc } from '@/trpc/client';
export function TaskDetails({ taskId }: { taskId: string }) {
const { data, error } = trpc.tasks.get.useQuery({ taskId });
if (error) {
if (error.data?.code === 'NOT_FOUND') {
return
Task not found
;
}
if (error.data?.code === 'UNAUTHORIZED') {
return
Please log in
;
}
return
Error: {error.message}
;
}
return
{data?.name}
;
}
```
## React Query Integration
tRPC uses React Query under the hood. You have access to all React Query features:
### Query Options
```tsx theme={null}
const { data } = trpc.tasks.list.useQuery(
{ wsId },
{
staleTime: 5 * 60 * 1000, // 5 minutes
refetchOnWindowFocus: false,
retry: 3,
enabled: !!wsId, // Only run if wsId exists
}
);
```
### Optimistic Updates
```tsx theme={null}
const utils = trpc.useContext();
const updateTask = trpc.tasks.update.useMutation({
onMutate: async (newData) => {
// Cancel outgoing refetches
await utils.tasks.get.cancel({ taskId: newData.taskId });
// Snapshot previous value
const previous = utils.tasks.get.getData({ taskId: newData.taskId });
// Optimistically update
utils.tasks.get.setData({ taskId: newData.taskId }, (old) => ({
...old!,
...newData,
}));
return { previous };
},
onError: (err, newData, context) => {
// Rollback on error
if (context?.previous) {
utils.tasks.get.setData({ taskId: newData.taskId }, context.previous);
}
},
onSettled: (data, error, variables) => {
// Always refetch after error or success
utils.tasks.get.invalidate({ taskId: variables.taskId });
},
});
```
### Cache Invalidation
```tsx theme={null}
const utils = trpc.useContext();
// Invalidate specific query
utils.tasks.get.invalidate({ taskId: '123' });
// Invalidate all tasks.list queries
utils.tasks.list.invalidate();
// Invalidate all tasks queries
utils.tasks.invalidate();
// Reset to initial state
utils.tasks.list.reset({ wsId });
```
## Performance Best Practices
### 1. Use Query Keys Wisely
```typescript theme={null}
// ✅ Good: Specific query keys
trpc.tasks.list.useQuery({ wsId, listId, completed: false });
// ❌ Bad: Over-fetching
trpc.tasks.getAll.useQuery(); // Gets ALL tasks
```
### 2. Enable Request Batching
tRPC automatically batches requests made within 10ms:
```tsx theme={null}
// These three queries are sent in a single HTTP request
const tasks = trpc.tasks.list.useQuery({ wsId });
const boards = trpc.boards.list.useQuery({ wsId });
const members = trpc.workspace.members.useQuery({ wsId });
```
### 3. Use `staleTime` for Cacheable Data
```tsx theme={null}
// User profile rarely changes - cache for 10 minutes
const { data: profile } = trpc.user.profile.useQuery(undefined, {
staleTime: 10 * 60 * 1000,
});
```
### 4. Prefetch on Server
```tsx theme={null}
// app/workspace/[wsId]/tasks/page.tsx
import { HydrateClient } from '@/trpc/query';
import { createCaller } from '@/trpc/server';
export default async function TasksPage({
params,
}: {
params: { wsId: string };
}) {
const trpc = await createCaller();
const tasks = await trpc.tasks.list({ wsId: params.wsId });
return (
{/* Uses prefetched data */}
);
}
```
## Testing tRPC Procedures
```typescript theme={null}
// __tests__/tasks.test.ts
import { createCaller } from '@/trpc/server';
import { describe, expect, it } from 'vitest';
describe('tasks router', () => {
it('should create a task', async () => {
const trpc = await createCaller();
const task = await trpc.tasks.create({
wsId: 'test-workspace',
listId: 'test-list',
name: 'Test Task',
});
expect(task.name).toBe('Test Task');
expect(task.ws_id).toBe('test-workspace');
});
it('should throw on invalid input', async () => {
const trpc = await createCaller();
await expect(
trpc.tasks.create({
wsId: '',
listId: 'test-list',
name: '', // Invalid: empty name
})
).rejects.toThrow();
});
});
```
## Related Documentation
* [API Routes](/platform/architecture/api-routes) - REST API patterns
* [Data Fetching](/platform/architecture/data-fetching) - When to use tRPC vs other patterns
* [Authentication](/platform/architecture/authentication) - Auth middleware
* [Authorization](/platform/architecture/authorization) - Permission checking
## External Resources
* [tRPC Official Docs](https://trpc.io/)
* [Zod Documentation](https://zod.dev/)
* [React Query Docs](https://tanstack.com/query/latest)
# Analytics Dashboard
Source: https://docs.rmitnct.club/platform/features/command-center-dashboard
Comprehensive analytics and insights for club performance, finance tracking, and member engagement.
## Overview
The NCT Hub Analytics Dashboard provides core team members with comprehensive insights into club operations, financial performance, member engagement, and project progress. This centralized view helps club leadership make data-driven decisions and track key metrics.
## Key Dashboard Components
### **Financial Analytics**
* **Budget Tracking** – Monitor club expenses and revenue streams
* **Price Prediction Charts** – AI-powered forecasting for financial planning
* **Commodity Comparison** – Analyze spending patterns and cost optimization
* **Advanced Analytics** – Machine learning insights for financial decision-making
### **Member Engagement Metrics**
* **Active Member Tracking** – Monitor participation in events and activities
* **Project Contribution** – Track member involvement in club projects
* **Event Attendance** – Analyze participation patterns using scanner data
* **Growth Analytics** – Monitor new member acquisition and retention
### **Project Performance**
* **Project Status Tracking** – Monitor progress across all club initiatives
* **Completion Rates** – Track project delivery and success metrics
* **Resource Allocation** – Analyze time and resource distribution
* **Impact Measurement** – Assess project outcomes and community impact
### **Club Operations**
* **Event Analytics** – Track meet-together scheduling and attendance
* **Educational Progress** – Monitor learning module completion
* **Game Engagement** – Analyze Neo Chess and Neo Crush participation
* **Communication Metrics** – Track engagement across different channels
## Dashboard Features
### Real-time Updates
* Live data feeds from all platform components
* Automatic refresh of key metrics
* Real-time notifications for important events
### Customizable Views
* Role-based dashboard configurations
* Personalized metric displays
* Flexible date ranges and filtering options
### Export Capabilities
* PDF report generation
* Data export for external analysis
* Scheduled report delivery
## Usage Scenarios
### For Club Leadership
* Monitor overall club health and growth
* Track financial performance and budget adherence
* Identify areas for improvement and expansion
### For Department Heads
* Analyze department-specific metrics
* Track project progress and resource utilization
* Monitor team engagement and productivity
### For Event Organizers
* Track event attendance and feedback
* Analyze meet-together scheduling effectiveness
* Monitor member participation patterns
## Integration Points
The dashboard integrates with all major platform components:
* **Finance Module** – Real-time financial data and predictions
* **Member Management** – Engagement and activity metrics
* **Project Tracking** – Progress and completion analytics
* **Event Management** – Attendance and scheduling insights
* **Education Platform** – Learning progress and completion rates
## Related Resources
* [Platform Overview](/platform/index) – Understanding the complete platform architecture
* [Member Management](/platform/features/user-management) – Managing club members and roles
* [Finance Tracking](/platform/features/finance-tracking) – Detailed financial management features
# Meet Together
Source: https://docs.rmitnct.club/platform/features/meet-together
Event scheduling and coordination tool for NCT club meetings and activities.
## Overview
Meet Together is NCT Hub's event scheduling and coordination system that helps club members find optimal meeting times, coordinate events, and manage club activities efficiently.
## Key Features
### **Smart Scheduling**
* **Availability Polling** – Collect availability from multiple participants
* **Optimal Time Detection** – Automatically find the best meeting times
* **Recurring Events** – Set up regular club meetings and activities
* **Timezone Support** – Handle different timezones for international members
### **Event Coordination**
* **Member Invitations** – Send invites to club members and external participants
* **RSVP Management** – Track attendance confirmations
* **Event Details** – Comprehensive event information and agenda management
* **Reminder System** – Automated reminders for upcoming events
### **Club Integration**
* **Member Database** – Integration with club member management system
* **Event Categories** – Organize events by type (meetings, workshops, social events)
* **Attendance Tracking** – Link with student scanner for accurate attendance records
* **Calendar Sync** – Integration with personal and club calendars
## Usage Workflow
### Creating Events
1. **Set Event Details** – Define event name, description, and duration
2. **Select Participants** – Choose from club members or add external participants
3. **Define Time Options** – Specify available time slots and dates
4. **Send Invitations** – Distribute invites with automatic link generation
### Participant Experience
1. **Receive Invitation** – Get notified via email or platform notification
2. **View Event Details** – Access comprehensive event information
3. **Select Availability** – Mark preferred time slots and dates
4. **Confirm Attendance** – RSVP and receive calendar integration
### Organizer Management
1. **Monitor Responses** – Track participant availability and RSVPs
2. **Finalize Schedule** – Choose optimal time based on responses
3. **Send Confirmations** – Notify all participants of final schedule
4. **Track Attendance** – Use scanner integration for accurate records
## Advanced Features
### **Analytics & Reporting**
* **Attendance Analytics** – Track participation patterns and trends
* **Event Success Metrics** – Measure event effectiveness and engagement
* **Member Engagement** – Monitor member participation across events
* **Resource Planning** – Optimize resource allocation based on attendance
### **Automation**
* **Recurring Events** – Automatic scheduling for regular club activities
* **Template Management** – Save common event configurations
* **Bulk Operations** – Manage multiple events simultaneously
* **Integration Workflows** – Connect with other platform modules
## Integration Points
### Platform Connections
* **Member Management** – Direct integration with member database
* **Analytics Dashboard** – Event data feeds into club analytics
* **Scanner System** – Attendance tracking for accurate records
* **Calendar Module** – Synchronization with personal and club calendars
### External Integrations
* **Email Notifications** – Automated email reminders and updates
* **Calendar Apps** – Google Calendar, Outlook, and other calendar systems
* **Communication Tools** – Integration with club communication channels
## Best Practices
### Event Planning
* **Early Scheduling** – Create events well in advance for better participation
* **Clear Communication** – Provide detailed event descriptions and agendas
* **Follow-up** – Send reminders and confirmations at appropriate intervals
### Member Engagement
* **Inclusive Scheduling** – Consider different time zones and availability
* **Varied Event Types** – Mix formal meetings with social activities
* **Feedback Collection** – Gather input to improve future events
## Related Resources
* [Platform Overview](/platform/index) – Understanding the complete platform architecture
* [Member Management](/platform/features/user-management) – Managing club members and permissions
* [Analytics Dashboard](/platform/features/command-center-dashboard) – Tracking event analytics and insights
# Member Management
Source: https://docs.rmitnct.club/platform/features/user-management
Comprehensive member management system for NCT club members, roles, and permissions.
## Overview
The Member Management system is the core of NCT Hub's user administration, providing comprehensive tools for managing club members, their roles, permissions, and engagement across all platform features.
## Key Features
### **Member Profiles**
* **Complete Profiles** – Detailed member information including contact details, skills, and interests
* **Profile Pictures** – Avatar management and profile customization
* **Member Status** – Track active, inactive, and alumni members
* **Skill Tracking** – Monitor member expertise and development areas
### **Role & Permission Management**
* **Role Hierarchy** – Define different member roles (Core Team, Department Heads, Regular Members)
* **Permission System** – Granular access control for different platform features
* **Department Assignment** – Organize members by departments (Tech, Finance, HR, Marketing)
* **Custom Permissions** – Flexible permission assignment for specific needs
### **Member Analytics**
* **Engagement Tracking** – Monitor member participation in events and projects
* **Activity Metrics** – Track platform usage and contribution patterns
* **Growth Analytics** – Monitor new member acquisition and retention rates
* **Performance Insights** – Analyze member contributions and achievements
## Member Lifecycle Management
### Onboarding Process
1. **Registration** – New member sign-up and profile creation
2. **Verification** – Email verification and profile completion
3. **Role Assignment** – Initial role assignment based on department and skills
4. **Orientation** – Access to onboarding materials and platform introduction
### Active Member Management
* **Profile Updates** – Regular profile maintenance and skill updates
* **Role Changes** – Dynamic role adjustments based on responsibilities
* **Permission Updates** – Access control modifications as needed
* **Engagement Monitoring** – Track participation and contribution levels
### Alumni Management
* **Status Transition** – Move graduated members to alumni status
* **Access Retention** – Maintain limited access for alumni engagement
* **Network Maintenance** – Keep connections for mentorship and networking
## Department Structure
### Technology Department
* **Software Development** – Full-stack developers, mobile developers
* **DevOps & Infrastructure** – System administrators, deployment specialists
* **AI/ML Specialists** – Machine learning engineers, data scientists
* **UI/UX Designers** – User interface and experience designers
### Finance & Logistics Department
* **Financial Management** – Budget tracking, expense management
* **Event Planning** – Logistics coordination, resource allocation
* **Vendor Relations** – External partner management
* **Inventory Management** – Asset tracking and procurement
### Human Resources Department
* **Recruitment** – New member acquisition and onboarding
* **Member Relations** – Conflict resolution, member support
* **Training & Development** – Skill development programs
* **Performance Management** – Member evaluation and feedback
### Marketing & Communications Department
* **Content Creation** – Social media, blog posts, promotional materials
* **Event Promotion** – Marketing campaigns and outreach
* **Brand Management** – Club identity and public relations
* **Community Engagement** – External community building
## Permission System
### Platform Access Levels
* **Public Access** – Landing page, project showcase, general information
* **Member Access** – Basic member features, event participation, games
* **Core Team Access** – Advanced analytics, member management, project oversight
* **Admin Access** – Full platform control, system configuration, user administration
### Feature-Specific Permissions
* **Analytics Dashboard** – View and export permissions
* **Member Management** – Add, edit, and remove member permissions
* **Event Management** – Create, modify, and manage events
* **Project Management** – Project creation and oversight permissions
* **Financial Management** – Budget and expense management access
## Integration Features
### Platform Connections
* **Analytics Dashboard** – Member data feeds into engagement metrics
* **Event Management** – Member participation in events and activities
* **Project Tracking** – Member contributions to club projects
* **Education Platform** – Learning progress and skill development tracking
### External Integrations
* **Email System** – Automated notifications and communications
* **Calendar Integration** – Member schedule and availability tracking
* **Communication Tools** – Slack, Discord, and other communication platforms
* **Social Media** – Member social media profile integration
## Member Engagement Tools
### Communication Features
* **Direct Messaging** – Internal messaging system for member communication
* **Announcements** – Club-wide notifications and updates
* **Discussion Forums** – Topic-based member discussions
* **Feedback System** – Member feedback collection and response
### Recognition System
* **Achievement Badges** – Recognition for member contributions
* **Leaderboards** – Gamified engagement tracking
* **Certificates** – Completion certificates for training and projects
* **Spotlight Features** – Highlighting member achievements and contributions
## Best Practices
### Member Onboarding
* **Clear Documentation** – Comprehensive onboarding guides and resources
* **Mentorship Program** – Pair new members with experienced mentors
* **Gradual Access** – Phased introduction to platform features
* **Regular Check-ins** – Scheduled follow-ups during onboarding period
### Ongoing Management
* **Regular Updates** – Keep member profiles and information current
* **Performance Reviews** – Regular evaluation of member contributions
* **Skill Development** – Provide opportunities for member growth
* **Community Building** – Foster connections between members
## Related Resources
* [Platform Overview](/platform/index) – Understanding the complete platform architecture
* [Analytics Dashboard](/platform/features/command-center-dashboard) – Member engagement analytics
* [Meet Together](/platform/features/meet-together) – Event management and member participation
* [Workspace Settings](/platform/workspace-routing) – Platform configuration and administration
# NCT Hub Platform Overview
Source: https://docs.rmitnct.club/platform/index
How NCT Hub combines club management, AI systems, education tools, and project tracking into a unified platform.
The NCT Hub platform serves as the central digital ecosystem for RMIT Neo Culture Tech, combining club management, AI-powered tools, educational resources, and project tracking into a unified experience. This platform supports both public visitors exploring our club and core team members managing operations.
## Platform Architecture
NCT Hub is built on a modern tech stack including Next.js, TypeScript, Supabase, and Turborepo, providing a scalable foundation for our growing community needs.
## Core Platform Features
### 🏢 **Club Management**
* **Member Management** – Complete user profiles, roles, and permissions system
* **Event Organization** – Meet Together scheduling and coordination tools
* **Student Scanner** – QR code-based attendance tracking for events
* **Project Showcase** – Public portfolio of club projects and achievements
### **AI & Automation**
* **AI Chat System** – Intelligent assistants for various tasks
* **Data Crawlers** – Automated content collection and processing
* **Model Management** – AI model deployment and monitoring
* **Pipeline Automation** – Workflow automation for repetitive tasks
### **Education & Learning**
* **Educational Modules** – Structured learning content and courses
* **Document Management** – Centralized document storage and sharing
* **Reading Lists** – Curated educational resources
* **Progress Tracking** – Monitor learning achievements and milestones
### **Analytics & Finance**
* **Dashboard Analytics** – Comprehensive club performance metrics
* **Financial Tracking** – Budget management and expense monitoring
* **Price Prediction** – AI-powered forecasting tools
* **Advanced Analytics** – Machine learning insights and reporting
### **Interactive Features**
* **Neo Chess** – Multiplayer chess game with AI opponents
* **Neo Crush** – Real-time multiplayer puzzle game
* **Time Tracking** – Productivity and project time management
* **Calendar Integration** – Schedule management and coordination
## How It All Fits Together
```mermaid theme={null}
flowchart TB
subgraph "Public Layer"
Landing["Landing Page"]
Projects["Project Showcase"]
About["About Us"]
Games["Neo Games"]
end
subgraph "Member Dashboard"
Dashboard["Analytics Dashboard"]
Tasks["Task Management"]
Calendar["Calendar & Events"]
Finance["Finance Tracking"]
end
subgraph "AI & Automation"
Chat["AI Chat System"]
Crawlers["Data Crawlers"]
Models["AI Models"]
Pipelines["Automation Pipelines"]
end
subgraph "Education"
Modules["Learning Modules"]
Documents["Document Hub"]
Progress["Progress Tracking"]
Resources["Resource Library"]
end
subgraph "Management"
Members["Member Management"]
Events["Event Organization"]
Scanner["Attendance Scanner"]
Settings["Workspace Settings"]
end
Landing --> Dashboard
Dashboard --> Chat
Chat --> Modules
Modules --> Members
Members --> Events
Events --> Scanner
Scanner --> Finance
Finance --> Dashboard
```
## Key Integrations
* **Supabase** – Database, authentication, and real-time features
* **GitHub** – Project repositories and version control
* **Vercel** – Deployment and hosting infrastructure
* **External APIs** – Google Calendar, email services, and more
## Next Steps
1. Explore the [Dashboard Features](/platform/features/command-center-dashboard) to understand the analytics system
2. Review [AI Integration](/platform/ai/structured-data) for automated workflows
3. Check out [Component Library](/platform/components/index) for UI patterns
4. Learn about [Workspace Routing](/platform/workspace-routing) for navigation
Ready to dive deeper? Explore our [Development Guide](/development) or check out our [Project Showcase](/projects).
# Language
Source: https://docs.rmitnct.club/platform/personalization/language
Enhance your experience with themes.
## Usage
Language helps you view everything on [NCT Hub](https://rmitnct.club) in your preferred language.
### Supported Languages
Currently, we provide first-class support for the following languages:
* **English**
* **Vietnamese**
### How to Change Language
[NCT Hub](https://rmitnct.club) will automatically detect your browser's language and set the language accordingly. If you want to change the language, you can do so by clicking on the language switcher in your profile avatar (located at the top right corner of the page).
The language switcher is only available after you have logged in.
### Contribute
If you want to help us translate [NCT Hub](https://rmitnct.club) into your language, feel free to open a pull request on our [GitHub repository](https://github.com/rmit-nct/hub) that contains the translation files for the language you want to contribute (e.g., `apps/web/locales/en/*.json` for English).
# Themes
Source: https://docs.rmitnct.club/platform/personalization/themes
Enhance your experience with themes.
## Usage
Themes are a way to customize the look and feel of your experience on [NCT Hub](https://rmitnct.club). You can choose from a variety of themes to suit your preferences.
### Modes
Modes are how the entire website looks. You can choose between **light mode**, **dark mode**, and **system mode** (which follows your system settings).
### Basic theme switcher
When you are not logged in, a basic theme switcher will be available which will allow you to switch between standard **dark mode** and **light mode** by clicking on the theme switcher in the top right corner of our website.
### Advanced theme switcher
You can switch between a variety of themes by tapping on your profile picture in the top right corner of our website and selecting the **Theme** option.
This switcher is will available when you are logged in.
#### Variants
When using **Advanced theme switcher**, you can also choose a variant of the selected mode.
For example, you can choose dark mode with a blue accent.
Available variants:
* **Standard** (Default)
* **Pink**
* **Purple**
* **Yellow**
* **Orange**
* **Green**
* **Blue**
# Workspace ID Routing System
Source: https://docs.rmitnct.club/platform/workspace-routing
Comprehensive documentation of the workspace ID routing system, middleware handling, and URL patterns
The workspace ID routing system provides a flexible and consistent way to handle workspace-scoped routes across the platform. This system supports multiple workspace identifier formats, automatic resolution, and intelligent middleware-based routing.
## Overview
The workspace routing system consists of several key components:
1. **URL Pattern**: `[locale]/(dashboard)/[wsId]/*`
2. **Middleware**: Handles workspace ID resolution and redirects
3. **WorkspaceWrapper**: React component for workspace validation and context
4. **API Routes**: `[wsId]` parameter for workspace-scoped API endpoints
## Workspace Identifier Types
The system supports multiple workspace identifier formats that are automatically resolved:
### 1. UUID Format
Standard UUID workspace identifiers:
```
550e8400-e29b-41d4-a716-446655440000
```
### 2. Personal Workspace
The special identifier `'personal'` resolves to the user's personal workspace:
```
personal
```
### 3. Internal Workspace
The special identifier `'internal'` resolves to the root workspace (system workspace):
```
internal
```
## URL Patterns
### User-Facing URLs
The actual URLs users see in their browser are clean and simple:
```
/[wsId]/...
```
**Examples (what users see and type in browser):**
* `/personal/dashboard` → Personal workspace dashboard
* `/550e8400-e29b-41d4-a716-446655440000/tasks` → Specific workspace tasks
* `/internal/settings` → Internal workspace settings
**Note**: Even if a user types `/en/personal/dashboard`, the middleware automatically normalizes this to `/personal/dashboard` for a cleaner URL experience.
### File Structure vs. URLs
The file structure uses `[locale]/(dashboard)/[wsId]/...` but both locale and route groups are implementation details:
* **File structure**: `apps/web/src/app/[locale]/(dashboard)/[wsId]/...`
* **Browser URL**: `/[wsId]/...` (both locale and route group handled transparently)
* **URL normalization**: `/en/personal/dashboard` becomes `/personal/dashboard` in browser
### How It Works
1. User visits `/[wsId]/...` in browser (this is what they see and type)
2. Middleware detects locale from cookie/browser preferences
3. Next.js internally routes to `[locale]/(dashboard)/[wsId]/...` file structure
4. Middleware normalizes `/en/[wsId]/...` → `/[wsId]/...` (transparent to user)
### API Routes
API routes follow the same clean URL pattern:
```
api/[wsId]/...
```
**Examples (what API clients request):**
* `/api/550e8400-e29b-41d4-a716-446655440000/task/create`
* `/api/personal/calendar/auto-schedule`
* `/api/internal/workspace-settings`
## Middleware Implementation
The middleware in `apps/web/src/middleware.ts` handles workspace routing with the following logic:
### 1. UUID Validation
```typescript theme={null}
const uuidRegex =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
```
### 2. Path Analysis
The middleware analyzes the URL path to identify:
* Presence of locale prefix
* Position of workspace ID in path
* Whether it's a special workspace identifier
### 3. Root Workspace Remapping
```typescript theme={null}
// Remap root workspace URL to the internal workspace slug for consistency
if (potentialWorkspaceId === ROOT_WORKSPACE_ID) {
const wsIdIndex = hasLocaleInPath ? 1 : 0;
const newPathSegments = [...pathSegments];
if (newPathSegments[wsIdIndex] !== 'internal') {
newPathSegments[wsIdIndex] = 'internal';
const redirectUrl = new URL(`/${newPathSegments.join('/')}`, req.nextUrl);
redirectUrl.search = req.nextUrl.search;
return NextResponse.redirect(redirectUrl);
}
}
```
### 4. Personal Workspace Detection
```typescript theme={null}
// If we found a potential workspace ID, check if it's a personal workspace
if (potentialWorkspaceId) {
try {
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
if (user) {
const isPersonal = await isPersonalWorkspace(potentialWorkspaceId);
if (isPersonal) {
// Construct the redirect URL replacing the workspace ID with 'personal'
const newPathSegments = [...pathSegments];
const wsIdIndex = hasLocaleInPath ? 1 : 0;
newPathSegments[wsIdIndex] = 'personal';
const redirectUrl = new URL(`/${newPathSegments.join('/')}`, req.nextUrl);
redirectUrl.search = req.nextUrl.search;
return NextResponse.redirect(redirectUrl);
}
}
} catch (error) {
console.error('Error checking personal workspace in middleware:', error);
}
}
```
### 5. Default Workspace Redirect
For authenticated users accessing root paths, the middleware automatically redirects to their default workspace:
```typescript theme={null}
// Handle authenticated users accessing the root path or root with locale
if (isRootPath || isLocaleRootPath) {
try {
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
if (user) {
const defaultWorkspace = await getUserDefaultWorkspace();
if (defaultWorkspace) {
const target = defaultWorkspace.personal
? 'personal'
: defaultWorkspace.id === ROOT_WORKSPACE_ID
? 'internal'
: defaultWorkspace.id;
const redirectUrl = new URL(`/${target}`, req.nextUrl);
return NextResponse.redirect(redirectUrl);
}
}
} catch (error) {
console.error('Error handling root path redirect:', error);
}
}
```
## WorkspaceWrapper Component
The `WorkspaceWrapper` component provides a standardized way to handle workspace ID resolution and validation:
### Basic Usage
```tsx theme={null}
import WorkspaceWrapper from '@/components/workspace-wrapper';
export default async function MyPage({
params,
}: {
params: Promise<{ wsId: string }>;
}) {
return (
{({ workspace, wsId, isPersonal, isRoot }) => (
{workspace.name}
Workspace UUID: {wsId}
Is Personal: {isPersonal ? 'Yes' : 'No'}
Is Root: {isRoot ? 'Yes' : 'No'}
)}
);
}
```
### Component API
```typescript theme={null}
interface WorkspaceWrapperProps {
params: Promise;
children: (
props: {
workspace: Workspace & { role: WorkspaceUserRole; joined: boolean };
wsId: string; // The validated UUID from workspace.id
isPersonal: boolean;
isRoot: boolean;
// Additional params from the original params object
} & Omit
) => ReactNode;
fallback?: ReactNode;
}
```
### Features
* **Automatic Resolution**: Converts legacy identifiers to validated UUIDs
* **Type Safety**: Provides fully typed workspace objects
* **Error Handling**: Automatically calls `notFound()` for invalid workspaces
* **Loading States**: Built-in Suspense support
* **Role Validation**: Includes user role and membership status
## API Routes with \[wsId]
API routes use the `[wsId]` parameter to scope operations to specific workspaces:
### Route Structure
```
app/api/[wsId]/
├── calendar/
│ └── auto-schedule/
│ └── route.ts
├── crawlers/
│ ├── domains/
│ ├── list/
│ └── uncrawled/
├── task/
│ └── [taskId]/
│ └── edit/
```
### Implementation Pattern
```typescript theme={null}
// apps/web/src/app/api/[wsId]/task/create/route.ts
import { createClient } from '@ncthub/supabase/next/server';
import { NextRequest, NextResponse } from 'next/server';
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ wsId: string }> }
) {
const { wsId } = await params;
const supabase = await createClient();
// wsId is automatically validated by middleware
// Use wsId in your database queries
const { data, error } = await supabase
.from('tasks')
.insert({ ...taskData, ws_id: wsId });
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json(data);
}
```
### Security Considerations
* **Authentication**: All workspace-scoped routes require authentication
* **Authorization**: Use `getPermissions()` to check workspace access
* **Validation**: Workspace ID is validated before reaching API handlers
## Helper Functions
### Workspace Resolution
```typescript theme={null}
import { resolveWorkspaceId, toWorkspaceSlug } from '@ncthub/utils/constants';
// Convert identifier to UUID
const uuid = resolveWorkspaceId('personal'); // Returns user's personal workspace UUID
const uuid = resolveWorkspaceId('internal'); // Returns ROOT_WORKSPACE_ID
const uuid = resolveWorkspaceId('550e8400-e29b-41d4-a716-446655440000'); // Returns UUID as-is
// Convert UUID to slug
const slug = toWorkspaceSlug(workspaceId, { personal: true }); // Returns 'personal'
const slug = toWorkspaceSlug(ROOT_WORKSPACE_ID); // Returns 'internal'
```
### Workspace Validation
```typescript theme={null}
import { isPersonalWorkspace } from '@ncthub/utils/workspace-helper';
// Check if workspace is personal
const isPersonal = await isPersonalWorkspace('personal'); // true
const isPersonal = await isPersonalWorkspace('550e8400-e29b-41d4-a716-446655440000'); // boolean
```
### User Default Workspace
```typescript theme={null}
import { getUserDefaultWorkspace } from '@ncthub/utils/user-helper';
// Get user's default workspace
const defaultWorkspace = await getUserDefaultWorkspace();
if (defaultWorkspace) {
const target = defaultWorkspace.personal ? 'personal' : defaultWorkspace.id;
}
```
## Constants
### Key Constants
```typescript theme={null}
// Root workspace ID (system workspace)
export const ROOT_WORKSPACE_ID = '00000000-0000-0000-0000-000000000000';
// Workspace slugs
export const INTERNAL_WORKSPACE_SLUG = 'internal';
export const PERSONAL_WORKSPACE_SLUG = 'personal';
```
## Error Handling
The workspace routing system includes comprehensive error handling:
### Invalid Workspace ID
* Returns `404 Not Found` for non-existent workspaces
* Redirects to login for unauthenticated users
### Permission Errors
* Returns `404 Not Found` for workspaces user doesn't have access to
* Use `getPermissions()` for fine-grained access control
### Middleware Errors
* Gracefully handles database connection errors
* Continues with normal flow if workspace checks fail
## Performance Considerations
### Middleware Performance
* Workspace validation happens at the edge
* Database queries are optimized with single queries
* Caching is handled by Supabase client
### Component Performance
* WorkspaceWrapper uses React Suspense for loading states
* Workspace data is fetched once and passed to children
* Consider using `fallback` prop for better UX
## Migration Guide
### Legacy URL Handling
The system automatically handles legacy workspace URLs:
* `/workspaces/550e8400-e29b-41d4-a716-446655440000` → `/550e8400-e29b-41d4-a716-446655440000`
* `/personal` → `/personal` (already correct)
* `/internal` → `/internal` (already correct)
### Component Migration
Replace manual workspace resolution with WorkspaceWrapper:
```tsx theme={null}
// Before
const { wsId: id } = await params;
const workspace = await getWorkspace(id);
if (!workspace) notFound();
// After
{({ workspace, wsId }) => (
// Use workspace and wsId safely
)}
```
## Testing
### Middleware Testing
Test workspace routing with different identifier types:
```typescript theme={null}
// Test UUID routing (what users actually request)
GET /550e8400-e29b-41d4-a716-446655440000/dashboard
// Test personal workspace
GET /personal/dashboard
// Test internal workspace
GET /internal/dashboard
// Note: /en/[wsId]/... URLs are automatically normalized to /[wsId]/...
// by Next.js middleware while maintaining i18n support
```
### Component Testing
Test WorkspaceWrapper with different scenarios:
```tsx theme={null}
// Test with valid workspace
const params = Promise.resolve({ wsId: '550e8400-e29b-41d4-a716-446655440000' });
// Test with personal workspace
const params = Promise.resolve({ wsId: 'personal' });
// Test with invalid workspace
const params = Promise.resolve({ wsId: 'invalid-id' });
```
## Troubleshooting
### Common Issues
**Issue**: Workspace not found errors
**Solution**: Verify the workspace ID is valid and user has access
**Issue**: Personal workspace redirects incorrectly
**Solution**: Check that user has a personal workspace configured
**Issue**: Internal workspace access denied
**Solution**: Ensure user has admin/owner role in root workspace
### Debug Tips
1. Check browser Network tab for failed workspace requests
2. Verify workspace ID in URL is correct
3. Ensure user is authenticated and has workspace access
4. Check console for middleware error messages
## Security
### Authentication
All workspace-scoped routes require authentication. Unauthenticated requests are redirected to login.
### Authorization
* Personal workspaces are only accessible to their owners
* Internal workspace requires admin/owner permissions
* Regular workspaces require membership
### Data Isolation
Each workspace's data is properly isolated through:
* Database-level row-level security
* API route parameter validation
* Middleware workspace ID validation
## Future Enhancements
### Potential Improvements
* Workspace invitation flow via URL parameters
* Workspace-specific feature flags
* Enhanced caching for workspace metadata
* Workspace-specific theming and branding
### Breaking Changes
Any changes to workspace identifier formats or URL patterns should be:
* Clearly documented in release notes
* Include migration guides for existing URLs
* Provide backward compatibility where possible