Strapi email designer plugin reference template to record - email

I'm currently developing a multi-tenant API with Strapi and for one of the parts I use the Strapi email designer plugin because I want to send some emails but I want them to be custom designed for each tenant, the problem is that the plugin's table is not accessible in the content manager of Strapi so I can only hard code the template to a specific endpoint, is there a way to have the plugin table in the content manager or for it to be referenced to a content manager table something like:
(table)tenant->(field)templateId => (ref-table)plugin-email-designer->(ref-field)templateId
you know so I can switch and set dynamically from the Strapi panel and not with hard-coded endpoints

I've checked your issue briefly, and there is option you are going to like, but it involves using patch-package...
So, let's assume that you have strapi project created and you have added strapi-plugin-email-designer and you are using yarn v1.xx.xx:
yarn add patch-package postinstall-postinstall
Go to node_modules/strapi-plugin-email-designer/server/content-types/email-template/schema.json
change following fileds:
{
...
"pluginOptions": {
"content-manager": {
"visible": true
},
"content-type-builder": {
"visible": true
}
},
...
}
now run
yarn patch-package strapi-plugin-email-designer
now open your projects package.json and add to scripts:
{
"scripts": {
...
"postinstall": "patch-package"
}
}
run
yarn build
yarn develop
head to admin ui, you should see new Collection:
so now you can do that:
Sending Email
Let's assume you added a relation has one called email_template to your model.
Next we need to add custom route, so in /src/api/tenant/routes/ create file called routes.js
/src/api/tenant/routes/routes.js
module.exports = {
routes: [
{
method: 'POST',
path: `/tenants/:id/send`,
handler: `tenant.send`
}
]
}
now, we need to add handler to controller:
/src/api/tenant/controllers/tenant.js
"use strict";
/**
* tenant controller
*/
const { createCoreController } = require("#strapi/strapi").factories;
module.exports = createCoreController("api::tenant.tenant", ({ strapi }) => ({
async send(ctx) {
const { id } = ctx.params;
const { data } = ctx.request.body;
// notice, if you need extra validation you add it here
// if (!data) return ctx.badRequest("no data was provided");
const { to, subject } = data;
const { email_template, ...tenant } = await strapi.db
.query("api::tenant.tenant")
// if you have extra relations it's better to populate them directly here
.findOne({ where: { id }, populate: ["email_template"] });
console.log(email_template);
try {
await strapi
.plugin("email-designer")
.service("email")
.sendTemplatedEmail(
{
to,
//from, < should be set in /config/plugins.js email.settings.defaultFrom
//replayTo < should be set in /config/plugins.js email.settings.defaultReplyTo
},
{
templateReferenceId: email_template.templateReferenceId,
subject,
},
{
...tenant,
// this equals to apply all the data you have in tenant
// this may need to be aligned between your tenant and template
}
);
return { success: `Message sent to ${to}` };
} catch (e) {
strapi.log.debug("📺: ", e);
return ctx.badRequest(null, e);
}
},
}));
don't forget to enable access to /api/tenants/:id/send in admin panel, Settings - Roles
POST http://localhost:1337/api/tenants/1/send
{
"data": {
"to" : "email#example.com",
"subject": "Hello World"
}
}
response:
{
"success": "Message sent to email#example.com"
}
pls note, there is no template validation, e.g. if you give it a wrong template it would not be happy

Related

How to create Strapi entries in Nextjs with a Form (Apollo and GraphQL)

