Laravel programmatically commands will not work with users - javascript

Hi I am trying to run commands with buttons I created. Some commands must send an email to a user, but I keep getting 500 internal server errors. Also, how do I filter the user data to retrieve email address of currently logged in user?
Here is my route:
Route::get('/admin/systemadmin/index', 'CommandsController#index')->middleware('permission:page-view-admin-systemadmin')->middleware('Analyse');
Route::post('/admin/artisan/commands/run', 'CommandsController#runCommand')->middleware('Analyse');
Here is my controller:
public function index() {
$users = User::all();
$commands = [
[
'id' => 1,
'signature' => 'sync:whatever',
'user' =>'',
'title' =>'Sync Whatever',
'groupID' => 1,
'groupName' => 'First Group'
],
[
'id' => 2,
'signature' => 'send:smsNotification',
'user' =>'users',
'title' =>'Send SMS',
'groupID' => 3,
'groupName' => 'Notification'
],
];
return view('admin.systemadmin.test')->with(
[
'users' => $users,
'commands' => collect($commands)
]
);
}
public function runCommand(Request $request){
$users = User::all();
$signature = $request->input('signature');
$command = Artisan::call($signature);
return response($command);
}
Here is my blade.php:
<div v-for="(commands, groupName) in groupedCommands">
<h4>#{{ groupName }}</h4>
<div class="btn-group" v-for="command in commands">
<commands-component
:entity-config="commandConfig(command.id, command.signature, command.user, command.title, command.groupID, command.groupName)">
<input style="margin-right:10px;margin-bottom:10px;" type="button" class="btn btn-primary" v-bind:value="command.title">
</commands-component>
</div>
</div>
My Vue:
commandConfig: function(ident, signature, user, title, groupId, groupName){
$data = {
id: { text: 'commandModal' + ident, id: null },
modalTitle: title,
buttons: [
{
buttonTitle: 'Run Command',
buttonClass: 'btn btn-success pull-right',
submitUrl: {
url: '/admin/artisan/commands/run',
},
}
],
attributes: [
{name: "message", displayName: "Are you sure you want to proceed with the command?", type: "action-text", col: "12" },
{name: "signature", displayName: "Command Signature", type:'text', col:"12"}
],
data: {
signature:signature + ' ' + this.users[0].email,
user: user
}
}
return $data;
}
}

Related

How to use an array with prisma upsert in transaction

