@rocketsearch/vue-uappi 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocketsearch/vue-uappi",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Rocket Search para storefronts Uappi em Vue 3 + Vite + Pinia: busca, autocomplete, vitrines, banners e eventos",
5
5
  "type": "module",
6
6
  "main": "index.js",
package/runtime/banner.js CHANGED
@@ -125,6 +125,12 @@ export function pickVideoUrl (content, win) {
125
125
  return probe.canPlayType && probe.canPlayType('video/' + ext[1].toLowerCase()) ? url : '';
126
126
  }
127
127
 
128
+ // Mesmo slug do painel (slugifyMenuKey): "Refrigeração Comercial" -> "refrigeracao-comercial".
129
+ export function slugKey (value) {
130
+ return String(value || '').trim().toLowerCase().normalize('NFD').replace(/\p{M}/gu, '')
131
+ .replace(/\s+/g, '-').replace(/[^a-z0-9_-]/g, '').replace(/^[-_]+/, '').slice(0, 63);
132
+ }
133
+
128
134
  export function isHeroSlot (position) {
129
135
  return /^(hero|fullbanner|header|top)$/i.test(String(position || ''));
130
136
  }
@@ -28,16 +28,22 @@
28
28
  import '../css/common.css';
29
29
  import '../css/banner.css';
30
30
  import RocketBannerItem from './banner/RocketBannerItem.vue';
31
- import { exactWidth, isHeroSlot } from '../banner.js';
31
+ import { MOBILE_MEDIA, exactWidth, isHeroSlot, slugKey } from '../banner.js';
32
32
 
33
33
  const positionOf = b => (b && ((b.placement && b.placement.position) || b.position)) || '';
34
34
 
