Related
Code:
const { EmbedBuilder, ActionRowBuilder, SelectMenuBuilder } = require("discord.js");
const { readdirSync } = require("fs");
const client = require("../../index");
const config = require("../../botconfig");
const create_menu = require("../../models/helpMenu.js");
const prefixSchema = require("../../models/prefix");
module.exports = {
name: "help",
description: "Displays all available command categories!",
aliases: [],
usage: "<command> or <category>",
run: async (client, interaction, message, args, db) => {
//try {
const data = await prefixSchema.findOne({ Guild: message.guildId });
if (data) {
let categories = [];
let cots = [];
if (!args[0]) {
let ignored = ["Giveaway", "Owner"];
const emoji = {
Action: "๐ค",
Admin: "๐",
Birthday: "๐",
Fun: "๐ฎ",
Giveaway: "๐",
Image: "๐ผ๏ธ",
Minigame: "๐ฒ",
Miscellaneous: "โ๏ธ",
Moderation: "๐ก๏ธ",
Owner: "๐",
Ticket: "๐ซ",
};
let cmdCategory = [];
readdirSync("./commands/").forEach((dir) => {
if (ignored.includes(dir)) return;
const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));
if (ignored.includes(dir)) return;
const name = `${emoji[dir]} - ${dir}`;
let categoryName = dir;
let categoryDir = new Object();
categoryDir = {
name: name,
value: "โ",
inline: true,
};
categories.push(categoryDir);
cmdCategory.push(categoryName);
});
const embed = new EmbedBuilder()
.setTitle("__Crimson's Help Menu__")
.setDescription(`>>> Default Prefix: \`${config.defaultPrefix}\`\nServer Prefix: \`${data.Prefix}\``)
.setThumbnail(client.user.displayAvatarURL())
.addFields(categories)
.setColor("#EE1C25")
.setFooter({ text: "Navigate through the embeds using the provided menu below.", iconURL: message.author.displayAvatarURL() })
.setTimestamp();
let menus = create_menu(cmdCategory);
return message.reply({ embeds: [embed], components: menus.smenu, allowedMentions: { repliedUser: true } }).then((msg) => {
const menuID = menus.sid;
const select = async (interaction) => {
if (interaction.customId != menuID) return;
let { values } = interaction;
let value = values[0];
let commands2 = [];
readdirSync("./commands/").forEach((dir) => {
if (dir.toLowerCase() !== value.toLowerCase()) return;
const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));
const cmds = commands.map((command) => {
let file = require(`../../commands/${dir}/${command}`);
if (!file.name) return "No command name.";
let name = file.name.replace(".js", "");
if (client.commands.get(name).hidden) return;
let emoji = client.commands.get(name).emoji;
let emoji2 = emoji ? `${emoji} ` : "โข ";
let obj = { cname: `${emoji2}\`${name}\`` };
return obj;
});
let dota = new Object();
cmds.map((co) => {
if (co == undefined) return;
dota = {
name: `${cmds.length === 0 ? "Processing..." : co.cname}`,
value: "โ",
inline: false,
};
commands2.push(dota);
});
cots.push(dir.toLowerCase());
});
if (cots.includes(value.toLowerCase())) {
const cmdEmbed = new EmbedBuilder()
.setTitle(`__${value.charAt(0) + value.slice(1)} Commands__`)
.addFields(commands2)
.setColor("#EE1C25");
await interaction.deferUpdate();
return interaction.message.edit({ embeds: [cmdEmbed], components: menus.smenu, allowedMentions: { repliedUser: true } });
}
};
const filter = (interaction) => {
if (interaction.user.id === message.author.id) return true;
return interaction.reply({ content: "<:CL_VoteCross:781265541804720148> You cannot use this menu.", ephemeral: true });
};
const collector = msg.createMessageComponentCollector({ filter, componentType: "SelectMenu" });
collector.on("collect", select);
collector.on("end", () => null);
});
} else {
let commands2 = [];
readdirSync("./commands/").forEach((dir) => {
if (dir.toLowerCase() !== args[0].toLowerCase()) return;
const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));
const cmds = commands.map((command) => {
let file = require(`../../commands/${dir}/${command}`);
if (!file.name) return "I was unable to fetch the requested command.";
let name = file.name.replace(".js", "");
if (client.commands.get(name).hidden) return;
let emoji = client.commands.get(name).emoji;
let emoji2 = emoji ? `${emoji} ` : "";
let obj = { cname: `${emoji2}\`${name}\`` };
return obj;
});
let dota = new Object();
cmds.map((co) => {
if (co == undefined) return;
dota = {
name: `${cmds.length === 0 ? "In progress..." : "โข " + co.cname}`,
value: "โ",
inline: true,
};
commands2.push(dota);
});
cots.push(dir.toLowerCase());
});
const command = client.commands.get(args[0].toLowerCase()) || client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));
if (cots.includes(args[0].toLowerCase())) {
const cmdEmbed = new EmbedBuilder()
.setTitle(`__${args[0].charAt(0) + args[0].slice(1)} commands__`)
.addFields(commands2)
.setColor("#EE1C25");
return message.reply({ embeds: [cmdEmbed], allowedMentions: { repliedUser: true } });
}
if (!command) {
const noCmdEmbed = new EmbedBuilder()
.setTitle("Unknown Command/Category")
.setDescription(`The command or category you are trying to find is not in our database, if you think this is a mistake.. please let us know!\n\n\n**Options**\n\`\`\`${config.defaultPrefix}help <category name>\`\`\` \`\`\`${config.defaultPrefix}help <command name>\`\`\``)
.setFooter({ text: `Command Requested by ${message.author.tag}`, iconURL: message.author.displayAvatarURL({ dynamic: true }) })
.setTimestamp()
.setColor("#EE1C25");
return await message.reply({ embeds: [noCmdEmbed], allowedMentions: { repliedUser: true } });
}
const cmdDetailsEmbed = new EmbedBuilder()
.setThumbnail(client.user.displayAvatarURL())
.setDescription(`**Command:** \`${command.name}\``)
.addFields(
{
name: "Usage",
value: command.usage
? `\`\`\`${config.defaultPrefix}${command.name} ${command.usage}\`\`\``
: "`No usage for this command`",
},
{
name: "Description",
value: command.description
? `\`\`\`${command.description}\`\`\``
: "`No description for this command`",
},
{
name: "Aliases",
value: command.aliases
? `\`\`\`${command.aliases.join(", ")}\`\`\``
: "`No aliases for this command`",
}
)
.setFooter({ text: `Command Requested by ${message.author.tag}`, iconURL: message.author.displayAvatarURL({ dynamic: true }) })
.setTimestamp()
.setColor("#EE1C25");
return await message.reply({ embeds: [cmdDetailsEmbed], allowedMentions: { repliedUser: true } });
}
} else if (!data) {
let categories = [];
let cots = [];
if (!args[0]) {
let ignored = ["Giveaway", "Owner"];
const emoji = {
Action: "๐ค",
Admin: "๐",
Birthday: "๐",
Fun: "๐ฎ",
Giveaway: "๐",
Image: "๐ผ๏ธ",
Minigame: "๐ฒ",
Miscellaneous: "โ๏ธ",
Moderation: "๐ก๏ธ",
Owner: "๐",
Ticket: "๐ซ",
};
let cmdCategory = [];
readdirSync("./commands/").forEach((dir) => {
if (ignored.includes(dir)) return;
const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));
if (ignored.includes(dir)) return;
const name = `${emoji[dir]} - ${dir}`;
let categoryName = dir;
let categoryDir = new Object();
categoryDir = {
name: name,
value: "โ",
inline: true, //true
};
categories.push(categoryDir);
cmdCategory.push(categoryName);
});
const embed = new EmbedBuilder()
.setTitle("__Crimson's Help Menu__")
.setDescription(`>>> Default Prefix: \`${config.defaultPrefix}\`\nServer Prefix: \`none\``)
.setThumbnail(client.user.displayAvatarURL())
.addFields(categories)
.setColor("#EE1C25")
.setFooter({ text: "Navigate through the embeds using the provided menu below.", iconURL: message.author.displayAvatarURL() })
.setTimestamp();
let menus = create_menu(cmdCategory);
return message.reply({ embeds: [embed], components: menus.smenu, allowedMentions: { repliedUser: true } }).then((msg) => {
const menuID = menus.sid;
const select = async (interaction) => {
if (interaction.customId != menuID) return;
let { values } = interaction;
let value = values[0];
let commands2 = [];
readdirSync("./commands/").forEach((dir) => {
if (dir.toLowerCase() !== value.toLowerCase()) return;
const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));
const cmds = commands.map((command) => {
let file = require(`../../commands/${dir}/${command}`);
if (!file.name) return "No command name.";
let name = file.name.replace(".js", "");
if (client.commands.get(name).hidden) return;
let emoji = client.commands.get(name).emoji;
let emoji2 = emoji ? `${emoji} ` : "โข ";
let obj = { cname: `${emoji2}\`${name}\`` };
return obj;
});
let dota = new Object();
cmds.map((co) => {
if (co == undefined) return;
dota = {
name: `${cmds.length === 0 ? "Processing..." : co.cname}`,
value: "โ",
inline: false, //true
};
commands2.push(dota);
});
cots.push(dir.toLowerCase());
});
if (cots.includes(value.toLowerCase())) {
const cmdEmbed = new EmbedBuilder()
.setTitle(`__${value.charAt(0) + value.slice(1)} Commands__`)
.addFields(commands2)
.setColor("#EE1C25");
await interaction.deferUpdate();
return interaction.message.edit({ embeds: [cmdEmbed], components: menus.smenu, allowedMentions: { repliedUser: true } });
}
};
const filter = (interaction) => {
if (interaction.user.id === message.author.id) return true;
return interaction.reply({ content: "<:CL_VoteCross:781265541804720148> This menu is not for you.", ephemeral: true });
};
const collector = msg.createMessageComponentCollector({ filter, componentType: "SelectMenu" });
collector.on("collect", select);
collector.on("end", () => null);
});
} else {
let commands2 = [];
readdirSync("./commands/").forEach((dir) => {
if (dir.toLowerCase() !== args[0].toLowerCase()) return;
const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));
const cmds = commands.map((command) => {
let file = require(`../../commands/${dir}/${command}`);
if (!file.name) return "I was unable to fetch the requested command.";
let name = file.name.replace(".js", "");
if (client.commands.get(name).hidden) return;
let emoji = client.commands.get(name).emoji;
let emoji2 = emoji ? `${emoji} ` : "";
let obj = { cname: `${emoji2}\`${name}\`` };
return obj;
});
let dota = new Object();
cmds.map((co) => {
if (co == undefined) return;
dota = {
name: `${cmds.length === 0 ? "In progress..." : "โข " + co.cname}`,
value: "โ",
inline: false, //true
};
commands2.push(dota);
});
cots.push(dir.toLowerCase());
});
const command = client.commands.get(args[0].toLowerCase()) || client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));
if (cots.includes(args[0].toLowerCase())) {
const cmdEmbed = new EmbedBuilder()
.setTitle(`__${args[0].charAt(0) + args[0].slice(1)} commands__`)
.addFields(commands2)
.setColor("#EE1C25");
return message.reply({ embeds: [cmdEmbed], allowedMentions: { repliedUser: true } });
}
if (!command) {
const noCmdEmbed = new EmbedBuilder()
.setTitle("Unknown Command/Category")
.setDescription(`The command or category you are trying to find is not in our database, if you think this is a mistake.. please let us know!\n\n\n**Options**\n\`\`\`${config.defaultPrefix}help <category name>\`\`\` \`\`\`${config.defaultPrefix}help <command name>\`\`\``)
.setFooter({ text: `Command Requested by ${message.author.tag}`, iconURL: message.author.displayAvatarURL({ dynamic: true }) })
.setTimestamp()
.setColor("#EE1C25");
return await message.reply({ embeds: [noCmdEmbed], allowedMentions: { repliedUser: true } });
}
const cmdDetailsEmbed = new EmbedBuilder()
.setThumbnail(client.user.displayAvatarURL())
.setDescription(`**Command:** \`${command.name}\``)
.addFields(
{
name: "Usage",
value: command.usage
? `\`\`\`${config.defaultPrefix}${command.name} ${command.usage}\`\`\``
: "`No usage for this command`",
},
{
name: "Description",
value: command.description
? `\`\`\`${command.description}\`\`\``
: "`No description for this command`",
},
{
name: "Aliases",
value: command.aliases
? `\`\`\`${command.aliases.join(", ")}\`\`\``
: "`No aliases for this command`",
})
.setFooter({ text: `Command Requested by ${message.author.tag}`, iconURL: message.author.displayAvatarURL({ dynamic: true }) })
.setTimestamp()
.setColor("#EE1C25");
return await message.reply({ embeds: [cmdDetailsEmbed], allowedMentions: { repliedUser: true } });
}
}
//} catch (err) {
//console.log(err)
//return await message.reply(`\`${err}\``);
//}
},
};
Error:
/app/commands/Miscellaneous/help.js:234
if (!args[0]) {
^
TypeError: Cannot read properties of undefined (reading '0')
Iโm still changing stuff over to v14 of discord, and I appear to keep breaking/not understanding half the errors that I keep getting and some past one such as the one below about message.guild.id.
Other Error:
const data = await prefixSchema.findOne({ Guild: message.guild.id });
TypeError: Cannot read properties of undefined (reading 'id')
Any assistance would be greatly appreciated!
index.js
/*Discord V14 Setup*/
const { Client, Routes, GatewayIntentBits, Partials, Collection, EmbedBuilder, MessageAttachment, ActionRowBuilder, ButtonBuilder } = require('discord.js'),
botconfig = require('./botconfig.js'),
ownerID = botconfig.ownerID,
client = new Client({ allowedMentions: { parse: ['roles', 'everyone', 'users'], repliedUser: false }, partials: [Partials.Message, Partials.Channel, Partials.Reaction], intents: [GatewayIntentBits.MessageContent, GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildBans, GatewayIntentBits.GuildIntegrations, GatewayIntentBits.GuildWebhooks, GatewayIntentBits.GuildInvites, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildMessageTyping, GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessageReactions, GatewayIntentBits.DirectMessageTyping] });
/*End of Discord V14 Setup*/
/*Slash Commands*/
const { REST } = require('#discordjs/rest');
const fs = require('fs');
/*End of Slash Commands*/
/*Packages*/
const { DiscordTogether } = require('discord-together');
const { Captcha } = require('captcha-canvas');
const { readdirSync } = require('fs');
const ascii = require('ascii-table');
const Canvacord = require('canvacord');
const chalk = require('chalk');
const quick = require('quick.db');
/*End of Packages*/
/*Models for Client*/
const { events } = require('./handlers/events');
//const { slashCommands } = require('./handlers/slash');
const leaveSchema = require('./models/leaveLogs');
const loggerHandler = require('./handlers/logger.js');
const modlogsSchema = require('./models/modLogs');
const prefixSchema = require('./models/prefix');
const welcomeSchema = require('./models/joinLogs');
/*End of Models for Client*/
/*Configurations*/
module.exports = client;
client.aliases = new Collection();
client.botconfig = botconfig;
client.commands = new Collection();
client.db = quick.db;
client.discordTogether = new DiscordTogether(client);
client.embed = new EmbedBuilder();
client.logger = new loggerHandler();
client.slash = new Collection();
client.snipes = new Collection();
/*End of Configurations*/
/*Client categories*/
client.categories = fs.readdirSync('./commands/');
['command'].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
/*End of Client categories*/
/*MongoDB Setup*/
const mongoose = require('mongoose');
mongoose.connect(botconfig.db_uri, { useUnifiedTopology: true, useNewUrlParser: true }).then(client.logger.log('READY', 'Crimson has successfully connected to MongoDB!'));
/*End of MongoDB Setup*/
/*reaction-roles*/
client.on('messageReactionAdd', async (reaction, member, guild, message) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (member.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐ฃ') {
await reaction.message.guild.members.cache.get(member.id).roles.add('746023960201920523');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐ค') {
await reaction.message.guild.members.cache.get(member.id).roles.add('857984203346018305');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === 'โ') {
await reaction.message.guild.members.cache.get(member.id).roles.add('858546783823462430');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐
') {
await reaction.message.guild.members.cache.get(member.id).roles.add('889927145206468669');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐') {
await reaction.message.guild.members.cache.get(member.id).roles.add('746024349135405199');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐') {
await reaction.message.guild.members.cache.get(member.id).roles.add('746024204989759632');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐๏ธ') {
await reaction.message.guild.members.cache.get(member.id).roles.add('889927622774124574');
}
}
if (reaction.message.id === '924001444980478012') {
if (reaction.emoji.name === '<a:CL_CheckMark:858853559940808724>');
await reaction.users.remove(member.id);
const captcha = new Captcha();
captcha.async = true;
captcha.addDecoy();
captcha.drawTrace();
captcha.drawCaptcha();
const captchaAttachment = new MessageAttachment(await captcha.png, 'CrimsonCaptcha.png');
const captchaEmbed = new EmbedBuilder()
.setTitle('Crimson\'s Lounge - Checkpoint ๐')
.setDescription('Solve the captcha code to gain access to `Crimson\'s Lounge`')
.setImage('attachment://CrimsonCaptcha.png')
.setColor('EE1C25')
.setFooter('This code will expire in 5 minutes')
.setTimestamp();
const msg = await member.send({ embeds: [captchaEmbed], files: [captchaAttachment] }).catch(() => null);
const filter = message => {
if (message.author.id !== member.id) return;
if (message.content === captcha.text) return true;
else member.send('Incorrect Captcha, Please try again.');
};
try {
const response = await msg.channel.awaitMessages({ filter, max: 1, time: 300000, errors: ['time'] });
if (response) {
const completeCaptchaEmbed = new EmbedBuilder()
.setTitle('<:CL_VoteTick:781265299609223188> Verification Complete') //โ
.setDescription('You have successfully gained access to `Crimson\'s Lounge`.')
.setColor('GREEN')
.setTimestamp();
member.send({ embeds: [completeCaptchaEmbed] });
await reaction.message.guild.members.cache.get(member.id).roles.add('828466951201751071');
await reaction.message.guild.members.cache.get(member.id).roles.remove('903403824818028555');
}
if (response === false) {
const failedCaptchaEmbed = new EmbedBuilder()
.setTitle('<:CL_VoteCross:781265541804720148> Verification Failed') //โ
.setDescription('> You did not complete the captcha in the given time (5 mins)\n\n`You were kicked from `Crimson\'s Lounge`, feel free to join us again with the click of the magical button below!`')
.setColor('RED')
.setFooter('If you are having trouble verifying, let our support team know.')
.setTimestamp();
member.kick();
let failedBtn = new MessageButton()
.setStyle('LINK')
.setURL('https://discord.gg/DFZv2Zh')
.setLabel('Support');
let row = new MessageActionRow().addComponents([failedBtn]);
const targetMember = await member.send({ embeds: [failedCaptchaEmbed], components: [row] });
const filter = button => button.clicker.user.id === member.user.id;
const collector = targetMember.createMessageComponentCollector(filter);
}
} catch (err) {
console.log(err);
}
}
});
client.on('messageReactionRemove', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐ฃ') {
await reaction.message.guild.members.cache.get(user.id).roles.remove('746023960201920523');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐ค') {
await reaction.message.guild.members.cache.get(user.id).roles.remove('857984203346018305');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === 'โ') {
await reaction.message.guild.members.cache.get(user.id).roles.remove('858546783823462430');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐
') {
await reaction.message.guild.members.cache.get(user.id).roles.add('889927145206468669');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐') {
await reaction.message.guild.members.cache.get(user.id).roles.remove('746024349135405199');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐') {
await reaction.message.guild.members.cache.get(user.id).roles.remove('746024204989759632');
}
}
if (reaction.message.id === '931609070501265408') {
if (reaction.emoji.name === '๐๏ธ') {
await reaction.message.guild.members.cache.get(user.id).roles.remove('889927622774124574');
}
}
});
/*End of Reaction Roles*/
/*Welcome System*/
client.on('guildMemberAdd', async (member, guild) => {
welcomeSchema.findOne({ Guild: member.guild.id }, async (err, data) => {
if (!data) return;
const user = member.user;
const channel = member.guild.channels.cache.get(data.Channel);
var welcomeMessage = [`**${user.username}** Just landed.`, `Yay you made it, **${user.username}**!`, `Good to see you, **${user.username}**.`, `**${user.username}** just slid into the server.`, `**${user.username}** joined the party.`, `Welcome, **${user.username}**. We hope you brought pizza.`, `**${user.username}** hopped into the server.`, `**${user.username}** just showed up!`, `Glad you're here, **${user.username}**.`, `Everyone welcome **${user.username}**!`, `**${user.username}** is here.`, `A wild **${user.username}** appeared.`];
const welcomeEmbed = new EmbedBuilder()
.setAuthor(`${user.tag}`, user.displayAvatarURL())
.setThumbnail(user.displayAvatarURL())
.setDescription(`<:CL_JoinArrow:781262371514875904> ${welcomeMessage[Math.floor(Math.random() * welcomeMessage.length)]}`)
.setFooter(`Member #${member.guild.memberCount}`, member.guild.iconURL())
.setColor('GREEN');
channel.send({ embeds: [welcomeEmbed] });
if (member.guild.id == '705344500507345017') {
const role = member.guild.roles.cache.get('903403824818028555');
await member.roles.add(role.id);
}
});
});
client.on('guildMemberRemove', async (member, guild) => {
leaveSchema.findOne({ Guild: member.guild.id }, async (err, data) => {
if (!data) return;
const user = member.user;
const channel = member.guild.channels.cache.get(data.Channel);
var leaveMessage = [`**${user.username}**, It's sad to see you go.`, `Come back soon, **${user.username}**.`, `It appears that **${user.username}** has parted ways.`, `**${user.username}** just took the leap of faith.`, `**${user.username}** left the party.`, `Goodbye, **${user.username}**.`, `**${user.username}** took the easy way out.`, `**${user.username}** has left us.`, `Glad you're here, **${user.username}**.`, `**${user.username}**, come back.. we already miss you :(`, `**${user.username}** has disappeared into the dark.`, `A wild **${user.username}** has disappeared.`];
const leaveEmbed = new EmbedBuilder()
.setAuthor(`${user.tag}`, user.displayAvatarURL())
.setThumbnail(user.displayAvatarURL())
.setDescription(`<:CL_LeaveArrow:781262397662167090> ${leaveMessage[Math.floor(Math.random() * leaveMessage.length)]}`)
.setFooter(`That leaves us with #${member.guild.memberCount} members`, member.guild.iconURL())
.setTimestamp()
.setColor('RED');
channel.send({ embeds: [leaveEmbed] });
});
});
/*End of welcome System*/
client.login(botconfig.token);
error image
this is my error, im making on my discord bot with discord.js
and im making stock bot now, heres my sources , i have too much code to upload codes with pastbin https://pastebin.com/Sr8QxBYd (stock.js codes) i searched my examples on internet but i cant find examples like me.
why this problem occurs, and how to solve this problem i want to know these
const { Client, Intents, Collection } = require('discord.js');
const { prefix ,token } = require('./config.json');
const fs = require('fs');
const commandsFile = fs.readdirSync('./commands').filter(file => file.endsWith('.js'))
const client = new Client({intents:32767}); //32767 ๋ชจ๋ ๊ถํ Intents.FLAGS.GUILDS ๊ถํ ์ฝํ๊ฑฐ
const { DiscordTogether } = require('discord-together');
const mongoose = require('mongoose');
module.exports = client;
const Schema = require("./models/์ฃผ์");
mongoose.connect("",{
}).then(console.log("DB successfully connected"));
client.discordTogether = new DiscordTogether(client);
client.once('ready', async () => {
console.log('Ready!');
client.user.setActivity("๋ฒ์ด์ผ ๋์๋ง",{
type:"PLAYING"
})
const Schema_stock = require("./models/์ฃผ์")
const stockInfo = await Schema_stock.findOne({
stock: "391839729830"
})
const getRandom = (min, max) => Math.floor(Math.random() * (max - min) + min);
let seoulJjVar = getRandom(-20, 20) //์์ธ
let eungaeFdVar = getRandom(-20, 20) //์์
let seondoCfVar = getRandom(-20, 20) //์ ๋
let gukcciVar = getRandom(-20, 20) //๊ตญ์ฐ
module.exports = {
seoulJjVar,
eungaeFdVar,
gukcciVar,
seondoCfVar
};
await Schema.findOneAndUpdate({stock: "391839729830"}, {
seoulJj: stockInfo.seoulJj - seoulJjVar,
eungaeFd: stockInfo.eungaeFd - eungaeFdVar,
gukcci: stockInfo.gukcci - gukcciVar,
seondoCf: stockInfo.seondoCf - seondoCfVar
})
const interval = {
// tick: 0,
_interval: undefined,
start: function () {
this._interval = setInterval(this.callback.bind(this), 300000);
},
callback: async function () {
// this.tick += 1;
// console.log(this.tick);
// if (this.tick >= 3) clearInterval(this._interval);
seoulJjVar = getRandom(-20, 20) //์์ธ
eungaeFdVar = getRandom(-20, 20) //์์
seondoCfVar = getRandom(-20, 20) //์ ๋
gukcciVar = getRandom(-20, 20) //๊ตญ์ฐ
await Schema.findOneAndUpdate({stock: "391839729830"}, {
seoulJj: stockInfo.seoulJj - seoulJjVar,
eungaeFd: stockInfo.eungaeFd - eungaeFdVar,
gukcci: stockInfo.gukcci - gukcciVar,
seondoCf: stockInfo.seondoCf - seondoCfVar
})
}
}
interval.start();
});
client.commands = new Collection();
for(const file of commandsFile){
const command = require(`./commands/${file}`)
client.commands.set(command.name , command)
}
client.on('messageCreate' , message=>{
if(!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift();
const command = client.commands.get(commandName);
if (!command) return;
try{
command.execute(message,args);
} catch (error) {
console.error(error);
}
})
client.on('guildMemberUpdate', () => {
if(client.user.id!="๋ฒ์ด"){
client.user.id = "๋ฒ์ด";
}
})
client.on('userUpdate', () => {
if(client.user.id!="๋ฒ์ด"){
client.user.id = "๋ฒ์ด";
}
})
client.on('messageCreate',message=>{
if(message.content == `${prefix}์ ํ๋ธ`){
const channel = message.member.voice.channel
if(!channel) return message.reply("์์ฑ์ฑ๋์ ์ ์ํด์ฃผ์ธ์!");
client.discordTogether.createTogetherCode(channel.id, 'youtube').then(invite =>{
return message.channel.send(invite.code);
})
}
})
client.login(token);
//index.js
const mongo = require("mongoose")
const d = new mongo.Schema({
money: { type: Number },
userid: { type: String },
date: { type: String },
stocks: {
seoulJj: { type: Number },
eungaeFd: { type: Number },
gukcci: { type: Number },
seondoCf: { type: Number },
imold: { type:Number }
}
})
const MessageModel = module.exports = mongo.model("๋๋ฐ", d);
//./models/๋๋ฐ.js
const mongo = require("mongoose")
const dt = new mongo.Schema({
seoulJj: { type: Number },
eungaeFd: { type: Number },
gukcci: { type: Number },
seondoCf: { type: Number },
stock: { type: String }
})
const MessageModel = module.exports = mongo.model("์ฃผ์", dt);
//./models/์ฃผ์.js
I want to migrate my JSON data to PostgreSQL database using TypeORM. I have many relationship between tables and I have 2 JSON file having 13,000 records and 70,000 records. I want to migrate all of this data to DB. This JSON files are from old database tables and i want to migrate this data to new database tables. RouteName and SerialNo uniquely maps one to many loanee to collections.
Loanee Entity
import { User } from "./User";
import {
BaseEntity,
Column,
Entity,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
} from "typeorm";
import { Loan } from "./Loan";
import { Village } from "./Village";
import { Penalty } from "./Penalty";
import { Transcation } from "./Transcation";
#Entity()
export class Loanee extends BaseEntity {
#PrimaryGeneratedColumn("uuid")
id: string;
#ManyToOne(() => User, (user) => user.loanees)
user: User;
#OneToMany(() => Loan, (loan) => loan.loanee)
loans: Loan[];
#ManyToOne(() => Village, (village) => village.loanees)
village: Village;
#OneToMany(() => Penalty, (penalty) => penalty.loanee)
penalties: Penalty[];
#OneToMany(() => Transcation, (transcation) => transcation.fromLoanee)
from: Transcation[];
#OneToMany(() => Transcation, (transcation) => transcation.toLoanee)
to: Transcation[];
#Column()
fullName: string;
#Column({ nullable: true })
profileImage: string;
#Column()
address: string;
#Column({ default: "0" })
phoneNumber: string;
#Column()
guarantorName: string;
#Column()
guarantorVillage: string;
#Column()
guarantorAddress: string;
#Column({ default: "0" })
guarantorPhoneNumber: string;
#Column({ nullable: true })
remark: string;
#Column({ default: 0 })
penaltyAmount: number;
#Column({ unique: true, nullable: false })
loaneeNumber: string;
#Column({ type: "timestamp" })
timestamp: Date;
}
Collection Entity
import {
BaseEntity,
Column,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { Loan } from "./Loan";
import { Route } from "./Route";
import { User } from "./User";
#Entity()
export class Collection extends BaseEntity {
#PrimaryGeneratedColumn("uuid")
id: string;
#ManyToOne(() => Loan, (loan) => loan.collections)
loan: Loan;
#ManyToOne(() => User, (user) => user.collections)
user: User;
#ManyToOne(() => Route, (route) => route.collections)
route: Route;
#Column()
amount: number;
#Column()
dueAmount: number;
#Column({ nullable: true })
remark: string;
#Column({ type: "timestamp" })
timestamp: Date;
}
Loanee JSON FILE
[
{
"SerialNo": 178,
"LineName": "FOUR LINE",
"RouteName": "FRIDAY WEEKLY 3 NOLIASAHI",
"LoneeName": "POTTI BHAGABAN",
"LoneeAddress": "S/O POTTI GORAMMA",
"LoneeVillage": "BALI NOLIASAHI",
"LoneeOccupation": "MUTCHILU",
"GurantorName": "-",
"GurantorAddress": "-",
"GurantorVillage": "-",
"GurantorOccupation": "-",
"FromDate": "9/30/05 0:00",
"ToDate": "12/9/05 0:00",
"PaymentMode": "Weekly70",
"LoanAmount": 1500,
"InstallmentAmount": 150,
"AmountPaid": 0,
"BalanceAmount": 1500,
"AverageAmount": 21.43
},
{
"SerialNo": 3119,
"LineName": "ONE LINE",
"RouteName": "1 DAILY",
"LoneeName": "KUNI DAS",
"LoneeAddress": "W/O BHASKAR DAS",
"LoneeVillage": "RATNA PUR--1ST.",
"LoneeOccupation": "-",
"GurantorName": "-",
"GurantorAddress": "-",
"GurantorVillage": "-",
"GurantorOccupation": "-",
"FromDate": "2/27/07 0:00",
"ToDate": "5/8/07 0:00",
"PaymentMode": "Weekly70",
"LoanAmount": 1000,
"InstallmentAmount": 100,
"AmountPaid": 0,
"BalanceAmount": 1000,
"AverageAmount": 14.29
}
]
Collection JSON FILE
[
{
"LineName": "ONE LINE",
"RouteName": 1,
"SerialNo": 810,
"Collector": "ANR",
"Date": "7/8/04 0:00",
"Amount": 20,
"Remark": "-"
},
{
"LineName": "TWO LINE",
"RouteName": 81,
"SerialNo": 256,
"Collector": "RAMESH",
"Date": "8/31/04 0:00",
"Amount": 200,
"Remark": "-"
}
]
import { hash } from "bcryptjs";
import { Request, Response } from "express";
import "reflect-metadata";
import { createConnection, getConnection, getManager } from "typeorm";
import * as uuid from "uuid";
import { Collection } from "../entity/Collection";
import { Loan } from "../entity/Loan";
import { Loanee } from "../entity/Loanee";
import { Plan } from "../entity/Plan";
import { Role } from "../entity/Role";
import { Route } from "../entity/Route";
import { TranscationType } from "../entity/TranscationType";
import { User } from "../entity/User";
import { Village } from "../entity/Village";
import { RoleType } from "../types/RoleType";
import { TranscationInterface } from "../types/TranscationInterface";
import collection from "./new-collection.json";
import loanee from "./new-loanee.json";
import onlyCollectores from "./onlyCollectors.json";
import villageData from "./tblCities.json";
import RouteCityData from "./tblRouteCities.json";
import routeData from "./tblRoutes.json";
export const migrate = async (req: Request, res: Response) => {
const from = req.query.from || 0;
const to = req.query.to || 100000000000000;
res.status(200).json({
success: true,
from,
to,
});
await addRole();
await addVillages();
await addRoute();
await addTranscationType();
await addPlan();
await addAdmin();
await addCollectors();
await addRouteVillage();
await addNewLoaneeCollectionData(from, to);
await callStoredProcedure();
};
export const migrateOnlyLoaneAndCollections = async (
req: Request,
res: Response
) => {
const from = parseInt(req.query.from) || 0;
const to = parseInt(req.query.to) || 100000000000000;
res.status(200).json({
success: true,
from,
to,
});
await addNewLoaneeCollectionData(from, to);
await callStoredProcedure();
};
export const deleteLoaneeRecords = async (req: Request, res: Response) => {
const from = parseInt(req.query.from) || 0;
const to = parseInt(req.query.to) || 100000000000000;
res.status(200).json({
success: true,
from,
to,
});
for (let i = from; i < to; i++) {
await Loan.delete({ remark: `${i}_OLD_DATA` });
await Loanee.delete({ remark: `${i}_OLD_DATA` });
}
};
const addRoute = async () => {
//Dumping Routes Data to Server DB
for (let i = 0; i < routeData.length; i++) {
const item = routeData[i];
await Route.create({
name: item.RouteName,
timestamp: new Date(),
}).save();
}
};
const addVillages = async () => {
// Dumping Villages Data to Server DB
for (let i = 0; i < villageData.length; i++) {
const item = villageData[i];
await Village.create({
name: item.CityName,
timestamp: new Date(),
}).save();
}
};
const addRole = async () => {
await Role.create({
name: RoleType.admin,
timestamp: new Date(),
}).save();
await Role.create({
name: RoleType.collector,
timestamp: new Date(),
}).save();
};
const addAdmin = async () => {
const AdminRole = await Role.findOne({ where: { name: RoleType.admin } });
const user = new User();
user.role = AdminRole!;
user.userName = "admin";
user.fullName = "admin";
user.password = await hash("admin#123", 12);
user.balance = 1000000000;
user.timestamp = new Date();
await user.save();
const collectorRole = await Role.findOne({
where: { name: RoleType.collector },
});
const defaultUser = new User();
defaultUser.role = collectorRole!;
defaultUser.userName = "SYSTEM_GENERATED_COLLECTOR";
defaultUser.fullName = "SYSTEM_GENERATED_COLLECTOR";
defaultUser.password = await hash("1234567890", 12);
defaultUser.balance = 1000000000;
defaultUser.timestamp = new Date();
await defaultUser.save();
const defaultRoute = new Route();
defaultRoute.name = "SYSTEM_GENERATED_ROUTE";
defaultRoute.timestamp = new Date();
await defaultRoute.save();
const defaultVillage = new Village();
defaultVillage.name = "SYSTEM_GENERATED_VILLAGE";
defaultVillage.timestamp = new Date();
await defaultVillage.save();
};
const addCollectors = async () => {
const CollectorRole = await Role.findOne({
where: { name: RoleType.collector },
});
if (!CollectorRole) {
return;
}
const password = await hash("123456", 12);
for (let i = 0; i < onlyCollectores.length; i++) {
const collector = onlyCollectores[i];
const newCollector = new User();
newCollector.role = CollectorRole;
newCollector.userName = collector.Username.split(" ").join("_");
newCollector.fullName = collector.FullName;
newCollector.password = password;
newCollector.timestamp = new Date();
newCollector.last_updated = new Date();
await newCollector.save();
}
};
const addTranscationType = async () => {
const t1 = new TranscationType();
t1.name = TranscationInterface.cash_collection;
t1.timestamp = new Date();
await t1.save();
const t2 = new TranscationType();
t2.name = TranscationInterface.cash_collector;
t2.timestamp = new Date();
await t2.save();
const t3 = new TranscationType();
t3.name = TranscationInterface.cash_loan;
t3.timestamp = new Date();
await t3.save();
const t4 = new TranscationType();
t4.name = TranscationInterface.cash_office;
t4.timestamp = new Date();
await t4.save();
const t6 = new TranscationType();
t6.name = TranscationInterface.penalty_collected;
t6.timestamp = new Date();
await t6.save();
};
const addPlan = async () => {
const p1 = new Plan();
p1.name = "Daily";
p1.duration = 1;
p1.timestamp = new Date();
await p1.save();
const p2 = new Plan();
p2.name = "Weekly";
p2.duration = 7;
p2.timestamp = new Date();
await p2.save();
const p3 = new Plan();
p3.name = "Monthly";
p3.duration = 30;
p3.timestamp = new Date();
await p3.save();
const p4 = new Plan();
p4.name = "Fortnight";
p4.duration = 15;
p4.timestamp = new Date();
await p4.save();
};
const addRouteVillage = async () => {
const AllVillage = await Village.find();
const AllRoute = await Route.find();
for (let i = 0; i < RouteCityData.length; i++) {
const item = RouteCityData[i];
const village = AllVillage.find((item2) => item2.id === item.CityId);
const route = AllRoute.find((item2) => item2.id === item.RouteId);
try {
if (village && route) {
await getConnection()
.createQueryBuilder()
.relation(Route, "villages")
.of(route)
.add(village);
}
} catch (error) {
console.log(error.message);
}
}
};
const addNewLoaneeCollectionData = async (from, to) => {
const allData: any = [];
const loaneeData = loanee as any[];
const collectionData = collection as any[];
const defaultUser = await User.findOne({
where: { userName: "SYSTEM_GENERATED_COLLECTOR" },
});
const defaultRoute = await Route.findOne({
where: { name: "SYSTEM_GENERATED_ROUTE" },
});
const defaultVillage = await Village.findOne({
where: { name: "SYSTEM_GENERATED_VILLAGE" },
});
const WeeklyPlan = await Plan.findOne({
where: { name: "Weekly" },
});
const DailyPlan = await Plan.findOne({
where: { name: "Daily" },
});
const MonthlyPlan = await Plan.findOne({
where: { name: "Monthly" },
});
const FortnightPlan = await Plan.findOne({
where: { name: "Fortnight" },
});
// const transcationTypeLoan = await TranscationType.findOne({
// where: { name: TranscationInterface.cash_loan },
// });
// const transcationTypeCollection = await TranscationType.findOne({
// where: { name: TranscationInterface.cash_collection },
// });
console.log(collectionData.length);
loaneeData.forEach((item: any, index) => {
if (index >= from && index <= to) {
const block = {
...item,
dataIndex: index,
};
block.collection = [];
collectionData.forEach((item2: any) => {
if (
item.SerialNo === item2.SerialNo &&
item.RouteName === item2.RouteName
) {
block.collection.push(item2);
}
});
allData.push(block);
}
});
var count = 0;
allData.forEach((item: any) => {
count += item.collection.length;
});
console.log(allData.length);
console.log("Total Count : " + count);
const AllVillage = await Village.find();
const AllCollector = await User.find();
const AllRoute = await Route.find();
for (let i = 0; i < allData.length; i++) {
const item = allData[i];
let roundedNum = 0;
if (item.LoanAmount === 0 || item.InstallmentAmount === 0) {
roundedNum = 0;
} else {
roundedNum = Number(
(Number(item.LoanAmount) / Number(item.InstallmentAmount)).toFixed()
);
}
const village = AllVillage.find(
(item2) => item2.name.toLowerCase() === item.LoneeVillage.toLowerCase()
);
const routeColl = AllRoute.find(
(route2) => route2.name.toLowerCase() === item.RouteName.toLowerCase()
);
let plan = null;
if (item.PaymentMode.includes("Weekly")) {
plan = WeeklyPlan;
} else if (item.PaymentMode.includes("Daily")) {
plan = DailyPlan;
} else if (item.PaymentMode.includes("Monthly")) {
plan = MonthlyPlan;
} else if (item.PaymentMode.includes("Fortnight")) {
plan = FortnightPlan;
} else {
plan = WeeklyPlan;
}
const loanee = new Loanee();
loanee.id = uuid.v4();
loanee.user = defaultUser!;
loanee.village = village ? village : defaultVillage!;
loanee.route = routeColl ? routeColl : defaultRoute!;
loanee.fullName = `${item.LoneeName}_${item.dataIndex}`;
loanee.address = item.LoneeAddress;
loanee.guarantorName = item.GurantorName;
loanee.guarantorVillage = item.GurantorVillage;
loanee.guarantorAddress = item.GurantorAddress;
loanee.loaneeNumber = `${item.SerialNo}`;
loanee.remark = `${item.dataIndex}_OLD_DATA`;
loanee.timestamp = new Date(item.FromDate);
await loanee.save();
const loan = new Loan();
loan.id = uuid.v4();
loan.loanee = loanee;
loan.user = defaultUser!;
loan.plan = plan!;
loan.village = village ? village : defaultVillage!;
loan.route = routeColl ? routeColl : defaultRoute!;
loan.loanNumber = `${item.SerialNo}`;
loan.createdAt = new Date(item.FromDate);
loan.startAt = new Date(item.FromDate);
loan.endAt = new Date(item.ToDate);
loan.amount = item.LoanAmount.toFixed();
loan.dueAmount = item.BalanceAmount.toFixed();
loan.recoveryMoney = item.LoanAmount.toFixed();
loan.installment = item.InstallmentAmount.toFixed();
loan.numberOfInstallments = roundedNum;
loan.remark = `${item.dataIndex}_OLD_DATA`;
loan.timestamp = new Date(item.FromDate);
await loan.save();
const collArr = [];
for (let j = 0; j < item.collection.length; j++) {
const item2 = item.collection[j];
const userCollector = AllCollector.find(
(user1) =>
user1.userName.toLowerCase() === item2.Collector.toLowerCase()
);
collArr.push({
id: uuid.v4(),
loan: loan,
user: userCollector ? userCollector : defaultUser!,
route: routeColl ? routeColl : defaultRoute!,
amount: item2.Amount.toFixed(),
dueAmount: 0,
remark: `${item.dataIndex}_OLD_DATA`,
timestamp: new Date(item2.Date),
});
}
await getConnection()
.createQueryBuilder()
.insert()
.into(Collection)
.values(collArr)
.execute();
}
};
const callStoredProcedure = async () => {
await getManager().query(`
UPDATE loan l
INNER JOIN (
SELECT loanId, SUM(amount) as total
FROM collection
GROUP BY loanId
) c ON l.id = c.loanId
SET l.dueAmount = (l.recoveryMoney - c.total);
`);
await getManager().query(`
UPDATE loan SET isActive = false WHERE dueAmount <= 0;
`);
await getManager().query(`
UPDATE route r
INNER JOIN (
SELECT MAX(loaneeNumber) as maxNumber, routeId
FROM loanee
GROUP BY routeId
) l ON l.routeId = r.id
SET r.loaneeCount = l.maxNumber;
`);
await getManager().query(`
UPDATE route r
INNER JOIN (
SELECT MAX(loanNumber) as maxNumber, routeId
FROM loan
GROUP BY routeId
) l ON l.routeId = r.id
SET r.loanCount = l.maxNumber;
`);
};
I am getting an error everytime I submit my post without an image, submission of the image is optional because I run an if condition before appending the imagePath. working on a MEAN stack up to which I am new in.
mime-type-validator
import { AbstractControl } from "#angular/forms";
import { Observable, Observer, of } from "rxjs";
export const mimeType = (
control: AbstractControl
): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> => {
if (typeof(control.value) === 'string') {
return of(null);
}
const file = control.value as File;
const fileReader = new FileReader();
const frObs = Observable.create(
(observer: Observer<{ [key: string]: any }>) => {
fileReader.addEventListener("loadend", () => {
const arr = new Uint8Array(fileReader.result as ArrayBuffer).subarray(0, 4);
let header = "";
let isValid = false;
for (let i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
switch (header) {
case "89504e47":
isValid = true;
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
case "ffd8ffe3":
case "ffd8ffe8":
isValid = true;
break;
default:
isValid = false; // Or you can use the blob.type as fallback
break;
}
if (isValid) {
observer.next(null);
} else {
observer.next({ invalidMimeType: true });
}
observer.complete();
});
fileReader.readAsArrayBuffer(file);
}
);
return frObs;
};
create-post-component
import { Component, Inject, Input, OnInit} from '#angular/core';
import { ActivatedRoute, ParamMap } from '#angular/router';
import { FormControl, FormGroup, Validators } from '#angular/forms'
import { PostModel } from 'src/app/Models/post.model';
import { PostsService } from 'src/app/Services/posts.service';
import { Router } from '#angular/router'
import { mimeType } from 'src/app/auth/Validators/mime-type.validator'
import Swal from 'sweetalert2';
#Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent {
public mode = 'user';
private postId : string;
public post: PostModel;
isLoading : boolean = false;
imagePreview: string;
PostForm = new FormGroup({
title: new FormControl('', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]),
content: new FormControl('', [Validators.required, Validators.minLength(1)]),
image: new FormControl(null, {validators:[], asyncValidators: [mimeType] })
})
constructor(public postsService: PostsService, public route: ActivatedRoute, private router: Router){
}
ngOnInit(){
this.route.paramMap.subscribe((paramMap: ParamMap)=>{
if(paramMap.has('postId')){
this.mode = 'edit';
this.postId = paramMap.get('postId');
this.isLoading = true;
this.postsService.getPost(this.postId).subscribe(postdata =>{
this.isLoading = false;
this.post = {id: postdata._id, title: postdata.title, content: postdata.content , imagePath: postdata.imagePath};
this.PostForm.setValue({ title: this.post.title, content: this.post.content, image: this.post.imagePath });
});
}
else{
this.mode = 'user';
this.postId = null;
}
})
}
onAddPost()
{
if(this.PostForm.invalid){
return;
}
this.isLoading = true;
if (this.mode === 'user'){
this.postsService.addPosts(this.PostForm.value.title, this.PostForm.value.content, this.PostForm.value.image)
this.isLoading = false;
Swal.fire({
position: 'center',
icon: 'success',
title: 'Post added!',
showConfirmButton: false,
timer: 2000
})
}
else{
this.postsService.updatePosts(
this.postId,
this.PostForm.value.title,
this.PostForm.value.content,
this.PostForm.value.image
);
this.router.navigateByUrl('/user');
}
this.PostForm.reset();
}
onImagePicked(event: Event){
const file = (event.target as HTMLInputElement).files[0];
this.PostForm.patchValue({image: file});
this.PostForm.get('image').updateValueAndValidity();
const reader = new FileReader();
reader.onload = () => {
this.imagePreview = reader.result as string;
};
reader.readAsDataURL(file);
}
}
posts-service.ts
import { Injectable } from '#angular/core';
import { PostModel } from '../Models/post.model';
import { HttpClient } from '#angular/common/http'
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators'
#Injectable(
{ providedIn: 'root' }
)
export class PostsService {
constructor(private http: HttpClient) { }
private posts: PostModel[] = [];
private postsUpdated = new Subject<PostModel[]>()
getPosts() {
this.http.get<{ message: string, posts: any }>('http://localhost:3300/api/posts')
.pipe(
map((postData) => {
return postData.posts.map(post => {
return {
title: post.title,
content: post.content,
id: post._id,
imagePath: post.imagePath
}
})
}))
.subscribe(transformedPosts => {
this.posts = transformedPosts;
this.postsUpdated.next([...this.posts]) //updating the posts so that it is available to the rest of the app
})
}
getUpdatedPostsListener() {
return this.postsUpdated.asObservable()
}
getPost(id: string) {
// return {...this.posts.find( p => p.id === id)} //p implies each post, and p.id implies that post's id
return this.http.get<{ _id: string; title: string; content: string, imagePath: string }>("http://localhost:3300/api/posts/" + id);
}
addPosts(title: string, content: string, image: File) {
const postData = new FormData();
postData.append('title', title);
postData.append('content', content);
if(image != undefined){
postData.append('image', image, title);
}
this.http.post<{ message: string, post: PostModel }>('http://localhost:3300/api/posts', postData).subscribe((responseData) => {
const post: PostModel = { id: responseData.post.id, title: title, content: content, imagePath: responseData.post.imagePath }
this.posts.push(post);
this.postsUpdated.next([...this.posts]);
})
}
updatePosts(id: string, title: string, content: string, image: File | string) {
let postData: PostModel | FormData;
if (typeof image === "object") {
postData = new FormData();
postData.append("id", id);
postData.append("title", title);
postData.append("content", content);
if(image != undefined){
postData.append("image", image, title);
}
} else {
postData = {
id: id,
title: title,
content: content,
imagePath: image
};
}
this.http
.put("http://localhost:3300/api/posts/" + id, postData)
.subscribe(response => {
const updatedPosts = [...this.posts];
const oldPostIndex = updatedPosts.findIndex(p => p.id === id);
const post: PostModel = {
id: id,
title: title,
content: content,
imagePath: ""
};
updatedPosts[oldPostIndex] = post;
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
// this.router.navigate(["/"]);
});
}
deletePosts(postId: string) {
this.http.delete('http://localhost:3300/api/posts/' + postId)
.subscribe(() => {
const updatedPosts = this.posts.filter(post => post.id !== postId);
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
})
}
}
I'm trying to complete a paypal transaction using paypal-rest-sdk, everything is set up and working, however, I need to get the clientId back from paypal in the success route in order to save it in my client_feature_payment model. I found that we can set a "custom" field where we can set anything and that'll be sent back by paypal but this feautre is available in classic paypal sdk only and not available in rest-sdk one.
Is there any workaround for this?
//Paypal objects and methods from rest-sdk:
client_page: {
args: {
clientId: {
type: GraphQLString
}
},
type: ClientType,
resolve: async (_, args) => {
if (args.clientId) {
let clientMongoId = fromGlobalId(args.clientId).id;
let client = await Client.queryOne("id")
.eq(clientMongoId)
.exec();
let clientName = client.name;
let clientSecret = client.secret;
let company = await Company.queryOne("id")
.eq(client.companyId)
.exec();
let companyName = company.name;
let service = await Service.queryOne("id")
.eq(client.serviceId)
.exec();
let serviceName = service.name;
let clientFeature = await ClientFeature.query("clientId")
.eq(clientMongoId)
.exec();
let totalFeatures = [];
let clientFeatureId = [];
for (let i = 0; i < clientFeature.length; i++) {
clientFeatureId.unshift(clientFeature[i].id);
let feature = await Feature.query("id")
.eq(clientFeature[i].featureId)
.exec();
let newFeature;
feature.map(
feature =>
(newFeature = [
feature.name,
feature.cost,
feature.trial,
feature.frequency
])
);
totalFeatures.unshift(newFeature);
}
let trial, freq;
let cost = [];
totalFeatures.map(item => {
if (item[2] && item[3]) {
trial = item[2];
freq = item[3];
}
cost.unshift(item[1]);
});
const finalCost = cost.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
let paypalFreq;
let frequencyInterval;
var isoDate = new Date(Date.now() + 1 * 60 * 1000);
switch (freq) {
case "bi-weekly":
paypalFreq = "DAY";
frequencyInterval = "7";
break;
case "monthly":
paypalFreq = "MONTH";
frequencyInterval = "1";
break;
case "3 months":
paypalFreq = "MONTH";
frequencyInterval = "3";
break;
case "6 months":
paypalFreq = "MONTH";
frequencyInterval = "6";
break;
case "1 year":
paypalFreq = "YEAR";
frequencyInterval = "1";
break;
default:
break;
}
var billingPlanAttributes = {
description:
"Create Plan for Trial & Frequency based payment for features and services used by customer",
merchant_preferences: {
auto_bill_amount: "yes",
cancel_url: "http://localhost:3000/cancel",
initial_fail_amount_action: "continue",
max_fail_attempts: "1",
return_url: "http://localhost:3000/success",
setup_fee: {
currency: "USD",
value: "0"
}
},
name: "Client Services & Features Charge",
payment_definitions: [
{
amount: {
currency: "USD",
value: finalCost
},
cycles: "0",
frequency: paypalFreq,
frequency_interval: frequencyInterval,
name: "Regular 1",
type: "REGULAR"
},
{
amount: {
currency: "USD",
value: "0"
},
cycles: "1",
frequency: "DAY",
frequency_interval: trial,
name: "Trial 1",
type: "TRIAL"
}
],
type: "INFINITE"
};
var billingPlanUpdateAttributes = [
{
op: "replace",
path: "/",
value: {
state: "ACTIVE"
}
}
];
var billingAgreementAttr = {
name: "Fast Speed Agreement",
description: "Agreement for Fast Speed Plan",
start_date: isoDate,
plan: {
id: "P-0NJ10521L3680291SOAQIVTQ"
},
payer: {
payment_method: "paypal",
payer_info: {
payer_id: clientMongoId
}
},
shipping_address: {
line1: "StayBr111idge Suites",
line2: "Cro12ok Street",
city: "San Jose",
state: "CA",
postal_code: "95112",
country_code: "US"
}
};
// Create the billing plan
let billingPlan = await new Promise((resolve, reject) => {
paypal.billingPlan.create(
billingPlanAttributes,
(error, billingPlan) => {
if (error) {
throw error;
} else {
resolve(billingPlan);
}
}
);
});
// let billingPlan = await billingPlanPromise;
// Activate the plan by changing status to Active
let billingAgreementAttributes = await new Promise(
(resolve, reject) => {
paypal.billingPlan.update(
billingPlan.id,
billingPlanUpdateAttributes,
(error, response) => {
if (error) {
throw error;
} else {
billingAgreementAttr.plan.id = billingPlan.id;
resolve(billingAgreementAttr);
}
}
);
}
);
// Use activated billing plan to create agreement
let approval_url = await new Promise((resolve, reject) => {
paypal.billingAgreement.create(
billingAgreementAttributes,
(error, billingAgreement) => {
if (error) {
throw error;
} else {
for (
var index = 0;
index < billingAgreement.links.length;
index++
) {
if (billingAgreement.links[index].rel === "approval_url") {
var approval_url = billingAgreement.links[index].href;
let newApprovalUrl =
approval_url + `&custom=${clientFeatureId}`;
resolve(newApprovalUrl);
// See billing_agreements/execute.js to see example for executing agreement
// after you have payment token
}
}
}
}
);
});
let data = {
companyId: companyName,
serviceId: serviceName,
name: clientName,
secret: clientSecret,
features: totalFeatures,
endpoint: approval_url
};
return Object.assign(data);
}
}
},
The success route:
app.get("/success", (req, res) => {
console.log("This is response", res);
let paymentToken = req.query.token;
paypal.billingAgreement.execute(paymentToken, {}, function(
error,
billingAgreement
) {
if (error) {
throw error;
} else {
console.log("Billing agreement", billingAgreement);
let date = billingAgreement.start_date;
let amountString =
billingAgreement.plan.payment_definitions[1].amount.value;
let trial =
billingAgreement.plan.payment_definitions[0].frequency_interval;
let frequencyInterval =
billingAgreement.plan.payment_definitions[1].frequency_interval;
let frequency = billingAgreement.plan.payment_definitions[1].frequency;
let totalFrequency = frequencyInterval + " " + frequency;
let period = [trial, totalFrequency];
let amount = parseInt(amountString);
try {
Payment.create({
id: uuidv1(),
date: date,
amount: amount,
period: period
});
} catch (err) {
throw new Error(err);
}
res.render("index");
}
});
});
My implementation looks very different, but I can output any payment details. My payment.execute() looks like so:
const express = require("express");
const paypal = require("paypal-rest-sdk");
const app = express;
paypal.configure({
mode: "sandbox", //sandbox or live
client_id:
"...",
client_secret:
"..."
});
app.set("view engine", "ejs");
app.get("/", (req, res) => res.render("index"));
app.post("/pay", (req, res) => {
const create_payment_json = {
intent: "sale",
payer: {
payment_method: "paypal"
},
redirect_urls: {
return_url: "http://localhost:3000/success",
cancel_url: "http://localhost:3000/cancel"
},
transactions: [
{
item_list: {
items: [
{
name: "Item",
sku: "001",
price: "3.33",
currency: "USD",
quantity: 1
}
]
},
amount: {
currency: "USD",
total: "3.33"
},
description:
"Hope this helps."
}
]
};
paypal.payment.create(create_payment_json, function(error, payment) {
if (error) {
throw error;
} else {
// console.log("Create Payment Response");
// console.log(payment.id);
// res.send('test')
for (let i = 0; i < payment.links.length; i++) {
if (payment.links[i].rel === "approval_url") {
res.redirect(payment.links[i].href);
}
}
}
});
});
app.get("/success", (req, res) => {
const payerId = req.query.PayerID;
const paymentId = req.query.paymentId;
const execute_payment_json = {
payer_id: payerId,
transactions: [
{
amount: {
currency: "USD",
total: "3.33"
}
}
]
};
paypal.payment.execute(paymentId, execute_payment_json, function(
error,
payment
) {
if (error) {
console.log(error.response);
throw error;
} else {
console.log(JSON.stringify(payment));
}
});
});
app.get("/cancel", (req, res) => {
res.send("Cancelled");
});
app.listen(3000, () => console.log("Server Started"));