code refactor

This commit is contained in:
Daniel Goc
2026-03-17 10:55:17 +01:00
parent 0da596826e
commit a0dcb56fda
8 changed files with 187 additions and 177 deletions

View File

@@ -27,9 +27,10 @@ var LangSrv *LangService
func (s *LangService) GetActive(c fiber.Ctx) response.Response[[]view.Language] {
res, err := s.repo.GetActive()
if err != nil {
return response.Make[[]view.Language](c, fiber.StatusBadRequest, nil, nil, i18n.T_(c, response.Message_NOK))
c.Status(fiber.StatusBadRequest)
return response.Make[[]view.Language](nil, 0, i18n.T_(c, response.Message_NOK))
}
return response.Make(c, fiber.StatusOK, nullable.GetNil(res), nullable.GetNil(len(res)), i18n.T_(c, response.Message_OK))
return response.Make(nullable.GetNil(res), 0, i18n.T_(c, response.Message_OK))
}
// LoadTranslations loads all translations from the database into the cache
@@ -54,25 +55,27 @@ func (s *LangService) ReloadTranslations() error {
func (s *LangService) GetTranslations(c fiber.Ctx, langID uint, scope string, components []string) response.Response[*i18n.TranslationResponse] {
translations, err := i18n.TransStore.GetTranslations(langID, scope, components)
if err != nil {
return response.Make[*i18n.TranslationResponse](c, fiber.StatusBadRequest, nil, nil, i18n.T_(c, Message_TranslationsNOK))
c.Status(fiber.StatusBadRequest)
return response.Make[*i18n.TranslationResponse](nil, 0, i18n.T_(c, Message_TranslationsNOK))
}
return response.Make(c, fiber.StatusOK, nullable.GetNil(translations), nil, i18n.T_(c, Message_TranslationsOK))
return response.Make(nullable.GetNil(translations), 0, i18n.T_(c, Message_TranslationsOK))
}
// GetAllTranslations returns all translations from the cache
func (s *LangService) GetAllTranslationsResponse(c fiber.Ctx) response.Response[*i18n.TranslationResponse] {
translations := i18n.TransStore.GetAllTranslations()
return response.Make(c, fiber.StatusOK, nullable.GetNil(translations), nil, i18n.T_(c, Message_TranslationsOK))
return response.Make(nullable.GetNil(translations), 0, i18n.T_(c, Message_TranslationsOK))
}
// ReloadTranslationsResponse returns response after reloading translations
func (s *LangService) ReloadTranslationsResponse(c fiber.Ctx) response.Response[map[string]string] {
err := s.ReloadTranslations()
if err != nil {
return response.Make[map[string]string](c, fiber.StatusInternalServerError, nil, nil, i18n.T_(c, Message_LangsNotLoaded))
c.Status(fiber.StatusInternalServerError)
return response.Make[map[string]string](nil, 0, i18n.T_(c, Message_LangsNotLoaded))
}
result := map[string]string{"status": "success"}
return response.Make(c, fiber.StatusOK, nullable.GetNil(result), nil, i18n.T_(c, Message_LangsLoaded))
return response.Make(nullable.GetNil(result), 0, i18n.T_(c, Message_LangsLoaded))
}
// GetDefaultLanguage returns the default language

View File

@@ -12,32 +12,26 @@ import (
"strings"
"time"
"cloud.google.com/go/auth/credentials"
translate "cloud.google.com/go/translate/apiv3"
"cloud.google.com/go/translate/apiv3/translatepb"
"git.ma-al.com/goc_daniel/b2b/app/config"
"git.ma-al.com/goc_daniel/b2b/app/db"
"git.ma-al.com/goc_daniel/b2b/app/model"
"git.ma-al.com/goc_daniel/b2b/app/service/langsService"
"git.ma-al.com/goc_daniel/b2b/app/utils/responseErrors"
ProductDescriptionRepo "git.ma-al.com/goc_daniel/b2b/repository/productDescriptionRepo"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
googleopt "google.golang.org/api/option"
"gorm.io/gorm"
// [START translate_v3_import_client_library]
"cloud.google.com/go/auth/credentials"
translate "cloud.google.com/go/translate/apiv3"
"cloud.google.com/go/translate/apiv3/translatepb"
// [END translate_v3_import_client_library]
)
type ProductDescriptionService struct {
db *gorm.DB
ctx context.Context
googleCli translate.TranslationClient
client openai.Client
// projectID is the Google Cloud project ID used as the "parent" in API calls,
// e.g. "projects/my-project-123/locations/global"
projectID string
productDescriptionRepo ProductDescriptionRepo.ProductDescriptionRepo
ctx context.Context
googleCli translate.TranslationClient
projectID string
openAIClient openai.Client
}
// New creates a ProductDescriptionService and authenticates against the
@@ -76,31 +70,19 @@ func New() *ProductDescriptionService {
log.Fatalf("productDescriptionService: cannot create Translation client: %v", err)
}
client := openai.NewClient(option.WithAPIKey("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"),
openAIClient := openai.NewClient(option.WithAPIKey("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"),
option.WithHTTPClient(&http.Client{Timeout: 300 * time.Second})) // five minutes timeout
return &ProductDescriptionService{
db: db.Get(),
ctx: ctx,
client: client,
googleCli: *googleCli,
projectID: cfg.GoogleTranslate.ProjectID,
ctx: ctx,
openAIClient: openAIClient,
googleCli: *googleCli,
projectID: cfg.GoogleTranslate.ProjectID,
}
}
// We assume that any user has access to all product descriptions
func (s *ProductDescriptionService) GetProductDescription(userID uint, productID uint, productShopID uint, productLangID uint) (*model.ProductDescription, error) {
var ProductDescription model.ProductDescription
err := s.db.
Table("ps_product_lang").
Where("id_product = ? AND id_shop = ? AND id_lang = ?", productID, productShopID, productLangID).
First(&ProductDescription).Error
if err != nil {
return nil, fmt.Errorf("database error: %w", err)
}
return &ProductDescription, nil
return s.productDescriptionRepo.GetProductDescription(productID, productShopID, productLangID)
}
// Updates relevant fields with the "updates" map
@@ -123,37 +105,12 @@ func (s *ProductDescriptionService) SaveProductDescription(userID uint, productI
}
}
record := model.ProductDescription{
ProductID: productID,
ShopID: productShopID,
LangID: productLangID,
}
err := s.db.
Table("ps_product_lang").
Where("id_product = ? AND id_shop = ? AND id_lang = ?", productID, productShopID, productLangID).
FirstOrCreate(&record).Error
err := s.productDescriptionRepo.CreateIfDoesNotExist(productID, productShopID, productLangID)
if err != nil {
return fmt.Errorf("database error: %w", err)
return err
}
if len(updates) == 0 {
return nil
}
updatesIface := make(map[string]interface{}, len(updates))
for k, v := range updates {
updatesIface[k] = v
}
err = s.db.
Table("ps_product_lang").
Where("id_product = ? AND id_shop = ? AND id_lang = ?", productID, productShopID, productLangID).
Updates(updatesIface).Error
if err != nil {
return fmt.Errorf("database error: %w", err)
}
return nil
return s.productDescriptionRepo.UpdateFields(productID, productShopID, productLangID, updates)
}
// TranslateProductDescription fetches the product description for productFromLangID,
@@ -163,16 +120,12 @@ func (s *ProductDescriptionService) SaveProductDescription(userID uint, productI
// The Google Cloud project must have the Cloud Translation API enabled and the
// service account must hold the "Cloud Translation API User" role.
func (s *ProductDescriptionService) TranslateProductDescription(userID uint, productID uint, productShopID uint, productFromLangID uint, productToLangID uint, aiModel string) (*model.ProductDescription, error) {
var ProductDescription model.ProductDescription
err := s.db.
Table("ps_product_lang").
Where("id_product = ? AND id_shop = ? AND id_lang = ?", productID, productShopID, productFromLangID).
First(&ProductDescription).Error
productDescription, err := s.productDescriptionRepo.GetProductDescription(productID, productShopID, productFromLangID)
if err != nil {
return nil, fmt.Errorf("database error: %w", err)
return nil, err
}
ProductDescription.LangID = productToLangID
productDescription.LangID = productToLangID
// we translate all changeable fields, and we keep the exact same HTML structure in relevant fields.
lang, err := langsService.LangSrv.GetLanguageById(productToLangID)
@@ -180,14 +133,14 @@ func (s *ProductDescriptionService) TranslateProductDescription(userID uint, pro
return nil, err
}
fields := []*string{&ProductDescription.Description,
&ProductDescription.DescriptionShort,
&ProductDescription.MetaDescription,
&ProductDescription.MetaTitle,
&ProductDescription.Name,
&ProductDescription.AvailableNow,
&ProductDescription.AvailableLater,
&ProductDescription.Usage,
fields := []*string{&productDescription.Description,
&productDescription.DescriptionShort,
&productDescription.MetaDescription,
&productDescription.MetaTitle,
&productDescription.Name,
&productDescription.AvailableNow,
&productDescription.AvailableLater,
&productDescription.Usage,
}
keys := []string{"translation_of_product_description",
"translation_of_product_short_description",
@@ -213,24 +166,23 @@ func (s *ProductDescriptionService) TranslateProductDescription(userID uint, pro
}
if aiModel == "OpenAI" {
openai_response, _ := s.client.Responses.New(context.Background(), responses.ResponseNewParams{
response, _ := s.openAIClient.Responses.New(context.Background(), responses.ResponseNewParams{
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(request)},
Model: openai.ChatModelGPT4_1Mini,
// Model: openai.ChatModelGPT4_1Nano,
})
if openai_response.Status != "completed" {
if response.Status != "completed" {
return nil, responseErrors.ErrAIResponseFail
}
response := openai_response.OutputText()
for i := 0; i < len(keys); i++ {
success, resolution := resolveResponse(*fields[i], response, keys[i])
success, resolution := resolveResponse(*fields[i], response.OutputText(), keys[i])
if !success {
return nil, responseErrors.ErrAIBadOutput
}
*fields[i] = resolution
fmt.Println(resolution)
// fmt.Println(resolution)
}
} else if aiModel == "Google" {
@@ -253,17 +205,17 @@ func (s *ProductDescriptionService) TranslateProductDescription(userID uint, pro
response := responseGoogle.GetTranslations()[0].GetTranslatedText()
for i := 0; i < len(keys); i++ {
success, match := GetStringInBetween(response, "<"+keys[i]+">", "</"+keys[i]+">")
success, match := getStringInBetween(response, "<"+keys[i]+">", "</"+keys[i]+">")
if !success || !isValidXHTML(match) {
return nil, responseErrors.ErrAIBadOutput
}
*fields[i] = match
fmt.Println(match)
// fmt.Println(match)
}
}
return &ProductDescription, nil
return productDescription, nil
}
func cleanForPrompt(s string) string {
@@ -284,17 +236,17 @@ func cleanForPrompt(s string) string {
switch v := token.(type) {
case xml.StartElement:
prompt += "<" + AttrName(v.Name)
prompt += "<" + attrName(v.Name)
for _, attr := range v.Attr {
if v.Name.Local == "img" && attr.Name.Local == "alt" {
prompt += fmt.Sprintf(` %s="%s"`, AttrName(attr.Name), attr.Value)
prompt += fmt.Sprintf(` %s="%s"`, attrName(attr.Name), attr.Value)
}
}
prompt += ">"
case xml.EndElement:
prompt += "</" + AttrName(v.Name) + ">"
prompt += "</" + attrName(v.Name) + ">"
case xml.CharData:
prompt += string(v)
case xml.Comment:
@@ -307,12 +259,12 @@ func cleanForPrompt(s string) string {
}
func resolveResponse(original string, response string, key string) (bool, string) {
success, match := GetStringInBetween(response, "<"+key+">", "</"+key+">")
success, match := getStringInBetween(response, "<"+key+">", "</"+key+">")
if !success || !isValidXHTML(match) {
return false, ""
}
success, resolution := RebuildFromResponse("<"+key+">"+original+"</"+key+">", "<"+key+">"+match+"</"+key+">")
success, resolution := rebuildFromResponse("<"+key+">"+original+"</"+key+">", "<"+key+">"+match+"</"+key+">")
if !success {
return false, ""
}
@@ -320,8 +272,8 @@ func resolveResponse(original string, response string, key string) (bool, string
return true, resolution[2+len(key) : len(resolution)-3-len(key)]
}
// GetStringInBetween returns empty string if no start or end string found
func GetStringInBetween(str string, start string, end string) (success bool, result string) {
// getStringInBetween returns empty string if no start or end string found
func getStringInBetween(str string, start string, end string) (success bool, result string) {
s := strings.Index(str, start)
if s == -1 {
return false, ""
@@ -358,7 +310,7 @@ func isValidXHTML(s string) bool {
// Rebuilds HTML using the original HTML as a template and the response as a source
// Assumes that both original and response have the exact same XML structure
func RebuildFromResponse(s_original string, s_response string) (bool, string) {
func rebuildFromResponse(s_original string, s_response string) (bool, string) {
r_original := strings.NewReader(s_original)
d_original := xml.NewDecoder(r_original)
@@ -397,17 +349,17 @@ func RebuildFromResponse(s_original string, s_response string) (bool, string) {
return false, ""
}
result += "<" + AttrName(v_original.Name)
result += "<" + attrName(v_original.Name)
for _, attr := range v_original.Attr {
if v_original.Name.Local != "img" || attr.Name.Local != "alt" {
result += fmt.Sprintf(` %s="%s"`, AttrName(attr.Name), attr.Value)
result += fmt.Sprintf(` %s="%s"`, attrName(attr.Name), attr.Value)
}
}
for _, attr := range v_response.Attr {
if v_response.Name.Local == "img" && attr.Name.Local == "alt" {
result += fmt.Sprintf(` %s="%s"`, AttrName(attr.Name), attr.Value)
result += fmt.Sprintf(` %s="%s"`, attrName(attr.Name), attr.Value)
}
}
result += ">"
@@ -429,7 +381,7 @@ func RebuildFromResponse(s_original string, s_response string) (bool, string) {
}
if v_original.Name.Local != "img" {
result += "</" + AttrName(v_original.Name) + ">"
result += "</" + attrName(v_original.Name) + ">"
}
case xml.CharData:
@@ -485,7 +437,7 @@ func RebuildFromResponse(s_original string, s_response string) (bool, string) {
}
}
func AttrName(name xml.Name) string {
func attrName(name xml.Name) string {
if name.Space == "" {
return name.Local
} else {