-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
222 lines (195 loc) · 7.99 KB
/
Copy pathindex.ts
File metadata and controls
222 lines (195 loc) · 7.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import type {
AdminForthResource,
IAdminForth,
IHttpServer,
} from "adminforth";
import clone from 'clone';
import { AdminForthPlugin, AdminForthResourcePages, suggestIfTypo } from "adminforth";
import { PluginOptions } from "./types.js";
import { interpretResource, ActionCheckSource } from "adminforth";
import { z } from "zod";
const startBulkActionBodySchema = z.object({
resourceId: z.string(),
actionId: z.union([z.string(), z.number()]),
recordIds: z.array(z.union([z.string(), z.number()])),
}).strict();
const getDefaultFiltersBodySchema = z.object({
record: z.record(z.string(), z.any()).nullish(),
}).strict();
export default class ForeignInlineListPlugin extends AdminForthPlugin {
foreignResource: AdminForthResource;
options: PluginOptions;
adminforth: IAdminForth;
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
}
instanceUniqueRepresentation(pluginOptions: any) : string {
return `${pluginOptions.foreignResourceId}`;
}
setupEndpoints(server: IHttpServer) {
process.env.HEAVY_DEBUG && console.log(`🪲 ForeignInlineListPlugin.setupEndpoints, registering: '/plugin/${this.pluginInstanceId}/get_resource'`);
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get_resource`,
handler: async ({ body, adminUser }) => {
const resource = this.adminforth.config.resources.find((res) => this.options.foreignResourceId === res.resourceId);
if (!resource) {
return { error: `Resource ${this.options.foreignResourceId} not found` };
}
// exclude "plugins" key
const resourceCopy = clone({ ...resource, plugins: undefined });
if (this.options.modifyTableResourceConfig) {
this.options.modifyTableResourceConfig(resourceCopy);
}
const { allowedActions } = await interpretResource(adminUser, resourceCopy, {}, ActionCheckSource.DisplayButtons, this.adminforth);
return {
resource: {
...resourceCopy,
options: {
...resourceCopy.options,
allowedActions,
},
}
};
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/start_bulk_action`,
request_schema: startBulkActionBodySchema,
handler: async ({ body, adminUser, tr }) => {
const data = body as z.infer<typeof startBulkActionBodySchema>;
const { resourceId, actionId, recordIds } = data;
const resource = this.adminforth.config.resources.find((res) => res.resourceId == resourceId);
if (!resource) {
return { error: await tr(`Resource {resourceId} not found`, 'errors', { resourceId }) };
}
const resourceCopy = clone({ ...resource, plugins: undefined });
if (this.options.modifyTableResourceConfig) {
this.options.modifyTableResourceConfig(resourceCopy);
}
const { allowedActions } = await interpretResource(
adminUser,
resourceCopy,
{ requestBody: body },
ActionCheckSource.BulkActionRequest,
this.adminforth
);
const action = resourceCopy.options.bulkActions?.find((act) => act.id == actionId);
if (!action) {
return { error: await tr(`Action {actionId} not found`, 'errors', { actionId }) };
}
if (action.allowed) {
const execAllowed = await action.allowed({ adminUser, resourceCopy, selectedIds: recordIds, allowedActions });
if (!execAllowed) {
return { error: await tr(`Action "{actionId}" not allowed`, 'errors', { actionId: action.label }) };
}
}
const response = await action.action({selectedIds: recordIds, adminUser, resourceCopy, tr});
return {
actionId,
recordIds,
resourceId,
...response
}
}
})
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get_default_filters`,
request_schema: getDefaultFiltersBodySchema,
handler: async ({ body }) => {
if (!this.options.defaultFilters) {
return { error: 'No default filters function defined', ok: false };
}
const data = body as z.infer<typeof getDefaultFiltersBodySchema>;
const record = data.record;
if (!record) {
return { error: 'No record provided in request body', ok: false };
}
const filters = this.options.defaultFilters(record);
if (!Array.isArray(filters)) {
throw new Error('defauiltFilters must return an array of FilterParams');
}
return {ok: true, filters};
}
})
}
async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);
this.adminforth = adminforth;
// get resource with foreignResourceId
this.foreignResource = adminforth.config.resources.find((resource) => resource.resourceId === this.options.foreignResourceId);
if (!this.foreignResource) {
const similar = suggestIfTypo(adminforth.config.resources.map((res) => res.resourceId), this.options.foreignResourceId);
throw new Error(`ForeignInlineListPlugin: Resource with ID "${this.options.foreignResourceId}" not found. ${similar ? `Did you mean "${similar}"?` : ''}`);
}
const defaultSort = this.foreignResource.options?.defaultSort;
const newColumn = {
name: `foreignInlineList_${this.foreignResource.resourceId}`,
label: 'Foreign Inline List',
virtual: true,
showIn: {
show: true,
list: false,
edit: false,
create: false,
filter: false,
},
components: {
showRow: {
file: this.componentPath('InlineList.vue'),
meta: {
defaultFiltersOn: this.options.defaultFilters ? true : false,
...this.options,
pluginInstanceId: this.pluginInstanceId,
disableForeignListResourceRefColumn: this.options.disableForeignListResourceRefColumn,
foreignResourceId: this.options.foreignResourceId,
...(defaultSort
? {
defaultSort: {
field: defaultSort.columnName,
direction: defaultSort.direction,
}
}
: {}
)
}
}
},
};
if (this.options.placeInGroup?.name) {
const fieldGroupTypes = [
'fieldGroups',
'createFieldGroups',
'editFieldGroups',
'showFieldGroups'
] as const;
let columnAdded = false;
for (const groupType of fieldGroupTypes) {
const targetGroup = resourceConfig.options?.[groupType]?.find(
group => group.groupName === this.options.placeInGroup?.name
);
if (targetGroup) {
if (this.options.placeInGroup.position < 0 || this.options.placeInGroup.position > targetGroup.columns.length) {
throw new Error(`ForeignInlineListPlugin: Invalid position ${this.options.placeInGroup?.position}. Must be between 0 and ${targetGroup.columns.length} for group "${this.options.placeInGroup?.name}"`);
}
// Only add the column to resourceConfig.columns once
if (!columnAdded) {
const beforeColumnName = targetGroup.columns[this.options.placeInGroup.position - 1];
const beforeColumnIndex = resourceConfig.columns.findIndex(
col => col.name === beforeColumnName
);
resourceConfig.columns.splice(beforeColumnIndex + 1, 0, newColumn);
columnAdded = true;
}
// Add the column name to the group's columns array
targetGroup.columns.splice(this.options.placeInGroup.position, 0, newColumn.name);
}
}
} else {
resourceConfig.columns.push(newColumn);
}
}
}