Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,7 @@ dist
.env*
!.env.example
.wrangler/

# Mac folder index

.DS_Store
22 changes: 22 additions & 0 deletions plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Development Plan: StartupAPI Cloudflare (Durable Object + SQLite)

## 🏗️ Phase 1: Storage & Identity Mapping

- **Durable Object Schema:** Implement SQLite-based storage within DO classes.
- **Direct ID Resolution:** Use Durable Object's `idFromName` to map unique identifiers (e.g., `google:12345`) directly to DO instances, eliminating the need for a separate KV registry.
- **Data Isolation:** Ensure each user/tenant has a dedicated SQLite file within their DO for maximum privacy and performance.

## 🔐 Phase 2: High-Performance Auth

- **Stateful Sessions:** Move session logic into DO memory for <10ms validation.
- **OAuth Handlers:** Centralize OAuth callbacks to update the specific User DO via internal fetch requests.
- **Account Switching:** Handle multi-tenant access by allowing a User DO to "point" to multiple Account DOs.

## 📈 Phase 3: Real-time Features

- **WebSocket Integration:** Use DO's native WebSocket support to push live "Badge Awarded" alerts to the frontend.
- **SQL Analytics:** Run local SQL queries within the DO to generate per-user transaction reports and audit logs.

## 🛠️ Phase 4: Modernized UI Injection

- **Edge Proxying:** Continue using `HTMLRewriter` to inject the `<power-strip>`, but pull the user state directly from the warm Durable Object.
39 changes: 39 additions & 0 deletions specs/accounts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Team & Account Management

## Overview
StartupAPI uses a multi-tenant architecture where users belong to "Accounts". An Account acts as a container for data, subscriptions, and team members, effectively allowing a single user to participate in multiple organizations or workspaces.

## Key Components

### 1. Account Entity
* **Class**: `Account` (`classes/Account.php`)
* **Role**: The primary unit of tenancy and billing.
* **Attributes**:
* `id`: Unique identifier.
* `name`: Account name.
* `plan`: Current subscription plan.
* `active`: Status flag.

### 2. User-Account Relationship
* **Many-to-Many**: A user can belong to multiple accounts; an account can have multiple users.
* **Roles**:
* `Account::ROLE_USER` (0): Standard member.
* `Account::ROLE_ADMIN` (1): Account administrator (can manage billing and users).
* **Context**: Users switch between accounts. `User::getCurrentAccount()` retrieves the active context.

### 3. Invitations
* **Class**: `Invitation` (`classes/Invitation.php`)
* **Functionality**: Allows adding users to the system or specific accounts.
* **Flows**:
* **Admin Invite**: System admins invite users to the platform.
* **Account Invite**: Account admins invite members to their team.
* **Data**: Stores `code`, `issuer`, `recipient_email`, `target_account_id`.

## Workflows
* **Creation**: Every new user gets a personal Account by default.
* **Switching**: Users can switch context via the UI (usually top navigation).
* **Membership**: Account admins can add/remove users via the Account Settings page.

## Security
* **Isolation**: Data queries should be scoped to the `current_account` to ensure tenant isolation.
* **Permissions**: Only Account Admins can modify billing settings or plan subscriptions.
32 changes: 32 additions & 0 deletions specs/admin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Administrative Control

## Overview
The Admin Panel provides a centralized interface for platform owners to manage users, accounts, subscriptions, and system settings. It is secured to allow access only to users with global administrative privileges.

## Key Components

### 1. Admin Menu System
* **Class**: `MenuElement` (Abstract) and subclasses in `admin/adminMenus.php`.
* **Structure**: Hierarchical menu defining the admin navigation.
* **Features**:
* Supports nested sub-menus.
* Handles active state highlighting.
* Can disable menu items with "Coming soon" tooltips.

### 2. User & Account Administration
* **Users**: (`admin/users.php`) List, search, and edit user details.
* **Accounts**: (`admin/accounts.php`) Manage account statuses, view details, and intervene in billing issues.
* **Impersonation**: Admins can log in as any user to reproduce bugs or assist with configuration.

