|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/base64" |
| 7 | + "fmt" |
| 8 | + "image/png" |
| 9 | + |
| 10 | + "github.com/boombuler/barcode" |
| 11 | + "github.com/boombuler/barcode/code128" |
| 12 | + "github.com/boombuler/barcode/code39" |
| 13 | + "github.com/boombuler/barcode/ean" |
| 14 | + "github.com/skip2/go-qrcode" |
| 15 | +) |
| 16 | + |
| 17 | +type BarcodeService struct { |
| 18 | + ctx context.Context |
| 19 | +} |
| 20 | + |
| 21 | +func NewBarcodeService() *BarcodeService { |
| 22 | + return &BarcodeService{} |
| 23 | +} |
| 24 | + |
| 25 | +func (s *BarcodeService) startup(ctx context.Context) { |
| 26 | + s.ctx = ctx |
| 27 | +} |
| 28 | + |
| 29 | +// GenerateBarcodeRequest represents the request to generate a barcode |
| 30 | +type GenerateBarcodeRequest struct { |
| 31 | + Content string `json:"content"` |
| 32 | + Standard string `json:"standard"` // QR, EAN-13, EAN-8, Code128, Code39 |
| 33 | + Size int `json:"size"` |
| 34 | + Level string `json:"level"` // For QR: L, M, Q, H |
| 35 | + Format string `json:"format"` // png, base64 |
| 36 | +} |
| 37 | + |
| 38 | +// GenerateBarcodeResponse represents the response from barcode generation |
| 39 | +type GenerateBarcodeResponse struct { |
| 40 | + DataURL string `json:"dataUrl"` |
| 41 | + Error string `json:"error"` |
| 42 | +} |
| 43 | + |
| 44 | +// GenerateBarcode generates a barcode based on the selected standard |
| 45 | +func (s *BarcodeService) GenerateBarcode(req GenerateBarcodeRequest) GenerateBarcodeResponse { |
| 46 | + if req.Content == "" { |
| 47 | + return GenerateBarcodeResponse{Error: "Content cannot be empty"} |
| 48 | + } |
| 49 | + |
| 50 | + // Set defaults |
| 51 | + size := req.Size |
| 52 | + if size < 64 { |
| 53 | + size = 256 |
| 54 | + } |
| 55 | + if size > 1024 { |
| 56 | + size = 1024 |
| 57 | + } |
| 58 | + |
| 59 | + standard := req.Standard |
| 60 | + if standard == "" { |
| 61 | + standard = "QR" |
| 62 | + } |
| 63 | + |
| 64 | + var img barcode.Barcode |
| 65 | + var err error |
| 66 | + |
| 67 | + switch standard { |
| 68 | + case "QR": |
| 69 | + return s.generateQR(req) |
| 70 | + case "EAN-13": |
| 71 | + // EAN-13 requires 12 or 13 digits |
| 72 | + img, err = ean.Encode(req.Content) |
| 73 | + case "EAN-8": |
| 74 | + // EAN-8 requires 7 or 8 digits |
| 75 | + img, err = ean.Encode(req.Content) |
| 76 | + case "Code128": |
| 77 | + img, err = code128.Encode(req.Content) |
| 78 | + case "Code39": |
| 79 | + img, err = code39.Encode(req.Content, true, true) |
| 80 | + default: |
| 81 | + return GenerateBarcodeResponse{Error: fmt.Sprintf("Unsupported barcode standard: %s", standard)} |
| 82 | + } |
| 83 | + |
| 84 | + if err != nil { |
| 85 | + return GenerateBarcodeResponse{Error: fmt.Sprintf("Failed to encode %s: %v", standard, err)} |
| 86 | + } |
| 87 | + |
| 88 | + // Scale the barcode to the requested size |
| 89 | + // For 1D barcodes, we maintain aspect ratio |
| 90 | + if standard != "QR" { |
| 91 | + bounds := img.Bounds() |
| 92 | + width := bounds.Dx() |
| 93 | + height := bounds.Dy() |
| 94 | + |
| 95 | + // Scale width to size, maintain aspect ratio for height |
| 96 | + scaleFactor := float64(size) / float64(width) |
| 97 | + newHeight := int(float64(height) * scaleFactor) |
| 98 | + |
| 99 | + // Ensure minimum height for visibility |
| 100 | + if newHeight < 100 { |
| 101 | + newHeight = 100 |
| 102 | + } |
| 103 | + |
| 104 | + img, err = barcode.Scale(img, size, newHeight) |
| 105 | + if err != nil { |
| 106 | + return GenerateBarcodeResponse{Error: fmt.Sprintf("Failed to scale barcode: %v", err)} |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + // Encode to PNG |
| 111 | + var buf bytes.Buffer |
| 112 | + err = png.Encode(&buf, img) |
| 113 | + if err != nil { |
| 114 | + return GenerateBarcodeResponse{Error: fmt.Sprintf("Failed to encode PNG: %v", err)} |
| 115 | + } |
| 116 | + |
| 117 | + // Convert to base64 data URL |
| 118 | + base64Data := base64.StdEncoding.EncodeToString(buf.Bytes()) |
| 119 | + dataURL := fmt.Sprintf("data:image/png;base64,%s", base64Data) |
| 120 | + |
| 121 | + return GenerateBarcodeResponse{DataURL: dataURL} |
| 122 | +} |
| 123 | + |
| 124 | +// generateQR generates a QR code using the skip2/go-qrcode library |
| 125 | +func (s *BarcodeService) generateQR(req GenerateBarcodeRequest) GenerateBarcodeResponse { |
| 126 | + // Parse error correction level |
| 127 | + level := qrcode.Medium |
| 128 | + switch req.Level { |
| 129 | + case "L": |
| 130 | + level = qrcode.Low |
| 131 | + case "M": |
| 132 | + level = qrcode.Medium |
| 133 | + case "Q": |
| 134 | + level = qrcode.High |
| 135 | + case "H": |
| 136 | + level = qrcode.Highest |
| 137 | + } |
| 138 | + |
| 139 | + // Generate QR code |
| 140 | + q, err := qrcode.New(req.Content, level) |
| 141 | + if err != nil { |
| 142 | + return GenerateBarcodeResponse{Error: fmt.Sprintf("Failed to create QR code: %v", err)} |
| 143 | + } |
| 144 | + |
| 145 | + // Generate PNG |
| 146 | + png, err := q.PNG(req.Size) |
| 147 | + if err != nil { |
| 148 | + return GenerateBarcodeResponse{Error: fmt.Sprintf("Failed to generate PNG: %v", err)} |
| 149 | + } |
| 150 | + |
| 151 | + // Convert to base64 data URL |
| 152 | + base64Data := base64.StdEncoding.EncodeToString(png) |
| 153 | + dataURL := fmt.Sprintf("data:image/png;base64,%s", base64Data) |
| 154 | + |
| 155 | + return GenerateBarcodeResponse{DataURL: dataURL} |
| 156 | +} |
| 157 | + |
| 158 | +// GetBarcodeStandards returns available barcode standards |
| 159 | +func (s *BarcodeService) GetBarcodeStandards() []map[string]string { |
| 160 | + return []map[string]string{ |
| 161 | + {"value": "QR", "label": "QR Code (2D)"}, |
| 162 | + {"value": "EAN-13", "label": "EAN-13 (Retail - 13 digits)"}, |
| 163 | + {"value": "EAN-8", "label": "EAN-8 (Small Retail - 8 digits)"}, |
| 164 | + {"value": "Code128", "label": "Code 128 (High Density)"}, |
| 165 | + {"value": "Code39", "label": "Code 39 (Alphanumeric)"}, |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +// GetQRErrorLevels returns available error correction levels for QR codes |
| 170 | +func (s *BarcodeService) GetQRErrorLevels() []map[string]string { |
| 171 | + return []map[string]string{ |
| 172 | + {"value": "L", "label": "Low (~7%)"}, |
| 173 | + {"value": "M", "label": "Medium (~15%)"}, |
| 174 | + {"value": "Q", "label": "Quartile (~25%)"}, |
| 175 | + {"value": "H", "label": "High (~30%)"}, |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 179 | +// GetBarcodeSizes returns available barcode sizes |
| 180 | +func (s *BarcodeService) GetBarcodeSizes() []map[string]interface{} { |
| 181 | + return []map[string]interface{}{ |
| 182 | + {"value": 128, "label": "Small (128px)"}, |
| 183 | + {"value": 256, "label": "Medium (256px)"}, |
| 184 | + {"value": 512, "label": "Large (512px)"}, |
| 185 | + {"value": 1024, "label": "Extra Large (1024px)"}, |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +// calculateEANChecksum calculates the EAN checksum digit |
| 190 | +func calculateEANChecksum(code string) int { |
| 191 | + sum := 0 |
| 192 | + for i, c := range code { |
| 193 | + digit := int(c - '0') |
| 194 | + if i%2 == 0 { |
| 195 | + sum += digit * 1 |
| 196 | + } else { |
| 197 | + sum += digit * 3 |
| 198 | + } |
| 199 | + } |
| 200 | + checksum := (10 - (sum % 10)) % 10 |
| 201 | + return checksum |
| 202 | +} |
| 203 | + |
| 204 | +// ValidateContent validates content for specific barcode standards |
| 205 | +func (s *BarcodeService) ValidateContent(content string, standard string) map[string]interface{} { |
| 206 | + result := map[string]interface{}{ |
| 207 | + "valid": true, |
| 208 | + "message": "", |
| 209 | + } |
| 210 | + |
| 211 | + switch standard { |
| 212 | + case "EAN-13": |
| 213 | + if len(content) != 12 && len(content) != 13 { |
| 214 | + result["valid"] = false |
| 215 | + result["message"] = "EAN-13 requires 12 or 13 digits" |
| 216 | + } else { |
| 217 | + // Check all digits |
| 218 | + allDigits := true |
| 219 | + for _, c := range content { |
| 220 | + if c < '0' || c > '9' { |
| 221 | + allDigits = false |
| 222 | + break |
| 223 | + } |
| 224 | + } |
| 225 | + if !allDigits { |
| 226 | + result["valid"] = false |
| 227 | + result["message"] = "EAN-13 can only contain digits" |
| 228 | + } else if len(content) == 13 { |
| 229 | + // Validate checksum for 13 digits |
| 230 | + providedChecksum := int(content[12] - '0') |
| 231 | + calculatedChecksum := calculateEANChecksum(content[:12]) |
| 232 | + if providedChecksum != calculatedChecksum { |
| 233 | + result["valid"] = false |
| 234 | + result["message"] = fmt.Sprintf("Invalid checksum. Correct EAN-13: %s%d", content[:12], calculatedChecksum) |
| 235 | + } |
| 236 | + } |
| 237 | + } |
| 238 | + case "EAN-8": |
| 239 | + if len(content) != 7 && len(content) != 8 { |
| 240 | + result["valid"] = false |
| 241 | + result["message"] = "EAN-8 requires 7 or 8 digits" |
| 242 | + } else { |
| 243 | + // Check all digits |
| 244 | + allDigits := true |
| 245 | + for _, c := range content { |
| 246 | + if c < '0' || c > '9' { |
| 247 | + allDigits = false |
| 248 | + break |
| 249 | + } |
| 250 | + } |
| 251 | + if !allDigits { |
| 252 | + result["valid"] = false |
| 253 | + result["message"] = "EAN-8 can only contain digits" |
| 254 | + } else if len(content) == 8 { |
| 255 | + // Validate checksum for 8 digits |
| 256 | + providedChecksum := int(content[7] - '0') |
| 257 | + calculatedChecksum := calculateEANChecksum(content[:7]) |
| 258 | + if providedChecksum != calculatedChecksum { |
| 259 | + result["valid"] = false |
| 260 | + result["message"] = fmt.Sprintf("Invalid checksum. Correct EAN-8: %s%d", content[:7], calculatedChecksum) |
| 261 | + } |
| 262 | + } |
| 263 | + } |
| 264 | + case "Code39": |
| 265 | + // Code 39 supports: 0-9, A-Z, and special characters: - . $ / + % space |
| 266 | + validChars := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%" |
| 267 | + for _, c := range content { |
| 268 | + found := false |
| 269 | + for _, valid := range validChars { |
| 270 | + if c == valid { |
| 271 | + found = true |
| 272 | + break |
| 273 | + } |
| 274 | + } |
| 275 | + if !found { |
| 276 | + result["valid"] = false |
| 277 | + result["message"] = "Code 39 only supports: 0-9, A-Z, and - . $ / + % space" |
| 278 | + break |
| 279 | + } |
| 280 | + } |
| 281 | + } |
| 282 | + |
| 283 | + return result |
| 284 | +} |
0 commit comments