Cleaned code and prepared for API communications.

This commit is contained in:
Filipe Soccol 2024-12-01 11:50:08 -03:00
parent 92f6cb4d35
commit c4dae86b5f
6 changed files with 64 additions and 100 deletions

View File

@ -1,75 +1,24 @@
<script setup lang="ts"> <script setup lang="ts">
import { pix } from "@/utils/QrCodePix"; import { pix } from "@/utils/QrCodePix";
import { onMounted, onUnmounted, ref } from "vue"; import { onMounted, onUnmounted, ref } from "vue";
import { debounce } from "@/utils/debounce";
import CustomButton from "@/components/CustomButton/CustomButton.vue"; import CustomButton from "@/components/CustomButton/CustomButton.vue";
import CustomModal from "@/components//CustomModal/CustomModal.vue"; import CustomModal from "@/components//CustomModal/CustomModal.vue";
import api from "@/services/index";
// props and store references // props and store references
const props = defineProps({ const props = defineProps({
pixTarget: String, sellerId: String,
tokenValue: Number, amount: Number,
}); });
const windowSize = ref<number>(window.innerWidth); const windowSize = ref<number>(window.innerWidth);
const qrCode = ref<string>(""); const qrCode = ref<string>("");
const qrCodePayload = ref<string>("");
const isPixValid = ref<boolean>(false); const isPixValid = ref<boolean>(false);
const isCodeInputEmpty = ref<boolean>(true);
const showWarnModal = ref<boolean>(true); const showWarnModal = ref<boolean>(true);
const e2eId = ref<string>(""); const releaseSignature = ref<string>("");
// Emits // Emits
const emit = defineEmits(["pixValidated"]); const emit = defineEmits(["pixValidated"]);
const pixQrCode = pix({
pixKey: props.pixTarget ?? "",
value: props.tokenValue,
});
pixQrCode.base64QrCode().then((code: string) => {
qrCode.value = code;
});
qrCodePayload.value = pixQrCode.payload();
const handleInputEvent = async (event: any): Promise<void> => {
const { value } = event.target;
e2eId.value = value;
await validatePix();
};
const validatePix = async (): Promise<void> => {
if (e2eId.value == "") {
isPixValid.value = false;
isCodeInputEmpty.value = true;
return;
}
const sellerPixKey = props.pixTarget;
const transactionValue = props.tokenValue;
if (sellerPixKey && transactionValue) {
const body_req = {
e2e_id: e2eId.value,
pix_key: sellerPixKey,
pix_value: transactionValue,
};
isCodeInputEmpty.value = false;
try {
await api.post("validate_pix", body_req);
isPixValid.value = true;
} catch (error) {
isPixValid.value = false;
}
} else {
isCodeInputEmpty.value = false;
isPixValid.value = false;
}
};
onMounted(() => { onMounted(() => {
window.addEventListener( window.addEventListener(
"resize", "resize",
@ -94,7 +43,7 @@ onUnmounted(() => {
</span> </span>
<span class="text font-medium lg:text-md text-sm max-w-[28rem]"> <span class="text font-medium lg:text-md text-sm max-w-[28rem]">
Após realizar o Pix no banco de sua preferência, clique no botão abaixo Após realizar o Pix no banco de sua preferência, clique no botão abaixo
para gerar a assinatura para liberação dos tokens. para liberação dos tokens.
</span> </span>
</div> </div>
<div class="main-container max-w-md text-black"> <div class="main-container max-w-md text-black">
@ -105,7 +54,7 @@ onUnmounted(() => {
<span class="text-center font-bold">Código pix</span> <span class="text-center font-bold">Código pix</span>
<div class="break-words w-4/5"> <div class="break-words w-4/5">
<span class="text-center text-xs"> <span class="text-center text-xs">
{{ qrCodePayload }} {{ qrCode }}
</span> </span>
</div> </div>
<img <img
@ -115,17 +64,11 @@ onUnmounted(() => {
height="16" height="16"
class="pt-2 lg:mb-5 cursor-pointer" class="pt-2 lg:mb-5 cursor-pointer"
/> />
<span class="text-xs text-start hidden sm:inline-block">
<strong>ATENÇÃO!</strong> A transação será processada após inserir
o código de autenticação. Caso contrário não conseguiremos comprovar o
seu depósito e não será possível transferir os tokens para sua
carteira. Confira aqui como encontrar o código no comprovante.
</span>
</div> </div>
<CustomButton <CustomButton
:is-disabled="isPixValid == false" :is-disabled="isPixValid == false"
:text="'Enviar para a rede'" :text="'Enviar para a rede'"
@button-clicked="emit('pixValidated', e2eId)" @button-clicked="emit('pixValidated', releaseSignature)"
/> />
</div> </div>
<CustomModal <CustomModal

View File

@ -6,7 +6,7 @@ const emit = defineEmits(["sendNetwork"]);
// props and store references // props and store references
const props = defineProps({ const props = defineProps({
pixKey: String, sellerId: String,
offer: Number, offer: Number,
selectedToken: String, selectedToken: String,
}); });
@ -39,7 +39,7 @@ const props = defineProps({
<div class="my-3"> <div class="my-3">
<p>Chave Pix</p> <p>Chave Pix</p>
<p class="text-xl text-gray-900 break-words"> <p class="text-xl text-gray-900 break-words">
{{ props.pixKey }} {{ props.sellerId }}
</p> </p>
</div> </div>
<div class="mb-5"> <div class="mb-5">

View File

@ -1,14 +0,0 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import axios from "axios";
const defaultConfig = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
};
const api = axios.create({
...defaultConfig,
baseURL: import.meta.env.VITE_API_URL,
});
export default api;

43
src/utils/bbPay.ts Normal file
View File

@ -0,0 +1,43 @@
export interface Participant {
offer: string;
fullName: string;
identification: string;
bankIspb?: string;
accountType: string;
account: string;
branch: string;
savingsVariation?: string;
}
export interface ParticipantWithID extends Participant {
id: string;
}
export interface Offer {
amount: number;
sellerID: string;
}
export const createParticipant = async (participant: Participant) => {
const response = await fetch(`${process.env.VUE_APP_API_URL}/participants`, {
method: "PUT",
body: JSON.stringify(participant),
});
const data = await response.json();
return { ...participant, id: data.id } as ParticipantWithID;
};
export const createSolicitation = async (offer: Offer) => {
const response = await fetch(`${process.env.VUE_APP_API_URL}/solicitation`, {
method: "POST",
body: JSON.stringify(offer),
});
return response.json();
};
export const getSolicitation = async (id: string) => {
const response = await fetch(
`${process.env.VUE_APP_API_URL}/solicitation/${id}`
);
return response.json();
};

View File

@ -140,8 +140,8 @@ onMounted(async () => {
/> />
<div v-if="flowStep == Step.Buy"> <div v-if="flowStep == Step.Buy">
<QrCodeComponent <QrCodeComponent
:pixTarget="String(pixTarget)" :sellerId="String(pixTarget)"
:tokenValue="tokenAmount" :amount="tokenAmount"
@pix-validated="releaseTransaction" @pix-validated="releaseTransaction"
v-if="!loadingLock" v-if="!loadingLock"
/> />

View File

@ -7,6 +7,7 @@ import { approveTokens, addDeposit } from "@/blockchain/sellerMethods";
import { ref } from "vue"; import { ref } from "vue";
import { useEtherStore } from "@/store/ether"; import { useEtherStore } from "@/store/ether";
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue"; import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
import { createParticipant, Participant } from "@/utils/bbPay";
enum Step { enum Step {
Search, Search,
@ -14,32 +15,21 @@ enum Step {
Network, Network,
} }
interface SellerData {
identification: string;
account: string;
branch: string;
bankIspb: string;
accountType: string;
savingsVariation: string;
}
const etherStore = useEtherStore(); const etherStore = useEtherStore();
etherStore.setSellerView(true); etherStore.setSellerView(true);
const flowStep = ref<Step>(Step.Sell); const flowStep = ref<Step>(Step.Sell);
const loading = ref<boolean>(false); const loading = ref<boolean>(false);
const offerValue = ref<string>(""); const seller = ref<Participant>();
const sellerId = ref<string>();
const showAlert = ref<boolean>(false); const showAlert = ref<boolean>(false);
// Verificar tipagem // Verificar tipagem
const approveOffer = async (args: { const approveOffer = async (args: Participant) => {
offer: string;
postProcessedPixKey: string;
}) => {
loading.value = true; loading.value = true;
try { try {
offerValue.value = args.offer; seller.value = args;
await approveTokens(args.offer); await approveTokens(args.offer);
flowStep.value = Step.Network; flowStep.value = Step.Network;
loading.value = false; loading.value = false;
@ -53,8 +43,10 @@ const approveOffer = async (args: {
const sendNetwork = async () => { const sendNetwork = async () => {
loading.value = true; loading.value = true;
try { try {
if (offerValue.value) { if (seller.value) {
await addDeposit(String(offerValue.value)); const participantWithId = await createParticipant(seller.value);
sellerId.value = participantWithId.id;
await addDeposit(String(seller.value.offer), participantWithId.id);
flowStep.value = Step.Sell; flowStep.value = Step.Sell;
loading.value = false; loading.value = false;
showAlert.value = true; showAlert.value = true;
@ -83,8 +75,8 @@ const sendNetwork = async () => {
/> />
<div v-if="flowStep == Step.Network"> <div v-if="flowStep == Step.Network">
<SendNetwork <SendNetwork
:pixKey="pixKeyBuyer" :sellerId="sellerId"
:offer="Number(offerValue)" :offer="Number(seller?.offer)"
:selected-token="etherStore.selectedToken" :selected-token="etherStore.selectedToken"
v-if="!loading" v-if="!loading"
@send-network="sendNetwork" @send-network="sendNetwork"