### 3. Subscription Management
* **Plans**: (`admin/plans.php`) View and edit subscription plans.
* **Outstanding Payments**: (`admin/outstanding.php`) Monitor failed charges and overdue accounts.
* **Transaction Logs**: (`admin/transaction_log.php`) Audit trail of all financial transactions.

### 4. System Settings & Modules
* **Settings**: (`admin/settings.php`) General platform configuration.
* **Modules**: (`admin/modules.php`) Enable/disable and configure system modules (Authentication, Payment, etc.).

## Security
* **Access Control**: All admin pages verify that the current user has global admin privileges (`Account::ROLE_ADMIN` context on the system account or specific flag).
* **Audit**: Critical actions are logged.
34 changes: 34 additions & 0 deletions specs/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Developer Platform / API

## Overview
StartupAPI provides a RESTful API (v1) to allow external applications and client-side frontends to interact with the platform. It features a structured endpoint system, parameter validation, and authentication.

## Key Components

### 1. Endpoint Architecture
* **Base Class**: `Endpoint` (`classes/API/Endpoint.php`).
* **Registration**: Endpoints are registered to a namespace and HTTP method via `Endpoint::register()`.
* **Discovery**: `api.php` handles routing based on the URL structure (e.g., `/api/v1/user`).

### 2. Request Handling
* **Routing**: Logic in `Endpoint::getEndpoint()` resolves the URL slug to a specific handler.
* **Parameters**:
* **Definition**: Endpoints define expected parameters (`Parameter` class).
* **Validation**: Built-in type checking and required/optional validation.
* **Parsing**: `parseURLEncoded` helper for processing input.

### 3. Authentication & Security
* **Base Class**: `AuthenticatedEndpoint`.
* **Mechanism**: automatically checks for a valid session or API token before processing the request.
* **Exceptions**:
* `UnauthenticatedException` (401)
* `UnauthorizedException` (403)
* `MethodNotAllowedException`

### 4. Core Endpoints
* **Namespace**: `v1` (configurable).
* **User**: `v1/User/Get.php` - Retrieve current user details.
* **Accounts**: `v1/Accounts.php` - List and manage user accounts.

## Documentation
* **Swagger/OpenAPI**: The project includes tools (`tools/swagger_validate.py`) and UI (`swagger-ui/`) to generate and display interactive API documentation.
35 changes: 35 additions & 0 deletions specs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# System Architecture & Utilities

## Overview
StartupAPI is built as a modular PHP application, designed for flexibility and rapid development. It employs a "Pluggable" architecture for core features and relies on established libraries for templating and frontend presentation.

## Core Architecture

### 1. Initialization & Bootstrapping
* **Entry Point**: `global.php` initializes the environment, loads configuration (`users_config.php`), and starts the session.
* **Main Class**: `StartupAPI` (`classes/StartupAPI.php`) serves as the central static accessor for global state and helper methods.
* **Autoloading**: Uses standard `require_once` patterns and Composer/library autoloaders where applicable.

### 2. Module System
* **Base Class**: `StartupAPIModule`.
* **Concept**: Functionality like Authentication, Payments, and Emailing are encapsulated in modules.
* **Registry**: `UserConfig::$all_modules` holds the list of active modules.
* **Extensibility**: Developers can create new modules by extending the base class and registering them in the config.

### 3. Frontend & Templating
* **Engine**: **Twig** is the primary templating engine (`twig/`).
* **Themes**: Support for multiple themes (`themes/awesome`, `themes/classic`).
* **UI Framework**: Heavy reliance on **Bootstrap** (v2/v3) for responsive layout and components.
* **Assets**: `bootswatch` integration allows for easy visual customization.

### 4. Utilities
* **Database Migration**: `dbupgrade.php` manages schema versioning and updates, ensuring the database stays in sync with the code.
* **Cron**: `cron.php` handles scheduled background tasks, essential for subscription billing and maintenance.
* **Dependency Check**: `depcheck.php` verifies that the server environment meets all requirements.

## File Structure
* `classes/`: Core logic and business entities.
* `modules/`: Pluggable functional blocks.
* `admin/`: Administrative interface logic.
* `themes/` & `view/`: Presentation layer.
* `controller/`: Request handling logic (MVC pattern).
51 changes: 51 additions & 0 deletions specs/billing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Subscription & Billing Engine

