# ToolStore Development Plan
**Version**: 1.0  
**Last Updated**: 2025-09-30  
**Status**: Pre-Development Planning

---

## Table of Contents
1. [Project Overview](#project-overview)
2. [Technology Stack Decisions](#technology-stack-decisions)
3. [Database Architecture](#database-architecture)
4. [Development Phases](#development-phases)
5. [Critical Implementation Details](#critical-implementation-details)
6. [Security Considerations](#security-considerations)
7. [Testing Strategy](#testing-strategy)
8. [Deployment & DevOps](#deployment-devops)
9. [Open Questions & Decisions](#open-questions-decisions)

---

## Project Overview

### What We're Building
A Telegram-first digital storefront where:
- Users deposit **Bitcoin** (via BitGo)
- Deposits are converted to **USD balance** at market rate
- Users purchase **digital products** using their USD balance
- Fulfillment is **instant** (we show them the data we have in details columm of the purchase product with other details of the product, such as price, balance etc)
- Admin manages everything via **Filament 4** panel

### Core User Journey
```
1. User starts Telegram bot
2. User creates deposit request and gets unique BTC address with QR
3. User sends BTC and BitGo detects transaction
4. After N confirmations USD credited to balance
5. User browses categories and products
6. User buys product, balance deducted, entitlement delivered
7. User can re-access purchases anytime
```

### Success Metrics
- **Idempotent** deposit crediting (no double-credits)
- **Transactional** purchases (atomic balance deduction)
- **Encrypted** sensitive payloads at rest
- **Auditable** admin actions
- **Sub-second** Telegram response times

---

## Technology Stack Decisions

### Confirmed Stack
- **Framework**: Laravel 12.x
- **Admin Panel**: Filament 4.x
- **Database**: MySQL 8.0+
- **Cache/Queue**: Redis 7.x
- **Queue Monitor**: Laravel Horizon
- **Audit Log**: spatie/laravel-activitylog
- **QR Codes**: endroid/qr-code
- **Error Tracking**: Sentry or Bugsnag

### Decisions Needed

**1. BitGo Integration Approach**
- Option A: Official BitGo SDK
- Option B: Direct REST API via Laravel HTTP
- Recommendation: Option B (more control)
- Decision: Option B

**2. Rate Provider for BTC to USD**
- Option A: CoinGecko API (free tier)
- Option B: CoinMarketCap API
- Option C: Binance API
- Recommendation: CoinGecko
- Decision: CoinGecko

**3. QR Code Storage**
- Option A: Generate on-the-fly
- Option B: Store in storage/app/qr/
- Recommendation: Option A
- Decision: Option A

**4. Telegram Message Delivery**
- Option A: Synchronous responses
- Option B: All messages queued
- Recommendation: Hybrid approach
- Decision: Hybrid approach

**5. Payload Encryption**
- Option A: Laravel Crypt (app key)
- Option B: Separate encryption key
- Recommendation: Option B
- Decision: Option A

---

## Database Architecture

### Tables Overview
- users (8 columns)
- categories (9 columns, self-referential)
- products (18 columns)
- deposit_requests (9 columns)
- deposits (13 columns)
- orders (5 columns)
- order_items (8 columns)
- entitlements (8 columns)
- support_tickets (7 columns)

### Critical Fields Discussion

**users.balance_usd**
- Type: DECIMAL(14,2)
- Question: Add balance_locked for pending orders?
- Decision: No

**products.balance**
- Purpose: Products that include usable credit
- Type: DECIMAL(14,2) NULLABLE
- Question: Auto-credit on purchase?
- Decision: We wont be selling products that include credit

**products.delivery_payload**
- Type: JSON (encrypted)
- Supports: text (we show them the data we have in details columm of the purchase product with other details of the product, such as price, balance etc)
- Decision: Support all types

**deposits.rate_usd_per_btc**
- Type: DECIMAL(18,8)
- Question: Cache rates or fetch on-demand?
- Decision: Yes

---

## Development Phases

### Phase 1: Foundation (Week 1)

**Goal**: Working Laravel app with database and admin panel

**Tasks**:
1. Install core packages (Filament, Spatie, QR, Horizon)
2. Configure Redis for queues and cache
3. Create all database migrations
4. Create models with relationships
5. Seed initial data (owner, categories, products)
6. Set up Filament admin panel
7. Test admin login and basic navigation

**Deliverable**: Admin can log in to Filament

---

### Phase 2: Telegram Bot Core (Week 1-2)

**Goal**: Bot responds to commands and shows menu

**Tasks**:
1. Create webhook route with CSRF exemption
2. Implement BotWebhookController
3. Create TelegramService helper
4. Implement handlers (start, balance, rules)
5. Set up webhook with Telegram API
6. Test bot responses

**Deliverable**: Bot responds to /start with menu

---

### Phase 3: Browse & Products (Week 2)

**Goal**: Users can navigate and view products

**Tasks**:
1. Implement category browsing with pagination
2. Implement product detail view
3. Handle back navigation
4. Cache category tree
5. Test full browse flow

**Deliverable**: Users can browse all products

---

### Phase 4: Deposits & BitGo (Week 2-3)

**Goal**: Users can deposit BTC and get USD

**Tasks**:
1. Create BitGoService wrapper
2. Create QrService for QR generation
3. Implement deposit request creation
4. Create BitGo webhook endpoint
5. Implement webhook controller with signature verification
6. Create RateService for BTC/USD rates
7. Implement USD crediting logic with idempotency
8. Create NotifyUserDepositCredited job
9. Create cron job to expire old requests
10. Test full deposit flow

**Deliverable**: Users can deposit BTC and receive USD

---

### Phase 5: Purchases & Fulfillment (Week 3)

**Goal**: Users can buy and receive products

**Tasks**:
1. Create PurchaseService with transaction logic
2. Implement buy handler
3. Create SendEntitlement job
4. Implement purchases list
5. Handle product balance auto-credit
6. Test purchase flow

**Deliverable**: Users can buy and receive products

---

### Phase 6: Admin Panel (Week 3-4)

**Goal**: Staff can manage everything

**Tasks**:
1. Create Filament resources (Users, Categories, Products)
2. Create Filament resources (Deposits, Orders, Entitlements)
3. Implement role-based permissions
4. Add custom actions (balance adjustment, refunds)
5. Create report pages
6. Test admin workflows

**Deliverable**: Full admin management capability

---

### Phase 7: Testing & QA (Week 4)

**Goal**: Comprehensive test coverage

**Tasks**:
1. Write unit tests (RateService, PurchaseService)
2. Write feature tests (webhooks, handlers)
3. Write E2E tests (full user journey)
4. Test edge cases (duplicates, expired requests)
5. Load testing for webhooks
6. Security audit

**Deliverable**: 80%+ test coverage

---

### Phase 8: Deployment (Week 4-5)

**Goal**: Production-ready deployment

**Tasks**:
1. Set up Horizon for queue monitoring
2. Configure Sentry for error tracking
3. Create backup scripts
4. Write deployment documentation
5. Set up staging environment
6. Production deployment
7. Monitor and optimize

**Deliverable**: Live production system

---

## Critical Implementation Details

### Idempotency Pattern
```php
// Always guard on nullable fields before crediting
if ($deposit->credited_usd !== null) {
    return; // Already credited
}
```

### Transaction Pattern
```php
DB::transaction(function () {
    // All balance changes must be in transactions
    // Check balance
    // Create order
    // Deduct balance
    // Create entitlement
});
```

### Money Math Pattern
```php
// Use bcmath for precision
$btc = bcdiv($satoshi, '100000000', 8);
$usd = bcmul($btc, $rate, 8);
$usd = floor($usd * 100) / 100; // Round down to cents
```

### Encryption Pattern
```php
// Encrypt sensitive data
$encrypted = encrypt($payload);

// Decrypt when needed
$decrypted = decrypt($encrypted);
```

---

## Security Considerations

### Webhook Security
- Verify BitGo HMAC signature
- Verify Telegram secret token
- Rate limit webhook endpoints

### Data Protection
- Encrypt delivery_payload
- Encrypt fulfillment_payload
- Never log decrypted sensitive data


### Admin Security
- only one superadmin account
- Audit trail for all actions


### Financial Security
- Idempotent operations
- Transactional balance updates
- Round down USD amounts
- Prevent negative balances

---

## Testing Strategy

### Unit Tests
- RateService returns valid numbers
- USD rounding works correctly
- PurchaseService handles insufficient balance
- Encryption/decryption works

### Feature Tests
- BitGo webhook creates deposit
- Confirmations trigger USD credit
- Duplicate webhooks don't double-credit
- Telegram handlers return correct responses
- Purchase flow works end-to-end

### E2E Tests
- Full user journey from deposit to purchase
- Multiple products in sequence
- Expired deposit requests
- Out of stock products

### Edge Cases
- Duplicate webhook deliveries
- Late confirmations
- Concurrent purchases
- Race conditions on balance

---

## Deployment & DevOps

### Environment Setup
```env
APP_NAME=ToolsStore
APP_ENV=production
QUEUE_CONNECTION=redis
CACHE_DRIVER=redis

TELEGRAM_BOT_TOKEN=
TELEGRAM_WEBHOOK_SECRET=
BITGO_API_KEY=
BITGO_WEBHOOK_SECRET=
PAYMENTS_REQUIRED_CONFIRMATIONS=2
RATE_PROVIDER=coingecko
```

### Server Requirements
- PHP 8.2+
- MySQL 8.0+
- Redis 7.x
- Supervisor for queues
- SSL certificate

### Monitoring
- Laravel Horizon for queues
- Sentry for errors
- Custom dashboard for deposits
- Alert on failed jobs

### Backups
- Daily database backups
- Storage backups
- Backup retention: 30 days
- Tested restore procedure

---

## Open Questions & Decisions

### Business Logic
1. Should deposit requests expire? If yes, after how long?
   - Recommendation: 24 hours
   - Decision: NO

2. What happens to multiple transactions to same address?
   - Recommendation: Credit all (link to request)
   - Decision: Credit all (link to request)

3. Should we support refunds? If yes, to balance or BTC?
   - Recommendation: To balance only
   - Decision: NO

4. Minimum deposit amount?
   - Recommendation: $10 USD equivalent
   - Decision: Yes(admin can set this from general configuration page in the admin panel)

5. Maximum balance limit per user?
   - Recommendation: $10,000 
   - Decision: YES

### Technical Decisions
1. How many confirmations required?
   - Recommendation: 2 for mainnet
   - Decision: YES

2. Rate refresh frequency?
   - Recommendation: Every 5 minutes
   - Decision: YES

3. Queue retry attempts?
   - Recommendation: 3 attempts with exponential backoff
   - Decision: YES

4. Session timeout for admin?
   - Recommendation: 2 hours
   - Decision: Fillament handles this

### Product Features
1. Should products have variants (size, color)?
   - Recommendation: Not in MVP
   - Decision: NO( product only have theses)

- DROP TABLE IF EXISTS `products`;
  CREATE TABLE `products` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `seller_id` int(11) DEFAULT NULL, // admin
  `category_id` varchar(50) DEFAULT NULL, // that will be the subcategory id
  `title` text DEFAULT NULL,
  `short_description` text DEFAULT NULL,
  `balance` varchar(255) DEFAULT NULL,
  `price` varchar(255) DEFAULT NULL,
  `details` longtext DEFAULT NULL, //detsils of the product which they will see after purchase 
  `sold` tinyint(1) NOT NULL DEFAULT 0,
  `sold_to` varchar(255) NOT NULL DEFAULT '', // purchased user id 
  `deleted` tinyint(1) NOT NULL DEFAULT 0,
  `refund` tinyint(1) NOT NULL DEFAULT 0,
  `joined` timestamp NOT NULL DEFAULT current_timestamp(),
  `purchased_time` timestamp NOT NULL DEFAULT current_timestamp(),
  `updated` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;



2. Should we support bundles?
   - Recommendation: Phase 2
   - Decision: NO

3. Discount codes or promotions?
   - Recommendation: Phase 2
   - Decision: NO

4. Affiliate system?
   - Recommendation: Phase 3
   - Decision: NO

---

## Next Steps

1. Review this document and make decisions on PENDING items
2. Set up development environment
3. Begin Phase 1 implementation
4. Schedule daily standups
5. Set up project tracking (GitHub Issues, Jira, etc.)

---

## Notes & Considerations

- Keep Telegram responses under 4096 characters
- Use inline keyboards for better UX
- Cache aggressively but invalidate correctly
- dont log  everything for debugging only few and critical ones or when i ask you to do so 
- Plan for horizontal scaling
- Consider multi-currency support later
- Document all API integrations
- Keep admin UI simple and fast

---

**Document Status**: Ready for review and decision-making
**Next Review Date**: Before Phase 1 starts
**Owner**: Development Team
