-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Fabio Brasileiro
authored and
Fabio Brasileiro
committed
Nov 18, 2024
1 parent
eeb22a6
commit 4a2e52b
Showing
11 changed files
with
387 additions
and
158 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import { TestBed } from '@angular/core/testing'; | ||
|
||
import { CartService } from './cart.service'; | ||
|
||
describe('CartService', () => { | ||
let service: CartService; | ||
|
||
beforeEach(() => { | ||
TestBed.configureTestingModule({}); | ||
service = TestBed.inject(CartService); | ||
}); | ||
|
||
it('should be created', () => { | ||
expect(service).toBeTruthy(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { Injectable } from '@angular/core'; | ||
import { BehaviorSubject } from 'rxjs'; | ||
|
||
@Injectable({ | ||
providedIn: 'root', | ||
}) | ||
export class CartService { | ||
private selectedProductsSubject = new BehaviorSubject<any[]>([]); | ||
selectedProducts$ = this.selectedProductsSubject.asObservable(); | ||
|
||
// Obtém a lista atual de produtos no carrinho | ||
get selectedProducts(): any[] { | ||
return this.selectedProductsSubject.getValue(); | ||
} | ||
|
||
// Adiciona um produto ao carrinho | ||
addProduct(product: any): void { | ||
const currentProducts = this.selectedProducts; | ||
const index = currentProducts.findIndex((p) => p.id === product.id); | ||
|
||
if (index === -1) { | ||
currentProducts.push({ ...product, quantity: 1 }); | ||
} else { | ||
currentProducts[index].quantity += 1; // Incrementa a quantidade | ||
} | ||
this.selectedProductsSubject.next([...currentProducts]); // Atualiza o BehaviorSubject | ||
} | ||
|
||
// Remove um produto do carrinho | ||
removeProduct(productId: number): void { | ||
const updatedProducts = this.selectedProducts.filter((p) => p.id !== productId); | ||
this.selectedProductsSubject.next(updatedProducts); // Atualiza o BehaviorSubject | ||
} | ||
|
||
// Limpa o carrinho | ||
clearCart(): void { | ||
this.selectedProductsSubject.next([]); // Esvazia o carrinho | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 97 additions & 9 deletions
106
src/app/modules/products/components/nft/nft-header/nft-header.component.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,107 @@ | ||
import { Component, OnInit } from '@angular/core'; | ||
import { Component, Input } from '@angular/core'; | ||
import { DrawerModule } from 'primeng/drawer'; | ||
import { ButtonModule } from 'primeng/button'; | ||
|
||
import { CurrencyPipe, NgFor, NgIf } from '@angular/common'; | ||
import { ImageModule } from 'primeng/image'; | ||
import { PaymentService } from 'src/app/core/services/payment-pix.service'; | ||
@Component({ | ||
selector: 'app-nft-header', | ||
templateUrl: './nft-header.component.html', | ||
standalone: true, | ||
imports: [ | ||
DrawerModule, | ||
ButtonModule | ||
] | ||
imports: [DrawerModule, ButtonModule, CurrencyPipe, NgIf, NgFor, ImageModule], | ||
}) | ||
export class NftHeaderComponent implements OnInit { | ||
export class NftHeaderComponent { | ||
visible: boolean = false; | ||
constructor() {} | ||
@Input() selectedProducts: any[] = []; // Recebe os produtos selecionados | ||
updatedProducts: any[] = []; // Array para manter os dados atualizados | ||
totalAmount: number = 0; // Soma total dos produtos no carrinho | ||
|
||
constructor(private paymentService: PaymentService) {} | ||
|
||
openDrawer() { | ||
// Inicializa `quantityItem` para todos os produtos selecionados | ||
this.updatedProducts = this.selectedProducts.map(product => ({ | ||
...product, | ||
quantityItem: product.quantityItem || 1, // Começa com 1 unidade por padrão | ||
})); | ||
this.calculateTotalAmount(); // Atualiza o valor total | ||
this.visible = true; | ||
} | ||
|
||
closeDrawer() { | ||
this.visible = false; | ||
} | ||
|
||
updateQuantity(product: any, quantity: number) { | ||
if (quantity < 1) { | ||
alert(`A quantidade mínima para ${product.name} é 1 unidade.`); | ||
product.quantityItem = 1; // Define a quantidade mínima | ||
} else if (quantity > product.quantity) { | ||
alert(`Você não pode adicionar mais do que ${product.quantity} unidades de ${product.name}.`); | ||
product.quantityItem = product.quantity; // Define a quantidade máxima | ||
} else { | ||
product.quantityItem = quantity; // Atualiza a quantidade | ||
} | ||
|
||
this.calculateTotalAmount(); // Recalcula o total ao atualizar a quantidade | ||
} | ||
|
||
onQuantityChange(product: any, event: Event): void { | ||
const inputElement = event.target as HTMLInputElement; | ||
if (inputElement) { | ||
const newValue = +inputElement.value; | ||
if (!isNaN(newValue)) { | ||
this.updateQuantity(product, newValue); | ||
} else { | ||
console.warn('Número inválido inserido.'); | ||
} | ||
} | ||
} | ||
|
||
increaseQuantity(product: any) { | ||
console.log("🚀 ~ NftHeaderComponent ~ increaseQuantity ~ product:", product) | ||
this.updateQuantity(product, product.quantityItem + 1); | ||
} | ||
|
||
decreaseQuantity(product: any) { | ||
this.updateQuantity(product, product.quantityItem - 1); | ||
} | ||
|
||
calculateTotalAmount() { | ||
this.totalAmount = this.updatedProducts.reduce((sum, product) => { | ||
return sum + product.price * product.quantityItem; | ||
}, 0); | ||
} | ||
|
||
processPayment() { | ||
if (this.selectedProducts.length === 0) { | ||
alert('Por favor, selecione pelo menos um produto!'); | ||
return; | ||
} | ||
|
||
// Construir lista de produtos com ID e quantidade | ||
const productsToPay = this.selectedProducts.map(product => ({ | ||
id: product.id, | ||
quantity: product.selectedQuantity, | ||
})); | ||
|
||
const paymentData = { | ||
transaction_amount: this.totalAmount, // Total calculado | ||
description: 'Pagamento dos produtos selecionados', | ||
payment_method_id: 'pix', | ||
payer: { email: 'usuario@exemplo.com' }, | ||
// products: productsToPay, // Adicionando lista de produtos ao paymentData | ||
}; | ||
|
||
this.paymentService.createPayment(paymentData).subscribe( | ||
(response: any) => { | ||
const paymentUrl = response.point_of_interaction.transaction_data.ticket_url; | ||
window.open(paymentUrl, '_blank'); | ||
}, | ||
(error: any) => { | ||
console.error('Erro no pagamento:', error); | ||
} | ||
); | ||
} | ||
|
||
ngOnInit(): void {} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.