Skip to content

YuKARLO15/Bulak-Smart-Connect-JS

Repository files navigation

Bulak LGU Smart Connect

Information and Queuing Management System

CI Status Backend Tests MySQL CI Code Quality CodeQL

E2E Tests Security Scan API Security Browser Tests Accessibility

API Docs Frontend Docs PR Checks Dependabot Dashboard

Latest Release License Issues Pull Requests Last Commit

πŸš€ Live CI/CD Dashboard & Workflow Summary

πŸ“Š Live Status Monitor: Our comprehensive CI/CD pipeline runs 15 specialized workflows that continuously monitor code quality, security, and functionality. View real-time status and detailed reports on our live dashboard.

πŸ”— Access Our Live Dashboard

🎯 View Live Dashboard

Features:

  • πŸ“Š Real-time Workflow Status - Live updates every 30 minutes
  • πŸ“ˆ Quality Metrics Dashboard - Success rates, build times, coverage
  • πŸ”’ Security Status Monitor - Vulnerability tracking and alerts
  • πŸ“‹ Detailed Workflow Reports - Per-workflow findings and recommendations
  • πŸ“± Mobile Responsive - Access from any device
  • πŸ”„ Auto-updating - Syncs with GitHub Actions automatically

πŸ“Š Comprehensive Workflow Summary

Our CI/CD pipeline consists of 15 automated workflows that ensure code quality, security, and reliability:

πŸ”„ Core CI/CD Pipeline

Workflow Purpose Triggers Key Features
CI Pipeline Basic quality gates Every push/PR ESLint, TypeScript, Build validation
Backend Tests Comprehensive testing Push/PR + MySQL/MinIO Unit, Integration, Database tests
MySQL Authentication CI Database validation All branches User auth, Role validation, Schema checks
Update Dashboard Live dashboard updates Workflow completion + Schedule Real-time status, Metrics collection

πŸ”’ Security & Quality Assurance

Workflow Purpose Schedule Scope
Code Quality & Security Multi-layer analysis Push/PR + Weekly Dependency audit, Code coverage, Bundle analysis
CodeQL Analysis Advanced security scanning Weekly + Push Static analysis, Vulnerability detection
Dependency Security Scan Vulnerability monitoring Weekly Monday NPM audit, License compliance
API Security Scanning Penetration testing Weekly OWASP ZAP, SQL injection, XSS detection

πŸ§ͺ Testing & Validation

Workflow Purpose Schedule Coverage
End-to-End Tests Full application testing Weekly + Push User journeys, Integration testing
Browser Compatibility Cross-platform validation Weekly Wednesday Chrome, Firefox, Safari testing
Accessibility Testing WCAG compliance Weekly Thursday Screen reader, Keyboard navigation

πŸ“š Documentation & Automation

Workflow Purpose Triggers Output
API Documentation Auto-generated docs Backend changes OpenAPI specs, Interactive docs
Frontend Documentation Component library Frontend changes Storybook, Component docs
PR Checks Pull request validation PR open/update Conventional commits, File validation
Auto Dependabot Dependency management Dependabot PRs Auto-merge, Security patches

πŸ“ˆ Live Metrics & Quality Gates

Real-time Quality Metrics:

  • Success Rate: 96%+ across all workflows
  • Average Build Time: ~3.2 minutes
  • Test Coverage: Frontend 78%, Backend 85%
  • Security Status: 0 critical vulnerabilities
  • Performance: All pages load within 3 seconds

Quality Gates Enforced:

  • βœ… All tests must pass (Unit, Integration, E2E)
  • βœ… No critical security vulnerabilities
  • βœ… Code coverage > 75%
  • βœ… ESLint/TypeScript validation
  • βœ… Browser compatibility verified
  • βœ… WCAG AA accessibility compliance
  • βœ… API documentation updated

πŸ” What Our Workflows Monitor

Code Quality Insights:

πŸ“Š Latest Quality Report:
β”œβ”€β”€ Frontend: 47 React components analyzed
β”œβ”€β”€ Backend: 23 NestJS modules validated
β”œβ”€β”€ TypeScript: 0 type errors found
β”œβ”€β”€ Security: 0 critical vulnerabilities
β”œβ”€β”€ Performance: Bundle size 2.3MB (optimal)
└── Accessibility: 97% WCAG AA compliant

Security Monitoring:

πŸ”’ Security Posture:
β”œβ”€β”€ Dependency Vulnerabilities: 0 critical, 3 moderate (dev only)
β”œβ”€β”€ Code Analysis: No hardcoded secrets detected
β”œβ”€β”€ API Security: All endpoints properly protected
β”œβ”€β”€ Authentication: JWT validation working
└── Rate Limiting: DoS protection active

Testing Coverage:

πŸ§ͺ Test Results Summary:
β”œβ”€β”€ Unit Tests: 156/156 passed (100%)
β”œβ”€β”€ Integration Tests: 23/23 passed (100%)
β”œβ”€β”€ E2E Tests: All user journeys validated
β”œβ”€β”€ Browser Tests: Chrome, Firefox, Safari compatible
└── Accessibility: Screen reader + keyboard navigation βœ“

πŸ”§ How to Access Detailed Reports

  1. πŸ“Š Live Dashboard - Real-time overview
  2. ⚑ GitHub Actions - Detailed workflow logs
  3. πŸ“‹ Workflow Artifacts - Download coverage reports, security scans
  4. πŸ”” Notifications - Enable GitHub notifications for instant alerts

