feat: Complete Pennyzo frontend with live waitlist tracking

- Live waitlist integration with backend API
- Real-time polling every 60 seconds
- Comprehensive API logging and error handling
- WaitlistContext for global state management
- Responsive UI with live data updates
- Registration form with automatic waitlist refresh
- Modern React/TypeScript architecture
- Tailwind CSS styling with luxury theme
This commit is contained in:
Hardik Sankhla
2025-09-26 04:25:47 +05:30
commit b7247f21a3
58 changed files with 9359 additions and 0 deletions

287
scripts/README.md Normal file
View File

@@ -0,0 +1,287 @@
# Pennyzo API Status Checker
Node.js scripts for checking the status of all primary endpoints of the Pennyzo General API.
This package includes two versions of the script:
- `api-status-checker.js` - Basic version with console output
- `api-status-checker-extended.js` - Extended version with report generation and additional features
## Overview
These scripts test both public and authenticated endpoints of the Pennyzo General API and log the results to the console. The scripts perform the following checks:
### Public Endpoints:
- GET `/system/health`
- GET `/registration/company/identity-rules`
### Authentication Flow:
- POST `/auth/login` (using placeholder credentials)
### Authenticated Endpoints (only if login is successful):
- GET `/auth/me`
- GET `/users/profile`
- GET `/users/stats`
- GET `/users/membership-info`
## Requirements
- Node.js (version 14 or higher recommended)
- npm packages:
- axios (for HTTP requests)
- chalk (for colorful console output)
## Installation
Both required packages are already installed in the project.
## Environment Configuration
The API endpoints are now environment-aware. By default:
- **Development**: `http://localhost:8000`
- **Production**: `https://api.pennyzo.com/api/v1/general`
### Setting Environment
Use the following npm scripts to configure your environment:
```bash
# Set development environment (localhost:8000)
npm run env:dev
# Set production environment (api.pennyzo.com)
npm run env:prod
# Show current environment configuration
npm run env:show
```
Alternatively, manually create a `.env` file:
```bash
# For development
VITE_API_BASE_URL=http://localhost:8000
NODE_ENV=development
# For production
VITE_API_BASE_URL=https://api.pennyzo.com/api/v1/general
NODE_ENV=production
```
## Usage
### Using npm Scripts (Recommended)
The following npm scripts are available for checking API status:
```bash
# Run basic API check
npm run api:check
# Run extended API check with report generation
npm run api:check:extended
# Run extended API check with verbose output
npm run api:check:verbose
# Run extended API check with real credentials
npm run api:check:real
```
### Direct Node Execution
To run the scripts directly with Node:
#### Basic Script
```powershell
node scripts/api-status-checker.js
```
#### Extended Script
```powershell
node scripts/api-status-checker-extended.js [options]
```
Available options:
- `--verbose`: Show detailed response data
- `--no-report`: Don't save a report file
- `--use-real-credentials`: Use credentials from environment variables
### Helper PowerShell Script
For additional flexibility, a PowerShell helper script is provided:
```powershell
.\scripts\run-api-check.ps1 [-Verbose] [-NoReport] [-UseRealCredentials] [-Extended]
```
Examples:
```powershell
# Run basic script
.\scripts\run-api-check.ps1
# Run extended script with verbose output
.\scripts\run-api-check.ps1 -Extended -Verbose
# Run extended script with real credentials
.\scripts\run-api-check.ps1 -Extended -UseRealCredentials
```
## Configuration
### Basic Configuration
You can modify the test credentials in the script to use valid credentials for testing authenticated endpoints:
```javascript
// Test credentials (replace with actual test credentials if available)
const TEST_CREDENTIALS = {
email: "your-test-email@example.com",
password: "your-test-password",
};
```
### Environment Variables
For the extended script, you can set environment variables for secure credential management:
```powershell
$env:PENNYZO_TEST_EMAIL = "your-test-email@example.com"
$env:PENNYZO_TEST_PASSWORD = "your-test-password"
```
Then run with the `--use-real-credentials` flag:
```powershell
node scripts/api-status-checker-extended.js --use-real-credentials
```
## Output
The script provides detailed output for each API call:
- Endpoint being tested
- HTTP method
- Status (SUCCESS or FAILED)
- HTTP status code
- Error details (if applicable)
For the system health endpoint, additional information is displayed:
- API Status
- Environment
- Version
- Message
## Features
### Basic Script
- Tests both public and authenticated endpoints
- Colorful console output with chalk
- Clear status indicators
### Extended Script (Additional Features)
- Saves detailed reports to JSON files (in a `reports` folder)
- Provides response time measurements
- Supports command line arguments
- Environment variable support for credentials
- Verbose mode for detailed output
- Summary statistics
## Example Output
### Basic Script Output
```
=== Pennyzo General API Status Checker ===
--- Testing Public Endpoints ---
GET /system/health: SUCCESS (200)
API Status: operational
Environment: production
Version: 1.0.0
Message: Service is healthy
GET /registration/company/identity-rules: SUCCESS (200)
--- Testing Authentication Flow ---
POST /auth/login: FAILED (401)
Error: Request failed with status code 401
Details: {
"error": {
"type": "unauthorized",
"code": 401,
"message": "Invalid credentials"
}
}
Authentication failed. Cannot test authenticated endpoints.
Note: This is expected if using placeholder credentials.
To test authenticated endpoints, update the TEST_CREDENTIALS with valid credentials.
=== API Status Check Complete ===
```
### Extended Script Output
```
=== Pennyzo General API Status Checker ===
Timestamp: 2025-09-25T10:15:30.123Z
Base URL: https://api.pennyzo.com/api/v1/general
Save Report: Yes
Verbose Mode: Yes
Using Real Credentials: No
--- Testing Public Endpoints ---
GET /system/health: SUCCESS (200) [342ms]
API Status: operational
Environment: production
Version: 1.0.0
Message: Service is healthy
GET /registration/company/identity-rules: SUCCESS (200) [285ms]
--- Testing Authentication Flow ---
POST /auth/login: FAILED (401) [520ms]
Error: Request failed with status code 401
Authentication failed. Cannot test authenticated endpoints.
Note: This is expected if using placeholder credentials.
To test authenticated endpoints, use the --use-real-credentials flag
and set PENNYZO_TEST_EMAIL and PENNYZO_TEST_PASSWORD environment variables.
=== API Status Check Summary ===
Total endpoints checked: 3
Successful: 2
Failed: 1
Success rate: 66.7%
Total time: 1.15 seconds
Report saved to: c:\Users\naman\OneDrive\Desktop\Pennyzo Web\reports\api-status-2025-09-25T10-15-30.123Z.json
=== API Status Check Complete ===
```
## Notes
- The scripts use placeholder credentials by default, which will likely fail authentication. This is expected behavior.
- To properly test authenticated endpoints, use real credentials via environment variables or direct script modification.
- The extended script saves reports to a `reports` directory for historical tracking of API status.
- All API calls and their results are logged to the console and (optionally) to report files.
- Response times are logged to help identify slow endpoints.
- A HTML report viewer is included at `reports/report-viewer.html` for visualizing the JSON reports.

