diff --git a/Discord/createProductMessageEmbend.js b/Discord/createProductMessageEmbend.js new file mode 100644 index 0000000..cb9788a --- /dev/null +++ b/Discord/createProductMessageEmbend.js @@ -0,0 +1,139 @@ +const db = require('../Firebase/models') +require('dotenv').config() +const path = require('path') +let Discord = require('discord.js') +const fs = require('fs'); +const sharp = require('sharp'); + +module.exports = async (Discord2, client, data) => { + try { + const DiscordServer = await client.guilds.cache.get(data.serverID); + const DiscordChannel = await DiscordServer.channels.cache.get(data.channelID); + + if (data.edit == true ) { + try { + const fetched = await DiscordChannel.messages.fetch({ limit: 100 }); + await DiscordChannel.bulkDelete(fetched) + } catch (error) {} + } + + let serverId = await data.serverID + let serverDb = await db.findOne({ colecao: 'servers', doc: serverId }) + let produtos = await serverDb.products + let productId = await data.productID + + var produto = await serverDb.products.find(product => product.productID == productId) + var index = await serverDb.products.findIndex(product => product.productID == productId) + let preco = await (produto.price / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }); + + let totalEstoque = [] + if (produto.estoque.length > 0) { + let estoque = produto.estoque.length > 25 ? 25 : produto.estoque.length + for (let index = 0; index < estoque; index++) { + let indexSring1 = `${index + 1}` + if (index == 0) { + totalEstoque.push(new Discord.StringSelectMenuOptionBuilder().setLabel(indexSring1).setValue(indexSring1).setDefault(true),) + }else{ + totalEstoque.push(new Discord.StringSelectMenuOptionBuilder().setLabel(indexSring1).setValue(indexSring1),) + } + + } + } + if (totalEstoque.length > 25) { + const numToRemove = totalEstoque.length - 25; + await totalEstoque.splice(-numToRemove); + } + if (totalEstoque.length <= 0) { + totalEstoque.push(new Discord.StringSelectMenuOptionBuilder().setLabel('Sem estoque').setValue('null').setDefault(true),) + } + let dburl = null + let Newdbres = null + if (produto.backGround) { + const bannerPath = path.join(__dirname, "..", produto.backGround); + 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 dburl2 = null + let Newdbres2 = null + if (produto.productLogo) { + const bannerPath = path.join(__dirname, "..", produto.productLogo); + 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] + }) + Newdbres2 = dbres + dburl2 = await dbres.attachments.first().url + } + let embed = await DiscordChannel.send({ + embeds: [ + new Discord.EmbedBuilder() + .setTitle(produto.productName,) + .setDescription(produto.producDesc) + .setColor('personalize' in serverDb && 'colorDest' in serverDb.personalize ? serverDb.personalize.colorDest : '#6E58C7') + .setTimestamp() + .setFields({ + name:'Preço:', + value:preco.toString(), + inline:true + },{ + name:"Estoque:", + value: produto.estoque.length.toString(), + inline:true + }) + .setThumbnail('personalize' in serverDb && 'iconProduct' in serverDb.personalize ? serverDb.personalize.iconProduct == true ? dburl2 : null : dburl2) + .setImage(dburl) + .setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp` }) + ], + components: [ + new Discord.ActionRowBuilder().addComponents( + new Discord.StringSelectMenuBuilder() + .setCustomId(`qntProduct_${data.productID}`) + .setPlaceholder('Selecione a quantidade!') + .setMinValues(1) + .setMaxValues(1) + .addOptions(...totalEstoque) + .setDisabled(produto.estoque.length <= 0 ? true : false) + ), + new Discord.ActionRowBuilder().addComponents( + new Discord.ButtonBuilder() + .setCustomId(`comprar_${data.productID}`) + .setLabel('Comprar') + .setStyle('3'), + ) + ] + }); + try { + DiscordChannel.setTopic(data.productID) + produto.mensageID = embed.id + + produtos[index] = produto; + + db.update('servers', data.serverID, { + products: produtos + }) + } catch (error) { + console.log(error); + } + + + + } catch (error) { + console.log(error); + } + +}; + diff --git a/Discord/discordIndex.js b/Discord/discordIndex.js index 0d7fa27..ed5bde2 100644 --- a/Discord/discordIndex.js +++ b/Discord/discordIndex.js @@ -688,7 +688,8 @@ module.exports = (Discord2, client) => { interaction.deleteReply().then((res) => { }).catch((err) => { }) } - if (interaction.customId == 'productSendConfirm') { + if (interaction.customId && interaction.customId.includes('productSendConfirm')) { + let quantidade = parseInt(interaction.customId.replace('productSendConfirm-','')) if (sendProduct[interaction.guild.id] && sendProduct[interaction.guild.id].user && sendProduct[interaction.guild.id].product) { let server = await db.findOne({ colecao: "servers", doc: interaction.guild.id }) const user = await client.users.fetch(await sendProduct[interaction.guild.id].user); @@ -700,30 +701,41 @@ module.exports = (Discord2, client) => { var productIndex = await server.products.findIndex(product => product.productID == productID) let estoqueData = await server.products[productIndex].estoque if (product && productIndex != -1 && estoqueData) { - if (estoqueData.length > 0) { + if (estoqueData.length >= quantidade) { let fields = [] - for (let index = 0; index < estoqueData[0].conteudo.length; index++) { - const element = estoqueData[0].conteudo[index]; - fields.push({ name: element.title, value: "`" + element.content + "`" }) + for (let index = 0; index < quantidade; index++) { + const element2 = estoqueData[0].conteudo; + + await element2.forEach(element=>{ + fields.push({ name: element.title, value: "`" + element.content + "`" }) + }) + await estoqueData.splice(0, 1); + product.estoque = estoqueData + server.products[productIndex] = product + db.update('servers',interaction.guild.id,{ + products: server.products + }) } + const concatenatedString = await fields.map(obj => `${obj.value.replace(/`/g, '')}`).join('\n'); + const buffer = Buffer.from(concatenatedString, 'utf-8'); + const attachment = new Discord.AttachmentBuilder(buffer, { name: 'compras.txt' }); user.send({ embeds: [ new Discord.EmbedBuilder() .setTitle(`🛍️ | Você recebeu um produto!`) .setDescription(`Você recebeu um novo produto de ${SendUser.globalName}`) - .addFields(...fields) .setAuthor({ name: "SDKApps", iconURL: `https://res.cloudinary.com/dgcnfudya/image/upload/v1711769157/vyzyvzxajoboweorxh9s.png`}) .setColor('personalize' in server && 'colorDest' in server.personalize ? server.personalize.colorDest : '#6E58C7') .setTimestamp() .setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp ` }) ], + files:[attachment] }).then((res) => { interaction.reply({ embeds: [ new Discord.EmbedBuilder() .setTitle(`✅ | Produto enviado!`) .setDescription(`Você enviou um produto para ${user.globalName} Abaixo esta uma copia do que foi enviado:`) - .addFields(...fields) .setAuthor({ name: "SDKApps", iconURL: `https://res.cloudinary.com/dgcnfudya/image/upload/v1711769157/vyzyvzxajoboweorxh9s.png`}) .setColor('personalize' in server && 'colorDest' in server.personalize ? server.personalize.colorDest : '#6E58C7') .setTimestamp() @@ -734,9 +746,7 @@ module.exports = (Discord2, client) => { }).catch(err => { console.log("err", err); }) - await estoqueData.splice(0, 1); - product.estoque = estoqueData - server.products[productIndex] = product + db.update('servers', interaction.guild.id, { products: server.products @@ -1537,15 +1547,51 @@ module.exports.sendProductPayment = async (params, id, type) => { ) ] }).catch((err) => { + if (product.embendType == 0) { + require('../Discord/createProductMessageEmbend.js')(Discord, client, { + channelID: product.channel, + serverID: params.serverID, + productID: element.product, + edit: true + }) + }else{ + require('../Discord/createProductMessage.js')(Discord, client, { + channelID: product.channel, + serverID: params.serverID, + productID: element.product, + edit: true + }) + } + + }) + } else { + if (product.embendType == 0) { + require('../Discord/createProductMessageEmbend.js')(Discord, client, { + channelID: product.channel, + serverID: params.serverID, + productID: element.product, + edit: true + }) + }else{ require('../Discord/createProductMessage.js')(Discord, client, { channelID: product.channel, serverID: params.serverID, productID: element.product, edit: true }) + } + } + + } catch (error) { + if (product.embendType == 0) { + require('../Discord/createProductMessageEmbend.js')(Discord, client, { + channelID: product.channel, + serverID: params.serverID, + productID: element.product, + edit: true }) - } else { + }else{ require('../Discord/createProductMessage.js')(Discord, client, { channelID: product.channel, serverID: params.serverID, @@ -1553,15 +1599,6 @@ module.exports.sendProductPayment = async (params, id, type) => { edit: true }) } - - } catch (error) { - - require('../Discord/createProductMessage.js')(Discord, client, { - channelID: product.channel, - serverID: params.serverID, - productID: element.product, - edit: true - }) } } } @@ -1614,27 +1651,6 @@ module.exports.sendProductPayment = async (params, id, type) => { sendTxtMensage(dono) } else { try { - await dono.send({ - embeds: [ - new Discord.EmbedBuilder() - .setTitle(`Nova compra no servidor: ${DiscordServer.name}`) - .setDescription(`Abaixo estão os dados que foram entregues:`) - .addFields( - { name: '\u200B', value: '\u200B' }, - { name: 'Nome do usuario comprador', value: user.username, inline: true }, - { name: 'ID do usuario', value: user.id, inline: true }, - { name: 'ID da compra', value: findChannel.id }, - { name: 'Data e hora da compra', value: dataHoraFormatada }, - { name: '\u200B', value: '\u200B' }, - ...fields - ) - .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') - .setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp` }) - ], - }).catch(() => { - sendTxtMensage(dono) - }) // dono.send({ files: [attachment] }).catch(()=>{}); await user.send({ embeds: [ @@ -1672,6 +1688,8 @@ module.exports.sendProductPayment = async (params, id, type) => { sendTxtMensage(findChannel) }) // findChannel.send({ files: [attachment] }).catch(()=>{}); + + } catch (error) { sendTxtMensage(findChannel) sendTxtMensage(user) @@ -1679,10 +1697,9 @@ module.exports.sendProductPayment = async (params, id, type) => { } } - - if ('configs' in serverData && 'publicBuyChannel' in serverData.configs && serverData.configs.publicBuyChannel) { + if ('saleLogs' in serverData && serverData.saleLogs.publicLog) { try { - let findChannelPublic = DiscordServer.channels.cache.find(c => c.id === serverData.configs.publicBuyChannel) + let findChannelPublic = DiscordServer.channels.cache.find(c => c.id === serverData.saleLogs.publicLog) let fieldsPublic = { name: `Carrinho:`, value: '' } let valorTotal = 0 await carrinho.forEach(async (element, index) => { @@ -1724,6 +1741,99 @@ module.exports.sendProductPayment = async (params, id, type) => { console.log("LogPublicError", error); } } + if ('saleLogs' in serverData && serverData.saleLogs.privateLog) { + let findChannelPrivate = DiscordServer.channels.cache.find(c => c.id === serverData.saleLogs.privateLog) + try { + + findChannelPrivate.send({ + embeds: [ + new Discord.EmbedBuilder() + .setTitle(`Nova compra no servidor!`) + .setDescription(`Abaixo estão os dados que foram entregues:`) + .addFields( + { name: '\u200B', value: '\u200B' }, + { name: 'Nome do usuario comprador', value: user.username, inline: true }, + { name: 'ID do usuario', value: user.id, inline: true }, + { name: 'ID da compra', value: findChannel.id }, + { name: 'Data e hora da compra', value: dataHoraFormatada }, + { name: '\u200B', value: '\u200B' }, + ...fields + ) + .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') + .setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp` }) + ], + }).catch(() => { + + sendTxtMensage(dono) + }) + } catch (error) { + findChannelPrivate.send({ + embeds: [ + new Discord.EmbedBuilder() + .setTitle(`Nova compra no servidor!`) + .setDescription(`Abaixo estão os dados que foram entregues:`) + .addFields( + { name: '\u200B', value: '\u200B' }, + { name: 'Nome do usuario comprador', value: user.username, inline: true }, + { name: 'ID do usuario', value: user.id, inline: true }, + { name: 'ID da compra', value: findChannel.id }, + { name: 'Data e hora da compra', value: dataHoraFormatada }, + { name: '\u200B', value: '\u200B' }, + ) + .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') + .setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp` }) + ], + }) + sendTxtMensage(dono) + } + }else{ + try { + await dono.send({ + embeds: [ + new Discord.EmbedBuilder() + .setTitle(`Nova compra no servidor: ${DiscordServer.name}`) + .setDescription(`Abaixo estão os dados que foram entregues:`) + .addFields( + { name: '\u200B', value: '\u200B' }, + { name: 'Nome do usuario comprador', value: user.username, inline: true }, + { name: 'ID do usuario', value: user.id, inline: true }, + { name: 'ID da compra', value: findChannel.id }, + { name: 'Data e hora da compra', value: dataHoraFormatada }, + { name: '\u200B', value: '\u200B' }, + ...fields + ) + .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') + .setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp` }) + ], + }).catch(() => { + sendTxtMensage(dono) + }) + } catch (error) { + await dono.send({ + embeds: [ + new Discord.EmbedBuilder() + .setTitle(`Nova compra no servidor: ${DiscordServer.name}`) + .setDescription(`Abaixo estão os dados que foram entregues:`) + .addFields( + { name: '\u200B', value: '\u200B' }, + { name: 'Nome do usuario comprador', value: user.username, inline: true }, + { name: 'ID do usuario', value: user.id, inline: true }, + { name: 'ID da compra', value: findChannel.id }, + { name: 'Data e hora da compra', value: dataHoraFormatada }, + { name: '\u200B', value: '\u200B' }, + ) + .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') + .setFooter({ text: DiscordServer.name, iconURL: `https://cdn.discordapp.com/icons/${DiscordServer.id}/${DiscordServer.icon}.webp` }) + ], + }) + sendTxtMensage(dono) + } + } + if ('personalize' in serverData && 'cargoPay' in serverData.personalize) { try { diff --git a/handler/commands/util/enviar.js b/handler/commands/util/enviar.js index cb50d65..4bb175c 100644 --- a/handler/commands/util/enviar.js +++ b/handler/commands/util/enviar.js @@ -6,8 +6,19 @@ module.exports = { name: 'enviar', description: 'Envie um produto para um usuario!', type: 1, - options: [], + options: [ + { + name:'quantidade', + description:"Quantidade de produtos que sera enviada!", + type:Discord.ApplicationCommandOptionType.Number, + } + ], run: async (client, interaction) => { + let quantidade = 1 + if (interaction.options.get('quantidade')) { + quantidade = interaction.options.get('quantidade').value + } + let verifyPermissions = await functions.verifyPermissions(interaction.user.id,interaction.guildId,Discord,client) if (verifyPermissions.error == false && verifyPermissions.perms.commands == true) { let server = await db.findOne({colecao:"servers",doc:interaction.guildId}) @@ -48,7 +59,7 @@ module.exports = { new Discord.ButtonBuilder() .setStyle(3) .setLabel('🛍️・Enviar Produto') - .setCustomId('productSendConfirm') + .setCustomId(`productSendConfirm-${quantidade}`) ) ], ephemeral: true diff --git a/index.js b/index.js index 5492eb6..3b040bc 100644 --- a/index.js +++ b/index.js @@ -380,7 +380,7 @@ app.get('/server/:id', functions.subscriptionStatus, async (req, res) => { if (adminServer && 'ticketOptions' in adminServer) { chatItens = adminServer.ticketOptions.motivos } - res.render('painel', { host: `${webConfig.host}`, chatItens:chatItens, user: user, server: server, comprasCanceladas: comprasCanceladas, comprasConcluidas: comprasConcluidas }) + res.render('painel', { host: `${webConfig.host}`, chatItens: chatItens, user: user, server: server, comprasCanceladas: comprasCanceladas, comprasConcluidas: comprasConcluidas }) }) @@ -417,12 +417,12 @@ app.get('/server/sales/:id', functions.subscriptionStatus, async (req, res) => { const channels = guild.channels.cache; const textChannels = channels.filter(channel => channel.type === 0); - let adminServer = db.findOne({colecao:'servers',doc:process.env.ADMINSERVER}) + let adminServer = db.findOne({ colecao: 'servers', doc: process.env.ADMINSERVER }) let chatItens = [] if (adminServer && 'ticketOptions' in adminServer) { chatItens = adminServer.ticketOptions.motivos } - res.render('sales', { perms: verifyPerms.perms,chatItens:chatItens, host: `${webConfig.host}`, bankData: bankData, user: user, server: server, channels: textChannels, formatarMoeda: functions.formatarMoeda }) + res.render('sales', { perms: verifyPerms.perms, chatItens: chatItens, host: `${webConfig.host}`, bankData: bankData, user: user, server: server, channels: textChannels, formatarMoeda: functions.formatarMoeda }) }) @@ -471,12 +471,12 @@ app.get('/server/personalize/:id', functions.subscriptionStatus, async (req, res id: role.id }; }); - let adminServer = await db.findOne({colecao:'servers',doc:process.env.ADMINSERVER}) + let adminServer = await db.findOne({ colecao: 'servers', doc: process.env.ADMINSERVER }) let chatItens = [] if (adminServer && 'ticketOptions' in adminServer) { chatItens = adminServer.ticketOptions.motivos } - res.render('personalize', { host: `${webConfig.host}`,chatItens:chatItens, cargos: roleObjects, user: user, server: server }) + res.render('personalize', { host: `${webConfig.host}`, chatItens: chatItens, cargos: roleObjects, user: user, server: server }) }) app.get('/server/analytics/:id', functions.subscriptionStatus, async (req, res) => { @@ -505,12 +505,12 @@ app.get('/server/analytics/:id', functions.subscriptionStatus, async (req, res) } } paymentMetod = JSON.stringify(paymentMetod) - let adminServer = await db.findOne({colecao:'servers',doc:process.env.ADMINSERVER}) - let chatItens = [] - if (adminServer && 'ticketOptions' in adminServer) { - chatItens = adminServer.ticketOptions.motivos - } - res.render('analytics', { host: `${webConfig.host}`,chatItens:chatItens, user: user, server: server, paymentMetod: paymentMetod, canceladosEstoque: canceladosEstoque, reebolsos: reebolsos, comprasCanceladas: comprasCanceladas, comprasConcluidas: comprasConcluidas }) + let adminServer = await db.findOne({ colecao: 'servers', doc: process.env.ADMINSERVER }) + let chatItens = [] + if (adminServer && 'ticketOptions' in adminServer) { + chatItens = adminServer.ticketOptions.motivos + } + res.render('analytics', { host: `${webConfig.host}`, chatItens: chatItens, user: user, server: server, paymentMetod: paymentMetod, canceladosEstoque: canceladosEstoque, reebolsos: reebolsos, comprasCanceladas: comprasCanceladas, comprasConcluidas: comprasConcluidas }) }) @@ -544,12 +544,12 @@ app.get('/server/permissions/:id', functions.subscriptionStatus, async (req, res let guild = guilds.get(serverID) let roles = guild.roles.cache let rolesFilter = roles.filter(role => role.managed == false && role.mentionable == false && role.name != "@everyone") - let adminServer = db.findOne({colecao:'servers',doc:process.env.ADMINSERVER}) - let chatItens = [] - if (adminServer && 'ticketOptions' in adminServer) { - chatItens = adminServer.ticketOptions.motivos - } - res.render('perms', { host: `${webConfig.host}`,chatItens:chatItens, user: user, server: server, roles: JSON.stringify(rolesFilter) }) + let adminServer = db.findOne({ colecao: 'servers', doc: process.env.ADMINSERVER }) + let chatItens = [] + if (adminServer && 'ticketOptions' in adminServer) { + chatItens = adminServer.ticketOptions.motivos + } + res.render('perms', { host: `${webConfig.host}`, chatItens: chatItens, user: user, server: server, roles: JSON.stringify(rolesFilter) }) }) @@ -605,12 +605,12 @@ app.get('/server/ticket/:id', functions.subscriptionStatus, async (req, res) => ticketOptions = server.ticketOptions } - let adminServer = await db.findOne({colecao:'servers',doc:process.env.ADMINSERVER}) - let chatItens = [] - if (adminServer && 'ticketOptions' in adminServer) { - chatItens = adminServer.ticketOptions.motivos - } - res.render('ticket', { host: `${webConfig.host}`,chatItens:chatItens, ticketOptions: ticketOptions, roles: JSON.stringify(rolesFilter), user: user, server: server, channels: textChannels, }) + let adminServer = await db.findOne({ colecao: 'servers', doc: process.env.ADMINSERVER }) + let chatItens = [] + if (adminServer && 'ticketOptions' in adminServer) { + chatItens = adminServer.ticketOptions.motivos + } + res.render('ticket', { host: `${webConfig.host}`, chatItens: chatItens, ticketOptions: ticketOptions, roles: JSON.stringify(rolesFilter), user: user, server: server, channels: textChannels, }) }) @@ -633,13 +633,13 @@ app.get('/server/config/:id', functions.subscriptionStatus, async (req, res) => const channels = guild.channels.cache; const textChannels = channels.filter(channel => channel.type === 0); - let adminServer = db.findOne({colecao:'servers',doc:process.env.ADMINSERVER}) + let adminServer = db.findOne({ colecao: 'servers', doc: process.env.ADMINSERVER }) let chatItens = [] if (adminServer && 'ticketOptions' in adminServer) { chatItens = adminServer.ticketOptions.motivos } - - res.render('config', { host: `${webConfig.host}`,chatItens:chatItens, user: user, channels: textChannels, server: server }) + + res.render('config', { host: `${webConfig.host}`, chatItens: chatItens, user: user, channels: textChannels, server: server }) } catch (error) { } @@ -993,7 +993,88 @@ app.post('/personalize/change', async (req, res) => { } } }) +app.post('/personalize/productIcon', async (req, res) => { + try { + let server = await db.findOne({ colecao: "servers", doc: req.body.serverID }) + if (server) { + let personalize = 'personalize' in server ? server.personalize : {} + personalize.iconProduct = req.body.icon + db.update('servers', req.body.serverID, { + personalize: personalize + }) + if (!res.headersSent) { + res.status(200).json({ success: true, }) + } + } else { + if (!res.headersSent) { + res.status(200).json({ success: false, data: 'Erro ao tentar recuperar o servidor!' }) + } + } + } catch (error) { + if (!res.headersSent) { + res.status(200).json({ success: false, data: 'Erro ao tentar mudar a personalização!' }) + } + } +}) +app.post('/sales/privateLog', async (req, res) => { + try { + let server = await db.findOne({ colecao: "servers", doc: req.body.serverID }) + if (server) { + let logs = { + publicLog: '', + privateLog: '' + } + if ('saleLogs' in server) { + logs = server.saleLogs + } + logs.privateLog = req.body.channelID + db.update('servers', req.body.serverID, { + saleLogs: logs + }) + if (!res.headersSent) { + res.status(200).json({ success: true, data: 'Log alterada' }) + } + } else { + if (!res.headersSent) { + res.status(200).json({ success: false, data: 'Erro ao tentar recuperar o servidor!' }) + } + } + } catch (error) { + if (!res.headersSent) { + res.status(200).json({ success: false, data: 'Erro ao tentar mudar a log!' }) + } + } +}) +app.post('/sales/publicLog', async (req, res) => { + try { + let server = await db.findOne({ colecao: "servers", doc: req.body.serverID }) + if (server) { + let logs = { + publicLog: '', + privateLog: '' + } + if ('saleLogs' in server) { + logs = server.saleLogs + } + logs.publicLog = req.body.channelID + db.update('servers', req.body.serverID, { + saleLogs: logs + }) + if (!res.headersSent) { + res.status(200).json({ success: true, data: 'Log alterada' }) + } + } else { + if (!res.headersSent) { + res.status(200).json({ success: false, data: 'Erro ao tentar recuperar o servidor!' }) + } + } + } catch (error) { + if (!res.headersSent) { + res.status(200).json({ success: false, data: 'Erro ao tentar mudar a log!' }) + } + } +}) app.post('/ticket/create', async (req, res) => { try { @@ -1018,7 +1099,7 @@ app.post('/ticket/saveSend', async (req, res) => { try { let body = await req.body let server = await db.findOne({ colecao: 'servers', doc: body.serverID }) - if ( 'ticketOptions' in server && server.ticketOptions.motivos.length <= 0) { + if ('ticketOptions' in server && server.ticketOptions.motivos.length <= 0) { if (!res.headersSent) { res.status(200).json({ success: false, data: 'Cadastre os motivos do ticket primeiro!' }) } @@ -1042,7 +1123,7 @@ app.post('/ticket/saveSend', async (req, res) => { db.update('servers', body.serverID, { ticketOptions: ticketOptions }) - + if (!res.headersSent) { res.status(200).json({ success: true, data: 'Mensagem do ticket enviada!' }) } @@ -1138,7 +1219,7 @@ app.post('/ticket/motivoADD', async (req, res) => { db.update('servers', body.serverID, { ticketOptions: ticketOptions }) - + if (ticketOptions.channel) { require('./Discord/createTicketMensage.js')(client, ticketOptions.channel, body.serverID) } @@ -1172,7 +1253,7 @@ app.post('/ticket/banner', upload.single('BannerTicket'), async (req, res) => { }, avaliacao: '', log: '', - banner:'' + banner: '' } if ('ticketOptions' in server) { ticketOptions = server.ticketOptions @@ -1263,7 +1344,7 @@ app.post('/ticket/privatelog', async (req, res) => { db.update('servers', body.serverID, { ticketOptions: ticketOptions }) - + if (!res.headersSent) { res.status(200).json({ success: true, data: 'Log privado modificado!' }) } @@ -1289,7 +1370,7 @@ app.post('/ticket/desc', async (req, res) => { avaliacao: '', log: '', privateLog: '', - desc:'' + desc: '' } if ('ticketOptions' in server) { ticketOptions = server.ticketOptions @@ -1386,7 +1467,7 @@ app.post('/send/discordMensage', async (req, res) => { .setDescription(`\n${textTranslate}\n`) .addFields({ name: '\u200B', value: '\u200B' }, { name: 'Tipo', value: `${req.body.admin == true ? "administrador" : "usuario"}`, inline: true }, { name: "Nome do usuario", value: user.username, inline: true }, { name: "ID do usuario", value: user.id, inline: true }) .setColor('#6E58C7') - .setAuthor({ name: "SDKApps", iconURL: `https://res.cloudinary.com/dgcnfudya/image/upload/v1711769157/vyzyvzxajoboweorxh9s.png`}) + .setAuthor({ name: "SDKApps", iconURL: `https://res.cloudinary.com/dgcnfudya/image/upload/v1711769157/vyzyvzxajoboweorxh9s.png` }) .setTimestamp() ] diff --git a/public/css/sales.css b/public/css/sales.css index b7e419a..d96cfb7 100644 --- a/public/css/sales.css +++ b/public/css/sales.css @@ -1007,6 +1007,38 @@ } } +#triple-containner{ + display: flex; + gap: 1em; +} + +#logs-sales-containner{ + width: 90%; + display: flex; + flex-wrap: wrap; + gap: 1em; + justify-content: space-around; + #private-log-content,#public-log-content{ + width: 40%; + display: flex; + flex-direction: column; + gap: 1em; + padding: 1em; + background-color: var(--secundary-color); + border-radius: var(--border-radius-mid); + } + .logs-channel-content{ + display: flex; + flex-direction: column; + gap: 1.5em; + } + .title-logs{ + display: flex; + text-align: center; + flex-direction: column; + gap: 0.5em; + } +} @media screen and (max-width:800px) { diff --git a/public/js/personalize.js b/public/js/personalize.js index 97c1f6d..ee7b735 100644 --- a/public/js/personalize.js +++ b/public/js/personalize.js @@ -116,4 +116,22 @@ document.getElementById('color-dest-input').addEventListener('change',()=>{ document.getElementById('color-dest-input').addEventListener('input',()=>{ document.getElementById('color-dest-preview').style.backgroundColor = document.getElementById('color-dest-input').value +}) + +document.getElementById('checkbox').addEventListener('change',async()=>{ + let session = await fetch('/personalize/productIcon', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + icon:document.getElementById('checkbox').checked , + serverID:serverID + }), + }).then(response => { return response.json() }) + if (session.success == true) { + successNotify('Personalização alterada!') + }else{ + errorNotify(session.data) + } }) \ No newline at end of file diff --git a/public/js/sales.js b/public/js/sales.js index 1bf66d9..7e1d175 100644 --- a/public/js/sales.js +++ b/public/js/sales.js @@ -758,7 +758,16 @@ document.getElementById('button-backGround-input-edit').addEventListener('click' } }) +document.getElementById('embend-type-input').addEventListener('blur', function () { + const inputValue = this.value.toLowerCase(); + const datalistOptions = Array.from(document.getElementById('embend-input-list').getElementsByTagName('option')); + const validOptions = datalistOptions.map(option => option.value.toLowerCase()); + if (!validOptions.includes(inputValue)) { + errorNotify('Por favor, selecione uma embend válida da lista.'); + this.value = ''; + } +}); function previewImage(input, preview) { if (input.files && input.files[0]) { @@ -868,6 +877,16 @@ document.getElementById("product-cadastro-content").addEventListener("submit", f } }); + + const opcoesEmbend = document.getElementById('embend-input-list').querySelectorAll('option'); + let EmbendID = null; + + opcoesEmbend.forEach(option => { + if (option.value === document.getElementById('embend-type-input').value) { + EmbendID = option.getAttribute('data-embend'); + } + }); + var formData = new FormData(); formData.append('estoque', JSON.stringify(EstoqueData)); formData.append('productLogo', document.getElementById('logo-input').files[0]); @@ -875,6 +894,7 @@ document.getElementById("product-cadastro-content").addEventListener("submit", f formData.append('productName', document.getElementById('product-name').value.trim()); formData.append('producDesc', document.getElementById('product-desc').value.trim()); formData.append('serverID', serverID); + formData.append('embend', EmbendID) formData.append('price', parseInt(document.getElementById('product-price').value.replace(/[^\d,]/g, '').replace(',', ''))); // if (parseInt(document.getElementById('product-price').value.replace(/[^\d,]/g, '').replace(',', '')) < 100) { // errorNotify('O valor do produto não pode ser menor que R$ 1,00') @@ -912,3 +932,86 @@ document.getElementById("product-cadastro-content").addEventListener("submit", f +document.getElementById('private-log-input').addEventListener('blur', function () { + const inputValue = this.value.toLowerCase(); + const datalistOptions = Array.from(document.getElementById('private-log-list').getElementsByTagName('option')); + const validOptions = datalistOptions.map(option => option.value.toLowerCase()); + + if (!validOptions.includes(inputValue)) { + errorNotify('Por favor, selecione um canal válido da lista.'); + this.value = ''; + } +}); + +document.getElementById('save-button-private-log').addEventListener('click',async()=>{ + if (document.getElementById('private-log-input').value <= 0) { + errorNotify('Selecione um canal primeiro!') + return + } + const opcoes = document.getElementById('private-log-list').querySelectorAll('option'); + let channelID = null; + + opcoes.forEach(option => { + if (option.value === document.getElementById('private-log-input').value) { + channelID = option.getAttribute('data-channel'); + } + }); + let session = await fetch('/sales/privateLog', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + channelID: channelID, + serverID:serverID + }), + }).then(response => { return response.json() }) + if (session.success == true) { + successNotify(session.data) + }else{ + errorNotify(session.data) + } +}) + + +document.getElementById('public-log-input').addEventListener('blur', function () { + const inputValue = this.value.toLowerCase(); + const datalistOptions = Array.from(document.getElementById('public-log-list').getElementsByTagName('option')); + const validOptions = datalistOptions.map(option => option.value.toLowerCase()); + + if (!validOptions.includes(inputValue)) { + errorNotify('Por favor, selecione um canal válido da lista.'); + this.value = ''; + } +}); + +document.getElementById('save-button-public-log').addEventListener('click',async()=>{ + if (document.getElementById('public-log-input').value <= 0) { + errorNotify('Selecione um canal primeiro!') + return + } + const opcoes = document.getElementById('public-log-list').querySelectorAll('option'); + let channelID = null; + + opcoes.forEach(option => { + if (option.value === document.getElementById('public-log-input').value) { + channelID = option.getAttribute('data-channel'); + } + }); + let session = await fetch('/sales/publicLog', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + channelID: channelID, + serverID:serverID + }), + }).then(response => { return response.json() }) + if (session.success == true) { + successNotify(session.data) + }else{ + errorNotify(session.data) + } +}) + diff --git a/stripe/productsRoutes.js b/stripe/productsRoutes.js index 8693ba7..ecbc1bd 100644 --- a/stripe/productsRoutes.js +++ b/stripe/productsRoutes.js @@ -80,7 +80,8 @@ router.post('/product/create', upload.fields([{ name: 'productLogo', maxCount: 1 backGround: backGround, price: await req.body.price, priceID: await price.id, - estoqueModel: JSON.parse(req.body.estoque)[0] + estoqueModel: JSON.parse(req.body.estoque)[0], + embendType: req.body.embend } if (server.products) { produtos = server.products @@ -91,11 +92,19 @@ router.post('/product/create', upload.fields([{ name: 'productLogo', maxCount: 1 products: await produtos }) - require('../Discord/createProductMessage.js')(Discord, client, { - channelID: req.body.channelID, - serverID: req.body.serverID, - productID: product.id, - }) + if (req.body.embend == '0') { + require('../Discord/createProductMessageEmbend.js')(Discord, client, { + channelID: req.body.channelID, + serverID: req.body.serverID, + productID: product.id, + }) + }else{ + require('../Discord/createProductMessage.js')(Discord, client, { + channelID: req.body.channelID, + serverID: req.body.serverID, + productID: product.id, + }) + } res.status(200).json({ success: true, data: model }) } catch (error) { @@ -182,12 +191,21 @@ router.post('/product/update', upload.fields([{ name: 'productLogo', maxCount: 1 db.update('servers', req.body.serverID, { products: produtos }) - require('../Discord/createProductMessage.js')(Discord, client, { - channelID: produto.channel, - serverID: req.body.serverID, - productID: productID, - edit: true - }) + if (produto.embendType == 0) { + require('../Discord/createProductMessageEmbend.js')(Discord, client, { + channelID: produto.channel, + serverID: req.body.serverID, + productID: productID, + edit: true + }) + }else{ + require('../Discord/createProductMessage.js')(Discord, client, { + channelID: produto.channel, + serverID: req.body.serverID, + productID: productID, + edit: true + }) + } res.status(200).json({ success: true, data: '' }) } catch (error) { console.log(error); @@ -350,12 +368,21 @@ router.post('/estoque/txt', async (req, res) => { db.update('servers', req.body.serverID, { products: produtos }) - require('../Discord/createProductMessage.js')(Discord, client, { - channelID: product.channel, - serverID: req.body.serverID, - productID: req.body.productID, - edit: true - }) + if (product.embendType == 0) { + require('../Discord/createProductMessageEmbend.js')(Discord, client, { + channelID: product.channel, + serverID: req.body.serverID, + productID: productID, + edit: true + }) + }else{ + require('../Discord/createProductMessage.js')(Discord, client, { + channelID: product.channel, + serverID: req.body.serverID, + productID: productID, + edit: true + }) + } } if (!res.headersSent) { res.status(200).json({ success: true }) @@ -396,12 +423,21 @@ router.post('/product/estoqueAdd', async (req, res) => { db.update('servers', req.body.serverID, { products: produtos }) - require('../Discord/createProductMessage.js')(Discord, client, { - channelID: product.channel, - serverID: req.body.serverID, - productID: req.body.productID, - edit: true - }) + if (product.embendType == 0) { + require('../Discord/createProductMessageEmbend.js')(Discord, client, { + channelID: product.channel, + serverID: req.body.serverID, + productID: productID, + edit: true + }) + }else{ + require('../Discord/createProductMessage.js')(Discord, client, { + channelID: product.channel, + serverID: req.body.serverID, + productID: productID, + edit: true + }) + } resolve({ err: false, error: null @@ -433,14 +469,27 @@ router.post('/product/estoqueAdd', async (req, res) => { }) -router.post('/product/mensage', (req, res) => { +router.post('/product/mensage', async(req, res) => { try { - require('../Discord/createProductMessage.js')(Discord, client, { - channelID: req.body.channelID, - serverID: req.body.serverID, - productID: req.body.productID, - edit: true - }) + let server = await db.findOne({ colecao: 'servers', doc: req.body.serverID }) + let productID = req.body.productID + let produtos = server.products + let produto = await produtos.find(product => product.productID == productID) + if (produto.embendType == 0) { + require('../Discord/createProductMessageEmbend.js')(Discord, client, { + channelID: req.body.channelID, + serverID: req.body.serverID, + productID: req.body.productID, + edit: true + }) + }else{ + require('../Discord/createProductMessage.js')(Discord, client, { + channelID: req.body.channelID, + serverID: req.body.serverID, + productID: req.body.productID, + edit: true + }) + } res.status(200).json({ success: true, data: 'Mensagem Enviada!' }) } catch (error) { console.log(error); diff --git a/views/config.ejs b/views/config.ejs index e52c194..28fe5be 100644 --- a/views/config.ejs +++ b/views/config.ejs @@ -44,15 +44,15 @@ <% }) %> -
+
diff --git a/views/personalize.ejs b/views/personalize.ejs index abec58d..5129854 100644 --- a/views/personalize.ejs +++ b/views/personalize.ejs @@ -57,6 +57,19 @@
+ +
+

Icone na mensagem do produto!

+

Caso essa opção esteja ativa ao criar um novo produto ou enviar uma nova mensagem não ira aparecer o icone do produto (Apenas na embend de mensagem)!

+
+
+ + +
+
diff --git a/views/sales.ejs b/views/sales.ejs index 88bdd59..7cafc00 100644 --- a/views/sales.ejs +++ b/views/sales.ejs @@ -116,6 +116,41 @@ <%- include('./reusable/header.ejs',{index:2}) %>
+
+
+
+

Log publico

+

Selecione o canal que deseja que apareca um log para o publico de vendas!

+ +
+
+
+ + + <% channels.forEach(element => { %> + + <% }) %> + + +
+
+
+
+

Log privado

+

Selecione o canal que deseja que apareca um log privado de vendas!

+
+
+
+ + + <% channels.forEach(element => { %> + + <% }) %> + + +
+
+
<% if (perms.owner == true || perms.paymentEdit && perms.paymentEdit == true) { %> @@ -194,6 +229,7 @@
+

Cadastrar Produto

@@ -238,9 +274,19 @@
-
- - +
+
+ + +
+
+ + + + + + +