35
35
  export default {
36
36
  name: 'RocketBanner',
37
37
  components: { RocketBannerItem },
38
+ // loaded(banners): a lista que o slot vai mostrar ([] = nada na posição) — para o tema ajustar o
39
+ // layout em volta (ex.: colunas do megamenu com ou sem banner).
40
+ emits: ['loaded'],
38
41
  props: {
39
42
  // placement.position cadastrada no painel (hero, top, middle...). Obrigatória fora da landing.
40
43
  position: { type: String, default: '' },
44
+ // Posição menu: aba do megamenu (banner.menuKey no painel). Aceita o rótulo da aba
45
+ // ("Refrigeração Comercial"), comparado pelo mesmo slug do painel.
46
+ menuKey: { type: String, default: '' },
41
47
  // eager: busca assim que a página tem contexto (hero/LCP). ondemand: só quando o slot
42
48
  // chega perto da viewport.
43
49
  loading: {
@@ -56,6 +62,9 @@ export default {
56
62
  // Mais de um banner na posição: carrossel (senão empilham na ordem do BE).
57
63
  carousel: { type: Boolean, default: false },
58
64
  sizes: { type: String, default: '100vw' },
65
+ // Onde vale a imagem mobile do painel. Slot que só existe no layout mobile do tema (ex.: menu
66
+ // mobile até 1340px) passa "all"; o padrão segue o breakpoint de 768px.
67
+ mobileMedia: { type: String, default: MOBILE_MEDIA },
59
68
  rootMargin: { type: String, default: '200px' },
60
69
  imageResizing: { type: Boolean, default: true }
61
70
  },
@@ -84,6 +93,12 @@ export default {
84
93
  this.requested = false;
85
94
  this.tryLoad();
86
95
  },
96
+ // Outra aba no mesmo slot (menu mobile): refiltra — a posição vem do cache.
97
+ menuKey () {
98
+ if (!this.requested) return;
99
+ this.requested = false;
100
+ this.tryLoad();
101
+ },
87
102
  // O contexto da página chega pelo currentPageData do tema (o plugin traduz para $rocket.setPage).
88
103
  '$rocket.currentPage.value' () {
89
104
  if (this.loading === 'eager' || this.visible) this.tryLoad();
@@ -111,19 +126,24 @@ export default {
111
126
  if (this.requested) return;
112
127
  if (!this.pageType && !this.$rocket.getPage().section) return;
113
128
  this.requested = true;
114
- // Largura exata do slot; sem medida a imagem sai com srcset.
115
- if (this.$el && this.$el.clientWidth) {
129
+ // Largura exata do slot (um banner ocupando o slot todo); sem medida a imagem sai com srcset.
130
+ // Com sizes próprio (vários banners lado a lado, ex.: cartões de categoria), fica o srcset e o
131
+ // navegador escolhe pela largura de cada um — medir o slot pediria a imagem larga para todos.
132
+ if (this.sizes === '100vw' && this.$el && this.$el.clientWidth) {
116
133
  this.width = exactWidth(this.$el.clientWidth, window.devicePixelRatio);
117
134
  }
118
135
  const key = this.landingKey;
136
+ const menuKey = this.menuKey;
119
137
  const list = this.pageType === 'custom'
120
138
  ? (key ? await this.$rocket.getBannersByContext('custom', { customKey: key }) : [])
121
139
  : await this.$rocket.getBannersByContext(this.pageType || undefined, { position: this.position });
122
- // Troca rápida de landing: a resposta da anterior não sobrescreve a atual.
123
- if (key !== this.landingKey) return;
124
- const mine = this.pageType === 'custom' ? list : list.filter(b => positionOf(b) === this.position);
140
+ // Troca rápida de landing/aba: a resposta da anterior não sobrescreve a atual.
141
+ if (key !== this.landingKey || menuKey !== this.menuKey) return;
142
+ let mine = this.pageType === 'custom' ? list : list.filter(b => positionOf(b) === this.position);
143
+ if (menuKey) mine = mine.filter(b => slugKey(b.banner && b.banner.menuKey) === slugKey(menuKey));
125
144
  this.banners = this.limit > 0 ? mine.slice(0, this.limit) : mine;
126
145
  this.waiting = false;
146
+ this.$emit('loaded', this.banners);
127
147
  },
128
148
 
129
149
  itemProps (index) {
@@ -138,7 +158,8 @@ export default {
138
158
  sizes: this.sizes,
139
159
  width: this.width,
140
160
  imageResizing: this.imageResizing,
141
- aspectRatio: this.ratio ? this.ratioCss : ''
161
+ aspectRatio: this.ratio ? this.ratioCss : '',
162
+ mobileMedia: this.mobileMedia
142
163
  };
143
164
  },
144
165
 
@@ -185,7 +185,7 @@ import '../css/search.css';
185
185
  import RocketSearchFacets from './search/RocketSearchFacets.vue';
186
186
  import RocketSearchPagination from './search/RocketSearchPagination.vue';
187
187
  import { productImage, productPath, productPrice, formatCurrency } from '../uappi.js';
188
- import { TRACKING_PARAMS, didYouMeanQuery, dispatchDidYouMeanClick, ratingLabel } from '../listing.js';
188
+ import { TRACKING_PARAMS, gridClickMeta, didYouMeanQuery, dispatchDidYouMeanClick, ratingLabel } from '../listing.js';
189
189
 
190
190
  // Parâmetros de campanha nunca viram filtro na busca.
191
191
  function emptyContext () {
@@ -511,7 +511,7 @@ export default {
511
511
  this.$rocket.dispatchEvent('click', {
512
512
  productId: String(product.id),
513
513
  position: index,
514
- meta: { source: 'search-page', query: this.term || '' }
514
+ meta: gridClickMeta(this.term, this.isCategory && this.categoryId)
515
515
  }).catch(() => {});
516
516
  }
517
517
  }
@@ -75,10 +75,12 @@ export default {
75
75
  // Largura exata (px) medida do slot; 0 = usa srcset.
76
76
  width: { type: Number, default: 0 },
77
77
  imageResizing: { type: Boolean, default: true },
78
- aspectRatio: { type: String, default: '' }
78
+ aspectRatio: { type: String, default: '' },
79
+ // Media query em que vale a imagem mobile (ver RocketBanner).
80
+ mobileMedia: { type: String, default: MOBILE_MEDIA }
79
81
  },
80
82
  data () {
81
- return { naturalRatio: null, resizeFailed: false, mobileMedia: MOBILE_MEDIA, videoSrc: '', videoPlaying: false };
83
+ return { naturalRatio: null, resizeFailed: false, videoSrc: '', videoPlaying: false };
82
84
  },
83
85
  computed: {
84
86
  content () {
@@ -221,7 +223,7 @@ export default {
221
223
  },
222
224
 
223
225
  imageVariant () {
224
- const narrow = window.matchMedia && window.matchMedia(MOBILE_MEDIA).matches;
226
+ const narrow = window.matchMedia && window.matchMedia(this.mobileMedia).matches;
225
227
  if (narrow && this.content.mobileImageUrl) return 'mobile';
226
228
  if (this.content.imageUrl) return 'desktop';
227
229
  return this.content.mobileImageUrl ? 'mobile' : undefined;
@@ -231,7 +231,8 @@ export function mergeIntoUappiPage (base, listing) {
231
231
  export async function rocketCategoryListing ({ $rocket, categoryId, query, limit, base, path }) {
232
232
  const params = Object.assign(toRocketParams(query, limit), { categoryId });
233
233
  const response = await $rocket.search(params);
234
- return mergeIntoUappiPage(base, await withUappiProducts($rocket, response, query, { limit, path }));
234
+ const listing = mergeIntoUappiPage(base, await withUappiProducts($rocket, response, query, { limit, path }));
235
+ return Object.assign(listing, { rocketCategory: true });
235
236
  }
236
237
 
237
238
  /** Coleção do painel pelo slug. null quando a Rocket não tem essa coleção no ar. */
@@ -242,7 +243,8 @@ export async function rocketCollectionListing ({ $rocket, slug, query, limit, ba
242
243
  const response = await $rocket.collection(slug, params);
243
244
  if (!response) return null;
244
245
  const defaultSort = response.sortOptions && response.sortOptions[0] && response.sortOptions[0].id;
245
- return mergeIntoUappiPage(base, await withUappiProducts($rocket, response, query, { limit, path, defaultSort }));
246
+ const listing = mergeIntoUappiPage(base, await withUappiProducts($rocket, response, query, { limit, path, defaultSort }));
247
+ return Object.assign(listing, { rocketCollection: slug });
246
248
  }
247
249
 
248
250
  export function dispatchListingSearch ($rocket, listing) {
@@ -278,11 +280,26 @@ export function dispatchDidYouMeanClick ($rocket, { from, suggestion, source })
278
280
  }).catch(() => {});
279
281
  }
280
282
 
283
+ // Contrato de eventos (spec 082): com termo é busca; grade sem termo (categoria, catálogo) é
284
+ // 'category-page' — 'search-page' vazio inflava a receita "Busca".
285
+ export function gridClickMeta (query, categoryId, collection) {
286
+ const term = String(query || '').trim();
287
+ if (term) return { source: 'search-page', query: term };
288
+ const meta = { source: 'category-page' };
289
+ if (categoryId) meta.categoryId = String(categoryId);
290
+ if (collection) meta.collection = collection;
291
+ return meta;
292
+ }
293
+
294
+ // Só grade servida pela Rocket (marcada por rocketSearchListing / rocketCategoryListing /
295
+ // rocketCollectionListing): a listagem de reserva da Uappi não é clique Rocket.
281
296
  export function dispatchListingClick ($rocket, listing, product, position) {
297
+ if (!listing || !(listing.rocketSearch || listing.rocketCategory || listing.rocketCollection)) return;
282
298
  if (!product || product.id == null) return;
299
+ const categoria = listing.conteudo && listing.conteudo.categoria;
283
300
  $rocket.dispatchEvent('click', {
284
301
  productId: String(product.id),
285
302
  position,
286
- meta: { source: 'search-page', query: (listing && listing.rocketSearch && listing.rocketSearch.query) || '' }
303
+ meta: gridClickMeta(listing.rocketSearch && listing.rocketSearch.query, categoria && categoria.id, listing.rocketCollection)
287
304
  }).catch(() => {});
288
305
  }
package/runtime/rocket.js CHANGED
@@ -16,7 +16,11 @@ const SHOWCASE_ATTR_TTL = 30 * 60 * 1000;
16
16
  // Mapa persistente produto -> vitrine (last-touch por produto). Diferente do slot único,
17
17
  // NÃO é apagado no add_to_cart: sobrevive até o checkout para atribuir GMV no purchase.
18
18
  const SHOWCASE_ATTR_MAP_KEY = 'rs_showcase_attr_map';
19
- const SEARCH_ATTR_KEY = 'rs_search_attr';
19
+ // Mapa produto -> origem do último clique em grade/autocomplete (search-page, category-page,
20
+ // autocomplete). Por produto, não por sessão (spec 082): o slot único de antes fazia todo
21
+ // view/add_to_cart dos 30 min seguintes herdar a origem de um clique em outro produto.
22
+ const SEARCH_ATTR_MAP_KEY = 'rs_search_attr_map';
23
+ const SEARCH_ATTR_SOURCES = ['autocomplete', 'search-page', 'category-page'];
20
24
  const PENDING_CART_EVENTS_KEY = 'rs_pending_add_to_cart_events';
21
25
  const ANON_SESSION_KEY = 'rs_anon_session_id';
22
26
  const ANON_SESSION_TTL = 30 * 60 * 1000;
@@ -333,24 +337,44 @@ export function createRocket (config) {
333
337
 
334
338
  // Só banners (DTO banner-native). Gated pela flag `banners`: loja sem ela recebe [].
335
339
  // options.customKey: identificador da landing (pageType=custom); sem ele a API responde 400.
336
- rocket.getBannersByContext = async function (type, options) {
340
+ // A resposta não depende da categoria/produto da página, só de pageType + posição + landing: fica
341
+ // 5 min em cache. O slot que remonta (dropdown do menu, que monta a cada hover) não chama a API de
342
+ // novo, e o banner agendado que acaba ainda sai do ar sem recarregar a página. Falha não fica.
343
+ const BANNER_TTL = 5 * 60 * 1000;
344
+ const bannerCache = {};
345
+ rocket.getBannersByContext = function (type, options) {
337
346
  const pageType = resolvePageType(type);
338
- if (!pageType) return [];
347
+ if (!pageType) return Promise.resolve([]);
339
348
  const opts = options || {};
349
+ const customKey = pageType === 'custom' ? opts.customKey : undefined;
350
+ const key = pageType + '|' + (opts.position || '') + '|' + (customKey || '');
351
+ const hit = bannerCache[key];
352
+ if (hit && Date.now() - hit.at < BANNER_TTL) return hit.list;
353
+ const list = fetchBanners(pageType, opts.position, customKey).then((banners) => {
354
+ if (banners) return banners;
355
+ delete bannerCache[key];
356
+ return [];
357
+ });
358
+ bannerCache[key] = { list, at: Date.now() };
359
+ return list;
360
+ };
361
+
362
+ // null = falhou (não entra no cache).
363
+ async function fetchBanners (pageType, position, customKey) {
340
364
  try {
341
365
  const sessionId = await getSessionIdWithTimeout();
342
- const params = { storeId: config.storeId, pageType, sessionId, position: opts.position };
343
- if (pageType === 'custom') params.customKey = opts.customKey;
366
+ const params = { storeId: config.storeId, pageType, sessionId, position };
367
+ if (pageType === 'custom') params.customKey = customKey;
344
368
  const res = await fetch(config.apiUrl + '/banners/context?' + query(params), { headers: headers() });
345
- if (!res.ok) return [];
369
+ if (!res.ok) return null;
346
370
  const banners = await res.json();
347
371
  return Array.isArray(banners) ? banners : [];
348
372
  }
349
373
  catch (e) {
350
374
  // Banner é conteúdo promocional — falha não pode quebrar a página.
351
- return [];
375
+ return null;
352
376
  }
353
- };
377
+ }
354
378
 
355
379
  // ---- Atribuição (sessionStorage) ----
356
380
 
@@ -381,24 +405,26 @@ export function createRocket (config) {
381
405
  return attr;
382
406
  }
383
407
 
384
- function saveShowcaseAttributionEntry (showcaseId, productId, position) {
385
- if (!showcaseId || productId == null || productId === '') return;
386
- const map = storageGet(SHOWCASE_ATTR_MAP_KEY) || {};
408
+ // Last-touch por produto; poda as entradas expiradas para o mapa não crescer na sessão.
409
+ function saveAttributionEntry (key, productId, entry) {
410
+ if (productId == null || productId === '') return;
411
+ const map = storageGet(key) || {};
387
412
  const now = Date.now();
388
- Object.keys(map).forEach((key) => {
389
- if (!map[key] || !map[key].ts || now - map[key].ts > SHOWCASE_ATTR_TTL) delete map[key];
413
+ Object.keys(map).forEach((k) => {
414
+ if (!map[k] || !map[k].ts || now - map[k].ts > SHOWCASE_ATTR_TTL) delete map[k];
390
415
  });
391
- map[String(productId)] = { showcaseId, position: position != null && position >= 0 ? position : null, ts: now };
392
- storageSet(SHOWCASE_ATTR_MAP_KEY, map);
416
+ map[String(productId)] = Object.assign(entry, { ts: now });
417
+ storageSet(key, map);
393
418
  }
394
419
 
395
- function getSearchAttribution () {
396
- const attr = storageGet(SEARCH_ATTR_KEY);
397
- if (!attr || !attr.ts || Date.now() - attr.ts > SHOWCASE_ATTR_TTL) {
398
- storageRemove(SEARCH_ATTR_KEY);
399
- return null;
400
- }
401
- return attr;
420
+ function saveShowcaseAttributionEntry (showcaseId, productId, position) {
421
+ if (!showcaseId) return;
422
+ saveAttributionEntry(SHOWCASE_ATTR_MAP_KEY, productId, { showcaseId, position: position != null && position >= 0 ? position : null });
423
+ }
424
+
425
+ function getSearchAttribution (productId) {
426
+ const entry = productId != null ? (storageGet(SEARCH_ATTR_MAP_KEY) || {})[String(productId)] : null;
427
+ return entry && entry.ts && Date.now() - entry.ts <= SHOWCASE_ATTR_TTL ? entry : null;
402
428
  }
403
429
 
404
430
  rocket.getShowcaseAttribution = getShowcaseAttribution;
@@ -428,8 +454,8 @@ export function createRocket (config) {
428
454
  });
429
455
  saveShowcaseAttributionEntry(data.vitrine, data.productId, data.position);
430
456
  }
431
- if (eventType === 'click' && (data.meta.source === 'autocomplete' || data.meta.source === 'search-page')) {
432
- storageSet(SEARCH_ATTR_KEY, { source: data.meta.source, ts: Date.now() });
457
+ if (eventType === 'click' && SEARCH_ATTR_SOURCES.includes(data.meta.source)) {
458
+ saveAttributionEntry(SEARCH_ATTR_MAP_KEY, data.productId, { source: data.meta.source });
433
459
  }
434
460
 
435
461
  const sessionId = await rocket.getSessionId();
@@ -530,10 +556,8 @@ export function createRocket (config) {
530
556
  rocket.fireProductView = function () {
531
557
  if (!page.productId) return;
532
558
  const viewData = { productId: page.productId };
533
- const showcaseAttr = getShowcaseAttribution(page.productId);
534
- const searchAttr = getSearchAttribution();
535
- if (showcaseAttr && showcaseAttr.showcaseId) viewData.meta = { source: 'showcase:' + showcaseAttr.showcaseId };
536
- else if (searchAttr && searchAttr.source) viewData.meta = { source: searchAttr.source };
559
+ const source = resolveProductSource(page.productId);
560
+ if (source) viewData.meta = { source };
537
561
  rocket.dispatchEvent('view', viewData).catch(() => {});
538
562
  };
539
563
 
@@ -583,11 +607,13 @@ export function createRocket (config) {
583
607
  return cached != null ? cached : null;
584
608
  }
585
609
 
586
- function resolveProductSource (productId, attr, searchAttr) {
610
+ // Origem só com clique NESTE produto: vitrine ou grade/autocomplete. Produto que apenas
611
+ // apareceu na grade (searchPriceCache) não ganha origem.
612
+ function resolveProductSource (productId) {
613
+ const attr = getShowcaseAttribution(productId);
587
614
  if (attr && attr.showcaseId) return 'showcase:' + attr.showcaseId;
588
- if (searchAttr && searchAttr.source) return searchAttr.source;
589
- if (searchPriceCache[String(productId)] != null) return 'search-page';
590
- return null;
615
+ const searchAttr = getSearchAttribution(productId);
616
+ return searchAttr ? searchAttr.source : null;
591
617
  }
592
618
 
593
619
  rocket.trackAddToCart = function (payload) {
@@ -602,7 +628,6 @@ export function createRocket (config) {
602
628
  if (!products.length) return;
603
629
 
604
630
  const attr = getShowcaseAttribution(products[0].productId);
605
- const searchAttr = getSearchAttribution();
606
631
  const experiment = attr && attr.experimentId != null
607
632
  ? { experimentId: attr.experimentId, variantId: attr.variantId != null ? attr.variantId : null }
608
633
  : {};
@@ -611,7 +636,7 @@ export function createRocket (config) {
611
636
  const p = products[0];
612
637
  const meta = { quantity: p.quantity };
613
638
  const price = resolveProductPrice(p.productId, attr);
614
- const source = resolveProductSource(p.productId, attr, searchAttr);
639
+ const source = resolveProductSource(p.productId);
615
640
  if (source) meta.source = source;
616
641
  if (price != null) meta.totalValue = price * p.quantity;
617
642
  const eventData = Object.assign({ productId: p.productId, meta }, experiment);
@@ -624,7 +649,7 @@ export function createRocket (config) {
624
649
  if (p.skuId) item.skuId = p.skuId;
625
650
  const price = resolveProductPrice(p.productId, attr);
626
651
  if (price != null) item.totalValue = price * p.quantity;
627
- const source = resolveProductSource(p.productId, attr, searchAttr);
652
+ const source = resolveProductSource(p.productId);
628
653
  if (source) item.source = source;
629
654
  if (attr && attr.showcaseId && String(attr.productId) === String(p.productId)) item.showcaseId = Number(attr.showcaseId);
630
655
  return item;