101
scripts/SUMMARY.md Normal file
View File

@@ -0,0 +1,101 @@
# Pennyzo API Status Checker
This project provides comprehensive tools for checking the status of the Pennyzo General API endpoints. It includes both basic and extended versions of the API status checker, along with supporting tools and documentation.
## Project Structure
```
scripts/
├── api-status-checker.js # Basic API status checker
├── api-status-checker-extended.js # Extended API status checker with additional features
├── run-api-check.ps1 # PowerShell helper script
└── README.md # Documentation for the scripts
reports/
├── example-report.json # Sample report file
├── report-viewer.html # HTML tool for visualizing reports
├── .gitignore # Git configuration for reports
└── README.md # Documentation for the reports directory
```
## Features
1. **Basic API Status Checker**
- Tests both public and authenticated endpoints
- Colorful console output
- Automatic token management
2. **Extended API Status Checker**
- All features of the basic checker
- Saves detailed reports to JSON files
- Provides response time measurements
- Support for command line arguments
- Environment variable support for credentials
3. **Report Viewer**
- HTML-based visualization tool
- Interactive endpoint details
- Summary statistics
- Color-coded status indicators
4. **Helper Tools**
- PowerShell script for flexible execution
- npm scripts for convenient access
- Example report for reference
## Getting Started
### Using npm Scripts
```bash
# Run basic API check
npm run api:check
# Run extended API check with report generation
npm run api:check:extended
# Run extended API check with verbose output
npm run api:check:verbose
# Run extended API check with real credentials
npm run api:check:real
```
### Using Environment Variables
For secure credential management with real credentials:
```powershell
$env:PENNYZO_TEST_EMAIL = "your-test-email@example.com"
$env:PENNYZO_TEST_PASSWORD = "your-test-password"
npm run api:check:real
```
### Viewing Reports
After running the extended script, reports are saved to the `reports` directory. To view a report:
1. Open `reports/report-viewer.html` in a web browser
2. Click "Choose Report File" to select a JSON report
3. Review the report details
## Summary of API Endpoints Tested
### Public Endpoints
- GET `/system/health`
- GET `/registration/company/identity-rules`
### Authentication Flow
- POST `/auth/login`
### Authenticated Endpoints
- GET `/auth/me`
- GET `/users/profile`
- GET `/users/stats`
- GET `/users/membership-info`