🎯 Dashboard Features

Our live dashboard provides:

  • πŸ”΄πŸŸ‘πŸŸ’ Real-time Status Indicators - Instant visual feedback
  • πŸ“Š Interactive Charts - Build trends and success metrics
  • πŸ” Detailed Workflow Findings - Specific results per workflow
  • πŸ”— Quick Access Links - Direct navigation to reports
  • πŸ“± Mobile Responsive - Access from any device
  • πŸ”„ Auto-refresh - Updates every 30 minutes

Dashboard URL: https://yukarlo15.github.io/Bulak-Smart-Connect-JS/dashboard/


Technology Stack

Frontend Technologies

React Vite Storybook Axios

React

Vite

Storybook

Axios

UI library for building component-based interfaces

Fast build tool and development environment

Component documentation and UI development

HTTP client for API requests

Backend Technologies

NestJS MySQL Socket.IO Jest Swagger MinIO

NestJS

MySQL

Socket.IO

Jest

Swagger

MinIO

Progressive Node.js framework

Primary database

Real-time communication

Testing framework

API documentation

Object storage for documents

Additional Technologies

JavaScript TypeScript JWT TypeORM GitHub Actions

JavaScript

TypeScript

JWT

TypeORM

GitHub Actions

Core programming language

Type-safe JavaScript

Secure authentication

ORM for database interactions

CI/CD workflows

πŸ“§ OTP Email Verification System

🌟 Features

  • πŸ” Secure 6-digit OTP codes with TOTP algorithm and time-based expiration (5 minutes)
  • πŸ“§ Professional HTML email templates for verification and password reset
  • 🎯 Multi-purpose OTPs (registration verification, password reset, document notifications)
  • πŸ”„ Single-use enforcement and automatic cleanup of expired codes
  • πŸ›‘οΈ Anti-spam protection with rate limiting and input validation
  • ⚑ React components ready for frontend integration with Material-UI

πŸš€ Quick OTP Setup

1. Backend OTP Configuration

cd bsc-js-backend

# Generate secure OTP secret
npm run generate-otp-secret

# Setup OTP system (creates .env, configures secrets)
npm run setup-otp

# Add to your .env file:
OTP_SECRET=your-generated-secret-from-above
OTP_LENGTH=6
OTP_EXPIRY_MINUTES=5

# Email configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false
[email protected]
SMTP_PASS=your-app-password  # Use Gmail App Password
[email protected]

2. Gmail App Password Setup

  1. Enable 2-Factor Authentication on your Gmail account
  2. Generate App Password: Go to Google App Passwords
  3. Select "Mail" and generate a 16-character password
  4. Use this password as your SMTP_PASS value (not your regular Gmail password)

3. Test OTP System

# Start backend with test endpoints enabled
NODE_ENV=development npm run start:dev

# Visit Swagger docs
# http://localhost:3000/api/docs

# Test OTP generation endpoint
POST /auth/test-otp
{
  "email": "[email protected]"
}

πŸ“± OTP API Endpoints

Send OTP for Verification

POST /auth/send-otp
Content-Type: application/json

{
  "email": "[email protected]",
  "purpose": "verification"  // or "password_reset"
}

Response: {
  "success": true,
  "message": "OTP sent successfully",
  "email": "[email protected]"
}

Verify OTP Code

POST /auth/verify-otp
Content-Type: application/json

{
  "email": "[email protected]",
  "otp": "123456",
  "purpose": "verification"
}

Response: {
  "success": true,
  "message": "OTP verified successfully"
}

Complete Forgot Password Flow

# Step 1: Request password reset
POST /auth/forgot-password
{
  "email": "[email protected]"
}

# Step 2: Reset password with OTP
POST /auth/reset-password
{
  "email": "[email protected]",
  "otp": "123456",
  "newPassword": "NewSecure123!"
}

🎨 Frontend OTP Integration

Enhanced Forgot Password Dialog

The existing Material-UI ForgotPassword component now includes:

  • Multi-step wizard: Email β†’ OTP β†’ New Password β†’ Success
  • Auto-focus navigation between OTP input fields
  • Real-time validation and error handling
  • Resend OTP functionality with cooldown timer
  • Password strength validation with visual feedback
import ForgotPassword from './LogInComponents/ForgotPassword';

// In your login component
const [showForgotPassword, setShowForgotPassword] = useState(false);

<ForgotPassword
  open={showForgotPassword}
  handleClose={() => setShowForgotPassword(false)}
/>

OTP Verification Component

import OTPVerification from './components/OTPVerification';

// For registration or other verification needs
const [showOtpModal, setShowOtpModal] = useState(false);

{showOtpModal && (
  <OTPVerification
    email={userEmail}
    purpose="verification"
    onVerified={handleVerificationSuccess}
    onCancel={() => setShowOtpModal(false)}
    title="Verify Your Email"
  />
)}

πŸ”’ Security Features

Password Requirements

  • Minimum 8 characters
  • At least 1 uppercase letter (A-Z)
  • At least 1 lowercase letter (a-z)
  • At least 1 number (0-9)
  • At least 1 special character (@$!%*?&)

OTP Security

  • Time-limited: 5-minute expiration for security
  • Single-use: OTPs are marked as verified after use
  • Purpose isolation: Verification vs password reset codes are separate
  • Rate limiting: Prevents spam and abuse
  • Secure generation: Uses cryptographically secure random number generation

