5 Commits

Author SHA1 Message Date
Daniel Goc
d38095f912 Merge branch 'main' of ssh://git.ma-al.com:8822/goc_daniel/b2b 2026-03-25 10:42:59 +01:00
Daniel Goc
f81eb84499 some debugging 2026-03-25 10:42:25 +01:00
7be02d1b6c Merge pull request 'test' (#27) from test into main
Reviewed-on: #27
2026-03-25 09:03:06 +00:00
5d1abafdd3 fix: errors 2026-03-25 09:42:09 +01:00
0c448c05c9 fix: product-list 2026-03-25 09:33:39 +01:00
26 changed files with 169 additions and 118 deletions

View File

@@ -33,8 +33,8 @@
"description": "Product listing and description endpoints (under /api/v1/restricted, requires authentication)" "description": "Product listing and description endpoints (under /api/v1/restricted, requires authentication)"
}, },
{ {
"name": "Product Description", "name": "Product Translation",
"description": "Product description management and translation endpoints (under /api/v1/restricted/product-description, requires authentication)" "description": "Product description management and translation endpoints (under /api/v1/restricted/product-translation, requires authentication)"
}, },
{ {
"name": "Menu", "name": "Menu",
@@ -915,9 +915,9 @@
} }
} }
}, },
"/api/v1/restricted/product-description/get-product-description": { "/api/v1/restricted/product-translation/get-product-description": {
"get": { "get": {
"tags": ["Product Description"], "tags": ["Product Translation"],
"summary": "Get product description", "summary": "Get product description",
"description": "Returns the product description for a given product ID and language. Requires authentication.", "description": "Returns the product description for a given product ID and language. Requires authentication.",
"operationId": "getProductDescription", "operationId": "getProductDescription",
@@ -982,9 +982,9 @@
} }
} }
}, },
"/api/v1/restricted/product-description/save-product-description": { "/api/v1/restricted/product-translation/save-product-description": {
"post": { "post": {
"tags": ["Product Description"], "tags": ["Product Translation"],
"summary": "Save product description", "summary": "Save product description",
"description": "Saves the product description for a given product ID in the specified language. Requires authentication.", "description": "Saves the product description for a given product ID in the specified language. Requires authentication.",
"operationId": "saveProductDescription", "operationId": "saveProductDescription",
@@ -1059,9 +1059,9 @@
} }
} }
}, },
"/api/v1/restricted/product-description/translate-product-description": { "/api/v1/restricted/product-translation/translate-product-description": {
"get": { "get": {
"tags": ["Product Description"], "tags": ["Product Translation"],
"summary": "Translate product description", "summary": "Translate product description",
"description": "Translates the product description from one language to another using AI (OpenAI or Google). Requires authentication.", "description": "Translates the product description from one language to another using AI (OpenAI or Google). Requires authentication.",
"operationId": "translateProductDescription", "operationId": "translateProductDescription",
@@ -1271,7 +1271,7 @@
"name": "id_category", "name": "id_category",
"in": "query", "in": "query",
"description": "Filter by category ID", "description": "Filter by category ID",
"required": true, "required": false,
"schema": { "schema": {
"type": "integer", "type": "integer",
"format": "uint" "format": "uint"
@@ -1281,7 +1281,7 @@
"name": "price_lower_bound", "name": "price_lower_bound",
"in": "query", "in": "query",
"description": "Lower price bound", "description": "Lower price bound",
"required": true, "required": false,
"schema": { "schema": {
"type": "number", "type": "number",
"format": "double" "format": "double"
@@ -1291,7 +1291,7 @@
"name": "price_upper_bound", "name": "price_upper_bound",
"in": "query", "in": "query",
"description": "Upper price bound", "description": "Upper price bound",
"required": true, "required": false,
"schema": { "schema": {
"type": "number", "type": "number",
"format": "double" "format": "double"
@@ -1336,7 +1336,7 @@
"get": { "get": {
"tags": ["Search"], "tags": ["Search"],
"summary": "Create search index", "summary": "Create search index",
"description": "Creates a MeiliSearch index for products. Requires superadmin access.", "description": "Creates a MeiliSearch index for products. Must be removed before proper release.",
"operationId": "createSearchIndex", "operationId": "createSearchIndex",
"security": [ "security": [
{ {
@@ -1381,7 +1381,7 @@
"get": { "get": {
"tags": ["Search"], "tags": ["Search"],
"summary": "Test MeiliSearch", "summary": "Test MeiliSearch",
"description": "Tests the MeiliSearch connection. Requires superadmin access.", "description": "Tests the MeiliSearch search. Must be removed before proper release.",
"operationId": "testMeiliSearch", "operationId": "testMeiliSearch",
"security": [ "security": [
{ {

View File

@@ -40,7 +40,6 @@ func AuthHandlerRoutes(r fiber.Router) fiber.Router {
r.Post("/reset-password", handler.ResetPassword) r.Post("/reset-password", handler.ResetPassword)
r.Post("/logout", handler.Logout) r.Post("/logout", handler.Logout)
r.Post("/refresh", handler.RefreshToken) r.Post("/refresh", handler.RefreshToken)
r.Post("/update-choice", handler.UpdateJWTToken)
// Google OAuth2 // Google OAuth2
r.Get("/google", handler.GoogleLogin) r.Get("/google", handler.GoogleLogin)
@@ -48,6 +47,7 @@ func AuthHandlerRoutes(r fiber.Router) fiber.Router {
authProtected := r.Group("", middleware.AuthMiddleware()) authProtected := r.Group("", middleware.AuthMiddleware())
authProtected.Get("/me", handler.Me) authProtected.Get("/me", handler.Me)
authProtected.Post("/update-choice", handler.UpdateJWTToken)
return r return r
} }
@@ -345,9 +345,9 @@ func (h *AuthHandler) CompleteRegistration(c fiber.Ctx) error {
return c.Status(fiber.StatusCreated).JSON(response) return c.Status(fiber.StatusCreated).JSON(response)
} }
// CompleteRegistration handles completion of registration with password // Updates JWT Tokens
func (h *AuthHandler) UpdateJWTToken(c fiber.Ctx) error { func (h *AuthHandler) UpdateJWTToken(c fiber.Ctx) error {
return h.UpdateJWTToken(c) return h.authService.UpdateJWTToken(c)
} }
// GoogleLogin redirects the user to Google's OAuth2 consent page // GoogleLogin redirects the user to Google's OAuth2 consent page

View File

@@ -25,7 +25,7 @@ func NewMeiliSearchHandler() *MeiliSearchHandler {
func MeiliSearchHandlerRoutes(r fiber.Router) fiber.Router { func MeiliSearchHandlerRoutes(r fiber.Router) fiber.Router {
handler := NewMeiliSearchHandler() handler := NewMeiliSearchHandler()
// for superadmin only // for testing purposes only. Must be removed before proper release.
r.Get("/create-index", handler.CreateIndex) r.Get("/create-index", handler.CreateIndex)
r.Get("/test", handler.Test) r.Get("/test", handler.Test)
@@ -84,32 +84,32 @@ func (h *MeiliSearchHandler) Search(c fiber.Ctx) error {
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
} }
id_category_attribute := c.Query("id_category") id_category_attribute := c.Query("id_category", "0")
id_category, err := strconv.Atoi(id_category_attribute) id_category, err := strconv.Atoi(id_category_attribute)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)). return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
} }
price_lower_bound_attribute := c.Query("price_lower_bound") price_lower_bound_attribute := c.Query("price_lower_bound", "-1.0")
price_lower_bound, err := strconv.ParseFloat(price_lower_bound_attribute, 64) price_lower_bound, err := strconv.ParseFloat(price_lower_bound_attribute, 64)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)). return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
} }
price_upper_bound_attribute := c.Query("price_upper_bound") price_upper_bound_attribute := c.Query("price_upper_bound", "-1.0")
price_upper_bound, err := strconv.ParseFloat(price_upper_bound_attribute, 64) price_upper_bound, err := strconv.ParseFloat(price_upper_bound_attribute, 64)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)). return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrBadAttribute)).
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
} }
test, err := h.meiliService.Search(id_lang, query, uint(limit), uint(id_category), price_lower_bound, price_upper_bound) meili_response, err := h.meiliService.Search(id_lang, query, uint(limit), uint(id_category), price_lower_bound, price_upper_bound)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(err)). return c.Status(responseErrors.GetErrorStatus(err)).
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))
} }
return c.JSON(response.Make(&test, 0, i18n.T_(c, response.Message_OK))) return c.JSON(response.Make(&meili_response, 0, i18n.T_(c, response.Message_OK)))
} }

View File

@@ -4,7 +4,7 @@ import (
"strconv" "strconv"
"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/productTranslationService"
"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/nullable"
"git.ma-al.com/goc_daniel/b2b/app/utils/response" "git.ma-al.com/goc_daniel/b2b/app/utils/response"
@@ -13,24 +13,24 @@ import (
"github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3"
) )
// ProductDescriptionHandler handles endpoints that receive, save and translate product descriptions. // ProductTranslationHandler handles endpoints that receive, save and translate product descriptions.
type ProductDescriptionHandler struct { type ProductTranslationHandler struct {
productDescriptionService *productDescriptionService.ProductDescriptionService productTranslationService *productTranslationService.ProductTranslationService
config *config.Config config *config.Config
} }
// NewProductDescriptionHandler creates a new ProductDescriptionHandler instance // NewProductTranslationHandler creates a new ProductTranslationHandler instance
func NewProductDescriptionHandler() *ProductDescriptionHandler { func NewProductTranslationHandler() *ProductTranslationHandler {
productDescriptionService := productDescriptionService.New() productTranslationService := productTranslationService.New()
return &ProductDescriptionHandler{ return &ProductTranslationHandler{
productDescriptionService: productDescriptionService, productTranslationService: productTranslationService,
config: config.Get(), config: config.Get(),
} }
} }
// ProductDescriptionRoutes registers all product description routes // ProductTranslationRoutes registers all product description routes
func ProductDescriptionHandlerRoutes(r fiber.Router) fiber.Router { func ProductTranslationHandlerRoutes(r fiber.Router) fiber.Router {
handler := NewProductDescriptionHandler() handler := NewProductTranslationHandler()
r.Get("/get-product-description", handler.GetProductDescription) r.Get("/get-product-description", handler.GetProductDescription)
r.Post("/save-product-description", handler.SaveProductDescription) r.Post("/save-product-description", handler.SaveProductDescription)
@@ -40,7 +40,7 @@ func ProductDescriptionHandlerRoutes(r fiber.Router) fiber.Router {
} }
// GetProductDescription returns the product description for a given product ID // GetProductDescription returns the product description for a given product ID
func (h *ProductDescriptionHandler) GetProductDescription(c fiber.Ctx) error { func (h *ProductTranslationHandler) 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)). return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
@@ -61,7 +61,7 @@ func (h *ProductDescriptionHandler) GetProductDescription(c fiber.Ctx) error {
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
} }
description, err := h.productDescriptionService.GetProductDescription(userID, uint(productID), uint(productLangID)) description, err := h.productTranslationService.GetProductDescription(userID, uint(productID), uint(productLangID))
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(err)). return c.Status(responseErrors.GetErrorStatus(err)).
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))
@@ -71,7 +71,7 @@ func (h *ProductDescriptionHandler) GetProductDescription(c fiber.Ctx) error {
} }
// SaveProductDescription saves the description for a given product ID, in given language // SaveProductDescription saves the description for a given product ID, in given language
func (h *ProductDescriptionHandler) SaveProductDescription(c fiber.Ctx) error { func (h *ProductTranslationHandler) 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)). return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
@@ -98,7 +98,7 @@ func (h *ProductDescriptionHandler) SaveProductDescription(c fiber.Ctx) error {
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrInvalidBody)))
} }
err = h.productDescriptionService.SaveProductDescription(userID, uint(productID), uint(productLangID), updates) err = h.productTranslationService.SaveProductDescription(userID, uint(productID), uint(productLangID), updates)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(err)). return c.Status(responseErrors.GetErrorStatus(err)).
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))
@@ -108,7 +108,7 @@ func (h *ProductDescriptionHandler) SaveProductDescription(c fiber.Ctx) error {
} }
// TranslateProductDescription returns translated product description // TranslateProductDescription returns translated product description
func (h *ProductDescriptionHandler) TranslateProductDescription(c fiber.Ctx) error { func (h *ProductTranslationHandler) 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)). return c.Status(responseErrors.GetErrorStatus(responseErrors.ErrInvalidBody)).
@@ -142,7 +142,7 @@ func (h *ProductDescriptionHandler) TranslateProductDescription(c fiber.Ctx) err
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, responseErrors.ErrBadAttribute)))
} }
description, err := h.productDescriptionService.TranslateProductDescription(userID, uint(productID), uint(productFromLangID), uint(productToLangID), aiModel) description, err := h.productTranslationService.TranslateProductDescription(userID, uint(productID), uint(productFromLangID), uint(productToLangID), aiModel)
if err != nil { if err != nil {
return c.Status(responseErrors.GetErrorStatus(err)). return c.Status(responseErrors.GetErrorStatus(err)).
JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err))) JSON(response.Make(nullable.GetNil(""), 0, responseErrors.GetErrorCode(c, err)))

