@azzas/azzas-tracker-web 1.0.80 → 1.0.82
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/README.md +130 -130
- package/dist/mod.cjs +178 -4
- package/dist/mod.cjs.map +1 -1
- package/dist/mod.d.cts +0 -0
- package/dist/mod.d.ts +0 -0
- package/dist/mod.global.js +178 -4
- package/dist/mod.global.js.map +1 -1
- package/dist/mod.js +178 -4
- package/dist/mod.js.map +1 -1
- package/dist/mod.vtex.global.js +227 -44
- package/package.json +38 -38
package/README.md
CHANGED
|
@@ -1,130 +1,130 @@
|
|
|
1
|
-
# azzas-tracker-web
|
|
2
|
-
|
|
3
|
-
Pacote interno para **Data Tracking** das lojas WEB, centralizando a captura e envio de eventos para diferentes plataformas de mídia (Meta, Dito, DataLayer, etc).
|
|
4
|
-
|
|
5
|
-
O objetivo é fornecer uma **camada única e consistente de tracking**, garantindo que todos os eventos sejam tratados, formatados e enviados de forma confiável.
|
|
6
|
-
|
|
7
|
-
E, principalmente, centralizar a complexidade e a “inteligência” de tracking **fora dos repositórios das lojas**.
|
|
8
|
-
|
|
9
|
-
---
|
|
10
|
-
|
|
11
|
-
## Fluxo do Tracking
|
|
12
|
-
|
|
13
|
-
O pacote segue o seguinte fluxo de eventos:
|
|
14
|
-
|
|
15
|
-
1. **User Action**
|
|
16
|
-
Ações do usuário na loja (ex: adicionar ao carrinho, iniciar checkout, finalizar compra).
|
|
17
|
-
|
|
18
|
-
2. **Tracks**
|
|
19
|
-
Ponto central que recebe o contexto do evento vindo da ação do usuário e encaminha para o *Formatter*.
|
|
20
|
-
|
|
21
|
-
3. **Formatter**
|
|
22
|
-
Acessa a constante `EVENTS` e, baseado no contexto do evento, puxa os parâmetros obrigatórios e entrega a biblioteca de parâmetros (`/params`).
|
|
23
|
-
|
|
24
|
-
4. **Params Library**
|
|
25
|
-
Contém **getters** e **resolvers** que garantem que os dados sejam legítimos e que todos os parâmetros sejam corretamente tratados.
|
|
26
|
-
|
|
27
|
-
5. **Adapters**
|
|
28
|
-
Módulos responsáveis por enviar os dados formatados para cada destino (Meta, Datalayer, Dito, etc).
|
|
29
|
-
|
|
30
|
-

