# ZXing WebAssembly Barcode/QR Scanner Implementation

## Overview

The Sales POS system now uses **ZXing (Zebra Crossing) WebAssembly** for barcode and QR code scanning. ZXing is a powerful, industry-standard barcode scanning library that provides superior accuracy and supports a wide range of barcode formats.

## Why ZXing?

### Advantages over Previous Libraries (QuaggaJS & jsQR):

1. **Better Accuracy**: ZXing has been battle-tested across millions of devices and provides more reliable scanning
2. **Comprehensive Format Support**: Supports 1D and 2D barcodes including:
   - **1D Barcodes**: EAN-13, EAN-8, UPC-A, UPC-E, Code 39, Code 93, Code 128, ITF, Codabar
   - **2D Codes**: QR Code, Data Matrix, Aztec, PDF417, MaxiCode
3. **WebAssembly Performance**: Uses WebAssembly for native-level performance in the browser
4. **Active Development**: Well-maintained with regular updates
5. **Mobile Optimized**: Works excellently on mobile devices with both front and rear cameras
6. **Single Library**: No need for separate libraries for barcodes and QR codes

## Features

### Current Implementation

- ✅ **Camera Selection**: Automatically selects rear camera on mobile devices
- ✅ **Real-time Scanning**: Continuous scanning with immediate feedback
- ✅ **Format Detection**: Auto-detects all supported barcode/QR formats
- ✅ **Duplicate Prevention**: Debouncing to prevent scanning the same code multiple times
- ✅ **Visual Feedback**: Animated scanner frame with success indicators
- ✅ **Audio Feedback**: Beep sound on successful scan
- ✅ **Responsive UI**: Works on desktop and mobile devices
- ✅ **Camera Switching**: Toggle between front and rear cameras
- ✅ **Error Handling**: Graceful handling of camera permissions and errors

## File Structure

```
Sales/
├── js/
│   ├── barcode-scanner.js          # Main ZXing scanner class
│   └── scanner-integration.js       # Integration with POS system
├── css/
│   └── barcode-scanner.css         # Scanner UI styles
└── index.php                        # Main POS page (loads ZXing library)
```

## Usage

### Opening the Scanner

There are multiple ways to open the barcode scanner:

1. **Camera Button**: Click the camera icon button next to the product code input
2. **Keyboard Shortcut**: Press `Ctrl/Cmd + K` to open scanner
3. **Programmatically**: Call `window.startBarcodeScanner()`

### Example Code

```javascript
// Create scanner instance
const scanner = new BarcodeScanner({
    onSuccess: function(code, format) {
        console.log(`Scanned: ${code} (Format: ${format})`);
        // Add product to cart
        searchProductByCode(code);
    },
    onError: function(error) {
        console.error('Scanner error:', error);
    },
    preferredCamera: 'environment' // 'environment' for rear, 'user' for front
});

// Start scanning
scanner.start();

// Stop scanning
scanner.stop();

// Switch camera
scanner.switchCamera();
```

## Scanner UI

The scanner modal includes:

- **Video Preview**: Live camera feed with overlay frame
- **Status Indicator**: Shows scanning status and results
- **Instructions**: Helpful text guiding the user
- **Control Buttons**:
  - Switch Camera: Toggle between available cameras
  - Close: Stop scanning and close modal

## Supported Barcode Formats

### 1D Barcodes
- **EAN-13**: Standard retail product codes (13 digits)
- **EAN-8**: Compact retail codes (8 digits)
- **UPC-A**: North American retail codes (12 digits)
- **UPC-E**: Compact UPC codes (6 digits)
- **Code 39**: Alphanumeric codes (common in logistics)
- **Code 93**: Improved version of Code 39
- **Code 128**: High-density alphanumeric (very common)
- **ITF**: Interleaved 2 of 5 (shipping containers)
- **Codabar**: Used in libraries, blood banks

