Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Fernando-Santana-j committed Nov 14, 2024
1 parent 6ada1aa commit 6ab842b
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 35 deletions.
Empty file removed .js
Empty file.
47 changes: 44 additions & 3 deletions Discord/discordIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ module.exports = (Discord2, client) => {
}
}
} catch (error) { }
}, 600000)
}, 400000)
setTimeout(async () => {
try {
let discordChannelDelete = await DiscordServer.channels.cache.get(channelID)
Expand All @@ -350,7 +350,7 @@ module.exports = (Discord2, client) => {
}

} catch (error) { }
}, 1000000)
}, 600000)
}
} else {
return interaction.editReply({ content: '⚠ | Não foi possivel criar o carrinho tente novamente!', ephemeral: true })
Expand Down Expand Up @@ -1991,7 +1991,48 @@ module.exports = (Discord2, client) => {
break;
}
if (estoqueNumber <= 0) {
return interaction.reply({ content: `Esse produto não tem estoque!`, ephemeral: true });
await interaction.reply({
content: `⚠️| O produto selecionado está sem estoque!\n Clique no botão para receber um aviso no privado quando voltar o estoque!`,
components: [
new Discord.ActionRowBuilder().addComponents(
new Discord.ButtonBuilder()
.setCustomId(`solicitarStok_${productId}`)
.setLabel('Solicitar estoque')
.setEmoji(await require('./emojisGet').stock)
.setStyle(Discord.ButtonStyle.Success),
).addComponents(
new Discord.ButtonBuilder()
.setCustomId(`privateAviso_${productId}`)
.setLabel('Receber aviso')
.setEmoji(await require('./emojisGet').notice)
.setStyle(Discord.ButtonStyle.Primary),
)
],
ephemeral: true
})
let analytics = await db.findOne({ colecao: "analytics", doc: interaction.guildId })

if (analytics.error == false) {
let canceladosEstoque = analytics['cancelados estoque']
await canceladosEstoque.push(await functions.formatDate(new Date()))
db.update('analytics', interaction.guildId, {
"cancelados estoque": canceladosEstoque
})
} else {
db.create('analytics', interaction.guildId, {
"cancelados estoque": [await functions.formatDate(new Date())],
"pagamentos": {
"PIX": 0,
"card": 0,
"boleto": 0,
},
"reebolsos": [],
"vendas canceladas": [],
"vendas completas": []
})
}

return
}

let findChannel = interaction.guild.channels.cache.find(c => c.topic === interaction.user.id && c.name && c.name.includes('🛒・carrinho・'))
Expand Down
55 changes: 46 additions & 9 deletions Discord/discordRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const webConfig = require('../config/web-config');
const sharp = require('sharp');
const botConfig = require('../config/bot-config.js');
const { default: axios } = require("axios");
const e = require('express');
const client = new Discord.Client({ intents: botConfig.intents })
client.login(botConfig.discordToken)

Expand Down Expand Up @@ -41,25 +42,46 @@ router.get('/auth/verify/:acesstoken', async (req, res) => {
res.redirect(webConfig.loginURL)
}
})

// test()
// function test(params) {
// const baseUrl = "https://discord.com/oauth2/authorize?";
// const test = new URLSearchParams({
// client_id: webConfig.clientId,
// response_type: "code",
// redirect_uri: webConfig.redirectAuthVerify,
// scope: ["guilds.join", "gdm.join", "guilds", "identify", "email", "connections"].join(" "), // O Discord espera os escopos separados por espaço
// state: '1295184253423980546'
// });
// console.log(baseUrl + test);

