-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.js
More file actions
203 lines (174 loc) · 6.63 KB
/
checkout.js
File metadata and controls
203 lines (174 loc) · 6.63 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
const STORAGE_KEYS = {
carrinho: "carrinho",
usuario: "usuarioLogado",
compras: "historicoCompras"
};
// Carrega o carrinho atual, o utilizador e o historico de compras.
let carrinho = JSON.parse(localStorage.getItem(STORAGE_KEYS.carrinho)) || [];
const usuario = JSON.parse(localStorage.getItem(STORAGE_KEYS.usuario)) || null;
let historicoCompras = JSON.parse(localStorage.getItem(STORAGE_KEYS.compras)) || [];
const checkoutForm = document.getElementById("checkoutForm");
const checkoutName = document.getElementById("checkoutName");
const checkoutEmail = document.getElementById("checkoutEmail");
const checkoutPhone = document.getElementById("checkoutPhone");
const checkoutAddress = document.getElementById("checkoutAddress");
const checkoutItems = document.getElementById("checkoutItems");
const checkoutEmpty = document.getElementById("checkoutEmpty");
const checkoutCount = document.getElementById("checkoutCount");
const checkoutSubtotal = document.getElementById("checkoutSubtotal");
const checkoutTotal = document.getElementById("checkoutTotal");
const checkoutMessage = document.getElementById("checkoutMessage");
const historyList = document.getElementById("historyList");
const historyEmpty = document.getElementById("historyEmpty");
const invoiceCard = document.getElementById("invoiceCard");
const invoiceNumber = document.getElementById("invoiceNumber");
const invoiceClient = document.getElementById("invoiceClient");
const invoiceDate = document.getElementById("invoiceDate");
const invoiceTotal = document.getElementById("invoiceTotal");
// Adapta itens antigos para o formato atual com quantidade.
function normalizarCarrinho() {
carrinho = carrinho.map((item) => {
if (item.quantidade) return item;
return { ...item, quantidade: 1 };
});
localStorage.setItem(STORAGE_KEYS.carrinho, JSON.stringify(carrinho));
}
function formatarPreco(valor) {
return `${Number(valor).toLocaleString("pt-PT")} MT`;
}
function validarEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
// Conta todas as unidades presentes no pedido.
function getTotalItens() {
return carrinho.reduce((total, item) => total + item.quantidade, 0);
}
// Soma o total do pedido com base nas quantidades.
function calcularTotal() {
return carrinho.reduce((total, item) => total + (item.preco * item.quantidade), 0);
}
function preencherUsuario() {
if (!usuario) return;
checkoutName.value = usuario.nome || "";
checkoutEmail.value = usuario.email || "";
}
// Mostra as compras ja finalizadas e guardadas localmente.
function renderHistorico() {
historyList.innerHTML = "";
if (historicoCompras.length === 0) {
historyEmpty.style.display = "block";
return;
}
historyEmpty.style.display = "none";
[...historicoCompras].reverse().forEach((compra) => {
const item = document.createElement("li");
item.innerHTML = `
<div class="checkout-item-info">
<strong>${compra.numero}</strong>
<p class="checkout-note">${compra.nome}</p>
</div>
<div class="checkout-item-meta">
<span class="checkout-qty">${compra.data}</span>
<strong>${formatarPreco(compra.total)}</strong>
</div>
`;
historyList.appendChild(item);
});
}
// Apresenta uma fatura simples logo depois da compra.
function mostrarFatura(compra) {
invoiceCard.classList.remove("hidden");
invoiceNumber.textContent = `Numero: ${compra.numero}`;
invoiceClient.textContent = `Cliente: ${compra.nome} - ${compra.email}`;
invoiceDate.textContent = `Data: ${compra.data}`;
invoiceTotal.textContent = `Total pago: ${formatarPreco(compra.total)}`;
}
// Atualiza o resumo com itens, quantidades, subtotal e total.
function renderResumo() {
checkoutItems.innerHTML = "";
if (carrinho.length === 0) {
checkoutEmpty.style.display = "block";
checkoutCount.textContent = "0";
checkoutSubtotal.textContent = "0 MT";
checkoutTotal.textContent = "0 MT";
checkoutForm.querySelector("button").disabled = true;
if (!checkoutMessage.classList.contains("success-message")) {
checkoutMessage.textContent = "O carrinho esta vazio. Volte para a loja para adicionar produtos.";
}
return;
}
checkoutEmpty.style.display = "none";
checkoutMessage.textContent = "";
checkoutMessage.className = "";
invoiceCard.classList.add("hidden");
carrinho.forEach((produto) => {
const item = document.createElement("li");
const subtotal = produto.preco * produto.quantidade;
item.innerHTML = `
<div class="checkout-item-info">
<strong>${produto.nome}</strong>
<p class="checkout-note">${formatarPreco(produto.preco)} cada</p>
</div>
<div class="checkout-item-meta">
<span class="checkout-qty">Qtd: ${produto.quantidade}</span>
<strong>${formatarPreco(subtotal)}</strong>
</div>
`;
checkoutItems.appendChild(item);
});
checkoutCount.textContent = `${getTotalItens()}`;
checkoutSubtotal.textContent = formatarPreco(calcularTotal());
checkoutTotal.textContent = formatarPreco(calcularTotal());
checkoutForm.querySelector("button").disabled = false;
}
// Valida o formulario, cria a compra, guarda no historico e limpa o carrinho.
checkoutForm.addEventListener("submit", (event) => {
event.preventDefault();
const nome = checkoutName.value.trim();
const email = checkoutEmail.value.trim().toLowerCase();
const telefone = checkoutPhone.value.trim();
const endereco = checkoutAddress.value.trim();
if (nome.length < 3) {
checkoutMessage.textContent = "Digite um nome valido.";
return;
}
if (!validarEmail(email)) {
checkoutMessage.textContent = "Digite um email valido.";
return;
}
if (telefone.length < 9) {
checkoutMessage.textContent = "Digite um telefone valido.";
return;
}
if (endereco.length < 8) {
checkoutMessage.textContent = "Digite um endereco mais completo.";
return;
}
const compra = {
numero: `FT-${Date.now()}`,
nome,
email,
telefone,
endereco,
total: calcularTotal(),
itens: carrinho,
data: new Date().toLocaleString("pt-PT")
};
historicoCompras.push(compra);
localStorage.setItem(STORAGE_KEYS.compras, JSON.stringify(historicoCompras));
localStorage.removeItem(STORAGE_KEYS.carrinho);
carrinho = [];
checkoutMessage.textContent = `Compra finalizada com sucesso para ${nome}.`;
checkoutMessage.className = "success-message";
checkoutForm.reset();
checkoutName.value = usuario ? usuario.nome || "" : "";
checkoutEmail.value = usuario ? usuario.email || "" : "";
renderResumo();
renderHistorico();
mostrarFatura(compra);
});
// Carrega os dados principais da pagina de checkout.
normalizarCarrinho();
preencherUsuario();
renderResumo();
renderHistorico();