Skip to content

Commit 40707e8

Browse files
authored
Merge pull request #746 from devforth/feature/AdminForth/2056/bulk-ai-flow-needs-something-l
feat: injection isVisible AdminForth/2056/bulk-ai-flow-needs-something-l
2 parents 049b614 + f23c2cd commit 40707e8

5 files changed

Lines changed: 141 additions & 23 deletions

File tree

‎adminforth/modules/restApi.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ import { ActionCheckSource, AdminForthActionFront, AdminForthConfigMenuItem, Adm
3232
AdminUser, AllowedActionsEnum,
3333
AnnouncementBadgeResponse,
3434
GetConfigResponse,
35-
ShowInResolved} from "../types/Common.js";
35+
ShowInResolved,
36+
type AdminForthPageInjectionDeclaration } from "../types/Common.js";
3637
import { filtersTools } from "../modules/filtersTools.js";
3738
import { normalizeColumnValue } from './columnValueNormalizer.js';
3839
import { isEmptyColumnValue, runColumnValidators } from './columnValueValidator.js';
@@ -52,6 +53,29 @@ function stripResourceColumnFrontendMeta(column: Record<string, any>) {
5253
return sanitizedColumn;
5354
}
5455

56+
/**
57+
* Drops the page injections whose isVisible returns false for the user, and the isVisible callbacks themselves.
58+
*/
59+
async function getVisiblePageInjections(adminUser: AdminUser, resource: AdminForthResource) {
60+
return Object.fromEntries(await Promise.all(
61+
Object.entries(resource.options.pageInjections ?? {}).map(async ([page, slots]) => [
62+
page,
63+
Object.fromEntries(await Promise.all(
64+
Object.entries(slots as Record<string, AdminForthPageInjectionDeclaration[]>).map(async ([slot, injections]) => {
65+
const visible = await Promise.all(injections.map(async (injection) => {
66+
if (typeof injection === 'string' || !injection.isVisible) {
67+
return injection;
68+
}
69+
const { isVisible, ...rest } = injection;
70+
return await isVisible({ adminUser, resource }) ? rest : null;
71+
}));
72+
return [slot, visible.filter(Boolean)];
73+
})
74+
)),
75+
])
76+
));
77+
}
78+
5579
const SIMPLE_FILTER_OPERATORS = Object.values(AdminForthFilterOperators).filter((operator) => {
5680
return operator !== AdminForthFilterOperators.AND && operator !== AdminForthFilterOperators.OR;
5781
});
@@ -1239,6 +1263,7 @@ export default class AdminForthRestAPI implements IAdminForthRestAPI {
12391263
),
12401264
options: {
12411265
...resource.options,
1266+
pageInjections: await getVisiblePageInjections(adminUser, resource),
12421267
listPageSizeOptions: typeof resource.options.listPageSizeOptions === 'function'
12431268
? await resource.options.listPageSizeOptions({ adminUser, adminforth: this.adminforth })
12441269
: resource.options.listPageSizeOptions,

‎adminforth/types/Common.ts‎

Lines changed: 42 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,27 @@ export { type AdminForthActionInput } from './Back.js'
346346

347347
export type AdminForthComponentDeclaration = AdminForthComponentDeclarationFull | string;
348348

349+
export interface AdminForthPageInjectionDeclarationFull extends AdminForthComponentDeclarationFull {
350+
/**
351+
* Called on the backend every time the resource is loaded for the user. When it returns false,
352+
* the injection is not sent to the frontend, so the component is not rendered for this user.
353+
* Use it to hide a component from users who are not allowed to use it, and check the same rule
354+
* in the backend endpoints the component calls.
355+
*
356+
* Example:
357+
*
358+
* ```ts
359+
* threeDotsDropdownItems: [{
360+
* file: '@@/GenerateReport.vue',
361+
* isVisible: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
362+
* }],
363+
* ```
364+
*/
365+
isVisible?: (params: { adminUser: AdminUser, resource: AdminForthResource }) => boolean | Promise<boolean>,
366+
}
367+
368+
export type AdminForthPageInjectionDeclaration = AdminForthPageInjectionDeclarationFull | string;
369+
349370
export type FieldGroup = {
350371
groupName: string;
351372
columns: string[];
@@ -587,15 +608,15 @@ export interface AdminForthResourceInputCommon {
587608
* Component accepts next props: [resource, adminUser, meta]
588609
*/
589610
list?: {
590-
beforeBreadcrumbs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
591-
afterBreadcrumbs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
592-
beforeActionButtons?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
593-
bottom?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
594-
threeDotsDropdownItems?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
595-
customActionIcons?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
596-
customActionIconsThreeDotsMenuItems?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
597-
tableBodyStart?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
598-
tableRowReplace?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
611+
beforeBreadcrumbs?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
612+
afterBreadcrumbs?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
613+
beforeActionButtons?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
614+
bottom?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
615+
threeDotsDropdownItems?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
616+
customActionIcons?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
617+
customActionIconsThreeDotsMenuItems?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
618+
tableBodyStart?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
619+
tableRowReplace?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
599620
},
600621

601622
/**
@@ -604,10 +625,10 @@ export interface AdminForthResourceInputCommon {
604625
* Component accepts next props: [record, resource, adminUser, meta]
605626
*/
606627
show?: {
607-
beforeBreadcrumbs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
608-
afterBreadcrumbs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
609-
bottom?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
610-
threeDotsDropdownItems?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
628+
beforeBreadcrumbs?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
629+
afterBreadcrumbs?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
630+
bottom?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
631+
threeDotsDropdownItems?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
611632
},
612633

613634
/**
@@ -616,10 +637,10 @@ export interface AdminForthResourceInputCommon {
616637
* Component accepts next props: [record, resource, adminUser, meta]
617638
*/
618639
edit?: {
619-
beforeBreadcrumbs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
620-
afterBreadcrumbs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
621-
bottom?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
622-
threeDotsDropdownItems?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
640+
beforeBreadcrumbs?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
641+
afterBreadcrumbs?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
642+
bottom?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
643+
threeDotsDropdownItems?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
623644
},
624645

625646
/**
@@ -628,10 +649,10 @@ export interface AdminForthResourceInputCommon {
628649
* Component accepts next props: [resource, adminUser, meta]
629650
*/
630651
create?: {
631-
beforeBreadcrumbs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
632-
afterBreadcrumbs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
633-
bottom?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
634-
threeDotsDropdownItems?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>,
652+
beforeBreadcrumbs?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
653+
afterBreadcrumbs?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
654+
bottom?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
655+
threeDotsDropdownItems?: AdminForthPageInjectionDeclaration | Array<AdminForthPageInjectionDeclaration>,
635656
},
636657
}
637658
},

‎dev-demo/resources/cars_resources/carsResourseTemplate.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ export default function carsResourseTemplate(resourceId: string, dataSource: Car
225225
`${dataSource}/car_images/cars/${originalFilename}_${Date.now()}.${originalExtension}`,
226226
preview: {
227227
maxShowWidth: "300px",
228+
maxListWidth: "100px",
228229
},
229230
}),
230231
new UploadPlugin({
@@ -247,6 +248,7 @@ export default function carsResourseTemplate(resourceId: string, dataSource: Car
247248
`${dataSource}/car_images/cars_promo_images/${originalFilename}_${Date.now()}.${originalExtension}`,
248249
preview: {
249250
maxShowWidth: "300px",
251+
maxListWidth: "100px",
250252
},
251253
}),
252254
new MarkdownPlugin({
@@ -364,6 +366,7 @@ export default function carsResourseTemplate(resourceId: string, dataSource: Car
364366
`${dataSource}/car_images/cars_promo_images_generated/${originalFilename}_${Date.now()}.${originalExtension}`,
365367
preview: {
366368
maxShowWidth: "300px",
369+
maxListWidth: "100px",
367370
previewUrl: ({filePath}) => `https://tmpbucket-adminforth.s3.eu-central-1.amazonaws.com/${filePath}`,
368371
},
369372
generation: {
@@ -394,6 +397,9 @@ export default function carsResourseTemplate(resourceId: string, dataSource: Car
394397
}),
395398
new BulkAiFlowPlugin({
396399
actionName: 'Generate description and Price',
400+
allowedActions: {
401+
generate: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
402+
},
397403
askConfirmationBeforeGenerating: true,
398404
textCompleteAdapter: new CompletionAdapterOpenAIResponses({
399405
openAiApiKey: process.env.OPENAI_API_KEY as string,
@@ -414,6 +420,9 @@ export default function carsResourseTemplate(resourceId: string, dataSource: Car
414420
}),
415421
new BulkAiFlowPlugin({
416422
actionName: 'Analyze image',
423+
allowedActions: {
424+
generate: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
425+
},
417426
askConfirmationBeforeGenerating: true,
418427
visionAdapter: new AdminForthImageVisionAdapterOpenAi({
419428
openAiApiKey: process.env.OPENAI_API_KEY as string,
@@ -438,6 +447,9 @@ export default function carsResourseTemplate(resourceId: string, dataSource: Car
438447
}),
439448
new BulkAiFlowPlugin({
440449
actionName: 'Generate promo image',
450+
allowedActions: {
451+
generate: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
452+
},
441453
askConfirmationBeforeGenerating: true,
442454
imageGenerationAdapter: new ImageGenerationAdapterOpenAI({
443455
openAiApiKey: process.env.OPENAI_API_KEY as string,

‎documentation/docs/tutorial/03-Customization/08-pageInjections.md‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,31 @@ const term = ref('');
824824
</script>
825825
```
826826
827-
## List table custom
827+
## Showing injection only to some users
828+
829+
Any resource page injection can have an `isVisible` callback. It is called on the backend every time the resource is loaded, and when it returns `false` the injection is not sent to the frontend, so the user does not see it:
830+
831+
```ts title="/apartments.ts"
832+
{
833+
resourceId: 'aparts',
834+
...
835+
options: {
836+
pageInjections: {
837+
list: {
838+
threeDotsDropdownItems: [
839+
{
840+
file: '@@/GenerateReport.vue',
841+
//diff-add
842+
isVisible: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
843+
},
844+
],
845+
},
846+
},
847+
},
848+
}
849+
```
850+
851+
`isVisible` only hides the component. If the component calls your own endpoint, check the same rule in the endpoint too.
828852
829853
## Global Injections
830854

‎documentation/docs/tutorial/09-Plugins/17-bulk-ai-flow.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,12 @@ export const admin = new AdminForth({
136136
new BulkAiFlowPlugin({
137137
//diff-add
138138
actionName: 'Analyze',
139+
//diff-add
140+
allowedActions: {
141+
//diff-add
142+
generate: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
143+
//diff-add
144+
},
139145
//diff-add
140146
attachFiles: async ({ record }: { record: any }) => {
141147
//diff-add
@@ -197,6 +203,27 @@ export const admin = new AdminForth({
197203
![alt text](Bulk-vision-3.png)
198204
199205
206+
## Who can run generation
207+
208+
Generation calls a paid AI provider, so it is disabled for all users by default. Set `allowedActions.generate` to choose who can run it. Users who are not allowed don't see the action, and their generation requests are rejected:
209+
210+
```ts
211+
new BulkAiFlowPlugin({
212+
actionName: 'Analyze',
213+
//diff-add
214+
allowedActions: {
215+
//diff-add
216+
generate: ({ adminUser }) => ['superadmin', 'editor'].includes(adminUser.dbUser.role),
217+
//diff-add
218+
},
219+
...
220+
}),
221+
```
222+
223+
`generate: true` allows generation to every user who can see the resource. If `allowedActions.generate` is not set, the plugin logs a warning on startup.
224+
225+
Saving the generated values also needs the `edit` permission on the resource and, if set, `isAllowedToSave`.
226+
200227
## Text-to-Text Processing
201228
This is the most basic plugin usage. You can connect any text completion adapter to fill one or several string/number/boolean fields from other fields.
202229
@@ -209,6 +236,9 @@ import CompletionAdapterOpenAIResponses from '@adminforth/completion-adapter-ope
209236
// Add to your resource plugins array
210237
new BulkAiFlowPlugin({
211238
actionName: 'Translate surnames',
239+
allowedActions: {
240+
generate: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
241+
},
212242
textCompleteAdapter: new CompletionAdapterOpenAIResponses({
213243
openAiApiKey: process.env.OPENAI_API_KEY as string,
214244
model: 'gpt-5-nano',
@@ -233,6 +263,9 @@ import AdminForthImageVisionAdapterOpenAi from '@adminforth/image-vision-adapter
233263
// Add to your resource plugins array
234264
new BulkAiFlowPlugin({
235265
actionName: 'Guess age',
266+
allowedActions: {
267+
generate: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
268+
},
236269
visionAdapter: new AdminForthImageVisionAdapterOpenAi({
237270
openAiApiKey: process.env.OPENAI_API_KEY as string,
238271
model: 'gpt-6-luna',
@@ -260,6 +293,9 @@ import ImageGenerationAdapterOpenAI from '@adminforth/image-generation-adapter-o
260293
// Add to your resource plugins array
261294
new BulkAiFlowPlugin({
262295
actionName: 'Generate cartoon avatars',
296+
allowedActions: {
297+
generate: ({ adminUser }) => adminUser.dbUser.role === 'superadmin',
298+
},
263299
imageGenerationAdapter: new ImageGenerationAdapterOpenAI({
264300
openAiApiKey: process.env.OPENAI_API_KEY as string,
265301
model: 'gpt-image-1.5',

0 commit comments

Comments
 (0)