### 2D Codes
- **QR Code**: Most popular 2D code (URLs, text, etc.)
- **Data Matrix**: Compact 2D code (small items)
- **Aztec**: High-density 2D code (transport tickets)
- **PDF417**: Stacked barcode (ID cards, shipping)
- **MaxiCode**: Used by UPS for package sorting

## Browser Compatibility

ZXing WebAssembly works on:

- ✅ Chrome/Edge 57+ (Desktop & Mobile)
- ✅ Firefox 52+ (Desktop & Mobile)
- ✅ Safari 11+ (Desktop & Mobile)
- ✅ Opera 44+
- ✅ Samsung Internet 7.2+

## Mobile Device Support

### Camera Access
The scanner automatically:
1. Requests camera permissions
2. Selects the rear camera (environment) by default
3. Provides high-quality video stream
4. Optimizes for barcode detection

### Performance Tips
- Use good lighting for best results
- Hold device steady when scanning
- Position barcode within the frame
- Keep barcode flat and clear

## Integration with POS System

### Product Search Flow

1. User opens scanner (camera button or shortcut)
2. Scanner captures barcode/QR code
3. Code is automatically searched in the database
4. Product is added to cart if found
5. Scanner closes automatically

### Caching
The system caches recently scanned products for faster subsequent scans (5-minute cache expiry).

## Troubleshooting

### Scanner Won't Open
- Check browser permissions for camera access
- Ensure HTTPS connection (required for camera access)
- Verify ZXing library is loaded (check browser console)

### Scanner Not Detecting Codes
- Ensure good lighting conditions
- Check if barcode is clear and not damaged
- Try different angles or distances
- Verify barcode format is supported

### Camera Permission Denied
- Check browser settings for camera permissions
- On mobile, check app permissions in device settings
- Try reloading the page

## Technical Details

### Library Information
- **Library**: ZXing ("Zebra Crossing")
- **Version**: Latest (loaded via CDN)
- **CDN**: `https://unpkg.com/@zxing/library@latest`
- **Technology**: WebAssembly + JavaScript
- **License**: Apache 2.0

### Performance
- **Decode Speed**: ~10-30 FPS depending on device
- **CPU Usage**: Low (optimized WebAssembly)
- **Memory Usage**: ~20-50 MB
- **Battery Impact**: Minimal

## API Reference

### BarcodeScanner Class

#### Constructor Options
```javascript
{
    onSuccess: function(code, format) {},  // Called when code is detected
    onError: function(error) {},           // Called on errors
    preferredCamera: 'environment',        // 'environment' or 'user'
    formats: []                            // Auto-detect all if empty
}
```

#### Methods
- `start()`: Initialize and start scanner
- `stop()`: Stop scanner and cleanup
- `switchCamera()`: Toggle between available cameras
- `showSuccess(code, format)`: Display success feedback

#### Properties
- `isScanning`: Boolean indicating scanner state
- `codeReader`: ZXing BrowserMultiFormatReader instance
- `videoElement`: Video element reference
- `selectedDeviceId`: Current camera device ID

## Future Enhancements

Potential improvements:
- [ ] Flashlight toggle for low-light conditions
- [ ] Manual focus control
- [ ] Scan history
- [ ] Batch scanning mode
- [ ] Custom scan regions
- [ ] OCR text recognition
- [ ] Offline scanning capability

## Support

For issues or questions:
1. Check browser console for error messages
2. Verify camera permissions
3. Test with different barcodes
4. Check device compatibility

## Credits

- **ZXing**: Created by Sean Owen and the ZXing team
- **WebAssembly Port**: Maintained by the @zxing/library team
- **Implementation**: Custom integration for UZRS Inventory System

## Version History

### v2.0.0 (Current) - ZXing Implementation
- Migrated from QuaggaJS/jsQR to ZXing WebAssembly
- Improved scanning accuracy and speed
- Unified barcode and QR code detection
- Enhanced mobile camera support

### v1.0.0 (Previous) - QuaggaJS/jsQR
- Initial implementation with separate libraries
- Basic barcode and QR code support

---

**Last Updated**: November 9, 2025
**Author**: UZRS Inventory Development Team