I am trying to create new Strapi entries in Nextjs by submitting a form using Apollo client and GraphQL.
I tried a lot of diffrent things with my limited knowledge and was not able to make it work. While researching the topic I realized that most people are using the "useMutation" hook. It never worked though (also when using "useQuery" for queries). So I used a similar approach as for queries because they work.
queries: client.query | mutations: client.mutate
What I have tried:
// GraphQL that works in the Strapi playground
const TEST1 = gql`
mutation CreateMitgliedanmeldung($name: String!) {
createMitgliedanmeldung(data: { name: $name }) {
data {
attributes {
name
}
}
}
}`;
export default function MitgliedWerden() {
const formState = {
name: ''
};
function updateFormState(key, value) {
formState[key] = value;
}
function submit2() {
console.log(formState.name);
client.mutate({
variables: { name: formState.name },
mutation: TEST1,
})
}
return (
<div>
<form onSubmit={submit2()}>
<input onChange={e => updateFormState('name', e.target.value)} id="name"></input>
<button type="submit">Mitglied werden 1</button>
</form>
</div>
)
}
The code above creates new entries but there are multiple problems:
Variable "name" is not present in the new entry but can be console logged inside "updateFormState" function
(same mutation works fine inside graphql playground)
Form is submitted when page is reloaded/loaded
When submitting the page reloads (this is fine if the other problems are gone)
To fix the reload problem I added the following and called it onSubmit.
// calling this onSubmit instead of submit2 function
const newsubmit = (e) => {
e.preventDefault();
submit2()
};
Now submitting or reloading the page does not create a new entry but I get the console.log with the correct value. It seems like the "client.mutate" is broken or can't work in those conditions.
I was not able to find a lot about the ".mutate" function from apollo and the more often used "useMutation" hook did not work at all for me. Using "client.query" works fine.
Apollo Client:
import { ApolloClient, InMemoryCache } from "#apollo/client"
const defaultOptions = {
query: {
fetchPolicy: "no-cache",
},
}
const client = new ApolloClient({
uri: process.env.STRAPI_GRAPHQL_URL,
headers: { "Authorization": process.env.STRAPI_TOKEN },
cache: new InMemoryCache(),
defaultOptions,
});
export default client
Dependencies:
"#apollo/client": "^3.6.9",
"#apollo/react-hooks": "^4.0.0",
"graphql": "^16.5.0",
"graphql-request": "^4.3.0",
"next": "12.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",

How can i read external json file in Azure-devops-extension development?

I am trying to read json file inside "index.html" file of the project, since for azure devops extension we already have require.js library, hence wanted to use the same capability of it to import "config.json" file inside "index.html" file.
basic file structure:
|-index.html
|-static  |-icon.png
|    |-config.json
|-vss-extension.json
my index.html file look somewhat like this :
init block
VSS.init({
explicitNotifyLoaded: true,
usePlatformScripts: true,
setupModuleLoader: true,
moduleLoaderConfig: {
paths: {
"Static": "static"
}
}
});
require block
VSS.require(
["TFS/WorkItemTracking/Services", "Static/config"],
function (_WorkItemServices, ConfigJson) {
VSS.ready(function(){
VSS.register(VSS.getContribution().id, function () {
return {
// Called when the active work item is modified
onFieldChanged: function (args) {
console.log(
"inside onfield : " +
JSON.stringify(ConfigJson)
);
}
....
};
});
VSS.notifyLoadSucceeded();
})
});
My vss-extension.json file :
File block
"files": [
{
"path": "static/config.json",
"addressable": true,
"contentType": "application/json"
},
....
]
I am always getting require.js Script error: https://requirejs.org/docs/errors.html#scripterror
Took reference from:
https://github.com/ALM-Rangers/Show-Area-Path-Dependencies-Extension/blob/master/src/VSTS.DependencyTracker/vss-extension.json for vss-extension file.
https://github.com/ALM-Rangers/Show-Area-Path-Dependencies-Extension/blob/master/src/VSTS.DependencyTracker/index.html for index.html
I am afraid that you couldn't directly get the content of the json file.
But you could try to use the HTTP request to get the content.
Please refer to the following sample:
onFieldChanged: function (args) {
var request = new XMLHttpRequest();
request.open('GET', 'config.json', true);
request.send(null);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader('Content-Type');
console.log( "inside onfield : " + JSON.stringify(request.responseText));
}
}
Check out these two tickets for details.
Loading a JSON file in a VSTS extension
read local JSON file into variable
Is VSS using unmodified RequireJS? If yes, then you can use JSON plugin, which will help:
https://github.com/millermedeiros/requirejs-plugins
Using it is pretty simple, you just have to add a prefix json! when specifying a json file as a dependency:
VSS.require(
["TFS/WorkItemTracking/Services", "json!Static/config"],
function (_WorkItemServices, ConfigJson) {
VSS.ready(function(){
VSS.register(VSS.getContribution().id, function () {
return {
// Called when the active work item is modified
onFieldChanged: function (args) {
console.log(
"inside onfield : " +
JSON.stringify(ConfigJson)
);
}
....
};
});
VSS.notifyLoadSucceeded();
})
});