## Overview
The Subscription & Billing engine provides a flexible system for monetizing the application. It supports multiple subscription plans, varying payment schedules, and abstract payment gateways.

## Key Components

### 1. Plans
* **Class**: `Plan` (`classes/Plan.php`)
* **Definition**: Represents a subscription tier (e.g., "Basic", "Pro").
* **Attributes**:
* `slug`: Unique identifier.
* `name`: Display name.
* `capabilities`: Feature flags enabled for this plan.
* `downgrade_to_slug`: Fallback plan upon cancellation.
* `grace_period`: Days to wait for payment before downgrading.
* **Hooks**: `account_activate_hook` and `account_deactivate_hook` for custom logic during plan changes.

### 2. Payment Schedules
* **Class**: `PaymentSchedule` (`classes/PaymentSchedule.php`)
* **Definition**: Defines how often and how much a user is charged for a plan.
* **Attributes**:
* `charge_amount`: Cost per period.
* `charge_period`: Frequency of billing (in days).
* `is_default`: Default schedule for a plan.

### 3. Payment Engines
* **Class**: `PaymentEngine` (`classes/PaymentEngine.php`)
* **Role**: Abstract interface for payment providers.
* **Implementations**:
* **Stripe**: Credit card processing.
* **External**: Manual or off-platform payments.
* **Functionality**: Handles charge requests, recurrent billing setup, and webhook processing.

### 4. Account Billing State
* **Management**: Handled within the `Account` class.
* **States**:
* Active plan.
* Next plan (scheduled change).
* Outstanding balance.
* **Lifecycle**:
* **Upgrades/Downgrades**: Handled with proration logic.
* **Cancellation**: Reverts to the "downgrade" plan (usually Free) after the current period or grace period.

## Configuration
* **Plan Definition**: Plans and schedules are defined in `users_config.php` passed to `Plan::init()`.
* **Gateways**: Credentials for providers like Stripe are configured in `UserConfig`.

## User Interface
* **Plans Page** (`plans.php`): Displays available plans and allows users to subscribe or switch.
* **Billing History**: Users can view past transactions and receipts (managed by `Account` and `TransactionLogger`).
42 changes: 42 additions & 0 deletions specs/contributors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Project Contributors by Feature

This document outlines the primary contributors for each major feature of the StartupAPI project, based on git commit history.

## Summary
**Sergey Chernyshev** is the primary architect and developer across all components of the system.
**whale2 (whale)** and **Alex Druk (Alex)** have made targeted contributions to specific modules.

## Detailed Breakdown

### 1. User Identity & Access Management (IAM)
* **Sergey Chernyshev**: 179 commits
* *Note: Sole contributor to the core IAM logic.*

### 2. Subscription & Billing
* **Sergey Chernyshev**: 35 commits
* **whale2 (whale)**: 12 commits
* *Note: Significant collaboration on the billing engine.*

### 3. Team & Account Management
* **Sergey Chernyshev**: 42 commits
* *Note: Sole contributor.*

### 4. Gamification & Engagement
* **Sergey Chernyshev**: 16 commits
* **Alex Druk**: 1 commit
* *Note: Primarily Sergey, with minor input from Alex.*

### 5. Administrative Control (Admin Panel)
* **Sergey Chernyshev**: 227 commits
* **whale2**: 17 commits
* *Note: Heavy collaboration on the admin interface.*

### 6. Developer Platform / API
* **Sergey Chernyshev**: 23 commits
* *Note: Sole contributor.*

### 7. System Architecture
* **Sergey Chernyshev**: 107 commits
* **whale2 (whale)**: 12 commits
* **Alex Druk (Alex)**: 3 commits
* *Note: Core system design was led by Sergey with contributions from others.*
70 changes: 70 additions & 0 deletions specs/features.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Feature Flags & Rollout Framework

## Overview

The Feature Framework allows developers to decouple code deployment from feature release. It supports granular feature flags, gradual rollouts, subscription-based feature gating, and emergency circuit breakers (load shedding) to ensure system stability.

