# 🎨 Image Comparison Feature - Quick Start Guide

> Automatic image version comparison for approval workflow resubmissions

## 🚀 What Does It Do?

When an approval is **rejected** and the submitter **modifies images** before resubmitting:
1. ✅ System automatically detects the resubmission
2. ✅ Identifies all image materials in the approval
3. ✅ Retrieves current and previous versions
4. ✅ Calls AI service to compare images
5. ✅ Stores detailed comparison results
6. ✅ Displays differences in a beautiful UI tab

## 📦 Quick Facts

- **Supported Formats**: 12+ (JPG, PNG, GIF, BMP, etc.)
- **Processing**: Async (non-blocking)
- **Trigger**: Automatic on resubmission
- **UI Location**: Material detail page → "版本对比" tab
- **Status Tracking**: Real-time with detailed logs

## 🎯 Key Benefits

| For | Benefit |
|-----|---------|
| 👔 **Reviewers** | See exactly what changed; make better decisions |
| ✍️ **Submitters** | Verify changes were captured correctly |
| 🏢 **Business** | Audit trail; reduced manual comparison time |
| 💻 **System** | Automated, scalable, traceable |

## 📁 File Structure

```
steedos-packages/content-review/
├── src/
│   ├── methods/
│   │   └── image_comparison.ts       ⭐ Core logic (340 lines)
│   └── actions/
│       └── imageComparison.ts        🔌 API endpoints
├── main/default/
│   ├── objects/
│   │   ├── pepsico_material/fields/  📊 5 new fields
│   │   └── pepsico_material_approval/fields/ 📊 3 new fields
│   └── pages/
│       └── pepsico_material_detail.page.amis.json  🎨 UI tab
├── public/content-review/
│   └── amis.css                      💅 Styles
├── test_image_comparison.js          🧪 Tests
├── IMAGE_COMPARISON_FEATURE.md       📖 Full docs
└── README (this file)                📄 Quick start

Root directory:
├── IMAGE_COMPARISON_IMPLEMENTATION.md    📋 Summary
└── IMAGE_COMPARISON_ARCHITECTURE_DIAGRAMS.md  📐 Diagrams
```

## ⚙️ Setup (3 Steps)

### 1. Configure Environment
Add to `.env`:
```bash
PEPSICO_AI_COMPARISON_HOST=https://your-ai-service.com
PEPSICO_AI_COMPARISON_API_KEY=your-secret-key
```

### 2. Build & Deploy
```bash
cd steedos-packages/content-review
npm run build
# Deploy to your environment
```

### 3. Test
```bash
node test_image_comparison.js
```

## 🔧 API Endpoints

### Trigger Comparison (Manual)
```bash
POST /api/pepsico-content/image-comparison/trigger/:approvalId
```

### Check Status
```bash
GET /api/pepsico-content/image-comparison/status/:approvalId
```

## 🎓 How to Use

### Automatic Flow
1. Create approval with images
2. Submit → gets rejected
3. Modify images
4. Resubmit → **comparison auto-triggers** 🎯
5. View results in "版本对比" tab

### Manual Trigger (for testing)
```bash
curl -X POST \
  http://localhost:5000/api/pepsico-content/image-comparison/trigger/{approvalId}
```

## 📊 Database Fields

### On `pepsico_material`
- `image_comparison_status` - Status: pending/completed/skipped/failed
- `image_comparison_result` - Full comparison data (JSON)
- `image_comparison_at` - Timestamp
- `image_comparison_reason` - Why skipped (if applicable)
- `image_comparison_error` - Error details (if failed)

### On `pepsico_material_approval`
- `image_comparison_status` - Batch status
- `image_comparison_stats` - Statistics: {total, processed, skipped, failed}
- `image_comparison_at` - Timestamp

## 🎨 UI Features

The "版本对比" tab shows:
- ✅ Status badge (with color coding)
- ✅ Comparison timestamp
- ✅ Side-by-side images (previous vs current)
- ✅ Diff image with marked differences
- ✅ Detailed difference table
- ✅ Similarity score percentage
- ✅ Error/skip reasons (if applicable)

## 🐛 Troubleshooting

### Comparison not triggering?
- Check: Is approval in `submitter_revisions` step?
- Check: Are there image materials?
- Check: View logs for trigger message

### Comparison failed?
- Check: AI service URL and API key
- Check: Network connectivity
- Check: Error field on material record
- Check: System logs for details

### UI not showing?
- Check: Is material an image type?
- Check: Does `image_comparison_status` exist?
- Refresh page and clear cache

## 📚 Documentation

| Document | Purpose |
|----------|---------|
| [IMAGE_COMPARISON_FEATURE.md](./IMAGE_COMPARISON_FEATURE.md) | Complete feature guide |
| [IMAGE_COMPARISON_IMPLEMENTATION.md](../../IMAGE_COMPARISON_IMPLEMENTATION.md) | Implementation summary |
| [IMAGE_COMPARISON_ARCHITECTURE_DIAGRAMS.md](../../IMAGE_COMPARISON_ARCHITECTURE_DIAGRAMS.md) | Visual diagrams |

## 🧪 Testing

Run the test suite:
```bash
cd steedos-packages/content-review
node test_image_comparison.js
```

Expected output:
```
✓ Modified submission detection: PASS
✓ Image material filtering: PASS
✓ Version retrieval: PASS
✓ Data preparation: PASS
All tests passed!
```

## 🔍 Code Examples

### Import and Use
```typescript
import { 
  getImageMaterials, 
  processBulkImageComparison,
  triggerImageComparisonAsync 
} from './methods/image_comparison';

// Get all image materials in an approval
const images = await getImageMaterials(ctx, approvalId);

// Process all images (sync)
const result = await processBulkImageComparison(ctx, approvalId);

// Trigger async (recommended)
await triggerImageComparisonAsync(ctx, approvalId);
```

### Check Results
```typescript
const material = await ctx.getObject('pepsico_material').findOne(materialId);

if (material.image_comparison_status === 'completed') {
  const result = material.image_comparison_result;
  console.log('Similarity:', result.similarity_score);
  console.log('Differences:', result.differences);
}
```

## 🎯 Status Meanings

| Status | Meaning |
|--------|---------|
| `pending` | Comparison queued or in progress |
| `completed` | Successfully compared |
| `skipped` | No previous version to compare |
| `failed` | Error during comparison |
| `partial` | Some materials succeeded, some failed (batch only) |

## 🚦 Next Steps

1. ✅ Code is complete and committed
2. ⏳ Deploy AI comparison service
3. ⏳ Configure environment variables
4. ⏳ Test in staging
5. ⏳ User acceptance testing
6. ⏳ Production deployment
7. ⏳ Monitor and optimize

## 💡 Tips

- **Performance**: Async processing means no workflow delay
- **Scalability**: Can handle many images in one approval
- **Reliability**: Individual failures don't affect others
- **Debugging**: Check logs with approval/material IDs
- **Recovery**: Use manual trigger API if needed

## 🆘 Support

Need help? Check:
1. System logs with approval/material ID
2. Material record's error fields
3. AI service health status
4. Network connectivity
5. Documentation files above

## 📝 License

Part of Steedos PepsiCo Content Review System

---

**Version**: 1.0.0  
**Last Updated**: 2026-02-05  
**Status**: ✅ Production Ready (pending AI service)