Nuxt.js - Implementing a component using Plugin

I would like to implement a custom Toaster component into my NuxtJs application by this method this.$toast.show({}) What is the best way of approaching this? Sadly I can't find any documentation on this.
Sorry, I arrive one year late...
I had the same proplem. Here is my code:
The index of my plugin (index.js ; Nofification.vue is a classical Vue component):
import Notifications from './Notifications.vue'
const NotificationStore = {
state: [], // here the notifications will be added
settings: {
overlap: false,
horizontalAlign: 'center',
type: 'info',
timeout: 5000,
...
},
setOptions(options) {
this.settings = Object.assign(this.settings, options)
},
removeNotification(timestamp) {
...
},
addNotification(notification) {
...
},
notify(notification) {
...
},
}
const NotificationsPlugin = {
install(Vue, options) {
const app = new Vue({
data: {
notificationStore: NotificationStore,
},
methods: {
notify(notification) {
this.notificationStore.notify(notification)
},
},
})
Vue.prototype.$notify = app.notify
Vue.notify = app.notify
Vue.prototype.$notifications = app.notificationStore
Vue.component('Notifications', Notifications)
if (options) {
NotificationStore.setOptions(options)
}
},
}
export default NotificationsPlugin
Here I call my plugin and inject it in Nuxt:
import Notifications from '~/components/NotificationPlugin'
Vue.use(Notifications)
export default (context, inject) => {
inject('notify', Vue.notify)
}
In my case, I use it in another plugin (nuxtjs axios).
import NOTIFICATIONS from '~/constants/notifications'
export default function ({ error, $axios, app }) {
// Using few axios helpers (https://axios.nuxtjs.org/helpers):
$axios.onError((axiosError) => {
// eslint-disable-next-line no-console
console.log('Axios: An error occured! ', axiosError, axiosError.response)
if (process.server) {
...
} else {
app.$notify({
message: 'Mon message',
timeout: NOTIFICATIONS.DEFAULT_TIMEOUT,
icon: 'tim-icons icon-spaceship',
horizontalAlign: NOTIFICATIONS.DEFAULT_ALIGN_HORIZONTAL,
verticalAlign: NOTIFICATIONS.DEFAULT_ALIGN_VERTICAL,
type: 'success',
})
console.log('PRINT ERROR')
return Promise.resolve(true)
}
})
}
As I injected it, I think I could have done export default function ({ error, $axios, app, $notify }) { and directly use $notify (and not the app.$notify).
If you want a better understanding, feel free to consult #nuxtjs/toast which works the same way:
https://github.com/nuxt-community/community-modules/blob/master/packages/toast/plugin.js
And the matching Vue component:
https://github.com/shakee93/vue-toasted/blob/master/src/index.js
Good luck, this is not easy stuff. I'll try to add something easier to understand in the docs!
you can find in this package https://www.npmjs.com/package/vue-toasted
installation
npm install vue-toasted --save
make a file as name toast.js in plugin folder
toast.js
import Vue from 'vue';
import Toasted from 'vue-toasted';
Vue.use(Toasted)
add this plugin to nuxt.config.js
plugins: [
{ src: '~/plugins/toast', ssr: false },
],
now you able to use in your methods like this
this.$toasted.show('hello i am your toast')
hope this helps

Google Cloud Print from Web

I wrote a script that prints some test pages from url on Web-site,
and every time I press a print button, a dialog frame for choosing printer appears . But I want to avoid this because my account synchronized with printer.
window.onload = function() {
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(
cloudprint.Gadget.createDefaultPrintButton("print_button_container")); // div id to contain the button
gadget.setPrintDocument("url", "Test Page", "https://www.google.com/landing/cloudprint/testpage.pdf");
}
You could use oath and an html button rather than a gadget to accomplish this. This requires using the google developer console to get oauth permissions.
Then you need to authorize the cloud print service.
The following set of functions are specifically good for use in Google Apps Scripts, but can be adapted. The first thing to do is Log a url link that you can go to in order to Authorize the cloud print service.
function showURL() {
var cpService = getCloudPrintService();
if (!cpService.hasAccess()) {
Logger.log(cpService.getAuthorizationUrl());
}
}
In the following component of this set of functions, make sure to replace the client Id and Secret.
function getCloudPrintService() {
return OAuth2.createService('print')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId('**YOUR CLIENT ID FROM GOOGLE DEVELOPER CONSOLE**')
.setClientSecret('**YOUR CLIENT SECRET**')
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('https://www.googleapis.com/auth/cloudprint')
.setParam('login_hint', Session.getActiveUser().getEmail())
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var isAuthorized = getCloudPrintService().handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('You can now use Google Cloud Print from Apps Script.');
} else {
return HtmlService.createHtmlOutput('Cloud Print Error: Access Denied');
}
}
Next, get the ID of the Cloud Print Printer that you want to use. This can be obtained in the settings menu of Chrome. Settings --> Show Advanced Settings --> Under Cloud Print " Manage" --> Select the Printer that you want to use "Manage" -->Advanced Details
To initiate cloud print, you need to add the details to a ticket:
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR",
vendor_id: "Color"
},
duplex: {
type: "LONG_EDGE"
},
copies: {copies: 1},
media_size: {
width_microns: 215900,
height_microns:279400
},
page_orientation: {
type: "PORTRAIT"
},
margins: {
top_microns:0,
bottom_microns:0,
left_microns:0,
right_microns:0
},
page_range: {
interval:
[{start:1,
end:????}]
}
}
};
There are many options that you can add to the ticket. See documentation
Finally, you need to initiate the Cloud Print Service. Here is where you get to define the specific printer that you want.
var payload = {
"printerid" : '**COPY YOUR PRINTER ID HERE**',
"title" : "Prep Print",
"content" : PUT YOUR CONTENT HERE...(e.g. If you do all of this using Google Apps Script...HtmlService.createHtmlOutput(VARIABLE).getAs('application/pdf')),
"contentType": 'text/html',
"ticket" : JSON.stringify(ticket)
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);}
var outcome = response.message;
}