I'm trying to pass an array in my request. My array can have up to 6 entries, but how to use them all with upsert using Prisma ?
The models used :
model Board {
id String #id #unique #default(uuid())
title String
User User #relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
userId Int
columns Column[]
tasks Task[]
}
model Column {
id Int #id #default(autoincrement())
column String
Board Board #relation(fields: [boardId], references: [id], onDelete: Cascade, onUpdate: Cascade)
boardId String
tasks Task[]
}
The function :
const columns = req.body.columns;
const updateBoardData = prisma.board.update({
where: { id: req.body.id },
data: { title: req.body.title },
});
const upsertColumns = prisma.column.upsert({
where: { id: 65 }, //If id exists, it's updated
update: columns[0],
create: columns[0],
});
await prisma
.$transaction([updateBoardData, upsertColumns])
.then((board) => {
return res.status(201).json({ board });
})
.catch((err) => {
console.log(err);
return res.status(500).json(`${err}`);
})
.finally(() => {
return prisma.$disconnect();
});
The problem with this function is, if the id exists,the update is done on the right column (the table i want to apply the update or create), but if the id doesn't exist, i am having this following error :
PrismaClientKnownRequestError:
Invalid `prisma.board.update()` invocation in
C:\Users\Sébastien\Desktop\Kanban\Server\src\routes\boards\boards.controllers.js:170:42
167 const columns = req.body.columns;
168 const boardId = req.body.id;
169
→ 170 const updateBoardData = prisma.board.update(
Unique constraint failed on the constraint: `PRIMARY`
at RequestHandler.handleRequestError (C:\Users\Sébastien\Desktop\Kanban\Server\node_modules\#prisma\client\runtime\index.js:34310:13)
at RequestHandler.request (C:\Users\Sébastien\Desktop\Kanban\Server\node_modules\#prisma\client\runtime\index.js:34293:12)
at async PrismaClient._request (C:\Users\Sébastien\Desktop\Kanban\Server\node_modules\#prisma\client\runtime\index.js:35273:16)
at async Promise.all (index 0)
at async updateBoard (C:\Users\Sébastien\Desktop\Kanban\Server\src\routes\boards\boards.controllers.js:189:5) {
code: 'P2002',
clientVersion: '4.6.0',
meta: { target: 'PRIMARY' }
}
The request sent via postman is the following one :
{
"id": "fe6e843a-bcab-4404-85d0-8324794f04cc",
"title": "TITLE UPDATED",
"columns": [
{ "id": 65, "column": "TODO", "boardId": "fe6e843a-bcab-4404-85d0-8324794f04cc"},
{ "id":66, "column": "DONE", "boardId": "fe6e843a-bcab-4404-85d0-8324794f04cc"},
{ "column": "NEW COLUMN", "boardId": "fe6e843a-bcab-4404-85d0-8324794f04cc" }
]
}
UPDATE : Console.log(req.body)
{
id: 'fe6e843a-bcab-4404-85d0-8324794f04cc',
title: 'TITLE UPDATED',
columns: [
{
id: 65,
column: 'TODO',
boardId: 'fe6e843a-bcab-4404-85d0-8324794f04cc'
},
{
id: 66,
column: 'DONE',
boardId: 'fe6e843a-bcab-4404-85d0-8324794f04cc'
},
{
column: 'NEW COLUMN',
boardId: 'fe6e843a-bcab-4404-85d0-8324794f04cc'
}
]
}
So my two issues are, how to make update and create working together ? And how make it dynamically while using every entries of the columns array.

How do I specify options for commands?

I want to specify choices for an option for my command in Discord.js. How do I do that?
The command:
module.exports = {
name: 'gifsearch',
description: 'Returns a gif based on your search term.',
options: [{
name: 'type',
type: 'STRING',
description: 'Whether to search for gifs or stickers.',
choices: //***this is the area where I have a question***
required: true
},
{
name: 'search_term',
type: 'STRING',
description: 'The search term to use when searching for gifs.',
required: true,
}],
async execute(interaction) {
let searchTerm = interaction.options.getString('search_term')
const res = fetch(`https://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=${process.env.giphyAPIkey}&limit=1&rating=g`)
.then((res) => res.json())
.then((json) => {
if (json.data.length <= 0) return interaction.reply({ content: `No gifs found!` })
interaction.reply({content: `${json.data[0].url}`})
})
},
};
I have read the discord.js documentation/guide and I know about the .addChoice() method, but it doesn't look like that will be compatible with my bot's current code.
The discord.js api describes this as ApplicationCommandOptionChoices.
So you basically just insert an array of this in your choices.
module.exports = {
...
choices: [
{
name: "name to display",
value: "the actual value"
},
{
name: "another option",
value: "the other value"
}
]
...
};

Sequelize include nested column: Unknown column in 'where clause'

I am trying to use the Sequelize ORM's feature that allows referring the nested column from the included Models (See Sequelize Docs: Complex where clauses at the top-level). In the docs it states that, I can use $nested.column$ syntax.
The following is what I was trying to do:
let where = { memberId };
if (req.query.search) {
const like = { [Op.like]: `%${req.query.search}%` };
where = {
...where,
[Op.or]: [
{ '$bookItem.serial$': like },
{ '$bookItem.book.name$': like },
{ '$bookItem.book.ISBNCode$': like },
],
};
}
const options = {
where,
include: [
{
model: models.BookItem,
as: 'bookItem',
required: false,
include: [
{
model: models.Book,
as: 'book',
attributes,
required: false,
},
],
},
],
});
const transactions = await models.Borrow.findAll(options);
However, for the code above, I am getting the following error:
"Unknown column 'bookItem.serial' in 'where clause'"
What am I missing?
Full DB Schema: https://dbdiagram.io/d/5e08b6aaedf08a25543f79cb
Is bookitem a Table? Or a Database?
bookItem.serial either represents db.tbl or tbl.column
bookItem.book.name can only represent db.tbl.column
Since bookItem seems to be a database name, then serial must be a table name. At that point, "tablename LIKE ..." is a syntax error.
In your linked documentation books has no name column, change $bookItem.book.name$ to $bookItem.book.title$, and try adding right: true below required: false to create an inner join.
I have corrected this error on my side. Initially, I am writing this query
but now I have rearranged the query and it works
WRONG QUERY
let where = {
[op.and]: [
{ id: partner_id },
{ [op.or]: [
{ '$customers.customer_name$': { [op.like]: '%' + query + '%'} },
{ '$customers.email$': { [op.like]: '%' + query + '%'} },
]},
],
};
// const where = {
// id: partner_id
// }
return await this.deliveryBoys.findOne({
attributes: [
['id', 'partner_id'],
'delivery_boy_name',
'email',
'profile_picture',
'phone_number',
'fcm_token',
],
include: [
{
model: this.customers,
as: 'customers',
attributes: ['id', 'customer_name', 'email', 'profile_picture', 'phone_number'],
require: true,
where: {
customer_name: {
[op.like]: '%' + query + '%'
}
},
include: [
{
model: this.company,
as: 'company',
},
{
model: this.address,
as: 'address',
required: false,
where: {
status: 1
}
}
]
},
],
where,
});
FINAL WORKING QUERY
let where = {
[op.and]: [
{ '$deliveryBoys.id$': partner_id },
{ [op.or]: [
{ '$customers.email$': { [op.like]: '%' + query + '%'} },
{ '$customers.customer_name$': { [op.like]: '%' + query + '%'} },
{ '$customers.phone_number$': { [op.like]: '%' + query + '%'} },
{ '$company.name$': { [op.like]: '%' + query + '%'} },
]},
],
};
return await this.customers.findAll({
attributes: ['id', 'customer_name', 'email', 'profile_picture', 'phone_number'],
include:[
{
model: this.deliveryBoys,
as: 'deliveryBoys',
attributes: ['id','delivery_boy_name','phone_number','email','profile_picture','status',],
where:{
id: partner_id
}
},
{
model: this.company,
as: 'company',
},
{
model: this.address,
as: 'address',
required: false,
where: {
status: 1
}
}
],
where
});

Typescript - get array that satisfy a condition

Is it possible to get an output array from the given that contains roles=1 without duplicate ?
Iam using angular 6 typescript. Is there any typescript array processing functions to do this operation
//Input Array
export const userMenus = [
{
name: 'Dashboard',
url: '/dashboards',
icon: 'icon-speedometer',
roles:'1,3,4'
},
{
name: 'Users',
url: '/Users',
icon: 'icon-bell',
roles:'1,2,3,4'
},
{
name: 'Article',
url: '/Users',
icon: 'icon-bell',
roles:'1,2,3,4',
children: [
{
name: 'Cards',
url: '/base/cards',
icon: 'icon-puzzle',
roles:'1,3,4',
},
{
name: 'Carousels',
url: '/base/carousels',
icon: 'icon-puzzle',
roles:'2,4',
},
{
name: 'Collapses',
url: '/base/collapses',
icon: 'icon-puzzle',
roles:'4'
}
]
}
]
--Need Output if role is 2.
removed items that not contain 2 in the role field
userMenus = [
{
name: 'Users',
url: '/Users',
icon: 'icon-bell',
roles:'1,2,3,4'
},
{
name: 'Article',
url: '/Users',
icon: 'icon-bell',
roles:'1,2,3,4',
children: [
{
name: 'Carousels',
url: '/base/carousels',
icon: 'icon-puzzle',
roles:'2,4',
},
]
}
You must filter your array and verify that you have 2 in your roles :
const filteredUserMenus = userMenus.filter((userMenu) => {
return userMenu.roles.find((role) => role === '2');
});
short syntax :
const filteredUserMenus = userMenus.filter((userMenu) =>
userMenu.roles.find((role) => role === '2'));
EDIT : your data structure is bad, roles shouldn't be a string but an array of role. Anyway, if you can't change it, here is a solution :
const filteredUserMenus = userMenus.filter((userMenu) => {
return userMenu.roles.split(',').find((role) => role === '2');
});
short syntax :
const filteredUserMenus = userMenus.filter((userMenu) =>
userMenu.roles.split(',').find((role) => role === '2'));

Returning a value with node inquirer package

I'm attempting to use the node.js inquirer package to run a simple flashcard generator. I'm having trouble getting the syntax to return the checkbox the user clicked. So, once the user makes a choice, I'd like to be able to log the result of that choice. Currently this console.log() returns "undefined".
Any help appreciated!
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
{
name: "Create a Basic Card"
},
{
name: "Create a Cloze Card"
},
{
name: "Run the flashcards!"
}
]
}
]).then(function(answers){
console.log(answers.typeOfCard[0])
});
const inquirer = require('inquirer');
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
"Create a Basic Card",
"Create a Cloze Card",
"Run the flashcards!"
]
}
]).then(function(answers){
console.log(answers.typeOfCard);
});
choices should just be an array of strings. You will then be returned an array containing the selected items, ex:
[ 'Create a Cloze Card', 'Run the flashcards!' ]
Hope that helps!
const inquirer = require("inquirer");
console.clear();
const main = async() => {
const readCardChoise = () => {
const read = new Promise((resolve, reject) => {
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
{
name: "Create a Basic Card"
},
{
name: "Create a Cloze Card"
},
{
name: "Run the flashcards!"
}
],
validate(answer) {
if (answer.length < 1) {
return 'You must choose at least one card.';
}
return true;
},
}])
.then((answers) => {
resolve(answers.typeOfCard);
});
});
return read;
}
const cadSelect = await readCardChoise();
console.log(cadSelect)
}
main();

Categories

Resources