// }
router.get('/discord/verify', async (req, res) => {
try {
if (!req.query.code) {
console.log(req.query);

if (!req.query.code || !req.query.state) {
res.redirect('/?error=Codigo invalido')
} else {
let server = await db.findOne({ colecao: 'servers', doc: req.query.state })
console.log(server);

if (server.error == true) {
res.redirect('/?error=Erro ao autenticar')
return
}
let param = new URLSearchParams({
client_id: webConfig.clientId,
client_secret: webConfig.secret,
client_id: '1272947467469459456',
client_secret: '21Fjwn97bHkeSRuJvNRUZCc95n2COimh',
grant_type: 'authorization_code',
code: req.query.code,
redirect_uri: process.env.DISCORDURI
redirect_uri: webConfig.redirectAuthVerify
})
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept-Encoding': 'application/x-www-form-urlencoded'
};
const response = await axios.post('https://discord.com/api/oauth2/token', param, { headers }).then((res) => { return res }).catch((err) => {
console.error(err)
console.error(err.response.data)
})
if (!response) {
res.redirect('/?error=Erro ao autenticar')
Expand All @@ -76,12 +98,27 @@ router.get('/discord/verify', async (req, res) => {



const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
let backups = 'backups' in server ? server.backups : {}
let userVerified = 'verified' in backups ? backups.verified : []
await userVerified.push({
id: await userResponse.id,
username: await userResponse.username,
avatar: await userResponse.avatar,
ip: await ip,
access_token:await response.data.access_token,
refresh_token: await response.data.refresh_token,
email: await userResponse.email,
})


backups.verified = userVerified
db.update('servers', req.query.state, {
backups: backups
})
res.redirect('/')
}
} catch (error) {
res.redirect('/logout')
res.redirect('/')
console.log(error);

}
Expand Down
32 changes: 17 additions & 15 deletions Discord/handler/commands/enviar.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ module.exports = {
titulo = await titulo.replaceAll('@@usersend', SendUser.username)
mensagem = await mensagem.replaceAll('@@usersend', SendUser.username)


let verifyPermissions = await functions.verifyPermissions(interaction.user.id, interaction.guildId, Discord, client)
if (verifyPermissions.error == false && verifyPermissions.perms.commands == true) {
if (serverData && serverData.botActive == false) {
Expand Down Expand Up @@ -134,26 +133,29 @@ module.exports = {
interaction.reply({ content: 'Não foi possivel enviar a mensagem privado do usuario selecionado ele pode ter bloqueado o privado!', ephemeral: true })
return
}
interaction.reply({
embeds: [
new Discord.EmbedBuilder()
.setTitle(`✅ | Produto enviado!`)
.setDescription(`Você enviou um produto para ${user.globalName}, foi enviado em seu privado uma copia do arquivo que o usuario recebeu!`)
.setAuthor({ name: "SDKApps", iconURL: `https://res.cloudinary.com/dgcnfudya/image/upload/v1711769157/vyzyvzxajoboweorxh9s.png` })
.setColor('personalize' in serverData && 'colorDest' in serverData.personalize ? serverData.personalize.colorDest : '#6E58C7')
.setTimestamp()
.setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp ` })
],
ephemeral: true
})
try {
interaction.reply({
embeds: [
new Discord.EmbedBuilder()
.setTitle(`✅ | Produto enviado!`)
.setDescription(`Você enviou um produto para ${user.globalName}, foi enviado em seu privado uma copia do arquivo que o usuario recebeu!`)
.setAuthor({ name: "SDKApps", iconURL: `https://res.cloudinary.com/dgcnfudya/image/upload/v1711769157/vyzyvzxajoboweorxh9s.png` })
.setColor('personalize' in serverData && 'colorDest' in serverData.personalize ? serverData.personalize.colorDest : '#6E58C7')
.setTimestamp()
.setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp ` })
],
ephemeral: true
})
} catch (error) {
console.log(error);
}
try {
SendUser.send({
content: `Copia do ultimo produto (${product.productName}) enviado para o usuario ${user.globalName}:`,
files: [attachment]
})
} catch (error) {
console.log(error);

interaction.reply({ content: 'Não foi possivel enviar a copia no seu privado ele pode estar bloqueado', ephemeral: true })
return
}
Expand All @@ -176,7 +178,7 @@ module.exports = {
db.update('servers', interaction.guild.id, {
products: serverData.products
})

} else {
interaction.reply({ content: 'Falta de estoque!', ephemeral: true })
}
Expand Down
2 changes: 2 additions & 0 deletions config/web-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ module.exports = {
secret: process.env.CLIENTSECRET,
clientId: process.env.CLIENTID,
redirect: process.env.REDIRECTURL,
redirectAuthVerify: process.env.DISCORDAUTHREDIRECT,
redirectDashboard: process.env.DASHBOARDREDIRECT,
stripe: process.env.STRIPE,
iban: process.env.IBAN,
stripeAccount: process.env.STRIPEACCOUNT,
Expand Down
19 changes: 13 additions & 6 deletions functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -422,12 +422,19 @@ module.exports = {
},

comprimAndRecort: async (arquivoOrigem, novoCaminho) => {
const metadata = await sharp(arquivoOrigem).metadata();
return await sharp(arquivoOrigem, { animated: metadata.pages > 1 })
[metadata.format === 'gif' && metadata.pages > 1 ? 'gif' : 'png']({ quality: 70 })
.toFile(novoCaminho)
.then(() => fs.unlink(arquivoOrigem))
.catch(err => ({ error: true, err }));
try {
const metadata = await sharp(arquivoOrigem).metadata();
const format = metadata.format === 'gif' && metadata.pages > 1 ? 'gif' : 'png';

await sharp(arquivoOrigem, { animated: metadata.pages > 1 })
[format]({ quality: 70 })
.toFile(novoCaminho);

await fs.unlink(arquivoOrigem);
return { success: true };
} catch (err) {
return { error: true, err };
}
},
formatarMoeda: (numeroCentavos) => {
const valorReal = numeroCentavos / 100;
Expand Down
4 changes: 2 additions & 2 deletions stripe/productsRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,8 @@ router.post('/product/update', functions.authPostState, upload.fields([{ name: '

let logo = produto.productLogo
if (req.files.productLogo) {
logo = await functions.comprimAndRecort(req.files.productLogo[0].path, path.join(__dirname, '..', `/uploads/produtos/logos/${'logo_' + req.files.productLogo[0].filename}`))
logo = `/uploads/produtos/logos/${'logo_' + req.files.productLogo[0].filename}`
await functions.comprimAndRecort(req.files.productLogo[0].path, path.join(__dirname, '..', `/uploads/produtos/logos/${'logo_' + req.files.productLogo[0].filename}`))
}

let typeProduct = 'typeProduct' in produto ? produto.typeProduct : 'normal'
Expand Down Expand Up @@ -306,7 +307,6 @@ router.post('/product/update', functions.authPostState, upload.fields([{ name: '
}

let produtos = server.products

produto.productName = req.body.productName,
produto.producDesc = req.body.producDesc,
produto.price = req.body.price,
Expand Down

0 comments on commit 6ab842b

Please sign in to comment.