Skip to content

Commit

Permalink
🐛 fix bugs: Cart and Product.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashu11-A committed Feb 20, 2024
1 parent dace715 commit d5c964e
Show file tree
Hide file tree
Showing 10 changed files with 387 additions and 32 deletions.
233 changes: 232 additions & 1 deletion src/classes/ctrlPanel.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { core, db } from '@/app'
import { numerosParaLetras, updateProgressAndEstimation } from '@/functions'
import { type PaymentServerCTRL, type PaymentUserCTRL, type UserData } from '@/interfaces'
import axios, { type AxiosError, type AxiosInstance } from 'axios'
import { type UserData } from '@/interfaces'

export class CtrlPanel {
private readonly url
Expand Down Expand Up @@ -44,4 +46,233 @@ export class CtrlPanel {
}
}
}

/**
* Pesquisar um E-mail específico
*/
public async searchEmail (options: {
email: string
guildId: string
}): Promise<{ status: boolean, userData: any[] | undefined }> {
const { email, guildId } = options

let metadata = await db.ctrlPanel.table(`${numerosParaLetras(guildId)}_users`).get('metadata')

if (metadata?.lastPage === undefined) {
metadata = await this.updateDatabase({ guildId, type: 'users' })
}

core.info(`Procurando: ${email}`)
let foundUsers: any[] = []

async function scan (): Promise<{
status: boolean
userData: any[] | undefined
}> {
let status: { status: boolean, userData: any[] | undefined } = { status: false, userData: undefined }
for (let page = 1; page <= metadata.lastPage; page++) {
const dataDB = await db.ctrlPanel.table(`${numerosParaLetras(guildId)}_users`).get(String(page))

if (Array.isArray(dataDB)) {
foundUsers = dataDB.filter(
(user: { email: string }) => user.email.toLowerCase() === email.toLowerCase()
)

if (foundUsers.length > 0) {
core.info(`Pesquisando: ${page}/${metadata.lastPage} | Encontrei`)
status = { status: true, userData: foundUsers }
break
} else {
core.info(`Pesquisando: ${page}/${metadata.lastPage} |`)
}
} else {
core.error('dataDB não é um array iterável.')
status = { status: false, userData: undefined }
break
}

if (page === metadata.last_page) {
status = { status: false, userData: undefined }
break
}
}
return status
}
return await scan()
}