## Key Components

### 1. Feature Entity

- **Class**: `Feature` (`classes/Feature.php`)
- **Purpose**: Represents a distinct piece of functionality that can be toggled.
- **Attributes**:
- `id`: Unique numeric identifier (constant).
- `name`: Human-readable display name.
- `enabled`: Global master switch (must be true for feature to work anywhere).
- `rolled_out_to_all_users`: If true, enables the feature globally (overrides specific settings).
- `emergency_shutdown`: Temporary kill switch to disable the feature strictly.

### 2. Stability & Load Shedding

- **Shutdown Priority**: Each feature has a `shutdown_priority` (int).
- Used to automate or guide the disabling of non-essential features during system overload.
- Lower priority features (or specifically assigned priorities) can be sacrificed to keep core functionality running.

### 3. Resolution Hierarchy

The system determines if a feature is active for a specific context (User or Account) based on the following precedence:

1. **Emergency Check**: If `emergency_shutdown` is true or global `enabled` is false → **DISABLED**.
2. **Global Rollout**: If `rolled_out_to_all_users` is true → **ENABLED**.
3. **Context Specifics**:
- **Accounts**:
1. **Plan**: Checked via `Plan::hasFeatureEnabled`.
2. **Database Override**: Checked against `u_account_features`.
- **Users**:
1. **Propagation**: If the User's _Current Account_ has the feature enabled, the User inherits it.
2. **Database Override**: Checked against `u_user_features`.

## Usage & Workflows

### Definition

Features are typically defined in the global configuration (e.g., `users_config.php`) using constants for IDs to ensure they are available at bootstrap.

```php
define('FEATURE_NEW_DASHBOARD', 101);
new Feature(FEATURE_NEW_DASHBOARD, 'New Dashboard', true, false);
```

### Checking Availability

Developers check for feature availability before rendering UI elements or executing logic.

```php
// Check for a user
if ($user->hasFeature(FEATURE_NEW_DASHBOARD)) {
// Show new dashboard
}

// Check for an account (e.g. during billing or background tasks)
if ($feature->isEnabledForAccount($account)) {
// Process feature logic
}
```

### Management

- **Enabling/Disabling**: Methods like `enableForAccount`, `removeForAccount`, `enableForUser`, and `removeForUser` manage specific overrides in the database.
- **Reporting**: `getUserCount()` and `getAccountCount()` provide usage statistics for specific features.
36 changes: 36 additions & 0 deletions specs/gamification.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Gamification & Engagement

## Overview
This module increases user retention and engagement through a badge-based achievement system and detailed campaign tracking for attribution.

## Key Components

### 1. Badge System
* **Class**: `Badge` (`classes/Badge.php`)
* **Concept**: Awards users for specific actions or milestones.
* **Structure**:
* `id` & `slug`: Unique identifiers.
* `set`: Grouping for badges.
* `title` & `description`: User-facing text.
* `hint`: Clue on how to unlock the badge.
* `calls_to_action`: Messages encouraging further progress.
* **Triggers**: `BadgeActivityTrigger` allows defining events that automatically award badges.
* **Levels**: Badges can have multiple levels, supporting progressive achievement.

### 2. Campaign Tracking
* **Class**: `CampaignTracker` (`classes/CampaignTracker.php`)
* **Purpose**: Tracks marketing effectiveness.
* **Functionality**:
* **UTM Parameters**: Captures `utm_source`, `utm_medium`, `utm_campaign`, etc., from the URL on landing.
* **Referrer**: Captures `HTTP_REFERER` on the first visit.
* **Persistence**: Stores data in cookies until registration, then associates it with the created User record.
* **Configuration**: `UserConfig::$campaign_variables` defines which URL parameters to track.

### 3. Cohorts
* **Class**: `Cohort` (`classes/Cohort.php`)
* **Purpose**: Groups users based on signup date or other shared characteristics for analysis.
* **Usage**: Helps in analyzing retention rates and feature usage over time.

## User Experience
* **Notifications**: Users are notified when badges are unlocked.
* **Profile**: Badges are displayed on the user's public or private profile (`show_badge.php`).
Loading