Files
bodyshop/client/src/utils/RenderTemplate.js
2021-01-22 15:30:29 -08:00

139 lines
4.1 KiB
JavaScript

import axios from "axios";
import gql from "graphql-tag";
import jsreport from "jsreport-browser-client-dist";
import { auth } from "../firebase/firebase.utils";
import { setEmailOptions } from "../redux/email/email.actions";
import { store } from "../redux/store";
import client from "../utils/GraphQLClient";
const server = process.env.REACT_APP_REPORTS_SERVER_URL;
jsreport.serverUrl = server;
export default async function RenderTemplate(
templateObject,
bodyshop,
renderAsHtml = false
) {
//Template Object
// {
// name: TemplateList().parts_order_confirmation.key,
// variables: {
// id: insertResult.data.insert_parts_orders.returning[0].id,
// },
// },
//Query assets that match the template name. Must be in format <<templateName>>.query
jsreport.headers["Authorization"] =
"Bearer " + (await auth.currentUser.getIdToken());
const jsReportQueries = await axios.get(
`${server}/odata/assets?$filter=name eq '${templateObject.name}.query'`
);
let templateQueryToExecute,
useShopSpecificTemplate = false;
if (jsReportQueries.data.value.length === 0) {
//We have no query to execute. Just render the template.
} else if (jsReportQueries.data.value.length === 1) {
//We're using the default template. Get the query and execute.
templateQueryToExecute = atob(jsReportQueries.data.value[0].content);
} else if (jsReportQueries.data.value.length === 2) {
//There's a custom template. Use that query instead and execute. We find it because it has a parent folder.
templateQueryToExecute = atob(
jsReportQueries.data.value.filter((v) => !!v.folder)[0].content
);
useShopSpecificTemplate = true;
} else {
//We have too many queries to choose from. Throw an error.
alert(
"There are too many queries to choose from. Please ensure there are no conflicting keys."
);
throw new Error(
"There are too many queries to choose from. Please ensure there are no conflicting keys."
);
}
const { data: contextData } = await client.query({
query: gql(templateQueryToExecute),
variables: { ...templateObject.variables },
fetchPolicy: "network-only",
});
let reportRequest = {
template: {
name: useShopSpecificTemplate
? `/${bodyshop.imexshopid}/${templateObject.name}`
: `/${templateObject.name}`,
...(renderAsHtml ? {} : { recipe: "chrome-pdf" }),
},
data: {
...contextData,
headerpath: `/${bodyshop.imexshopid}/header.html`,
bodyshop: bodyshop,
},
};
const render = await jsreport.renderAsync(reportRequest);
if (!renderAsHtml) {
render.download();
// var html =
// "<html>" +
// "<style>html,body {padding:0;margin:0;} iframe {width:100%;height:100%;border:0}</style>" +
// "<body>" +
// '<iframe type="application/pdf" src="' +
// render.toDataURI() +
// '"></iframe>' +
// "</body></html>";
// displayTemplateInWindowNoprint(html);
} else {
return new Promise((resolve, reject) => {
resolve(render.toString());
});
}
}
export const displayTemplateInWindow = (html) => {
try {
var newWin = window.open("", "_blank", "toolbar=0,location=0,menubar=0");
newWin.document.write(html);
setTimeout(function () {
newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();
}, 500);
} catch (error) {
console.log("Unable to write to new window.", error);
}
};
export const displayTemplateInWindowNoprint = (html) => {
try {
var newWin = window.open("", "_blank", "toolbar=0,location=0,menubar=0");
newWin.document.write(html);
setTimeout(function () {
newWin.document.close();
newWin.focus();
//newWin.print();
//newWin.close();
}, 500);
} catch (error) {
console.log("Unable to write to new window.", error);
}
};
export const GenerateDocument = async (template, messageOptions, sendType) => {
const bodyshop = store.getState().user.bodyshop;
if (sendType === "e") {
store.dispatch(
setEmailOptions({
messageOptions,
template,
})
);
} else {
await RenderTemplate(template, bodyshop);
}
};