# AppManager Module & Boilerplate Integration Documentation

## 1. Introduction

This document outlines the functionality of the AppManager Module and its integration with a target Boilerplate Application. The primary goal is to provide a robust system for licensing, activation, and secure distribution of application files and updates.

### 1.1. Purpose of AppManager Module (Server-Side)

The AppManager module acts as a central server for:

- Managing different scripts/applications and their versions.
- Creating and managing licenses (internal, CodeCanyon/Envato, subscription-based).
- Verifying purchase codes against the Envato API.
- Tracking license activations and their associated domains/IPs.
- Securely serving downloadable files (e.g., application updates, core components) to activated boilerplate instances.
- Providing API endpoints for boilerplate applications to interact with for activation and file downloads.

### 1.2. Purpose of Boilerplate Integration (Client-Side)

The boilerplate application integrates with the AppManager module to:

- Implement a secure installation and activation wizard for new instances.
- Verify its license against the AppManager upon installation and periodically thereafter.
- Ensure it's running on an authorized domain.
- Download essential core files or updates from the AppManager after successful activation.
- Restrict access to the application if activation/license checks fail.

## 2. AppManager Module (Server-Side)

This section details the features and configuration of the AppManager module itself, which runs as part of your main Laravel application (e.g., `digitalvocano.co.za`).

### 2.1. Key Features Implemented

- Managed Scripts (Products): Implemented
  - CRUD operations for defining applications/scripts.
  - Fields: Name, Slug, Current Version, Description, Changelog, Status (active, beta, etc.), Envato Item ID, Is Boilerplate Core.
  - Admin UI: `/admin/appmanager/scripts`
- Downloadable Files: Implemented
  - CRUD operations for files associated with a Managed Script and version.
  - Fields: File Name, Stored File Path, Version, Target Path (for client-side placement), File Hash (SHA256), Description, Is Critical.
  - Secure storage using Laravel's filesystem (configurable disk).
  - Admin UI: Nested under Managed Scripts (e.g., `/admin/appmanager/scripts/{script_id}/files`).
- License Management: Implemented
  - CRUD operations for licenses.
  - Types: Internal, CodeCanyon, Subscription (basic structure).
  - Fields: License Key (auto-generated or manual), Script Association, Customer Info, Purchase Code (for CodeCanyon), Activation Limit, Current Activations, Status, Expiry, Support Until, Metadata (JSON for extra info like Envato license type).
  - Admin UI: `/admin/appmanager/licenses`
- Activation Logging: Implemented
  - Logs every activation attempt (success or failure).
  - Records: License, Domain, IP, Server Signature, Status, Message, Date.
  - Admin UI with filtering: `/admin/appmanager/activation-logs`
- Envato API Integration: Implemented
  - Verifies Envato purchase codes against the official API.
  - Handles various Envato API responses (success, not found, permissions error).
  - Requires Envato Personal Token with "View and search Envato sites" and "View the user’s items’ sales history" permissions.
- API Endpoints: Implemented
  - `POST /api/app-manager/activate`: For boilerplate instances to activate their license/purchase code.
  - `POST /api/app-manager/validate-license`: For boilerplate instances to periodically re-validate their license.
  - `POST /api/app-manager/download-file`: For activated boilerplate instances to download files using a short-lived, single-use (or limited-use) download token.
