mirror of
https://github.com/serty2005/rmser.git
synced 2026-02-05 03:12:34 -06:00
58 lines
1.5 KiB
Go
58 lines
1.5 KiB
Go
package ocr
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
|
|
"rmser/internal/domain/ocr"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type pgRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewRepository(db *gorm.DB) ocr.Repository {
|
|
return &pgRepository{db: db}
|
|
}
|
|
|
|
func (r *pgRepository) SaveMatch(rawName string, productID uuid.UUID) error {
|
|
normalized := strings.ToLower(strings.TrimSpace(rawName))
|
|
match := ocr.ProductMatch{
|
|
RawName: normalized,
|
|
ProductID: productID,
|
|
}
|
|
|
|
// Upsert: если такая строка уже была, обновляем ссылку на товар
|
|
return r.db.Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "raw_name"}},
|
|
DoUpdates: clause.AssignmentColumns([]string{"product_id", "updated_at"}),
|
|
}).Create(&match).Error
|
|
}
|
|
|
|
func (r *pgRepository) FindMatch(rawName string) (*uuid.UUID, error) {
|
|
normalized := strings.ToLower(strings.TrimSpace(rawName))
|
|
var match ocr.ProductMatch
|
|
|
|
err := r.db.Where("raw_name = ?", normalized).First(&match).Error
|
|
if err != nil {
|
|
if err == gorm.ErrRecordNotFound {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
return &match.ProductID, nil
|
|
}
|
|
|
|
func (r *pgRepository) GetAllMatches() ([]ocr.ProductMatch, error) {
|
|
var matches []ocr.ProductMatch
|
|
// Preload("Product") загружает связанную сущность товара,
|
|
// чтобы мы видели не только ID, но и название товара из каталога.
|
|
err := r.db.Preload("Product").Order("updated_at DESC").Find(&matches).Error
|
|
return matches, err
|
|
}
|