File size: 1,282 Bytes
1e69593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package productcode

import (
	"fmt"

	"mexa/api/v1/db"
)

const charset = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

func encodeBase60(n int64, length int) string {
	base := int64(len(charset))
	result := make([]byte, length)
	for i := length - 1; i >= 0; i-- {
		result[i] = charset[n%base]
		n /= base
	}
	return string(result)
}

// Generate returns a 6-char product code: T1+T2+T3+S1+S2+S3.
// T1, T2, T3 are single chars from the 60-char charset.
// S1-S3 is a 3-char base-60 sequence — 216,000 per group.
// System-generated only. mrShymo never constructs or chooses a code.
// UPSERT ensures the group row is created on first use — no seeding required.
func Generate(t1, t2, t3 string) (string, error) {
	if len(t1) != 1 || len(t2) != 1 || len(t3) != 1 {
		return "", fmt.Errorf("t1, t2, t3 must each be exactly 1 char")
	}
	group := t1 + t2 + t3
	var seq int64
	err := db.DB.QueryRow(`
		INSERT INTO product_sequences (group_key, current_val)
		VALUES ($1, 1)
		ON CONFLICT (group_key)
		DO UPDATE SET current_val = product_sequences.current_val + 1
		RETURNING current_val
	`, group).Scan(&seq)
	if err != nil {
		return "", fmt.Errorf("product_sequences upsert failed for group %s: %w", group, err)
	}
	return group + encodeBase60(seq, 3), nil
}