Compare commits
3 Commits
789d59b0c9
...
22e8556c9d
| Author | SHA1 | Date | |
|---|---|---|---|
| 22e8556c9d | |||
| c79e08dbb8 | |||
|
|
a0dcb56fda |
@@ -6,6 +6,8 @@ import (
|
||||
"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/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"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
@@ -41,151 +43,132 @@ func ProductDescriptionHandlerRoutes(r fiber.Router) fiber.Router {
|
||||
func (h *ProductDescriptionHandler) GetProductDescription(c fiber.Ctx) error {
|
||||
userID, ok := c.Locals("userID").(uint)
|
||||
if !ok {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody), // possibly could return a different error
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody)))
|
||||
}
|
||||
|
||||
productID_attribute := c.Query("productID")
|
||||
productID, err := strconv.Atoi(productID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
productShopID_attribute := c.Query("productShopID")
|
||||
productShopID, err := strconv.Atoi(productShopID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
productLangID_attribute := c.Query("productLangID")
|
||||
productLangID, err := strconv.Atoi(productLangID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(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 {
|
||||
return c.Status(responseErrors.GetErrorStatus(err)).JSON(fiber.Map{
|
||||
"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
|
||||
func (h *ProductDescriptionHandler) SaveProductDescription(c fiber.Ctx) error {
|
||||
userID, ok := c.Locals("userID").(uint)
|
||||
if !ok {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody), // possibly could return a different error
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody)))
|
||||
}
|
||||
|
||||
productID_attribute := c.Query("productID")
|
||||
productID, err := strconv.Atoi(productID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
productShopID_attribute := c.Query("productShopID")
|
||||
productShopID, err := strconv.Atoi(productShopID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
productLangID_attribute := c.Query("productLangID")
|
||||
productLangID, err := strconv.Atoi(productLangID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
updates := make(map[string]string)
|
||||
if err := c.Bind().Body(&updates); err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(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)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(err)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, err),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(err)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"message": i18n.T_(c, "product_description.successfully_updated_fields"),
|
||||
})
|
||||
return c.JSON(response.Make(nullable.GetNil(""), 0, i18n.T_(c, response.Message_OK)))
|
||||
}
|
||||
|
||||
// GetProductDescription returns the product description for a given product ID
|
||||
// TranslateProductDescription returns translated product description
|
||||
func (h *ProductDescriptionHandler) TranslateProductDescription(c fiber.Ctx) error {
|
||||
userID, ok := c.Locals("userID").(uint)
|
||||
if !ok {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody), // possibly could return a different error
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody)))
|
||||
}
|
||||
|
||||
productID_attribute := c.Query("productID")
|
||||
productID, err := strconv.Atoi(productID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
productShopID_attribute := c.Query("productShopID")
|
||||
productShopID, err := strconv.Atoi(productShopID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
productFromLangID_attribute := c.Query("productFromLangID")
|
||||
productFromLangID, err := strconv.Atoi(productFromLangID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
productToLangID_attribute := c.Query("productToLangID")
|
||||
productToLangID, err := strconv.Atoi(productToLangID_attribute)
|
||||
if err != nil {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
|
||||
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
|
||||
}
|
||||
|
||||
model := c.Query("model")
|
||||
if model != "OpenAI" && model != "Google" {
|
||||
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute),
|
||||
})
|
||||
aiModel := c.Query("model")
|
||||
if aiModel != "OpenAI" && aiModel != "Google" {
|
||||
return c.Status(responseErrors.GetErrorStatus(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 {
|
||||
return c.Status(responseErrors.GetErrorStatus(err)).JSON(fiber.Map{
|
||||
"error": responseErrors.GetErrorCode(c, err),
|
||||
})
|
||||
return c.Status(responseErrors.GetErrorStatus(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)))
|
||||
}
|
||||
|
||||
@@ -86,6 +86,6 @@ func (h *SettingsHandler) GetSettings(cfg *config.Config) fiber.Handler {
|
||||
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)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
productDescriptionRepo ProductDescriptionRepo.ProductDescriptionRepo
|
||||
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
|
||||
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,
|
||||
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 {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
package response
|
||||
|
||||
import "github.com/gofiber/fiber/v3"
|
||||
|
||||
type Response[T any] struct {
|
||||
Message string `json:"message,omitempty"`
|
||||
Items *T `json:"items,omitempty"`
|
||||
Count *int `json:"count,omitempty"`
|
||||
Message string `json:"message"`
|
||||
Items *T `json:"items"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
func Make[T any](c fiber.Ctx, status int, items *T, count *int, message string) Response[T] {
|
||||
c.Status(status)
|
||||
func Make[T any](items *T, count int, message string) Response[T] {
|
||||
return Response[T]{
|
||||
Message: message,
|
||||
Items: items,
|
||||
|
||||
@@ -38,7 +38,7 @@ var (
|
||||
ErrVerificationTokenExpired = errors.New("verification token has expired")
|
||||
|
||||
// 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")
|
||||
ErrInvalidXHTML = errors.New("text is not in xhtml format")
|
||||
ErrAIResponseFail = errors.New("AI responded with failure")
|
||||
@@ -119,9 +119,9 @@ func GetErrorCode(c fiber.Ctx, err error) string {
|
||||
case errors.Is(err, ErrInvalidXHTML):
|
||||
return i18n.T_(c, "error.err_invalid_html")
|
||||
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):
|
||||
return i18n.T_(c, "error.err_openai_bad_output")
|
||||
return i18n.T_(c, "error.err_ai_bad_output")
|
||||
|
||||
default:
|
||||
return i18n.T_(c, "error.err_internal_server_error")
|
||||
1
bo/components.d.ts
vendored
1
bo/components.d.ts
vendored
@@ -17,6 +17,7 @@ declare module 'vue' {
|
||||
En_TermsAndConditionsView: typeof import('./src/components/terms/en_TermsAndConditionsView.vue')['default']
|
||||
LangSwitch: typeof import('./src/components/inner/langSwitch.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']
|
||||
Pl_PrivacyPolicyView: typeof import('./src/components/terms/pl_PrivacyPolicyView.vue')['default']
|
||||
Pl_TermsAndConditionsView: typeof import('./src/components/terms/pl_TermsAndConditionsView.vue')['default']
|
||||
|
||||
@@ -2,10 +2,6 @@ import type { NuxtUIOptions } from '@nuxt/ui/unplugin'
|
||||
|
||||
export const uiOptions: NuxtUIOptions = {
|
||||
ui: {
|
||||
colors: {
|
||||
primary: 'blue',
|
||||
neutral: 'zink',
|
||||
},
|
||||
pagination: {
|
||||
slots: {
|
||||
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!',
|
||||
}
|
||||
|
||||
},
|
||||
modal: {
|
||||
slots: {
|
||||
content: 'border! border-(--border-light)! dark:border-(--border-dark)! outline-0! ring-0! bg-(--second-light) dark:bg-(--main-dark)',
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ const authStore = useAuthStore()
|
||||
<template>
|
||||
<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)">
|
||||
<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">
|
||||
<!-- Logo -->
|
||||
<RouterLink :to="{ name: 'home' }" class="flex items-center gap-2">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="container my-10 ">
|
||||
<div class="container my-10 mx-auto ">
|
||||
|
||||
<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">
|
||||
|
||||
@@ -1,118 +1,148 @@
|
||||
<template>
|
||||
<div class="container">
|
||||
<div class="p-6 bg-white dark:bg-(--black) min-h-screen font-sans">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h1 class="text-2xl font-bold text-black dark:text-white">
|
||||
{{ t('addresses.title') }}
|
||||
</h1>
|
||||
<UButton @click="showModal = true"
|
||||
class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors flex items-center gap-2">
|
||||
<span class="i-lucide-plus" />
|
||||
{{ t('addresses.addNew') }}
|
||||
<div class="container mx-auto mt-10">
|
||||
<div class="flex flex-col mb-6">
|
||||
<h1 class="text-2xl font-bold text-black dark:text-white">{{ t('Addresses') }}</h1>
|
||||
<div class="flex justify-between items-center">
|
||||
<div class="flex gap-2 items-center">
|
||||
<UInput v-model="searchQuery" type="text" :placeholder="t('Search address')"
|
||||
class="bg-white dark:bg-gray-800 text-black dark:text-white absolute" />
|
||||
<UIcon name="ic:baseline-search"
|
||||
class="text-[20px] text-(--accent-blue-light) dark:text-(--accent-blue-dark) relative left-40" />
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<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-if="paginatedAddresses.length" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
<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">
|
||||
<div class="flex justify-between items-start">
|
||||
<div class="flex-1">
|
||||
<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>
|
||||
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">
|
||||
<p class="text-black dark:text-white">{{ address.street }}</p>
|
||||
<p class="text-black dark:text-white">{{ address.zipCode }}, {{ address.city }}</p>
|
||||
<p class="text-black dark:text-white">{{ address.country }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</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') }}
|
||||
<div class="flex gap-2 mt-2">
|
||||
<UButton size="sm" color="neutral" variant="outline" @click="openEditModal(address)"
|
||||
class="text-(--accent-blue-light) dark:text-(--accent-blue-dark)">{{ t('edit') }}
|
||||
</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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
</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">
|
||||
<UButton color="neutral" variant="outline" @click="closeModal">Cancel</UButton>
|
||||
<UButton type="submit" color="primary">Save</UButton>
|
||||
<UModal v-model:open="showDeleteConfirm" :overlay="true" class="max-w-md mx-auto">
|
||||
<template #content>
|
||||
<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>
|
||||
</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>
|
||||
</template>
|
||||
</UModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAddressStore, type Address, type AddressFormData } from '@/stores/address'
|
||||
import { useAddressStore } from '@/stores/address'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const router = useRouter()
|
||||
const addressStore = useAddressStore()
|
||||
const { t } = useI18n()
|
||||
|
||||
const searchQuery = ref('')
|
||||
const showModal = ref(false)
|
||||
const isEditing = ref(false)
|
||||
const editingAddressId = ref<number | null>(null)
|
||||
const formData = ref({ street: '', zipCode: '', city: '', country: '' })
|
||||
|
||||
const formData = ref<AddressFormData>({
|
||||
street: '',
|
||||
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 showDeleteConfirm = ref(false)
|
||||
const addressToDelete = ref<number | null>(null)
|
||||
|
||||
const page = ref(addressStore.currentPage)
|
||||
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() {
|
||||
formData.value = {
|
||||
street: '',
|
||||
zipCode: '',
|
||||
city: '',
|
||||
country: ''
|
||||
}
|
||||
formErrors.value = {}
|
||||
formData.value = { street: '', zipCode: '', city: '', country: '' }
|
||||
editingAddressId.value = null
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
@@ -120,35 +150,35 @@ function closeModal() {
|
||||
resetForm()
|
||||
}
|
||||
|
||||
function validateForm(): boolean {
|
||||
formErrors.value = {}
|
||||
|
||||
if (!formData.value.street.trim()) {
|
||||
formErrors.value.street = 'Street is required'
|
||||
}
|
||||
if (!formData.value.zipCode.trim()) {
|
||||
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 validate() {
|
||||
const errors = []
|
||||
if (!formData.value.street) errors.push({ name: 'street', message: 'Street required' })
|
||||
if (!formData.value.zipCode) errors.push({ name: 'zipCode', message: 'Zip Code required' })
|
||||
if (!formData.value.city) errors.push({ name: 'city', message: 'City required' })
|
||||
if (!formData.value.country) errors.push({ name: 'country', message: 'Country required' })
|
||||
return errors.length ? errors : null
|
||||
}
|
||||
|
||||
function saveAddress() {
|
||||
if (!validateForm()) return
|
||||
|
||||
if (validate()) return
|
||||
if (isEditing.value && editingAddressId.value) {
|
||||
(editingAddressId.value, formData.value)
|
||||
addressStore.updateAddress(editingAddressId.value, formData.value)
|
||||
} else {
|
||||
addressStore.addAddress(formData.value)
|
||||
}
|
||||
|
||||
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>
|
||||
9
bo/src/components/customer/PageCart.vue
Normal file
9
bo/src/components/customer/PageCart.vue
Normal file
@@ -0,0 +1,9 @@
|
||||
<template>
|
||||
<div class="container mx-auto">
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
</script>
|
||||
@@ -1,5 +1,5 @@
|
||||
<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-1">
|
||||
<div class="bg-gray-100 dark:bg-gray-800 rounded-lg p-8 flex items-center justify-center min-h-[300px]">
|
||||
|
||||
@@ -22,42 +22,20 @@ export const useAddressStore = defineStore('address', () => {
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
const currentPage = ref(1)
|
||||
const pageSize = 10
|
||||
const totalItems = computed(() => filteredAddresses.value.length)
|
||||
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize))
|
||||
const pageSize = 20
|
||||
|
||||
const searchQuery = ref('')
|
||||
|
||||
function initMockData() {
|
||||
addresses.value = [
|
||||
{
|
||||
id: 1,
|
||||
street: 'Main Street 123',
|
||||
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'
|
||||
}
|
||||
{ id: 1, street: 'Main Street 123', 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(() => {
|
||||
if (!searchQuery.value) {
|
||||
return addresses.value
|
||||
}
|
||||
if (!searchQuery.value) return addresses.value
|
||||
|
||||
const query = searchQuery.value.toLowerCase()
|
||||
|
||||
@@ -68,34 +46,62 @@ export const useAddressStore = defineStore('address', () => {
|
||||
addr.zipCode.toLowerCase().includes(query)
|
||||
)
|
||||
})
|
||||
|
||||
const totalItems = computed(() => filteredAddresses.value.length)
|
||||
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize))
|
||||
|
||||
const paginatedAddresses = computed(() => {
|
||||
const start = (currentPage.value - 1) * pageSize
|
||||
const end = start + pageSize
|
||||
return filteredAddresses.value.slice(start, end)
|
||||
return filteredAddresses.value.slice(start, start + pageSize)
|
||||
})
|
||||
|
||||
function getAddressById(id: number): Address | undefined {
|
||||
function getAddressById(id: number) {
|
||||
return addresses.value.find(addr => addr.id === id)
|
||||
}
|
||||
|
||||
function addAddress(formData: AddressFormData): Address {
|
||||
const now = new Date().toISOString()
|
||||
|
||||
const newAddress: Address = {
|
||||
id: Date.now(),
|
||||
...formData,
|
||||
function normalize(data: AddressFormData): AddressFormData {
|
||||
return {
|
||||
street: data.street.trim(),
|
||||
zipCode: data.zipCode.trim(),
|
||||
city: data.city.trim(),
|
||||
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
|
||||
}
|
||||
|
||||
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 {
|
||||
const index = addresses.value.findIndex(addr => addr.id === id)
|
||||
const index = addresses.value.findIndex(a => a.id === id)
|
||||
if (index === -1) return false
|
||||
|
||||
addresses.value.splice(index, 1)
|
||||
resetPagination()
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -128,6 +134,7 @@ export const useAddressStore = defineStore('address', () => {
|
||||
paginatedAddresses,
|
||||
getAddressById,
|
||||
addAddress,
|
||||
updateAddress,
|
||||
deleteAddress,
|
||||
setPage,
|
||||
setSearchQuery,
|
||||
|
||||
@@ -24,7 +24,8 @@ INSERT IGNORE INTO b2b_language
|
||||
VALUES
|
||||
(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, '🇬🇧'),
|
||||
(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 (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
|
||||
74
repository/productDescriptionRepo/productDescriptionRepo.go
Normal file
74
repository/productDescriptionRepo/productDescriptionRepo.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user