# ZXing WebAssembly Barcode Scanner Implementation - Purchase Module

## Overview
The Purchase module has been updated to use **ZXing WebAssembly** for barcode and QR code scanning, replacing the old QuaggaJS + jsQR implementation.

## Implementation Date
December 2024

## What Changed

### 1. Library Update
**Before:**
```html
<script src="https://cdn.jsdelivr.net/npm/quagga@0.12.1/dist/quagga.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
```

**After:**
```html
<script src="https://unpkg.com/@zxing/library@latest"></script>
```

### 2. Scanner Class (Purchase/js/barcode-scanner.js)
- Complete rewrite using ZXing WebAssembly
- **Removed:** QuaggaJS and jsQR implementations
- **Added:** ZXing BrowserMultiFormatReader
- **Benefit:** Single library handles all barcode/QR formats

### 3. Integration (Purchase/js/scanner-integration.js)
- No changes required
- Already uses generic BarcodeScanner class
- Compatible with ZXing implementation

## Key Features

### Unified Scanning
- **All barcode formats:** CODE-128, EAN, UPC, CODE-39, etc.
- **QR codes:** Full support built-in
- **Auto-detection:** No need to specify format
- **Higher accuracy:** WebAssembly-powered detection

### Mobile-Optimized
- **Rear camera preference:** Automatic selection
- **Camera switching:** Switch between front/rear
- **Touch-friendly UI:** Large buttons and controls
- **Responsive design:** Works on all screen sizes

### User Experience
- **Fast scanning:** Real-time detection
- **Visual feedback:** Scanning frame with animation
- **Audio feedback:** Success beep sound
- **Error handling:** Clear error messages

## How to Use

### Using Camera Button
1. Click the camera icon next to the Product Code field
2. Position barcode/QR within the frame
3. Scanner automatically detects and adds product

### Keyboard Shortcut
- Press **Ctrl+K** (or **Cmd+K** on Mac) to open scanner

### Manual Entry
- Enter code in Product Code field
- Press Enter to search

## Technical Details

### Scanner Initialization
```javascript
const scanner = new BarcodeScanner({
    onSuccess: (code, format) => {
        // Handle scanned code
    },
    onError: (error) => {
        // Handle errors
    },
    preferredCamera: 'environment' // Rear camera
});
```

### Start Scanning
```javascript
await scanner.start();
```

### Stop Scanning
```javascript
await scanner.stop();
```

## API Integration

### Product Search
When a code is scanned:
1. Check product cache first
2. Make AJAX request to `api/search-product-by-code.php`
3. Add product to cart or show selection modal
4. Cache product for faster future lookups

### Cache Management
- **Cache size:** 50 products
- **Cache expiry:** 5 minutes
- **Auto-cleanup:** Removes oldest entries

## Browser Compatibility

### Required
- **Modern browser** with WebAssembly support
- **Camera access** permission
- **HTTPS connection** (for camera access)

### Supported Browsers
- ✅ Chrome 57+ (Desktop/Mobile)
- ✅ Firefox 52+ (Desktop/Mobile)
- ✅ Safari 11+ (Desktop/Mobile)
- ✅ Edge 16+ (Desktop/Mobile)
- ✅ Opera 44+ (Desktop/Mobile)

## Files Modified

### Core Files
1. **Purchase/index.php**
   - Updated library reference to ZXing

2. **Purchase/js/barcode-scanner.js**
   - Complete rewrite with ZXing implementation
   - Removed QuaggaJS and jsQR code
   - Added ZXing methods

3. **Purchase/js/scanner-integration.js**
   - No changes (already compatible)

## Benefits Over Previous Implementation

| Feature | QuaggaJS + jsQR | ZXing WebAssembly |
|---------|-----------------|-------------------|
| Libraries | 2 separate | 1 unified |
| QR Codes | Limited support | Full support |
| Accuracy | Moderate | High |
| Speed | Slower | Faster |
| File Size | ~180KB combined | ~120KB |
| Maintenance | 2 libraries | 1 library |
| Detection | Separate loops | Unified detection |

## Troubleshooting

### Camera Permission Denied
- Browser blocks camera access
- Solution: Allow camera in browser settings

### No Camera Found
- Device has no camera
- Solution: Use manual barcode entry

### Scanner Not Working
1. Check browser console for errors
2. Verify ZXing library loaded (check Network tab)
3. Ensure HTTPS connection
4. Try different browser
5. Clear browser cache

### Product Not Found
- Barcode not in database
- Solution: Add product manually or check barcode

## Performance Considerations

### Optimization
- **Debounce time:** 500ms prevents duplicate scans
- **Cache:** Reduces API calls for repeated products
- **WebAssembly:** Near-native performance
- **Video resolution:** Optimized for speed vs quality

### Memory Management
- Scanner cleanup on stop
- Video stream release
- Cache size limit
- Automatic cache expiry

## Security

### Camera Access
- Requires user permission
- Only active during scanning
- Stream released after use

### API Calls
- Server-side validation
- No client-side price manipulation
- Secure AJAX requests

## Future Enhancements

### Possible Additions
- [ ] Batch scanning mode
- [ ] Offline product database
- [ ] Custom barcode formats
- [ ] Scan history tracking
- [ ] Export scan logs
- [ ] Multi-product scanning

## Support

### Getting Help
1. Check browser console for errors
2. Verify all files are updated
3. Test on different devices
4. Review this documentation

### Common Issues
- **Slow scanning:** Check lighting conditions
- **Can't switch camera:** Device may have only one camera
- **Blurry image:** Hold device steady
- **Won't scan:** Ensure barcode is clear and well-lit

## Testing Checklist

### Desktop Testing
- [ ] Camera permission prompt appears
- [ ] Scanner opens and shows video feed
- [ ] Barcode detection works
- [ ] QR code detection works
- [ ] Product added to cart
- [ ] Scanner closes automatically
- [ ] Keyboard shortcut (Ctrl+K) works

### Mobile Testing
- [ ] Rear camera selected by default
- [ ] Touch controls work
- [ ] Camera switch button works
- [ ] Scanner UI responsive
- [ ] Orientation changes handled
- [ ] Success feedback visible
- [ ] Product added correctly

## Related Documentation
- See `Sales/ZXING_SCANNER_README.md` for Sales implementation
- See `items/BARCODE_SCANNER_GUIDE.md` for Add Item implementation

## Conclusion
The Purchase module now uses the modern ZXing WebAssembly library for superior barcode and QR code scanning. This provides better accuracy, faster performance, and easier maintenance compared to the previous implementation.

---
*Last Updated: December 2024*