Using Grunt to Mock Endpoints

I'm using Yeoman, Grunt, and Bower, to construct a platform for building a frontend independently of a a backend. The idea would be that all of my (AngularJS) controller, services, factories, etc live in this project, and get injected afterwards into my serverside codebase based off the result of grunt build.
My question is:
How can I mock endpoints so that the Grunt server responds to the same endpoints as my (Rails) App will?
At the moment I am using:
angular.module('myApp', ['ngResource'])
.run(['$rootScope', function ($rootScope) {
$rootScope.testState = 'test';
}]);
And then in each of my individual services:
mockJSON = {'foo': 'myMockJSON'}
And on every method:
if($rootScope.testState == 'test'){
return mockJSON;
}
else {
real service logic with $q/$http goes here
}
Then after grunt build, testState = 'test' gets removed.
This is clearly a relatively janky architecture. How can I avoid it? How can I have Grunt respond to the same endpoints as my app (some of which have dynamic params) apply some logic (if necessary), and serve out a json file (possibly dependent on path params)?
I've fixed this issue by using express to write a server that responds with static json.
First I created a directory in my project called 'api'. Within that directory I have the following files:
package.json:
{
"name": "mockAPI",
"version": "0.0.0",
"dependencies": {
"express": "~3.3.4"
}
}
Then I run npm install in this directory.
index.js:
module.exports = require('./lib/server');
lib/server.js:
express = require('express');
var app = express();
app.get('/my/endpoint', function(req, res){
res.json({'foo': 'myMockJSON'});
});
module.exports = app
and finally in my global Gruntfile.js:
connect: {
options: {
port: 9000,
hostname: 'localhost',
},
livereload: {
options: {
middleware: function (connect, options) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app),
require('./api')
];
}
}
},
Then the services make the requests, and the express server serves the correct JSON.
After grunt build, the express server is simply replaced by a rails server.
As of grunt-contrib-connect v.0.7.0 you can also just add your custom middleware to the existing middleware stack without having to manually rebuild the existing middleware stack.
livereload: {
options: {
open: true,
base: [
'.tmp',
'<%= config.app %>'
],
middleware: function(connect, options, middlewares) {
// inject a custom middleware into the array of default middlewares
middlewares.push(function(req, res, next) {
if (req.url !== '/my/endpoint') {
return next();
}
res.writeHead(200, {'Content-Type': 'application/json' });
res.end("{'foo': 'myMockJSON'}");
});
return middlewares;
}
}
},
See https://github.com/gruntjs/grunt-contrib-connect#middleware for the official documentation.
Alternatively you can use the grunt-connect-proxy to proxy everything that is missing in your test server to an actual backend.
It's quite easy to install, just one thing to remember when adding proxy to your livereload connect middleware is to add it last, like this:
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app),
proxySnippet
];
}
grunt-connect-prism is similar to the Ruby project VCR. It provides an easy way for front end developers to record HTTP responses returned by their API (or some other remote source) and replay them later. It's basically an HTTP cache, but for developers working on a Single Page Application (SPA). You can also generate stubs for API calls that don't exist, and populate them the way you want.
It's useful for mocking complex & high latency API calls during development. It's also useful when writing e2e tests for your SPA only, removing the server from the equation. This results in much faster execution of your e2e test suite.
Prism works by adding a custom connect middleware to the connect server provided by the grunt-contrib-connect plugin. While in 'record' mode it will generate a file per response on the filesystem with content like the following:
{
"requestUrl": "/api/ponies",
"contentType": "application/json",
"statusCode": 200,
"data": {
"text": "my little ponies"
}
}
DISCLAIMER: I'm the author of this project.
You can use Apache proxy and connect your REST server with gruntjs.
Apache would do this:
proxy / -> gruntjs
proxy /service -> REST server
you would use your application hitting Apache and angular.js application would think that is talking with itself so no cross domain problem.
Here is a great tutorial on how to set this up:
http://alfrescoblog.com/2014/06/14/angular-js-activiti-webapp-with-activiti-rest/
Just my alternative way that based on Abraham P's answer. It does not need to install express within 'api' folder. I can separate the mock services for certain files. For example, my 'api' folder contains 3 files:
api\
index.js // assign all the "modules" and then simply require that.
user.js // all mocking for user
product.js // all mocking for product
file user.js
var user = function(req, res, next) {
if (req.method === 'POST' && req.url.indexOf('/user') === 0) {
res.end(
JSON.stringify({
'id' : '5463c277-87c4-4f1d-8f95-7d895304de12',
'role' : 'admin'
})
);
}
else {
next();
}
}
module.exports = user;
file product.js
var product = function(req, res, next) {
if (req.method === 'POST' && req.url.indexOf('/product') === 0) {
res.end(
JSON.stringify({
'id' : '5463c277-87c4-4f1d-8f95-7d895304de12',
'name' : 'test',
'category': 'test'
})
);
}
else {
next();
}
}
module.exports = product;
index.js just assigns all the "modules" and we simply require that.
module.exports = {
product: require('./product.js'),
user: require('./user.js')
};
My Gruntfile.js file
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app),
require('./api').user,
require('./api').product,
];
}
}
}