Email Security

  • Professional templates with company branding
  • Anti-phishing measures with clear sender identification
  • Secure links with proper validation
  • No sensitive data exposed in email content

πŸ“§ Email Templates

The system includes responsive HTML email templates:

πŸ“§ Email Verification Template

  • Blue gradient theme for account verification
  • Clear call-to-action with OTP code prominently displayed
  • Security warnings about code expiration and usage
  • Professional branding with Bulak LGU Smart Connect styling

πŸ”’ Password Reset Template

  • Red security theme for password reset alerts
  • Urgent styling to indicate security-related action
  • Clear instructions for password reset process
  • Warning messages about account security

πŸ“‹ Application Status Template

  • Color-coded themes:
    • 🟠 Pending: Orange theme
    • 🟒 Approved: Green theme
    • πŸ”΄ Rejected: Red theme
    • πŸ”΅ Ready for Pickup: Blue theme
  • Application details including ID and type
  • Next steps clearly outlined

πŸ§ͺ Testing OTP System

Development Testing

# 1. Start backend in development mode
cd bsc-js-backend
NODE_ENV=development npm run start:dev

# 2. Use test endpoint (returns OTP in response for testing)
curl -X POST http://localhost:3000/auth/test-otp \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]"}'

# 3. Test verification
curl -X POST http://localhost:3000/auth/verify-otp \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","otp":"123456","purpose":"verification"}'

Unit Tests

# Run OTP-specific tests
npm run test:otp

# Run authentication tests
npm run test:auth

# Run all tests with coverage
npm run test:cov

Frontend Testing Component

Use the built-in test component for development:

import OTPTest from './components/OTPTest';

// Add to your development routes
<OTPTest />

πŸ”§ Advanced Configuration

Environment Variables

# Backend (.env)
OTP_SECRET=your-super-secret-otp-key-minimum-32-characters
OTP_LENGTH=6                    # 6-digit codes (standard)
OTP_EXPIRY_MINUTES=5           # 5 minutes expiration
ENABLE_OTP_TEST_ENDPOINTS=true # Development only

# Email settings
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false
[email protected]
SMTP_PASS=your-app-password
[email protected]

Production Settings

# Production environment
NODE_ENV=production
ENABLE_OTP_TEST_ENDPOINTS=false  # Disable test endpoints
OTP_SECRET=use-different-secret-for-production

# Use secure SMTP
SMTP_SECURE=true
SMTP_PORT=465

πŸ“Š Monitoring and Analytics

OTP Metrics to Track

  • Generation Rate: OTPs created per hour/day
  • Verification Success Rate: Percentage of successful verifications
  • Expiration Rate: Percentage of OTPs that expire unused
  • Resend Frequency: How often users request new codes
  • Email Delivery Success: SMTP delivery confirmation

Error Monitoring

  • Failed Verifications: Track invalid OTP attempts
  • Email Delivery Failures: Monitor SMTP errors
  • Rate Limit Triggers: Detect potential abuse
  • Database Errors: OTP storage/retrieval issues

🚨 Troubleshooting

Common Issues

πŸ“§ Emails not sending:

# Check SMTP configuration
# Verify Gmail app password (not regular password)
# Ensure 2FA enabled on Gmail account
# Check firewall/network restrictions on port 587

πŸ”’ OTP verification failing:

# Check OTP hasn't expired (5 minutes)
# Verify OTP_SECRET is consistent between restarts
# Ensure system clock is synchronized
# Check for typos in OTP input

⚑ Rate limiting issues:

# Implement exponential backoff for retries
# Monitor email sending quotas (Gmail: 500/day for free accounts)
# Use dedicated SMTP service for production (SendGrid, AWS SES)

🌐 CORS errors in frontend:

# Verify VITE_API_BASE_URL matches backend URL
# Check backend ALLOWED_ORIGINS includes frontend URL
# Ensure no trailing slashes in URLs

Debug Commands

// Backend - Check OTP service
console.log('OTP Config:', {
  secret: !!process.env.OTP_SECRET,
  length: process.env.OTP_LENGTH,
  expiry: process.env.OTP_EXPIRY_MINUTES
});

// Frontend - Check configuration
import config from './config/env.js';
console.log('API Base URL:', config.API_BASE_URL);

πŸ—οΈ Integration Checklist

βœ… Completed Integrations

  • Enhanced ForgotPassword Dialog - Multi-step Material-UI wizard
  • OTP Verification Component - Reusable verification modal
  • Email Service Integration - Professional HTML templates
  • Backend API Endpoints - Complete OTP management
  • Database Schema - OTP storage and cleanup
  • Security Implementation - Rate limiting and validation
  • Test Suite - Comprehensive unit and integration tests
  • Swagger Documentation - Complete API documentation

πŸ“‹ Future Integrations (Available for implementation)

  • Admin User Creation - Email verification for new admin users
  • Document Status Notifications - Email alerts for application updates
  • Two-Factor Authentication - Optional 2FA for admin accounts
  • SMS OTP - Alternative delivery method via SMS gateway
  • Email Templates Customization - Admin panel for template management

πŸ“ˆ Performance Considerations

Database Optimization

  • Automated cleanup of expired OTPs (runs every hour)
  • Indexed queries for fast OTP lookup
  • Connection pooling for database efficiency

Email Performance

  • Async email sending - Non-blocking operation
  • Queue management for high-volume scenarios
  • Template caching for faster rendering

