Skip to content

Commit

Permalink
v014 release (#2)
Browse files Browse the repository at this point in the history
* FIx date response

* Add generate plugin settings.

* bump version

* Hide Plugin Settings from users.

* fix bug.
  • Loading branch information
redondi88 authored Nov 11, 2024
1 parent 947509d commit bf66695
Show file tree
Hide file tree
Showing 10 changed files with 99 additions and 23 deletions.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ add the following to your `config/plugin.ts`
config: {
beautifyDate:{
fields: [ 'date' ], // name of fields that will be changed
options: { // check JS toLocaleDateString options for details
year: 'numeric',
month: 'long',
day: 'numeric'
}
}
}
},
Expand All @@ -60,6 +65,11 @@ add the following to your `config/plugin.ts`

### Admin panel

- The following must be enabled so a user can generate files:
- Inside Role editor, find the pdf plugin and allow role to generate document.
- The users' role must have access to view content `template`.
- _By default super admins will be able to generate files_.

- Once the first template is created and assigned to a collection type, the admin can navigate to an entry and a PDF button should appear on the right side menu.
![strapi pdf creator](./examples/fillable_fields/screenshots/screenshot1.png)
Check [Examples](./examples/) for more details.
Expand Down Expand Up @@ -100,7 +110,6 @@ Enjoy 🎉

## TODO:

- Security: Allow other roles to generate documents
- Allow other fonts
- Beautify date fields.
- Settings function to validate template against schema.
Expand Down
32 changes: 27 additions & 5 deletions admin/src/components/GenerateFileButton.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import { Button, Typography, Flex } from "@strapi/design-system";
import { useFetchClient, useAuth } from '@strapi/strapi/admin';
import { useFetchClient, useAuth, isFetchError, useNotification } from '@strapi/strapi/admin';
import { Download } from '@strapi/icons';
import { useParams, useLocation } from 'react-router-dom';
import axios from 'axios';
Expand All @@ -19,6 +19,7 @@ const GenerateFileButton = () => {
});

const location = useLocation();
const { toggleNotification } = useNotification();
const client = useFetchClient();
const [isVisible, setIsVisible] = useState(false);
const [templates, setTemplates] = useState<TemplateType[]>([]);
Expand All @@ -39,12 +40,16 @@ const GenerateFileButton = () => {
data.results.forEach(item => {
if (location.pathname.includes(item.collectionName)) {
setIsVisible(true);
setTemplates(prevTemplates => [...prevTemplates, item]);
setTemplates(prevTemplates => [...prevTemplates, item]);
}
});
}
} catch (error) {
console.error('Error checking button visibility:', error);
} catch (err) {
if (isFetchError(err)) {
console.warn(': You do not have permission to view PDF Templates.');
} else {
console.error('An unknown error occurred:', err);
}
}
};

Expand Down Expand Up @@ -77,7 +82,24 @@ const GenerateFileButton = () => {
console.error('Expected a blob response, but got:', response);
}
} catch (error) {
console.error('There has been a problem with your axios operation:', error);
if (axios.isAxiosError(error)) {
if (error.response && error.response.status === 403) {
toggleNotification({
type: "danger",
title: "Error",
message: 'You do not have permission to generate PDF Templates.',
});

} else {
toggleNotification({
type: "danger",
title: "Error",
message: error.message,
});
}
} else {
console.error('An unknown error occurred:', error);
}
}
};

Expand Down
11 changes: 11 additions & 0 deletions admin/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { PLUGIN_ID } from "./pluginId";
export const PERMISSIONS = {
// This permission regards the main component (App) and is used to tell
// If the plugin link should be displayed in the menu
// And also if the plugin is accessible. This use case is found when a user types the url of the
// plugin directly in the browser
settings: [
{ action: `plugin::${PLUGIN_ID}.admin`, subject: null },

],
};
10 changes: 4 additions & 6 deletions admin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { prefixPluginTranslations } from './utils/prefixPluginTranslations';
import { PLUGIN_ID } from './pluginId';
import { Initializer } from './components/Initializer';
import GenerateFileButton from './components/GenerateFileButton';
import { PERMISSIONS } from './constants';