- Admin Dashboard Overview: Implemented
  - Shows statistics: Total Managed Scripts, Total Licenses Issued, Recent Successful Activations.
  - Located at `/admin/appmanager/scripts` (serves as the module's dashboard).

### 2.2. Configuration (`config/appmanager.php` & `.env`) Implemented

- `APPMANAGER_STORAGE_DISK`: Filesystem disk for storing downloadable files (default: `local`).
- `ENVATO_PERSONAL_TOKEN`: Your Envato API personal token.
- `APPMANAGER_DOWNLOAD_TOKEN_TTL`: Time-to-live for download tokens (minutes).
- `APPMANAGER_DOWNLOAD_TOKEN_MAX_USES`: Max uses per download token.

### 2.3. Future Enhancements / To-Do To-Do

- Automated Updates: Implement a more sophisticated mechanism for boilerplate applications to check for and apply updates (beyond simple file downloads). This might involve version comparison, update scripts, etc.
- Granular Feature Control: Allow licenses to control specific features within the boilerplate (e.g., via metadata).
- Webhook Handling:
  - Envato webhooks for license events (e.g., refunds, reversals) to automatically update license status.
  - Payment gateway webhooks if integrating subscription-based licenses directly.
- Reporting & Analytics: More detailed reports on activations, popular scripts, license expirations, etc.
- Client Portal (Optional): If AppManager serves multiple clients, a portal for them to view their purchased licenses and activations.
- Subscription Management Integration: Deeper integration with a subscription management system if the 'subscription' license type is to be fully automated.

## 3. Boilerplate Integration (Client-Side)

This section describes how a typical boilerplate application (e.g., your TALL stack application) integrates with the AppManager module.

### 3.1. Installation & Activation Flow Implemented

A multi-step wizard guides the user through the initial setup of the boilerplate:

1. Step 1: License Verification (`/install/activate-application`)
   - User provides their License Key or Envato Purchase Code.
   - User provides the primary domain for the application (e.g., `digitalvocano.co.za` or `localhost/myproject` for XAMPP).
   - The boilerplate's `BoilerplateActivationController` calls the AppManager's `/api/app-manager/activate` endpoint.
   - If successful, activation details are stored temporarily in the session, and the user proceeds to the next step.
2. Step 2: Database & Admin User Setup (`/install/setup-application`)
   - User provides database connection details (host, port, database name, username, password).
   - User creates the initial admin user account (name, email, password).
   - The `BoilerplateActivationController`:
     - Tests the database connection.
     - Updates the boilerplate's `.env` file with DB credentials.
     - Runs database migrations (`php artisan migrate --force`).
     - Creates the admin user in the database and assigns a role (e.g., 'super_admin').
3. Step 3: Finalization & Core File Download
   - The `BoilerplateActivationController`:
     - Permanently stores activation details (activation token, license key used, activated domain, license status, product version) into the boilerplate's `settings` database table.
     - Downloads essential core files (e.g., `AuthServiceProvider.php`, `custom_helpers.php`) from the AppManager using the received activation token. Note: `config/app.php` is NOT downloaded to avoid overwriting critical boilerplate-specific configurations.
     - Marks the installation as complete by setting `boilerplate_install_complete` to `true` in the `settings` table.
     - Attempts to clear relevant Laravel caches (config, etc.).
     - Logs in the newly created admin user.
     - Redirects the user to the admin dashboard.
     - Flashes a message prompting the user to delete the installation directory for security.

### 3.2. Ongoing License Verification (Middleware) Implemented

The `EnsureAppIsActivated` middleware (aliased as `app.activated`) protects the boilerplate application after installation:

- Applied to relevant route groups (e.g., admin panel, or globally with exceptions).
- Checks performed:
  1. Is `boilerplate_install_complete` set to `true` in settings?
  2. Are essential activation settings (`boilerplate_license_key`, `boilerplate_activated_domain`) present?
  3. Does the current request's domain match the `boilerplate_activated_domain` stored during activation?
  4. Periodically (cached result, e.g., every 60 minutes) calls the AppManager's `/api/app-manager/validate-license` endpoint to re-verify the license status for the current domain.
- If any check fails, the user is redirected to the installation/activation form (`/install/activate-application`) with an error message.
- Includes a development mode bypass (`BOILERPLATE_DEV_MODE_SKIP_LICENSE_CHECK` in `.env`).
- Routes necessary for the installation process itself (e.g., `/install/*`) are exempted from these checks.

### 3.3. Configuration (Boilerplate's `.env` & `config/app.php`) Implemented

The boilerplate requires these settings (primarily in `.env`, read via `config/app.php`):

- `BOILERPLATE_PRODUCT_SLUG`: Identifies the boilerplate to AppManager. (Manual setup in `.env`)
- `APPMANAGER_URL`: Base URL of the AppManager API. (Manual setup in `.env`)
- `BOILERPLATE_DEV_MODE_SKIP_LICENSE_CHECK`: (Optional) Set to `true` in local dev `.env` to bypass middleware checks.
- `LICENSE_CHECK_INTERVAL_MINUTES`: (Optional) How often the middleware re-validates the license.

The following are stored in the boilerplate's `settings` database table by the installer:

- `boilerplate_activation_token`
- `boilerplate_license_key` (the key/code used for activation)
- `boilerplate_activated_domain`
- `boilerplate_activated_version`
- `boilerplate_license_status`
- `boilerplate_install_complete` (flag set to 'true')

### 3.4. Post-Installation Security Partially Implemented

- User is prompted to delete an "installation directory" (e.g., `public/install_init_temp`) after successful setup. Currently, this is a flashed message; automated deletion is commented out due to potential permission issues.

### 3.5. User Experience Partially Implemented

- Installation/activation forms provide steps and feedback.
- Error messages guide the user if activation or setup fails.

### 3.6. Future Enhancements / To-Do (Boilerplate) To-Do

- Automated Update Mechanism: Implement logic to check for new versions with AppManager and apply updates (potentially using downloaded update packages/scripts).
- Installation Directory Deletion: Explore more robust ways to handle the deletion of the installation directory or use a marker file that gets deleted.
- Client-Side License Management UI: A section in the boilerplate's admin panel for the admin to view their current license status, expiry, support details, etc. (fetched from AppManager or local settings).
- Graceful API Downtime Handling: For the periodic license re-validation in `EnsureAppIsActivated`, implement a "grace period" if the AppManager API is temporarily unreachable, instead of immediately locking the app.
- Detailed Setup Instructions: For files like `AuthServiceProvider.php` or helpers, if they require manual registration or specific configurations post-download, provide clear instructions or automate this if possible.

## 4. Local Development & XAMPP Considerations

The system is designed to work in local development environments like XAMPP.

- AppManager URL: If the AppManager module is part of the same Laravel application as the boilerplate (common for local testing), the `APPMANAGER_URL` in the boilerplate's `.env` can often be left blank or set to the project's base URL (e.g., `http://localhost/myproject`). The `BoilerplateActivationController` has a fallback to `url('/')`.
- Domain for Activation: When activating locally, use your local development domain (e.g., `http://localhost`, `http://myproject.test`, `http://digitalvocano.co.za` if that's your local setup). The `EnsureAppIsActivated` middleware will check against this.
- Development Mode Bypass: Set `BOILERPLATE_DEV_MODE_SKIP_LICENSE_CHECK=true` in the boilerplate's `.env` to bypass the `EnsureAppIsActivated` middleware checks during development, avoiding the need to constantly activate or have the AppManager running.
- Database Setup: The installer allows manual entry of database credentials, suitable for XAMPP where you create the database and user manually.

## 5. AppManager API Reference (Brief)

The AppManager module exposes the following key API endpoints for boilerplate interaction:

Method | Endpoint | Purpose | Key Payload Fields | Success Response Fields
--- | --- | --- | --- | ---
POST | `/api/app-manager/activate` | Activates a license/purchase code for a product and domain. | `license_key` OR `purchase_code`, `product_slug`, `domain`, `server_signature` (optional) | `status: "success"`, `activation_token`, `product_info`, `license_info`
POST | `/api/app-manager/validate-license` | Periodically re-validates an existing license for a domain. | `license_key`, `product_slug`, `domain` | `status: "valid"` or `status: "invalid"`
POST | `/api/app-manager/download-file` | Downloads a specific file for an activated product. | `activation_token`, `product_slug`, `file_identifier`, `version` | File stream with `X-File-Hash` header.

Documentation last updated: {{ date("Y-m-d H:i:s") }}