BCards/CLAUDE.md

10 KiB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

BCards is a professional LinkTree clone built in ASP.NET Core MVC, targeting Brazilian and Spanish markets. It provides hierarchical URLs organized by business categories (/page/{category}/{slug}), integrated Stripe payments, and a sophisticated moderation system with preview tokens.

Development Commands

Build & Run

# Quick clean build (RECOMMENDED after VS 2022 updates)
./clean-build.sh

# Manual process:
dotnet restore
dotnet build

# Run development server
cd src/BCards.Web
dotnet run
# Access: https://localhost:49178

# Run with Docker
docker-compose up -d
# Access: http://localhost:8080

🚨 Known Issues After VS 2022 Updates

Problem: After VS 2022 updates, build cache gets corrupted causing:

  • OAuth login failures (especially Google in Edge browser)
  • Need for constant clean/rebuild cycles
  • NuGet package resolution errors

Solution: Use the automated cleanup script:

./clean-build.sh

Google OAuth Edge Issue: If Google login shows "browser not secure" error:

  1. Clear browser data for localhost:49178 and accounts.google.com
  2. Test in incognito/private mode
  3. Use Vivaldi or Chrome (Edge has known compatibility issues)

Testing

# Run all tests
dotnet test

# Run tests with coverage
dotnet test --collect:"XPlat Code Coverage"

# Run specific test
dotnet test --filter "TestClassName"

Architecture Overview

Technology Stack

  • Framework: ASP.NET Core MVC (.NET 8)
  • Database: MongoDB 7.0 with MongoDB.Driver 2.25.0
  • Authentication: OAuth 2.0 (Google + Microsoft)
  • Payments: Stripe.NET 44.7.0
  • Frontend: Bootstrap 5.3.2, jQuery 3.7.1, vanilla JavaScript
  • Email: SendGrid 9.29.3
  • Containerization: Docker + Docker Compose

Core Architecture Patterns

  • MVC Pattern: Controllers handle HTTP requests, Views render UI, Models represent data
  • Repository Pattern: Data access abstraction via IUserPageRepository, ICategoryRepository, etc.
  • Service Layer: Business logic encapsulation (IUserPageService, IModerationService, etc.)
  • Dependency Injection: Built-in ASP.NET Core DI container
  • Domain-Driven Design: Rich domain models with business logic

Key Business Logic

Page Status System

Pages follow this lifecycle with explicit numeric enum values:

  • Creating = 6: Development phase, requires preview tokens
  • PendingModeration = 4: Submitted for approval, requires preview tokens
  • Rejected = 5: Failed moderation, requires preview tokens
  • Active = 0: Live and publicly accessible
  • Inactive = 3: Paused by user
  • Expired = 1: Trial expired, redirects to pricing
  • PendingPayment = 2: Payment overdue, shows warning

Moderation System

  • Content approval workflow with attempts tracking
  • Preview tokens with 4-hour expiration for non-Active pages
  • Email notifications for status changes
  • Automatic status transitions based on user actions

Pricing Strategy

Three-tier system with psychological pricing (decoy effect):

  • Basic (R$ 9.90/mês): 5 links, basic themes
  • Professional (R$ 24.90/mês): 15 links, all themes - DECOY
  • Premium (R$ 29.90/mês): Unlimited links, custom themes

Project Structure

src/BCards.Web/
├── Controllers/           # MVC Controllers (9 total)
│   ├── AdminController    # User dashboard and page management
│   ├── AuthController     # OAuth authentication
│   ├── HomeController     # Public pages and landing
│   ├── PaymentController  # Stripe integration
│   ├── ModerationController # Content approval system
│   └── UserPageController # Public page display
├── Models/               # Domain entities (12 total)
│   ├── User              # Authentication and subscriptions
│   ├── UserPage          # Main business card entity
│   ├── LinkItem          # Individual links with analytics
│   └── Category          # Business categories
├── Services/             # Business logic (20 services)
│   ├── IUserPageService  # Core page operations
│   ├── IModerationService # Content approval
│   ├── IAuthService      # Authentication
│   └── IPaymentService   # Stripe integration
├── Repositories/         # Data access (8 repositories)
├── ViewModels/          # View-specific models
├── Middleware/          # Custom middleware (4 pieces)
│   ├── PageStatusMiddleware    # Handles page access by status
│   ├── ModerationAuthMiddleware # Admin access control
│   └── PreviewTokenMiddleware  # Preview token validation
└── Views/               # Razor templates with Bootstrap 5

Database Design (MongoDB)

Core Collections

  • users: Authentication, subscription status, Stripe customer data
  • userpages: Business cards with status, links, themes, moderation history
  • categories: Business categories with SEO metadata
  • subscriptions: Stripe subscription tracking

