From 30e86ecaca6b616aa0d4ff80f7587e539e8bb442 Mon Sep 17 00:00:00 2001 From: fernando Date: Tue, 13 Aug 2024 14:19:54 -0300 Subject: [PATCH] fix --- .gitignore | 2 +- Discord/createProductMessageEmbend.js | 4 +- Discord/createTicketMensage.js | 21 +- Discord/discordIndex.js | 351 +++++++++++++------------- index.js | 24 +- public/js/personalize.js | 20 +- public/js/ticket.js | 13 + views/personalize.ejs | 4 +- 8 files changed, 219 insertions(+), 220 deletions(-) diff --git a/.gitignore b/.gitignore index 382136f..ca566e2 100644 --- a/.gitignore +++ b/.gitignore @@ -6,5 +6,5 @@ config/web-config.js config config/mercadoPagoData.json - +/uploads /cart.list \ No newline at end of file diff --git a/Discord/createProductMessageEmbend.js b/Discord/createProductMessageEmbend.js index fb43286..ffec283 100644 --- a/Discord/createProductMessageEmbend.js +++ b/Discord/createProductMessageEmbend.js @@ -49,8 +49,8 @@ module.exports = async (Discord2, client, data) => { } let backGroundLink = '' let logoLink = '' - logoLink = produto.productLogo ? await functions.discordDB(produto.productLogo,client,Discord) : `` - backGroundLink = produto.backGround ? await functions.discordDB(produto.backGround,client,Discord) : `` + logoLink = produto.productLogo ? await functions.discordDB(produto.productLogo,client,Discord) : null + backGroundLink = produto.backGround ? await functions.discordDB(produto.backGround,client,Discord) : null let embed = await DiscordChannel.send({ embeds: [ diff --git a/Discord/createTicketMensage.js b/Discord/createTicketMensage.js index d6e3e71..eb5bb34 100644 --- a/Discord/createTicketMensage.js +++ b/Discord/createTicketMensage.js @@ -1,9 +1,11 @@ let Discord = require('discord.js') let db = require('../Firebase/models') let webConfig = require('../config/web-config') +let botConfig = require('../config/bot-config') const path = require('path') const fs = require('fs') const sharp = require('sharp') +const functions = require('../functions') module.exports = async (client, channelID, serverID) => { try { @@ -28,23 +30,8 @@ module.exports = async (client, channelID, serverID) => { ) } } - let dburl = null - let Newdbres = null - if (serverData && 'ticketOptions' in serverData && 'banner' in serverData.ticketOptions) { - const bannerPath = path.join(__dirname, '..', serverData.ticketOptions.banner); - let file = await fs.readFileSync(bannerPath); - let buffer = Buffer.from(file, 'binary'); - let newBuffer = await sharp(buffer).jpeg().toBuffer() - const attachment = new Discord.AttachmentBuilder(newBuffer, { name: 'test.jpg' }); - let dbBannerDiscordServer = await client.guilds.cache.get('1246186853241978911') - let dbBannerDiscordChannel = await dbBannerDiscordServer.channels.cache.get('1253279027662426142') - let dbres = await dbBannerDiscordChannel.send({ - files: [attachment] - }) - Newdbres = dbres - dburl = await dbres.attachments.first().url - } - + let dburl = serverData.ticketOptions.banner ? await functions.discordDB(serverData.ticketOptions.banner,client,Discord) : null + //salvar essa url no banco de dados para nao precisar ta criando toda hora uma nova mensagem await DiscordChannel.send({ embeds: [ diff --git a/Discord/discordIndex.js b/Discord/discordIndex.js index 69e7284..ca4a4a7 100644 --- a/Discord/discordIndex.js +++ b/Discord/discordIndex.js @@ -60,176 +60,6 @@ client.on('guildMemberAdd', async member => { } }); - - -async function comprarFunction(productID,interaction) { - let server = await db.findOne({ colecao: "servers", doc: interaction.guildId }) - let product = await server.products.find(product => product.productID == productID) - let findChannel = interaction.guild.channels.cache.find(c => c.topic === interaction.user.id && c.name && c.name.includes('🛒・carrinho・')) - if (!product || server.error == true || product.estoque.length <= 0) { - 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(`privateAviso_${productID}`) - .setLabel('Receber aviso') - .setStyle(Discord.ButtonStyle.Primary), - ) - ], - ephemeral: true - }) - let analytics = await db.findOne({ colecao: "analytics", doc: server.id }) - - if (analytics.error == false) { - let canceladosEstoque = analytics['cancelados estoque'] - await canceladosEstoque.push(await functions.formatDate(new Date())) - db.update('analytics', server.id, { - "cancelados estoque": canceladosEstoque - }) - } else { - db.create('analytics', server.id, { - "cancelados estoque": [await functions.formatDate(new Date())], - "pagamentos": { - "PIX": 0, - "card": 0, - "boleto": 0, - }, - "reebolsos": [], - "vendas canceladas": [], - "vendas completas": [] - }) - } - - return - } - async function findUniCarrinhos() { - let prodid = productID - let findItem - if (preCarrinhos[interaction.user.id]) { - findItem = await preCarrinhos[interaction.user.id].find(element => element.product == prodid) - } else { - findItem = null - } - if (!carrinhos[interaction.user.id]) { - carrinhos[interaction.user.id] = [] - } - if (findItem) { - carrinhos[interaction.user.id].push(findItem) - } else { - carrinhos[interaction.user.id].push({ - product: prodid, - quantidade: 1 - }) - } - } - if (findChannel) { - if (!carrinhos[interaction.user.id]) { - interaction.reply({ content: 'O seu carrinho expirou vamos apaga-lo! Apos isso você poderá adicionar produtos ao seu novo carrinho! ', ephemeral: true }) - await deleteExpiredCart(interaction.guildId, interaction, findChannel.id) - return - } - let prodid = await productID - let findProductCart = await carrinhos[interaction.user.id].find((item) => item.product == prodid) - let findProductCartIndex = await carrinhos[interaction.user.id].findIndex((item) => item.product == prodid) - if (findProductCart) { - carrinhos[interaction.user.id][findProductCartIndex].quantidade = parseInt(carrinhos[interaction.user.id][findProductCartIndex].quantidade) + 1 - } else { - findUniCarrinhos() - } - - interaction.reply({ - embeds: [ - new Discord.EmbedBuilder() - .setColor("#C21010") - .setTitle(`⚠️| Você já possui um carrinho aberto!`) - .setDescription(`Adicionamos esse produto ao seu carrinho!`) - ], - components: [ - new Discord.ActionRowBuilder() - .addComponents( - new Discord.ButtonBuilder() - .setStyle(5) - .setLabel('🛒・Ir para o Carrinho') - .setURL(`https://discord.com/channels/${interaction.guild.id}/${findChannel.id}`) - ) - ], - ephemeral: true - }) - - require('./createCartMessage')(Discord, client, { - serverID: interaction.guild.id, - user: interaction.user, - member: interaction.member, - channelID: await findChannel.id, - edit: true - }) - - } else { - let categoria = DiscordServer.channels.cache.find(c => c.type === Discord.ChannelType.GuildCategory && c.name === 'carrinhos') - if (!categoria) { - categoria = await DiscordServer.channels.create({ - name: 'carrinhos', - type: Discord.ChannelType.GuildCategory, - permissionOverwrites: [{ - id: DiscordServer.roles.everyone, - deny: [Discord.PermissionsBitField.Flags.ViewChannel] - }] - }); - } - const newChannel = await DiscordServer.channels.create({ - name: `🛒・Carrinho・${interaction.user.username}`, - type: 0, - parent: categoria, - topic: interaction.user.id, - permissionOverwrites: [{ - id: interaction.user.id, - allow: [Discord.PermissionsBitField.Flags.ViewChannel] - }, { - id: DiscordServer.roles.everyone, - deny: [Discord.PermissionsBitField.Flags.ViewChannel] - }] - }) - if (newChannel) { - await interaction.reply({ - content: `🛒 | Criando o Carrinho...`, - ephemeral: true - }) - setTimeout(() => { - interaction.editReply({ - content: ` `, - embeds: [ - new Discord.EmbedBuilder() - .setColor('personalize' in server && 'colorDest' in server.personalize ? server.personalize.colorDest : '#6E58C7') - .setTitle(`😍 | Carrinho Criado!`) - .setDescription(`<@${interaction.user.id}> **Seu carrinho foi criado com sucesso, fique avontade para adicionar mais produtos.**`) - ], - components: [ - new Discord.ActionRowBuilder() - .addComponents( - new Discord.ButtonBuilder() - .setStyle(5) - .setLabel('🛒・Ir para o Carrinho') - .setURL(`https://discord.com/channels/${interaction.guild.id}/${newChannel.id}`) - ) - ], - ephemeral: true - }); - }, 2500); - } else { - return interaction.reply({ content: 'Não foi possivel criar o carrinho tente novamente!', ephemeral: true }) - } - findUniCarrinhos() - require('./createCartMessage')(Discord, client, { - serverID: interaction.guild.id, - user: interaction.user, - member: interaction.member, - channelID: await newChannel.id, - edit: false - }) - } -} - module.exports = (Discord2, client) => { try { @@ -245,12 +75,187 @@ module.exports = (Discord2, client) => { var DeleteDiscordChannel = await DiscordServer.channels.cache.get(deleteChannel) await DeleteDiscordChannel.delete() if (interection && interection.replied) { - interection.editReply({ content: 'O seu carrinho expirou vamos apaga-lo! Status: Carrinho apagado!', ephemeral: true }) + interection.editReply({ content: 'O seu carrinho expirou vamos apaga-lo! \n Status: Carrinho apagado!', ephemeral: true }) } } catch (error) { console.log(error); } } + + + async function comprarFunction(productID,interaction) { + var DiscordServer = await client.guilds.cache.get(interaction.guildId); + var DiscordChannel = await DiscordServer.channels.cache.get(interaction.channelId) + + let server = await db.findOne({ colecao: "servers", doc: interaction.guildId }) + let product = await server.products.find(product => product.productID == productID) + let findChannel = interaction.guild.channels.cache.find(c => c.topic === interaction.user.id && c.name && c.name.includes('🛒・carrinho・')) + if (!product || server.error == true || product.estoque.length <= 0) { + 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(`privateAviso_${productID}`) + .setLabel('Receber aviso') + .setStyle(Discord.ButtonStyle.Primary), + ) + ], + ephemeral: true + }) + let analytics = await db.findOne({ colecao: "analytics", doc: server.id }) + + if (analytics.error == false) { + let canceladosEstoque = analytics['cancelados estoque'] + await canceladosEstoque.push(await functions.formatDate(new Date())) + db.update('analytics', server.id, { + "cancelados estoque": canceladosEstoque + }) + } else { + db.create('analytics', server.id, { + "cancelados estoque": [await functions.formatDate(new Date())], + "pagamentos": { + "PIX": 0, + "card": 0, + "boleto": 0, + }, + "reebolsos": [], + "vendas canceladas": [], + "vendas completas": [] + }) + } + + return + } + async function findUniCarrinhos() { + let prodid = productID + let findItem + if (preCarrinhos[interaction.user.id]) { + findItem = await preCarrinhos[interaction.user.id].find(element => element.product == prodid) + } else { + findItem = null + } + if (!carrinhos[interaction.user.id]) { + carrinhos[interaction.user.id] = [] + } + if (findItem) { + carrinhos[interaction.user.id].push(findItem) + } else { + carrinhos[interaction.user.id].push({ + product: prodid, + quantidade: 1 + }) + } + } + if (findChannel) { + if (!carrinhos[interaction.user.id]) { + interaction.reply({ content: 'O seu carrinho expirou vamos apaga-lo! Apos isso você poderá adicionar produtos ao seu novo carrinho! ', ephemeral: true }) + await deleteExpiredCart(interaction.guildId, interaction, findChannel.id) + return + } + let prodid = await productID + let findProductCart = await carrinhos[interaction.user.id].find((item) => item.product == prodid) + let findProductCartIndex = await carrinhos[interaction.user.id].findIndex((item) => item.product == prodid) + if (findProductCart) { + carrinhos[interaction.user.id][findProductCartIndex].quantidade = parseInt(carrinhos[interaction.user.id][findProductCartIndex].quantidade) + 1 + } else { + findUniCarrinhos() + } + + interaction.reply({ + embeds: [ + new Discord.EmbedBuilder() + .setColor("#C21010") + .setTitle(`⚠️| Você já possui um carrinho aberto!`) + .setDescription(`Adicionamos esse produto ao seu carrinho!`) + ], + components: [ + new Discord.ActionRowBuilder() + .addComponents( + new Discord.ButtonBuilder() + .setStyle(5) + .setLabel('🛒・Ir para o Carrinho') + .setURL(`https://discord.com/channels/${interaction.guild.id}/${findChannel.id}`) + ) + ], + ephemeral: true + }) + + require('./createCartMessage')(Discord, client, { + serverID: interaction.guild.id, + user: interaction.user, + member: interaction.member, + channelID: await findChannel.id, + edit: true + }) + + } else { + let categoria = DiscordServer.channels.cache.find(c => c.type === Discord.ChannelType.GuildCategory && c.name === 'carrinhos') + if (!categoria) { + categoria = await DiscordServer.channels.create({ + name: 'carrinhos', + type: Discord.ChannelType.GuildCategory, + permissionOverwrites: [{ + id: DiscordServer.roles.everyone, + deny: [Discord.PermissionsBitField.Flags.ViewChannel] + }] + }); + } + const newChannel = await DiscordServer.channels.create({ + name: `🛒・Carrinho・${interaction.user.username}`, + type: 0, + parent: categoria, + topic: interaction.user.id, + permissionOverwrites: [{ + id: interaction.user.id, + allow: [Discord.PermissionsBitField.Flags.ViewChannel] + }, { + id: DiscordServer.roles.everyone, + deny: [Discord.PermissionsBitField.Flags.ViewChannel] + }] + }) + if (newChannel) { + await interaction.reply({ + content: `🛒 | Criando o Carrinho...`, + ephemeral: true + }) + setTimeout(() => { + interaction.editReply({ + content: ` `, + embeds: [ + new Discord.EmbedBuilder() + .setColor('personalize' in server && 'colorDest' in server.personalize ? server.personalize.colorDest : '#6E58C7') + .setTitle(`😍 | Carrinho Criado!`) + .setDescription(`<@${interaction.user.id}> **Seu carrinho foi criado com sucesso, fique avontade para adicionar mais produtos.**`) + ], + components: [ + new Discord.ActionRowBuilder() + .addComponents( + new Discord.ButtonBuilder() + .setStyle(5) + .setLabel('🛒・Ir para o Carrinho') + .setURL(`https://discord.com/channels/${interaction.guild.id}/${newChannel.id}`) + ) + ], + ephemeral: true + }); + }, 2500); + } else { + return interaction.reply({ content: 'Não foi possivel criar o carrinho tente novamente!', ephemeral: true }) + } + findUniCarrinhos() + require('./createCartMessage')(Discord, client, { + serverID: interaction.guild.id, + user: interaction.user, + member: interaction.member, + channelID: await newChannel.id, + edit: false + }) + } + } + + + //ticket client.on('messageCreate', async message => { @@ -434,11 +439,11 @@ module.exports = (Discord2, client) => { // interacao do botao de compra de um produto if (interaction.customId && interaction.customId.includes('comprar')) { - comprarFunction(interaction.customId.replace('comprar_', '')) + comprarFunction(interaction.customId.replace('comprar_', ''),interaction) } if (interaction.customId == 'multSelectProduct') { - comprarFunction(interaction.values[0]) + comprarFunction(interaction.values[0],interaction) } if (interaction.customId && interaction.customId.includes('privateAviso')) { diff --git a/index.js b/index.js index 1c370de..b3d46a7 100644 --- a/index.js +++ b/index.js @@ -114,24 +114,6 @@ client.on(Events.ShardError, error => { console.error('A websocket connection encountered an error:', error); }); -process.on('unhandledRejection', error => { - console.error('Unhandled promise rejection:', error); -}); - -process.on('unhandRejection', (reason, promise) => { - console.log(`🚫 Erro Detectado:\n\n` + reason, promise) -}); - -process.on('uncaughtException', (error, origin) => { - console.log(`🚫 Erro Detectado:\n\n` + error, origin) -}); - -process.on('uncaughtExceptionMonitor', (error, origin) => { - console.log(`🚫 Erro Detectado:\n\n` + error, origin) -}); - - - //TODO------------WEB PAGE-------------- @@ -991,7 +973,7 @@ app.post('/personalize/welcomeActive', async (req, res) => { if (server) { server.personalize.welcomeMensage.active = true db.update('servers', req.body.serverID, { - personalize: personalize + personalize: server.personalize }) if (!res.headersSent) { res.status(200).json({ success: true, }) @@ -1014,7 +996,7 @@ app.post('/personalize/welcomeDesactive', async (req, res) => { if (server) { server.personalize.welcomeMensage.active = false db.update('servers', req.body.serverID, { - personalize: personalize + personalize: server.personalize }) if (!res.headersSent) { res.status(200).json({ success: true, }) @@ -1277,7 +1259,7 @@ app.post('/ticket/banner', upload.single('BannerTicket'), async (req, res) => { ticketOptions: ticketOptions }) if (ticketOptions.channel) { - require('./Discord/createTicketMensage.js')(client, ticketOptions.channel, body.serverID) + require('./Discord/createTicketMensage.js')(client, ticketOptions.channel, req.body.serverID) } if (!res.headersSent) { res.status(200).json({ success: true, data: 'Banner Alterado!' }) diff --git a/public/js/personalize.js b/public/js/personalize.js index 4d9b18b..7c0ad66 100644 --- a/public/js/personalize.js +++ b/public/js/personalize.js @@ -146,6 +146,18 @@ document.getElementById('welcome-channel-input').addEventListener('blur', functi } }); document.getElementById('save-mensage-welcome').addEventListener('click',async()=>{ + if (document.getElementById(`title-welcome`).value.trim().length <= 0) { + errorNotify(`Insira um titulo primeiro!`) + return + } + if (document.getElementById(`mensage-welcome`).value.trim().length <= 0) { + errorNotify(`Insira uma mensagem primeiro!`) + return + } + if (document.getElementById(`welcome-channel-input`).value.trim().length <= 0) { + errorNotify(`Insira um canal primeiro!`) + return + } const opcoes = document.getElementById('welcome-channel-list').querySelectorAll('option'); let channelID = null; @@ -186,8 +198,8 @@ document.getElementById('desative-welcome').addEventListener('click',async()=>{ }).then(response => { return response.json() }) if (session.success == true) { successNotify('Mensagem de boas vindas desativada!') - document.getElementById(`active-welcome`).classList.add(`hidden`) - document.getElementById(`desative-welcome`).classList.remove(`hidden`) + document.getElementById(`active-welcome`).classList.remove(`hidden`) + document.getElementById(`desative-welcome`).classList.add(`hidden`) }else{ errorNotify(session.data) } @@ -205,8 +217,8 @@ document.getElementById('active-welcome').addEventListener('click',async()=>{ }).then(response => { return response.json() }) if (session.success == true) { successNotify('Mensagem de boas vindas ativada!') - document.getElementById(`active-welcome`).classList.remove(`hidden`) - document.getElementById(`desative-welcome`).classList.add(`hidden`) + document.getElementById(`active-welcome`).classList.add(`hidden`) + document.getElementById(`desative-welcome`).classList.remove(`hidden`) }else{ errorNotify(session.data) } diff --git a/public/js/ticket.js b/public/js/ticket.js index 52c5eeb..3f30f77 100644 --- a/public/js/ticket.js +++ b/public/js/ticket.js @@ -60,6 +60,19 @@ document.getElementById('motivo-responsavel-ticket-edit').addEventListener('blur }); document.getElementById('save-channel-ticket').addEventListener('click',async()=>{ + let server = await fetch('/get/server', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + serverID:serverID + }), + }).then(response => { return response.json() }) + if (server.success == true && `ticketOptions` in server.data && server.data.ticketOptions.motivos.length <= 0) { + errorNotify(`Cadastre um motivo primeiro!`) + return + } if (document.getElementById('bot-ticket-channel').value <= 0) { errorNotify('Selecione um canal primeiro!') return diff --git a/views/personalize.ejs b/views/personalize.ejs index 0d51150..8875993 100644 --- a/views/personalize.ejs +++ b/views/personalize.ejs @@ -84,11 +84,11 @@ <% } %>
- +
- +