|
|
31
|
-
|
|
32
|
-
## Instalação
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
```bash
|
|
36
|
-
npm install /path/azzas-tracker-web
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
## Exemplos
|
|
41
|
-
|
|
42
|
-
Listagem dos `EVENTS` e função orquestradora `trackWebEvent`:
|
|
43
|
-
```javascript
|
|
44
|
-
const EVENTS = {
|
|
45
|
-
ADD_PERSONAL_INFO: {
|
|
46
|
-
name: 'add_personal_info',
|
|
47
|
-
destinations: ['DataLayer'],
|
|
48
|
-
requiredParams: ['brand', 'pre_filled', 'currency', 'value', 'subtotal'],
|
|
49
|
-
},
|
|
50
|
-
VIEW_CART: {
|
|
51
|
-
name: 'add_personal_info',
|
|
52
|
-
destinations: ['DataLayer', 'Meta', 'Dito'],
|
|
53
|
-
requiredParams: ['....'],
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export async function trackWebEvent(event: EventName, context: EventContext = {}) {
|
|
58
|
-
try {
|
|
59
|
-
const parameters = await getParameters(context, event);
|
|
60
|
-
return await dispatchTrackEvent(event, parameters);
|
|
61
|
-
} catch (err) {
|
|
62
|
-
return console.error(`[DT] Error tracking event ${event}:`, err);
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
Uso básico da função no consumidor:
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
```javascript
|
|
71
|
-
import { trackWebEvent } from 'azzas-tracker-web';
|
|
72
|
-
|
|
73
|
-
// DATA TRACKING | add_personal_info at submit (pre-filled always false)
|
|
74
|
-
// @see notion document for more details:
|
|
75
|
-
const form: Element = document.querySelector('xxxxxx');
|
|
76
|
-
if (form) {
|
|
77
|
-
form.addEventListener('submit', () => {
|
|
78
|
-
trackWebEvent('ADD_PERSONAL_INFO', { preFilled: false, orderForm: vtexjs.checkout.orderForm });
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
***OBS***: atente-se ao adicionar eventos novos e contribua na documentação do NOTION ou apenas DOCUMENTE em algum lugar! Seu futuro EU será grato 👍
|
|
84
|
-
|
|
85
|
-
## Teste Local para Ambientes CDN/DENO
|
|
86
|
-
|
|
87
|
-
Para testar alterações na biblioteca localmente, simulando a forma como ela é carregada por uma CDN (<script src="...">), use o script npm run dev:deno.
|
|
88
|
-
|
|
89
|
-
Este comando realiza o build mais recente da biblioteca, empacota-o e inicia um servidor HTTP local usando o Deno para servir o arquivo
|
|
90
|
-
|
|
91
|
-
1. Aqui nesse repositório, rode o script que inicia o servidor local:
|
|
92
|
-
|
|
93
|
-
```bash
|
|
94
|
-
npm run dev:deno
|
|
95
|
-
```
|
|
96
|
-
|
|
97
|
-
O servidor será iniciado e começará a servir o seu arquivo de build no seguinte endereço: http://localhost:4507/.
|
|
98
|
-
|
|
99
|
-
2. No Projeto Consumidor (DENO/FRONT):
|
|
100
|
-
|
|
101
|
-
Altere o link do <script> no seu projeto para apontar para o servidor local.
|
|
102
|
-
|
|
103
|
-
Você deve usar: <script src="http://localhost:4507/dist/mod.global.js"></script>
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
## Boas Práticas
|
|
107
|
-
- Sempre garantir que os `requiredParams` de cada evento estejam preenchidos antes de enviar.
|
|
108
|
-
|
|
109
|
-
- Procure sempre manter o envio das ações de usuário o mais ***genérico*** possível. Toda a inteligência e complexidade do tratamento dos dados deve ficar centralizada na lib, e não nos repositórios das lojas.
|
|
110
|
-
|
|
111
|
-
- Usar nomes de eventos semânticos e consistentes (ex: VIEW_CART, ADD_PAYMENT_INFO).
|
|
112
|
-
|
|
113
|
-
- Manter os contextos enxutos, enviando apenas dados realmente necessários.
|
|
114
|
-
|
|
115
|
-
- Cada novo evento deve ser registrado em `EVENTS` com seus destinos e parâmetros obrigatórios. Essa constante talvez venha a ser dinâmica dependendo da MARCA utilizada
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
## Contribuição
|
|
119
|
-
|
|
120
|
-
- Adicionar novos eventos em `EVENTS`.
|
|
121
|
-
|
|
122
|
-
- Criar adapter correspondente caso seja necessário integrar com nova plataforma. Nesse caso deve-se avaliar qual será o serviço feito, o que será consumido, para onde será enviado.
|
|
123
|
-
|
|
124
|
-
- Garantir que todos os parâmetros obrigatórios estejam mapeados nos getters/resolvers.
|
|
125
|
-
|
|
126
|
-
- Executar build (npm run build) antes de testar no checkout/loja.
|
|
127
|
-
|
|
128
|
-
## Authors
|
|
129
|
-
|
|
130
|
-
- Lucas Soares
|
|
1
|
+
# azzas-tracker-web
|
|
2
|
+
|
|
3
|
+
Pacote interno para **Data Tracking** das lojas WEB, centralizando a captura e envio de eventos para diferentes plataformas de mídia (Meta, Dito, DataLayer, etc).
|
|
4
|
+
|
|
5
|
+
O objetivo é fornecer uma **camada única e consistente de tracking**, garantindo que todos os eventos sejam tratados, formatados e enviados de forma confiável.
|
|
6
|
+
|
|
7
|
+
E, principalmente, centralizar a complexidade e a “inteligência” de tracking **fora dos repositórios das lojas**.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Fluxo do Tracking
|
|
12
|
+
|
|
13
|
+
O pacote segue o seguinte fluxo de eventos:
|
|
14
|
+
|
|
15
|
+
1. **User Action**
|
|
16
|
+
Ações do usuário na loja (ex: adicionar ao carrinho, iniciar checkout, finalizar compra).
|
|
17
|
+
|
|
18
|
+
2. **Tracks**
|
|
19
|
+
Ponto central que recebe o contexto do evento vindo da ação do usuário e encaminha para o *Formatter*.
|
|
20
|
+
|
|
21
|
+
3. **Formatter**
|
|
22
|
+
Acessa a constante `EVENTS` e, baseado no contexto do evento, puxa os parâmetros obrigatórios e entrega a biblioteca de parâmetros (`/params`).
|
|
23
|
+
|
|
24
|
+
4. **Params Library**
|
|
25
|
+
Contém **getters** e **resolvers** que garantem que os dados sejam legítimos e que todos os parâmetros sejam corretamente tratados.
|
|
26
|
+
|
|
27
|
+
5. **Adapters**
|
|
28
|
+
Módulos responsáveis por enviar os dados formatados para cada destino (Meta, Datalayer, Dito, etc).
|
|
29
|
+
|
|
30
|
+

|
|
31
|
+
|
|
32
|
+
## Instalação
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm install /path/azzas-tracker-web
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
## Exemplos
|
|
41
|
+
|
|
42
|
+
Listagem dos `EVENTS` e função orquestradora `trackWebEvent`:
|
|
43
|
+
```javascript
|
|
44
|
+
const EVENTS = {
|
|
45
|
+
ADD_PERSONAL_INFO: {
|
|
46
|
+
name: 'add_personal_info',
|
|
47
|
+
destinations: ['DataLayer'],
|
|
48
|
+
requiredParams: ['brand', 'pre_filled', 'currency', 'value', 'subtotal'],
|
|
49
|
+
},
|
|
50
|
+
VIEW_CART: {
|
|
51
|
+
name: 'add_personal_info',
|
|
52
|
+
destinations: ['DataLayer', 'Meta', 'Dito'],
|
|
53
|
+
requiredParams: ['....'],
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function trackWebEvent(event: EventName, context: EventContext = {}) {
|
|
58
|
+
try {
|
|
59
|
+
const parameters = await getParameters(context, event);
|
|
60
|
+
return await dispatchTrackEvent(event, parameters);
|
|
61
|
+
} catch (err) {
|
|
62
|
+
return console.error(`[DT] Error tracking event ${event}:`, err);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Uso básico da função no consumidor:
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
```javascript
|
|
71
|
+
import { trackWebEvent } from 'azzas-tracker-web';
|
|
72
|
+
|
|
73
|
+
// DATA TRACKING | add_personal_info at submit (pre-filled always false)
|
|
74
|
+
// @see notion document for more details:
|
|
75
|
+
const form: Element = document.querySelector('xxxxxx');
|
|
76
|
+
if (form) {
|
|
77
|
+
form.addEventListener('submit', () => {
|
|
78
|
+
trackWebEvent('ADD_PERSONAL_INFO', { preFilled: false, orderForm: vtexjs.checkout.orderForm });
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
***OBS***: atente-se ao adicionar eventos novos e contribua na documentação do NOTION ou apenas DOCUMENTE em algum lugar! Seu futuro EU será grato 👍
|
|
84
|
+
|
|
85
|
+
## Teste Local para Ambientes CDN/DENO
|
|
86
|
+
|
|
87
|
+
Para testar alterações na biblioteca localmente, simulando a forma como ela é carregada por uma CDN (<script src="...">), use o script npm run dev:deno.
|
|
88
|
+
|
|
89
|
+
Este comando realiza o build mais recente da biblioteca, empacota-o e inicia um servidor HTTP local usando o Deno para servir o arquivo
|
|
90
|
+
|
|
91
|
+
1. Aqui nesse repositório, rode o script que inicia o servidor local:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npm run dev:deno
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
O servidor será iniciado e começará a servir o seu arquivo de build no seguinte endereço: http://localhost:4507/.
|
|
98
|
+
|
|
99
|
+
2. No Projeto Consumidor (DENO/FRONT):
|
|
100
|
+
|
|
101
|
+
Altere o link do <script> no seu projeto para apontar para o servidor local.
|
|
102
|
+
|
|
103
|
+
Você deve usar: <script src="http://localhost:4507/dist/mod.global.js"></script>
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
## Boas Práticas
|
|
107
|
+
- Sempre garantir que os `requiredParams` de cada evento estejam preenchidos antes de enviar.
|
|
108
|
+
|
|
109
|
+
- Procure sempre manter o envio das ações de usuário o mais ***genérico*** possível. Toda a inteligência e complexidade do tratamento dos dados deve ficar centralizada na lib, e não nos repositórios das lojas.
|
|
110
|
+
|
|
111
|
+
- Usar nomes de eventos semânticos e consistentes (ex: VIEW_CART, ADD_PAYMENT_INFO).
|
|
112
|
+
|
|
113
|
+
- Manter os contextos enxutos, enviando apenas dados realmente necessários.
|
|
114
|
+
|
|
115
|
+
- Cada novo evento deve ser registrado em `EVENTS` com seus destinos e parâmetros obrigatórios. Essa constante talvez venha a ser dinâmica dependendo da MARCA utilizada
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
## Contribuição
|
|
119
|
+
|
|
120
|
+
- Adicionar novos eventos em `EVENTS`.
|
|
121
|
+
|
|
122
|
+
- Criar adapter correspondente caso seja necessário integrar com nova plataforma. Nesse caso deve-se avaliar qual será o serviço feito, o que será consumido, para onde será enviado.
|
|
123
|
+
|
|
124
|
+
- Garantir que todos os parâmetros obrigatórios estejam mapeados nos getters/resolvers.
|
|
125
|
+
|
|
126
|
+
- Executar build (npm run build) antes de testar no checkout/loja.
|
|
127
|
+
|
|
128
|
+
## Authors
|
|
129
|
+
|
|
130
|
+
- Lucas Soares
|
package/dist/mod.cjs
CHANGED
|
@@ -630,10 +630,174 @@ async function itemsFromOrderForm(context) {
|
|
|
630
630
|
);
|
|
631
631
|
}
|
|
632
632
|
|
|
633
|
+
// src/params/utils/itemListAttribution.ts
|
|
634
|
+
var LAST_SELECTED_ITEM_KEY = "last_selected_item";
|
|
635
|
+
var STORAGE_VIEWED = "last_viewed_item";
|
|
636
|
+
var CART_LIST_HISTORY_KEY = "cart_list_history";
|
|
637
|
+
var DAY_IN_MS = 24 * 60 * 60 * 1e3;
|
|
638
|
+
function getStorage() {
|
|
639
|
+
try {
|
|
640
|
+
if (typeof window === "undefined" || !window.localStorage) return null;
|
|
641
|
+
return window.localStorage;
|
|
642
|
+
} catch (e) {
|
|
643
|
+
return null;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
function parseJSON(value) {
|
|
647
|
+
if (!value) return null;
|
|
648
|
+
try {
|
|
649
|
+
return JSON.parse(value);
|
|
650
|
+
} catch (e) {
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
function isFreshTimestamp(timestamp) {
|
|
655
|
+
const elapsed = Date.now() - timestamp;
|
|
656
|
+
return elapsed >= 0 && elapsed < DAY_IN_MS;
|
|
657
|
+
}
|
|
658
|
+
function isStoredItemMemory(value) {
|
|
659
|
+
if (!value || typeof value !== "object") return false;
|
|
660
|
+
const candidate = value;
|
|
661
|
+
return typeof candidate.item_id === "string" && typeof candidate.item_list_name === "string" && typeof candidate.timestamp === "number";
|
|
662
|
+
}
|
|
663
|
+
function normalizeStoredItemMemory(value) {
|
|
664
|
+
if (!value || typeof value !== "object") return null;
|
|
665
|
+
const candidate = value;
|
|
666
|
+
const itemId = candidate.item_id;
|
|
667
|
+
const itemListName = candidate.item_list_name;
|
|
668
|
+
const timestamp = candidate.timestamp;
|
|
669
|
+
if (typeof itemId !== "string" || typeof itemListName !== "string" || typeof timestamp !== "number") {
|
|
670
|
+
return null;
|
|
671
|
+
}
|
|
672
|
+
return {
|
|
673
|
+
item_id: itemId,
|
|
674
|
+
item_list_name: itemListName,
|
|
675
|
+
timestamp
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
function resolveIdFromUnknownItem(item) {
|
|
679
|
+
var _a, _b, _c, _d, _e;
|
|
680
|
+
const id = (_e = (_d = (_c = (_b = (_a = item == null ? void 0 : item.productID) != null ? _a : item == null ? void 0 : item.productId) != null ? _b : item == null ? void 0 : item.item_group_id) != null ? _c : item == null ? void 0 : item.item_id) != null ? _d : item == null ? void 0 : item.id) != null ? _e : null;
|
|
681
|
+
return id == null ? null : String(id);
|
|
682
|
+
}
|
|
683
|
+
function resolveItemId(item) {
|
|
684
|
+
return resolveIdFromUnknownItem(item);
|
|
685
|
+
}
|
|
686
|
+
function readStoredItem(key) {
|
|
687
|
+
const storage = getStorage();
|
|
688
|
+
if (!storage) return null;
|
|
689
|
+
try {
|
|
690
|
+
const parsed = parseJSON(storage.getItem(key));
|
|
691
|
+
const normalized = normalizeStoredItemMemory(parsed);
|
|
692
|
+
return normalized && isStoredItemMemory(normalized) ? normalized : null;
|
|
693
|
+
} catch (e) {
|
|
694
|
+
return null;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
function writeStoredItem(key, value) {
|
|
698
|
+
const storage = getStorage();
|
|
699
|
+
if (!storage) return;
|
|
700
|
+
try {
|
|
701
|
+
storage.setItem(key, JSON.stringify(value));
|
|
702
|
+
} catch (e) {
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
function readCartHistory() {
|
|
706
|
+
const storage = getStorage();
|
|
707
|
+
if (!storage) return [];
|
|
708
|
+
try {
|
|
709
|
+
const parsed = parseJSON(storage.getItem(CART_LIST_HISTORY_KEY));
|
|
710
|
+
if (!Array.isArray(parsed)) return [];
|
|
711
|
+
return parsed.filter((entry) => !!entry && typeof entry === "object" && typeof entry.item_id === "string" && typeof entry.item_list_name === "string");
|
|
712
|
+
} catch (e) {
|
|
713
|
+
return [];
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
function writeCartHistory(history) {
|
|
717
|
+
const storage = getStorage();
|
|
718
|
+
if (!storage) return;
|
|
719
|
+
try {
|
|
720
|
+
storage.setItem(CART_LIST_HISTORY_KEY, JSON.stringify(history));
|
|
721
|
+
} catch (e) {
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
function saveSelectedItem(productId, listName) {
|
|
725
|
+
if (productId == null || !listName) return;
|
|
726
|
+
const payload = {
|
|
727
|
+
item_id: String(productId),
|
|
728
|
+
item_list_name: String(listName),
|
|
729
|
+
timestamp: Date.now()
|
|
730
|
+
};
|
|
731
|
+
writeStoredItem(LAST_SELECTED_ITEM_KEY, payload);
|
|
732
|
+
}
|
|
733
|
+
function saveViewedItem(productId, listName) {
|
|
734
|
+
if (productId == null) return;
|
|
735
|
+
const payload = {
|
|
736
|
+
item_id: String(productId),
|
|
737
|
+
item_list_name: String(listName != null ? listName : "PDP"),
|
|
738
|
+
timestamp: Date.now()
|
|
739
|
+
};
|
|
740
|
+
writeStoredItem(STORAGE_VIEWED, payload);
|
|
741
|
+
}
|
|
742
|
+
function resolveItemListName(params) {
|
|
743
|
+
const { event, item, itemListName } = params;
|
|
744
|
+
const currentListName = itemListName != null ? itemListName : null;
|
|
745
|
+
const isResolvableEvent = event === "VIEW_ITEM" || event === "ADD_TO_CART";
|
|
746
|
+
if (!isResolvableEvent) return currentListName;
|
|
747
|
+
const currentItemId = resolveIdFromUnknownItem(item);
|
|
748
|
+
if (event === "VIEW_ITEM") {
|
|
749
|
+
if (!currentItemId) return "PDP";
|
|
750
|
+
const selectedItem = readStoredItem(LAST_SELECTED_ITEM_KEY);
|
|
751
|
+
if (!selectedItem) return "PDP";
|
|
752
|
+
if (selectedItem.item_id === currentItemId && isFreshTimestamp(selectedItem.timestamp)) {
|
|
753
|
+
return selectedItem.item_list_name;
|
|
754
|
+
}
|
|
755
|
+
return "PDP";
|
|
756
|
+
}
|
|
757
|
+
if (currentListName !== "PDP" && currentListName !== null) return currentListName;
|
|
758
|
+
if (!currentItemId) return currentListName;
|
|
759
|
+
const viewedItem = readStoredItem(STORAGE_VIEWED);
|
|
760
|
+
if (viewedItem && viewedItem.item_id === currentItemId && isFreshTimestamp(viewedItem.timestamp)) {
|
|
761
|
+
return viewedItem.item_list_name;
|
|
762
|
+
}
|
|
763
|
+
return currentListName === "PDP" ? "PDP" : null;
|
|
764
|
+
}
|
|
765
|
+
function appendCartHistory(productId, listName) {
|
|
766
|
+
if (productId == null) return;
|
|
767
|
+
const history = readCartHistory();
|
|
768
|
+
history.push({
|
|
769
|
+
item_id: String(productId),
|
|
770
|
+
item_list_name: listName ? String(listName) : "PDP"
|
|
771
|
+
});
|
|
772
|
+
writeCartHistory(history);
|
|
773
|
+
}
|
|
774
|
+
function pickSelectedItemFromResolvedItems(items, source) {
|
|
775
|
+
var _a;
|
|
776
|
+
if (!Array.isArray(items) || items.length === 0) return null;
|
|
777
|
+
if (typeof (source == null ? void 0 : source.index) === "number") {
|
|
778
|
+
const indexed = (_a = items.find((item) => (item == null ? void 0 : item.index) === source.index)) != null ? _a : items[source.index];
|
|
779
|
+
if (indexed && typeof indexed === "object") return indexed;
|
|
780
|
+
}
|
|
781
|
+
return items[0];
|
|
782
|
+
}
|
|
783
|
+
function persistSelectItemOriginFromResolvedItems(items, source) {
|
|
784
|
+
var _a, _b, _c;
|
|
785
|
+
const selectedItem = pickSelectedItemFromResolvedItems(items, source);
|
|
786
|
+
if (!selectedItem) return;
|
|
787
|
+
const productId = resolveIdFromUnknownItem(selectedItem);
|
|
788
|
+
const listName = (_c = (_b = (_a = selectedItem == null ? void 0 : selectedItem.item_list_name) != null ? _a : source == null ? void 0 : source.itemListName) != null ? _b : source == null ? void 0 : source.item_list_name) != null ? _c : null;
|
|
789
|
+
saveSelectedItem(productId, listName);
|
|
790
|
+
}
|
|
791
|
+
|
|
633
792
|
// src/params/resolvers/items/fromItem.ts
|
|
634
793
|
async function itemsFromItem(context, event) {
|
|
635
794
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
|
|
636
795
|
const { item, orderForm, itemListName } = context;
|
|
796
|
+
const resolvedListName = resolveItemListName({ event, item, itemListName });
|
|
797
|
+
const resolvedItemId = resolveItemId(item);
|
|
798
|
+
if (event === "ADD_TO_CART") {
|
|
799
|
+
appendCartHistory(resolvedItemId, resolvedListName);
|
|
800
|
+
}
|
|
637
801
|
return [
|
|
638
802
|
{
|
|
639
803
|
index: typeof (item == null ? void 0 : item.index) === "number" ? item.index : null,
|
|
@@ -651,7 +815,7 @@ async function itemsFromItem(context, event) {
|
|
|
651
815
|
item_variant: ((item == null ? void 0 : item.skuName) || (item == null ? void 0 : item.item_variant) || (item == null ? void 0 : item.name) || (item == null ? void 0 : item.itemOffered.name)).split(/[-/]/)[0].trim() || null,
|
|
652
816
|
item_variant2: (item == null ? void 0 : item.size) || ((_n = item == null ? void 0 : item.itemAttributes) == null ? void 0 : _n.size) || ((_p = (_o = (item == null ? void 0 : item.skuName) || (item == null ? void 0 : item.name) || (item == null ? void 0 : item.itemOffered.name)) == null ? void 0 : _o.split(/[-/]/).pop()) == null ? void 0 : _p.trim()) || null,
|
|
653
817
|
discount: getDiscount(item),
|
|
654
|
-
item_list_name:
|
|
818
|
+
item_list_name: resolvedListName,
|
|
655
819
|
item_url: (item == null ? void 0 : item.item_url) || null,
|
|
656
820
|
// add_to_cart dito
|
|
657
821
|
image_url: resizeVtexImage(item == null ? void 0 : item.image) || resizeVtexImage(item == null ? void 0 : item.imageUrl) || null
|
|
@@ -681,9 +845,14 @@ async function itemsFromList(context) {
|
|
|
681
845
|
}
|
|
682
846
|
|
|
683
847
|
// src/params/resolvers/items/fromPdp.ts
|
|
684
|
-
async function itemsFromPDP(context) {
|
|
848
|
+
async function itemsFromPDP(context, event) {
|
|
685
849
|
var _a, _b, _c, _d;
|
|
686
850
|
const { item, value, brand } = context;
|
|
851
|
+
const resolvedListName = resolveItemListName({ event, item, itemListName: null });
|
|
852
|
+
const resolvedItemId = resolveItemId(item);
|
|
853
|
+
if (event === "VIEW_ITEM") {
|
|
854
|
+
saveViewedItem(resolvedItemId, resolvedListName);
|
|
855
|
+
}
|
|
687
856
|
return [
|
|
688
857
|
{
|
|
689
858
|
price: value || 0,
|
|
@@ -700,7 +869,8 @@ async function itemsFromPDP(context) {
|
|
|
700
869
|
item_sku: (item == null ? void 0 : item.sku) || (item == null ? void 0 : item.productId) || null,
|
|
701
870
|
item_url: (item == null ? void 0 : item.url) || (item == null ? void 0 : item.item_url) || (item == null ? void 0 : item.link) || null,
|
|
702
871
|
image_url: resizeVtexImage(item == null ? void 0 : item.image) || resizeVtexImage(item == null ? void 0 : item.imageUrl) || null,
|
|
703
|
-
seller_id: (item == null ? void 0 : item.seller) || null
|
|
872
|
+
seller_id: (item == null ? void 0 : item.seller) || null,
|
|
873
|
+
item_list_name: resolvedListName
|
|
704
874
|
}
|
|
705
875
|
];
|
|
706
876
|
}
|
|
@@ -743,11 +913,15 @@ function getItems(context, eventName) {
|
|
|
743
913
|
case "REMOVE_FROM_CART":
|
|
744
914
|
return itemsFromItem(context, eventName);
|
|
745
915
|
case "SELECT_ITEM":
|
|
916
|
+
return itemsFromList(context).then((items) => {
|
|
917
|
+
persistSelectItemOriginFromResolvedItems(items, context);
|
|
918
|
+
return items;
|
|
919
|
+
});
|
|
746
920
|
case "VIEW_ITEM_LIST":
|
|
747
921
|
return itemsFromList(context);
|
|
748
922
|
case "VIEW_ITEM":
|
|
749
923
|
case "CUSTOM_VIEW_ITEM":
|
|
750
|
-
return itemsFromPDP(context);
|
|
924
|
+
return itemsFromPDP(context, eventName);
|
|
751
925
|
case "VIEW_PROMOTION":
|
|
752
926
|
case "SELECT_PROMOTION":
|
|
753
927
|
return itemsFromBanner(context);
|