View File

@@ -0,0 +1,241 @@
/**
* Pennyzo General API Status Checker (Extended Version)
*
* This script checks the status of all primary endpoints of the Pennyzo General API,
* logs the results to the console, and optionally saves a detailed report to a file.
*
* Features:
* - Tests both public and authenticated endpoints
* - Provides detailed error information
* - Generates a report with timestamp
* - Saves results to a file
* - Supports command line arguments for customization
*/
// Load environment variables from .env file
require('dotenv').config();
const axios = require('axios');
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
// Parse command line arguments
const args = process.argv.slice(2);
const saveReport = !args.includes('--no-report');
const verbose = args.includes('--verbose');
const useRealCredentials = args.includes('--use-real-credentials');
// Define the base URL based on environment
const BASE_URL = process.env.VITE_API_BASE_URL ||
process.env.API_BASE_URL ||
(process.env.NODE_ENV === 'production' ?
'https://api.pennyzo.com/api/v1/general' :
'http://localhost:8000');
// Test credentials
const TEST_CREDENTIALS = {
email: useRealCredentials ? process.env.PENNYZO_TEST_EMAIL || 'test@example.com' : 'test@example.com',
password: useRealCredentials ? process.env.PENNYZO_TEST_PASSWORD || 'Password123!' : 'Password123!'
};
// Store the access token for authenticated requests
let accessToken = null;
// Store all results for reporting
const results = [];
const startTime = new Date();
// Helper function to log API call results
function logResult(endpoint, method, status, statusCode, responseTime, data = null, error = null) {
const statusText = status === 'SUCCESS' ? chalk.green(status) : chalk.red(status);
const statusCodeText = statusCode ? `(${statusCode})` : '';
const responseTimeText = responseTime ? `[${responseTime}ms]` : '';
console.log(`${chalk.yellow(method)} ${chalk.blue(endpoint)}: ${statusText} ${statusCodeText} ${responseTimeText}`);
if (error) {
console.log(` Error: ${chalk.red(error.message)}`);
if (error.response?.data && verbose) {
console.log(` Details: ${JSON.stringify(error.response.data, null, 2)}`);
}
} else if (data && verbose) {
const dataPreview = JSON.stringify(data).substring(0, 100) + (JSON.stringify(data).length > 100 ? '...' : '');
console.log(` Data: ${dataPreview}`);
}
// Store result for reporting
results.push({
endpoint,
method,
status,
statusCode: statusCode || 'N/A',
responseTime,
timestamp: new Date().toISOString(),
error: error ? {
message: error.message,
details: error.response?.data || null
} : null,
data: data && verbose ? data : null
});
}
// Helper function to make API calls and log results
async function callApi(endpoint, method = 'GET', data = null, authenticated = false) {
const url = `${BASE_URL}${endpoint}`;
const config = {};
if (authenticated && accessToken) {
config.headers = {
'Authorization': `Bearer ${accessToken}`
};
}
// Special handling for form-urlencoded content type (login endpoint)
if (endpoint === '/auth/login') {
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
// Convert data to URLSearchParams for login endpoint
if (data) {
const params = new URLSearchParams();
params.append('username', data.email); // API uses username field for email
params.append('password', data.password);
data = params;
}
}
const startTime = Date.now();
try {
let response;
switch (method) {
case 'GET':
response = await axios.get(url, config);
break;
case 'POST':
response = await axios.post(url, data, config);
break;
default:
throw new Error(`Unsupported method: ${method}`);
}
const responseTime = Date.now() - startTime;
logResult(endpoint, method, 'SUCCESS', response.status, responseTime, response.data);
return { success: true, data: response.data, responseTime };
} catch (error) {
const responseTime = Date.now() - startTime;
const statusCode = error.response?.status || 'N/A';
logResult(endpoint, method, 'FAILED', statusCode, responseTime, null, error);
return { success: false, error, responseTime };
}
}
// Function to generate and save a report
function saveReportToFile() {
const endTime = new Date();
const duration = (endTime - startTime) / 1000; // in seconds
// Count successes and failures
const successCount = results.filter(r => r.status === 'SUCCESS').length;
const failureCount = results.filter(r => r.status === 'FAILED').length;
const report = {
title: 'Pennyzo API Status Check Report',
timestamp: endTime.toISOString(),
duration: `${duration.toFixed(2)} seconds`,
summary: {
totalEndpoints: results.length,
successful: successCount,
failed: failureCount,
successRate: `${((successCount / results.length) * 100).toFixed(1)}%`
},
baseUrl: BASE_URL,
results: results
};
const reportDir = path.join(__dirname, '../reports');
if (!fs.existsSync(reportDir)) {
fs.mkdirSync(reportDir, { recursive: true });
}
const reportPath = path.join(reportDir, `api-status-${endTime.toISOString().replace(/:/g, '-')}.json`);
fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
console.log(chalk.bold(`\nReport saved to: ${reportPath}`));
}
// Main function to run the API checks
async function checkApiStatus() {
console.log(chalk.bold('\n=== Pennyzo General API Status Checker ===\n'));
console.log(`Timestamp: ${startTime.toISOString()}`);
console.log(`Base URL: ${BASE_URL}`);
console.log(`Save Report: ${saveReport ? 'Yes' : 'No'}`);
console.log(`Verbose Mode: ${verbose ? 'Yes' : 'No'}`);
console.log(`Using Real Credentials: ${useRealCredentials ? 'Yes' : 'No'}\n`);
console.log(chalk.bold('\n--- Testing Public Endpoints ---\n'));
// Test system health endpoint
const healthResult = await callApi('/system/health');
if (healthResult.success) {
console.log(` API Status: ${healthResult.data.status}`);
console.log(` Environment: ${healthResult.data.environment}`);
console.log(` Version: ${healthResult.data.version}`);
console.log(` Message: ${healthResult.data.message}\n`);
}
// Test registration company identity rules endpoint
await callApi('/registration/company/identity-rules');
console.log(chalk.bold('\n--- Testing Authentication Flow ---\n'));
// Try to authenticate with test credentials
const loginResult = await callApi('/auth/login', 'POST', TEST_CREDENTIALS);
if (loginResult.success) {
accessToken = loginResult.data.access_token;
console.log(chalk.green(' Authentication successful. Access token received.'));
console.log(` Token type: ${loginResult.data.token_type}`);
if (loginResult.data.expires_in) {
console.log(` Token expires in: ${loginResult.data.expires_in} seconds\n`);
}
console.log(chalk.bold('\n--- Testing Authenticated Endpoints ---\n'));
// Test authenticated endpoints
await callApi('/auth/me', 'GET', null, true);
await callApi('/users/profile', 'GET', null, true);
await callApi('/users/stats', 'GET', null, true);
await callApi('/users/membership-info', 'GET', null, true);
} else {
console.log(chalk.red(' Authentication failed. Cannot test authenticated endpoints.'));
console.log(' Note: This is expected if using placeholder credentials.');
console.log(' To test authenticated endpoints, use the --use-real-credentials flag');
console.log(' and set PENNYZO_TEST_EMAIL and PENNYZO_TEST_PASSWORD environment variables.\n');
}
// Summary
const successCount = results.filter(r => r.status === 'SUCCESS').length;
const failureCount = results.filter(r => r.status === 'FAILED').length;
console.log(chalk.bold('\n=== API Status Check Summary ===\n'));
console.log(`Total endpoints checked: ${results.length}`);
console.log(`Successful: ${chalk.green(successCount)}`);
console.log(`Failed: ${chalk.red(failureCount)}`);
console.log(`Success rate: ${((successCount / results.length) * 100).toFixed(1)}%`);
console.log(`Total time: ${((new Date() - startTime) / 1000).toFixed(2)} seconds\n`);
// Save report if enabled
if (saveReport) {
saveReportToFile();
}
console.log(chalk.bold('=== API Status Check Complete ===\n'));
}
// Execute the API checker
checkApiStatus().catch(error => {
console.error(chalk.red('\nUnexpected error during API status check:'));
console.error(error);
});