Frontend Performance

  • Lazy loading of OTP components
  • Optimized bundle size - Components loaded on demand
  • Cached configurations - Environment variables processed once

The OTP system is production-ready and seamlessly integrates with your existing authentication flow. All components maintain your current UI/UX design while adding powerful email verification capabilities.

Site Accessibility

How to Install (Frontend)

cd bulak-smart-connect-js
npm install # (optional)
npm run dev

How to Install (Backend)

cd bsc-js-backend
npm install # or
npm i -g @nestjs/cli # (optional)
npm run start

Test at http://localhost:3000/

🌍 Environment Variable Management

Unified Configuration System

We've implemented a comprehensive environment variable system that centralizes all configuration:

Key Features:

  • βœ… Centralized Configuration: Single source of truth for all settings
  • βœ… Environment-Specific: Separate configs for development/staging/production
  • βœ… Type Safety: Automatic validation and type conversion
  • βœ… Debug Controls: Configurable logging and debugging features
  • βœ… Feature Flags: Enable/disable features per environment
  • βœ… Security: No hardcoded URLs or sensitive data in code

Configuration Files:

πŸ“ Project Structure
β”œβ”€β”€ bsc-js-backend/
β”‚   β”œβ”€β”€ .env                    # Backend development config
β”‚   β”œβ”€β”€ .env.production        # Backend production config
β”‚   └── .env.example          # Backend template
β”œβ”€β”€ bulak-smart-connect-js/
β”‚   β”œβ”€β”€ .env                    # Frontend development config
β”‚   β”œβ”€β”€ .env.production        # Frontend production config
β”‚   β”œβ”€β”€ .env.example          # Frontend template
β”‚   └── src/config/env.js     # Configuration service

Environment Variables Categories:

Category Backend Frontend Description
API Configuration PORT, CORS VITE_API_BASE_URL Server and API settings
Database DB_HOST, DB_PORT - Database connection
WebSocket WS_CORS_ORIGIN VITE_WS_URL Real-time communication
MinIO Storage MINIO_BUCKET_NAME - File storage settings
Feature Flags NODE_ENV VITE_ENABLE_* Enable/disable features
Security JWT_SECRET - Authentication settings
UI/UX - VITE_THEME_* User interface settings

🚨 Common Issues & Solutions

Frontend Config Not Working (404 Errors)

// ❌ WRONG - Don't use import.meta.env directly
const response = await axios.get('http://localhost:3000/auth/profile');

// βœ… CORRECT - Use the config system
import config from '../config/env.js';
const response = await axios.get(`${config.API_BASE_URL}/auth/profile`);

Environment Variables Not Loading

# Restart dev servers after changing .env files
npm run dev

# Check if variables are loaded
console.log('Config:', config);

CORS Errors

  • Verify VITE_API_BASE_URL matches backend PORT
  • Check WS_CORS_ORIGIN matches frontend URL
  • Ensure ALLOWED_ORIGINS includes frontend URL

TypeORM Migrations for Production

#Install TypeORM CLI
npm install -g typeorm

#Generate a migration after making entity changes
typeorm migration:generate -n CreateUserRolesStructure

#Apply migrations
typeorm migration:run

Complementary Instructions After Revisions

MySQL Setup

  1. Download and install MySQL Installer from https://dev.mysql.com/downloads/installer/ or https://dev.mysql.com/downloads/workbench/

  2. During installation, select:

  • MySQL Server
  • MySQL Workbench
  • MySQL Shell
  • Connector/J

I selected all though

  1. Configure MySQL Server with these settings:
  • Authentication Method: Use Strong Password Encryption
  • Root Password: [create a secure password]
  1. Launch MySQL Workbench
  2. Create a new database:
CREATE DATABASE bulak_smart_connect; 
USE bulak_smart_connect; 

-- Create users table 
CREATE TABLE users ( 
  id INT AUTO_INCREMENT PRIMARY KEY, 
  email VARCHAR(255) NOT NULL UNIQUE, 
  password VARCHAR(255) NOT NULL, 
  name VARCHAR(255) NOT NULL, 
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP 
); 

-- Create a test user (password: password123) 
INSERT INTO users (email, password, name) 
VALUES ('[email protected]', '$2b$10$mExcKUyHurlq1zNDNos9LOXbtUJZuvIKybmHr/BngC6ZamAjz1ohS', 'Test User'); 

-- Add roles table 
CREATE TABLE `roles` ( 
  `id` int NOT NULL AUTO_INCREMENT, 
  `name` varchar(50) NOT NULL, 
  `description` varchar(255), 
  PRIMARY KEY (`id`), 
  UNIQUE KEY `IDX_roles_name` (`name`) 
); 

-- Insert default roles 
INSERT INTO `roles` (name, description) VALUES 
('super_admin', 'Has all permissions and can manage other admins'), 
('admin', 'Can manage staff and citizens'), 
('staff', 'Can process applications and manage citizen requests'), 
('citizen', 'Regular user of the system'); 

-- Add user_roles table for role assignment 
CREATE TABLE `user_roles` ( 
  `user_id` int NOT NULL, 
  `role_id` int NOT NULL, 
  PRIMARY KEY (`user_id`, `role_id`), 
  FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE, 
  FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE 
); 

-- Add a default role column to users table for quick access 
ALTER TABLE `users` ADD COLUMN `default_role_id` int; 
ALTER TABLE `users` ADD CONSTRAINT `fk_users_roles` FOREIGN KEY (`default_role_id`) REFERENCES `roles` (`id`); 