export default {
register(app: any) {

app.createSettingSection(
{
id: PLUGIN_ID,
Expand All @@ -21,9 +21,9 @@ export default {
to: PLUGIN_ID,
Component: () =>
import('./pages/Settings').then((mod) => ({
default: mod.SettingsPage,
default: mod.ProtectedSettingsPage,
})),
// permissions: PERMISSIONS.settings,
permissions: PERMISSIONS.settings,
},
]
);
Expand All @@ -34,14 +34,12 @@ export default {
isReady: false,
name: PLUGIN_ID,
});

},
bootstrap(app: any) {
app.getPlugin('content-manager').injectComponent('editView', 'right-links', {
name: 'PDF Creator',
Component: GenerateFileButton
Component: GenerateFileButton,
});

},

async registerTrads(app: any) {
Expand Down
15 changes: 8 additions & 7 deletions admin/src/pages/Settings.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useNotification } from '@strapi/strapi/admin';
import { Layouts, Page } from "@strapi/admin/strapi-admin";
import { Button, Tabs, Loader } from "@strapi/design-system";
import { Tabs, Loader } from "@strapi/design-system";
import { useState, useCallback, useEffect } from "react";
import { useFetchClient } from '@strapi/strapi/admin';
import { useTr } from '../hooks/useTr';
Expand All @@ -9,7 +9,14 @@ import TemplateTab from "./TemplateTab";
import SettingsTab from './SettingsTab';
import handleAPIError, { ToBeFixed } from '../utils/handleApiError';
import { SettingsType } from 'src/types';
// import { PERMISSIONS } from '../constants';


export const ProtectedSettingsPage = () => (
// <Page.Protect permissions={PERMISSIONS.settings}> // NEED TO FIX actual page rendering.
<SettingsPage />
// </Page.Protect>
);
const SettingsPage = () => {
const client = useFetchClient();
const [settings, setSettings] = useState<SettingsType | null>(null);
Expand Down Expand Up @@ -49,11 +56,6 @@ const SettingsPage = () => {
id="header"
title={translate("home.title")}
subtitle={translate("home.subtitle")}
// primaryAction={
// <Button onClick={() => toggleNotification({ type: 'success', message: 'Home clicked!' })}>
// {translate("home.button")}
// </Button>
// }
/>
<Layouts.Content>
{loading ? (
Expand Down Expand Up @@ -90,4 +92,3 @@ const SettingsPage = () => {
);
};

export { SettingsPage };
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"type": "git",
"directory": "."
},
"version": "0.1.3",
"version": "0.1.4",
"keywords": [
"strapi",
"plugin",
Expand Down
22 changes: 21 additions & 1 deletion server/src/bootstrap.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
import type { Core } from '@strapi/strapi';
import { PLUGIN_ID } from './pluginId';

const bootstrap = ({ strapi }: { strapi: Core.Strapi }) => {
const bootstrap = async ({ strapi }: { strapi: Core.Strapi }) => {
// bootstrap phase
await registerPermissionActions();
};
const registerPermissionActions = async () => {
const actions = [
{
section: 'plugins',
displayName: 'Generate PDF from templates',
uid: 'generate',
pluginName: PLUGIN_ID,
},
{
section: 'plugins',
displayName: 'Manage plugin Settings',
uid: 'admin',
pluginName: PLUGIN_ID,
}
];

await strapi.service('admin::permission').actionProvider.registerMany(actions);
};

export default bootstrap;
8 changes: 7 additions & 1 deletion server/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
export default {
default: {},
default: {
enabled: true,
beautifyDate: {
fields: [],
options: {}
},
},
validator() {},
};
10 changes: 9 additions & 1 deletion server/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,15 @@ export default [
path: '/create-pdf',
handler: 'pdfGenerator.create',
config: {
policies: [`plugin::${PLUGIN_ID}.isAdmin`]
policies: [
'admin::isAuthenticatedAdmin',
{
name: 'admin::hasPermissions',
config: {
actions: [`plugin::${PLUGIN_ID}.generate`],
},
},
],
},
},

Expand Down
1 change: 1 addition & 0 deletions server/src/services/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ async function createPageFromTemplate(
const dateFields = beautifyDate.fields;
if (dateFields.some((item) => item === name)) {
const date = new Date(Date.parse(data[name]));
return date.toLocaleDateString(undefined, beautifyDate.options);
}
}
return(data[name] || null)};
Expand Down

0 comments on commit bf66695

Please sign in to comment.