private async updateDatabase (options: {
guildId: string
type: 'users' | 'servers'
}): Promise<
{ lastPage: number, perPage: number, total: number } |
undefined> {
const { guildId, type } = options
const { url, token } = this
const usersData: PaymentUserCTRL[] = []
const serversData: PaymentServerCTRL[] = []
const startTime = Date.now()
let clientCount = 0
let teamCount = 0

async function fetchUsers (urlAPI: string): Promise<{ lastPage: number, perPage: number, total: number } | undefined> {
try {
const response = await axios.get(urlAPI, {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
})

const data = response.data
const users = data.data

for (const user of users) {
const { id, name, email, pterodactyl_id: pterodactylId, role } = user
usersData.push({
id,
name,
email,
pterodactylId,
role
})
if (user.role === 'client') {
clientCount++
}
if (user.role === 'admin') {
teamCount++
}
}

if (data.current_page <= data.last_page) {
const dataBD = await db.ctrlPanel.table(`${numerosParaLetras(guildId)}_users`).get(String(data.current_page))
if (dataBD?.length <= 50 || usersData?.length > 0) {
let isDataChanged = false

for (let i = 0; i < 50; i++) {
if (usersData?.[i] !== undefined && i >= 0 && i < usersData.length) {
if (
(dataBD?.[i] === undefined) ||
(JSON.stringify(usersData?.[i]) !== JSON.stringify(dataBD?.[i]))
) {
// Se houver diferenças, marque como dados alterados
isDataChanged = true
break
}
}
}
if (isDataChanged) {
core.info(`Tabela: ${data.current_page}/${data.last_page} | Mesclando`)
await db.ctrlPanel.table(`${numerosParaLetras(guildId)}_users`).set(`${data.current_page}`, usersData)
} else {
core.info(`Tabela: ${data.current_page}/${data.last_page} | Sincronizado`)
}

if (data.current_page % 2 === 0) {
const { progress, estimatedTimeRemaining } = updateProgressAndEstimation({
totalTables: data.last_page,
currentTable: data.current_page,
startTime
})
core.log(`Tabelas: ${data.current_page}/${data.last_page}`, `Users: ${data.from} - ${data.to} / ${data.total}`, `${progress.toFixed(2)}% | Tempo Restante: ${estimatedTimeRemaining.toFixed(2)}s`)
}
}

if (data.current_page === data.last_page) {
const { last_page: lastPage, per_page: perPage, total } = data
const metadata = {
lastPage,
perPage,
total,
clientCount,
teamCount
}
await db.ctrlPanel.table(`${numerosParaLetras(guildId)}_users`).set('metadata', metadata)
return metadata
} else if (data.next_page_url !== null) {
usersData.length = 0
return await fetchUsers(data.next_page_url)
}
}
} catch (err) {
console.log(err)
}
}

async function fetchServers (urlAPI: string): Promise<{ lastPage: number, perPage: number, total: number } | undefined> {
try {
const response = await axios.get(urlAPI, {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
})

const data = response.data
const servers = data.data

for (const server of servers) {
const { user_id: userId, suspended, created_at: createAt, name, identifier, pterodactyl_id: pterodactylId } = server
serversData.push({
userId,
pterodactylId,
name,
identifier,
suspended,
createAt
})
}

if (data.current_page <= data.last_page) {
const dataBD = await db.ctrlPanel.table(`${numerosParaLetras(guildId)}_servers`).get(String(data.current_page))
if (dataBD?.length <= 50 || serversData?.length > 0) {
let isDataChanged = false

for (let i = 0; i < 50; i++) {
if (serversData?.[i] !== undefined && i >= 0 && i < serversData.length) {
if (
(dataBD?.[i] === undefined) ||
(JSON.stringify(serversData?.[i]) !== JSON.stringify(dataBD?.[i]))
) {
isDataChanged = true
break
}
}
}
if (isDataChanged) {
core.info(`Tabela: ${data.current_page}/${data.last_page} | Mesclando`)
await db.ctrlPanel.table(`${numerosParaLetras(guildId)}_servers`).set(`${data.current_page}`, serversData)
} else {
core.info(`Tabela: ${data.current_page}/${data.last_page} | Sincronizado`)
}
}

if (data.current_page === data.last_page) {
const { last_page: lastPage, per_page: perPage, total } = data
const metadata = {
lastPage,
perPage,
total,
sincDate: Number(new Date())
}
console.log(metadata)
await db.ctrlPanel.table(`${numerosParaLetras(guildId)}_servers`).set('metadata', metadata)
return metadata
} else if (data.next_page_url !== null) {
serversData.length = 0
return await fetchServers(data.next_page_url)
}
}
} catch (err) {
console.log(err)
}
}

// Iniciar o processo sincronizar os dados externos com os atuais
if (type === 'users') {
return await fetchUsers(`${url}/api/users?page=1`)
} else if (type === 'servers') {
return await fetchServers(`${url}/api/servers?page=1`)
}
}
}
24 changes: 21 additions & 3 deletions src/discord/components/account/functions/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,28 @@ export class GenAccount {
/**
* genLogin
*/
public async genLogin (): Promise<Message<boolean> | undefined> {
public async genLogin (options: {
disable: {
ptero?: boolean
dash?: boolean
}
}): Promise<Message<boolean> | undefined> {
const { interaction } = this
const { disable } = options
console.log(disable)
const { urlCtrl, urlPtero, tokenCtrl, tokenPtero, ctrlUserDB, pteroUserDB } = await this.getData()

if (disable.dash === true && disable.ptero === true) {
await interaction.editReply({
embeds: [
new EmbedBuilder({
title: 'Você tem produtos com diferentes características de entrega, no momento isso não é permitido!'
}).setColor('Red')
]
})
return
}

const embed = new EmbedBuilder({
title: `👋 Bem vindo ${interaction.user.username}.`,
description:
Expand All @@ -127,7 +145,7 @@ export class GenAccount {
const row = new ActionRowBuilder<ButtonBuilder>()
// const row2 = new ActionRowBuilder<ButtonBuilder>()

if (urlCtrl !== undefined && tokenCtrl !== undefined) {
if ((urlCtrl !== undefined && tokenCtrl !== undefined) && !(disable.dash ?? false)) {
row.addComponents(
new CustomButtonBuilder({
permission: 'User',
Expand All @@ -150,7 +168,7 @@ export class GenAccount {
// )
}

if (urlPtero !== undefined && tokenPtero !== undefined) {
if ((urlPtero !== undefined && tokenPtero !== undefined) && !(disable.ptero ?? false)) {
row.addComponents(
new CustomButtonBuilder({
permission: 'User',
Expand Down
26 changes: 15 additions & 11 deletions src/discord/components/account/functions/validator.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { validarEmail } from '@/functions'
import { EmbedBuilder, type CacheType, type ModalSubmitInteraction } from 'discord.js'
import { type ButtonInteraction, type CommandInteraction, EmbedBuilder, type StringSelectMenuInteraction, type CacheType, type ModalSubmitInteraction } from 'discord.js'

export async function validator (options: {
url: string
token: string
email: string
interaction: ModalSubmitInteraction<CacheType>
email?: string
interaction: ModalSubmitInteraction<CacheType> | ButtonInteraction<CacheType> | CommandInteraction<CacheType> | StringSelectMenuInteraction<CacheType>
}): Promise<boolean> {
const { email, interaction, token, url } = options

if (url === undefined || token === undefined) {
console.log('❌ | URL ou Token do pterodactyl não está configurado, tente `/config pterodactyl`')
await interaction.reply({
ephemeral,
embeds: [
new EmbedBuilder({
title: '❌ | URL ou Token do pterodactyl não está configurado, tente `/config pterodactyl`'
Expand All @@ -21,14 +22,17 @@ export async function validator (options: {
return true
}

const [isValid, msg] = validarEmail(email)
if (!isValid) {
console.log(msg)
await interaction.reply({
ephemeral,
embeds: [new EmbedBuilder({ title: msg }).setColor('Red')]
})
return true
if (email !== undefined) {
const [isValid, msg] = validarEmail(email)
if (!isValid) {
console.log(msg)
await interaction.reply({
ephemeral,
embeds: [new EmbedBuilder({ title: msg }).setColor('Red')]
})
return true
}
}

return false
}
43 changes: 39 additions & 4 deletions src/discord/components/payments/cart/cartCollectorModal.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { core, db } from '@/app'
import { UpdateCart } from '@/discord/components/payments'
import { validarEmail } from '@/functions'
import { ctrlPanel } from '@/functions/ctrlPanel'
import { EmbedBuilder, type CacheType, type ModalSubmitInteraction } from 'discord.js'
import { EmbedBuilder, codeBlock, type CacheType, type ModalSubmitInteraction } from 'discord.js'
import { getModalData } from './functions/getModalData'
import { PaymentFunction } from './functions/cartCollectorFunctions'
import { CtrlPanel } from '@/classes/ctrlPanel'

export default async function cartCollectorModal (options: {
interaction: ModalSubmitInteraction<CacheType>
Expand All @@ -27,10 +27,45 @@ export default async function cartCollectorModal (options: {
const [validador, messageInfo] = validarEmail(dataInfo.email)
if (validador) {
core.info(`Solicitação para o E-mail: ${dataInfo.email}`)
const userData = await ctrlPanel.searchEmail({ interaction, email: dataInfo.email })
const { token, url } = await db.payments.get(`${guildId}.config.ctrlPanel`)

if (token === undefined || url === undefined) {
await interaction.reply({
ephemeral,
embeds: [
new EmbedBuilder({
title: '☹️ | Desculpe-me, mas o dono do servidor não configurou essa opção...'
}).setColor('Red')
]
})
return
}

const msg = await interaction.reply({
embeds: [
new EmbedBuilder({
title: 'Aguarde, estou consultando os seus dados...',
description: '(Isso pode levar 1 minuto caso sua conta seja nova)'
}).setColor('Yellow')
]
})

const CtrlPanelBuilder = new CtrlPanel({ url, token })
const { status, userData } = await CtrlPanelBuilder.searchEmail({ email: dataInfo.email, guildId })

console.log(status, userData)

await msg.edit({
embeds: [
new EmbedBuilder({
title: (status && userData !== undefined) ? `👋 Olá ${userData[0].name}` : 'Desculpe-me, mas o E-mail informado não foi encontrado...',
description: (status && userData !== undefined) ? codeBlock(`Sabia que seu id é ${userData[0].id}?`) : undefined
})
]
})

if (userData !== undefined) {
await db.payments.set(`${guildId}.process.${channelId}.user`, userData)
await db.payments.set(`${guildId}.process.${channelId}.user`, userData[0])

if (message !== null) {
const PaymentBuilder = new PaymentFunction({ interaction, key })
Expand Down
Loading

0 comments on commit d5c964e

Please sign in to comment.