-- Update existing users to be citizens by default 
UPDATE `users` SET `default_role_id` = (SELECT id FROM roles WHERE name = 'citizen'); 

-- Create a test admin (password: admin123) 
INSERT INTO users (email, password, name) 
VALUES ('[email protected]', '$2b$10$oFpTU0U73YZPA.szNm2UHe22GtJY6k3yrGi2qa3txYzOD7EG2h.hq', 'Admin User'); 

-- Create test super admin 
INSERT INTO users (email, password, name)  
VALUES ('[email protected]', '$2b$10$oFpTU0U73YZPA.szNm2UHe22GtJY6k3yrGi2qa3txYzOD7EG2h.hq', 'Super Admin User'); 

-- Create test staff 
INSERT INTO users (email, password, name)  
VALUES ('[email protected]', '$2b$10$oFpTU0U73YZPA.szNm2UHe22GtJY6k3yrGi2qa3txYzOD7EG2h.hq', 'Staff User'); 

-- Assign appropriate roles 
INSERT INTO user_roles (user_id, role_id) 
SELECT u.id, r.id 
FROM users u, roles r 
WHERE u.email = '[email protected]' AND r.name = 'admin'; 

INSERT INTO user_roles (user_id, role_id) 
SELECT u.id, r.id 
FROM users u, roles r 
WHERE u.email = '[email protected]' AND r.name = 'super_admin'; 

INSERT INTO user_roles (user_id, role_id) 
SELECT u.id, r.id 
FROM users u, roles r 
WHERE u.email = '[email protected]' AND r.name = 'staff'; 

-- Set default roles 
UPDATE users u JOIN roles r ON r.name = 'admin' 
SET u.default_role_id = r.id 
WHERE u.email = '[email protected]'; 

UPDATE users u JOIN roles r ON r.name = 'super_admin' 
SET u.default_role_id = r.id 
WHERE u.email = '[email protected]'; 

UPDATE users u JOIN roles r ON r.name = 'staff' 
SET u.default_role_id = r.id 
WHERE u.email = '[email protected]'; 