Important Indexes

  • Compound: {category: 1, slug: 1} for page lookups
  • User pages: {userId: 1, status: 1} for dashboard filtering
  • Active pages: {status: 1, category: 1} for public listings

Key Features Implementation

Preview Token System

Non-Active pages require preview tokens for access:

// Generate fresh token (4-hour expiry)
POST /Admin/GeneratePreviewToken/{id}

// Access page with token
GET /page/{category}/{slug}?preview={token}

OAuth Integration

Supports Google and Microsoft OAuth with automatic user creation and session management.

Stripe Payment Flow

Complete subscription lifecycle:

  1. Checkout session creation
  2. Webhook handling for events
  3. Subscription status updates
  4. Plan limitation enforcement

Dynamic Theming

CSS generation system with customizable colors, backgrounds, and layouts based on user's plan limitations.

Configuration

Required Environment Variables

{
  "MongoDb": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "BCardsDB"
  },
  "Stripe": {
    "PublishableKey": "pk_test_...",
    "SecretKey": "sk_test_...",
    "WebhookSecret": "whsec_..."
  },
  "Authentication": {
    "Google": { "ClientId": "...", "ClientSecret": "..." },
    "Microsoft": { "ClientId": "...", "ClientSecret": "..." }
  }
}

Development Setup

  1. Install .NET 8 SDK, MongoDB 4.4+
  2. Configure OAuth credentials (Google Cloud Console, Azure Portal)
  3. Set up Stripe account with test keys
  4. Configure webhook endpoints for /webhook/stripe

Important Implementation Notes

Page Status Middleware

PageStatusMiddleware intercepts all /page/{category}/{slug} requests and enforces access rules based on page status. Non-Active pages require valid preview tokens.

Moderation Workflow

  1. Pages start as Creating status
  2. Users click "Submit for Moderation" → PendingModeration
  3. Moderators approve/reject → Active or Rejected
  4. Rejected pages can be edited and resubmitted

Preview Token Security

  • Tokens expire after 4 hours
  • Generated on-demand via AJAX calls
  • Required for Creating, PendingModeration, and Rejected pages
  • Validated by middleware before page access

Plan Limitations

Enforced throughout the application:

  • Link count limits per plan
  • Theme availability restrictions
  • Analytics access control
  • Page creation limits

Common Development Patterns

Repository Usage

var page = await _userPageService.GetPageByIdAsync(id);
await _userPageService.UpdatePageAsync(page);

Service Layer Pattern

Business logic resides in services, not controllers:

public class UserPageService : IUserPageService
{
    private readonly IUserPageRepository _repository;
    // Implementation with business rules
}

Status-Based Logic

Always check page status before operations:

if (page.Status == PageStatus.Creating || page.Status == PageStatus.Rejected)
{
    // Allow editing
}

This architecture supports a production-ready SaaS application with complex business rules, payment integration, and content moderation workflows.

Project instructions

ctx — use before reading files

This project has ctx available in PATH. Use it to understand the codebase before reading files directly. It produces compact markdown summaries that cost far fewer tokens than raw file content.

When to use

Always use ctx first when you need to:

  • Understand project structure → ctx csharp project or ctx react project
  • Understand a file's structure → ctx csharp outline <file> or ctx react outline <file>
  • Check build errors → ctx csharp errors or ctx react errors
  • Understand git state → ctx git
  • Detect what stack this project uses → ctx auto detect

Workflow

  1. Start of session: run ctx auto detect to see what's here, then ctx <stack> project for an overview.
  2. Before reading a file: run ctx <stack> outline <file> first. Only read the full file if the outline isn't enough (e.g., you need to see method body logic).
  3. After making changes: run ctx <stack> errors instead of dotnet build or tsc — the output is pre-filtered to only relevant diagnostics.
  4. Before committing: run ctx git for a compact diff summary.

Available commands

ctx auto detect              # detect stack(s) in current directory
ctx auto project             # run project summary for all detected stacks

ctx csharp project           # .NET solution overview (projects, refs, packages)
ctx csharp outline <file.cs> # file structure without method bodies
ctx csharp errors            # filtered dotnet build output (errors + top warnings)

ctx git                      # branch, status, recent commits, diff summary

Important

  • ctx output is a summary, not the full picture. If you need implementation details (method bodies, exact logic, specific lines), read the file directly.
  • Do not run ctx commands that don't match the project stack. Use ctx auto detect if unsure.
  • ctx csharp errors assumes dotnet restore was already run. If you get restore errors, run dotnet restore first, then ctx csharp errors.