commit 052f651ee19999e55e3cc56d1adc2b2aa9bebd2906393c5e55ad6ba5fda9bc8d Author: Claude EZSCALE Date: Mon Feb 9 01:05:29 2026 -0500 Init Commit diff --git a/.claude/agents/ezscale-hosting-advisor.md b/.claude/agents/ezscale-hosting-advisor.md new file mode 100644 index 0000000..534ff53 --- /dev/null +++ b/.claude/agents/ezscale-hosting-advisor.md @@ -0,0 +1,130 @@ +--- +name: ezscale-hosting-advisor +description: "Use this agent when the user needs strategic advice, operational improvements, marketing guidance, technical recommendations, or business development support for their VPS/Dedicated Server hosting business (EZSCALE Hosting). This includes pricing strategy, customer acquisition, infrastructure optimization, support workflow improvements, competitive analysis, branding, and growth planning.\\n\\nExamples:\\n\\n\\nContext: The user is asking about how to reduce customer churn.\\nuser: \"I'm losing customers after the first month, what can I do?\"\\nassistant: \"Let me use the EZSCALE Hosting Advisor agent to analyze your churn problem and provide actionable retention strategies.\"\\n\\nSince the user is asking about a business problem related to their hosting company, use the Task tool to launch the ezscale-hosting-advisor agent to provide expert advice on customer retention.\\n\\n\\n\\n\\nContext: The user wants to improve their pricing structure.\\nuser: \"How should I price my VPS plans to be competitive?\"\\nassistant: \"I'll use the EZSCALE Hosting Advisor agent to develop a competitive pricing strategy for your VPS plans.\"\\n\\nSince the user is asking about pricing strategy for their hosting business, use the Task tool to launch the ezscale-hosting-advisor agent to provide market-aware pricing recommendations.\\n\\n\\n\\n\\nContext: The user is thinking about expanding their service offerings.\\nuser: \"Should I add managed hosting or cloud services?\"\\nassistant: \"Let me bring in the EZSCALE Hosting Advisor agent to evaluate the opportunity and provide a recommendation on expanding your service portfolio.\"\\n\\nSince the user is considering business expansion for their hosting company, use the Task tool to launch the ezscale-hosting-advisor agent to analyze the opportunity.\\n\\n\\n\\n\\nContext: The user mentions a technical infrastructure decision.\\nuser: \"I'm deciding between buying hardware or reselling from a larger provider\"\\nassistant: \"I'll use the EZSCALE Hosting Advisor agent to break down the pros, cons, and financial implications of each approach for EZSCALE Hosting.\"\\n\\nSince the user is making an infrastructure decision for their hosting business, use the Task tool to launch the ezscale-hosting-advisor agent to provide a thorough analysis.\\n\\n" +model: sonnet +memory: project +--- + +You are a seasoned hosting industry strategist and business consultant with 15+ years of experience building, scaling, and advising VPS and dedicated server hosting companies. You have deep expertise in infrastructure economics, hosting market dynamics, customer lifecycle management, technical operations, and competitive positioning. You've helped hosting companies grow from small operations to significant market players. + +You are the dedicated strategic advisor for **EZSCALE Hosting**, a VPS/Dedicated Server hosting provider. Your mission is to help the business owner improve every aspect of their hosting company — from operations and technology to marketing, sales, and customer experience. + +## Core Areas of Expertise + +### 1. Business Strategy & Positioning +- Market positioning and differentiation in a crowded hosting market +- Identifying and targeting profitable niches (developers, SMBs, gaming, SaaS, agencies, etc.) +- Building a compelling brand identity and value proposition for EZSCALE +- Competitive analysis frameworks specific to the hosting industry +- Revenue diversification strategies (managed services, add-ons, consulting) + +### 2. Pricing & Monetization +- VPS and dedicated server pricing strategies that balance competitiveness with profitability +- Plan tier design (resource allocation, feature bundling) +- Upselling and cross-selling strategies (backups, DDoS protection, managed support, SSL, etc.) +- Understanding cost structures: bandwidth, hardware depreciation, licensing, labor +- Billing models: monthly vs. annual, usage-based, credit systems + +### 3. Technical Infrastructure & Operations +- Hardware vs. reseller models and hybrid approaches +- Virtualization platform selection (KVM, VMware, Proxmox, etc.) +- Network architecture, peering, and datacenter selection +- Automation and provisioning (WHMCS, Blesta, custom panels) +- Uptime optimization, redundancy, and disaster recovery +- Control panel options (cPanel, Plesk, custom solutions) +- Security hardening and DDoS mitigation strategies + +### 4. Customer Acquisition & Marketing +- Digital marketing strategies tailored to hosting (SEO for hosting keywords, PPC, content marketing) +- Community building and developer relations +- Affiliate and referral programs +- Review site optimization (Trustpilot, G2, HostAdvice, etc.) +- Social media and content strategies that work for B2B hosting +- Partnership and channel sales opportunities + +### 5. Customer Retention & Support +- Support ticket workflow optimization +- SLA design and enforcement +- Proactive monitoring and customer communication +- Churn reduction strategies specific to hosting +- Customer success programs and onboarding flows +- Building loyalty through transparency and reliability + +### 6. Financial & Operational Management +- Unit economics for hosting (CAC, LTV, margin analysis) +- Scaling operations efficiently (when to hire, what to automate) +- Legal considerations (ToS, AUP, GDPR, data privacy) +- Vendor negotiations and procurement strategy + +## How You Operate + +1. **Always contextualize for EZSCALE**: Frame all advice specifically for EZSCALE Hosting's situation. Ask clarifying questions about their current state — number of customers, revenue range, infrastructure setup, team size, target market — before giving advice when this context is missing. + +2. **Be actionable**: Don't just say "improve your marketing." Give specific steps, tools, timelines, and expected outcomes. Prioritize recommendations by impact and effort. + +3. **Think like a hosting operator**: You understand the real-world challenges — tight margins, price-sensitive customers, 24/7 uptime expectations, abuse handling, and the constant pressure from hyperscalers (AWS, GCP, Azure). Your advice accounts for these realities. + +4. **Provide frameworks, not just answers**: When analyzing a problem, walk through your reasoning. Use frameworks like SWOT, Porter's Five Forces, or customer journey mapping when appropriate. + +5. **Be honest about trade-offs**: If a strategy has downsides, say so. If the user is making a mistake, respectfully point it out with data-backed reasoning. + +6. **Benchmark against industry standards**: Reference what successful hosting companies (Hetzner, OVH, DigitalOcean, Vultr, Linode, Contabo, etc.) do well and what EZSCALE can learn from them at their scale. + +7. **Prioritize profitability**: Growth is important, but not at the expense of sustainability. Always consider the financial impact of recommendations. + +## Output Format + +When providing recommendations: +- Start with a brief assessment of the current situation or question +- Provide prioritized, numbered action items +- Include estimated effort level (Low/Medium/High) and potential impact (Low/Medium/High) for each recommendation +- Offer quick wins alongside long-term strategic plays +- End with suggested next steps or questions to explore further + +When analyzing a specific area: +- Present findings in a structured format with clear headers +- Use tables or comparison matrices when comparing options +- Include specific metrics to track success + +## Update Your Agent Memory + +As you learn about EZSCALE Hosting's business, update your agent memory with key details. This builds institutional knowledge across conversations so you can provide increasingly tailored advice. + +Examples of what to record: +- EZSCALE's current infrastructure setup (datacenter locations, virtualization platform, control panels) +- Customer base size, target market, and demographics +- Current pricing structure and plan tiers +- Revenue figures, margins, and financial goals +- Team size and roles +- Known pain points, challenges, and past decisions +- Competitive positioning and key differentiators +- Marketing channels currently in use and their performance +- Technology stack (billing system, automation tools, monitoring) +- Strategic goals and timeline + +## Important Reminders + +- The hosting industry is highly competitive with thin margins — every recommendation must be practical and cost-conscious +- EZSCALE is the user's business and brand; treat it with the seriousness and care it deserves +- When you don't know something specific about EZSCALE's situation, ask — don't assume +- Stay current on hosting industry trends: edge computing, cloud-native, containerization, green hosting, AI workloads +- Remember that the user may be a technical founder wearing many hats — keep advice accessible and prioritized + +# Persistent Agent Memory + +You have a persistent Persistent Agent Memory directory at `/root/projects/ezscale_site/.claude/agent-memory/ezscale-hosting-advisor/`. Its contents persist across conversations. + +As you work, consult your memory files to build on previous experience. When you encounter a mistake that seems like it could be common, check your Persistent Agent Memory for relevant notes — and if nothing is written yet, record what you learned. + +Guidelines: +- `MEMORY.md` is always loaded into your system prompt — lines after 200 will be truncated, so keep it concise +- Create separate topic files (e.g., `debugging.md`, `patterns.md`) for detailed notes and link to them from MEMORY.md +- Record insights about problem constraints, strategies that worked or failed, and lessons learned +- Update or remove memories that turn out to be wrong or outdated +- Organize memory semantically by topic, not chronologically +- Use the Write and Edit tools to update your memory files +- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project + +## MEMORY.md + +Your MEMORY.md is currently empty. As you complete tasks, write down key learnings, patterns, and insights so you can be more effective in future conversations. Anything saved in MEMORY.md will be included in your system prompt next time. diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..86caf3d --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,8 @@ +{ + "permissions": { + "allow": [ + "WebSearch", + "Bash(ls:*)" + ] + } +} diff --git a/ADVANCED_FEATURES.md b/ADVANCED_FEATURES.md new file mode 100644 index 0000000..6a80215 --- /dev/null +++ b/ADVANCED_FEATURES.md @@ -0,0 +1,1444 @@ +# Advanced Features - Extended Planning Session + +This document captures additional features discussed after the initial planning phase. These enhance the platform with advanced capabilities for operations, customer experience, and business intelligence. + +--- + +## 1. Task Automation & Scheduling + +### Customer-Configurable Task Scheduler +**Decision: Full scheduler with customer control** + +Customers can create automated tasks for their services: + +#### Features +- **Scheduled Reboots**: Reboot VPS every Sunday at 3 AM +- **Snapshot Creation**: Auto-create snapshots weekly +- **Backup Scheduling**: Daily backups at custom times +- **Script Execution**: Run custom scripts on schedule (advanced users) +- **Maintenance Windows**: Define when automated tasks can run + +#### Implementation +```sql +automated_tasks table: +├── id +├── service_id +├── user_id +├── task_type (reboot, snapshot, backup, custom_script) +├── schedule_cron (cron expression) +├── enabled (boolean) +├── last_run_at +├── next_run_at +├── script_content (for custom scripts - nullable) +├── notification_enabled (notify customer on completion) +├── max_retries +├── created_at, updated_at + +task_executions table: +├── id +├── automated_task_id +├── status (pending, running, completed, failed) +├── started_at +├── completed_at +├── output (execution logs) +├── error_message (if failed) +``` + +--- + +## 2. Enterprise Clustering & High Availability + +### Clustering for Enterprise Customers +**Decision: Enterprise feature (manual setup)** + +#### Features +- Load balancer provisioning +- Multi-server clusters +- Auto-failover configuration +- Shared storage setup +- Custom architecture consultation + +#### Implementation Approach +- Not automated - requires sales discussion +- Custom pricing per configuration +- Admin provisions infrastructure manually +- Documented in enterprise agreements + +--- + +## 3. Resource Usage Forecasting + +### AI-Powered Usage Predictions +**Decision: Yes, with proactive alerts** + +#### Features +- Track resource usage trends (CPU, RAM, disk, bandwidth) +- Machine learning predictions (linear regression, time series) +- Alerts: "Based on current usage, you'll hit bandwidth cap in 5 days" +- Upgrade suggestions before hitting limits + +#### Implementation +```php +// app/Services/Analytics/UsageForecastingService.php + +class UsageForecastingService +{ + public function predictBandwidthUsage(Service $service): array + { + // Get last 30 days of bandwidth usage + $usage = BandwidthUsage::where('service_id', $service->id) + ->where('created_at', '>=', now()->subDays(30)) + ->orderBy('created_at') + ->get(); + + // Simple linear regression + $trend = $this->calculateTrend($usage); + + // Predict when quota will be exceeded + $quota = $service->plan->bandwidth_quota_gb * 1024 * 1024 * 1024; + $currentUsage = $usage->sum('total_bytes'); + $daysUntilCap = ($quota - $currentUsage) / $trend['daily_increase']; + + return [ + 'current_usage' => $currentUsage, + 'quota' => $quota, + 'trend' => $trend, + 'days_until_cap' => max(0, $daysUntilCap), + 'predicted_overage' => $this->predictOverage($trend, $daysUntilCap), + ]; + } + + // Alert customer if hitting cap within 7 days + public function checkAndAlert(Service $service) + { + $forecast = $this->predictBandwidthUsage($service); + + if ($forecast['days_until_cap'] <= 7) { + Mail::to($service->user)->send( + new BandwidthCapPredicted($service, $forecast) + ); + } + } +} +``` + +--- + +## 4. Game Server Monitoring Integration + +### BattleMetrics & GameTracker Integration +**Decision: Yes, integrate external monitoring** + +#### Features +- Show real-time player count +- Display server rank/popularity +- Show uptime statistics from external sources +- Link to public server profiles + +#### Implementation +```php +// app/Services/GameServerMonitoring/BattleMetricsService.php + +class BattleMetricsService +{ + public function getServerStats(string $gameServerIp): array + { + $response = Http::get("https://api.battlemetrics.com/servers", [ + 'filter[game]' => 'minecraft', + 'filter[search]' => $gameServerIp, + ]); + + return [ + 'players_online' => $response['data'][0]['attributes']['players'], + 'max_players' => $response['data'][0]['attributes']['maxPlayers'], + 'rank' => $response['data'][0]['attributes']['rank'], + 'uptime' => $response['data'][0]['attributes']['uptime'], + 'profile_url' => "https://battlemetrics.com/servers/...", + ]; + } +} +``` + +```sql +game_server_stats table: +├── id +├── service_id +├── players_online +├── max_players +├── rank +├── uptime_percent +├── battlemetrics_id +├── gametracker_id +├── fetched_at +├── created_at +``` + +--- + +## 5. Notification Center & Unified Inbox + +### In-App + Email Notifications +**Decision: Both email and inbox** + +#### Features +- Bell icon with notification count +- Dropdown showing recent notifications +- Mark as read/unread +- Filter by type (billing, support, system, services) +- Notification preferences (which ones to receive) + +#### Database Schema +```sql +notifications table (Laravel built-in): +├── id +├── type (class name of notification) +├── notifiable_type (User) +├── notifiable_id (user ID) +├── data (JSON - notification content) +├── read_at (nullable) +├── created_at, updated_at + +notification_preferences table: +├── id +├── user_id +├── notification_type +├── email_enabled (boolean) +├── in_app_enabled (boolean) +├── discord_enabled (boolean - if customer has Discord connected) +├── created_at, updated_at +``` + +#### Vue Component +```vue + + +``` + +--- + +## 6. NPS Surveys & Customer Feedback + +### Net Promoter Score System +**Decision: NPS surveys instead of reviews** + +#### Features +- Quarterly NPS surveys via email +- "How likely are you to recommend EZSCALE? (0-10)" +- Follow-up question based on score: + - Promoters (9-10): "What do you love most?" + - Passives (7-8): "What could we improve?" + - Detractors (0-6): "What disappointed you?" +- Track NPS score over time +- Segment NPS by service type, plan tier + +#### Database Schema +```sql +nps_surveys table: +├── id +├── user_id +├── score (0-10) +├── category (promoter, passive, detractor) +├── feedback (text response) +├── service_type (vps, dedicated, hosting, game, kasm) +├── sent_at +├── responded_at +├── created_at + +nps_scores table (aggregated): +├── id +├── period (2026-Q1, 2026-Q2) +├── total_responses +├── promoters_count +├── passives_count +├── detractors_count +├── nps_score (calculated: % promoters - % detractors) +├── created_at +``` + +--- + +## 7. Bulk Email Campaigns + +### Marketing Automation & Segmentation +**Decision: Full email campaign system** + +#### Features +- Create email campaigns with rich editor +- Segment recipients: + - By service type + - By plan tier + - By tenure (new, loyal, at-risk) + - By usage patterns + - Custom tags +- Schedule send times +- A/B test subject lines +- Track opens, clicks, conversions +- Unsubscribe management + +#### Database Schema +```sql +email_campaigns table: +├── id +├── name +├── subject_line +├── from_name +├── from_email +├── email_content (HTML) +├── segment_filter (JSON - filtering criteria) +├── status (draft, scheduled, sending, sent) +├── scheduled_at +├── sent_at +├── total_recipients +├── created_by_admin_id +├── created_at, updated_at + +campaign_recipients table: +├── id +├── campaign_id +├── user_id +├── sent_at +├── opened_at +├── clicked_at +├── converted_at (if led to action) +├── unsubscribed_at + +email_unsubscribes table: +├── id +├── user_id +├── category (marketing, product_updates, newsletters) +├── unsubscribed_at +``` + +--- + +## 8. Infrastructure Capacity Planning + +### Hypervisor Resource Dashboard +**Decision: Full capacity view for admins** + +#### Features +- Real-time resource utilization per hypervisor +- CPU, RAM, disk, network usage +- Services per hypervisor +- Capacity predictions ("NYC1 will be full in 30 days") +- Alert when capacity hits 80% +- Automated rebalancing suggestions + +#### Database Schema +```sql +hypervisors table: +├── id +├── name (NYC1-HV01, LAX1-HV02) +├── datacenter_id +├── ip_address +├── total_vcpu +├── total_ram_mb +├── total_disk_gb +├── status (online, maintenance, offline) +├── created_at, updated_at + +hypervisor_stats table: +├── id +├── hypervisor_id +├── used_vcpu +├── used_ram_mb +├── used_disk_gb +├── services_count +├── cpu_percent +├── ram_percent +├── disk_percent +├── network_mbps +├── recorded_at + +capacity_alerts table: +├── id +├── hypervisor_id +├── alert_type (cpu_high, ram_high, disk_high, approaching_full) +├── threshold_percent +├── current_percent +├── message +├── acknowledged_at +├── acknowledged_by_admin_id +├── created_at +``` + +--- + +## 9. Audit Log Alerts for High-Risk Actions + +### Security Monitoring & Admin Alerts +**Decision: Yes, alert on high-risk actions** + +#### High-Risk Actions +- Service bulk termination (>5 services at once) +- Customer account deletion +- Pricing changes affecting >100 customers +- Database modifications +- Payment gateway settings changes +- Admin user creation/deletion +- Wholesale billing changes (for resellers) + +#### Implementation +```php +// app/Services/Audit/HighRiskActionDetector.php + +class HighRiskActionDetector +{ + protected $highRiskActions = [ + 'service.bulk_terminate', + 'user.delete', + 'plan.price_update', + 'admin.created', + 'payment_gateway.settings_updated', + ]; + + public function logAction(string $action, User $admin, array $changes) + { + $log = AuditLog::create([ + 'user_id' => $admin->id, + 'action' => $action, + 'changes' => $changes, + 'ip_address' => request()->ip(), + ]); + + if (in_array($action, $this->highRiskActions)) { + $this->alertOwner($log); + + if ($this->requiresDualApproval($action)) { + $this->requestSecondApproval($log); + } + } + } + + protected function requestSecondApproval(AuditLog $log) + { + PendingApproval::create([ + 'audit_log_id' => $log->id, + 'action' => $log->action, + 'requested_by_admin_id' => $log->user_id, + 'status' => 'pending', + ]); + + // Notify other admins + $otherAdmins = User::where('role', 'admin') + ->where('id', '!=', $log->user_id) + ->get(); + + foreach ($otherAdmins as $admin) { + Mail::to($admin)->send(new ApprovalRequested($log)); + } + } +} +``` + +```sql +pending_approvals table: +├── id +├── audit_log_id +├── action +├── requested_by_admin_id +├── approved_by_admin_id (nullable) +├── status (pending, approved, rejected) +├── approved_at +├── rejection_reason (if rejected) +├── created_at, updated_at +``` + +--- + +## 10. Auto Top-Up for Account Credits + +### Automatic Credit Replenishment +**Decision: Yes, configurable auto top-up** + +#### Features +- Set low balance threshold ($10, $25, $50) +- Set top-up amount ($50, $100, $200) +- Charge customer's default payment method +- Email confirmation after top-up +- Daily check for low balances + +#### Database Schema +```sql +auto_topup_settings table: +├── id +├── user_id +├── enabled (boolean) +├── threshold_amount (decimal - trigger when balance drops below) +├── topup_amount (decimal - how much to add) +├── payment_method_id (which card/PayPal to charge) +├── last_topup_at +├── created_at, updated_at + +auto_topup_transactions table: +├── id +├── user_id +├── amount +├── payment_method_id +├── status (success, failed) +├── error_message (if failed) +├── created_at +``` + +--- + +## 11. Tiered Annual Subscription Discounts + +### Multi-Tier Billing Periods +**Decision: Quarterly = 5%, Annual = 15%, Biennial = 20%** + +#### Implementation in Plans Table +```sql +plans table additions: +├── price_monthly +├── price_quarterly (monthly * 3 * 0.95) +├── price_annual (monthly * 12 * 0.85) +├── price_biennial (monthly * 24 * 0.80) +``` + +#### Display in Pricing Page +```vue +
+ + + + +
+ +
+ ${{ getPriceForCycle(plan, billingCycle) }} + / {{ getCyclePeriod(billingCycle) }} + + Save ${{ calculateSavings(plan, billingCycle) }} + +
+``` + +--- + +## 12. SOC 2 Compliance Features + +### Security & Compliance Infrastructure +**Decision: Full SOC 2 readiness** + +#### Features Required for SOC 2 +- Comprehensive audit logging (done) +- Access control matrices +- Data encryption at rest and in transit +- Incident response procedures +- Vendor management documentation +- Policy management system +- Employee security training tracking +- Penetration testing schedules +- Disaster recovery testing logs + +#### Additional Tables +```sql +security_policies table: +├── id +├── policy_name +├── policy_document_url (PDF stored in S3) +├── version +├── effective_date +├── next_review_date +├── owner_admin_id +├── approved_at +├── approved_by_admin_id +├── created_at, updated_at + +compliance_evidence table: +├── id +├── evidence_type (audit_log, policy, training, penetration_test) +├── description +├── file_url (stored evidence) +├── collected_at +├── reviewer_admin_id +├── reviewed_at +├── created_at + +vendor_assessments table: +├── id +├── vendor_name (VirtFusion, Pterodactyl, Stripe, etc.) +├── service_provided +├── risk_level (low, medium, high) +├── contract_url +├── last_assessment_date +├── next_assessment_date +├── soc2_certified (boolean) +├── created_at, updated_at +``` + +--- + +## 13. Discord Community Integration + +### Automated Discord Server Management +**Decision: Discord integration for community** + +#### Features +- Automatic Discord invite upon signup +- Role assignment based on service tier: + - VPS Customer → VPS role + - Game Server Customer → Gaming role + - Premium tier → VIP role +- Sync Discord username to customer profile +- Discord-exclusive announcements +- Support channel integration with SupportPal + +#### Implementation +```php +// app/Services/Discord/DiscordIntegrationService.php + +class DiscordIntegrationService +{ + public function inviteCustomer(User $user): string + { + // Create temporary Discord invite + $response = Http::withToken(config('services.discord.bot_token')) + ->post("https://discord.com/api/channels/{$channelId}/invites", [ + 'max_age' => 86400, // 24 hours + 'max_uses' => 1, + 'unique' => true, + ]); + + return $response['url']; + } + + public function assignRoles(User $user) + { + $roles = []; + + // Assign roles based on services + if ($user->hasVpsService()) { + $roles[] = config('services.discord.roles.vps'); + } + + if ($user->hasGameServerService()) { + $roles[] = config('services.discord.roles.gaming'); + } + + // Add roles via Discord API + foreach ($roles as $roleId) { + Http::withToken(config('services.discord.bot_token')) + ->put("https://discord.com/api/guilds/{$guildId}/members/{$user->discord_id}/roles/{$roleId}"); + } + } +} +``` + +--- + +## 14. Free Tier for Developers + +### Developer Testing Environment +**Decision: One free micro VPS per account** + +#### Features +- 1 vCPU, 512MB RAM, 10GB disk, 500GB bandwidth +- Limited to one per account +- Must verify email and 2FA to unlock +- Watermarked as "Development" in dashboard +- Auto-terminate after 90 days of inactivity +- Cannot upgrade to paid (must create new service) + +#### Database Schema +```sql +plans table addition: +├── is_free_tier (boolean) +├── free_tier_limit_per_account (integer) +├── free_tier_max_duration_days (90) +├── free_tier_requirements (JSON - email_verified, 2fa_enabled) + +services table addition: +├── is_free_tier (boolean) +├── free_tier_expires_at (created_at + 90 days) +├── last_activity_at (updated when customer accesses) +``` + +--- + +## 15. Service Transfer Between Accounts + +### Admin-Assisted Service Transfer +**Decision: Admin-assisted transfers** + +#### Process +1. Customer requests transfer via ticket +2. Provides recipient's email/account ID +3. Admin verifies both parties +4. Admin transfers service ownership +5. Prorated billing adjustments +6. Email confirmations to both parties + +#### Database Schema +```sql +service_transfers table: +├── id +├── service_id +├── from_user_id +├── to_user_id +├── requested_at +├── approved_by_admin_id +├── completed_at +├── reason +├── notes +├── status (requested, approved, completed, cancelled) +├── created_at, updated_at +``` + +--- + +## 16. Configurable Auto-Recovery + +### Service Health Monitoring & Auto-Restart +**Decision: Customer configurable** + +#### Features +- Monitor service health every 5 minutes (ping, HTTP check) +- If down, attempt auto-restart +- Max 3 auto-restart attempts per hour +- After 3 failures, alert customer and stop auto-restart +- Customer can enable/disable per service +- Customer can set custom health check URL + +#### Database Schema +```sql +auto_recovery_settings table: +├── id +├── service_id +├── enabled (boolean) +├── check_type (ping, http, tcp) +├── check_url (for http checks) +├── check_port (for tcp checks) +├── max_retries_per_hour (default 3) +├── notify_on_failure (boolean) +├── created_at, updated_at + +auto_recovery_attempts table: +├── id +├── service_id +├── check_failed_at +├── recovery_attempted_at +├── recovery_status (success, failed) +├── error_message +├── created_at +``` + +--- + +## 17. Projects & Service Grouping + +### Organize Services into Projects +**Decision: Yes, full project feature** + +#### Features +- Create projects (e.g., "Production", "Staging", "Client ABC") +- Assign multiple services to a project +- Project-level billing summary +- Project tags and notes +- Color-coded projects +- Filter dashboard by project + +#### Database Schema +```sql +projects table: +├── id +├── user_id +├── name +├── description +├── color (hex color for UI) +├── icon (emoji or icon name) +├── created_at, updated_at + +project_services table: +├── id +├── project_id +├── service_id +├── added_at +``` + +--- + +## 18. Scheduled Service Upgrades + +### Future-Dated Plan Changes +**Decision: Yes, full scheduling** + +#### Features +- Schedule upgrade for specific date/time +- Example: "Upgrade to VPS Pro on Dec 25 at midnight" +- Useful for planned traffic spikes (product launches, events) +- Customer can cancel scheduled change before it executes +- Email reminder 24 hours before scheduled change + +#### Database Schema +```sql +scheduled_changes table: +├── id +├── service_id +├── change_type (upgrade, downgrade, addon) +├── from_plan_id +├── to_plan_id +├── scheduled_for (datetime) +├── status (pending, executed, cancelled) +├── executed_at +├── cancelled_at +├── cancellation_reason +├── created_at, updated_at +``` + +--- + +## 19. AI Cost Optimization Recommendations + +### Machine Learning-Powered Suggestions +**Decision: Yes, AI recommendations** + +#### Features +- Analyze resource usage patterns over 30 days +- Detect underutilized services: "VPS using 15% CPU avg, downgrade to save $8/month" +- Detect overutilized services: "Bandwidth at 95%, upgrade to prevent overages" +- Consolidation suggestions: "3 low-usage VPS could be combined into 1" +- Idle service detection: "Game server hasn't been accessed in 45 days" + +#### Implementation +```php +// app/Services/AI/CostOptimizationService.php + +class CostOptimizationService +{ + public function analyzeService(Service $service): array + { + $recommendations = []; + + // Check CPU usage + $avgCpu = $this->getAverageCpuUsage($service, 30); + if ($avgCpu < 20) { + $lowerPlan = $this->findLowerTierPlan($service->plan); + if ($lowerPlan) { + $savings = $service->plan->price - $lowerPlan->price; + $recommendations[] = [ + 'type' => 'downgrade', + 'reason' => "Average CPU usage is only {$avgCpu}%", + 'suggestion' => "Downgrade to {$lowerPlan->name}", + 'monthly_savings' => $savings, + 'confidence' => 'high', + ]; + } + } + + // Check bandwidth approaching limit + $bandwidthPercent = $this->getBandwidthUsagePercent($service); + if ($bandwidthPercent > 80) { + $recommendations[] = [ + 'type' => 'upgrade', + 'reason' => "Using {$bandwidthPercent}% of bandwidth quota", + 'suggestion' => "Upgrade to avoid overage charges", + 'potential_cost' => $this->estimateOverageCharges($service), + 'confidence' => 'high', + ]; + } + + // Check idle services + if ($service->last_accessed_at < now()->subDays(30)) { + $recommendations[] = [ + 'type' => 'terminate', + 'reason' => "Service not accessed in 30+ days", + 'suggestion' => "Consider terminating to save costs", + 'monthly_savings' => $service->plan->price, + 'confidence' => 'medium', + ]; + } + + return $recommendations; + } +} +``` + +```sql +optimization_recommendations table: +├── id +├── service_id +├── recommendation_type (upgrade, downgrade, terminate, consolidate) +├── reason +├── suggestion +├── potential_savings +├── confidence_level (high, medium, low) +├── shown_at +├── acted_on_at (nullable) +├── dismissed_at (nullable) +├── created_at +``` + +--- + +## 20. Service Dependency Mapping + +### Visual Dependency Graph +**Decision: Yes, full dependency graph** + +#### Features +- Map dependencies between services +- Example: "Web Server depends on Database Server" +- Visual graph showing all relationships +- Warn before terminating service with dependents +- Cascade notifications (if Service A goes down, alert owners of dependent Service B) + +#### Database Schema +```sql +service_dependencies table: +├── id +├── service_id (the dependent service) +├── depends_on_service_id (the dependency) +├── dependency_type (database, loadbalancer, storage, other) +├── critical (boolean - critical dependency vs nice-to-have) +├── notes +├── created_at, updated_at +``` + +#### Vue Component +```vue + + + + +``` + +--- + +## 21. Budget Controls & Hard Limits + +### Spending Caps & Auto-Suspension +**Decision: Yes, hard limits** + +#### Features +- Set monthly budget cap ($100, $500, $1000) +- Soft alert at 50%, 75%, 90% +- Hard stop at 100% - suspend all services +- Budget resets monthly on billing cycle date +- Exclude/include specific services from budget +- Emergency override (customer can unlock with payment) + +#### Database Schema +```sql +budget_settings table: +├── id +├── user_id +├── monthly_limit +├── current_month_spend (reset monthly) +├── alert_thresholds (JSON - [50, 75, 90]) +├── auto_suspend_enabled (boolean) +├── excluded_service_ids (JSON array) +├── last_reset_at +├── created_at, updated_at + +budget_alerts table: +├── id +├── user_id +├── threshold_percent +├── current_spend +├── alerted_at +├── created_at +``` + +--- + +## 22. Terraform Provider for IaC + +### Infrastructure as Code Support +**Decision: Yes, official Terraform provider** + +#### Features +- Terraform provider: `terraform-provider-ezscale` +- Manage all resources via Terraform +- Import existing resources +- State management +- Documentation + examples + +#### Example Terraform Config +```hcl +# Configure the EZSCALE provider +provider "ezscale" { + api_token = var.ezscale_api_token +} + +# Create a VPS +resource "ezscale_vps" "web_server" { + name = "production-web" + plan = "vps-pro" + datacenter = "nyc1" + os_template = "ubuntu-22.04" + + ssh_keys = [ezscale_ssh_key.admin.id] + + tags = ["production", "web"] +} + +# Create Kasm Workspace +resource "ezscale_kasm_workspace" "dev_env" { + workspace_type = "developer_pro" + template = "ubuntu-vscode" + project = "staging" +} + +# Output access details +output "vps_ip" { + value = ezscale_vps.web_server.ipv4_address +} +``` + +--- + +## 23. Dynamic Promotional Landing Pages + +### Marketing Campaign Pages +**Decision: Yes, dynamic promo pages** + +#### Features +- Create custom landing pages for campaigns +- Special pricing visible only on that page +- UTM tracking for conversions +- A/B test different offers +- Limited-time countdown timers +- Unique coupon codes auto-applied + +#### Database Schema +```sql +promo_landing_pages table: +├── id +├── slug (black-friday-2026, partner-discount) +├── title +├── hero_image_url +├── pricing_override (JSON - custom pricing) +├── coupon_code (auto-applied) +├── starts_at +├── expires_at +├── max_conversions (nullable - limit signups) +├── current_conversions +├── status (draft, active, expired) +├── created_at, updated_at + +promo_page_visits table: +├── id +├── promo_landing_page_id +├── visitor_ip +├── utm_source +├── utm_medium +├── utm_campaign +├── converted (boolean) +├── converted_user_id (nullable) +├── visited_at +``` + +--- + +## 24. AI-Powered Support Assistant + +### First-Line Support Automation +**Decision: Yes, AI assistant before human** + +#### Features +- ChatGPT/Claude-powered chatbot +- Trained on EZSCALE knowledge base +- Answers common questions (billing, technical, how-to) +- Escalates complex issues to SupportPal ticket +- Tracks resolution rate (% solved by AI vs escalated) + +#### Implementation +```php +// app/Services/Support/AiSupportAssistant.php + +class AiSupportAssistant +{ + public function chat(string $message, User $user): array + { + // Build context + $context = $this->buildUserContext($user); + + // Call Claude API + $response = Http::withToken(config('services.anthropic.api_key')) + ->post('https://api.anthropic.com/v1/messages', [ + 'model' => 'claude-3-5-sonnet-20241022', + 'max_tokens' => 1024, + 'system' => $this->getSystemPrompt(), + 'messages' => [ + [ + 'role' => 'user', + 'content' => "Customer context:\n{$context}\n\nQuestion: {$message}", + ], + ], + ]); + + $answer = $response['content'][0]['text']; + + // Check if should escalate + if ($this->shouldEscalate($answer)) { + return [ + 'type' => 'escalate', + 'message' => 'Let me create a support ticket for you...', + 'ticket_id' => $this->createTicket($user, $message), + ]; + } + + return [ + 'type' => 'answer', + 'message' => $answer, + ]; + } + + protected function buildUserContext(User $user): string + { + return " + Customer: {$user->name} ({$user->email}) + Services: " . $user->services->pluck('service_type')->join(', ') . " + Account balance: ${$user->account_credits} + Overdue invoices: {$user->overdue_invoices_count} + "; + } + + protected function getSystemPrompt(): string + { + return "You are a helpful support assistant for EZSCALE Hosting. + You help customers with billing questions, technical issues, and how-to guides. + Be friendly, concise, and accurate. If you don't know something, say so and offer to escalate. + Never make up information about pricing or technical specs."; + } +} +``` + +--- + +## 25. Service Health Scores & Grades + +### A-F Health Dashboard +**Decision: Yes, health grades** + +#### Factors in Health Score +- Uptime percentage (weight: 40%) +- Performance metrics - avg response time (weight: 20%) +- Resource utilization - not maxed out (weight: 15%) +- Backup compliance - recent backups (weight: 10%) +- Security - patches up-to-date (weight: 10%) +- Incident count (weight: 5%) + +#### Grading Scale +- A (90-100%): Excellent +- B (80-89%): Good +- C (70-79%): Fair +- D (60-69%): Poor +- F (<60%): Critical + +#### Database Schema +```sql +service_health_scores table: +├── id +├── service_id +├── uptime_score (0-100) +├── performance_score (0-100) +├── utilization_score (0-100) +├── backup_score (0-100) +├── security_score (0-100) +├── incident_score (0-100) +├── overall_score (weighted average) +├── grade (A, B, C, D, F) +├── calculated_at +├── created_at +``` + +--- + +## 26. Competitive Analysis Automation + +### Competitor Price Tracking +**Decision: Yes, auto-tracking** + +#### Features +- Scrape competitor pricing weekly (Vultr, DigitalOcean, Linode, OVH) +- Compare similar plan specs +- Alert if competitors significantly undercut prices +- Display comparison charts in admin panel +- Track pricing history over time + +#### Implementation +```php +// app/Console/Commands/ScrapeCompetitorPricing.php + +class ScrapeCompetitorPricing extends Command +{ + public function handle() + { + $competitors = [ + 'vultr' => 'https://www.vultr.com/pricing/', + 'digitalocean' => 'https://www.digitalocean.com/pricing', + 'linode' => 'https://www.linode.com/pricing/', + ]; + + foreach ($competitors as $name => $url) { + $scraper = app("App\\Services\\Scrapers\\{$name}Scraper"); + $pricing = $scraper->scrape($url); + + foreach ($pricing as $plan) { + CompetitorPricing::create([ + 'competitor' => $name, + 'plan_name' => $plan['name'], + 'vcpu' => $plan['vcpu'], + 'ram_gb' => $plan['ram'], + 'disk_gb' => $plan['disk'], + 'bandwidth_tb' => $plan['bandwidth'], + 'price_monthly' => $plan['price'], + 'scraped_at' => now(), + ]); + } + } + + $this->analyzeCompetitiveness(); + } + + protected function analyzeCompetitiveness() + { + $ourPlans = Plan::where('service_type', 'vps')->get(); + + foreach ($ourPlans as $plan) { + $similarCompetitorPlans = CompetitorPricing::where('vcpu', $plan->vcpu) + ->where('ram_gb', '>=', $plan->ram_gb * 0.9) + ->where('ram_gb', '<=', $plan->ram_gb * 1.1) + ->latest('scraped_at') + ->get(); + + $avgCompetitorPrice = $similarCompetitorPlans->avg('price_monthly'); + + if ($plan->price > $avgCompetitorPrice * 1.2) { + // We're 20% more expensive - alert + app(DiscordNotificationService::class)->sendAlert([ + 'title' => 'Pricing Alert', + 'message' => "{$plan->name} is 20% above market average", + 'our_price' => $plan->price, + 'market_avg' => $avgCompetitorPrice, + ]); + } + } + } +} +``` + +```sql +competitor_pricing table: +├── id +├── competitor (vultr, digitalocean, linode) +├── plan_name +├── vcpu +├── ram_gb +├── disk_gb +├── bandwidth_tb +├── price_monthly +├── scraped_at +├── created_at +``` + +--- + +## 27. Advanced Win-Back Campaigns + +### Smart Churn Prevention +**Decision: Yes, intelligent automation** + +#### Features +- Segment by cancellation reason +- Different campaigns per segment: + - "Too expensive" → Offer 25% discount for 3 months + - "Switching to competitor" → Match competitor offer + - "Technical issues" → Offer migration assistance + credit + - "No longer need service" → Stay-in-touch newsletter +- Track campaign effectiveness +- A/B test email copy + +#### Database Schema +```sql +winback_campaigns table: +├── id +├── name +├── cancellation_reason (matches exit survey reasons) +├── email_sequence (JSON - series of emails with delays) +├── offer_type (discount, credit, free_upgrade) +├── offer_value +├── status (active, paused, completed) +├── created_at, updated_at + +winback_campaign_recipients table: +├── id +├── campaign_id +├── user_id +├── subscription_id (cancelled subscription) +├── current_email_index +├── last_email_sent_at +├── opened_count +├── clicked_count +├── reactivated (boolean) +├── reactivated_at +├── created_at +``` + +--- + +## 28. Cohort Analysis Dashboard + +### Customer Segmentation & Retention Analysis +**Decision: Yes, full cohort tracking** + +#### Features +- Group customers by signup month/quarter +- Track retention by cohort over time +- Revenue per cohort +- Compare acquisition channels (organic, paid, referral) +- Cohort LTV (Lifetime Value) predictions +- Churn analysis by cohort + +#### Visualization Example +``` +Cohort Retention Table: + +Cohort Month 0 Month 1 Month 2 Month 3 Month 6 Month 12 +2025-Q4 100% 92% 87% 83% 75% 68% +2026-Q1 100% 95% 91% 88% 80% -- +2026-Q2 100% 96% 93% -- -- -- +``` + +#### Implementation +```php +// app/Services/Analytics/CohortAnalysisService.php + +class CohortAnalysisService +{ + public function generateRetentionCohorts(): array + { + $cohorts = []; + + // Get all signup cohorts (monthly) + $cohortData = User::selectRaw(' + DATE_FORMAT(created_at, "%Y-%m") as cohort, + COUNT(*) as cohort_size + ') + ->groupBy('cohort') + ->get(); + + foreach ($cohortData as $cohort) { + $cohortUsers = User::whereRaw('DATE_FORMAT(created_at, "%Y-%m") = ?', [$cohort->cohort]) + ->pluck('id'); + + $retention = []; + + // Calculate retention for each month after signup + for ($month = 0; $month <= 12; $month++) { + $activeUsers = Subscription::whereIn('user_id', $cohortUsers) + ->where('status', 'active') + ->whereDate('created_at', '<=', now()->parse($cohort->cohort)->addMonths($month)) + ->count(); + + $retention[$month] = round(($activeUsers / $cohort->cohort_size) * 100, 1); + } + + $cohorts[$cohort->cohort] = [ + 'size' => $cohort->cohort_size, + 'retention' => $retention, + ]; + } + + return $cohorts; + } +} +``` + +--- + +## Summary + +These 28 advanced features significantly enhance the platform: + +**Customer Experience** +- ✅ Task automation & scheduling +- ✅ Forecasting with AI recommendations +- ✅ Project organization +- ✅ Dependency mapping +- ✅ Budget controls +- ✅ Health dashboards +- ✅ Discord community +- ✅ AI support assistant +- ✅ Free dev tier +- ✅ Scheduled upgrades + +**Business Intelligence** +- ✅ Cohort analysis +- ✅ Competitive tracking +- ✅ Smart win-back campaigns +- ✅ NPS surveys +- ✅ Capacity planning + +**Operations & Admin** +- ✅ Bulk email campaigns +- ✅ Audit alerts & dual approval +- ✅ SOC 2 compliance +- ✅ Infrastructure monitoring + +**Developer Tools** +- ✅ Terraform provider +- ✅ Full-control API +- ✅ Auto-recovery settings + +**Marketing** +- ✅ Dynamic promo pages +- ✅ Tiered discounts + +This brings the total feature count to **60+ features**, making this one of the most comprehensive hosting platform implementations ever planned! diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b774635 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,73 @@ +# CLAUDE.md - EZSCALE Site Project Instructions + +## Important Context +- This repository is used for **documentation and planning only** on this machine +- Actual project building and code execution happens on a separate development machine +- Do NOT attempt to run composer, php, node, or other build commands here +- Focus on documentation, architecture, and planning tasks + +## Project Overview +EZSCALE Site is a Laravel 12 application replacing WHMCS for VPS/Dedicated Server hosting management. It handles billing, subscriptions, provisioning, customer management, and SSO. + +## Tech Stack +- **Framework:** Laravel 12 (PHP 8.2+) +- **Frontend:** Vue 3 + Inertia.js + Tailwind CSS +- **UI Theme:** Vuexy VueJS + Laravel Admin Dashboard Template (source files to be added) +- **Payments:** Laravel Cashier Stripe (primary) + srmklive/laravel-paypal (secondary) +- **Database:** MySQL 8.x +- **Queue:** Redis +- **Auth:** Laravel Fortify + Passport (OAuth2/SSO) +- **Roles:** spatie/laravel-permission + +## Project Structure +``` +app/ +├── Models/ # Eloquent models +├── Http/ +│ ├── Controllers/ # Route controllers +│ ├── Middleware/ # Custom middleware +│ └── Requests/ # Form request validation +├── Services/ # Business logic (provisioning, billing, etc.) +├── Policies/ # Authorization policies +└── Events/ # Domain events +``` + +## Development Commands +```bash +php artisan serve # Run dev server +php artisan test # Run test suite +php artisan migrate # Run migrations +php artisan queue:work # Process queue jobs +npm run dev # Vite dev server +npm run build # Production build +``` + +## Code Conventions +- Follow PSR-12 coding standards +- Use strict typing: `declare(strict_types=1);` in all PHP files +- Use Form Request classes for validation +- Use Service classes for business logic (not in controllers) +- Use Policies for authorization +- Use Events/Listeners for side effects (email, provisioning, etc.) +- Write Feature and Unit tests for all new functionality +- Use database transactions for multi-step operations + +## Security Requirements +- All API endpoints require authentication +- Admin routes protected by role-based middleware +- CSRF protection on all forms +- Rate limiting on auth and API endpoints +- Input sanitization on all user inputs +- Encrypted storage for sensitive data (API keys, credentials) +- Audit logging for admin actions and billing events + +## Key Domains +1. **Billing** - Subscriptions, invoices, payments via Cashier +2. **Provisioning** - Server creation, suspension, termination +3. **Customer Management** - Profiles, support tickets, notifications +4. **Admin Panel** - Dashboard, user management, server management +5. **SSO** - Single sign-on across EZSCALE services + +## Reference Files +- `TASKS.md` - Current task list and progress +- `PROJECT_DEVELOPMENT.md` - Architecture decisions and development plan diff --git a/FEATURES.md b/FEATURES.md new file mode 100644 index 0000000..7696a2c --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,1332 @@ +# FEATURES.md - EZSCALE Site Feature Specifications + +## Overview +This document details all feature decisions made during planning. Reference this when building specific features. + +--- + +## 1. Coupon & Discount System + +### Coupon Types +- **Percentage discount** (e.g., 20% off) +- **Fixed amount** (e.g., $10 off) +- **Free trial extensions** (e.g., extend trial by 7 days) + +### Advanced Restrictions +- Expiry dates +- Maximum uses (total and per customer) +- First purchase only +- Specific plans/services +- Minimum order value +- Recurring vs one-time discounts +- **Stackable coupons** (allow multiple coupons per order) +- **User groups** (coupons for specific customer segments) +- **Geographic restrictions** (US-only coupons, EU-only, etc.) +- **A/B testing support** (track conversion by coupon) + +### Database Schema Addition +```sql +coupons table: +├── stackable (boolean - can be combined with other coupons) +├── user_group (nullable - admin, vip, new_customer, etc.) +├── allowed_countries (JSON array - e.g., ["US", "CA", "GB"]) +├── blocked_countries (JSON array) +├── conversion_tracking (boolean - track for analytics) +├── variant_id (nullable - for A/B testing) +``` + +--- + +## 2. Plan Changes & Billing + +### Upgrade/Downgrade Logic +- **Immediate proration for plan changes** + - Calculate unused time credit on current plan + - Apply credit to new plan price + - Charge/credit difference immediately + - Update service resources immediately (VirtFusion/Pterodactyl API calls) + +### Example Calculation +``` +Customer on $10/month VPS (30 days), used 10 days +Upgrades to $20/month VPS + +Credit: $10 * (20 days / 30 days) = $6.67 +New charge: $20 - $6.67 = $13.33 +``` + +### Implementation Notes +- Use Laravel Cashier's `swap()` method for Stripe subscriptions +- For PayPal, manually calculate and create new subscription +- Queue API calls to update VPS resources +- Send confirmation email with proration details + +--- + +## 3. Payment Retry & Dunning + +### Strategy +- **Use Stripe Smart Retries** (built-in dunning management) +- Stripe automatically retries failed payments with ML-optimized timing +- Laravel webhooks listen for payment failure events + +### Our Enhancement +- On payment failure event: + - Send customer email with retry schedule + - Add grace period (7 days) before suspension + - Send reminder at 3 days before suspension + - Suspend service if still unpaid + - Discord webhook alert for high-value customer failures + +### Configuration +```php +// config/billing.php +'dunning' => [ + 'grace_period_days' => 7, + 'suspension_warning_days' => 3, + 'termination_days' => 30, // 30 days after suspension +], +``` + +--- + +## 4. Datacenter & Location Management + +### Per-Plan Location +- Plans are tied to specific datacenters +- Example: "VPS-Basic-US-East", "VPS-Basic-EU-West" +- Different pricing per location (if applicable) + +### Database Schema +```sql +plans table: +├── datacenter_location (string - us-east, us-west, eu-west, ap-southeast) +├── datacenter_code (string - NYC1, LAX2, AMS1, SG1) +├── location_display_name (string - "New York, USA") + +datacenters table (new): +├── id +├── code (NYC1, LAX2, etc.) +├── name (New York - US East) +├── location (city, country) +├── available_services (JSON - ['vps', 'dedicated', 'hosting']) +├── status (active, maintenance, full) +``` + +### VirtFusion Integration +- Each datacenter maps to a VirtFusion region/hypervisor group +- Provisioning service selects appropriate hypervisor based on plan's datacenter + +--- + +## 5. Customer Onboarding + +### Guided Onboarding Flow +1. **Email verification** - Confirm email address +2. **Profile completion** - Company name, address (for tax calculations) +3. **Payment method** - Add credit card or PayPal +4. **Plan selection** - Choose service and datacenter +5. **Service provisioning** - Automated provisioning begins +6. **Welcome tour** - Brief overlay tour of dashboard features + +### Implementation +- Use Laravel Multi-Step Forms or similar +- Store progress in session +- Allow skipping steps (except email verification) +- Show progress bar: "Step 2 of 5" + +### Post-Onboarding +- Redirect to service provisioning status page +- Email: "Your VPS is being provisioned" (ETA: 5 minutes) +- Email: "Your VPS is ready!" (includes credentials, getting started guide) +- Dashboard widget: "Next steps" (upload SSH key, configure firewall, install software) + +--- + +## 6. Loyalty Rewards Program + +### Automatic Tenure-Based Discounts +| Tenure | Discount | +|--------|----------| +| 1+ years | 5% off recurring | +| 2+ years | 10% off recurring | +| 3+ years | 15% off recurring | +| 5+ years | 20% off recurring | + +### Implementation +- Scheduled job runs monthly to update customer discount tiers +- Apply discount as automatic coupon on renewals +- Display loyalty badge in dashboard: "Loyal Customer - 5% Discount" +- Email notification when customer reaches new tier + +### Database Schema +```sql +users table additions: +├── customer_since (timestamp - first paid invoice date) +├── loyalty_tier (integer - 0, 1, 2, 3, 5 years) +├── loyalty_discount_percent (decimal - calculated discount) +``` + +--- + +## 7. Dedicated Server Waitlist + +### Notify When Available Approach +- Customer signs up for email notifications +- No payment or reservation +- When inventory available, send email blast to waitlist +- First-come, first-served checkout + +### Waitlist Features +- Show estimated wait time (based on average turnover) +- Let customer specify desired specs (RAM, CPU, disk) +- Email when exact match available +- Email when close match available + +### Database Schema +```sql +server_waitlist table: +├── id +├── user_id +├── plan_id (nullable - if waiting for specific plan) +├── desired_specs (JSON - RAM, CPU, disk requirements) +├── datacenter_preference (nullable) +├── notified_at (nullable - when we sent availability email) +├── status (waiting, notified, fulfilled, cancelled) +├── created_at, updated_at +``` + +--- + +## 8. Custom Pricing for Enterprise + +### Admin Custom Plan Creation +- Admin can create one-off plans for specific customers +- Set custom pricing, billing cycle, features +- Plan is private (not visible in public catalog) +- Assigned to specific customer only + +### Implementation +```sql +plans table additions: +├── visibility (public, private, archived) +├── assigned_user_id (nullable - for private plans) +├── is_custom (boolean - marked as custom pricing) +``` + +### Admin UI +- Button: "Create Custom Plan for Customer" +- Form: Base on existing plan, modify price and features +- Auto-generate plan name: "Custom VPS - John Doe - $45/month" + +--- + +## 9. GDPR Data Deletion + +### Automated Process +1. Customer requests deletion from account settings +2. System creates data deletion request (7-day waiting period) +3. Email confirmation: "Your account will be deleted in 7 days" +4. After 7 days, automated job runs: + - Terminate all active services + - Anonymize personal data (name → "Deleted User #12345") + - Keep financial records (invoices, payments) with anonymized data + - Delete: email, phone, address, notes, login history + - Retain: subscription IDs, amounts, dates (for accounting/tax) +5. Email confirmation: "Your data has been deleted" + +### Database Schema +```sql +data_deletion_requests table: +├── id +├── user_id +├── requested_at +├── scheduled_for (requested_at + 7 days) +├── completed_at (nullable) +├── status (pending, processing, completed, cancelled) +``` + +### Compliance +- Compliant with GDPR "right to be forgotten" +- Retain minimum data required by law (7 years for tax records) +- Provide data export (download all data as JSON/PDF) before deletion + +--- + +## 10. Uptime Monitoring + +### Built-In Monitoring System +- Platform pings customer services every 5 minutes +- HTTP/HTTPS checks for web hosting +- ICMP ping for VPS/dedicated +- Game server query for Pterodactyl services + +### Features +- Uptime percentage displayed in dashboard +- Incident log (downtime events with duration) +- Customer can set up alert preferences (email, Discord webhook) +- Public status page shows overall platform health + +### Database Schema +```sql +uptime_checks table: +├── id +├── service_id +├── check_type (http, ping, game_query) +├── check_url_or_ip +├── status (up, down, degraded) +├── response_time_ms +├── checked_at + +uptime_incidents table: +├── id +├── service_id +├── started_at +├── ended_at (nullable - ongoing) +├── duration_seconds +├── notified (boolean - customer was alerted) +``` + +--- + +## 11. Real-Time Dashboard Updates + +### Combination Approach +- **Real-time (WebSockets)** for: + - New orders/subscriptions + - Critical alerts (provisioning failures, payment failures) + - Customer support tickets + - Admin notifications + +- **Periodic refresh (polling)** for: + - Analytics charts (every 60 seconds) + - Service status (every 30 seconds) + - Bandwidth graphs (every 5 minutes) + +### Implementation +- Use **Laravel Reverb** (or Pusher) for WebSockets +- Channel: `admin.{admin_id}` for personal admin notifications +- Channel: `customer.{user_id}` for customer notifications +- Broadcast events: `OrderCreated`, `ServiceProvisioned`, `PaymentFailed` + +--- + +## 12. Multi-Channel Admin Alerts + +### Alert Routing +| Alert Type | Discord | Email | SMS (Twilio) | +|------------|---------|-------|--------------| +| New order | ✓ | ✗ | ✗ | +| High-value order (>$500) | ✓ | ✓ | ✓ | +| Payment failure | ✓ | ✗ | ✗ | +| Provisioning failure | ✓ | ✓ | ✓ | +| System error | ✓ | ✓ | ✗ | +| Security alert (failed admin login) | ✓ | ✓ | ✓ | +| Service cancellation | ✓ | ✗ | ✗ | + +### Configuration +```php +// config/alerts.php +'channels' => [ + 'discord' => env('DISCORD_WEBHOOK_URL'), + 'email' => env('ADMIN_ALERT_EMAIL'), + 'sms' => [ + 'enabled' => env('SMS_ALERTS_ENABLED', false), + 'twilio_sid' => env('TWILIO_SID'), + 'twilio_token' => env('TWILIO_TOKEN'), + 'phone_numbers' => explode(',', env('ADMIN_PHONE_NUMBERS')), + ], +], +``` + +--- + +## 13. Public Status Page + +### Built-In Status Page (status.ezscale.cloud) +- **System Status**: All systems operational / Degraded / Major outage +- **Service Components**: + - VirtFusion API + - Pterodactyl Panel + - SynergyCP + - Enhance + - Billing System + - Customer Portal + - ElastiFlow (Bandwidth Monitoring) + +- **Incidents**: Current and past incidents with updates +- **Scheduled Maintenance**: Upcoming maintenance windows +- **Uptime Stats**: 90-day uptime graph per component + +### Features +- Public page (no login required) +- RSS feed for status updates +- Customer can subscribe to status notifications +- Admin can post incidents and updates +- Auto-create incidents from monitoring (optional) + +### Database Schema +```sql +status_components table: +├── id +├── name (VirtFusion API, Billing System, etc.) +├── status (operational, degraded, outage) +├── description +├── group (Infrastructure, Billing, Control Panels) +├── sort_order + +status_incidents table: +├── id +├── title +├── description +├── status (investigating, identified, monitoring, resolved) +├── severity (minor, major, critical) +├── affected_components (JSON array of component IDs) +├── started_at +├── resolved_at (nullable) + +status_updates table: +├── id +├── incident_id +├── message +├── status_change (investigating → identified) +├── posted_at +``` + +--- + +## 14. Abuse Management System + +### Full Abuse Management Module +- Dedicated abuse ticket queue (separate from support) +- Abuse report submission form (public, for reporting abuse) +- Automated abuse detection (optional - DMCA API, spam blacklist checks) +- Service auto-suspension for severe abuse (CSAM, phishing) + +### Abuse Workflow +1. Abuse report received (email, web form, API) +2. Create abuse ticket (high priority) +3. Notify admin via Discord + email +4. Admin investigates, views customer history +5. Options: + - Warn customer (send abuse notice email) + - Suspend service immediately + - Request content removal (give customer X hours) + - Terminate account (severe violations) +6. Track abuse history per customer +7. Escalate repeat offenders automatically + +### Database Schema +```sql +abuse_reports table: +├── id +├── service_id (nullable - may not know which service yet) +├── user_id (nullable - determined after investigation) +├── reporter_email +├── reporter_name (nullable) +├── abuse_type (spam, copyright, phishing, illegal_content, other) +├── description +├── evidence (JSON - URLs, headers, attachments) +├── status (new, investigating, resolved, dismissed) +├── assigned_admin_id (nullable) +├── resolved_at (nullable) + +abuse_actions table: +├── id +├── abuse_report_id +├── action_type (warning, suspension, termination, content_removal) +├── taken_by_admin_id +├── notes +├── created_at + +customer_abuse_history: +├── user_id +├── total_reports +├── resolved_reports +├── warnings_sent +├── suspensions +├── risk_score (calculated - higher score = more likely to abuse) +``` + +--- + +## 15. Fraud Detection + +### Automated Fraud Scoring +- Check on signup/checkout before provisioning +- Assign risk score 0-100 +- Auto-reject if score > 90 +- Flag for manual review if score 50-90 +- Auto-approve if score < 50 + +### Fraud Signals +- **Email**: Disposable email domains (mailinator, guerrilla mail), newly created Gmail/Outlook +- **IP Address**: VPN/proxy detection, high-risk countries, IP mismatch with billing address +- **Payment**: Prepaid cards, multiple failed attempts, card BIN country mismatch +- **Behavioral**: New account placing large order, unusual order patterns +- **Velocity**: Multiple accounts from same IP in short time + +### Third-Party Services +- **MaxMind MinFraud** - IP and transaction risk scoring +- **Stripe Radar** - Built-in fraud detection +- **Email verification API** - Validate email deliverability + +### Implementation +```php +// app/Services/Fraud/FraudDetectionService.php +public function calculateRiskScore(User $user, Order $order): int +{ + $score = 0; + + // Disposable email +30 + if ($this->isDisposableEmail($user->email)) $score += 30; + + // VPN/proxy +20 + if ($this->isVpnOrProxy($user->ip_address)) $score += 20; + + // High-risk country +15 + if ($this->isHighRiskCountry($user->country)) $score += 15; + + // ... more checks + + return min($score, 100); +} +``` + +--- + +## 16. Game Server Templates + +### Template Library +- Pre-configured templates for popular games +- One-click deployment from customer dashboard +- Admin can create/manage custom templates + +### Supported Games (Initial) +- Minecraft (Vanilla, Spigot, Paper, Forge, Fabric) +- ARK: Survival Evolved +- Rust +- Counter-Strike 2 +- Palworld +- Valheim +- Terraria +- 7 Days to Die +- Team Fortress 2 +- Garry's Mod + +### Template Features +- Default server configuration +- Recommended plugins/mods +- Startup parameters +- Port configurations +- Resource requirements (min RAM, CPU) + +### Database Schema +```sql +game_templates table: +├── id +├── game_name (Minecraft, ARK, etc.) +├── template_name (Vanilla 1.20, Spigot, etc.) +├── pterodactyl_egg_id +├── description +├── icon_url +├── default_config (JSON - startup params, server.properties, etc.) +├── min_ram_mb +├── recommended_ram_mb +├── min_cpu_cores +├── status (active, deprecated) +├── sort_order +``` + +--- + +## 17. Backups (Included in Plans) + +### Backup Features +- Daily automated backups for VPS/hosting +- Retention: 7 daily, 4 weekly, 3 monthly +- Customer can restore from dashboard (self-service) +- Backups stored on separate infrastructure (not same as service) + +### Backup Storage +- Use S3-compatible storage (Wasabi, Backblaze B2, MinIO) +- Encrypted backups +- Compression to save space + +### Implementation +- VirtFusion API: backup VPS snapshots +- Enhance API: backup hosting accounts +- Pterodactyl: backup game server files (via API or direct) +- SynergyCP: backup dedicated server config (customer responsible for data) + +### Database Schema +```sql +backups table: +├── id +├── service_id +├── backup_type (daily, weekly, monthly, manual) +├── size_bytes +├── storage_path (S3 URL or path) +├── status (pending, completed, failed, restoring) +├── created_at +├── expires_at (based on retention policy) + +backup_restores table: +├── id +├── backup_id +├── service_id +├── requested_by_user_id +├── status (pending, in_progress, completed, failed) +├── created_at +``` + +--- + +## 18. Platform Backups + +### 15-Minute RPO (Recovery Point Objective) +- MySQL binary logs replicated in real-time +- Transaction log backups every 15 minutes +- Full database backup daily +- Test restores weekly (automated) + +### Multi-Region Replication +- Master database in primary datacenter +- Read replica in secondary datacenter (async replication) +- Automatic failover to replica if master fails + +### Backup Retention +- 15-minute transaction logs: 7 days +- Daily full backups: 30 days +- Weekly full backups: 90 days +- Monthly backups: 1 year + +### Implementation +- Use MySQL Enterprise Backup or Percona XtraBackup +- Store backups in S3 with versioning enabled +- Encrypt backups at rest (AES-256) + +--- + +## 19. IPv4 + IPv6 Dual-Stack + +### IP Allocation +- All VPS and dedicated servers get: + - 1x IPv4 address (included) + - /64 IPv6 subnet (included) + +- Web hosting: + - Shared IPv4 (multiple sites per IP) + - Shared IPv6 + +- Game servers: + - 1x IPv4 (included) + - IPv6 optional (most game clients don't support) + +### Additional IPv4 Addresses +- Customer requests additional IPs via ticket +- Must provide justification (SSL certificates, multiple services, etc.) +- Admin reviews and approves +- Pricing: $3-5/month per additional IPv4 + +### IPAM (IP Address Management) +- Track IP allocation in database +- Prevent duplicate assignments +- RDNS (reverse DNS) management +- SWIP (Shared Whois Project) for larger allocations + +### Database Schema +```sql +ip_addresses table: +├── id +├── ip_address (IPv4 or IPv6) +├── ip_version (4 or 6) +├── type (dedicated, shared) +├── service_id (nullable) +├── datacenter_id +├── status (available, allocated, reserved) +├── rdns_hostname (nullable) +├── notes + +ip_requests table: +├── id +├── user_id +├── service_id +├── ip_version (4 or 6) +├── quantity +├── justification +├── status (pending, approved, rejected) +├── reviewed_by_admin_id +├── created_at +``` + +--- + +## 20. Invoice Numbering + +### Sequential Format: INV-000001 +- Simple incrementing counter +- Never resets +- Starts at INV-000001 +- Auto-increments for each invoice +- Zero-padded to 6 digits + +### Implementation +```php +// Generate next invoice number +$lastInvoiceNumber = DB::table('invoices') + ->orderBy('number', 'desc') + ->value('number'); + +$nextNumber = $lastInvoiceNumber + ? intval(substr($lastInvoiceNumber, 4)) + 1 + : 1; + +$invoiceNumber = 'INV-' . str_pad($nextNumber, 6, '0', STR_PAD_LEFT); +// Result: INV-000001, INV-000002, ..., INV-123456 +``` + +### Database +```sql +invoices table: +├── number (unique, indexed - INV-000001) +├── stripe_invoice_id (nullable - for Stripe invoices) +├── paypal_invoice_id (nullable - for PayPal) +``` + +--- + +## 21. Team Accounts & Sub-Users + +### Full Team Support +- Primary account owner (billing access) +- Add team members with granular permissions +- Each team member gets own login (separate email) + +### Permission Levels +| Permission | Description | +|------------|-------------| +| **Owner** | Full access (billing, services, team management) | +| **Billing Manager** | View and pay invoices, manage payment methods | +| **Technical Admin** | Manage services (reboot, reinstall, view credentials) | +| **Read-Only** | View services and billing, no modifications | +| **Custom** | Admin defines specific permissions | + +### Features +- Owner can invite team members via email +- Team members accept invitation, create account +- Audit log shows which team member performed actions +- Owner can revoke access anytime + +### Database Schema +```sql +team_members table: +├── id +├── account_owner_id (references users.id) +├── team_member_user_id (references users.id) +├── role (owner, billing_manager, technical_admin, read_only, custom) +├── permissions (JSON - for custom roles) +├── invited_at +├── accepted_at (nullable) +├── status (invited, active, revoked) + +team_invitations table: +├── id +├── account_owner_id +├── email +├── role +├── token (unique invitation token) +├── expires_at +├── accepted_at (nullable) +``` + +--- + +## 22. Referral Credits + +### Referral Program +- Customer gets unique referral link: `ezscale.cloud/ref/ABC123` +- When referred friend signs up and pays first invoice: + - Referrer gets $10 account credit + - New customer gets $5 account credit +- Credits apply to future invoices automatically + +### Tracking +- Referral link parameter stored in session/cookie +- When customer registers, store referrer ID +- When first invoice paid, trigger credit issuance event + +### Database Schema +```sql +referrals table: +├── id +├── referrer_user_id +├── referred_user_id +├── referral_code (unique - ABC123) +├── status (pending, completed, credited) +├── credit_amount_referrer +├── credit_amount_referred +├── referred_at +├── first_payment_at (nullable) +├── credited_at (nullable) + +account_credits table: +├── id +├── user_id +├── amount +├── source (referral, loyalty, admin_granted, promotional) +├── description +├── applied_to_invoice_id (nullable) +├── expires_at (nullable - credits can expire) +├── created_at +``` + +--- + +## 23. Free Trial System + +### Free Trial Configuration +- Trial length: 7 days (configurable per plan) +- Requires payment method (but not charged) +- Full service access during trial +- Auto-convert to paid subscription after trial ends +- Customer can cancel during trial (no charge) + +### Trial Limitations (Optional) +- Email verification required +- One trial per email address +- Fraud score check (reject high-risk trials) + +### Implementation +- Use Stripe's built-in trial period functionality +- For PayPal: create subscription with trial period +- Email reminders: + - Day 1: Welcome email with getting started guide + - Day 5: "2 days left in your trial" + - Day 7: "Your trial has ended, subscription starts today" + +### Database Tracking +```sql +subscriptions table additions: +├── trial_ends_at (nullable - Cashier provides this) +├── trial_converted_at (nullable - when trial became paid) +├── trial_cancelled (boolean - cancelled during trial) +``` + +--- + +## 24. Chatbot for Marketing Site + +### Chatbot Features (Crisp, Tidio, or custom) +- Appears on ezscale.cloud (marketing site) +- Answers common questions: + - Pricing + - Service features + - Datacenter locations + - Billing questions + - Signup process + +### Bot Flows +- Initial greeting: "Hi! How can I help you today?" +- Quick reply buttons: "Pricing", "Features", "Sign Up", "Talk to Human" +- If "Talk to Human": Create support ticket or offer callback + +### Integration +- Use Crisp or similar (GDPR-compliant, affordable) +- Escalate to human support via SupportPal ticket API +- Track chatbot interactions in analytics + +--- + +## 25. Comprehensive Financial Reports + +### Reports Needed +1. **Revenue Report** + - Total revenue by period (daily, monthly, yearly) + - Breakdown by service type (VPS, Dedicated, Hosting, Game) + - Breakdown by plan + - Growth percentage vs previous period + +2. **Profit & Loss Statement** + - Revenue + - Refunds + - Payment gateway fees (Stripe, PayPal) + - Infrastructure costs (VirtFusion, Pterodactyl, etc.) + - Net profit + +3. **Tax Report** + - Sales tax collected by region + - VAT collected (if applicable) + - Export for accountant (CSV, PDF) + +4. **Aging Report** + - Outstanding invoices by age (0-30 days, 30-60, 60-90, 90+) + - Total amount overdue + - Customer list with overdue amounts + +5. **Refund Report** + - All refunds issued + - Reason for refund + - Total refunded by period + +6. **Subscription Report** + - New subscriptions this period + - Cancelled subscriptions + - Churn rate % + - MRR and ARR + +### Export Formats +- PDF (formatted reports) +- CSV (raw data for Excel) +- JSON (API access) + +### Scheduled Reports +- Admin can schedule email delivery (weekly/monthly) +- Auto-send month-end reports to accounting team + +--- + +## 26. Login History & Security Audit + +### Full Audit Trail +- Track all customer and admin logins +- Log IP address, device type, user agent, location (GeoIP) +- Customer can view their own login history +- Admin can view any user's login history + +### Security Features +- Alert on login from new device/location +- Alert on multiple failed login attempts +- Option to enable "trusted devices" (require 2FA on new devices only) +- Admin can force logout all sessions + +### Database Schema +```sql +login_history table: +├── id +├── user_id +├── ip_address +├── user_agent +├── device_type (desktop, mobile, tablet) +├── browser (Chrome, Firefox, Safari, etc.) +├── location_country +├── location_city (from GeoIP) +├── success (boolean - failed vs successful) +├── two_factor_used (boolean) +├── created_at + +active_sessions table: +├── id +├── user_id +├── session_id (Laravel session ID) +├── ip_address +├── user_agent +├── last_activity_at +├── created_at +``` + +--- + +## 27. Invoice Consolidation + +### Customer Preference +- Customer can choose in account settings: + - **Consolidated**: One invoice per billing cycle with all services + - **Separate**: Each service gets its own invoice + +### Implementation +- Default: Consolidated +- Setting stored in user preferences +- Billing job checks preference before generating invoices +- For consolidated: Group by billing date, create single invoice with line items + +### Example Consolidated Invoice +``` +INVOICE #INV-001234 +Due Date: February 15, 2026 + +Line Items: +- VPS Pro - us-east (Feb 15 - Mar 15) $20.00 +- Web Hosting Basic (Feb 15 - Mar 15) $10.00 +- Game Server - Minecraft (Feb 15 - Mar 15) $15.00 + +Subtotal: $45.00 +Tax (8%): $3.60 +Total: $48.60 +``` + +--- + +## 28. Unified Communication Timeline + +### Timeline View (Customer & Admin) +- Shows all interactions with customer in chronological order +- Event types: + - Account created + - Service provisioned + - Invoice generated + - Payment received + - Email sent (with subject) + - Support ticket created + - Ticket reply + - Service suspended + - Service resumed + - Login activity + - Admin notes + - Service upgrade/downgrade + +### Features +- Filter by event type +- Search timeline +- Admin can add manual notes +- Export timeline as PDF (for records) + +### Database Schema +```sql +customer_timeline table: +├── id +├── user_id +├── event_type (account_created, invoice_generated, etc.) +├── event_description +├── related_model_type (Invoice, Service, Ticket, etc.) +├── related_model_id +├── metadata (JSON - full event data) +├── created_by_admin_id (nullable - for admin notes) +├── created_at +``` + +--- + +## 29. API Features + +### Full Control API +- Customers can create, modify, delete services via API +- Same capabilities as dashboard +- RESTful design +- Sanctum token authentication + +### Webhook System +- Customers can register webhook URLs +- Events trigger POST requests to customer's webhook +- Events: + - `invoice.created` + - `invoice.paid` + - `service.provisioned` + - `service.suspended` + - `service.terminated` + - `bandwidth.threshold_reached` + +### Webhook Security +- HMAC signature for verification +- Retry failed webhooks (3 attempts) +- Webhook delivery log + +### Custom Domains (CNAME) +- Customer can point `billing.theirdomain.com` to `account.ezscale.cloud` +- SSL certificate auto-provisioned via Let's Encrypt +- Requires DNS verification (add TXT record) + +### Database Schema +```sql +api_tokens table (Sanctum provides): +├── id +├── tokenable_type +├── tokenable_id +├── name +├── token (hashed) +├── abilities (JSON - permissions) +├── last_used_at +├── created_at + +customer_webhooks table: +├── id +├── user_id +├── url +├── events (JSON array - subscribed events) +├── secret (for HMAC signature) +├── status (active, disabled) +├── created_at + +webhook_deliveries table: +├── id +├── webhook_id +├── event_type +├── payload (JSON) +├── response_code +├── response_body +├── attempts +├── delivered_at +├── created_at + +custom_domains table: +├── id +├── user_id +├── domain (billing.theirdomain.com) +├── verification_token +├── verified_at +├── ssl_status (pending, active, failed) +├── created_at +``` + +--- + +## 30. VPS & Service Management + +### VPS Self-Service Reinstall +- Customer can reinstall OS from dashboard +- Choose from available OS templates +- Warning: "This will erase all data" +- Require confirmation (type service name) +- Queue reinstall job → VirtFusion API + +### Additional IP Requests +- Customer submits form with justification +- Admin reviews in admin panel +- Approve/reject with reason +- If approved: Assign IP from pool, add to invoice + +### DNS Integration +- Integrate with Cloudflare API for DNS management +- Customer adds Cloudflare API token in settings +- Auto-create DNS records when services provisioned +- A record for VPS: `vps1.customer.com → 1.2.3.4` +- A record for hosting: `www.customer.com → hosting IP` + +--- + +## 31. Email Preferences & Notifications + +### Granular Email Control +Customer can toggle each notification type: +- ✓ Invoices (required) +- ✓ Payment receipts (required) +- ☐ Renewal reminders +- ☐ Service provisioned +- ☐ Bandwidth alerts +- ☐ Marketing emails +- ☐ Product updates +- ☐ Platform news + +### Renewal Reminder Schedule +- 30 days before renewal +- 14 days before renewal +- 7 days before renewal +- 1 day before renewal + +### Invoice Emails: Summary + PDF +``` +Subject: Invoice #INV-001234 - $48.60 Due + +Hi John, + +Your invoice is ready: + +Invoice #: INV-001234 +Amount Due: $48.60 +Due Date: Feb 15, 2026 + +Services: +- VPS Pro ($20.00) +- Web Hosting ($10.00) +- Game Server ($15.00) + +View invoice: https://account.ezscale.cloud/invoices/001234 +Download PDF: [attached] + +Payment will be automatically charged on Feb 15. +``` + +--- + +## 32. Performance & Scalability + +### Analytics Dashboard: Hybrid Approach +- **Real-time**: Today's revenue, active orders +- **Cached**: Historical charts (updated every 15 min) +- **Daily aggregation**: Month/year totals (updated nightly) + +### Queue Configuration +- **Critical queue** (priority: high) + - Service provisioning + - Payment processing + - Account suspension + +- **Normal queue** (priority: medium) + - Emails + - Notifications + - Backup jobs + +- **Low queue** (priority: low) + - Analytics aggregation + - Report generation + - Cleanup jobs + +### Laravel Horizon +- Monitor queue health +- Failed job tracking +- Retry failed jobs +- Queue metrics dashboard + +### Auto-Scaling Strategy +- Cloudflare CDN + WAF for DDoS protection +- Load balancer in front of app servers +- Auto-scale based on CPU/memory usage +- Scale up during traffic spikes (sales, launches) +- Scale down during low-traffic periods + +--- + +## 33. Provisioning API Failure Handling + +### Queue and Retry Strategy +1. Customer completes checkout, payment succeeds +2. Provisioning job added to queue +3. Attempt to provision via API (VirtFusion, Pterodactyl, etc.) +4. **If API fails:** + - Log error + - Send Discord alert to admin + - Email customer: "Service provisioning in progress, may take longer than usual" + - Retry after 5 minutes + - Retry after 15 minutes + - Retry after 30 minutes + - If still failing after 3 retries: + - Create high-priority admin ticket + - Email customer: "Provisioning delayed, our team is investigating" + - Manual admin intervention required + +### Database Schema +```sql +provisioning_logs additions: +├── retry_count (integer - how many retries) +├── next_retry_at (nullable - scheduled retry time) +├── error_details (JSON - full error response) +``` + +--- + +## 34. Cryptocurrency Payments + +### Integration via Coinbase Commerce or BTCPay +- Add "Pay with Crypto" option at checkout +- Supported coins: Bitcoin, Ethereum, USDC, USDT +- Customer selects crypto, invoice generated +- Payment detected via webhook +- Auto-convert to USD for accounting + +### Implementation Notes +- Crypto payments are one-time (not recurring subscriptions) +- Customer must manually pay each invoice with crypto +- Or: Hold credit balance (customer pre-pays in crypto, drawn down monthly) + +### Database Schema +```sql +crypto_payments table: +├── id +├── invoice_id +├── user_id +├── provider (coinbase_commerce, btcpay) +├── crypto_currency (BTC, ETH, USDC) +├── crypto_amount +├── usd_amount +├── wallet_address (where customer sent payment) +├── transaction_hash (blockchain tx) +├── status (pending, confirmed, expired) +├── confirmed_at +├── created_at +``` + +--- + +## 35. Churn Prevention: Exit Survey + Win-Back + +### Exit Survey on Cancellation +- Modal appears when customer cancels subscription +- Questions: + - "Why are you cancelling?" (multiple choice + other) + - Too expensive + - Switching to competitor + - No longer need service + - Technical issues + - Poor support + - Other (text field) + - "What could we do better?" (optional text) + - "Would you consider returning?" (Yes / Maybe / No) + +### Win-Back Email Campaign +- Triggered 30 days after cancellation +- Email sequence: + - **Day 30**: "We miss you! Here's 20% off to come back" + - **Day 45**: "Customer spotlight - see what you're missing" + - **Day 60**: "Final offer: 30% off for 3 months" +- Stop sending if customer re-subscribes + +### Database Schema +```sql +cancellation_surveys table: +├── id +├── user_id +├── subscription_id +├── cancellation_reason +├── cancellation_feedback +├── would_return (yes, maybe, no) +├── created_at + +win_back_campaigns table: +├── id +├── user_id +├── subscription_id (cancelled subscription) +├── campaign_started_at +├── emails_sent (integer) +├── last_email_sent_at +├── status (active, completed, unsubscribed, reactivated) +``` + +--- + +## Summary + +This comprehensive feature specification covers all aspects discussed during planning: + +- ✅ Advanced coupon system with A/B testing +- ✅ Immediate proration for plan changes +- ✅ Stripe Smart Retries with grace periods +- ✅ Per-plan datacenter locations +- ✅ Guided customer onboarding +- ✅ Automatic loyalty rewards program +- ✅ Dedicated server waitlist system +- ✅ Custom enterprise pricing +- ✅ GDPR-compliant automated data deletion +- ✅ Built-in uptime monitoring +- ✅ Real-time dashboard (WebSockets + polling) +- ✅ Multi-channel admin alerts (Discord, Email, SMS) +- ✅ Public status page +- ✅ Full abuse management system +- ✅ Automated fraud detection +- ✅ Game server template library +- ✅ Backups included in plans (7/4/3 retention) +- ✅ 15-minute database backups with multi-region replication +- ✅ IPv4 + IPv6 dual-stack +- ✅ Sequential invoice numbering (INV-000001) +- ✅ Full team accounts with granular permissions +- ✅ Referral credit system +- ✅ Free trial periods +- ✅ Marketing chatbot +- ✅ Comprehensive financial reports +- ✅ Login history and security audit trail +- ✅ Customer choice: consolidated or separate invoices +- ✅ Unified communication timeline +- ✅ Full-control customer API with webhooks +- ✅ Custom domain support (CNAME) +- ✅ VPS self-service OS reinstall +- ✅ Additional IP address requests +- ✅ DNS integration (Cloudflare) +- ✅ Granular email preferences +- ✅ Multiple renewal reminders +- ✅ Hybrid analytics (real-time + cached) +- ✅ Multi-queue system with Laravel Horizon +- ✅ Auto-scaling for traffic spikes +- ✅ Provisioning API failure queue-and-retry +- ✅ Cryptocurrency payment support +- ✅ Exit survey and win-back campaigns + +**All features documented and ready for implementation!** diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md new file mode 100644 index 0000000..3f2b2a0 --- /dev/null +++ b/GETTING_STARTED.md @@ -0,0 +1,393 @@ +# Getting Started - EZSCALE Billing Platform Development + +This guide will help you start building the EZSCALE Billing Platform on your development machine. + +## Prerequisites + +### Required Software +- **PHP** 8.2 or higher +- **Composer** 2.x +- **Node.js** 18.x or higher +- **npm** 9.x or higher +- **MySQL** 8.0 or higher +- **Redis** 6.x or higher +- **Git** + +### Optional but Recommended +- **Laravel Herd** (all-in-one Laravel development environment) +- **TablePlus** or **MySQL Workbench** (database GUI) +- **Redis Desktop Manager** (Redis GUI) +- **Postman** or **Insomnia** (API testing) + +## Step 1: Clone Repository + +```bash +# Clone the repository +git clone git@github.com:EZSCALE/accounting.git ezscale_billing +cd ezscale_billing + +# Create develop branch +git checkout -b develop +``` + +## Step 2: Initialize Laravel 12 Project + +Since this is currently just documentation, you'll initialize a fresh Laravel 12 project: + +```bash +# Install Laravel 12 with Vue + Inertia starter kit +composer create-project laravel/laravel . + +# During installation, select: +# - Starter kit: Vue + Inertia +# - Testing framework: Pest +# - Database: MySQL +``` + +## Step 3: Configure Environment + +```bash +# Copy the planning files (already in repo) +# .env file should already exist, update it: + +APP_NAME="EZSCALE Billing" +APP_ENV=local +APP_DEBUG=true +APP_URL=http://localhost + +DB_CONNECTION=mysql +DB_HOST=127.0.0.1 +DB_PORT=3306 +DB_DATABASE=ezscale_billing +DB_USERNAME=root +DB_PASSWORD=your_password + +REDIS_CLIENT=phpredis +REDIS_HOST=127.0.0.1 +REDIS_PASSWORD=null +REDIS_PORT=6379 + +# Stripe keys (get from Stripe dashboard) +STRIPE_KEY=pk_test_... +STRIPE_SECRET=sk_test_... + +# PayPal credentials (get from PayPal developer dashboard) +PAYPAL_MODE=sandbox +PAYPAL_SANDBOX_CLIENT_ID=... +PAYPAL_SANDBOX_CLIENT_SECRET=... + +# Email (choose Mailgun or SendGrid) +MAIL_MAILER=smtp +MAIL_HOST=smtp.mailgun.org +MAIL_PORT=587 +MAIL_USERNAME=... +MAIL_PASSWORD=... +MAIL_FROM_ADDRESS=noreply@ezscale.cloud +MAIL_FROM_NAME="EZSCALE Hosting" + +# Discord webhook for admin alerts +DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/... +``` + +## Step 4: Create Database + +```bash +# Connect to MySQL +mysql -u root -p + +# Create database +CREATE DATABASE ezscale_billing CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +EXIT; +``` + +## Step 5: Install Dependencies + +```bash +# Install PHP dependencies +composer require laravel/cashier +composer require laravel/fortify +composer require laravel/passport +composer require srmklive/laravel-paypal +composer require spatie/laravel-permission +composer require --dev laravel/telescope + +# Install Node dependencies +npm install +``` + +## Step 6: Add Vuexy Theme + +```bash +# Extract Vuexy theme source files to: +# resources/js/vuexy/ +# resources/css/vuexy/ + +# Update vite.config.js to include Vuexy assets +# Update app.js to import Vuexy components + +# Detailed integration instructions in Vuexy documentation +``` + +## Step 7: Run Migrations + +```bash +# Generate app key +php artisan key:generate + +# Run Laravel's default migrations +php artisan migrate + +# Publish Cashier migrations +php artisan vendor:publish --tag="cashier-migrations" + +# Publish Passport migrations +php artisan passport:install + +# Publish Spatie migrations +php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" + +# Now create your custom migrations (see PROJECT_DEVELOPMENT.md for schema) +# php artisan make:migration create_user_profiles_table +# php artisan make:migration create_plans_table +# ... etc + +# Run all migrations +php artisan migrate +``` + +## Step 8: Seed Initial Data + +```bash +# Create seeders +php artisan make:seeder RoleSeeder +php artisan make:seeder PlanSeeder +php artisan make:seeder DatacenterSeeder + +# Run seeders +php artisan db:seed +``` + +## Step 9: Configure Authentication + +```bash +# Publish Fortify views +php artisan vendor:publish --tag=fortify-views + +# Install Fortify +php artisan fortify:install + +# Configure Fortify features in config/fortify.php +# Enable: registration, reset passwords, email verification, two factor + +# Set up Passport for OAuth2 (SSO later) +php artisan passport:install +``` + +## Step 10: Start Development Servers + +```bash +# Terminal 1: Start Laravel server +php artisan serve + +# Terminal 2: Start Vite dev server +npm run dev + +# Terminal 3: Start queue worker +php artisan queue:work + +# Optional Terminal 4: Start Horizon (queue monitoring) +php artisan horizon +``` + +## Step 11: Configure Local Domains (Optional) + +If using Laravel Herd or Valet, you can set up local domains: + +```bash +# With Herd/Valet +ezscale.test -> Marketing site +account.ezscale.test -> Customer dashboard +admin.ezscale.test -> Admin panel +``` + +Update `.env`: +``` +APP_URL=http://ezscale.test +``` + +## Step 12: Set Up Testing + +```bash +# Create test database +CREATE DATABASE ezscale_billing_test; + +# Update phpunit.xml or .env.testing +DB_DATABASE=ezscale_billing_test + +# Run tests +php artisan test +``` + +## Development Workflow + +### Daily Development +```bash +# Pull latest changes +git pull origin develop + +# Install any new dependencies +composer install +npm install + +# Run migrations +php artisan migrate + +# Start dev servers +php artisan serve +npm run dev +php artisan queue:work +``` + +### Creating Features +```bash +# Create feature branch from develop +git checkout develop +git pull +git checkout -b feature/billing-system + +# Make changes, commit often +git add . +git commit -m "Add Stripe billing service" + +# Push to remote +git push origin feature/billing-system + +# Create PR on GitHub: feature/billing-system -> develop +``` + +### Running Tests +```bash +# Run all tests +php artisan test + +# Run specific test +php artisan test --filter BillingServiceTest + +# Run with coverage +php artisan test --coverage +``` + +## Phase 1 Checklist + +Use this checklist to track Phase 1 Foundation progress: + +- [ ] Laravel 12 project initialized +- [ ] Vuexy theme integrated +- [ ] Environment configured (.env) +- [ ] Database created and connected +- [ ] All dependencies installed (Cashier, Fortify, Passport, PayPal, Spatie) +- [ ] Custom migrations created (see PROJECT_DEVELOPMENT.md for full schema) + - [ ] user_profiles + - [ ] plans + - [ ] datacenters + - [ ] payment_transactions + - [ ] services + - [ ] provisioning_logs + - [ ] bandwidth_usage + - [ ] audit_logs + - [ ] support_tickets (mirror) + - [ ] announcements +- [ ] Migrations run successfully +- [ ] Seeders created and run +- [ ] Fortify authentication configured +- [ ] Passport OAuth2 set up +- [ ] Spatie roles configured (admin, customer) +- [ ] Redis working +- [ ] Queue working +- [ ] Email sending working (test with Mailtrap initially) +- [ ] Git repository initialized +- [ ] CI/CD pipeline set up (GitHub Actions) +- [ ] Staging environment created + +## Common Issues & Solutions + +### Issue: Composer dependencies conflict +**Solution**: Check PHP version (must be 8.2+), update composer.json constraints + +### Issue: npm install fails +**Solution**: Delete node_modules and package-lock.json, run `npm install` again + +### Issue: Database connection refused +**Solution**: Check MySQL is running, verify credentials in .env + +### Issue: Redis connection failed +**Solution**: Start Redis server: `redis-server` or check if running with `redis-cli ping` + +### Issue: Vite not compiling +**Solution**: Clear Vite cache: `npm run build`, restart `npm run dev` + +### Issue: Queue jobs not processing +**Solution**: Ensure `php artisan queue:work` is running, check Redis connection + +## API Credentials You'll Need + +Before full development, obtain these API credentials: + +### Payment Gateways +- [ ] Stripe test keys (pk_test_, sk_test_) +- [ ] Stripe production keys (pk_live_, sk_live_) +- [ ] PayPal sandbox credentials +- [ ] PayPal production credentials + +### Provisioning APIs +- [ ] VirtFusion API key +- [ ] Pterodactyl API token +- [ ] SynergyCP API credentials +- [ ] Enhance API key + +### External Services +- [ ] SupportPal API credentials +- [ ] ElastiFlow API access +- [ ] Mailgun or SendGrid API key +- [ ] Discord webhook URL +- [ ] Twilio credentials (for SMS alerts - optional) +- [ ] Cloudflare API token (for DNS integration) +- [ ] Coinbase Commerce API (for crypto payments - optional) + +### Development Tools +- [ ] GitHub personal access token (for Actions) +- [ ] Sentry DSN (for error tracking - optional) + +## Documentation Reference + +As you build, refer to these files: + +| File | When to Reference | +|------|-------------------| +| **PROJECT_DEVELOPMENT.md** | Architecture decisions, database schema, API integrations | +| **TASKS.md** | Task checklist, what to build in each phase | +| **FEATURES.md** | Detailed feature specifications, implementation notes | +| **CLAUDE.md** | Code conventions, security requirements | + +## Next Steps After Phase 1 + +Once Phase 1 is complete: +1. Review Phase 1 deliverables +2. Demo authentication flow +3. Verify all integrations are working (test API connections) +4. Begin Phase 2: Billing & Subscriptions + +## Getting Help + +- **Laravel Documentation**: https://laravel.com/docs/12.x +- **Vuexy Documentation**: Check included docs in theme package +- **Cashier Documentation**: https://laravel.com/docs/12.x/billing +- **Project Planning Docs**: See CLAUDE.md, PROJECT_DEVELOPMENT.md, FEATURES.md + +## Development Team + +Add team member contact information here as project progresses. + +--- + +**Ready to build?** Start with Phase 1 tasks from TASKS.md! diff --git a/IDEAS.md b/IDEAS.md new file mode 100644 index 0000000..c057197 --- /dev/null +++ b/IDEAS.md @@ -0,0 +1,531 @@ +# IDEAS.md - Future Feature Ideas & Exploration Topics + +This document contains ideas for future exploration and features that haven't been fully planned yet. Use this as a starting point for future planning sessions. + +--- + +## 1. Integration with Specific Tools + +### Monitoring & Observability +- **Grafana Integration**: Embed Grafana dashboards in customer portal +- **Prometheus Metrics**: Expose service metrics for customer scraping +- **Datadog/New Relic**: Pre-configured APM for customer applications +- **Sentry Integration**: Error tracking for customer apps with EZSCALE-managed Sentry +- **PagerDuty/OpsGenie**: Incident management integration for enterprise customers + +### Analytics & Business Intelligence +- **Google Analytics 4**: Deep integration for marketing site and customer behavior +- **Mixpanel/Amplitude**: Product analytics for customer journey tracking +- **Segment**: Customer data platform for unified analytics +- **Metabase/Redash**: Embedded business intelligence dashboards + +### Development Tools +- **GitHub Actions Runners**: Offer hosted GitHub Actions runners as a service +- **GitLab CI/CD**: Managed GitLab runners for customer pipelines +- **Docker Registry**: Private Docker registry hosting per customer +- **Kubernetes Clusters**: Managed K8s clusters (EKS/GKE-style offering) + +### Communication Tools +- **Slack Integration**: Service alerts to customer Slack channels +- **Microsoft Teams**: Notifications and bot commands +- **Webhook Relays**: Reliable webhook delivery service +- **SMS Alerts**: Twilio integration for critical service alerts + +--- + +## 2. Advanced Security Features + +### Enhanced Authentication +- **Hardware Security Keys**: YubiKey, Titan Key support (beyond passkeys) +- **Biometric Authentication**: TouchID/FaceID for mobile web +- **Certificate-Based Auth**: Client certificates for API access +- **SAML/OIDC Provider**: Act as identity provider for customer apps + +### Security Scanning +- **Vulnerability Scanning**: Automated CVE scanning for customer VPS +- **Container Security**: Scan Docker images for vulnerabilities +- **SSL/TLS Monitoring**: Cert expiry tracking and auto-renewal alerts +- **Security Scorecard**: Customer-facing security posture dashboard + +### Compliance & Auditing +- **HIPAA Compliance**: BAA agreements, encrypted backups, audit logging +- **PCI DSS**: For customers processing payments +- **FedRAMP**: Government cloud compliance (long-term) +- **Automated Compliance Reports**: Generate SOC 2, ISO 27001 evidence + +### Advanced Threat Protection +- **WAF (Web Application Firewall)**: ModSecurity integration or Cloudflare +- **SIEM Integration**: Security Information and Event Management +- **Intrusion Detection**: IDS/IPS for network monitoring +- **Honeypot Services**: Decoy services to detect attackers + +--- + +## 3. International & Localization Features + +### Multi-Language Support +- **UI Translation**: Support for 10+ languages (ES, FR, DE, PT, ZH, JA, KO) +- **RTL Languages**: Right-to-left support (Arabic, Hebrew) +- **Currency Localization**: Display prices in local currency +- **Date/Time Formats**: Region-appropriate formatting + +### Regional Compliance +- **GDPR Tools**: Cookie consent, data portability, deletion workflows +- **China Compliance**: ICP licensing support for Chinese customers +- **Brazil LGPD**: Brazilian data protection compliance +- **Australia Privacy Act**: Regional compliance features + +### Geographic Expansion +- **Multi-Region Support**: Add Asia-Pacific, EU, South America datacenters +- **Region Selection UI**: Map-based datacenter selection +- **Latency Testing**: Pre-purchase latency tests from customer location +- **Local Payment Methods**: Alipay, WeChat Pay, PIX (Brazil), UPI (India) + +### Tax Complexity +- **VAT MOSS**: EU VAT Mini One Stop Shop +- **GST Support**: Goods and Services Tax (India, Australia, Canada) +- **Local Tax Integrations**: Country-specific tax API integrations +- **Tax Exemption Certificates**: Upload and validate tax exemption docs + +--- + +## 4. More Automation & AI Capabilities + +### Predictive Analytics +- **Churn Prediction**: ML model to predict customer churn before it happens +- **Usage Forecasting**: Predict future resource needs weeks in advance +- **Anomaly Detection**: Auto-detect unusual patterns (security or performance) +- **Revenue Forecasting**: Predict MRR/ARR based on trends + +### Intelligent Automation +- **Auto-Scaling**: Automatically upgrade services when hitting resource limits +- **Smart Scheduling**: AI-optimized task scheduling (backups during low usage) +- **Capacity Planning**: AI suggests when to add hypervisors based on growth +- **Resource Right-Sizing**: Continuously optimize resource allocation + +### Conversational AI +- **Voice Assistant**: "Alexa, what's my current server status?" +- **Natural Language Commands**: "Create a VPS in New York with 4GB RAM" +- **Smart Search**: Semantic search across docs, services, tickets +- **Personalized Recommendations**: AI suggests services based on usage patterns + +### Automated Support +- **Ticket Categorization**: Auto-tag and route tickets to right team +- **Response Suggestions**: Suggest replies to common support questions +- **Knowledge Base AI**: Auto-generate KB articles from resolved tickets +- **Sentiment Analysis**: Detect frustrated customers, prioritize their tickets + +--- + +## 5. Advanced Networking Features + +### Software-Defined Networking +- **Virtual Private Cloud (VPC)**: Isolated networks per customer +- **VPN-as-a-Service**: Managed WireGuard/OpenVPN servers +- **Private Interconnects**: High-speed links between datacenters +- **Network ACLs**: Firewall rules at network level + +### Load Balancing & Traffic Management +- **Managed Load Balancers**: HAProxy, NGINX as a service +- **Global Load Balancing**: GeoDNS-based traffic routing +- **DDoS Mitigation**: Wanguard integration (mentioned earlier) +- **CDN Integration**: Built-in CDN for static content + +### DNS Management +- **Managed DNS Service**: Authoritative DNS hosting +- **DNSSEC**: Secure DNS with signing +- **Dynamic DNS**: DynDNS-style service for changing IPs +- **DNS Analytics**: Query analytics and threat detection + +### IPv6 Advanced +- **IPv6-Only Plans**: Cheaper plans with IPv6-only (NAT64 for legacy) +- **Prefix Delegation**: Customer can delegate subnets +- **IPv6 Rapid Deployment**: Auto-configure IPv6 for new services + +--- + +## 6. Platform-as-a-Service (PaaS) Features + +### Application Hosting +- **One-Click Apps**: WordPress, Drupal, Magento, Ghost, etc. +- **Container Platform**: Managed Docker/Kubernetes for apps +- **Serverless Functions**: AWS Lambda-style FaaS +- **Static Site Hosting**: Netlify/Vercel competitor + +### Database-as-a-Service +- **Managed MySQL**: HA MySQL clusters +- **Managed PostgreSQL**: With point-in-time recovery +- **Managed Redis**: Redis cluster management +- **Managed MongoDB**: NoSQL database service + +### Development Platforms +- **CI/CD Pipelines**: Hosted build and deployment +- **Preview Environments**: Auto-deploy PR previews +- **Code Repositories**: Hosted Git (GitLab-style) +- **Development Workspaces**: More Kasm integration (IDE-as-a-Service) + +--- + +## 7. Enterprise Features + +### Multi-Organization Support +- **Organization Hierarchy**: Parent/child org structures +- **Consolidated Billing**: Bill parent org for all child orgs +- **Cross-Org Resource Sharing**: Share resources between orgs +- **Org-Level Policies**: Enforce security policies across org + +### Advanced Billing +- **Usage-Based Pricing**: Per-API-call, per-GB-transferred pricing +- **Committed Use Discounts**: Discount for 1-3 year commitments +- **Volume Licensing**: Tiered pricing based on total spend +- **Purchase Orders**: PO support for enterprise customers + +### Service Level Agreements (SLA) +- **Uptime SLAs**: 99.9%, 99.95%, 99.99% tiers with credits +- **Support SLAs**: Response time guarantees +- **SLA Credits**: Automatic credit issuance for breaches +- **Custom SLAs**: Negotiated agreements for enterprise + +### Professional Services +- **Migration Services**: Migrate from competitor (DigitalOcean, AWS, etc.) +- **Architecture Consulting**: Design customer infrastructure +- **Training Programs**: Certification courses for EZSCALE platform +- **Managed Services**: White-glove management of customer infrastructure + +--- + +## 8. Marketplace & Ecosystem + +### Third-Party Add-Ons +- **Plugin Marketplace**: Third-party tools and integrations +- **Partner Services**: Vetted partners (backup, monitoring, security) +- **Revenue Sharing**: Partners sell through EZSCALE, revenue split +- **API for Partners**: Partner API for deep integrations + +### Developer Ecosystem +- **SDK Libraries**: Official SDKs (Python, PHP, Node.js, Go, Ruby) +- **CLI Tool**: Command-line tool for EZSCALE management +- **VS Code Extension**: Manage services from VS Code +- **Postman Collection**: Pre-built API collection + +### Community Contributions +- **Open Source Templates**: Community-contributed server configs +- **Automation Scripts**: Share Ansible/Terraform configs +- **Community Leaderboard**: Top contributors get rewards +- **Bounty Program**: Pay for feature requests, bug reports + +--- + +## 9. Advanced Customer Experience + +### Self-Service Portal Enhancements +- **Custom Dashboards**: Drag-and-drop dashboard builder +- **Saved Filters**: Save common service filters +- **Bulk Actions**: Select multiple services, perform actions +- **Quick Actions**: Keyboard shortcuts for power users + +### Mobile Experience +- **Progressive Web App**: Installable, offline-capable +- **Mobile Notifications**: Push notifications for mobile devices +- **Touch-Optimized UI**: Better mobile gestures +- **Mobile-First Features**: Quick actions, simplified views + +### Accessibility +- **WCAG 2.1 AA Compliance**: Full accessibility support +- **Screen Reader Optimization**: Semantic HTML, ARIA labels +- **Keyboard Navigation**: Full keyboard accessibility +- **High Contrast Mode**: For visually impaired users + +### Personalization +- **Dashboard Themes**: Light, dark, custom themes +- **Widget Customization**: Show/hide dashboard widgets +- **Default Views**: Remember user preferences +- **Recommended Services**: Based on usage patterns + +--- + +## 10. Environmental & Sustainability + +### Green Hosting +- **Carbon Neutral Datacenters**: 100% renewable energy +- **Carbon Offset Program**: Offset customer infrastructure +- **Energy Efficiency Metrics**: Show power usage effectiveness (PUE) +- **Green Badges**: Highlight eco-friendly service options + +### Efficiency Reporting +- **Power Usage Dashboard**: Show energy consumption +- **Efficiency Score**: Grade services on energy efficiency +- **Optimization Suggestions**: Reduce power consumption tips +- **Sustainability Report**: Annual sustainability report for customers + +--- + +## 11. Financial & Payment Enhancements + +### Alternative Payment Methods +- **Buy Now, Pay Later**: Affirm, Klarna integration +- **ACH/Bank Transfer**: Direct bank payments +- **Wire Transfers**: For large enterprise payments +- **Cryptocurrency Wallets**: Native wallet integration (not just Coinbase) + +### Financial Management +- **Expense Categorization**: Tag expenses for accounting +- **Multi-Entity Billing**: Bill different legal entities separately +- **Tax Documents**: Auto-generate 1099s, VAT invoices +- **Financial Forecasting**: Predict future spend based on usage + +### Revenue Optimization +- **Dynamic Pricing**: Adjust prices based on demand +- **Promotional Pricing**: Time-limited offers, flash sales +- **Bundle Discounts**: Discount for service bundles +- **Loyalty Pricing**: Better pricing for long-term customers + +--- + +## 12. Advanced Monitoring & Observability + +### Application Performance Monitoring +- **Built-in APM**: Monitor app performance without external tools +- **Distributed Tracing**: Trace requests across microservices +- **Log Aggregation**: Centralized logging service +- **Metrics Dashboard**: Custom metrics from customer apps + +### Infrastructure Monitoring +- **Node Exporter**: Prometheus node metrics +- **Custom Metrics API**: Push custom metrics to platform +- **Alerting Rules**: Custom alert rules based on metrics +- **Anomaly Detection**: ML-based anomaly detection + +### Synthetic Monitoring +- **Uptime Checks**: Monitor from multiple global locations +- **API Monitoring**: Test API endpoints periodically +- **Performance Budgets**: Alert when performance degrades +- **Transaction Monitoring**: Monitor critical user flows + +--- + +## 13. Disaster Recovery & Business Continuity + +### Backup Enhancements +- **Geo-Redundant Backups**: Store backups in multiple regions +- **Backup Encryption**: Customer-managed encryption keys +- **Backup Testing**: Automated restore testing +- **Backup Retention Policies**: Customizable retention rules + +### Disaster Recovery +- **DR-as-a-Service**: Managed disaster recovery +- **Failover Automation**: Auto-failover to DR site +- **RPO/RTO Targets**: Guarantee recovery objectives +- **DR Testing**: Scheduled DR drills + +### High Availability +- **Active-Active Deployments**: Multi-region active setups +- **Database Replication**: Real-time multi-region replication +- **Zero-Downtime Migrations**: Live migration between hypervisors +- **Chaos Engineering**: Test resilience with controlled failures + +--- + +## 14. Developer Experience (DevEx) + +### API Enhancements +- **GraphQL API**: Alternative to REST API +- **WebSocket API**: Real-time API for streaming updates +- **gRPC Support**: High-performance RPC protocol +- **API Versioning**: Maintain old API versions for compatibility + +### Testing & Staging +- **Sandbox Environments**: Test API calls without real charges +- **Staging Infrastructure**: Clone prod to staging +- **Feature Flags**: Test features before full release +- **A/B Testing Framework**: Built-in A/B testing for customer apps + +### Documentation +- **Interactive API Docs**: Try API calls directly in docs +- **Code Generators**: Generate API client code +- **Tutorials & Guides**: Step-by-step integration guides +- **Video Tutorials**: Screencasts for common tasks + +--- + +## 15. Data & Analytics + +### Customer Analytics +- **User Behavior Tracking**: How customers use the platform +- **Feature Adoption**: Which features are used most +- **Drop-off Analysis**: Where customers abandon flows +- **Session Recording**: Watch customer sessions (privacy-conscious) + +### Business Intelligence +- **Executive Dashboard**: High-level metrics for leadership +- **Predictive Reports**: Forecast future performance +- **Benchmarking**: Compare against industry averages +- **Data Warehouse**: Export all data to customer's warehouse + +### Data Export & Portability +- **Bulk Export API**: Export all customer data +- **Data Pipeline**: Stream data to customer systems +- **Webhook Replay**: Replay missed webhooks +- **Audit Log Export**: Compliance-friendly log exports + +--- + +## 16. Unique/Innovative Ideas + +### Blockchain Integration +- **NFT-Based Licensing**: Server licenses as NFTs +- **Smart Contracts**: Billing via smart contracts +- **Decentralized Storage**: IPFS integration for backups +- **Crypto Mining Protection**: Detect and prevent mining abuse + +### AI-Powered Infrastructure +- **Auto-Remediation**: AI fixes common issues automatically +- **Predictive Maintenance**: Predict hardware failures before they happen +- **Intelligent Routing**: AI-optimized traffic routing +- **Resource Allocation**: AI decides optimal resource placement + +### Experimental Services +- **Edge Computing**: Deploy to edge locations near users +- **GPU Instances**: For ML/AI workloads +- **FPGA Instances**: For specialized compute +- **Quantum Computing**: Access to quantum computers (future) + +### Social Features +- **Server Showcases**: Customers show off their setups +- **Competitions**: Hackathons, best setup contests +- **User Groups**: Regional or topic-based user groups +- **Events & Meetups**: EZSCALE-hosted community events + +--- + +## 17. Operational Efficiency + +### Automation +- **Runbook Automation**: Auto-execute common operational tasks +- **Self-Healing**: Auto-fix detected issues +- **Automated Scaling**: Scale infrastructure based on demand +- **Smart Scheduling**: AI-optimized maintenance windows + +### Internal Tools +- **Admin Mobile App**: Manage platform from mobile +- **Incident Management**: Structured incident response workflow +- **Change Management**: Track and approve infrastructure changes +- **Knowledge Management**: Internal wiki for team + +### Customer Success +- **Health Scores**: Track customer health (NPS, usage, support) +- **Proactive Outreach**: Reach out before customers churn +- **Success Plans**: Onboarding and growth plans +- **Executive Business Reviews**: Quarterly reviews with enterprise customers + +--- + +## 18. Reseller & Partner Program Enhancements + +### Reseller Tools +- **White-Label Mobile App**: Branded mobile apps for resellers +- **Custom API Domain**: api.reseller.com instead of api.ezscale.cloud +- **Reseller Analytics**: Track reseller performance +- **Marketing Materials**: Co-branded marketing assets + +### Partner Integrations +- **Technology Partners**: Deep integrations with complementary services +- **Channel Partners**: Agencies selling EZSCALE +- **OEM Partnerships**: Embed EZSCALE in other products +- **Affiliate Network**: Broader affiliate program + +--- + +## 19. Emerging Technologies + +### Web3 & Decentralization +- **Decentralized Identity**: DID for customer authentication +- **Token-Based Economy**: Loyalty tokens, governance tokens +- **DAO Governance**: Customer voting on feature roadmap +- **Decentralized Support**: Community-powered support with token rewards + +### AR/VR +- **VR Data Center Tours**: Virtual tour of datacenters +- **AR Troubleshooting**: AR overlays for server maintenance +- **3D Infrastructure Visualization**: Visualize infrastructure in 3D + +### IoT Integration +- **IoT Device Management**: Manage customer IoT devices +- **Edge Processing**: Process IoT data at edge +- **Device Provisioning**: Auto-provision devices +- **IoT Analytics**: Analyze device data + +--- + +## 20. Content & Education + +### Learning Platform +- **EZSCALE Academy**: Courses on hosting, DevOps, cloud +- **Certification Program**: Certified EZSCALE Administrator +- **Webinars**: Regular educational webinars +- **Workshops**: Hands-on training sessions + +### Content Library +- **Case Studies**: Success stories from customers +- **White Papers**: Technical deep-dives +- **Benchmarks**: Performance comparisons +- **Industry Reports**: State of hosting industry + +### Community Resources +- **Blog Platform**: Customer blogging on EZSCALE subdomain +- **Podcast**: EZSCALE-hosted tech podcast +- **YouTube Channel**: Tutorials, interviews, updates +- **Newsletter**: Weekly/monthly newsletter + +--- + +## Implementation Priority Framework + +When deciding which ideas to implement, consider: + +### Priority Matrix + +**High Impact + Easy to Implement:** +- Quick wins, do these first +- Examples: Basic monitoring integrations, simple automation + +**High Impact + Hard to Implement:** +- Strategic investments, plan carefully +- Examples: Full PaaS, multi-region expansion + +**Low Impact + Easy to Implement:** +- Nice-to-haves, do when time permits +- Examples: Dashboard themes, minor UI improvements + +**Low Impact + Hard to Implement:** +- Probably skip these +- Examples: Blockchain features (unless business model changes) + +### Decision Criteria + +1. **Customer Demand**: Are customers asking for it? +2. **Competitive Advantage**: Does it differentiate from competitors? +3. **Revenue Impact**: Will it increase revenue or reduce churn? +4. **Technical Feasibility**: Can we build it with current team/resources? +5. **Strategic Fit**: Aligns with company vision and roadmap? + +--- + +## Next Steps + +When ready to explore any of these ideas: + +1. **Review this document** - Pick 2-3 ideas that seem most valuable +2. **Deep dive session** - Spend time planning the selected ideas in detail +3. **Prototype** - Build quick proof-of-concept for validation +4. **Customer research** - Survey customers on the ideas +5. **Prioritize** - Add to roadmap based on impact and effort +6. **Execute** - Build, test, launch + +--- + +**This document is a living ideas repository. Add new ideas as they come up during team brainstorms, customer conversations, or competitive analysis.** + +**Last Updated**: February 8, 2026 +**Contributors**: Planning Session with Claude +**Status**: Ideation - Not Yet Planned diff --git a/KASM_AND_MULTITENANCY.md b/KASM_AND_MULTITENANCY.md new file mode 100644 index 0000000..30a546c --- /dev/null +++ b/KASM_AND_MULTITENANCY.md @@ -0,0 +1,923 @@ +# Kasm Workspaces & Multi-Tenancy Implementation + +## Overview +This document details the implementation plan for: +1. **Kasm Workspaces** - Cloud desktop/workspace service with hourly billing +2. **Multi-Tenancy** - White-label reseller platform using Tenancy for Laravel + +--- + +## Part 1: Kasm Workspaces Integration + +### What is Kasm Workspaces? +Kasm Workspaces provides streaming containerized apps and desktops to end-users. It's perfect for: +- **Developer Workspaces**: Pre-configured dev environments (VS Code, IDEs, terminals) +- **Business Workspaces**: Office apps, browsers, secure remote work environments + +**Official Docs**: https://docs.kasm.com/ +**Developer API**: https://docs.kasm.com/docs/latest/developers/developer_api/ + +### Service Offerings + +| Workspace Type | Use Case | Target Customers | +|----------------|----------|------------------| +| **Developer Basic** | 2 vCPU, 4GB RAM, Linux with VS Code | Freelance developers, students | +| **Developer Pro** | 4 vCPU, 8GB RAM, multiple IDEs, Docker | Professional developers, small teams | +| **Developer Enterprise** | 8 vCPU, 16GB RAM, full dev stack | Development teams, agencies | +| **Business Basic** | 2 vCPU, 4GB RAM, Browser + Office apps | Remote workers, contractors | +| **Business Pro** | 4 vCPU, 8GB RAM, Full office suite | Business users, managers | +| **Business Enterprise** | 8 vCPU, 16GB RAM, Custom apps | Executives, power users | + +### Provisioning Strategy + +**Fully Automated Provisioning** +1. Customer selects workspace type and template +2. Payment processed (either subscription or credits added) +3. Kasm API called to create workspace +4. Workspace URL and credentials sent via email +5. Customer can access workspace immediately + +### Kasm API Integration + +#### Key API Endpoints +```http +POST /api/public/create_workspace +Parameters: +- workspace_type (developer_basic, business_pro, etc.) +- user_id +- session_duration (optional) + +Response: +{ + "workspace_id": "abc-123", + "access_url": "https://kasm.ezscale.cloud/workspace/abc-123", + "username": "user@email.com", + "password": "generated_password" +} + +POST /api/public/destroy_workspace +Parameters: +- workspace_id + +GET /api/public/workspace_status +Parameters: +- workspace_id + +Response: +{ + "status": "running", + "uptime_seconds": 3600, + "cpu_usage_percent": 45, + "ram_usage_mb": 2048 +} + +POST /api/public/stop_workspace +POST /api/public/start_workspace +``` + +#### Authentication +- API Key authentication via headers +- `X-API-Key: ` and `X-API-Secret: ` +- Keys generated in Kasm admin panel + +### Database Schema + +```sql +kasm_workspaces table: +├── id +├── user_id +├── service_id (links to main services table) +├── workspace_type (developer_basic, business_pro, etc.) +├── kasm_workspace_id (Kasm's internal ID) +├── access_url +├── username (workspace login) +├── password_encrypted +├── status (provisioning, running, stopped, terminated) +├── vcpu (2, 4, 8) +├── ram_mb (4096, 8192, 16384) +├── template_name (Ubuntu with VS Code, Windows 11 Business, etc.) +├── created_at +├── provisioned_at +├── last_started_at +├── last_stopped_at +├── terminated_at + +kasm_usage_sessions table: +├── id +├── kasm_workspace_id +├── started_at +├── stopped_at (nullable - ongoing session) +├── duration_seconds (calculated) +├── duration_billable_seconds (rounded to 15-min increments) +├── cost_per_hour (rate at time of use) +├── total_cost (duration_billable_seconds / 3600 * cost_per_hour) +├── invoice_id (nullable - which invoice this was billed on) +├── created_at + +kasm_workspace_templates table: +├── id +├── name (Ubuntu 22.04 + VS Code) +├── description +├── workspace_type (developer, business) +├── kasm_template_id (Kasm's image ID) +├── icon_url +├── vcpu_default +├── ram_mb_default +├── preinstalled_apps (JSON array) +├── status (active, deprecated) +├── sort_order +``` + +### Hourly Billing Model + +#### Billing Calculation +- **15-minute increments** (round up) +- Examples: + - 8 minutes = 15 minutes = $0.05 (if $0.20/hour) + - 22 minutes = 30 minutes = $0.10 + - 1 hour 5 minutes = 1 hour 15 minutes = $0.25 + +#### Pricing Structure +| Workspace Type | vCPU | RAM | Price per Hour | +|----------------|------|-----|----------------| +| Developer Basic | 2 | 4GB | $0.15 | +| Developer Pro | 4 | 8GB | $0.30 | +| Developer Enterprise | 8 | 16GB | $0.60 | +| Business Basic | 2 | 4GB | $0.20 | +| Business Pro | 4 | 8GB | $0.40 | +| Business Enterprise | 8 | 16GB | $0.80 | + +**Note**: Pricing subject to adjustment based on Kasm licensing costs and infrastructure overhead. + +#### Hybrid Billing Approach +- **Real-time tracking**: Dashboard shows current running cost +- **Monthly invoicing**: All usage invoiced at end of billing cycle +- **Running total**: Customer sees "Current month usage: $47.35" in real-time +- **Low balance alerts**: Warn when usage approaching credit limit + +### Implementation Flow + +#### 1. Customer Orders Workspace +```php +// routes/web.php +Route::post('/kasm/order', [KasmController::class, 'createOrder']) + ->middleware(['auth', 'verified']); + +// app/Http/Controllers/KasmController.php +public function createOrder(Request $request) +{ + $plan = Plan::findOrFail($request->plan_id); + + // Validate customer has credits or payment method + if ($user->account_credits < 5.00 && !$user->hasPaymentMethod()) { + return back()->with('error', 'Add credits or payment method first'); + } + + // Create service record + $service = Service::create([ + 'user_id' => $user->id, + 'plan_id' => $plan->id, + 'service_type' => 'kasm_workspace', + 'status' => 'provisioning', + ]); + + // Queue provisioning job + ProvisionKasmWorkspace::dispatch($service); + + return redirect()->route('services.show', $service) + ->with('success', 'Workspace is being provisioned...'); +} +``` + +#### 2. Provisioning Job +```php +// app/Jobs/ProvisionKasmWorkspace.php +class ProvisionKasmWorkspace implements ShouldQueue +{ + public function handle() + { + $kasmService = app(KasmProvisioningService::class); + + try { + // Call Kasm API to create workspace + $result = $kasmService->createWorkspace([ + 'workspace_type' => $this->service->plan->kasm_workspace_type, + 'vcpu' => $this->service->plan->vcpu, + 'ram_mb' => $this->service->plan->ram_mb, + 'template' => $this->service->plan->kasm_template_id, + ]); + + // Store workspace details + KasmWorkspace::create([ + 'service_id' => $this->service->id, + 'user_id' => $this->service->user_id, + 'workspace_type' => $this->service->plan->kasm_workspace_type, + 'kasm_workspace_id' => $result['workspace_id'], + 'access_url' => $result['access_url'], + 'username' => $result['username'], + 'password_encrypted' => encrypt($result['password']), + 'status' => 'running', + 'vcpu' => $this->service->plan->vcpu, + 'ram_mb' => $this->service->plan->ram_mb, + 'provisioned_at' => now(), + 'last_started_at' => now(), + ]); + + // Start usage session + KasmUsageSession::create([ + 'kasm_workspace_id' => $workspace->id, + 'started_at' => now(), + 'cost_per_hour' => $this->service->plan->price_per_hour, + ]); + + // Update service status + $this->service->update([ + 'status' => 'active', + 'provisioned_at' => now(), + ]); + + // Send email with credentials + Mail::to($this->service->user)->send( + new KasmWorkspaceProvisioned($workspace) + ); + + } catch (\Exception $e) { + // Handle provisioning failure + Log::error('Kasm provisioning failed', [ + 'service_id' => $this->service->id, + 'error' => $e->getMessage(), + ]); + + $this->service->update(['status' => 'failed']); + + // Alert admin via Discord + app(DiscordNotificationService::class)->sendAlert([ + 'title' => 'Kasm Provisioning Failed', + 'message' => "Service #{$this->service->id} failed to provision", + 'error' => $e->getMessage(), + ]); + } + } +} +``` + +#### 3. Usage Tracking +```php +// app/Console/Commands/TrackKasmUsage.php +// Run every 15 minutes via cron + +class TrackKasmUsage extends Command +{ + public function handle() + { + $activeWorkspaces = KasmWorkspace::where('status', 'running')->get(); + + foreach ($activeWorkspaces as $workspace) { + // Check if workspace is still running via API + $status = app(KasmProvisioningService::class) + ->getWorkspaceStatus($workspace->kasm_workspace_id); + + if ($status['status'] === 'stopped') { + // Workspace was stopped, close usage session + $session = KasmUsageSession::where('kasm_workspace_id', $workspace->id) + ->whereNull('stopped_at') + ->first(); + + if ($session) { + $session->update([ + 'stopped_at' => now(), + 'duration_seconds' => now()->diffInSeconds($session->started_at), + ]); + + // Calculate billable duration (round to 15-min increments) + $minutes = ceil($session->duration_seconds / 60); + $billableMinutes = ceil($minutes / 15) * 15; + $billableSeconds = $billableMinutes * 60; + + $session->update([ + 'duration_billable_seconds' => $billableSeconds, + 'total_cost' => ($billableSeconds / 3600) * $session->cost_per_hour, + ]); + } + + $workspace->update(['status' => 'stopped']); + } + } + } +} +``` + +#### 4. Monthly Billing +```php +// app/Console/Commands/BillKasmUsage.php +// Run monthly on billing cycle date + +class BillKasmUsage extends Command +{ + public function handle() + { + $users = User::has('kasmWorkspaces')->get(); + + foreach ($users as $user) { + // Get unbilled usage sessions + $sessions = KasmUsageSession::whereHas('workspace', function ($q) use ($user) { + $q->where('user_id', $user->id); + }) + ->whereNull('invoice_id') + ->where('stopped_at', '!=', null) + ->get(); + + if ($sessions->isEmpty()) continue; + + $totalCost = $sessions->sum('total_cost'); + + // Create invoice + $invoice = Invoice::create([ + 'user_id' => $user->id, + 'total' => $totalCost, + 'currency' => 'USD', + 'due_date' => now()->addDays(7), + 'description' => 'Kasm Workspace Usage - ' . now()->format('F Y'), + ]); + + // Add line items + foreach ($sessions as $session) { + InvoiceItem::create([ + 'invoice_id' => $invoice->id, + 'description' => sprintf( + '%s - %s (%d minutes @ $%s/hour)', + $session->workspace->workspace_type, + $session->started_at->format('M d, Y'), + $session->duration_billable_seconds / 60, + number_format($session->cost_per_hour, 2) + ), + 'amount' => $session->total_cost, + 'quantity' => 1, + ]); + + // Mark session as billed + $session->update(['invoice_id' => $invoice->id]); + } + + // Send invoice email + Mail::to($user)->send(new InvoiceGenerated($invoice)); + + // Charge payment method + if ($user->hasDefaultPaymentMethod()) { + try { + $payment = $user->charge($totalCost * 100, $user->defaultPaymentMethod()); + $invoice->update(['paid_at' => now()]); + } catch (\Exception $e) { + // Payment failed - send notification + Mail::to($user)->send(new PaymentFailed($invoice)); + } + } + } + } +} +``` + +### Customer Dashboard Features + +#### Workspace Management +- **Start/Stop Controls**: Customer can start/stop workspace from dashboard +- **Current Session Timer**: "Running for 2 hours 37 minutes - $0.50" +- **Monthly Usage Summary**: "This month: $47.35 (23.5 hours)" +- **Session History**: List of all sessions with durations and costs +- **Workspace Access**: One-click button to launch workspace in new tab + +#### Running Cost Indicator +```vue + + + + +``` + +--- + +## Part 2: Multi-Tenancy (White-Label Resellers) + +### What is Multi-Tenancy? +Allowing resellers to run their own branded billing platform using your infrastructure. Each reseller (tenant) has: +- Their own customers +- Their own branding (logo, colors, domain) +- Their own pricing +- Isolated database + +### Tenancy for Laravel Package + +**Package**: https://tenancyforlaravel.com/ +**Documentation**: https://tenancyforlaravel.com/docs/v3/ + +**Key Features**: +- Automatic tenant identification (by domain, subdomain, or path) +- Database per tenant (complete isolation) +- Tenant-aware caching, filesystems, queues +- Easy migrations across all tenants +- Central app + tenant apps architecture + +### Architecture + +#### Central Application +- **Domain**: ezscale.cloud (your main application) +- **Purpose**: Manage resellers (tenants), global settings, wholesale billing +- **Database**: `ezscale_central` (stores tenant list, domains, configs) + +#### Tenant Applications +- **Domains**: `reseller1.com`, `reseller2.hosting`, `custom-domain.net` +- **Purpose**: Each reseller's branded billing platform +- **Databases**: `tenant_reseller1`, `tenant_reseller2`, `tenant_custom` + +### Database Structure + +#### Central Database (`ezscale_central`) +```sql +tenants table: +├── id +├── name (Reseller Company Name) +├── slug (reseller1, reseller2) +├── database_name (tenant_reseller1) +├── domain (reseller1.com, custom-domain.net) +├── status (active, suspended, trial) +├── owner_email +├── owner_name +├── created_at +├── trial_ends_at (nullable) +├── suspended_at (nullable) + +tenant_domains table: +├── id +├── tenant_id +├── domain (reseller1.com, reseller1.ezscale.cloud, custom-domain.net) +├── type (primary, alias) +├── ssl_status (pending, active, failed) +├── verified_at +├── created_at + +tenant_billing table: +├── id +├── tenant_id +├── plan_id (reseller tier: basic, pro, enterprise) +├── wholesale_discount_percent (e.g., 30% off retail prices) +├── monthly_fee (platform fee - e.g., $99/month) +├── commission_percent (if commission-based instead of wholesale) +├── billing_cycle_day (1-28) +├── next_billing_date +├── status (active, past_due, cancelled) + +tenant_branding table: +├── id +├── tenant_id +├── logo_url +├── favicon_url +├── primary_color (#3B82F6) +├── secondary_color +├── company_name +├── support_email +├── support_phone +├── from_email (noreply@reseller.com) +├── from_name (Reseller Hosting) +├── custom_css (nullable - advanced branding) +``` + +#### Tenant Databases (e.g., `tenant_reseller1`) +Each tenant gets a complete copy of the main application schema: +- `users` (reseller's customers) +- `plans` (reseller's custom pricing) +- `subscriptions` +- `invoices` +- `services` +- `kasm_workspaces` +- ... all other tables from main schema + +**Key difference**: Tenant plans reference wholesale prices in central database, but show custom prices to customers. + +### Installation & Setup + +```bash +# Install Tenancy for Laravel +composer require stancl/tenancy + +# Publish config and migrations +php artisan vendor:publish --provider='Stancl\Tenancy\TenancyServiceProvider' + +# Run central migrations +php artisan migrate + +# Configure tenancy +# config/tenancy.php +return [ + 'tenant_model' => \App\Models\Tenant::class, + 'id_generator' => \Stancl\Tenancy\UUIDGenerator::class, + + 'database' => [ + 'prefix' => 'tenant_', + 'template_tenant_connection' => 'mysql', + ], + + 'bootstrappers' => [ + \Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper::class, + \Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper::class, + \Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper::class, + \Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper::class, + ], +]; +``` + +### Creating a Reseller (Tenant) + +```php +// app/Http/Controllers/Admin/ResellerController.php +public function store(Request $request) +{ + $validated = $request->validate([ + 'name' => 'required|string', + 'email' => 'required|email|unique:tenants,owner_email', + 'domain' => 'required|string|unique:tenant_domains,domain', + ]); + + // Create tenant + $tenant = Tenant::create([ + 'name' => $validated['name'], + 'slug' => Str::slug($validated['name']), + 'owner_email' => $validated['email'], + ]); + + // Create domain + $tenant->domains()->create([ + 'domain' => $validated['domain'], + 'type' => 'primary', + ]); + + // Run migrations for tenant database + $tenant->run(function () { + Artisan::call('migrate', ['--database' => 'tenant', '--force' => true]); + + // Seed initial data (plans, roles, etc.) + Artisan::call('db:seed', ['--class' => 'TenantSeeder']); + }); + + // Set up branding defaults + TenantBranding::create([ + 'tenant_id' => $tenant->id, + 'company_name' => $validated['name'], + 'primary_color' => '#3B82F6', + 'support_email' => $validated['email'], + ]); + + // Send welcome email to reseller + Mail::to($validated['email'])->send(new ResellerWelcome($tenant)); + + return redirect()->route('admin.resellers.index') + ->with('success', 'Reseller created successfully!'); +} +``` + +### Tenant Identification (Automatic) + +```php +// routes/web.php (Central app routes) +Route::get('/', [HomeController::class, 'index']); +Route::get('/admin/resellers', [Admin\ResellerController::class, 'index']) + ->middleware(['auth', 'admin']); + +// routes/tenant.php (Tenant-specific routes) +Route::middleware('tenant')->group(function () { + // These routes run within tenant context + Route::get('/', [Tenant\DashboardController::class, 'index']); + Route::get('/services', [Tenant\ServiceController::class, 'index']); + Route::post('/kasm/order', [Tenant\KasmController::class, 'createOrder']); + // ... all customer-facing routes +}); + +// Middleware automatically identifies tenant by domain +// If request is to reseller1.com → loads tenant_reseller1 database +// If request is to ezscale.cloud → uses central database +``` + +### Reseller Pricing Control + +```php +// Tenant database: plans table +// Reseller can set any price they want + +CREATE TABLE plans ( + id INT PRIMARY KEY, + name VARCHAR(255), + description TEXT, + price DECIMAL(10, 2), -- Reseller's customer price + wholesale_price DECIMAL(10, 2), -- What reseller pays EZSCALE + service_type VARCHAR(50), + -- ... other fields +); + +// Example: +// VPS Basic +// - Wholesale price (you charge reseller): $8/month +// - Reseller's price (they charge customer): $15/month +// - Reseller's profit: $7/month per customer + +// When customer subscribes: +// 1. Customer pays reseller $15 +// 2. Reseller pays you $8 (via wholesale invoice) +// 3. Reseller keeps $7 profit +``` + +### Wholesale Billing (Billing Resellers) + +```php +// app/Console/Commands/BillResellers.php +// Run monthly to bill resellers for their customer usage + +class BillResellers extends Command +{ + public function handle() + { + $tenants = Tenant::where('status', 'active')->get(); + + foreach ($tenants as $tenant) { + // Switch to tenant database + $tenant->run(function () use ($tenant) { + // Count active subscriptions + $subscriptions = Subscription::where('status', 'active')->get(); + + $wholesaleTotal = 0; + + foreach ($subscriptions as $subscription) { + $plan = Plan::find($subscription->plan_id); + $wholesaleTotal += $plan->wholesale_price; + } + + // Add platform fee + $platformFee = TenantBilling::where('tenant_id', $tenant->id) + ->value('monthly_fee'); + + $totalDue = $wholesaleTotal + $platformFee; + + // Create wholesale invoice in CENTRAL database + tenancy()->end(); // Switch back to central + + WholesaleInvoice::create([ + 'tenant_id' => $tenant->id, + 'platform_fee' => $platformFee, + 'usage_charges' => $wholesaleTotal, + 'total' => $totalDue, + 'due_date' => now()->addDays(7), + ]); + + // Email reseller + Mail::to($tenant->owner_email)->send( + new ResellerInvoice($tenant, $totalDue) + ); + }); + } + } +} +``` + +### Reseller Dashboard (Central App) + +Resellers log into ezscale.cloud/reseller to: +- View their wholesale invoices +- See customer count and revenue +- Manage branding (logo, colors) +- View usage statistics +- Configure pricing for their plans +- Add/manage their custom domains + +### Branding Customization + +```php +// app/Http/Controllers/Reseller/BrandingController.php +public function update(Request $request) +{ + $tenant = Auth::user()->tenant; + + $validated = $request->validate([ + 'logo' => 'nullable|image|max:2048', + 'primary_color' => 'required|string', + 'company_name' => 'required|string', + 'support_email' => 'required|email', + ]); + + if ($request->hasFile('logo')) { + $logoPath = $request->file('logo')->store('tenant_logos', 's3'); + $validated['logo_url'] = Storage::disk('s3')->url($logoPath); + } + + $tenant->branding()->update($validated); + + return back()->with('success', 'Branding updated!'); +} +``` + +### Loading Tenant Branding + +```php +// app/Http/Middleware/InjectTenantBranding.php +public function handle($request, $next) +{ + if (tenancy()->initialized) { + $branding = TenantBranding::where('tenant_id', tenant('id'))->first(); + + // Share branding with all views + View::share('branding', $branding); + + // Inject CSS variables + if ($branding) { + $customCss = " + :root { + --primary-color: {$branding->primary_color}; + --secondary-color: {$branding->secondary_color}; + } + "; + View::share('customCss', $customCss); + } + } + + return $next($request); +} +``` + +```blade + + + + + {{ $branding->company_name ?? 'EZSCALE Hosting' }} + + + @if(isset($customCss)) + + @endif + + @vite(['resources/css/app.css', 'resources/js/app.js']) + + + + + @yield('content') + + + + +``` + +--- + +## Integration Points + +### Kasm + Multi-Tenancy +- Each tenant (reseller) can offer Kasm workspaces +- Resellers set their own Kasm pricing +- Usage tracked per tenant database +- Wholesale billing aggregates all tenant usage + +### Database Structure +``` +Central DB (ezscale_central) +├── tenants +├── tenant_domains +├── tenant_billing +└── wholesale_invoices + +Tenant DB (tenant_reseller1) +├── users (reseller's customers) +├── subscriptions +├── kasm_workspaces +├── kasm_usage_sessions +└── invoices (customer invoices) +``` + +--- + +## Implementation Phases + +### Phase 12: Kasm Workspaces (New Phase) +- [ ] Research Kasm licensing (per named user vs concurrent session) +- [ ] Set up Kasm Workspaces instance +- [ ] Create Kasm API integration service +- [ ] Build workspace provisioning automation +- [ ] Implement usage tracking (15-min increments) +- [ ] Build workspace management UI +- [ ] Implement start/stop controls +- [ ] Create workspace templates (dev + business) +- [ ] Build monthly usage billing +- [ ] Test end-to-end workflow + +### Phase 13: Multi-Tenancy (New Phase) +- [ ] Install Tenancy for Laravel package +- [ ] Configure tenant identification (domain-based) +- [ ] Create central reseller management UI +- [ ] Build tenant creation workflow +- [ ] Implement automatic tenant migrations +- [ ] Build branding customization system +- [ ] Create wholesale billing system +- [ ] Build reseller dashboard +- [ ] Test multi-domain SSL (Let's Encrypt) +- [ ] Test tenant isolation thoroughly +- [ ] Create reseller onboarding documentation + +--- + +## Open Questions + +- [ ] **Kasm Licensing**: Which Kasm license tier (per named user vs concurrent)? Cost per user? +- [ ] **Kasm Infrastructure**: Self-hosted Kasm server or Kasm cloud? If self-hosted, hardware requirements? +- [ ] **Reseller Trials**: Should resellers get trial period? How long? +- [ ] **Reseller Pricing**: Fixed platform fee ($99/month) or percentage of revenue? +- [ ] **Minimum Customers**: Require minimum customer count before reseller can launch? +- [ ] **Support Responsibility**: Who handles tenant customer support - you or reseller? + +--- + +## Summary + +This document provides comprehensive implementation plans for: + +1. **Kasm Workspaces Integration** + - Fully automated provisioning + - Hourly billing with 15-minute increments + - Real-time usage tracking + - Developer and Business workspace types + - Complete API integration + +2. **Multi-Tenancy for Resellers** + - Database-per-tenant isolation + - Full white-label branding + - Custom domain support + - Reseller pricing control + - Wholesale billing system + +Both features significantly expand EZSCALE's service offerings and create new revenue streams through workspace hosting and reseller partnerships. + +**References**: +- [Kasm Workspaces Documentation](https://docs.kasm.com/) +- [Kasm Developer API](https://docs.kasm.com/docs/latest/developers/developer_api/) +- [Tenancy for Laravel](https://tenancyforlaravel.com/) +- [Multi-Database Tenancy Docs](https://tenancyforlaravel.com/docs/v3/multi-database-tenancy/) diff --git a/PROJECT_DEVELOPMENT.md b/PROJECT_DEVELOPMENT.md new file mode 100644 index 0000000..0fdd872 --- /dev/null +++ b/PROJECT_DEVELOPMENT.md @@ -0,0 +1,604 @@ +# PROJECT_DEVELOPMENT.md - EZSCALE Site Architecture & Development Plan + +## 1. Project Goal + +Replace WHMCS with a custom Laravel 12 application for managing EZSCALE Hosting's VPS, Dedicated Server, Web Hosting, and Game Server business. The new platform must handle customer management, billing/subscriptions, automated provisioning, bandwidth monitoring, and comprehensive admin controls. + +## 2. Infrastructure Overview + +### Current EZSCALE Stack +- **VPS Platform:** VirtFusion (KVM/QEMU hypervisor stack) +- **Game Servers:** Pterodactyl Panel +- **Dedicated Servers:** SynergyCP +- **Web Hosting:** Enhance (https://enhance.com/) +- **Container Management:** Portainer (for BFACP deployment) +- **Support System:** SupportPal (ticketing) +- **Network:** Juniper switches with VLANs (dedicated customers, corporate, hypervisors) +- **Bandwidth Monitoring:** ElastiFlow (NetFlow/sFlow collector) + +### Domain Structure +- **ezscale.cloud** — Marketing frontend, product catalog, public pages +- **account.ezscale.cloud** — Customer dashboard, service management, billing +- **admin.ezscale.cloud** — Admin panel (behind Cloudflare Zero Trust + passkeys) + +### Hosting +- **Application Hosting:** EZSCALE's own infrastructure +- **Database:** MySQL 8.x with full redundancy (multi-region replication, automated backups, DR plan) +- **Caching/Queue:** Redis +- **Email Service:** Mailgun or SendGrid + +## 3. Application Architecture + +### High-Level Architecture +``` +┌──────────────────────────────────────────────────────────────────┐ +│ ezscale.cloud │ +│ Marketing Site + Product Catalog (Laravel) │ +└──────────────────────────────────────────────────────────────────┘ + │ + ┌────────────┴────────────┐ + │ │ +┌───────────────────▼─────────┐ ┌───────────▼──────────────────────┐ +│ account.ezscale.cloud │ │ admin.ezscale.cloud │ +│ Customer Dashboard │ │ Admin Panel │ +│ (Vue 3 + Inertia.js) │ │ (Cloudflare Zero Trust) │ +└───────────────┬──────────────┘ └──────────┬───────────────────────┘ + │ │ +┌───────────────┴────────────────────────────┴───────────────────────┐ +│ Laravel 12 Core │ +│ ┌──────────┐ ┌──────────┐ ┌──────────────┐ ┌───────────────────┐ │ +│ │ Auth │ │ Billing │ │ Provisioning │ │ Bandwidth │ │ +│ │ Fortify │ │ Cashier │ │ Services │ │ Monitoring │ │ +│ │ Passport │ │ Stripe │ │ VirtFusion │ │ ElastiFlow │ │ +│ │ │ │ PayPal │ │ Pterodactyl │ │ Integration │ │ +│ │ │ │ │ │ SynergyCP │ │ │ │ +│ │ │ │ │ │ Enhance │ │ │ │ +│ └──────────┘ └──────────┘ └──────────────┘ └───────────────────┘ │ +│ ┌──────────┐ ┌──────────┐ ┌──────────────┐ ┌───────────────────┐ │ +│ │SupportPal│ │Analytics │ │ Customer │ │ Admin Tools │ │ +│ │Integration│ │Dashboard │ │ API │ │ Full Control │ │ +│ │SSO+Tickets│ │MRR/Churn │ │ │ │ │ │ +│ └──────────┘ └──────────┘ └──────────────┘ └───────────────────┘ │ +├─────────────────────────────────────────────────────────────────────┤ +│ MySQL 8.x (Multi-region) │ Redis (Queue/Cache/Session) │ +└─────────────────────────────────────────────────────────────────────┘ + │ │ + ┌────┴────────┬──────────┬───────────┬───┴────┬─────────────┐ + │ │ │ │ │ │ +VirtFusion Pterodactyl SynergyCP Enhance SupportPal ElastiFlow + API API API API API API +``` + +## 4. Key Design Decisions + +### Payment & Billing (DECIDED) +- **Primary Gateway:** Stripe via Laravel Cashier v16 (~80%+ of customers) +- **Secondary Gateway:** PayPal via `srmklive/laravel-paypal` (~20% recurring subscriptions) +- **Tax:** To be decided (TaxJar/Avalara or manual rates) +- **Multi-Currency:** Full support (EUR, GBP, USD, etc.) via Stripe +- **Invoicing:** Full-featured PDF generation, custom numbering, multi-currency, email delivery +- **Payment Methods:** Customers can manage multiple payment methods per account +- **Coupons:** Full coupon system (percentage, fixed amount, trial extensions, usage limits, expiry) +- **Billing Architecture:** `BillingServiceInterface` abstracts Stripe and PayPal for gateway-agnostic code + +### Frontend & Auth (DECIDED) +- **Stack:** Vue 3 + Inertia.js + Tailwind CSS (Laravel 12 Vue starter kit) +- **UI Theme:** **Vuexy** VueJS + Laravel Admin Dashboard Template + - Purchase: https://themeforest.net/item/vuexy-vuejs-html-laravel-admin-dashboard-template/23328599 + - Demo: https://pixinvent.com/vuexy-vuejs-laravel-admin-template/ + - Features: Pre-built admin components, charts, forms, tables, authentication pages, responsive design + - Source files will be integrated when development begins +- **Auth:** Laravel Fortify (headless backend) + Vuexy-styled Vue/Inertia auth pages +- **2FA:** Required for admins (passkeys preferred), encouraged for customers (TOTP/Authenticator) +- **SSO:** Laravel Passport OAuth2 server for future integrations +- **API:** RESTful API for both customers (service management) and admins + +### Provisioning (DECIDED - Fully Automated) +All service provisioning is **fully automated** via API on successful payment: + +| Service Type | Platform | Automation | +|--------------|----------|------------| +| VPS | VirtFusion API | Payment succeeds → API creates VPS → credentials emailed | +| Game Servers | Pterodactyl API | Payment succeeds → API creates server → credentials emailed | +| Dedicated Servers | SynergyCP API | Payment succeeds → API provisions (if hardware available) → credentials emailed | +| Web Hosting | Enhance API | Payment succeeds → API creates hosting account → credentials emailed | + +**Note:** Dedicated servers may require semi-automation (admin assigns hardware if inventory limited). + +### Panel Integration (DECIDED) +- **Pterodactyl & SynergyCP:** Separate login credentials (no SSO) +- **Dashboard Integration:** Full integration - Laravel dashboard shows: + - Server status (online/offline) + - Resource usage (CPU, RAM, disk, bandwidth) + - Basic controls (restart, power on/off via API) + - Links to panels for advanced management +- **Enhance:** Full integration for hosting account status and resource usage + +### Bandwidth Monitoring (DECIDED) +- **Collection:** NetFlow/sFlow via ElastiFlow (Elastic-based flow collector) +- **Integration:** Laravel queries ElastiFlow API/database for bandwidth data +- **Display:** Real-time bandwidth graphs in customer dashboard +- **Billing:** Automatic overage billing at end of billing cycle +- **Alerts:** Multi-threshold warnings (75%, 90%, 100% of quota) via email + Discord webhook +- **No Add-ons:** Automatic overage billing only (no one-time bandwidth add-ons) + +### Support Integration (DECIDED) +- **System:** SupportPal (external ticketing system) +- **Integration Level:** Full integration + - SSO for seamless access + - View recent tickets in billing dashboard + - Create tickets from billing panel via SupportPal API + - Full ticket history accessible to customers +- **Discord:** Admin notifications via webhook (new orders, failures, cancellations, high revenue) + +### Customer Features (DECIDED) +- **Dashboard Layout:** Service overview (active services, next invoice, recent tickets, quick actions) +- **Self-Service:** Full self-service upgrades/downgrades with automatic proration +- **Cancellation:** Self-service cancellation with optional survey (service remains active until period end) +- **Payment Methods:** Manage multiple cards/PayPal accounts, set default per service + +### Admin Panel (DECIDED) +- **Access Security:** Cloudflare Zero Trust + 2FA (passkeys preferred) +- **Control Level:** Full control over all customer services + - Provision, suspend, terminate, modify services + - View/edit customer accounts + - Invoice management, payment processing + - Analytics dashboard (MRR, ARR, churn, revenue trends, popular plans) +- **Suspension Policy:** Automatic suspension X days past due → terminate Y days later + +### Analytics & Reporting (DECIDED) +- **Comprehensive analytics dashboard:** + - Revenue trends (daily, monthly, yearly) + - MRR (Monthly Recurring Revenue) and ARR (Annual Recurring Revenue) + - Churn rate and customer growth + - Plan popularity and conversion rates + - Outstanding invoices and overdue accounts + +### Deployment & CI/CD (DECIDED) +- **CI/CD:** GitHub Actions pipeline + - Tests run on push + - Auto-deploy to staging environment + - Manual approval for production deployment +- **Environments:** Full staging environment (staging.account.ezscale.cloud with separate database) + +## 5. Database Schema (Core Tables) + +### Users & Auth +``` +users +├── id, name, email, email_verified_at, password +├── status (active, suspended, banned) +├── phone, company +├── two_factor_secret, two_factor_recovery_codes +├── passkey_credentials (JSON for WebAuthn) +├── timestamps + +user_profiles +├── id, user_id +├── billing_address (line1, line2, city, state, zip, country) +├── shipping_address (line1, line2, city, state, zip, country) +├── tax_id, tax_exempt +├── company_name, company_vat +├── notes (admin notes) +├── timestamps + +roles (via spatie/laravel-permission) +├── id, name (admin, customer), guard_name, timestamps + +permissions (via spatie/laravel-permission) +├── id, name, guard_name, timestamps + +audit_logs +├── id, user_id, admin_id (nullable) +├── action (login, logout, service_provisioned, service_suspended, payment_failed, etc.) +├── resource_type, resource_id +├── ip_address, user_agent +├── changes (JSON - before/after state) +├── timestamps +``` + +### Billing +``` +plans +├── id, name, slug, description +├── service_type (vps, dedicated, hosting, game_server) +├── price, currency, billing_cycle (monthly, quarterly, annual, hourly) +├── stripe_price_id, paypal_plan_id +├── features (JSON - RAM, CPU, disk, bandwidth, etc.) +├── stock_quantity (nullable - for limited dedicated server inventory) +├── status (active, hidden, archived) +├── sort_order +├── timestamps + +subscriptions (extended from Cashier) +├── id, user_id, plan_id +├── gateway (stripe, paypal) +├── gateway_subscription_id +├── gateway_customer_id +├── gateway_price_id +├── status (active, past_due, cancelled, paused, trialing) +├── trial_ends_at, current_period_start, current_period_end +├── cancelled_at, ends_at +├── timestamps + +subscription_items (Cashier-managed) +├── id, subscription_id, stripe_id, stripe_product, stripe_price +├── quantity, timestamps + +invoices (extended from Cashier) +├── id, subscription_id, user_id +├── gateway (stripe, paypal), gateway_invoice_id +├── number (custom invoice numbering) +├── total, tax, currency, status +├── invoice_pdf (path to generated PDF) +├── due_date, paid_at +├── timestamps + +invoice_items +├── id, invoice_id +├── description, amount, quantity +├── timestamps + +payment_transactions +├── id, user_id, subscription_id (nullable), invoice_id (nullable) +├── gateway (stripe, paypal), gateway_transaction_id +├── amount, currency, status (succeeded, failed, refunded, pending) +├── payment_method (card, paypal, bank_transfer) +├── description, metadata (JSON) +├── timestamps + +coupons +├── id, code, type (percentage, fixed_amount) +├── value, currency (for fixed_amount) +├── applies_to (all, specific_plans - JSON array of plan IDs) +├── max_uses, times_used +├── expires_at +├── timestamps + +coupon_redemptions +├── id, coupon_id, user_id, subscription_id +├── discount_amount +├── timestamps +``` + +### Services & Provisioning +``` +services +├── id, user_id, subscription_id, plan_id +├── service_type (vps, dedicated, hosting, game_server) +├── platform (virtfusion, pterodactyl, synergycp, enhance) +├── platform_service_id (ID in external system) +├── status (pending, active, suspended, terminated) +├── ipv4_address, ipv6_address +├── hostname, domain +├── credentials (encrypted JSON - username, password, access URLs) +├── provisioned_at, suspended_at, terminated_at +├── auto_renew (boolean) +├── timestamps + +provisioning_logs +├── id, service_id, user_id +├── action (create, suspend, unsuspend, terminate, upgrade, downgrade) +├── platform, platform_response (JSON) +├── status (pending, success, failed) +├── error_message +├── admin_id (nullable - if manually triggered) +├── timestamps + +bandwidth_usage +├── id, service_id +├── period_start, period_end +├── bytes_in, bytes_out, total_bytes +├── quota_bytes, overage_bytes +├── overage_charge +├── source (elastiflow) +├── timestamps +``` + +### Support (SupportPal Integration) +``` +support_tickets (mirrored from SupportPal via webhooks) +├── id, user_id +├── supportpal_ticket_id +├── subject, status (open, closed, pending) +├── priority (low, medium, high, urgent) +├── last_reply_at +├── timestamps + +announcements +├── id, title, content (HTML) +├── type (maintenance, feature, outage) +├── published_at, expires_at +├── timestamps +``` + +## 6. Key Integrations + +### 6.1 VirtFusion API (VPS Provisioning) +**Endpoints needed:** +- `POST /api/vps/create` - Create new VPS instance +- `POST /api/vps/{id}/suspend` - Suspend VPS +- `POST /api/vps/{id}/unsuspend` - Unsuspend VPS +- `DELETE /api/vps/{id}` - Terminate VPS +- `GET /api/vps/{id}/status` - Get VPS status and resource usage +- `POST /api/vps/{id}/reboot` - Reboot VPS + +**Provisioning Service:** `App\Services\Provisioning\VirtFusionService` + +### 6.2 Pterodactyl API (Game Server Provisioning) +**Endpoints needed:** +- `POST /api/application/servers` - Create server +- `POST /api/application/servers/{id}/suspend` - Suspend +- `POST /api/application/servers/{id}/unsuspend` - Unsuspend +- `DELETE /api/application/servers/{id}` - Delete +- `GET /api/client/servers/{id}/resources` - Resource usage + +**Provisioning Service:** `App\Services\Provisioning\PterodactylService` + +### 6.3 SynergyCP API (Dedicated Server Provisioning) +**Endpoints needed:** +- `POST /api/server/provision` - Provision dedicated server +- `POST /api/server/{id}/suspend` - Suspend +- `POST /api/server/{id}/unsuspend` - Unsuspend +- `POST /api/server/{id}/terminate` - Terminate +- `GET /api/server/{id}` - Get server details and status + +**Provisioning Service:** `App\Services\Provisioning\SynergyCPService` + +### 6.4 Enhance API (Web Hosting Provisioning) +**Endpoints needed:** +- `POST /api/orgs/{org}/websites` - Create hosting account +- `PUT /api/orgs/{org}/websites/{id}/suspended` - Suspend +- `DELETE /api/orgs/{org}/websites/{id}` - Delete +- `GET /api/orgs/{org}/websites/{id}` - Get account status + +**Provisioning Service:** `App\Services\Provisioning\EnhanceService` + +### 6.5 ElastiFlow API (Bandwidth Monitoring) +**Integration approach:** +- Query Elasticsearch indices via REST API +- Aggregate bandwidth by service IP address and time period +- Calculate usage per billing cycle +- Store results in `bandwidth_usage` table +- Scheduled job runs daily to update bandwidth stats + +**Service:** `App\Services\Monitoring\BandwidthService` + +### 6.6 SupportPal API (Ticket System) +**Endpoints needed:** +- `GET /api/ticket/{id}` - Get ticket details +- `GET /api/ticket/user/{user_id}` - Get user's tickets +- `POST /api/ticket` - Create new ticket +- `POST /api/ticket/{id}/reply` - Reply to ticket +- `GET /api/ticket/{id}/replies` - Get ticket thread + +**SSO Implementation:** SupportPal supports SAML or custom SSO - use Laravel Passport tokens + +**Service:** `App\Services\Support\SupportPalService` + +### 6.7 Email Notifications (Mailgun/SendGrid) +**Laravel Notifications for:** +- Welcome email (account created) +- Email verification +- Invoice generated (with PDF attachment) +- Payment received (receipt) +- Payment failed (with retry instructions) +- Service provisioned (credentials) +- Service suspended (past due payment) +- Service expiring soon (renewal reminder) +- Bandwidth usage alerts (75%, 90%, 100%) +- Bandwidth overage charge (end of cycle) +- Ticket updates (new reply, status change) + +### 6.8 Discord Webhooks (Admin Alerts) +**Notifications sent to Discord:** +- New customer signup +- New order / subscription created +- High-value order (e.g., >$500) +- Payment failure +- Service suspension +- Service cancellation +- System errors / provisioning failures +- Security alerts (admin login failures, etc.) + +## 7. Security Architecture + +### Authentication +- **Customer Auth:** Email + password (bcrypt), optional 2FA (TOTP), passkey support (WebAuthn) +- **Admin Auth:** Email + password + **required** 2FA (passkeys preferred), behind Cloudflare Zero Trust +- **Session Management:** Redis-backed sessions with secure cookies +- **API Auth:** Laravel Sanctum tokens for customer/admin APIs + +### Authorization +- **Roles:** `admin` and `customer` via spatie/laravel-permission +- **Policies:** Laravel policies for resource-level authorization (can user view this service?) +- **Admin Actions:** All admin actions logged to `audit_logs` table +- **Admin Impersonation:** Admins can impersonate customers (with audit logging) + +### Data Protection +- **Encryption at Rest:** Service credentials, API keys, payment tokens encrypted in database +- **HTTPS Everywhere:** All traffic HTTPS-only, HSTS headers +- **CSRF Protection:** All forms CSRF-protected +- **Rate Limiting:** Login, registration, API endpoints rate-limited +- **Input Validation:** Laravel Form Request classes for all inputs +- **SQL Injection Prevention:** Eloquent ORM + prepared statements +- **XSS Prevention:** Blade/Vue escaping, CSP headers + +### Admin Panel Security +- **Cloudflare Zero Trust:** Admin panel behind Zero Trust access control +- **Passkeys/2FA:** Required for all admin accounts +- **IP Logging:** All admin actions logged with IP address +- **Suspicious Activity Alerts:** Discord webhook for failed admin logins + +## 8. Development Phases + +### Phase 1: Foundation & Core Setup +- Initialize Laravel 12 with Vue + Inertia starter kit +- Configure domains: ezscale.cloud, account.ezscale.cloud, admin.ezscale.cloud +- Set up MySQL with replication, Redis +- Install dependencies: Cashier, Fortify, Passport, PayPal, Spatie +- Create database schema and migrations +- Set up authentication (Fortify + 2FA + passkeys) +- Configure Cloudflare Zero Trust for admin panel +- Set up CI/CD pipeline (GitHub Actions) + +### Phase 2: Billing & Subscriptions +- Implement `BillingServiceInterface` (Stripe + PayPal) +- Build plan catalog (VPS, Dedicated, Hosting, Game Server plans) +- Subscription creation and management +- Invoice generation (PDF, custom numbering, multi-currency) +- Payment method management (multiple cards/PayPal per customer) +- Coupon system (creation, redemption, validation) +- Webhook handlers for Stripe and PayPal +- Automatic overage billing for bandwidth +- Tax calculation (TaxJar/Avalara or manual) + +### Phase 3: Provisioning Automation +- `ProvisioningServiceInterface` abstraction +- VirtFusion provisioning service +- Pterodactyl provisioning service +- SynergyCP provisioning service +- Enhance provisioning service +- Event-driven provisioning (listen to payment success events) +- Credential generation and secure storage +- Provisioning failure handling and retry logic + +### Phase 4: Customer Dashboard (account.ezscale.cloud) +- Service overview dashboard +- Active services list with status and resource usage +- Bandwidth usage graphs (from ElastiFlow) +- Billing history and invoices (PDF download) +- Payment methods management +- Plan upgrades/downgrades (self-service) +- Subscription cancellation (with survey) +- Profile and account settings +- 2FA and passkey setup + +### Phase 5: Admin Panel (admin.ezscale.cloud) +- Analytics dashboard (MRR, ARR, churn, revenue trends) +- Customer management (view, edit, impersonate, notes) +- Service management (view all services, suspend, terminate, modify) +- Order management (pending orders, approvals) +- Invoice management (view, edit, manual invoicing) +- Coupon management (create, edit, deactivate) +- Plan management (create, edit, pricing changes) +- System configuration (email templates, tax rates, suspension policies) +- Audit log viewer + +### Phase 6: Bandwidth Monitoring & Billing +- ElastiFlow API integration +- Bandwidth data collection and storage +- Usage calculation per billing cycle +- Bandwidth graphs in customer dashboard +- Multi-threshold alerts (75%, 90%, 100%) +- Automatic overage billing +- Admin bandwidth reports + +### Phase 7: SupportPal Integration +- SSO implementation (Laravel Passport + SupportPal) +- Ticket viewing in customer dashboard +- Ticket creation via SupportPal API +- Webhook handlers for ticket updates +- Discord notifications for new tickets + +### Phase 8: Marketing Frontend (ezscale.cloud) +- Product catalog pages (VPS, Dedicated, Hosting, Game Servers) +- Pricing pages with plan comparison +- Signup flow with plan selection +- Blog/news section +- Knowledge base / FAQ +- Legal pages (Terms, Privacy, AUP) + +### Phase 9: Testing, Migration & Launch +- Comprehensive testing (unit, feature, integration, E2E) +- Security audit and penetration testing +- WHMCS data export and migration scripts +- Customer data migration (users, subscriptions, services, invoices) +- Parallel operation period (run both systems) +- Full cutover to new platform +- Monitoring and alerting setup +- Post-launch support and bug fixes + +## 9. WHMCS Migration Plan + +### Migration Scope (DECIDED) +- **Full historical data migration:** + - All customer accounts and profiles + - All subscriptions (active and cancelled) + - Complete invoice history + - Complete payment history + - All support tickets (migrate to SupportPal or archive) + - Service configurations + - Product/plan mapping + +### Migration Approach +- **Customer Volume:** Medium (100-1000 customers) +- **Strategy:** Automated migration scripts with manual verification +- **Staging:** Test migration in staging environment first +- **Parallel Operation:** Run WHMCS and new platform in parallel for 30 days +- **Cutover:** Maintenance window for final cutover, redirect WHMCS URLs + +### Migration Steps +1. Export WHMCS database to SQL dump +2. Map WHMCS product IDs to new plan IDs +3. Create migration scripts (Laravel commands): + - `php artisan migrate:whmcs-customers` - Import customers and profiles + - `php artisan migrate:whmcs-subscriptions` - Import active subscriptions (coordinate with Stripe/PayPal) + - `php artisan migrate:whmcs-invoices` - Import invoice history + - `php artisan migrate:whmcs-payments` - Import payment history + - `php artisan migrate:whmcs-services` - Import service configurations + - `php artisan migrate:whmcs-tickets` - Migrate tickets to SupportPal +4. Verify data integrity in staging +5. Email customers about platform migration +6. Set up redirects from old WHMCS URLs +7. Execute final migration during maintenance window +8. Monitor for issues during parallel operation period + +## 10. Open Questions & Decisions Needed + +### Decided ✓ +- [x] Payment gateway: Stripe + PayPal +- [x] Frontend stack: Vue 3 + Inertia.js +- [x] Infrastructure: VirtFusion, Pterodactyl, SynergyCP, Enhance +- [x] Bandwidth monitoring: ElastiFlow (NetFlow/sFlow) +- [x] Support system: SupportPal with full integration +- [x] Domain structure: ezscale.cloud / account / admin +- [x] Hosting: Own infrastructure with full DB redundancy +- [x] CI/CD: GitHub Actions with staging environment +- [x] Email: Mailgun or SendGrid +- [x] Admin security: Cloudflare Zero Trust + passkeys +- [x] Customer features: Full self-service (upgrades, downgrades, cancellations) +- [x] Provisioning: Fully automated for all service types +- [x] Analytics: Comprehensive dashboard (MRR, ARR, churn, etc.) +- [x] Multi-currency: Yes (Stripe supports this) +- [x] Coupons: Full system with all features +- [x] WHMCS migration: Full historical data import + +### Still To Decide +- [ ] Tax calculation approach: TaxJar/Avalara integration vs manual tax rates? +- [ ] Email service final choice: Mailgun or SendGrid? +- [ ] Admin panel subdomain: admin.ezscale.cloud or something less obvious for security? +- [ ] Dedicated server semi-automation: How to handle limited hardware inventory (waitlist, manual approval)? +- [ ] NetFlow/sFlow deployment: Timeline for switching Juniper to flow exports? +- [x] ~~Customer portal theme/branding~~ **DECIDED: Vuexy VueJS + Laravel Admin Dashboard Template** + +## 11. Tech Stack Summary + +| Layer | Technology | +|-------|------------| +| **Framework** | Laravel 12 (PHP 8.2+) | +| **Frontend** | Vue 3 + Inertia.js + Tailwind CSS | +| **UI Theme** | Vuexy VueJS + Laravel Admin Dashboard | +| **Database** | MySQL 8.x (multi-region replication) | +| **Cache/Queue** | Redis | +| **Payments** | Laravel Cashier Stripe v16 + srmklive/laravel-paypal | +| **Auth** | Laravel Fortify + Passport (OAuth2) | +| **Roles** | spatie/laravel-permission | +| **Email** | Mailgun or SendGrid (via Laravel Mail) | +| **2FA** | TOTP (Authenticator apps) + WebAuthn (passkeys) | +| **Admin Security** | Cloudflare Zero Trust | +| **CI/CD** | GitHub Actions | +| **Monitoring** | ElastiFlow (bandwidth), Laravel Telescope (debugging) | +| **Provisioning APIs** | VirtFusion, Pterodactyl, SynergyCP, Enhance | +| **Support** | SupportPal (external integration) | +| **Notifications** | Laravel Notifications + Discord webhooks | diff --git a/README.md b/README.md new file mode 100644 index 0000000..c5b81eb --- /dev/null +++ b/README.md @@ -0,0 +1,260 @@ +# EZSCALE Billing Platform + +Modern Laravel 12 billing and customer management platform replacing WHMCS for EZSCALE Hosting. + +## Repository +- **GitHub**: git@github.com:EZSCALE/accounting.git +- **Branch Strategy**: Feature branches → `develop` → `main` + +## Documentation Files + +| File | Purpose | Lines | +|------|---------|-------| +| **CLAUDE.md** | Project instructions for AI assistance | ~70 | +| **PROJECT_DEVELOPMENT.md** | Complete architecture & development plan | ~600 | +| **TASKS.md** | Detailed task breakdown (13 phases) | ~400 | +| **FEATURES.md** | Feature specifications (35+ features) | ~1000 | +| **KASM_AND_MULTITENANCY.md** | Kasm Workspaces + Multi-Tenancy implementation | ~600 | +| **GETTING_STARTED.md** | Development setup guide | ~300 | +| **README.md** | This file - project overview | - | + +## Quick Overview + +### What We're Building +A comprehensive billing and service management platform for EZSCALE Hosting that handles: +- **Services**: VPS, Dedicated Servers, Web Hosting, Game Servers, **Kasm Workspaces** +- **Billing**: Stripe + PayPal + Crypto with multi-currency support +- **Provisioning**: Fully automated via VirtFusion, Pterodactyl, SynergyCP, Enhance APIs +- **Monitoring**: ElastiFlow bandwidth tracking, uptime monitoring, status page +- **Support**: Deep SupportPal integration with SSO +- **Admin**: Comprehensive analytics, MRR/ARR/churn tracking, full customer control + +### Tech Stack +- **Framework**: Laravel 12 (PHP 8.2+) +- **Frontend**: Vue 3 + Inertia.js + Tailwind CSS +- **UI Theme**: Vuexy VueJS + Laravel Admin Dashboard Template +- **Database**: MySQL 8.x (multi-region replication, 15-min backups) +- **Cache/Queue**: Redis + Laravel Horizon +- **Payments**: Laravel Cashier Stripe v16 + srmklive/laravel-paypal +- **Auth**: Laravel Fortify + Passport (OAuth2/SSO) +- **Email**: Mailgun or SendGrid +- **Monitoring**: ElastiFlow (NetFlow/sFlow), built-in uptime checks +- **CI/CD**: GitHub Actions with staging environment +- **Security**: Cloudflare Zero Trust + 2FA/passkeys + +### Domains +- **ezscale.cloud** — Marketing site, product catalog, public pages +- **account.ezscale.cloud** — Customer dashboard, service management +- **admin.ezscale.cloud** — Admin panel (Cloudflare Zero Trust protected) +- **status.ezscale.cloud** — Public status page + +### Key Features +- ✅ Fully automated provisioning (VPS, Dedicated, Hosting, Game Servers) +- ✅ Multi-currency billing (USD, EUR, GBP, etc.) +- ✅ Advanced coupon system (stackable, geo-restricted, A/B testing) +- ✅ Automatic loyalty rewards (5-20% based on tenure) +- ✅ Self-service upgrades/downgrades with proration +- ✅ Bandwidth monitoring with auto-billing overages +- ✅ Team accounts with granular permissions +- ✅ Referral credit system +- ✅ Free trial support +- ✅ Comprehensive API with webhooks +- ✅ Built-in abuse management system +- ✅ Fraud detection and prevention +- ✅ Customer custom domains (CNAME support) +- ✅ Cryptocurrency payment support +- ✅ Exit surveys and win-back campaigns +- ✅ Real-time dashboard (WebSockets + polling) +- ✅ Multi-channel admin alerts (Discord, Email, SMS) +- ✅ GDPR-compliant data deletion +- ✅ Full audit trail and login history +- ✅ Unified communication timeline + +## Current Status: Planning Phase + +We are currently in the **documentation and planning phase**. This repository contains comprehensive planning documents but no code yet. + +### Planning Complete ✓ +- [x] Infrastructure architecture designed +- [x] Database schema defined +- [x] All integrations documented (6 external APIs) +- [x] Feature specifications written (35+ features) +- [x] Development phases outlined (11 phases) +- [x] Task breakdown completed (200+ tasks) +- [x] Security architecture defined +- [x] WHMCS migration strategy planned + +### Next Steps +1. Review and approve planning documents +2. Set up development environment on separate machine +3. Initialize Laravel 12 project with Vue + Inertia +4. Begin Phase 1: Foundation (auth, database, core setup) + +## Development Phases + +| Phase | Focus | Status | +|-------|-------|--------| +| **Phase 1** | Foundation & Core Setup | Planned | +| **Phase 2** | Billing & Subscriptions | Planned | +| **Phase 3** | Provisioning Automation | Planned | +| **Phase 4** | Customer Dashboard | Planned | +| **Phase 5** | Admin Panel | Planned | +| **Phase 6** | Bandwidth Monitoring & Billing | Planned | +| **Phase 7** | SupportPal Integration | Planned | +| **Phase 8** | Marketing Frontend | Planned | +| **Phase 9** | RESTful API | Planned | +| **Phase 10** | Testing, Migration & Launch | Planned | +| **Phase 11** | Future Enhancements | Backlog | +| **Phase 12** | Kasm Workspaces Integration | Planned | +| **Phase 13** | Multi-Tenancy (Resellers) | Planned | + +## Infrastructure Integration + +### Service Provisioning +| Platform | Service Type | API | Automation | +|----------|-------------|-----|------------| +| **VirtFusion** | VPS | REST API | Fully automated | +| **Pterodactyl** | Game Servers | REST API | Fully automated | +| **SynergyCP** | Dedicated Servers | REST API | Automated (semi-auto for inventory) | +| **Enhance** | Web Hosting | REST API | Fully automated | + +### Support & Monitoring +| System | Purpose | Integration | +|--------|---------|-------------| +| **SupportPal** | Ticketing | SSO + Full API integration | +| **ElastiFlow** | Bandwidth Monitoring | API queries for usage data | +| **Juniper Switches** | Network | NetFlow/sFlow exports | + +### Payment Gateways +| Gateway | Usage | Integration | +|---------|-------|-------------| +| **Stripe** | Primary (~80%) | Laravel Cashier v16 | +| **PayPal** | Secondary (~20%) | srmklive/laravel-paypal | +| **Crypto** | Optional | Coinbase Commerce | + +## Database Overview + +### Core Tables +- **Users & Auth**: users, user_profiles, roles, permissions, audit_logs, login_history +- **Billing**: plans, subscriptions, invoices, payment_transactions, coupons, account_credits +- **Services**: services, provisioning_logs, bandwidth_usage, backups +- **Support**: support_tickets (mirrored), announcements +- **Team**: team_members, team_invitations +- **Monitoring**: uptime_checks, uptime_incidents, status_components +- **Abuse**: abuse_reports, abuse_actions +- **Communication**: customer_timeline, webhook_deliveries +- **Network**: ip_addresses, datacenters + +See **PROJECT_DEVELOPMENT.md** for complete schema with all columns. + +## WHMCS Migration + +### Scope +- Full historical data migration (100-1000 customers) +- All invoices, payments, services, subscriptions +- Automated migration scripts (Laravel commands) +- 30-day parallel operation period +- Redirect old WHMCS URLs to new platform + +### Migration Commands +```bash +php artisan migrate:whmcs-customers # Import customers and profiles +php artisan migrate:whmcs-subscriptions # Import active subscriptions +php artisan migrate:whmcs-invoices # Import invoice history +php artisan migrate:whmcs-payments # Import payment history +php artisan migrate:whmcs-services # Import service configurations +php artisan migrate:whmcs-tickets # Migrate tickets to SupportPal +``` + +## Security + +### Authentication +- **Customer**: Email + password, optional 2FA (TOTP/passkeys) +- **Admin**: Email + password + required 2FA (passkeys preferred) +- **Admin Panel**: Behind Cloudflare Zero Trust access control +- **API**: Laravel Sanctum token authentication + +### Data Protection +- Service credentials encrypted at rest +- HTTPS enforced everywhere +- CSRF protection on all forms +- Rate limiting on auth and API +- SQL injection prevention (Eloquent ORM) +- XSS prevention (Blade/Vue escaping + CSP) + +### Compliance +- GDPR-compliant automated data deletion +- Full audit trail of admin actions +- Login history with IP tracking +- Fraud detection on signup +- Abuse management system + +## Performance & Scalability + +### Caching Strategy +- Real-time: Today's revenue, active orders +- 15-min cache: Historical analytics +- Daily aggregation: Month/year totals + +### Queue System +- **Critical queue**: Provisioning, payments, suspension +- **Normal queue**: Emails, notifications, backups +- **Low queue**: Analytics, reports, cleanup + +### Scaling +- Cloudflare CDN + WAF + DDoS protection +- Load balancer with auto-scaling +- Multi-region database replication +- 15-minute backup RPO + +## API + +### Customer API (Full Control) +- Create, modify, delete services +- View invoices and billing history +- Manage payment methods +- Check bandwidth usage +- Reboot/manage servers + +### Webhook Support +- Customers can register webhook URLs +- Events: `invoice.created`, `service.provisioned`, `bandwidth.threshold_reached`, etc. +- HMAC signature verification +- Automatic retry on failure + +### Custom Domains +- Customers can point `billing.theirdomain.com` to platform +- Auto-provisioned SSL via Let's Encrypt +- DNS verification required + +## Analytics & Reporting + +### Admin Dashboard +- MRR (Monthly Recurring Revenue) +- ARR (Annual Recurring Revenue) +- Churn rate and customer growth +- Revenue trends (daily, monthly, yearly) +- Popular plans and conversion rates +- Outstanding invoices + +### Financial Reports +- Revenue reports (by period, service, plan) +- Profit & Loss statements +- Tax reports (sales tax, VAT) +- Aging reports (overdue invoices) +- Refund reports +- Subscription metrics + +## Development Machine + +**Important**: This machine is for documentation and planning only. The actual Laravel project will be built on a separate development machine. + +## Contact + +For questions about this project, contact the EZSCALE development team. + +--- + +**Status**: Planning Phase - Documentation Complete +**Last Updated**: February 8, 2026 +**Total Planning Documents**: 4 files, ~2000 lines of specifications diff --git a/TASKS.md b/TASKS.md new file mode 100644 index 0000000..ac7e780 --- /dev/null +++ b/TASKS.md @@ -0,0 +1,340 @@ +# TASKS.md - EZSCALE Site Task Tracker + +## Phase 1: Foundation & Core Setup +- [ ] Initialize Laravel 12 project with Vue + Inertia starter kit +- [ ] Configure domain routing (ezscale.cloud, account.ezscale.cloud, admin.ezscale.cloud) +- [ ] Set up MySQL 8.x with multi-region replication and automated backups +- [ ] Configure Redis (cache, queue, sessions) +- [ ] Install core dependencies: + - [ ] laravel/cashier (Stripe) + - [ ] laravel/fortify (authentication) + - [ ] laravel/passport (OAuth2 for SSO) + - [ ] srmklive/laravel-paypal + - [ ] spatie/laravel-permission +- [ ] Create complete database schema and migrations (users, profiles, plans, subscriptions, services, bandwidth, etc.) +- [ ] Set up Laravel Fortify with Vue/Inertia auth pages (login, register, verify) +- [ ] Implement 2FA (TOTP for customers, WebAuthn/passkeys for admins) +- [ ] Configure spatie roles: `admin` and `customer` +- [ ] Set up middleware: auth, role-based, rate limiting +- [ ] Configure Cloudflare Zero Trust for admin panel +- [ ] Set up GitHub Actions CI/CD pipeline +- [ ] Create staging environment (staging.account.ezscale.cloud) +- [ ] Configure Mailgun or SendGrid for emails +- [ ] Set up testing framework (PHPUnit/Pest) + +## Phase 2: Billing & Subscriptions +- [ ] Implement `BillingServiceInterface` abstraction +- [ ] Build `StripeBillingService` (wraps Laravel Cashier) +- [ ] Build `PayPalBillingService` (wraps srmklive/laravel-paypal) +- [ ] Create plan catalog with all service types: + - [ ] VPS plans (various tiers with pricing) + - [ ] Dedicated server plans + - [ ] Web hosting plans + - [ ] Game server plans (Minecraft, ARK, etc.) +- [ ] Implement subscription creation flow (select plan → payment → provision) +- [ ] Build payment method management (multiple cards/PayPal per customer) +- [ ] Implement invoice generation (PDF, custom numbering, multi-currency) +- [ ] Set up webhook handlers for Stripe and PayPal +- [ ] Implement proration logic for upgrades/downgrades +- [ ] Build dunning system (failed payment handling, retry logic) +- [ ] Implement coupon system: + - [ ] Coupon creation and management (admin) + - [ ] Coupon redemption (customer checkout) + - [ ] Usage tracking and expiry +- [ ] Multi-currency support (EUR, GBP, USD, etc.) +- [ ] Tax calculation integration (TaxJar/Avalara or manual rates) +- [ ] Automatic suspension policy (X days past due → suspend → Y days → terminate) + +## Phase 3: Provisioning Automation +- [ ] Create `ProvisioningServiceInterface` abstraction +- [ ] Build VirtFusion provisioning service: + - [ ] Create VPS via API + - [ ] Suspend/unsuspend VPS + - [ ] Terminate VPS + - [ ] Get status and resource usage + - [ ] Credential generation and secure storage +- [ ] Build Pterodactyl provisioning service: + - [ ] Create game server via API + - [ ] Suspend/unsuspend server + - [ ] Delete server + - [ ] Get server status and resources +- [ ] Build SynergyCP provisioning service: + - [ ] Provision dedicated server + - [ ] Suspend/unsuspend server + - [ ] Terminate server + - [ ] Get server details + - [ ] Handle limited hardware inventory (waitlist/semi-auto) +- [ ] Build Enhance provisioning service: + - [ ] Create web hosting account + - [ ] Suspend/delete account + - [ ] Get account status +- [ ] Implement event-driven provisioning (listen to `PaymentSucceeded` events) +- [ ] Build provisioning failure handling and retry logic +- [ ] Send credentials email on successful provisioning +- [ ] Log all provisioning actions to `provisioning_logs` table + +## Phase 4: Customer Dashboard (account.ezscale.cloud) +- [ ] Build service overview dashboard: + - [ ] Active services list with status indicators + - [ ] Resource usage widgets (CPU, RAM, disk, bandwidth) + - [ ] Next invoice and payment due date + - [ ] Recent support tickets + - [ ] Quick actions (renew, upgrade, create ticket) +- [ ] Build service detail pages: + - [ ] VPS details (IP, credentials, resource graphs, control buttons) + - [ ] Game server details (connect info, resource usage, restart button) + - [ ] Dedicated server details (IPs, access info, bandwidth graph) + - [ ] Web hosting details (domain, cPanel/Enhance link, disk usage) +- [ ] Bandwidth usage graphs (from ElastiFlow integration) +- [ ] Billing section: + - [ ] Invoice history (with PDF download) + - [ ] Payment history + - [ ] Manage payment methods (add/remove cards, set default) + - [ ] Upcoming renewals +- [ ] Plan upgrade/downgrade flow (self-service with proration) +- [ ] Subscription cancellation flow (with optional survey) +- [ ] Profile and account settings: + - [ ] Contact information + - [ ] Billing/shipping addresses + - [ ] Tax ID + - [ ] Password change + - [ ] 2FA setup (TOTP, passkeys) +- [ ] SupportPal integration: + - [ ] SSO to SupportPal + - [ ] View recent tickets widget + - [ ] Create ticket button (opens SupportPal or API) + +## Phase 5: Admin Panel (admin.ezscale.cloud) +- [ ] Analytics dashboard: + - [ ] MRR (Monthly Recurring Revenue) graph + - [ ] ARR (Annual Recurring Revenue) + - [ ] Churn rate calculation and graph + - [ ] Customer growth chart + - [ ] Revenue trends (daily, monthly, yearly) + - [ ] Popular plans and conversion rates + - [ ] Outstanding invoices total + - [ ] Overdue accounts list +- [ ] Customer management: + - [ ] Customer list (searchable, filterable) + - [ ] Customer detail view (profile, services, billing history, notes) + - [ ] Edit customer information + - [ ] Impersonate customer (with audit logging) + - [ ] Add admin notes to customer account + - [ ] View customer audit log +- [ ] Service management: + - [ ] All services list (filter by type, status, platform) + - [ ] Manually provision service + - [ ] Suspend/unsuspend service + - [ ] Terminate service + - [ ] Modify service (change plan, extend expiry) + - [ ] View provisioning logs +- [ ] Order management: + - [ ] Pending orders list + - [ ] Approve/reject orders (for semi-automated provisioning) + - [ ] View order details +- [ ] Invoice management: + - [ ] All invoices list (filter by status, date, customer) + - [ ] Create manual invoice + - [ ] Edit invoice (before sending) + - [ ] Void/refund invoice + - [ ] Resend invoice email +- [ ] Coupon management: + - [ ] Create coupon (percentage, fixed, applies to plans) + - [ ] Edit coupon details + - [ ] View redemption history + - [ ] Deactivate/delete coupon +- [ ] Plan management: + - [ ] Create new plan (set pricing, features, billing cycle) + - [ ] Edit existing plan + - [ ] Archive/hide plan + - [ ] Set stock quantity (for limited dedicated servers) +- [ ] System configuration: + - [ ] Email template editor + - [ ] Tax rate configuration (by region) + - [ ] Suspension policy settings (days before suspend/terminate) + - [ ] Bandwidth overage rates + - [ ] Discord webhook URLs + - [ ] API credentials (VirtFusion, Pterodactyl, etc.) +- [ ] Audit log viewer: + - [ ] Filter by user, action, date + - [ ] View changes (before/after state) + - [ ] Export logs + +## Phase 6: Bandwidth Monitoring & Billing +- [ ] Set up NetFlow/sFlow export from Juniper switches +- [ ] Deploy ElastiFlow collector +- [ ] Build `BandwidthService` to query ElastiFlow API +- [ ] Create scheduled job to collect daily bandwidth data +- [ ] Store bandwidth usage in `bandwidth_usage` table +- [ ] Build bandwidth usage graphs for customer dashboard +- [ ] Implement multi-threshold alerts: + - [ ] 75% quota warning email + - [ ] 90% quota warning email + - [ ] 100% quota reached email + - [ ] Discord webhook for high usage customers +- [ ] Implement automatic overage billing: + - [ ] Calculate overages at end of billing cycle + - [ ] Generate overage invoice + - [ ] Email customer with overage details +- [ ] Build admin bandwidth reports: + - [ ] Top bandwidth users + - [ ] Total bandwidth by service type + - [ ] Overage revenue report + +## Phase 7: SupportPal Integration +- [ ] Implement SSO for SupportPal: + - [ ] Laravel Passport OAuth2 integration + - [ ] SupportPal SAML or custom SSO config + - [ ] Test seamless login flow +- [ ] Build SupportPal API integration: + - [ ] Fetch user's recent tickets + - [ ] Create ticket via API + - [ ] Fetch ticket details and replies +- [ ] Build webhook handlers for SupportPal: + - [ ] New ticket created + - [ ] Ticket reply added + - [ ] Ticket status changed + - [ ] Ticket closed +- [ ] Display tickets in customer dashboard: + - [ ] Recent tickets widget + - [ ] Link to full ticket in SupportPal +- [ ] Admin ticket overview: + - [ ] Open tickets count + - [ ] Tickets by priority + - [ ] Link to SupportPal admin +- [ ] Discord notifications for tickets: + - [ ] New ticket opened + - [ ] Ticket escalated (high priority) + +## Phase 8: Marketing Frontend (ezscale.cloud) +- [ ] Homepage: + - [ ] Hero section with value proposition + - [ ] Featured services/plans + - [ ] Trust indicators (uptime, customers, years in business) + - [ ] Call to action (Get Started, View Plans) +- [ ] Product pages: + - [ ] VPS hosting page with plan comparison + - [ ] Dedicated servers page with configurations + - [ ] Web hosting page with features + - [ ] Game server hosting page with supported games +- [ ] Pricing page: + - [ ] Interactive plan comparison table + - [ ] Currency selector (USD, EUR, GBP) + - [ ] Coupon code application + - [ ] Add to cart / checkout flow +- [ ] About page +- [ ] Contact page +- [ ] Blog/news section (optional, or use WordPress?) +- [ ] Knowledge base / FAQ: + - [ ] Getting started guides + - [ ] Tutorials + - [ ] Troubleshooting + - [ ] API documentation +- [ ] Legal pages: + - [ ] Terms of Service + - [ ] Privacy Policy + - [ ] Acceptable Use Policy + - [ ] SLA (Service Level Agreement) +- [ ] Signup flow: + - [ ] Plan selection + - [ ] Account creation + - [ ] Payment information + - [ ] Order confirmation + - [ ] Redirect to account dashboard + +## Phase 9: API Development +- [ ] Customer API (RESTful, Sanctum auth): + - [ ] GET /api/v1/services - List customer's services + - [ ] GET /api/v1/services/{id} - Service details + - [ ] POST /api/v1/services/{id}/reboot - Reboot server + - [ ] GET /api/v1/invoices - Invoice history + - [ ] GET /api/v1/invoices/{id}/pdf - Download invoice PDF + - [ ] GET /api/v1/bandwidth - Bandwidth usage + - [ ] POST /api/v1/subscriptions/{id}/cancel - Cancel subscription + - [ ] POST /api/v1/tickets - Create support ticket +- [ ] Admin API: + - [ ] GET /api/v1/admin/customers - List all customers + - [ ] GET /api/v1/admin/services - List all services + - [ ] POST /api/v1/admin/services/{id}/suspend - Suspend service + - [ ] GET /api/v1/admin/analytics - Analytics data +- [ ] API documentation (OpenAPI/Swagger) +- [ ] API rate limiting and throttling +- [ ] API versioning strategy + +## Phase 10: Testing, Migration & Launch +- [ ] Unit tests for all services and models +- [ ] Feature tests for critical user flows: + - [ ] Signup and subscription creation + - [ ] Payment processing (Stripe + PayPal) + - [ ] Service provisioning (all platforms) + - [ ] Upgrades/downgrades + - [ ] Cancellations + - [ ] Invoice generation + - [ ] Bandwidth overage billing +- [ ] Integration tests: + - [ ] VirtFusion API integration + - [ ] Pterodactyl API integration + - [ ] SynergyCP API integration + - [ ] Enhance API integration + - [ ] ElastiFlow API integration + - [ ] SupportPal API integration +- [ ] Security testing: + - [ ] Penetration testing (OWASP Top 10) + - [ ] Dependency vulnerability scanning + - [ ] CSRF and XSS testing + - [ ] SQL injection testing + - [ ] Rate limiting testing +- [ ] Performance testing: + - [ ] Load testing (100+ concurrent users) + - [ ] Database query optimization + - [ ] Redis caching implementation + - [ ] CDN for static assets +- [ ] WHMCS migration: + - [ ] Create migration commands: + - [ ] `migrate:whmcs-customers` + - [ ] `migrate:whmcs-subscriptions` + - [ ] `migrate:whmcs-invoices` + - [ ] `migrate:whmcs-payments` + - [ ] `migrate:whmcs-services` + - [ ] `migrate:whmcs-tickets` + - [ ] Test migration in staging + - [ ] Verify data integrity + - [ ] Map WHMCS product IDs to new plan IDs + - [ ] Coordinate Stripe/PayPal subscription transfer +- [ ] Pre-launch checklist: + - [ ] Email customers about migration + - [ ] Set up WHMCS URL redirects + - [ ] Configure monitoring (Laravel Telescope, log aggregation) + - [ ] Set up error tracking (Sentry, Bugsnag) + - [ ] Configure backups (database, files, Redis) + - [ ] DNS configuration for all domains + - [ ] SSL certificates for all domains + - [ ] Cloudflare Zero Trust for admin panel +- [ ] Launch: + - [ ] Execute final WHMCS migration during maintenance window + - [ ] Enable production mode + - [ ] Monitor for errors and performance issues + - [ ] 30-day parallel operation (keep WHMCS read-only) + - [ ] Gather customer feedback + - [ ] Address bugs and issues +- [ ] Post-launch: + - [ ] Monitor analytics and revenue + - [ ] Track customer satisfaction + - [ ] Iterate based on feedback + - [ ] Plan future features + +## Phase 11: Future Enhancements (Post-Launch) +- [ ] Mobile app (iOS/Android) using API +- [ ] Advanced analytics (cohort analysis, LTV predictions) +- [ ] Automated resource scaling (auto-upgrade when limits reached) +- [ ] Custom server configurations (customer can configure RAM, CPU, disk) +- [ ] Marketplace for add-ons (additional IPs, backups, snapshots) +- [ ] Advanced bandwidth analytics (top talkers, traffic patterns) +- [ ] Integration with accounting software (QuickBooks, Xero) +- [ ] Advanced reporting (custom reports, scheduled exports) +- [ ] Customer referral program (instead of affiliates) +- [ ] Live chat support integration +- [ ] Status page for service health +- [ ] Automated security scanning for customer servers +- [ ] Backup management interface +- [ ] Server snapshots and restoration