3 Commits

Author SHA1 Message Date
22e8556c9d fix: page Addresses 2026-03-18 16:31:29 +01:00
c79e08dbb8 Merge branch 'main' of ssh://git.ma-al.com:8822/goc_daniel/b2b into test 2026-03-18 10:02:44 +01:00
Daniel Goc
a0dcb56fda code refactor 2026-03-17 10:55:17 +01:00
16 changed files with 390 additions and 331 deletions

View File

@@ -6,6 +6,8 @@ import (
"git.ma-al.com/goc_daniel/b2b/app/config" "git.ma-al.com/goc_daniel/b2b/app/config"
"git.ma-al.com/goc_daniel/b2b/app/service/productDescriptionService" "git.ma-al.com/goc_daniel/b2b/app/service/productDescriptionService"
"git.ma-al.com/goc_daniel/b2b/app/utils/i18n" "git.ma-al.com/goc_daniel/b2b/app/utils/i18n"
"git.ma-al.com/goc_daniel/b2b/app/utils/nullable"
"git.ma-al.com/goc_daniel/b2b/app/utils/response"
"git.ma-al.com/goc_daniel/b2b/app/utils/responseErrors" "git.ma-al.com/goc_daniel/b2b/app/utils/responseErrors"
"github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3"
@@ -41,151 +43,132 @@ func ProductDescriptionHandlerRoutes(r fiber.Router) fiber.Router {
func (h *ProductDescriptionHandler) GetProductDescription(c fiber.Ctx) error { func (h *ProductDescriptionHandler) GetProductDescription(c fiber.Ctx) error {
userID, ok := c.Locals("userID").(uint) userID, ok := c.Locals("userID").(uint)
if !ok { if !ok {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody), // possibly could return a different error JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody)))
})
} }
productID_attribute := c.Query("productID") productID_attribute := c.Query("productID")
productID, err := strconv.Atoi(productID_attribute) productID, err := strconv.Atoi(productID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
productShopID_attribute := c.Query("productShopID") productShopID_attribute := c.Query("productShopID")
productShopID, err := strconv.Atoi(productShopID_attribute) productShopID, err := strconv.Atoi(productShopID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
productLangID_attribute := c.Query("productLangID") productLangID_attribute := c.Query("productLangID")
productLangID, err := strconv.Atoi(productLangID_attribute) productLangID, err := strconv.Atoi(productLangID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
response, err := h.productDescriptionService.GetProductDescription(userID, uint(productID), uint(productShopID), uint(productLangID)) description, err := h.productDescriptionService.GetProductDescription(userID, uint(productID), uint(productShopID), uint(productLangID))
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(err)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(err)).JSON(fiber.Map{
"error": responseErrors.GetErrorCode(c, err), "error": responseErrors.GetErrorCode(c, err),
}) })
} }
return c.JSON(response) return c.JSON(response.Make(description, 1, i18n.T_(c, response.Message_OK)))
} }
// SaveProductDescription saves the description for a given product ID, in given shop and language // SaveProductDescription saves the description for a given product ID, in given shop and language
func (h *ProductDescriptionHandler) SaveProductDescription(c fiber.Ctx) error { func (h *ProductDescriptionHandler) SaveProductDescription(c fiber.Ctx) error {
userID, ok := c.Locals("userID").(uint) userID, ok := c.Locals("userID").(uint)
if !ok { if !ok {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody), // possibly could return a different error JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody)))
})
} }
productID_attribute := c.Query("productID") productID_attribute := c.Query("productID")
productID, err := strconv.Atoi(productID_attribute) productID, err := strconv.Atoi(productID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
productShopID_attribute := c.Query("productShopID") productShopID_attribute := c.Query("productShopID")
productShopID, err := strconv.Atoi(productShopID_attribute) productShopID, err := strconv.Atoi(productShopID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
productLangID_attribute := c.Query("productLangID") productLangID_attribute := c.Query("productLangID")
productLangID, err := strconv.Atoi(productLangID_attribute) productLangID, err := strconv.Atoi(productLangID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
updates := make(map[string]string) updates := make(map[string]string)
if err := c.Bind().Body(&updates); err != nil { if err := c.Bind().Body(&updates); err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody)))
})
} }
err = h.productDescriptionService.SaveProductDescription(userID, uint(productID), uint(productShopID), uint(productLangID), updates) err = h.productDescriptionService.SaveProductDescription(userID, uint(productID), uint(productShopID), uint(productLangID), updates)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(err)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(err)).
"error": responseErrors.GetErrorCode(c, err), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))
})
} }
return c.JSON(fiber.Map{ return c.JSON(response.Make(nullable.GetNil(""), 0, i18n.T_(c, response.Message_OK)))
"message": i18n.T_(c, "product_description.successfully_updated_fields"),
})
} }
// GetProductDescription returns the product description for a given product ID // TranslateProductDescription returns translated product description
func (h *ProductDescriptionHandler) TranslateProductDescription(c fiber.Ctx) error { func (h *ProductDescriptionHandler) TranslateProductDescription(c fiber.Ctx) error {
userID, ok := c.Locals("userID").(uint) userID, ok := c.Locals("userID").(uint)
if !ok { if !ok {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody), // possibly could return a different error JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody)))
})
} }
productID_attribute := c.Query("productID") productID_attribute := c.Query("productID")
productID, err := strconv.Atoi(productID_attribute) productID, err := strconv.Atoi(productID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
productShopID_attribute := c.Query("productShopID") productShopID_attribute := c.Query("productShopID")
productShopID, err := strconv.Atoi(productShopID_attribute) productShopID, err := strconv.Atoi(productShopID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
productFromLangID_attribute := c.Query("productFromLangID") productFromLangID_attribute := c.Query("productFromLangID")
productFromLangID, err := strconv.Atoi(productFromLangID_attribute) productFromLangID, err := strconv.Atoi(productFromLangID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
productToLangID_attribute := c.Query("productToLangID") productToLangID_attribute := c.Query("productToLangID")
productToLangID, err := strconv.Atoi(productToLangID_attribute) productToLangID, err := strconv.Atoi(productToLangID_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
model := c.Query("model") aiModel := c.Query("model")
if model != "OpenAI" && model != "Google" { if aiModel != "OpenAI" && aiModel != "Google" {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
})
} }
response, err := h.productDescriptionService.TranslateProductDescription(userID, uint(productID), uint(productShopID), uint(productFromLangID), uint(productToLangID), model) description, err := h.productDescriptionService.TranslateProductDescription(userID, uint(productID), uint(productShopID), uint(productFromLangID), uint(productToLangID), aiModel)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(err)).JSON(fiber.Map{ return c.Status(responseErrors.GetErrorStatus(err)).
"error": responseErrors.GetErrorCode(c, err), JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))
})
} }
return c.JSON(response) return c.JSON(response.Make(description, 1, i18n.T_(c, response.Message_OK)))
} }

