Skip to content

Commit

Permalink
feat
Browse files Browse the repository at this point in the history
  • Loading branch information
Fabio Brasileiro authored and Fabio Brasileiro committed Nov 18, 2024
1 parent eeb22a6 commit 4a2e52b
Show file tree
Hide file tree
Showing 11 changed files with 387 additions and 158 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
"name": "angular-tailwind",
"displayName": "NEXT PAYMENT",
"version": "0.0.1",
"description": "Angular & Tailwind CSS Admin Dashboard Starter Kit, Free and Open Source",
"homepage": "https://github.com/lannodev/angular-tailwind#readme",
"description": "Angular & Tailwind CSS PDV",
"homepage": "https://github.com/fabiobrasileiroo/front-next-payment#",
"repository": {
"type": "git",
"url": "git+https://github.com/lannodev/angular-tailwind.git"
"url": "git+https://github.com/fabiobrasileiroo/front-next-payment"
},
"keywords": [
"angular",
Expand Down
1 change: 1 addition & 0 deletions src/app/core/guards/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export class AuthGuard implements CanActivate {
if (isValid) {
return true; // If token is valid, allow access
} else {
console.log('ta passando aqui')
this.router.navigate(['/auth/sign-in']); // If token is invalid, redirect to login
return false;
}
Expand Down
16 changes: 16 additions & 0 deletions src/app/core/services/cart.service.spec.ts
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();
});
});
39 changes: 39 additions & 0 deletions src/app/core/services/cart.service.ts
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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
NEXT PAYMENT
</a>
</div>
<ul class="flex text-muted-foreground/50">
<!-- <ul class="flex text-muted-foreground/50">
<li class="hover:text-primary">
<a href="https://github.com/luciano-work/angular-tailwind/issues" target="_blank" class="menu-link px-2">
Issues
Expand All @@ -18,6 +18,6 @@
<li class="hover:text-primary">
<a href="https://github.com/luciano-work/angular-tailwind" target="_blank" class="menu-link px-2">Starred</a>
</li>
</ul>
</ul> -->
</div>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

<div class="mx-4 my-4 space-y-1">
<!-- Version -->
<a target="_blank" href="https://github.com/luciano-work/angular-tailwind"
<a target="_blank" href="https://github.com/fabiobrasileiroo/front-next-payment"
class="group flex h-9 cursor-pointer items-center justify-start rounded p-2 hover:bg-card">
<svg-icon src="assets/icons/heroicons/outline/information-circle.svg"
[svgClass]="'h-5 w-5 text-muted-foreground/50'">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,65 @@ <h3 class="font-semibold text-foreground">Produtos</h3>
</div>
<div class="inline-block space-x-4">
<button
class="flex-none rounded-md bg-muted px-4 py-2.5 text-xs font-semibold text-muted-foreground hover:text-foreground">
class="flex-none rounded-md bg-muted px-4 py-2.5 text-xs font-semibold text-muted-foreground hover:text-foreground"
(click)="openDrawer()">
Carrinho
</button>

<!-- [ngStyle]="{ 'background-color': 'var(--primary-color)', 'width': '100%' }" -->
<!-- class="flex-none rounded-md px-4 !py-2.5 !text-xs !font-semibold !text-primary-foreground" -->
<p-button
type="button"
styleClass="!w-full md:!w-80 lg:!w-[30rem] !bg-primary !flex-none !rounded-md !border-border !px-4 !py-2.5 !text-xs !font-semibold !text-primary-foreground"
(click)="visible = true">
Finaliza comprar
</p-button>

<!-- <p-button type="button" (click)="visible = true" icon="pi pi-arrow-left" /> -->
<!-- <p-button
type="button"
styleClass="!w-full md:!w-80 lg:!w-[30rem] !bg-primary !flex-none !rounded-md !border-border !px-4 !py-2.5 !text-xs !font-semibold !text-primary-foreground"
(click)="openDrawer()">
Finalizar Compra
</p-button> -->
</div>
</div>