View File

@@ -89,9 +89,9 @@ func (s *Server) Setup() error {
auth := s.public.Group("/auth") auth := s.public.Group("/auth")
public.AuthHandlerRoutes(auth) public.AuthHandlerRoutes(auth)
// product description routes (restricted) // product translation routes (restricted)
productDescription := s.restricted.Group("/product-description") productTranslation := s.restricted.Group("/product-translation")
restricted.ProductDescriptionHandlerRoutes(productDescription) restricted.ProductTranslationHandlerRoutes(productTranslation)
// listing products routes (restricted) // listing products routes (restricted)
listProducts := s.restricted.Group("/list-products") listProducts := s.restricted.Group("/list-products")

View File

@@ -6,8 +6,8 @@ type Country struct {
Name string `gorm:"column:name" json:"name"` Name string `gorm:"column:name" json:"name"`
Flag string `gorm:"size:16;not null;column:flag" json:"flag"` Flag string `gorm:"size:16;not null;column:flag" json:"flag"`
CurrencyID uint `gorm:"column:id_currency" json:"currency_id"` CurrencyID uint `gorm:"column:id_currency" json:"currency_id"`
CurrencyISOCode string `gorm:"column:iso_code" json:"currency_iso_code"` CurrencyISOCode string `gorm:"column:currency_iso_code" json:"currency_iso_code"`
CurrencyName string `gorm:"column:name" json:"currency_name"` CurrencyName string `gorm:"column:currency_name" json:"currency_name"`
} }
func (Country) TableName() string { func (Country) TableName() string {

View File

@@ -85,7 +85,7 @@ type ProductFilters struct {
} }
type ScannedCategory struct { type ScannedCategory struct {
CategoryID uint `gorm:"column:ID;primaryKey"` CategoryID uint `gorm:"column:category_id;primaryKey"`
Name string `gorm:"column:name"` Name string `gorm:"column:name"`
Active uint `gorm:"column:active"` Active uint `gorm:"column:active"`
Position uint `gorm:"column:position"` Position uint `gorm:"column:position"`

View File

@@ -22,7 +22,7 @@ func (repo *CategoriesRepo) GetAllCategories(id_lang uint) ([]model.ScannedCateg
err := db.DB. err := db.DB.
Table("ps_category"). Table("ps_category").
Select(` Select(`
ps_category.id_category AS id, ps_category.id_category AS category_id,
ps_category_lang.name AS name, ps_category_lang.name AS name,
ps_category.active AS active, ps_category.active AS active,
ps_category_shop.position AS position, ps_category_shop.position AS position,

View File

@@ -28,8 +28,9 @@ func (repo *LocaleSelectorRepo) GetCountriesAndCurrencies() ([]model.Country, er
var countries []model.Country var countries []model.Country
err := db.DB. err := db.DB.
Table("b2b_countries").
Select("b2b_countries.id, b2b_countries.name, b2b_countries.flag, ps_currency.id_currency as id_currency, ps_currency.name as currency_name, ps_currency.iso_code as currency_iso_code"). Select("b2b_countries.id, b2b_countries.name, b2b_countries.flag, ps_currency.id_currency as id_currency, ps_currency.name as currency_name, ps_currency.iso_code as currency_iso_code").
Joins("JOIN ps_currency ON ps_currency.id_currency = b2b_countries.currency"). Joins("LEFT JOIN ps_currency ON ps_currency.id_currency = b2b_countries.currency_id").
Scan(&countries).Error Scan(&countries).Error
return countries, err return countries, err

View File

@@ -34,7 +34,7 @@ func New() *MeiliService {
} }
} }
// ==================================== FOR SUPERADMIN ONLY ==================================== // ==================================== FOR TESTING ONLY ====================================
func (s *MeiliService) CreateIndex(id_lang uint) error { func (s *MeiliService) CreateIndex(id_lang uint) error {
indexName := "meili_products_shop" + strconv.FormatInt(constdata.SHOP_ID, 10) + "_lang" + strconv.FormatInt(int64(id_lang), 10) indexName := "meili_products_shop" + strconv.FormatInt(constdata.SHOP_ID, 10) + "_lang" + strconv.FormatInt(int64(id_lang), 10)
@@ -130,7 +130,7 @@ func (s *MeiliService) CreateIndex(id_lang uint) error {
return err return err
} }
// ==================================== FOR DEBUG ONLY ==================================== // ==================================== FOR TESTING ONLY ====================================
func (s *MeiliService) Test(id_lang uint) (meilisearch.SearchResponse, error) { func (s *MeiliService) Test(id_lang uint) (meilisearch.SearchResponse, error) {
indexName := "meili_products_shop" + strconv.FormatInt(constdata.SHOP_ID, 10) + "_lang" + strconv.FormatInt(int64(id_lang), 10) indexName := "meili_products_shop" + strconv.FormatInt(constdata.SHOP_ID, 10) + "_lang" + strconv.FormatInt(int64(id_lang), 10)

View File

@@ -1,6 +1,7 @@
package menuService package menuService
import ( import (
"fmt"
"sort" "sort"
"git.ma-al.com/goc_daniel/b2b/app/model" "git.ma-al.com/goc_daniel/b2b/app/model"
@@ -27,6 +28,10 @@ func (s *MenuService) GetMenu(id_lang uint) (*model.Category, error) {
return &model.Category{}, err return &model.Category{}, err
} }
fmt.Printf("all_categories: %v\n", all_categories)
fmt.Printf("id_lang: %v\n", id_lang)
// find the root // find the root
root_index := 0 root_index := 0
root_found := false root_found := false

View File

@@ -1,4 +1,4 @@
package productDescriptionService package productTranslationService
import ( import (
"context" "context"
@@ -26,7 +26,7 @@ import (
googleopt "google.golang.org/api/option" googleopt "google.golang.org/api/option"
) )
type ProductDescriptionService struct { type ProductTranslationService struct {
productDescriptionRepo productDescriptionRepo.UIProductDescriptionRepo productDescriptionRepo productDescriptionRepo.UIProductDescriptionRepo
ctx context.Context ctx context.Context
googleCli translate.TranslationClient googleCli translate.TranslationClient
@@ -34,7 +34,7 @@ type ProductDescriptionService struct {
openAIClient openai.Client openAIClient openai.Client
} }
// New creates a ProductDescriptionService and authenticates against the // New creates a ProductTranslationService and authenticates against the
// Google Cloud Translation API using a service account key file. // Google Cloud Translation API using a service account key file.
// //
// Required configuration (set in .env or environment): // Required configuration (set in .env or environment):
@@ -44,14 +44,14 @@ type ProductDescriptionService struct {
// //
// The service account must have the "Cloud Translation API User" role // The service account must have the "Cloud Translation API User" role
// (roles/cloudtranslate.user) granted in Google Cloud IAM. // (roles/cloudtranslate.user) granted in Google Cloud IAM.
func New() *ProductDescriptionService { func New() *ProductTranslationService {
ctx := context.Background() ctx := context.Background()
cfg := config.Get() cfg := config.Get()
// Read the service account key file whose path comes from config / env. // Read the service account key file whose path comes from config / env.
data, err := os.ReadFile(cfg.GoogleTranslate.CredentialsFile) data, err := os.ReadFile(cfg.GoogleTranslate.CredentialsFile)
if err != nil { if err != nil {
log.Fatalf("productDescriptionService: cannot read credentials file %q: %v", log.Fatalf("ProductTranslationService: cannot read credentials file %q: %v",
cfg.GoogleTranslate.CredentialsFile, err) cfg.GoogleTranslate.CredentialsFile, err)
} }
@@ -62,18 +62,18 @@ func New() *ProductDescriptionService {
CredentialsJSON: data, CredentialsJSON: data,
}) })
if err != nil { if err != nil {
log.Fatalf("productDescriptionService: cannot build Google credentials: %v", err) log.Fatalf("ProductTranslationService: cannot build Google credentials: %v", err)
} }
googleCli, err := translate.NewTranslationClient(ctx, googleopt.WithAuthCredentials(creds)) googleCli, err := translate.NewTranslationClient(ctx, googleopt.WithAuthCredentials(creds))
if err != nil { if err != nil {
log.Fatalf("productDescriptionService: cannot create Translation client: %v", err) log.Fatalf("ProductTranslationService: cannot create Translation client: %v", err)
} }
openAIClient := openai.NewClient(option.WithAPIKey(os.Getenv("OPENAI_KEY")), openAIClient := openai.NewClient(option.WithAPIKey(os.Getenv("OPENAI_KEY")),
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 &ProductTranslationService{
productDescriptionRepo: productDescriptionRepo.New(), productDescriptionRepo: productDescriptionRepo.New(),
ctx: ctx, ctx: ctx,
openAIClient: openAIClient, openAIClient: openAIClient,
@@ -82,12 +82,12 @@ func New() *ProductDescriptionService {
} }
} }
func (s *ProductDescriptionService) GetProductDescription(userID uint, productID uint, productLangID uint) (*model.ProductDescription, error) { func (s *ProductTranslationService) GetProductDescription(userID uint, productID uint, productLangID uint) (*model.ProductDescription, error) {
return s.productDescriptionRepo.GetProductDescription(productID, productLangID) return s.productDescriptionRepo.GetProductDescription(productID, productLangID)
} }
// Updates relevant fields with the "updates" map // Updates relevant fields with the "updates" map
func (s *ProductDescriptionService) SaveProductDescription(userID uint, productID uint, productLangID uint, updates map[string]string) error { func (s *ProductTranslationService) SaveProductDescription(userID uint, productID uint, productLangID uint, updates map[string]string) error {
// only some fields can be affected // only some fields can be affected
allowedFields := []string{"description", "description_short", "meta_description", "meta_title", "name", "available_now", "available_later", "usage"} allowedFields := []string{"description", "description_short", "meta_description", "meta_title", "name", "available_now", "available_later", "usage"}
for key := range updates { for key := range updates {
@@ -120,7 +120,7 @@ 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, productFromLangID uint, productToLangID uint, aiModel string) (*model.ProductDescription, error) { func (s *ProductTranslationService) TranslateProductDescription(userID uint, productID uint, productFromLangID uint, productToLangID uint, aiModel string) (*model.ProductDescription, error) {
productDescription, err := s.productDescriptionRepo.GetProductDescription(productID, productFromLangID) productDescription, err := s.productDescriptionRepo.GetProductDescription(productID, productFromLangID)
if err != nil { if err != nil {

5
bo/components.d.ts vendored
View File

@@ -13,19 +13,17 @@ declare module 'vue' {
export interface GlobalComponents { export interface GlobalComponents {
Cart1: typeof import('./src/components/customer/Cart1.vue')['default'] Cart1: typeof import('./src/components/customer/Cart1.vue')['default']
CategoryMenu: typeof import('./src/components/inner/categoryMenu.vue')['default'] CategoryMenu: typeof import('./src/components/inner/categoryMenu.vue')['default']
CompanyAccountView: typeof import('./src/components/customer/CompanyAccountView.vue')['default']
Cs_PrivacyPolicyView: typeof import('./src/components/terms/cs_PrivacyPolicyView.vue')['default'] Cs_PrivacyPolicyView: typeof import('./src/components/terms/cs_PrivacyPolicyView.vue')['default']
Cs_TermsAndConditionsView: typeof import('./src/components/terms/cs_TermsAndConditionsView.vue')['default'] Cs_TermsAndConditionsView: typeof import('./src/components/terms/cs_TermsAndConditionsView.vue')['default']
En_PrivacyPolicyView: typeof import('./src/components/terms/en_PrivacyPolicyView.vue')['default'] En_PrivacyPolicyView: typeof import('./src/components/terms/en_PrivacyPolicyView.vue')['default']
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']
PageAccount: typeof import('./src/components/customer/PageAccount.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'] PageCart: typeof import('./src/components/customer/PageCart.vue')['default']
PageCreateAccount: typeof import('./src/components/customer/PageCreateAccount.vue')['default'] PageCreateAccount: typeof import('./src/components/customer/PageCreateAccount.vue')['default']
PageCustomerData: typeof import('./src/components/customer/PageCustomerData.vue')['default'] PageCustomerData: typeof import('./src/components/customer/PageCustomerData.vue')['default']
PageProductCardFull: typeof import('./src/components/customer/PageProductCardFull.vue')['default'] PageProductCardFull: typeof import('./src/components/customer/PageProductCardFull.vue')['default']
PageProductsList: typeof import('./src/components/customer/PageProductsList.vue')['default'] PageProductsList: typeof import('./src/components/admin/PageProductsList.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']
ProductCustomization: typeof import('./src/components/customer/components/ProductCustomization.vue')['default'] ProductCustomization: typeof import('./src/components/customer/components/ProductCustomization.vue')['default']
@@ -48,7 +46,6 @@ declare module 'vue' {
UInput: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Input.vue')['default'] UInput: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Input.vue')['default']
UInputNumber: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/InputNumber.vue')['default'] UInputNumber: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/InputNumber.vue')['default']
UModal: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Modal.vue')['default'] UModal: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Modal.vue')['default']
UNavigationMenu: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/NavigationMenu.vue')['default']
UPagination: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Pagination.vue')['default'] UPagination: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Pagination.vue')['default']
USelect: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Select.vue')['default'] USelect: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/Select.vue')['default']
USelectMenu: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/SelectMenu.vue')['default'] USelectMenu: typeof import('./node_modules/@nuxt/ui/dist/runtime/components/SelectMenu.vue')['default']

View File

@@ -19,6 +19,9 @@ const authStore = useAuthStore()
<span class="font-semibold text-gray-900 dark:text-white">TimeTracker</span> <span class="font-semibold text-gray-900 dark:text-white">TimeTracker</span>
</RouterLink> </RouterLink>
<!-- Right Side Actions --> <!-- Right Side Actions -->
<RouterLink :to="{ name: 'products-list' }">
products list
</RouterLink>
<RouterLink :to="{ name: 'product-detail' }"> <RouterLink :to="{ name: 'product-detail' }">
product detail product detail
</RouterLink> </RouterLink>
@@ -37,9 +40,6 @@ const authStore = useAuthStore()
<RouterLink :to="{ name: 'cart1' }"> <RouterLink :to="{ name: 'cart1' }">
Cart1 Cart1
</RouterLink> </RouterLink>
<RouterLink :to="{ name: 'products-list' }">
Products List
</RouterLink>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<!-- Language Switcher --> <!-- Language Switcher -->
<LangSwitch /> <LangSwitch />

View File

@@ -22,7 +22,7 @@
Image</th> Image</th>
<th <th
class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider"> class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Product ID</th> Product Code</th>
<th <th
class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider"> class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Name</th> Name</th>
@@ -33,18 +33,19 @@
</thead> </thead>
<tbody class="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700"> <tbody class="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
<tr v-for="product in productsList" :key="product.product_id" <tr v-for="product in productsList" :key="product.product_id"
class="hover:bg-gray-50 dark:hover:bg-gray-800"> class="hover:bg-gray-50 dark:hover:bg-gray-800"
@click="goToProduct(product.product_id)">
<td class="px-6 py-4 whitespace-nowrap"> <td class="px-6 py-4 whitespace-nowrap">
<img :src="product.ImageID" alt="product image" <img :src="product.image_link" alt="product image"
class="w-16 h-16 object-cover rounded" /> class="w-16 h-16 object-cover rounded" />
</td> </td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">{{ <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">{{
product.product_id }}</td> product.reference }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">{{ <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">{{
product.name }} product.name }}
</td> </td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-blue-600 dark:text-blue-400"> <td class="px-6 py-4 whitespace-nowrap text-sm text-blue-600 dark:text-blue-400">
{{ product.LinkRewrite }} {{ product.link_rewrite }}
</td> </td>
</tr> </tr>
</tbody> </tbody>
@@ -65,13 +66,16 @@
import { ref, onMounted, watch } from 'vue' import { ref, onMounted, watch } from 'vue'
import { useFetchJson } from '@/composable/useFetchJson' import { useFetchJson } from '@/composable/useFetchJson'
import Default from '@/layouts/default.vue' import Default from '@/layouts/default.vue'
import { useRouter } from 'vue-router'
interface Product { interface Product {
reference: number
product_id:number product_id:number
name: string name: string
ImageID: string image_link: string
LinkRewrite: string link_rewrite: string
} }
const router = useRouter()
const page = ref(1) const page = ref(1)
const perPage = ref(15) const perPage = ref(15)
@@ -97,6 +101,7 @@ async function fetchProductList() {
) as ApiResponse ) as ApiResponse
productsList.value = response.items || [] productsList.value = response.items || []
console.log(response)
total.value = response.count || 0 total.value = response.count || 0
} catch (e: unknown) { } catch (e: unknown) {
error.value = e instanceof Error ? e.message : 'Failed to load products' error.value = e instanceof Error ? e.message : 'Failed to load products'
@@ -109,4 +114,11 @@ watch(page, () => {
fetchProductList() fetchProductList()
}) })
onMounted(fetchProductList) onMounted(fetchProductList)
function goToProduct(productId: number) {
router.push({
name: 'product-detail',
params: { id: productId }
})
}
</script> </script>

View File

@@ -35,11 +35,19 @@
</div> </div>
</div> </div>
<div class="flex items-start gap-30"> <div v-if="productStore.loading" class="flex items-center justify-center py-20">
<p class="p-80 bg-(--second-light)">img</p> <UIcon name="svg-spinners:ring-resize" class="text-4xl text-primary" />
</div>
<div v-else-if="productStore.error" class="flex items-center justify-center py-20">
<p class="text-red-500">{{ productStore.error }}</p>
</div>
<div v-else-if="productStore.productDescription" class="flex items-start gap-30">
<div class="w-80 h-80 bg-(--second-light) dark:bg-gray-700 rounded-lg flex items-center justify-center">
<span class="text-gray-500 dark:text-gray-400">Product Image</span>
</div>
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
<p class="text-[25px] font-bold text-black dark:text-white"> <p class="text-[25px] font-bold text-black dark:text-white">
{{ productStore.productDescription.name }} {{ productStore.productDescription.name || 'Product Name' }}
</p> </p>
<p v-html="productStore.productDescription.description_short" class="text-black dark:text-white"></p> <p v-html="productStore.productDescription.description_short" class="text-black dark:text-white"></p>
<div class="space-y-[10px]"> <div class="space-y-[10px]">
@@ -52,14 +60,14 @@
<div class="flex items-center gap-1"> <div class="flex items-center gap-1">
<UIcon name="marketeq:car-shipping" class="text-[25px] text-green-600" /> <UIcon name="marketeq:car-shipping" class="text-[25px] text-green-600" />
<p class="text-[18px] font-bold text-black dark:text-white"> <p class="text-[18px] font-bold text-black dark:text-white">
{{ productStore.productDescription.delivery_in_stock }} {{ productStore.productDescription.delivery_in_stock || 'Delivery information' }}
</p> </p>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="mt-16"> <div v-if="productStore.productDescription" class="mt-16">
<div class="flex gap-4 my-6"> <div class="flex gap-4 my-6">
<UButton @click="activeTab = 'description'" <UButton @click="activeTab = 'description'"
:class="['cursor-pointer', activeTab === 'description' ? 'bg-blue-500 text-white' : '']" color="neutral" :class="['cursor-pointer', activeTab === 'description' ? 'bg-blue-500 text-white' : '']" color="neutral"
@@ -118,21 +126,19 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed } from 'vue' import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useProductStore } from '@/stores/product' import { useProductStore } from '@/stores/product'
import { useEditable } from '@/composable/useConteditable' import { useEditable } from '@/composable/useConteditable'
import { langs } from '@/router/langs' import { langs } from '@/router/langs'
import type { Language } from '@/types' import type { Language } from '@/types'
import Default from '@/layouts/default.vue' import Default from '@/layouts/default.vue'
const route = useRoute()
const activeTab = ref('description') const activeTab = ref('description')
const productStore = useProductStore() const productStore = useProductStore()
const translating = ref(false) const translating = ref(false)
// const availableLangs = computed(() => {
// return langs.filter((l: Language) => ['cs', 'pl', 'der'].includes(l.iso_code))
// })
const isEditing = ref(false) const isEditing = ref(false)
const availableLangs = computed(() => langs) const availableLangs = computed(() => langs)
@@ -140,21 +146,29 @@ const availableLangs = computed(() => langs)
const selectedLanguage = ref('pl') const selectedLanguage = ref('pl')
const currentLangId = ref(2) const currentLangId = ref(2)
const productID = ref<number>(0)
// Watch for language changes and refetch product description
watch(selectedLanguage, async (newLang: string) => {
if (productID.value) {
await fetchForLanguage(newLang)
}
})
const fetchForLanguage = async (langCode: string) => { const fetchForLanguage = async (langCode: string) => {
const lang = langs.find((l: Language) => l.iso_code === langCode) const lang = langs.find((l: Language) => l.iso_code === langCode)
if (lang) { if (lang && productID.value) {
await productStore.getProductDescription(lang.id) await productStore.getProductDescription(lang.id, productID.value)
currentLangId.value = lang.id currentLangId.value = lang.id
} }
} }
const translateToSelectedLanguage = async () => { const translateToSelectedLanguage = async () => {
const targetLang = langs.find((l: Language) => l.iso_code === selectedLanguage.value) const targetLang = langs.find((l: Language) => l.iso_code === selectedLanguage.value)
if (targetLang && currentLangId.value) { if (targetLang && currentLangId.value && productID.value) {
translating.value = true translating.value = true
try { try {
await productStore.translateProductDescription(currentLangId.value, targetLang.id) await productStore.translateProductDescription(productID.value, currentLangId.value, targetLang.id)
currentLangId.value = targetLang.id currentLangId.value = targetLang.id
} finally { } finally {
translating.value = false translating.value = false
@@ -162,7 +176,14 @@ const translateToSelectedLanguage = async () => {
} }
} }
onMounted(async () => {
const id = route.params.id
if (id) {
productID.value = Number(id)
await fetchForLanguage(selectedLanguage.value) await fetchForLanguage(selectedLanguage.value)
}
})
const descriptionRef = ref<HTMLElement | null>(null) const descriptionRef = ref<HTMLElement | null>(null)
const usageRef = ref<HTMLElement | null>(null) const usageRef = ref<HTMLElement | null>(null)
@@ -174,7 +195,7 @@ const originalUsage = ref('')
const saveDescription = async () => { const saveDescription = async () => {
descriptionEdit.disableEdit() descriptionEdit.disableEdit()
await productStore.saveProductDescription() await productStore.saveProductDescription(productID.value)
} }
const cancelDescriptionEdit = () => { const cancelDescriptionEdit = () => {
@@ -202,7 +223,7 @@ const enableEdit = () => {
const saveText = () => { const saveText = () => {
usageEdit.disableEdit() usageEdit.disableEdit()
isEditing.value = false isEditing.value = false
productStore.saveProductDescription() productStore.saveProductDescription(productID.value)
} }
const cancelEdit = () => { const cancelEdit = () => {

View File

@@ -23,9 +23,9 @@ const page = ref(1)
const pageSize = 5 const pageSize = 5
// Fetch products on mount // Fetch products on mount
onMounted(() => { // onMounted(() => {
productStore.getProductDescription() // productStore.getProductDescription(langID: , productID.value)
}) // })
// Filtered products // Filtered products
// const filteredProducts = computed(() => { // const filteredProducts = computed(() => {

View File

@@ -153,6 +153,7 @@ function validate() {
return errors return errors
} }
function saveAccount() { function saveAccount() {
const errors = validate() const errors = validate()
if (errors.length) return if (errors.length) return
@@ -169,7 +170,7 @@ function saveAccount() {
vat: formData.value.vat, vat: formData.value.vat,
companyAddressId: formData.value.companyAddressId, companyAddressId: formData.value.companyAddressId,
billingAddressId: formData.value.billingAddressId, billingAddressId: formData.value.billingAddressId,
companyAddress: selectedAddr || null companyAddress : ''
}) })
router.push({ name: 'customer-data' }) router.push({ name: 'customer-data' })

View File

@@ -2,8 +2,8 @@ import { createRouter, createWebHistory } from 'vue-router'
import { currentLang, langs } from './langs' import { currentLang, langs } from './langs'
import { getSettings } from './settings' import { getSettings } from './settings'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
import Default from '@/layouts/default.vue' // import Default from '@/layouts/default.vue'
import { getMenu } from './menu' // import { getMenu } from './menu'
function isAuthenticated(): boolean { function isAuthenticated(): boolean {
@@ -34,7 +34,7 @@ const router = createRouter({
{ path: 'create-account', component: () => import('@/components/customer/PageCreateAccount.vue'), name: 'create-account' }, { path: 'create-account', component: () => import('@/components/customer/PageCreateAccount.vue'), name: 'create-account' },
{ path: 'cart', component: () => import('@/components/customer/PageCart.vue'), name: 'cart' }, { path: 'cart', component: () => import('@/components/customer/PageCart.vue'), name: 'cart' },
{ path: 'cart1', component: () => import('@/components/customer/Cart1.vue'), name: 'cart1' }, { path: 'cart1', component: () => import('@/components/customer/Cart1.vue'), name: 'cart1' },
{ path: 'products-list', component: () => import('@/components/customer/PageProductsList.vue'), name: 'products-list' }, { path: 'products-list', component: () => import('@/components/admin/PageProductsList.vue'), name: 'products-list' },
{ path: 'login', component: () => import('@/views/LoginView.vue'), name: 'login', meta: { guest: true, } }, { path: 'login', component: () => import('@/views/LoginView.vue'), name: 'login', meta: { guest: true, } },
{ path: 'register', component: () => import('@/views/RegisterView.vue'), name: 'register', meta: { guest: true } }, { path: 'register', component: () => import('@/views/RegisterView.vue'), name: 'register', meta: { guest: true } },
{ path: 'password-recovery', component: () => import('@/views/PasswordRecoveryView.vue'), name: 'password-recovery', meta: { guest: true } }, { path: 'password-recovery', component: () => import('@/views/PasswordRecoveryView.vue'), name: 'password-recovery', meta: { guest: true } },

View File

@@ -1,6 +1,7 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { ref } from 'vue' import { ref } from 'vue'
import { useFetchJson } from '@/composable/useFetchJson' import { useFetchJson } from '@/composable/useFetchJson'
import type { ProductDescription } from '@/types/product'
export interface Product { export interface Product {
id: number id: number
@@ -27,25 +28,29 @@ export const useProductStore = defineStore('product', () => {
const loading = ref(false) const loading = ref(false)
const error = ref<string | null>(null) const error = ref<string | null>(null)
async function getProductDescription(langId: number = 1) { async function getProductDescription(langId = 1, productID: number) {
loading.value = true loading.value = true
error.value = null error.value = null
try { try {
const response = await useFetchJson(`/api/v1/restricted/product-description/get-product-description?productID=51&productShopID=1&productLangID=${langId}`) const response = await useFetchJson<ProductDescription>(
productDescription.value = response `/api/v1/restricted/product-description/get-product-description?productID=${productID}&productLangID=${langId}`
} catch (e: any) { )
error.value = e?.message || 'Failed to load product description' console.log(response, 'dfsfsdf');
console.error('Failed to fetch product description:', e) productDescription.value = response.items
} catch (e: unknown) {
error.value = e instanceof Error ? e.message : 'Failed to load product description'
} finally { } finally {
loading.value = false loading.value = false
} }
} }
async function saveProductDescription() { async function saveProductDescription(productID?: number) {
const id = productID || 1
try { try {
const data = await useFetchJson( const data = await useFetchJson(
`/api/v1/restricted/product-description/save-product-description?productID=1&productShopID=1&productLangID=1`, `/api/v1/restricted/product-description/save-product-description?productID=${id}&productShopID=1&productLangID=1`,
{ {
method: 'POST', method: 'POST',
body: JSON.stringify( body: JSON.stringify(
@@ -64,14 +69,14 @@ export const useProductStore = defineStore('product', () => {
} }
} }
async function translateProductDescription(fromLangId: number, toLangId: number) { async function translateProductDescription(productID: number, fromLangId: number, toLangId: number) {
loading.value = true loading.value = true
error.value = null error.value = null
try { try {
const response = await useFetchJson(`/api/v1/restricted/product-description/translate-product-description?productID=51&productShopID=1&productFromLangID=${fromLangId}&productToLangID=${toLangId}&model=OpenAI`) const response = await useFetchJson<ProductDescription>(`/api/v1/restricted/product-description/translate-product-description?productID=${productID}&productShopID=1&productFromLangID=${fromLangId}&productToLangID=${toLangId}&model=OpenAI`)
productDescription.value = response productDescription.value = response.items
return response return response.items
} catch (e: any) { } catch (e: any) {
error.value = e?.message || 'Failed to translate product description' error.value = e?.message || 'Failed to translate product description'
console.error('Failed to translate product description:', e) console.error('Failed to translate product description:', e)

9
bo/src/types/product.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
export interface ProductDescription {
id?: number
name?: string
description: string
description_short: string
meta_description: string
available_now: string
usage: string
}

View File

@@ -2,7 +2,7 @@
<component :is="Default || 'div'"> <component :is="Default || 'div'">
<div class="container mt-24"> <div class="container mt-24">
<div class="row"> <div class="row">
<div class="col-12"> <!-- <div class="col-12">
<h2 class="text-2xl">Category ID: {{ $route.params.category_id }}</h2> <h2 class="text-2xl">Category ID: {{ $route.params.category_id }}</h2>
<div v-for="(p, i) in products" :key="i"> <div v-for="(p, i) in products" :key="i">
<p> <p>
@@ -10,7 +10,7 @@
<span class="border-b-1 bg-red-100 px-4">{{ p.price }}</span> <span class="border-b-1 bg-red-100 px-4">{{ p.price }}</span>
</p> </p>
</div> </div>
</div> </div> -->
</div> </div>
</div> </div>
</component> </component>
@@ -34,7 +34,7 @@ const products = ref([])
watch(() => route.params, async (n) => { watch(() => route.params, async (n) => {
categoryStore.setCategoryID(parseInt(n.category_id as string)) categoryStore.setCategoryID(parseInt(n.category_id as string))
const res = await categoryStore.getCategoryProducts() const res = await categoryStore.getCategoryProducts()
products.value = res // products.value = res
}, { immediate: true }) }, { immediate: true })

View File

@@ -126,13 +126,13 @@ CREATE INDEX IF NOT EXISTS idx_refresh_tokens_customer_id ON b2b_refresh_tokens
CREATE TABLE IF NOT EXISTS b2b_countries ( CREATE TABLE IF NOT EXISTS b2b_countries (
id INT AUTO_INCREMENT PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(128) NOT NULL, name VARCHAR(128) NOT NULL,
currency INT UNSIGNED NOT NULL, currency_id INT UNSIGNED NOT NULL,
flag VARCHAR(16) NOT NULL, flag VARCHAR(16) NOT NULL,
CONSTRAINT fk_countries_currency FOREIGN KEY (currency) REFERENCES ps_currency(id_currency) ON DELETE RESTRICT ON UPDATE RESTRICT CONSTRAINT fk_countries_currency FOREIGN KEY (currency_id) REFERENCES ps_currency(id_currency) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT IGNORE INTO b2b_countries INSERT IGNORE INTO b2b_countries
(id, name, currency, flag) (id, name, currency_id, flag)
VALUES VALUES
(1, 'Polska', 1, '🇵🇱'), (1, 'Polska', 1, '🇵🇱'),
(2, 'England', 2, '🇬🇧'), (2, 'England', 2, '🇬🇧'),