View File

@@ -86,6 +86,6 @@ func (h *SettingsHandler) GetSettings(cfg *config.Config) fiber.Handler {
Version: version.GetInfo(), Version: version.GetInfo(),
} }
return c.JSON(response.Make(c, fiber.StatusOK, nullable.GetNil(settings), nullable.GetNil(0), i18n.T_(c, response.Message_OK))) return c.JSON(response.Make(nullable.GetNil(settings), 0, i18n.T_(c, response.Message_OK)))
} }
} }

View File

@@ -27,9 +27,10 @@ var LangSrv *LangService
func (s *LangService) GetActive(c fiber.Ctx) response.Response[[]view.Language] { func (s *LangService) GetActive(c fiber.Ctx) response.Response[[]view.Language] {
res, err := s.repo.GetActive() res, err := s.repo.GetActive()
if err != nil { 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 // 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] { 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) translations, err := i18n.TransStore.GetTranslations(langID, scope, components)
if err != nil { 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 // GetAllTranslations returns all translations from the cache
func (s *LangService) GetAllTranslationsResponse(c fiber.Ctx) response.Response[*i18n.TranslationResponse] { func (s *LangService) GetAllTranslationsResponse(c fiber.Ctx) response.Response[*i18n.TranslationResponse] {
translations := i18n.TransStore.GetAllTranslations() 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 // ReloadTranslationsResponse returns response after reloading translations
func (s *LangService) ReloadTranslationsResponse(c fiber.Ctx) response.Response[map[string]string] { func (s *LangService) ReloadTranslationsResponse(c fiber.Ctx) response.Response[map[string]string] {
err := s.ReloadTranslations() err := s.ReloadTranslations()
if err != nil { 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"} 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 // GetDefaultLanguage returns the default language

View File

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

View File

@@ -1,15 +1,12 @@
package response package response
import "github.com/gofiber/fiber/v3"
type Response[T any] struct { type Response[T any] struct {
Message string `json:"message,omitempty"` Message string `json:"message"`
Items *T `json:"items,omitempty"` Items *T `json:"items"`
Count *int `json:"count,omitempty"` Count int `json:"count"`
} }
func Make[T any](c fiber.Ctx, status int, items *T, count *int, message string) Response[T] { func Make[T any](items *T, count int, message string) Response[T] {
c.Status(status)
return Response[T]{ return Response[T]{
Message: message, Message: message,
Items: items, Items: items,

View File

@@ -38,7 +38,7 @@ var (
ErrVerificationTokenExpired = errors.New("verification token has expired") ErrVerificationTokenExpired = errors.New("verification token has expired")
// Typed errors for product description handler // Typed errors for product description handler
ErrBadAttribute = errors.New("bad attribute") ErrBadAttribute = errors.New("bad or missing attribute value in header")
ErrBadField = errors.New("this field can not be updated") ErrBadField = errors.New("this field can not be updated")
ErrInvalidXHTML = errors.New("text is not in xhtml format") ErrInvalidXHTML = errors.New("text is not in xhtml format")
ErrAIResponseFail = errors.New("AI responded with failure") ErrAIResponseFail = errors.New("AI responded with failure")
@@ -119,9 +119,9 @@ func GetErrorCode(c fiber.Ctx, err error) string {
case errors.Is(err, ErrInvalidXHTML): case errors.Is(err, ErrInvalidXHTML):
return i18n.T_(c, "error.err_invalid_html") return i18n.T_(c, "error.err_invalid_html")
case errors.Is(err, ErrAIResponseFail): case errors.Is(err, ErrAIResponseFail):
return i18n.T_(c, "error.err_openai_response_fail") return i18n.T_(c, "error.err_ai_response_fail")
case errors.Is(err, ErrAIBadOutput): case errors.Is(err, ErrAIBadOutput):
return i18n.T_(c, "error.err_openai_bad_output") return i18n.T_(c, "error.err_ai_bad_output")
default: default:
return i18n.T_(c, "error.err_internal_server_error") return i18n.T_(c, "error.err_internal_server_error")

1
bo/components.d.ts vendored
View File

@@ -17,6 +17,7 @@ declare module 'vue' {
En_TermsAndConditionsView: typeof import('./src/components/terms/en_TermsAndConditionsView.vue')['default'] En_TermsAndConditionsView: typeof import('./src/components/terms/en_TermsAndConditionsView.vue')['default']
LangSwitch: typeof import('./src/components/inner/langSwitch.vue')['default'] LangSwitch: typeof import('./src/components/inner/langSwitch.vue')['default']
PageAddresses: typeof import('./src/components/customer/PageAddresses.vue')['default'] PageAddresses: typeof import('./src/components/customer/PageAddresses.vue')['default']
PageCart: typeof import('./src/components/customer/PageCart.vue')['default']
PageProductCardFull: typeof import('./src/components/customer/PageProductCardFull.vue')['default'] PageProductCardFull: typeof import('./src/components/customer/PageProductCardFull.vue')['default']
Pl_PrivacyPolicyView: typeof import('./src/components/terms/pl_PrivacyPolicyView.vue')['default'] Pl_PrivacyPolicyView: typeof import('./src/components/terms/pl_PrivacyPolicyView.vue')['default']
Pl_TermsAndConditionsView: typeof import('./src/components/terms/pl_TermsAndConditionsView.vue')['default'] Pl_TermsAndConditionsView: typeof import('./src/components/terms/pl_TermsAndConditionsView.vue')['default']

View File

@@ -2,10 +2,6 @@ import type { NuxtUIOptions } from '@nuxt/ui/unplugin'
export const uiOptions: NuxtUIOptions = { export const uiOptions: NuxtUIOptions = {
ui: { ui: {
colors: {
primary: 'blue',
neutral: 'zink',
},
pagination: { pagination: {
slots: { slots: {
root: '', root: '',
@@ -56,6 +52,12 @@ export const uiOptions: NuxtUIOptions = {
tr: 'border-b! border-(--border-light)! dark:border-(--border-dark)! outline-0! ring-0! text-(--black)! dark:text-white!', tr: 'border-b! border-(--border-light)! dark:border-(--border-dark)! outline-0! ring-0! text-(--black)! dark:text-white!',
} }
},
modal: {
slots: {
content: 'border! border-(--border-light)! dark:border-(--border-dark)! outline-0! ring-0! bg-(--second-light) dark:bg-(--main-dark)',
}
} }
} }
} }

View File

@@ -9,7 +9,7 @@ const authStore = useAuthStore()
<template> <template>
<header <header
class="fixed top-0 left-0 right-0 z-50 bg-white/80 dark:bg-(--black) backdrop-blur-md border-b border-(--border-light) dark:border-(--border-dark)"> class="fixed top-0 left-0 right-0 z-50 bg-white/80 dark:bg-(--black) backdrop-blur-md border-b border-(--border-light) dark:border-(--border-dark)">
<div class="container px-4 sm:px-6 lg:px-8"> <div class="container mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between h-14"> <div class="flex items-center justify-between h-14">
<!-- Logo --> <!-- Logo -->
<RouterLink :to="{ name: 'home' }" class="flex items-center gap-2"> <RouterLink :to="{ name: 'home' }" class="flex items-center gap-2">

View File

@@ -1,5 +1,5 @@
<template> <template>
<div class="container my-10 "> <div class="container my-10 mx-auto ">
<div <div
class="flex items-end justify-between gap-4 mb-6 bg-(--second-light) dark:bg-(--main-dark) border border-(--border-light) dark:border-(--border-dark) p-4 rounded-md"> class="flex items-end justify-between gap-4 mb-6 bg-(--second-light) dark:bg-(--main-dark) border border-(--border-light) dark:border-(--border-dark) p-4 rounded-md">

View File

@@ -1,118 +1,148 @@
<template> <template>
<div class="container"> <div class="container mx-auto mt-10">
<div class="p-6 bg-white dark:bg-(--black) min-h-screen font-sans"> <div class="flex flex-col mb-6">
<div class="flex justify-between items-center mb-6"> <h1 class="text-2xl font-bold text-black dark:text-white">{{ t('Addresses') }}</h1>
<h1 class="text-2xl font-bold text-black dark:text-white"> <div class="flex justify-between items-center">
{{ t('addresses.title') }} <div class="flex gap-2 items-center">
</h1> <UInput v-model="searchQuery" type="text" :placeholder="t('Search address')"
<UButton @click="showModal = true" class="bg-white dark:bg-gray-800 text-black dark:text-white absolute" />
class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors flex items-center gap-2"> <UIcon name="ic:baseline-search"
<span class="i-lucide-plus" /> class="text-[20px] text-(--accent-blue-light) dark:text-(--accent-blue-dark) relative left-40" />
{{ t('addresses.addNew') }} </div>
<UButton color="primary" @click="openCreateModal"
class="bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) text-white hover:bg-(--accent-blue-dark) dark:hover:bg-(--accent-blue-light)">
<UIcon name="mdi:add-bold" />
{{ t('Add Address') }}
</UButton> </UButton>
</div>
</div>
</div> <div v-if="paginatedAddresses.length" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
<div class="mb-6">
<UInput v-model="searchQuery" type="text" :placeholder="t('addresses.searchPlaceholder')"
class="bg-white dark:bg-gray-800 text-black dark:text-white w-[30%]" />
</div>
<div v-if="paginatedAddresses.length > 0" class="space-y-4">
<div v-for="address in paginatedAddresses" :key="address.id" <div v-for="address in paginatedAddresses" :key="address.id"
class="border border-gray-200 dark:border-gray-700 rounded-lg p-4 bg-white dark:bg-gray-800 hover:shadow-md transition-shadow"> class="border border-(--border-light) dark:border-(--border-dark) rounded-md p-4 bg-(--second-light) dark:bg-(--main-dark) hover:shadow-md transition-shadow">
<div class="flex justify-between items-start"> <p class="text-black dark:text-white">{{ address.street }}</p>
<div class="flex-1"> <p class="text-black dark:text-white">{{ address.zipCode }}, {{ address.city }}</p>
<p class="text-black dark:text-white mt-1">
{{ address.street }}
</p>
<p class="text-black dark:text-white flex gap-2">
{{ address.zipCode }}, <span>{{ address.city }}</span>
</p>
<p class="text-black dark:text-white">{{ address.country }}</p> <p class="text-black dark:text-white">{{ address.country }}</p>
</div> <div class="flex gap-2 mt-2">
</div> <UButton size="sm" color="neutral" variant="outline" @click="openEditModal(address)"
</div> class="text-(--accent-blue-light) dark:text-(--accent-blue-dark)">{{ t('edit') }}
</div>
<div v-else class="text-center py-12 text-gray-500 dark:text-gray-400">
<span class="i-lucide-map-pin text-4xl mb-4 block" />
<p class="text-lg">{{ t('addresses.noAddresses') }}</p>
<UButton @click="showModal"
class="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors">
{{ t('addresses.addFirst') }}
</UButton> </UButton>
<button size="sm" color="destructive" variant="outline" @click="confirmDelete(address.id)"
class="text-red-500 hover:bg-red-100 dark:hover:bg-red-900 dark:hover:text-red-100 rounded transition-colors p-2">
<UIcon name="material-symbols:delete" class="text-[16px]" />
</button>
</div> </div>
<form @submit.prevent="saveAddress" class="space-y-4 mt-4"> </div>
</div>
<div v-else class="text-center py-8 text-gray-500 dark:text-gray-400">{{ t('No addresses found') }}</div>
<div class="mt-6 flex justify-center">
<UPagination v-model:page="page" :total="totalItems" :page-size="pageSize" />
</div>
<UModal v-model:open="showModal" :overlay="true" class="max-w-md mx-auto">
<template #content>
<div class="p-6 flex flex-col gap-6">
<p class="text-[20px] text-black dark:text-white ">Address</p>
<UForm @submit.prevent="saveAddress" class="space-y-4" :validate="validate">
<div> <div>
<label class="block text-sm font-medium text-black dark:text-white mb-1">Street *</label> <label class="block text-sm font-medium text-black dark:text-white mb-1">Street *</label>
<UInput v-model="formData.street" placeholder="Enter street" /> <UInput v-model="formData.street" placeholder="Enter street" name="street" class="w-full" />
</div> </div>
<div> <div>
<label class="block text-sm font-medium text-black dark:text-white mb-1">Zip Code *</label> <label class="block text-sm font-medium text-black dark:text-white mb-1">Zip Code *</label>
<UInput v-model="formData.zipCode" placeholder="Enter zip code" /> <UInput v-model="formData.zipCode" placeholder="Enter zip code" name="zipCode"
class="w-full" />
</div> </div>
<div> <div>
<label class="block text-sm font-medium text-black dark:text-white mb-1">City *</label> <label class="block text-sm font-medium text-black dark:text-white mb-1">City *</label>
<UInput v-model="formData.city" placeholder="Enter city" /> <UInput v-model="formData.city" placeholder="Enter city" name="city" class="w-full" />
</div> </div>
<div> <div>
<label class="block text-sm font-medium text-black dark:text-white mb-1">Country *</label> <label class="block text-sm font-medium text-black dark:text-white mb-1">Country *</label>
<UInput v-model="formData.country" placeholder="Enter country" /> <UInput v-model="formData.country" placeholder="Enter country" name="country"
class="w-full" />
</div> </div>
</UForm>
<div class="flex justify-end gap-2">
<UButton variant="outline" color="neutral" @click="closeModal"
class="text-black dark:text-white">{{ t('Cancel') }}</UButton>
<UButton variant="outline" color="neutral" @click="saveAddress"
class="text-white bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) hover:bg-(--accent-blue-dark) dark:hover:bg-(--accent-blue-light)">
{{ t('Save') }}</UButton>
</div>
</div>
</template>
</UModal>
<div class="flex justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700"> <UModal v-model:open="showDeleteConfirm" :overlay="true" class="max-w-md mx-auto">
<UButton color="neutral" variant="outline" @click="closeModal">Cancel</UButton> <template #content>
<UButton type="submit" color="primary">Save</UButton> <div class="p-6 flex flex-col gap-3">
<div class="flex flex-col gap-2 justify-center items-center">
<p class="flex items-end gap-2 dark:text-white text-black">
<UIcon name='f7:exclamationmark-triangle' class="text-[35px] text-red-700" />
Confirm Delete
</p>
<p class="text-gray-700 dark:text-gray-300">
{{ t('Are you sure you want to delete this address?') }}</p>
</div> </div>
</form> <div class="flex justify-center gap-5">
<UButton variant="outline" color="neutral" @click="showDeleteConfirm = false"
class="dark:text-white text-black">{{ t('Cancel') }}
</UButton>
<UButton variant="outline" color="neutral" @click="deleteAddress" class="text-red-700">
{{ t('Delete') }}</UButton>
</div> </div>
</div> </div>
</template> </template>
</UModal>
</div>
</template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch } from 'vue' import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router' import { useAddressStore } from '@/stores/address'
import { useAddressStore, type Address, type AddressFormData } from '@/stores/address'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
const router = useRouter()
const addressStore = useAddressStore() const addressStore = useAddressStore()
const { t } = useI18n() const { t } = useI18n()
const searchQuery = ref('')
const showModal = ref(false) const showModal = ref(false)
const isEditing = ref(false) const isEditing = ref(false)
const editingAddressId = ref<number | null>(null) const editingAddressId = ref<number | null>(null)
const formData = ref({ street: '', zipCode: '', city: '', country: '' })
const formData = ref<AddressFormData>({ const showDeleteConfirm = ref(false)
street: '', const addressToDelete = ref<number | null>(null)
zipCode: '',
city: '',
country: ''
})
const formErrors = ref<Record<string, string>>({})
const searchQuery = ref('')
let searchTimeout: ReturnType<typeof setTimeout> | null = null
watch(searchQuery, (newValue) => {
if (searchTimeout) clearTimeout(searchTimeout)
searchTimeout = setTimeout(() => {
addressStore.setSearchQuery(newValue)
}, 300)
})
const page = ref(addressStore.currentPage)
const paginatedAddresses = computed(() => addressStore.paginatedAddresses) const paginatedAddresses = computed(() => addressStore.paginatedAddresses)
const totalItems = computed(() => addressStore.totalItems)
const pageSize = addressStore.pageSize
watch(page, (newPage) => addressStore.setPage(newPage))
watch(searchQuery, (val) => {
addressStore.setSearchQuery(val)
})
function openCreateModal() {
resetForm()
isEditing.value = false
showModal.value = true
}
function openEditModal(address: any) {
formData.value = { ...address }
isEditing.value = true
editingAddressId.value = address.id
showModal.value = true
}
function resetForm() { function resetForm() {
formData.value = { formData.value = { street: '', zipCode: '', city: '', country: '' }
street: '', editingAddressId.value = null
zipCode: '',
city: '',
country: ''
}
formErrors.value = {}
} }
function closeModal() { function closeModal() {
@@ -120,35 +150,35 @@ function closeModal() {
resetForm() resetForm()
} }
function validateForm(): boolean { function validate() {
formErrors.value = {} const errors = []
if (!formData.value.street) errors.push({ name: 'street', message: 'Street required' })
if (!formData.value.street.trim()) { if (!formData.value.zipCode) errors.push({ name: 'zipCode', message: 'Zip Code required' })
formErrors.value.street = 'Street is required' if (!formData.value.city) errors.push({ name: 'city', message: 'City required' })
} if (!formData.value.country) errors.push({ name: 'country', message: 'Country required' })
if (!formData.value.zipCode.trim()) { return errors.length ? errors : null
formErrors.value.zipCode = 'Zip Code is required'
}
if (!formData.value.city.trim()) {
formErrors.value.city = 'City is required'
}
if (!formData.value.country.trim()) {
formErrors.value.country = 'Country is required'
}
return Object.keys(formErrors.value).length === 0
} }
function saveAddress() { function saveAddress() {
if (!validateForm()) return if (validate()) return
if (isEditing.value && editingAddressId.value) { if (isEditing.value && editingAddressId.value) {
(editingAddressId.value, formData.value) addressStore.updateAddress(editingAddressId.value, formData.value)
} else { } else {
addressStore.addAddress(formData.value) addressStore.addAddress(formData.value)
} }
closeModal() closeModal()
} }
function confirmDelete(id: number) {
addressToDelete.value = id
showDeleteConfirm.value = true
}
function deleteAddress() {
if (addressToDelete.value) {
addressStore.deleteAddress(addressToDelete.value)
}
showDeleteConfirm.value = false
addressToDelete.value = null
}
</script> </script>

View File

@@ -0,0 +1,9 @@
<template>
<div class="container mx-auto">
</div>
</template>
<script setup lang="ts">
</script>

View File

@@ -1,5 +1,5 @@
<template> <template>
<div class="container mt-14"> <div class="container mt-14 mx-auto">
<div class="flex justify-between gap-8 mb-6"> <div class="flex justify-between gap-8 mb-6">
<div class="flex-1"> <div class="flex-1">
<div class="bg-gray-100 dark:bg-gray-800 rounded-lg p-8 flex items-center justify-center min-h-[300px]"> <div class="bg-gray-100 dark:bg-gray-800 rounded-lg p-8 flex items-center justify-center min-h-[300px]">

View File

@@ -22,42 +22,20 @@ export const useAddressStore = defineStore('address', () => {
const error = ref<string | null>(null) const error = ref<string | null>(null)
const currentPage = ref(1) const currentPage = ref(1)
const pageSize = 10 const pageSize = 20
const totalItems = computed(() => filteredAddresses.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize))
const searchQuery = ref('') const searchQuery = ref('')
function initMockData() { function initMockData() {
addresses.value = [ addresses.value = [
{ { id: 1, street: 'Main Street 123', zipCode: '10-001', city: 'New York', country: 'United States' },
id: 1, { id: 2, street: 'Oak Avenue 123', zipCode: '90-001', city: 'Los Angeles', country: 'United States' },
street: 'Main Street 123', { id: 3, street: 'Pine Road 123', zipCode: '60-601', city: 'Chicago', country: 'United States' }
zipCode: '10-001',
city: 'New York',
country: 'United States'
},
{
id: 2,
street: 'Oak Avenue 123',
zipCode: '90-001',
city: 'Los Angeles',
country: 'United States'
},
{
id: 3,
street: 'Pine Road 123 ',
zipCode: '60-601',
city: 'Chicago',
country: 'United States'
}
] ]
} }
const filteredAddresses = computed(() => { const filteredAddresses = computed(() => {
if (!searchQuery.value) { if (!searchQuery.value) return addresses.value
return addresses.value
}
const query = searchQuery.value.toLowerCase() const query = searchQuery.value.toLowerCase()
@@ -68,34 +46,62 @@ export const useAddressStore = defineStore('address', () => {
addr.zipCode.toLowerCase().includes(query) addr.zipCode.toLowerCase().includes(query)
) )
}) })
const totalItems = computed(() => filteredAddresses.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize))
const paginatedAddresses = computed(() => { const paginatedAddresses = computed(() => {
const start = (currentPage.value - 1) * pageSize const start = (currentPage.value - 1) * pageSize
const end = start + pageSize return filteredAddresses.value.slice(start, start + pageSize)
return filteredAddresses.value.slice(start, end)
}) })
function getAddressById(id: number): Address | undefined { function getAddressById(id: number) {
return addresses.value.find(addr => addr.id === id) return addresses.value.find(addr => addr.id === id)
} }
function addAddress(formData: AddressFormData): Address { function normalize(data: AddressFormData): AddressFormData {
const now = new Date().toISOString() return {
street: data.street.trim(),
const newAddress: Address = { zipCode: data.zipCode.trim(),
id: Date.now(), city: data.city.trim(),
...formData, country: data.country.trim()
}
} }
addresses.value.push(newAddress) function generateId(): number {
return Math.max(0, ...addresses.value.map(a => a.id)) + 1
}
function addAddress(formData: AddressFormData): Address {
const newAddress: Address = {
id: generateId(),
...normalize(formData)
}
addresses.value.unshift(newAddress)
resetPagination()
return newAddress return newAddress
} }
function updateAddress(id: number, formData: AddressFormData): boolean {
const index = addresses.value.findIndex(a => a.id === id)
if (index === -1) return false
addresses.value[index] = {
...addresses.value[index],
...normalize(formData)
}
return true
}
function deleteAddress(id: number): boolean { function deleteAddress(id: number): boolean {
const index = addresses.value.findIndex(addr => addr.id === id) const index = addresses.value.findIndex(a => a.id === id)
if (index === -1) return false if (index === -1) return false
addresses.value.splice(index, 1) addresses.value.splice(index, 1)
resetPagination()
return true return true
} }
@@ -128,6 +134,7 @@ export const useAddressStore = defineStore('address', () => {
paginatedAddresses, paginatedAddresses,
getAddressById, getAddressById,
addAddress, addAddress,
updateAddress,
deleteAddress, deleteAddress,
setPage, setPage,
setSearchQuery, setSearchQuery,

View File

@@ -24,7 +24,8 @@ INSERT IGNORE INTO b2b_language
VALUES VALUES
(1, '2022-09-16 17:10:02.837', '2026-03-02 21:24:36.779730', NULL, 'Polski', 'pl', 'pl', '__-__-____', '__-__', 0, 0, 1, '🇵🇱'), (1, '2022-09-16 17:10:02.837', '2026-03-02 21:24:36.779730', NULL, 'Polski', 'pl', 'pl', '__-__-____', '__-__', 0, 0, 1, '🇵🇱'),
(2, '2022-09-16 17:10:02.852', '2026-03-02 21:24:36.779730', NULL, 'English', 'en', 'en', '__-__-____', '__-__', 0, 1, 1, '🇬🇧'), (2, '2022-09-16 17:10:02.852', '2026-03-02 21:24:36.779730', NULL, 'English', 'en', 'en', '__-__-____', '__-__', 0, 1, 1, '🇬🇧'),
(3, '2022-09-16 17:10:02.865', '2026-03-02 21:24:36.779730', NULL, 'Čeština', 'cs', 'cs', '__-__-____', '__-__', 0, 0, 1, '🇨🇿'); (3, '2022-09-16 17:10:02.865', '2026-03-02 21:24:36.779730', NULL, 'Čeština', 'cs', 'cs', '__-__-____', '__-__', 0, 0, 1, '🇨🇿'),
(4, '2022-09-16 17:10:02.852', '2026-03-02 21:24:36.779730', NULL, 'Deutsch', 'de', 'de', '__-__-____', '__-__', 0, 0, 1, '🇩🇪');
CREATE TABLE IF NOT EXISTS b2b_components ( CREATE TABLE IF NOT EXISTS b2b_components (
id INT AUTO_INCREMENT PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,

View File

@@ -0,0 +1,74 @@
package ProductDescriptionRepo
import (
"fmt"
"git.ma-al.com/goc_daniel/b2b/app/db"
"git.ma-al.com/goc_daniel/b2b/app/model"
)
type UIProductDescriptionRepo interface {
GetProductDescription(productID uint, productShopID uint, productLangID uint) (*model.ProductDescription, error)
CreateIfDoesNotExist(productID uint, productShopID uint, productLangID uint) error
UpdateFields(productID uint, productShopID uint, productLangID uint, updates map[string]string) error
}
type ProductDescriptionRepo struct{}
func New() UIProductDescriptionRepo {
return &ProductDescriptionRepo{}
}
// We assume that any user has access to all product descriptions
func (r *ProductDescriptionRepo) GetProductDescription(productID uint, productShopID uint, productLangID uint) (*model.ProductDescription, error) {
var ProductDescription model.ProductDescription
err := db.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
}
// If it doesn't exist, returns an error.
func (r *ProductDescriptionRepo) CreateIfDoesNotExist(productID uint, productShopID uint, productLangID uint) error {
record := model.ProductDescription{
ProductID: productID,
ShopID: productShopID,
LangID: productLangID,
}
err := db.DB.
Table("ps_product_lang").
Where("id_product = ? AND id_shop = ? AND id_lang = ?", productID, productShopID, productLangID).
FirstOrCreate(&record).Error
if err != nil {
return fmt.Errorf("database error: %w", err)
}
return nil
}
func (r *ProductDescriptionRepo) UpdateFields(productID uint, productShopID uint, productLangID uint, updates map[string]string) error {
if len(updates) == 0 {
return nil
}
updatesIface := make(map[string]interface{}, len(updates))
for k, v := range updates {
updatesIface[k] = v
}
err := db.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
}