-- Additional tables for the complete system
CREATE TABLE announcements (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  content TEXT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE TABLE appointments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  appointment_date DATE NOT NULL,
  appointment_time TIME NOT NULL,
  purpose VARCHAR(255) NOT NULL,
  status ENUM('pending', 'confirmed', 'cancelled', 'completed') DEFAULT 'pending',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE TABLE queues (
  id INT AUTO_INCREMENT PRIMARY KEY,
  queue_number VARCHAR(20) NOT NULL,
  user_id INT,
  department VARCHAR(100) NOT NULL,
  service_type VARCHAR(100) NOT NULL,
  status ENUM('waiting', 'serving', 'completed', 'cancelled') DEFAULT 'waiting',
  priority_level INT DEFAULT 1,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  called_at TIMESTAMP NULL,
  completed_at TIMESTAMP NULL,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
);

Note

You can also import the database from the folder "database" Export it if you make any changes on the database and/or to ensure we have a backup to match the proper database on the latest iterations Also ensure there is no personal information on the database before you export it, for our safety. Optionally, you can just export it without the data, only the schema.

MinIO Setup

  1. Download MinIO:

    # Windows
    wget https://dl.min.io/server/minio/release/windows-amd64/minio.exe
    # Or download from https://min.io/download
  2. Create MinIO directory:

    mkdir C:\minio\data
  3. Start MinIO Server:

    # Create start-minio.bat
    @echo off
    set MINIO_ROOT_USER=minioadmin
    set MINIO_ROOT_PASSWORD=minioadmin123
    minio.exe server C:\minio\data --console-address ":9001"
  4. Verify Installation:

  5. Create Bucket (if not auto-created):

    • Option A: Using Web Console

      • Login to MinIO Console
      • Click "Create Bucket"
      • Name: bulak-smart-connect
      • Set to public read if needed
    • Option B: Using MinIO Client (if installed)

    mc.exe mb local/bulak-smart-connect
  6. Update Environment Variables:

    # In your .env file
    MINIO_ENDPOINT=localhost
    MINIO_PORT=9000
    MINIO_USE_SSL=false
    MINIO_ACCESS_KEY=minioadmin
    MINIO_SECRET_KEY=minioadmin123
    MINIO_BUCKET_NAME=bulak-smart-connect
    FILE_STORAGE_TYPE=minio

MinIO is an object storage solution used for storing and managing document files in the application.

Option 1: Docker Installation (Recommended)

  1. Install Docker (if not already installed):

  2. Run MinIO using Docker:

# Create a directory for MinIO data (optional)
mkdir -p ~/minio/data

# Run MinIO container
docker run -d \
  -p 9000:9000 \
  -p 9001:9001 \
  --name minio \
  -v ~/minio/data:/data \
  -e "MINIO_ROOT_USER=minioadmin" \
  -e "MINIO_ROOT_PASSWORD=minioadmin123" \
  quay.io/minio/minio server /data --console-address ":9001"
  1. Access MinIO Console:

Option 2: Windows Binary Installation

  1. Download MinIO:

    # Open PowerShell as Administrator
    Invoke-WebRequest -Uri "https://dl.min.io/server/minio/release/windows-amd64/minio.exe" -OutFile "minio.exe"
  2. Create MinIO directory and setup:

# Create directory structure
mkdir C:\minio
mkdir C:\minio\data

# Move the downloaded minio.exe to C:\minio\
# Or download directly to the directory:
cd C:\minio

If using PowerShell to download directly to the correct location:

# Create directory and download in one go
New-Item -ItemType Directory -Force -Path "C:\minio"
New-Item -ItemType Directory -Force -Path "C:\minio\data"
Invoke-WebRequest -Uri "https://dl.min.io/server/minio/release/windows-amd64/minio.exe" -OutFile "C:\minio\minio.exe"
  1. Create a startup batch file (Recommended for easy management):

Create a file named start-minio.bat in C:\minio\ with the following content:

@echo off
REM MinIO Server Startup Script
REM Place this file in C:\minio\start-minio.bat

echo ===============================================
echo Starting MinIO Object Storage Server
echo ===============================================

REM Set MinIO credentials (change these for production)
set MINIO_ROOT_USER=minioadmin
set MINIO_ROOT_PASSWORD=minioadmin123

REM Optional: Set additional MinIO configurations
set MINIO_CONSOLE_ADDRESS=:9001

echo.
echo MinIO Configuration:
echo - API Server: http://localhost:9000
echo - Web Console: http://localhost:9001
echo - Username: %MINIO_ROOT_USER%
echo - Password: %MINIO_ROOT_PASSWORD%
echo.
echo Starting server...
echo (Press Ctrl+C to stop the server)
echo.

REM Start MinIO server
minio.exe server C:\minio\data --console-address ":9001"

echo.
echo MinIO server has stopped.
pause
  1. Start MinIO Server:

Method 1: Using the batch file (Recommended)

# Double-click start-minio.bat or run from command prompt:
cd C:\minio
start-minio.bat

Method 2: Manual command line

cd C:\minio
set MINIO_ROOT_USER=minioadmin
set MINIO_ROOT_PASSWORD=minioadmin123
minio.exe server C:\minio\data --console-address ":9001"

Method 3: Using PowerShell

cd C:\minio
$env:MINIO_ROOT_USER = "minioadmin"
$env:MINIO_ROOT_PASSWORD = "minioadmin123"
.\minio.exe server C:\minio\data --console-address ":9001"

Option 3: Using XAMPP/Alternative Setup

If you're using XAMPP or prefer a different approach:

  1. Follow Option 1 (Docker) as it's platform-independent
  2. Alternatively, use MinIO's Windows Service installer from their official website

(Optional) Install the MinIO Client

The MinIO Client allows you to work with your MinIO volume from the command line for advanced operations.

  1. Download MinIO Client:

    # Download to C:\minio\ directory
    Invoke-WebRequest -Uri "https://dl.min.io/client/mc/release/windows-amd64/mc.exe" -OutFile "C:\minio\mc.exe"
  2. Set up MinIO Client:

# Navigate to MinIO directory
cd C:\minio

# Test the client
mc.exe --help
  1. Configure MinIO Client alias:
# Set up alias for your local MinIO instance
mc.exe alias set local http://127.0.0.1:9000 minioadmin minioadmin123

# Test the connection
mc.exe admin info local
  1. Common MinIO Client Commands:
# List buckets
mc.exe ls local

# Create a bucket
mc.exe mb local/my-new-bucket

# List files in a bucket
mc.exe ls local/document-applications

# Copy files
mc.exe cp myfile.pdf local/document-applications/

# Get bucket policy
mc.exe policy get local/document-applications

Post-Installation Setup

  1. Verify Installation:

  2. Create Bucket (if not auto-created):

    • Option A: Using Web Console

      • Login to MinIO Console
      • Click "Create Bucket"
      • Name: document-applications (or as specified in your .env)
      • Set to public read if needed
    • Option B: Using MinIO Client (if installed)

    mc.exe mb local/document-applications
  3. Update Environment Variables:

    # In your .env file
    MINIO_ENDPOINT=localhost
    MINIO_PORT=9000
    MINIO_USE_SSL=false
    MINIO_ACCESS_KEY=minioadmin
    MINIO_SECRET_KEY=minioadmin123
    MINIO_BUCKET_NAME=document-applications

Troubleshooting

  • Port Conflicts: If port 9000 is in use, change to a different port:

    # For Docker
    docker run -d -p 9002:9000 -p 9003:9001 --name minio ...
    
    # For Windows Binary - update your batch file:
    minio.exe server C:\minio\data --address ":9002" --console-address ":9003"
    
    # Update .env file
    MINIO_PORT=9002
  • Permission Issues:

    • Ensure the data directory has proper read/write permissions
    • Run Command Prompt as Administrator if needed
    • Check Windows Defender/Antivirus isn't blocking minio.exe
  • Docker Issues:

    # Stop existing container
    docker stop minio
    docker rm minio
    
    # Run new container
    docker run -d ...
  • Windows Binary Issues:

    # Check if MinIO is running
    netstat -an | findstr :9000
    
    # Kill existing MinIO process if needed
    taskkill /f /im minio.exe
    
    # Restart using batch file
    start-minio.bat
  • MinIO Client Issues:

    # Test client connectivity
    mc.exe admin info local
    
    # Re-configure alias if needed
    mc.exe alias remove local
    mc.exe alias set local http://127.0.0.1:9000 minioadmin minioadmin123
  • Connection Testing: The backend will automatically test MinIO connection on startup and provide helpful error messages.

Production Considerations

For production environments, consider:

  1. Change Default Credentials:

    # In start-minio.bat, update:
    set MINIO_ROOT_USER=your_secure_username
    set MINIO_ROOT_PASSWORD=your_secure_password_min_8_chars
  2. Use HTTPS/TLS:

    # Add certificates and update:
    set MINIO_USE_SSL=true
    minio.exe server C:\minio\data --certs-dir C:\minio\certs --console-address ":9001"
  3. Run as Windows Service: Consider using tools like NSSM (Non-Sucking Service Manager) to run MinIO as a Windows service.

  4. Backup Strategy: Regularly backup your C:\minio\data directory.


## Environment Setup

### πŸ”§ Backend Environment Configuration

Create a `.env` file in the `bsc-js-backend` directory with:

```bash
# ===========================================
# BSC BACKEND ENVIRONMENT CONFIGURATION
# ===========================================

# Server Configuration
NODE_ENV=development
PORT=3000
HOST=localhost

# CORS & WebSocket Configuration
ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000
WS_CORS_ORIGIN=http://localhost:5173
FRONTEND_URL=http://localhost:5173

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=root
DB_PASSWORD=your_password
DB_NAME=bulak_smart_connect
DB_SYNCHRONIZE=false
DB_LOGGING=false
DB_TIMEZONE=+08:00

# JWT Configuration
JWT_SECRET=your_jwt_secret_key_min_32_chars
JWT_EXPIRES_IN=7d

# MinIO Configuration
MINIO_ENDPOINT=localhost
MINIO_PORT=9000
MINIO_USE_SSL=false
MINIO_ACCESS_KEY=minioadmin
MINIO_SECRET_KEY=minioadmin123
MINIO_BUCKET_NAME=bulak-smart-connect
FILE_STORAGE_TYPE=minio

# Swagger Documentation
SWAGGER_TITLE=Bulak Smart Connect API
SWAGGER_DESCRIPTION=REST API for Bulak Smart Connect Municipal Services System
SWAGGER_VERSION=1.0.0

# Application URLs for logging
SERVER_BASE_URL=http://localhost:3000
SWAGGER_URL=http://localhost:3000/api/docs

🎨 Frontend Environment Configuration

Create a .env file in the bulak-smart-connect-js directory:

# ===========================================
# BSC FRONTEND ENVIRONMENT CONFIGURATION
# ===========================================

# API Configuration
VITE_API_BASE_URL=http://localhost:3000
VITE_WS_URL=http://localhost:3000
VITE_API_TIMEOUT=15000

# Application Configuration
VITE_APP_TITLE=Bulak Smart Connect
VITE_APP_DESCRIPTION=Municipal Services Digital Platform
VITE_APP_VERSION=1.0.0
VITE_NODE_ENV=development

# Feature Flags
VITE_ENABLE_PWA=true
VITE_ENABLE_ANALYTICS=false
VITE_ENABLE_DEBUG=true

# Storage Configuration
VITE_STORAGE_PREFIX=

# Print Settings
VITE_PRINT_ENABLED=true
VITE_PRINT_COPIES=1
VITE_PRINTER_NAME=default

# Queue System Configuration
VITE_QUEUE_REFRESH_INTERVAL=5000
VITE_QUEUE_AUTO_REFRESH=true

# File Upload Configuration
VITE_MAX_FILE_SIZE=10485760
VITE_ALLOWED_FILE_TYPES=pdf,doc,docx,jpg,jpeg,png

# External Services
VITE_GOOGLE_MAPS_API_KEY=
VITE_RECAPTCHA_SITE_KEY=

# UI Configuration
VITE_THEME_PRIMARY=#184a5b
VITE_THEME_SECONDARY=#ffffff
VITE_SIDEBAR_DEFAULT_OPEN=true

# Development URLs
VITE_ADMIN_PANEL_URL=http://localhost:5173/AdminHome
VITE_USER_DASHBOARD_URL=http://localhost:5173/UserDashboard

# Endpoints Configuration
VITE_AUTH_ENDPOINT=/auth
VITE_QUEUE_ENDPOINT=/queue
VITE_APPOINTMENTS_ENDPOINT=/appointments
VITE_ANNOUNCEMENTS_ENDPOINT=/announcements
VITE_DOCUMENT_APPLICATIONS_ENDPOINT=/document-applications
VITE_USERS_ENDPOINT=/users

πŸ” Environment Variable Generation

Generate secure environment variables:

# Generate a secure JWT secret
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"

# Generate secure MinIO credentials for production
node -e "console.log('MINIO_ACCESS_KEY=' + require('crypto').randomBytes(16).toString('hex'))"
node -e "console.log('MINIO_SECRET_KEY=' + require('crypto').randomBytes(32).toString('hex'))"

πŸ“‹ Quick Setup Commands

# Copy environment templates
cp bsc-js-backend/.env.example bsc-js-backend/.env
cp bulak-smart-connect-js/.env.example bulak-smart-connect-js/.env

# Edit configuration files with your actual values
# Update database credentials, API keys, and other settings

XAMPP Setup (Alternative to MySQL Installer/Optional)

If you prefer using XAMPP instead of MySQL Installer:

  1. Download and install XAMPP from https://www.apachefriends.org/
  2. Start the MySQL and Apache services from XAMPP Control Panel
  3. Open phpMyAdmin at http://localhost/phpmyadmin
  4. Create database and tables as described in the MySQL Setup section
  5. Note that XAMPP uses MariaDB instead of MySQL, but this is compatible with the provided instructions

New Ways to Run Project

cd bulak-smart-connect-js
npm run dev            # Run React and NestJS concurrently
npm run start-frontend # Run React only
npm run start-backend  # Run NestJS only
npm run build          # Vite build
npm run lint           # ESLint
npm run preview        # Vite preview

For more backend options:

cd bsc-js-backend
npm run start          # Start NestJS normally
npm run start:dev      # Start NestJS in development mode

Development Scripts

Frontend (bulak-smart-connect-js)

npm run dev            # Run React with Vite dev server
npm run build          # Build for production
npm run preview        # Preview production build
npm run lint           # Run ESLint
npm run storybook      # Start Storybook
npm run build-storybook # Build Storybook

Backend (bsc-js-backend)

npm run start          # Start production server
npm run start:dev      # Start development server with hot reload
npm run start:debug    # Start in debug mode
npm run build          # Build TypeScript
npm run test           # Run tests
npm run test:e2e       # Run end-to-end tests
npm run test:cov       # Run tests with coverage

Full Stack Development

# From root directory
npm run dev            # Run both frontend and backend concurrently
npm run start-frontend # Run React only  
npm run start-backend  # Run NestJS only

Testing

Backend Tests

cd bsc-js-backend
npm test                    # Run all tests
npm run test:watch          # Run tests in watch mode
npm run test:cov            # Run tests with coverage
npm run test:e2e            # Run end-to-end tests

Test Coverage

  • βœ… Authentication & Authorization
  • βœ… User Management & Roles
  • βœ… Queue Management System
  • βœ… Appointment Scheduling
  • βœ… Announcements
  • βœ… Document Applications with MinIO Storage
  • βœ… Real-time WebSocket Gateway

All modules include both unit tests and controller tests with proper mocking.

API Documentation

Swagger/OpenAPI Documentation

  • Local Development: http://localhost:3000/api/docs
  • Interactive API Testing: Available through Swagger UI
  • JWT Authentication: Supported in Swagger interface

Additional Documentation

API Testing

# Start the backend server
cd bsc-js-backend
npm run start:dev

# Access Swagger documentation at:
# http://localhost:3000/api/docs

Using Swagger UI

  1. Start your backend server (npm run start:dev)
  2. Navigate to http://localhost:3000/api/docs
  3. Use the "Authorize" button to add your JWT token
  4. Test endpoints directly from the interface

Authentication

  • POST /auth/login - User login
  • POST /auth/register - User registration
  • GET /auth/profile - Get user profile
  • POST /auth/update-profile - Update user profile

Queue Management

  • GET /queue - Get all queues
  • POST /queue/join - Join a queue
  • DELETE /queue/leave - Leave a queue
  • WebSocket events for real-time updates

Appointments

  • GET /appointment - Get appointments
  • POST /appointment - Create appointment
  • PATCH /appointment/:id - Update appointment

Announcements

  • GET /announcements - Get all announcements
  • GET /announcements/recent - Get recent announcements

Document Applications

  • GET /document-applications - Get user's applications
  • POST /document-applications - Create new application
  • POST /document-applications/:id/upload - Upload document file
  • GET /document-applications/files/:fileId/download - Get file download URL
  • PATCH /document-applications/:id - Update application
  • PATCH /document-applications/:id/status - Update application status (Admin only)
  • DELETE /document-applications/:id - Delete application

File Storage

  • MinIO Integration: Secure document storage and retrieval
  • File Upload: Support for multiple document types (PDF, Images)
  • Presigned URLs: Secure file access with expiration
  • Automatic Bucket Management: Auto-creation and configuration

For complete API documentation, check the Postman collection in /docs/bulak-smart-connect-postman-collection.json

Test Accounts

The system comes with pre-configured test accounts:

Email Password Role Description
[email protected] password123 citizen Regular user account
[email protected] admin123 admin Administrator account
[email protected] admin123 super_admin Super administrator
[email protected] admin123 staff Staff member account

All passwords are hashed using bcrypt for security.

Project Structure

Bulak-Smart-Connect-JS/
β”œβ”€β”€ bulak-smart-connect-js/     # React frontend
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/         # Reusable components
β”‚   β”‚   β”œβ”€β”€ LandingPageComponents/ # Landing page specific
β”‚   β”‚   └── ...
β”‚   └── package.json
β”œβ”€β”€ bsc-js-backend/            # NestJS backend
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ auth/              # Authentication module
β”‚   β”‚   β”œβ”€β”€ users/             # User management
β”‚   β”‚   β”œβ”€β”€ roles/             # Role management
β”‚   β”‚   β”œβ”€β”€ modules/
β”‚   β”‚   β”‚   β”œβ”€β”€ queue/         # Queue management
β”‚   β”‚   β”‚   β”œβ”€β”€ appointment/   # Appointment system
β”‚   β”‚   β”‚   β”œβ”€β”€ announcement/  # Announcements
β”‚   β”‚   β”‚   └── document-applications/ # Document applications with MinIO
β”‚   β”‚   └── main.ts
β”‚   β”œβ”€β”€ test/                  # E2E tests
β”‚   β”œβ”€β”€ docs/                  # API documentation
β”‚   └── package.json
└── README.md

Authors

YuKARLO15 user profile dennissegailfrancisco user profile jhazminereigne user profile Astriaaa user profile

YuKARLO15

dennissegailfrancisco

jhazminereigne

Astriaaa

BS Computer Science

BS Information Technology

BS Computer Science

BS Information Technology

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 8