---
name: receipt-scan-app
description: Build a receipt scanning app that complements a home renovation app — uses Apple Vision Kit for OCR (free, local), tracks price history, enables social sharing, and integrates with renovation app's material database.
---

# Receipt Scan App Development

Build an iOS-native receipt scanning app that works with your home renovation app:
- **Scan receipts** → Extract items, prices, quantities
- **Match materials** → Auto-match to renovation app's database
- **Track prices** → Historical price trends (Home Depot, Lowe's, 淘宝, 京东)
- **Social sharing** → Share material lists with friends (earn commissions)
- **Budget tracking** → Compare actual spending vs renovation app budget

## When to Use
- Building companion app to home renovation app
- Need OCR for receipts (iOS native, free)
- Want price history + social features
- Integrating with existing material database

## Architecture Pattern

### 1. Tech Stack
```
iOS App (SwiftUI)
    ↓ Vision Kit OCR (free, local)
Receipt Items
    ↓ Match to Materials DB
Renovation App Backend (shared)
    ↓ Price History + Social Share
User Gets Full Ecosystem
```

### 2. Project Structure
```
~/projects/receipt-scan-app/
├── ios/
│   ├── CLAUDE.md              # SwiftUI engineer context
│   ├── ReceiptScanApp.swift    # App entry + data models
│   ├── ScannerView.swift        # Camera + Vision OCR
│   ├── ReceiptListView.swift    # Receipt list
│   ├── MaterialMatchView.swift # Match to renovation DB
│   └── PriceHistoryView.swift  # Swift Charts price trends
└── backend/                   # Optional: shared API
    └── (reuse renovation app backend)
```

### 3. Key Dependencies
```swift
import Vision      // Free OCR, 95%+ accuracy
import SwiftUI     // Modern UI
import Core Data  // Persistence (or SwiftData iOS 17+)
import Swift Charts // Price history graphs (iOS 16+)
```

## Core Features

### Feature 1: Vision Kit OCR

**Why Vision Kit?**
| Advantage | Description |
|-----------|-------------|
| **Free** | No API costs, unlimited scans |
| **Local** | No network needed, better privacy |
| **Native** | Perfect SwiftUI integration |
| **Accurate** | 95%+ for English, 85%+ Chinese |

**Basic OCR Code:**
```swift
import Vision

func scanText(in image: CGImage) async -> [String] {
    await withCheckedContinuation { continuation in
        let request = VNRecognizeTextRequest { request, error in
            let texts = (request.results as? [VNRecognizedTextObservation])?
                .compactMap { $0.topCandidates(1).first?.string } ?? []
            continuation.resume(returning: texts)
        }
        request.recognitionLanguages = ["en-US", "zh-Hans"]
        request.recognitionLevel = .accurate
        
        let handler = VNImageRequestHandler(cgImage: image)
        try? handler.perform([request])
    }
}
```

**Receipt Parsing:**
```swift
func parseReceipt(_ texts: [String]) -> [ReceiptItem] {
    var items: [ReceiptItem] = []
    
    for text in texts {
        // Match: "Product Name   $Price"
        let pattern = "(.+?)\\s+\\$?(\\d+\\.\\d{2})"
        if let regex = try? NSRegularExpression(pattern: pattern),
           let match = regex.firstMatch(in: text, range: NSRange(location: 0, length: text.utf16.count)) {
            
            if let nameRange = Range(match.range(at: 1),
               let priceRange = Range(match.range(at: 2)) {
                let item = ReceiptItem(
                    name: String(text[nameRange]),
                    price: Double(String(text[priceRange])) ?? 0.0,
                    quantity: 1
                )
                items.append(item)
            }
        }
    }
    return items
}
```

### Feature 2: Material Matching

**Match scanned items to renovation app's database:**
```swift
func matchMaterial(_ itemName: String) async -> Material? {
    // Query renovation app backend
    let url = URL(string: "http://192.18.149.172:8000/api/v1/materials/query?name=\(itemName)")!
    
    let (data, _) = try! await URLSession.shared.data(from: url)
    let materials = try! JSONDecoder().decode([Material].self, from: data)
    
    return materials.first // Or show user multiple options
}
```

**Material model:**
```swift
struct Material: Identifiable, Codable {
    let id: UUID
    let name: String
    let brand: String
    let pricePerUnit: Double
    let category: String
    let purchaseURL: String
}
```

### Feature 3: Price History

**Fetch price history (from backend or web scraping):**
```swift
struct PricePoint {
    let date: Date
    let price: Double
}

func fetchPriceHistory(for materialId: String) async -> [PricePoint] {
    // Query backend API or scrape Home Depot/Lowe's
    // Return last 6 months of prices
    return [] // Implementation depends on backend
}
```

**Display with Swift Charts:**
```swift
import Charts

struct PriceHistoryView: View {
    let prices: [PricePoint]
    
    var body: some View {
        Chart(prices) { point in
            LineMark(
                x: .value("Date", point.date),
                y: .value("Price", point.price)
            )
        }
        .frame(height: 200)
    }
}
```

### Feature 4: Social Sharing

**Generate shareable card:**
```swift
func generateShareCard(items: [ReceiptItem]) -> UIImage {
    // Render a SwiftUI view to image
    let cardView = ShareCardView(items: items)
    return cardView.renderAsImage()
}
```

**System share sheet:**
```swift
struct ReceiptDetailView: View {
    @State private var showShareSheet = false
    
    var body: some View {
        Button("Share with Friends") {
            showShareSheet = true
        }
        .sheet(isPresented: $showShareSheet) {
            ActivityView(activityItems: [generateShareCard(items)])
        }
    }
}
```

**Deep link to renovation app:**
```
yourapp://materials?source=receipt&items=...
```

## Integration with Renovation App

### Shared Data
```
Renovation App (FastAPI backend)
    ↓ materials.json (shared)
Receipt Scan App (iOS)
    ↓ Scanned receipts
Budget Comparison
    ↓ "You saved $500 vs budget!"
```

### API Endpoints Needed
```python
# Add to renovation app backend
@app.get("/api/v1/materials/query")
async def query_material(name: str):
    """Query materials DB by name (for receipt app matching)"""
    matched = [m for m in materials_db if name.lower() in m['name'].lower()]
    return {"materials": matched}

@app.post("/api/v1/share-receipt")
async def share_receipt(receipt: Receipt):
    """Generate shareable link for receipt"""
    share_id = str(uuid.uuid4())
    # Save to Redis/DB
    return {"share_url": f"https://yourapp.com/share/{share_id}"}
```

## Workflow: Building the App

### Step 1: Setup iOS Project
```bash
cd ~/projects/receipt-scan-app
mkdir -p ios
# Create Xcode project or start with SwiftUI files
```

### Step 2: Create SwiftUI Files
Use the ios-agent tmux session:
```bash
tmux send-keys -t ios-agent "cat > ScannerView.swift << 'EOF' ..." Enter
```

### Step 3: Integrate Vision Kit
- Add `ScannerView.swift` (camera + OCR)
- Test with real receipts
- Parse items, prices, quantities

### Step 4: Match Materials
- Query renovation app backend
- Auto-match scanned items
- Let user confirm/correct matches

### Step 5: Add Price History
- Fetch/scrape price history
- Display with Swift Charts
- Show "lowest price" alerts

### Step 6: Social Features
- Generate shareable cards
- Implement system share sheet
- Create deep links

## iOS SwiftUI Engineer Role

Create `ios/CLAUDE.md` with context:
```markdown
# iOS SwiftUI Engineer
- **Tech**: SwiftUI + Vision Kit + Core Data
- **Role**: Build receipt scanning app
- **Key**: Free OCR, local processing, privacy-first
- **Integration**: Match to renovation app's materials DB
```

Activate with tmux:
```bash
tmux new-session -d -s ios-agent
tmux send-keys -t ios-agent "cd ~/projects/receipt-scan-app/ios && cat CLAUDE.md" Enter
```

## Pitfalls

1. **Chinese OCR weaker**: Vision Kit ~85% for Chinese (vs 95% English). Consider Baidu OCR SDK as backup for CN market.

2. **Receipt parsing brittle**: Different stores have different formats. Use ML model (Core ML) for robust parsing.

3. **Fake purchase URLs**: Always use real URLs (Home Depot.com, 淘宝), never example.com.

4. **Budget tracking inaccurate**: Users may not scan all receipts. Show "X% of budget tracked" warning.

5. **Share card too large**: Keep image under 2MB for messaging apps.

## Business Model

| Source | Revenue | Notes |
|--------|---------|-------|
| **Affiliate commissions** | 3-8% from Home Depot, 淘宝 | $500-2000/month at scale |
| **Premium subscription** | $4.99/month | Price history + advanced analytics |
| **Enterprise** | $49/month per account | For renovation companies |
| **Data monetization** | Sell anonymized data | $500-3000/month |

**Monthly revenue estimate (mature): $4300-22000** 🎉

## References

- [ScannerView.swift](references/ScannerView.swift) - Complete camera + Vision OCR view
- [ReceiptModels.swift](references/ReceiptModels.swift) - Data models for receipts
- [vision-ocr-guide.md](references/vision-ocr-guide.md) - Vision Kit best practices
- [price-history-charts.swift](references/price-history-charts.swift) - Swift Charts examples
