-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathproducts.go
More file actions
259 lines (224 loc) · 7.34 KB
/
Copy pathproducts.go
File metadata and controls
259 lines (224 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package appie
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
)
// searchResponse matches the API response for product search
type searchResponse struct {
Products []productResponse `json:"products"`
Page struct {
Number int `json:"number"`
Size int `json:"size"`
TotalElements int `json:"totalElements"`
TotalPages int `json:"totalPages"`
} `json:"page"`
}
type productResponse struct {
WebshopID int `json:"webshopId"`
HqID int `json:"hqId"`
Title string `json:"title"`
Brand string `json:"brand"`
SalesUnitSize string `json:"salesUnitSize"`
UnitPriceDescription string `json:"unitPriceDescription"`
Images []Image `json:"images"`
CurrentPrice float64 `json:"currentPrice"`
PriceBeforeBonus float64 `json:"priceBeforeBonus"`
IsBonus bool `json:"isBonus"`
BonusMechanism string `json:"bonusMechanism"`
MainCategory string `json:"mainCategory"`
SubCategory string `json:"subCategory"`
NutriScore string `json:"nutriscore"`
AvailableOnline bool `json:"availableOnline"`
IsPreviouslyBought bool `json:"isPreviouslyBought"`
IsOrderable bool `json:"isOrderable"`
PropertyIcons []string `json:"propertyIcons"`
}
// GraphQL query for fetching product nutritional info via tradeItem
const fetchProductNutritionQuery = `query FetchProduct($productId: Int!) {
product(id: $productId) {
id
tradeItem {
nutritions {
nutrients {
type
name
value
}
}
}
}
}`
type productNutritionResponse struct {
Product struct {
ID int `json:"id"`
TradeItem *struct {
Nutritions []struct {
Nutrients []struct {
Type string `json:"type"`
Name string `json:"name"`
Value string `json:"value"`
} `json:"nutrients"`
} `json:"nutritions"`
} `json:"tradeItem"`
} `json:"product"`
}
func (p *productResponse) toProduct() Product {
price := p.CurrentPrice
if price == 0 {
price = p.PriceBeforeBonus
}
return Product{
ID: p.WebshopID,
WebshopID: strconv.Itoa(p.WebshopID),
Title: p.Title,
Brand: p.Brand,
Category: p.MainCategory,
SubCategory: p.SubCategory,
Price: Price{Now: price, Was: p.PriceBeforeBonus},
Images: p.Images,
NutriScore: p.NutriScore,
IsBonus: p.IsBonus,
BonusMechanism: p.BonusMechanism,
IsAvailable: p.AvailableOnline,
IsOrderable: p.IsOrderable,
IsPreviouslyBought: p.IsPreviouslyBought,
UnitSize: p.SalesUnitSize,
UnitPriceDescription: p.UnitPriceDescription,
PropertyIcons: p.PropertyIcons,
}
}
// SearchProducts searches for products by query string and returns up to limit results.
// If limit is 0 or negative, defaults to 30 products.
//
// Example:
//
// products, err := client.SearchProducts(ctx, "melk", 10)
func (c *Client) SearchProducts(ctx context.Context, query string, limit int) ([]Product, error) {
return c.SearchProductsFiltered(ctx, SearchOptions{Query: query, Limit: limit})
}
// GetProduct retrieves a single product by its webshopId.
// For nutritional information, use GetProductFull instead.
func (c *Client) GetProduct(ctx context.Context, productID int) (*Product, error) {
path := fmt.Sprintf("/mobile-services/product/detail/v4/fir/%d", productID)
var result struct {
ProductID int `json:"productId"`
ProductCard productResponse `json:"productCard"`
}
if err := c.DoRequest(ctx, http.MethodGet, path, nil, &result); err != nil {
return nil, fmt.Errorf("get product failed: %w", err)
}
product := result.ProductCard.toProduct()
return &product, nil
}
// GetProductFull retrieves a product with full details including nutritional info.
// This makes an additional GraphQL call for nutritional data.
func (c *Client) GetProductFull(ctx context.Context, productID int) (*Product, error) {
product, err := c.GetProduct(ctx, productID)
if err != nil {
return nil, err
}
nutritionInfo, err := c.fetchNutritionalInfo(ctx, productID)
if err != nil {
return nil, fmt.Errorf("get product nutrition failed: %w", err)
}
product.NutritionalInfo = nutritionInfo
return product, nil
}
// fetchNutritionalInfo fetches nutritional data for a product via GraphQL.
func (c *Client) fetchNutritionalInfo(ctx context.Context, productID int) ([]NutritionalInfo, error) {
variables := map[string]any{
"productId": productID,
}
var resp productNutritionResponse
if err := c.DoGraphQL(ctx, fetchProductNutritionQuery, variables, &resp); err != nil {
return nil, err
}
if resp.Product.TradeItem == nil || len(resp.Product.TradeItem.Nutritions) == 0 {
return nil, nil
}
var nutritionalInfo []NutritionalInfo
for _, nutrition := range resp.Product.TradeItem.Nutritions {
for _, n := range nutrition.Nutrients {
nutritionalInfo = append(nutritionalInfo, NutritionalInfo{
Name: n.Name,
Type: n.Type,
Value: n.Value,
})
}
}
return nutritionalInfo, nil
}
// SearchOptions configures a product search.
type SearchOptions struct {
Query string // Search term
Limit int // Max results (default 30)
Bonus bool // Only return products currently on bonus/promotion
}
// SearchProductsFiltered searches for products using the REST API.
// When Bonus is true, over-fetches and filters client-side to return
// up to Limit bonus products.
func (c *Client) SearchProductsFiltered(ctx context.Context, opts SearchOptions) ([]Product, error) {
limit := opts.Limit
if limit <= 0 {
limit = 30
}
var products []Product
page := 0
pageSize := limit
if opts.Bonus {
pageSize = limit * 5
}
for len(products) < limit {
params := url.Values{}
params.Set("query", opts.Query)
params.Set("page", strconv.Itoa(page))
params.Set("size", strconv.Itoa(pageSize))
params.Set("sortOn", "RELEVANCE")
path := "/mobile-services/product/search/v2?" + params.Encode()
var result searchResponse
if err := c.DoRequest(ctx, http.MethodGet, path, nil, &result); err != nil {
return nil, fmt.Errorf("search products failed: %w", err)
}
for _, p := range result.Products {
prod := p.toProduct()
if opts.Bonus && !prod.IsBonus {
continue
}
products = append(products, prod)
if len(products) >= limit {
break
}
}
// Stop if we've exhausted all results
if (page+1)*pageSize >= result.Page.TotalElements {
break
}
page++
}
return products, nil
}
// GetProductsByIDs retrieves multiple products by their webshopIds in a single request.
// Products are returned in the same order as the input IDs.
func (c *Client) GetProductsByIDs(ctx context.Context, productIDs []int) ([]Product, error) {
if len(productIDs) == 0 {
return nil, nil
}
params := url.Values{}
for _, id := range productIDs {
params.Add("ids", strconv.Itoa(id))
}
params.Set("sortOn", "INPUT_PRODUCT_IDS")
path := "/mobile-services/product/search/v2/products?" + params.Encode()
var result []productResponse
if err := c.DoRequest(ctx, http.MethodGet, path, nil, &result); err != nil {
return nil, fmt.Errorf("get products by ids failed: %w", err)
}
products := make([]Product, 0, len(result))
for _, p := range result {
products = append(products, p.toProduct())
}
return products, nil
}