<p-drawer header="Finalizar pagamento" [(visible)]="visible" position="right">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
</p>
</p-drawer>
<!-- Drawer para exibir os produtos do carrinho -->
<p-drawer header="Finalizar pagamento" [(visible)]="visible" position="right" [modal]="true"
styleClass="!bg-background !border-border !w-full md:!w-80 lg:!w-[30rem] !text-foreground">
<div *ngIf="updatedProducts.length > 0; else emptyCart">
<div *ngFor="let product of updatedProducts" class="mb-4">
<div class="flex justify-between items-center">
<div>
<div class="flex">
<div class="card flex justify-center mr-3">
<p-image [src]="product.imageUrl" [preview]="true" alt="Image" width="50"></p-image>
</div>
<div class="flex flex-col">
<h3 class="font-semibold">{{ product.name }}</h3>
<span class="text-sm text-muted-foreground">{{ product.company?.name || 'N/A' }}</span>
</div>
</div>
</div>
<div class="flex flex-col items-end">
<span class="font-semibold">{{ product.price | currency: "BRL" }}</span>
<div class="flex items-center">
<button pButton icon="pi pi-minus"
class="!rounded-md !bg-muted !text-xs !font-semibold !text-muted-foreground !border-border !hover:text-foreground"
(click)="decreaseQuantity(product)"></button>
<input type="number" min="1" [value]="product.quantityItem" class="mx-2 w-20 text-center border rounded-md"
(change)="onQuantityChange(product, $event)" />
<button pButton icon="pi pi-plus"
class="!rounded-md !bg-muted !text-xs !font-semibold !text-muted-foreground !border-border !hover:text-foreground"
(click)="increaseQuantity(product)"></button>
</div>
<span *ngIf="product.quantityItem >= product.quantity" class="text-xs text-red-500">
Estoque máximo atingido!
</span>
</div>
</div>
</div>
<div class="flex justify-between mt-4">
<p>Total:</p>
<p>{{ totalAmount | currency: "BRL" }}</p>
</div>
<div class="flex justify-end mt-4">
<button pButton label="Finalizar Pagamento" (click)="processPayment()"
class="!bg-primary !text-primary-foreground !border-border !rounded-md"></button>
</div>
</div>
<ng-template #emptyCart>
<p class="text-center text-muted-foreground mt-6">Seu carrinho está vazio.</p>
</ng-template>
</p-drawer>
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 {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<!-- styleClass="!w-full md:!w-80 lg:!w-[30rem] !bg-primary !flex-none !rounded-md !border-border !px-4 !py-2.5 !text-xs !font-semibold !text-primary-foreground" -->
<p-toolbar styleClass="mb-6 gap-2 !bg-background !border-border">
<ng-template pTemplate="left">
<p-button pRipple severity="success" label="New" icon="pi pi-plus" class="mr-2" styleClass="!bg-primary !border-border !text-primary" (click)="openNew()" />
<p-button pRipple severity="success" label="New" icon="pi pi-plus" class="mr-2" styleClass="!bg-primary !border-border text-primary" (click)="openNew()" />
<p-button pRipple severity="danger" label="Delete" icon="pi pi-trash" (click)="deleteSelectedProducts()"
[disabled]="!selectedProducts || !selectedProducts.length" />
</ng-template>
Expand All @@ -28,7 +28,7 @@
>
<ng-template pTemplate="caption" styleClass="!bg-background !border-border">
<div class="flex items-center justify-between" >
<h5 class="m-0">Gerenciar produtos</h5>
<h5 class="m-0" >Gerenciar produtos</h5>
<p-iconfield iconPosition="left" class="ml-4">
<p-inputicon>
<i class="pi pi-search"></i>
Expand Down
Loading

0 comments on commit 4a2e52b

Please sign in to comment.