View File

@@ -0,0 +1,144 @@
/**
* Pennyzo General API Status Checker
*
* This script checks the status of all primary endpoints of the Pennyzo General API
* and logs the results to the console.
*/
// Load environment variables from .env file
require('dotenv').config();
const axios = require('axios');
const chalk = require('chalk'); // For colorful console output
// Define the base URL based on environment
const BASE_URL = process.env.VITE_API_BASE_URL ||
process.env.API_BASE_URL ||
(process.env.NODE_ENV === 'production' ?
'https://api.pennyzo.com/api/v1/general' :
'http://localhost:8000');
// Test credentials (replace with actual test credentials if available)
const TEST_CREDENTIALS = {
email: 'test@example.com',
password: 'Password123!'
};
// Store the access token for authenticated requests
let accessToken = null;
// Helper function to log API call results
function logResult(endpoint, method, status, statusCode, error = null) {
const statusText = status === 'SUCCESS' ? chalk.green(status) : chalk.red(status);
const statusCodeText = statusCode ? `(${statusCode})` : '';
console.log(`${chalk.yellow(method)} ${chalk.blue(endpoint)}: ${statusText} ${statusCodeText}`);
if (error) {
console.log(` Error: ${chalk.red(error.message)}`);
if (error.response?.data) {
console.log(` Details: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
// Helper function to make API calls and log results
async function callApi(endpoint, method = 'GET', data = null, authenticated = false) {
const url = `${BASE_URL}${endpoint}`;
const config = {};
if (authenticated && accessToken) {
config.headers = {
'Authorization': `Bearer ${accessToken}`
};
}
// Special handling for form-urlencoded content type (login endpoint)
if (endpoint === '/auth/login') {
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
// Convert data to URLSearchParams for login endpoint
if (data) {
const params = new URLSearchParams();
params.append('username', data.email); // API uses username field for email
params.append('password', data.password);
data = params;
}
}
try {
let response;
switch (method) {
case 'GET':
response = await axios.get(url, config);
break;
case 'POST':
response = await axios.post(url, data, config);
break;
default:
throw new Error(`Unsupported method: ${method}`);
}
logResult(endpoint, method, 'SUCCESS', response.status);
return { success: true, data: response.data };
} catch (error) {
const statusCode = error.response?.status || 'N/A';
logResult(endpoint, method, 'FAILED', statusCode, error);
return { success: false, error };
}
}
// Main function to run the API checks
async function checkApiStatus() {
console.log(chalk.bold('\n=== Pennyzo General API Status Checker ===\n'));
console.log(chalk.bold('\n--- Testing Public Endpoints ---\n'));
// Test system health endpoint
const healthResult = await callApi('/system/health');
if (healthResult.success) {
console.log(` API Status: ${healthResult.data.status}`);
console.log(` Environment: ${healthResult.data.environment}`);
console.log(` Version: ${healthResult.data.version}`);
console.log(` Message: ${healthResult.data.message}\n`);
}
// Test registration company identity rules endpoint
await callApi('/registration/company/identity-rules');
console.log(chalk.bold('\n--- Testing Authentication Flow ---\n'));
// Try to authenticate with test credentials
const loginResult = await callApi('/auth/login', 'POST', TEST_CREDENTIALS);
if (loginResult.success) {
accessToken = loginResult.data.access_token;
console.log(chalk.green(' Authentication successful. Access token received.'));
console.log(` Token type: ${loginResult.data.token_type}`);
if (loginResult.data.expires_in) {
console.log(` Token expires in: ${loginResult.data.expires_in} seconds\n`);
}
console.log(chalk.bold('\n--- Testing Authenticated Endpoints ---\n'));
// Test authenticated endpoints
await callApi('/auth/me', 'GET', null, true);
await callApi('/users/profile', 'GET', null, true);
await callApi('/users/stats', 'GET', null, true);
await callApi('/users/membership-info', 'GET', null, true);
} else {
console.log(chalk.red(' Authentication failed. Cannot test authenticated endpoints.'));
console.log(' Note: This is expected if using placeholder credentials.');
console.log(' To test authenticated endpoints, update the TEST_CREDENTIALS with valid credentials.\n');
}
console.log(chalk.bold('\n=== API Status Check Complete ===\n'));
}
// Execute the API checker
checkApiStatus().catch(error => {
console.error(chalk.red('\nUnexpected error during API status check:'));
console.error(error);
});

36
scripts/run-api-check.ps1 Normal file
View File

@@ -0,0 +1,36 @@
# PowerShell script to run the Pennyzo API Status Checker
param (
[switch]$Verbose,
[switch]$NoReport,
[switch]$UseRealCredentials,
[switch]$Extended
)
$ScriptArgs = @()
if ($Verbose) {
$ScriptArgs += "--verbose"
}
if ($NoReport) {
$ScriptArgs += "--no-report"
}
if ($UseRealCredentials) {
$ScriptArgs += "--use-real-credentials"
}
# Determine which script to run
$ScriptPath = if ($Extended) {
"scripts\api-status-checker-extended.js"
}
else {
"scripts\api-status-checker.js"
}
# Display command that will be executed
Write-Host "Running: node $ScriptPath $ScriptArgs"
# Run the script
node $ScriptPath $ScriptArgs

110
scripts/set-env.ps1 Normal file
View File

@@ -0,0 +1,110 @@
#!/usr/bin/env powershell
# Environment Configuration Helper Script
# This script helps you switch between development and production API endpoints
param(
[Parameter(Mandatory = $false)]
[ValidateSet("dev", "development", "prod", "production", "local")]
[string]$Environment = "dev",
[switch]$Show
)
$EnvFile = ".env"
$EnvExampleFile = ".env.example"
function Show-CurrentConfig {
Write-Host "Current Environment Configuration:" -ForegroundColor Green
Write-Host "=================================" -ForegroundColor Green
if (Test-Path $EnvFile) {
$content = Get-Content $EnvFile
foreach ($line in $content) {
if ($line -match "VITE_API_BASE_URL=(.+)") {
Write-Host "API Base URL: " -NoNewline -ForegroundColor Yellow
Write-Host $matches[1] -ForegroundColor White
}
if ($line -match "NODE_ENV=(.+)") {
Write-Host "Node Environment: " -NoNewline -ForegroundColor Yellow
Write-Host $matches[1] -ForegroundColor White
}
}
}
else {
Write-Host "No .env file found. Using default configuration." -ForegroundColor Red
Write-Host "API Base URL: " -NoNewline -ForegroundColor Yellow
Write-Host "http://localhost:8000 (development default)" -ForegroundColor White
}
Write-Host ""
}
function Set-Environment {
param([string]$Env)
$apiUrl = ""
$nodeEnv = ""
switch ($Env.ToLower()) {
{ $_ -in @("dev", "development", "local") } {
$apiUrl = "http://localhost:8000"
$nodeEnv = "development"
Write-Host "Configuring for DEVELOPMENT environment..." -ForegroundColor Green
}
{ $_ -in @("prod", "production") } {
$apiUrl = "https://api.pennyzo.com/api/v1/general"
$nodeEnv = "production"
Write-Host "Configuring for PRODUCTION environment..." -ForegroundColor Green
}
default {
Write-Host "Unknown environment: $Env" -ForegroundColor Red
return
}
}
# Create .env content
$debugValue = if ($nodeEnv -eq "development") { "true" } else { "false" }
$logLevel = if ($nodeEnv -eq "development") { "INFO" } else { "WARN" }
$envContent = @"
# Environment Configuration - Auto-generated
# Generated on: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
# API Base URL
VITE_API_BASE_URL=$apiUrl
# Environment
NODE_ENV=$nodeEnv
# Debug settings
DEBUG=$debugValue
LOG_LEVEL=$logLevel
# API Status Checker Credentials (optional)
# PENNYZO_TEST_EMAIL=your-test-email@example.com
# PENNYZO_TEST_PASSWORD=your-test-password
"@
# Write to .env file
$envContent | Out-File -FilePath $EnvFile -Encoding UTF8
Write-Host "Environment configured successfully!" -ForegroundColor Green
Write-Host "API Base URL set to: " -NoNewline -ForegroundColor Yellow
Write-Host $apiUrl -ForegroundColor White
Write-Host ""
}
# Main execution
if ($Show) {
Show-CurrentConfig
}
else {
Set-Environment -Env $Environment
Show-CurrentConfig
Write-Host "Usage Examples:" -ForegroundColor Cyan
Write-Host " .\scripts\set-env.ps1 dev # Set development environment" -ForegroundColor Gray
Write-Host " .\scripts\set-env.ps1 prod # Set production environment" -ForegroundColor Gray
Write-Host " .\scripts\set-env.ps1 -Show # Show current configuration" -ForegroundColor Gray
Write-Host ""
Write-Host "Restart your development server for changes to take effect." -ForegroundColor Yellow
}

72
scripts/test-config.js Normal file
View File

@@ -0,0 +1,72 @@
/**
* API Configuration Test Script
*
* This script verifies that all API configurations are properly set up
* and that the URLs are correctly configured for different environments.
*/
// Load environment variables
require('dotenv').config();
const chalk = require('chalk');
function testConfiguration() {
console.log(chalk.bold('\n=== API Configuration Test ===\n'));
// Test environment variables
console.log(chalk.yellow('Environment Variables:'));
console.log(` VITE_API_BASE_URL: ${process.env.VITE_API_BASE_URL || 'undefined'}`);
console.log(` NODE_ENV: ${process.env.NODE_ENV || 'undefined'}`);
console.log(` DEBUG: ${process.env.DEBUG || 'undefined'}`);
console.log(` LOG_LEVEL: ${process.env.LOG_LEVEL || 'undefined'}\n`);
// Test URL logic from scripts
const scriptUrl = process.env.VITE_API_BASE_URL ||
process.env.API_BASE_URL ||
(process.env.NODE_ENV === 'production' ?
'https://api.pennyzo.com/api/v1/general' :
'http://localhost:8000');
console.log(chalk.yellow('Script URL Resolution:'));
console.log(` Resolved URL: ${scriptUrl}\n`);
// Test individual components
console.log(chalk.yellow('Component URLs:'));
console.log(` API Status Checker: ${scriptUrl}`);
console.log(` React App (via VITE_API_BASE_URL): ${process.env.VITE_API_BASE_URL || 'Will use config.ts logic'}`);
console.log(` PennyzoApiService: Will use config.ts -> ${scriptUrl}\n`);
// Test endpoint construction
const testEndpoints = [
'/system/health',
'/registration/company/identity-rules',
'/auth/login',
'/auth/me',
'/users/profile'
];
console.log(chalk.yellow('Full Endpoint URLs:'));
testEndpoints.forEach(endpoint => {
console.log(` ${scriptUrl}${endpoint}`);
});
console.log(chalk.bold('\n=== Configuration Test Complete ===\n'));
// Summary
const isLocalhost = scriptUrl.includes('localhost');
const status = isLocalhost ?
chalk.green('✓ Configured for local development') :
chalk.blue('✓ Configured for production');
console.log(chalk.bold('Summary:'));
console.log(` ${status}`);
console.log(` Base URL: ${scriptUrl}`);
if (isLocalhost) {
console.log(chalk.yellow('\n Note: Ensure your backend server is running on localhost:8000'));
} else {
console.log(chalk.yellow('\n Note: Ensure the production API server is accessible'));
}
}
testConfiguration();