@adminforth/many2many 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+
2
+ #!/bin/bash
3
+
4
+ # write npm run output both to console and to build.log
5
+ npm run build 2>&1 | tee build.log
6
+ build_status=${PIPESTATUS[0]}
7
+
8
+ # if exist status from the npm run build is not 0
9
+ # then exit with the status code from the npm run build
10
+ if [ $build_status -ne 0 ]; then
11
+ echo "Build failed. Exiting with status code $build_status"
12
+ exit $build_status
13
+ fi
@@ -0,0 +1,44 @@
1
+ #!/bin/sh
2
+
3
+ set -x
4
+
5
+ COMMIT_SHORT_SHA=$(echo $CI_COMMIT_SHA | cut -c1-8)
6
+
7
+
8
+ if [ "$CI_STEP_STATUS" = "success" ]; then
9
+ MESSAGE="Did a build without issues on \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\`. Commit: _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
10
+
11
+ curl -s -X POST -H "Content-Type: application/json" -d '{
12
+ "username": "'"$CI_COMMIT_AUTHOR"'",
13
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
14
+ "attachments": [
15
+ {
16
+ "mrkdwn_in": ["text", "pretext"],
17
+ "color": "#36a64f",
18
+ "text": "'"$MESSAGE"'"
19
+ }
20
+ ]
21
+ }' "$DEVELOPERS_SLACK_WEBHOOK"
22
+ exit 0
23
+ fi
24
+ export BUILD_LOG=$(cat ./build.log)
25
+
26
+ BUILD_LOG=$(echo $BUILD_LOG | sed 's/"/\\"/g')
27
+
28
+ MESSAGE="Broke \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\` with commit _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
29
+ CODE_BLOCK="\`\`\`$BUILD_LOG\n\`\`\`"
30
+
31
+ echo "Sending slack message to developers $MESSAGE"
32
+ # Send the message
33
+ curl -sS -X POST -H "Content-Type: application/json" -d '{
34
+ "username": "'"$CI_COMMIT_AUTHOR"'",
35
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
36
+ "attachments": [
37
+ {
38
+ "mrkdwn_in": ["text", "pretext"],
39
+ "color": "#8A1C12",
40
+ "text": "'"$CODE_BLOCK"'",
41
+ "pretext": "'"$MESSAGE"'"
42
+ }
43
+ ]
44
+ }' "$DEVELOPERS_SLACK_WEBHOOK" 2>&1
@@ -0,0 +1,40 @@
1
+ clone:
2
+ git:
3
+ image: woodpeckerci/plugin-git
4
+ settings:
5
+ partial: false
6
+ depth: 5
7
+
8
+ steps:
9
+ init-secrets:
10
+ when:
11
+ - event: push
12
+ image: infisical/cli
13
+ environment:
14
+ INFISICAL_TOKEN:
15
+ from_secret: VAULT_TOKEN
16
+ commands:
17
+ - infisical export --domain https://vault.devforth.io/api --format=dotenv-export --env="prod" > /woodpecker/deploy.vault.env
18
+
19
+ release:
20
+ image: node:20
21
+ when:
22
+ - event: push
23
+ commands:
24
+ - apt update && apt install -y rsync
25
+ - export $(cat /woodpecker/deploy.vault.env | xargs)
26
+ - npm clean-install
27
+ - /bin/bash ./.woodpecker/buildRelease.sh
28
+ - npm audit signatures
29
+ - npx semantic-release
30
+
31
+ slack-on-failure:
32
+ when:
33
+ - event: push
34
+ status: [failure, success]
35
+ - event: push
36
+ image: curlimages/curl
37
+ commands:
38
+ - export $(cat /woodpecker/deploy.vault.env | xargs)
39
+ - /bin/sh ./.woodpecker/buildSlackNotify.sh
40
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Devforth.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/build.log ADDED
@@ -0,0 +1,12 @@
1
+
2
+ > @adminforth/many2many@1.0.1 build
3
+ > tsc && rsync -av --exclude 'node_modules' custom dist/
4
+
5
+ sending incremental file list
6
+ custom/
7
+ custom/ManyToManyInput.vue
8
+ custom/ManyToManyShow.vue
9
+ custom/tsconfig.json
10
+
11
+ sent 4,884 bytes received 77 bytes 9,922.00 bytes/sec
12
+ total size is 4,592 speedup is 0.93
@@ -0,0 +1,117 @@
1
+ <template>
2
+ <Select
3
+ class="w-full"
4
+ :options="selectOptions"
5
+ v-model="selected"
6
+ multiple
7
+ @search="loadForeignOptions"
8
+ @scroll-near-end="scrollNearEnd"
9
+ ></Select>
10
+ </template>
11
+
12
+
13
+ <script lang="ts" setup>
14
+ import { Select } from '@/afcl'
15
+ import { ref, onMounted, watch } from 'vue';
16
+ import { callAdminForthApi } from '@/utils';
17
+
18
+ const props = defineProps<{
19
+ column: any,
20
+ record: any,
21
+ meta: any,
22
+ resource: any
23
+ }>();
24
+
25
+ const emit = defineEmits([
26
+ 'update:value',
27
+ ]);
28
+
29
+ const selected = ref([])
30
+ const selectOptions = ref([])
31
+ const pickedValues = ref([])
32
+ const currentSearch = ref('')
33
+ const lastSearch = ref('')
34
+ const loadOffset = ref(0);
35
+ const wasLimitReached = ref(false);
36
+
37
+ onMounted(async() => {
38
+ if ( !props.record || Object.keys(props.record).length === 0 ) {
39
+ loadForeignOptions();
40
+ } else {
41
+ try {
42
+ const resp = await callAdminForthApi({
43
+ method: 'POST',
44
+ path: `/plugin/${props.meta.pluginInstanceId}/get-junctionResource-records`,
45
+ body: {
46
+ recordId: props.record[props.meta.resourcePrimaryKeyColumnName]
47
+ },
48
+ });
49
+ selected.value = resp.data
50
+ } catch (error) {
51
+ console.error('Error loading foreign options:', error);
52
+ }
53
+
54
+ try {
55
+ const resp = await callAdminForthApi({
56
+ method: 'POST',
57
+ path: `/plugin/${props.meta.pluginInstanceId}/get-junctionResource-records`,
58
+ body: {
59
+ recordId: props.record[props.meta.resourcePrimaryKeyColumnName],
60
+ returnLabels: true,
61
+ },
62
+ });
63
+ pickedValues.value = resp.data
64
+ } catch (error) {
65
+ console.error('Error loading foreign options:', error);
66
+ }
67
+
68
+ loadForeignOptions();
69
+ }
70
+ });
71
+
72
+ async function loadForeignOptions(search = '', offset = 0) {
73
+ lastSearch.value = currentSearch.value;
74
+ currentSearch.value = search;
75
+ try {
76
+ const resp = await callAdminForthApi({
77
+ method: 'POST',
78
+ path: `/get_resource_foreign_data`,
79
+ body: {
80
+ resourceId: props.meta.junctionResourceId,
81
+ column: props.meta.linkedColumnName,
82
+ limit: 100,
83
+ offset: offset,
84
+ search: search,
85
+ },
86
+ });
87
+
88
+ wasLimitReached.value = resp.items.length < 100;
89
+ const removeValues = pickedValues.value.map(i => i.value);
90
+ const result = resp.items.filter(item => !removeValues.includes(item.value));
91
+ selectOptions.value = selectOptions.value.filter(item => !removeValues.includes(item.value));
92
+ const removeValues2 = selectOptions.value.map(i => i.value);
93
+ const finalResult = result.filter(item => !removeValues2.includes(item.value));
94
+
95
+ selectOptions.value = [...pickedValues.value, ...selectOptions.value, ...finalResult];
96
+ } catch (error) {
97
+ console.error('Error loading foreign options:', error);
98
+ }
99
+ }
100
+
101
+ function scrollNearEnd() {
102
+ console.log('scrollNearEnd');
103
+ if ( lastSearch.value !== currentSearch.value ) {
104
+ loadOffset.value = 0;
105
+ } else {
106
+ loadOffset.value += 100;
107
+ }
108
+ if ( wasLimitReached.value ) return;
109
+ loadForeignOptions(currentSearch.value, loadOffset.value);
110
+ }
111
+
112
+ watch(() => selected.value, (value) => {
113
+ pickedValues.value.push(selectOptions.value.find(i => i.value === value[value.length -1]));
114
+ emit('update:value', value);
115
+ });
116
+
117
+ </script>
@@ -0,0 +1,43 @@
1
+ <template>
2
+ <template v-for="value in values" :key="value.value">
3
+ <Link :to="`/resource/${props.meta.linkedResourceId}/show/${value.value}`" class="badge bg-primary me-1 mr-3">{{ value.label }}</Link>
4
+ </template>
5
+ </template>
6
+
7
+ <script lang="ts" setup>
8
+ import { onMounted, ref } from 'vue';
9
+ import { callAdminForthApi } from '@/utils';
10
+ import { Link } from '@/afcl'
11
+
12
+
13
+ const props = defineProps<{
14
+ column: any,
15
+ record: any,
16
+ meta: any,
17
+ resource: any
18
+ }>();
19
+
20
+ const emit = defineEmits([
21
+ 'update:value',
22
+ ]);
23
+
24
+ const values = ref([]);
25
+
26
+ onMounted(async() => {
27
+ if ( !props.record || Object.keys(props.record).length === 0 ) return;
28
+ try {
29
+ const resp = await callAdminForthApi({
30
+ method: 'POST',
31
+ path: `/plugin/${props.meta.pluginInstanceId}/get-junctionResource-records`,
32
+ body: {
33
+ recordId: props.record[props.meta.resourcePrimaryKeyColumnName],
34
+ returnLabels: true,
35
+ },
36
+ });
37
+ values.value = resp.data;
38
+ } catch (error) {
39
+ console.error('Error loading foreign options:', error);
40
+ }
41
+ });
42
+
43
+ </script>
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "baseUrl": ".", // This should point to your project root
4
+ "paths": {
5
+ "@/*": [
6
+ "../node_modules/adminforth/dist/spa/src/*"
7
+ ],
8
+ "*": [
9
+ "../node_modules/adminforth/dist/spa/node_modules/*"
10
+ ],
11
+ "@@/*": [
12
+ "."
13
+ ]
14
+ }
15
+ }
16
+ }
@@ -0,0 +1,117 @@
1
+ <template>
2
+ <Select
3
+ class="w-full"
4
+ :options="selectOptions"
5
+ v-model="selected"
6
+ multiple
7
+ @search="loadForeignOptions"
8
+ @scroll-near-end="scrollNearEnd"
9
+ ></Select>
10
+ </template>
11
+
12
+
13
+ <script lang="ts" setup>
14
+ import { Select } from '@/afcl'
15
+ import { ref, onMounted, watch } from 'vue';
16
+ import { callAdminForthApi } from '@/utils';
17
+
18
+ const props = defineProps<{
19
+ column: any,
20
+ record: any,
21
+ meta: any,
22
+ resource: any
23
+ }>();
24
+
25
+ const emit = defineEmits([
26
+ 'update:value',
27
+ ]);
28
+
29
+ const selected = ref([])
30
+ const selectOptions = ref([])
31
+ const pickedValues = ref([])
32
+ const currentSearch = ref('')
33
+ const lastSearch = ref('')
34
+ const loadOffset = ref(0);
35
+ const wasLimitReached = ref(false);
36
+
37
+ onMounted(async() => {
38
+ if ( !props.record || Object.keys(props.record).length === 0 ) {
39
+ loadForeignOptions();
40
+ } else {
41
+ try {
42
+ const resp = await callAdminForthApi({
43
+ method: 'POST',
44
+ path: `/plugin/${props.meta.pluginInstanceId}/get-junctionResource-records`,
45
+ body: {
46
+ recordId: props.record[props.meta.resourcePrimaryKeyColumnName]
47
+ },
48
+ });
49
+ selected.value = resp.data
50
+ } catch (error) {
51
+ console.error('Error loading foreign options:', error);
52
+ }
53
+
54
+ try {
55
+ const resp = await callAdminForthApi({
56
+ method: 'POST',
57
+ path: `/plugin/${props.meta.pluginInstanceId}/get-junctionResource-records`,
58
+ body: {
59
+ recordId: props.record[props.meta.resourcePrimaryKeyColumnName],
60
+ returnLabels: true,
61
+ },
62
+ });
63
+ pickedValues.value = resp.data
64
+ } catch (error) {
65
+ console.error('Error loading foreign options:', error);
66
+ }
67
+
68
+ loadForeignOptions();
69
+ }
70
+ });
71
+
72
+ async function loadForeignOptions(search = '', offset = 0) {
73
+ lastSearch.value = currentSearch.value;
74
+ currentSearch.value = search;
75
+ try {
76
+ const resp = await callAdminForthApi({
77
+ method: 'POST',
78
+ path: `/get_resource_foreign_data`,
79
+ body: {
80
+ resourceId: props.meta.junctionResourceId,
81
+ column: props.meta.linkedColumnName,
82
+ limit: 100,
83
+ offset: offset,
84
+ search: search,
85
+ },
86
+ });
87
+
88
+ wasLimitReached.value = resp.items.length < 100;
89
+ const removeValues = pickedValues.value.map(i => i.value);
90
+ const result = resp.items.filter(item => !removeValues.includes(item.value));
91
+ selectOptions.value = selectOptions.value.filter(item => !removeValues.includes(item.value));
92
+ const removeValues2 = selectOptions.value.map(i => i.value);
93
+ const finalResult = result.filter(item => !removeValues2.includes(item.value));
94
+
95
+ selectOptions.value = [...pickedValues.value, ...selectOptions.value, ...finalResult];
96
+ } catch (error) {
97
+ console.error('Error loading foreign options:', error);
98
+ }
99
+ }
100
+
101
+ function scrollNearEnd() {
102
+ console.log('scrollNearEnd');
103
+ if ( lastSearch.value !== currentSearch.value ) {
104
+ loadOffset.value = 0;
105
+ } else {
106
+ loadOffset.value += 100;
107
+ }
108
+ if ( wasLimitReached.value ) return;
109
+ loadForeignOptions(currentSearch.value, loadOffset.value);
110
+ }
111
+
112
+ watch(() => selected.value, (value) => {
113
+ pickedValues.value.push(selectOptions.value.find(i => i.value === value[value.length -1]));
114
+ emit('update:value', value);
115
+ });
116
+
117
+ </script>
@@ -0,0 +1,43 @@
1
+ <template>
2
+ <template v-for="value in values" :key="value.value">
3
+ <Link :to="`/resource/${props.meta.linkedResourceId}/show/${value.value}`" class="badge bg-primary me-1 mr-3">{{ value.label }}</Link>
4
+ </template>
5
+ </template>
6
+
7
+ <script lang="ts" setup>
8
+ import { onMounted, ref } from 'vue';
9
+ import { callAdminForthApi } from '@/utils';
10
+ import { Link } from '@/afcl'
11
+
12
+
13
+ const props = defineProps<{
14
+ column: any,
15
+ record: any,
16
+ meta: any,
17
+ resource: any
18
+ }>();
19
+
20
+ const emit = defineEmits([
21
+ 'update:value',
22
+ ]);
23
+
24
+ const values = ref([]);
25
+
26
+ onMounted(async() => {
27
+ if ( !props.record || Object.keys(props.record).length === 0 ) return;
28
+ try {
29
+ const resp = await callAdminForthApi({
30
+ method: 'POST',
31
+ path: `/plugin/${props.meta.pluginInstanceId}/get-junctionResource-records`,
32
+ body: {
33
+ recordId: props.record[props.meta.resourcePrimaryKeyColumnName],
34
+ returnLabels: true,
35
+ },
36
+ });
37
+ values.value = resp.data;
38
+ } catch (error) {
39
+ console.error('Error loading foreign options:', error);
40
+ }
41
+ });
42
+
43
+ </script>
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "baseUrl": ".", // This should point to your project root
4
+ "paths": {
5
+ "@/*": [
6
+ "../node_modules/adminforth/dist/spa/src/*"
7
+ ],
8
+ "*": [
9
+ "../node_modules/adminforth/dist/spa/node_modules/*"
10
+ ],
11
+ "@@/*": [
12
+ "."
13
+ ]
14
+ }
15
+ }
16
+ }
package/dist/index.js ADDED
@@ -0,0 +1,178 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { AdminForthPlugin, Filters } from "adminforth";
11
+ let junctionResource = null;
12
+ let linkedColumnNameInJunctionResource = null;
13
+ let resourceColumnNameInJunctionResource = null;
14
+ export default class extends AdminForthPlugin {
15
+ constructor(options) {
16
+ super(options, import.meta.url);
17
+ this.options = options;
18
+ }
19
+ modifyResourceConfig(adminforth, resourceConfig) {
20
+ const _super = Object.create(null, {
21
+ modifyResourceConfig: { get: () => super.modifyResourceConfig }
22
+ });
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ var _a, _b, _c, _d, _e;
25
+ _super.modifyResourceConfig.call(this, adminforth, resourceConfig);
26
+ for (const resource of this.adminforth.config.resources) {
27
+ let wasLinkedResourceFound = false;
28
+ let wasCurrentResourceFound = false;
29
+ for (const column of resource.columns) {
30
+ if (((_a = column.foreignResource) === null || _a === void 0 ? void 0 : _a.resourceId) === this.options.linkedResourceId) {
31
+ wasLinkedResourceFound = true;
32
+ }
33
+ else if (((_b = column.foreignResource) === null || _b === void 0 ? void 0 : _b.resourceId) === resourceConfig.resourceId) {
34
+ wasCurrentResourceFound = true;
35
+ }
36
+ }
37
+ if (wasLinkedResourceFound && wasCurrentResourceFound) {
38
+ junctionResource = resource;
39
+ break;
40
+ }
41
+ }
42
+ if (!junctionResource) {
43
+ throw new Error(`Junction resource not found for many-to-many relation between ${resourceConfig.resourceId} and ${this.options.linkedResourceId}`);
44
+ }
45
+ linkedColumnNameInJunctionResource = (_c = junctionResource.columns.find(c => { var _a; return ((_a = c.foreignResource) === null || _a === void 0 ? void 0 : _a.resourceId) === this.options.linkedResourceId; })) === null || _c === void 0 ? void 0 : _c.name;
46
+ resourceColumnNameInJunctionResource = (_d = junctionResource.columns.find(c => { var _a; return ((_a = c.foreignResource) === null || _a === void 0 ? void 0 : _a.resourceId) === resourceConfig.resourceId; })) === null || _d === void 0 ? void 0 : _d.name;
47
+ const pluginFrontendOptions = {
48
+ pluginInstanceId: this.pluginInstanceId,
49
+ resourceId: resourceConfig.resourceId,
50
+ linkedResourceId: this.options.linkedResourceId,
51
+ junctionResourceId: junctionResource ? junctionResource.resourceId : null,
52
+ linkedColumnName: linkedColumnNameInJunctionResource,
53
+ resourcePrimaryKeyColumnName: (_e = resourceConfig.columns.find(c => c.primaryKey)) === null || _e === void 0 ? void 0 : _e.name,
54
+ };
55
+ const virtualColumn = {
56
+ virtual: true,
57
+ name: `many2many_${this.pluginInstanceId}`,
58
+ components: {
59
+ edit: {
60
+ file: this.componentPath('ManyToManyInput.vue'),
61
+ meta: pluginFrontendOptions,
62
+ },
63
+ create: {
64
+ file: this.componentPath('ManyToManyInput.vue'),
65
+ meta: pluginFrontendOptions,
66
+ },
67
+ show: {
68
+ file: this.componentPath('ManyToManyShow.vue'),
69
+ meta: pluginFrontendOptions,
70
+ },
71
+ },
72
+ showIn: {
73
+ create: true,
74
+ edit: true,
75
+ list: false,
76
+ show: true,
77
+ filter: false,
78
+ },
79
+ required: {
80
+ create: false,
81
+ edit: false
82
+ },
83
+ label: this.options.linkedResourceId
84
+ };
85
+ resourceConfig.columns.push(virtualColumn);
86
+ // ** HOOKS FOR CREATE **//
87
+ resourceConfig.hooks.create.afterSave.push((_a) => __awaiter(this, [_a], void 0, function* ({ recordId, recordWithVirtualColumns }) {
88
+ if (recordWithVirtualColumns[`many2many_${this.pluginInstanceId}`]) {
89
+ for (const linkedId of recordWithVirtualColumns[`many2many_${this.pluginInstanceId}`]) {
90
+ yield this.adminforth.resource(junctionResource.resourceId).create({
91
+ [resourceColumnNameInJunctionResource]: recordId,
92
+ [linkedColumnNameInJunctionResource]: linkedId,
93
+ });
94
+ }
95
+ }
96
+ return { ok: true };
97
+ }));
98
+ // ** HOOKS FOR EDIT **//
99
+ resourceConfig.hooks.edit.beforeSave.push((_a) => __awaiter(this, [_a], void 0, function* ({ recordId, updates }) {
100
+ if (updates[`many2many_${this.pluginInstanceId}`]) {
101
+ const existingJunctionRecords = yield this.adminforth.resource(junctionResource.resourceId).list([Filters.EQ(resourceColumnNameInJunctionResource, recordId)]);
102
+ const updatedLinkedIds = updates[`many2many_${this.pluginInstanceId}`];
103
+ for (const jr of existingJunctionRecords) {
104
+ const linkedId = jr[linkedColumnNameInJunctionResource];
105
+ if (!updatedLinkedIds.includes(linkedId)) {
106
+ yield this.adminforth.resource(junctionResource.resourceId).delete(jr[junctionResource.columns.find(c => c.primaryKey).name]);
107
+ }
108
+ }
109
+ for (const linkedId of updatedLinkedIds) {
110
+ const alreadyExists = existingJunctionRecords.find(jr => jr[linkedColumnNameInJunctionResource] === linkedId);
111
+ if (!alreadyExists) {
112
+ yield this.adminforth.resource(junctionResource.resourceId).create({
113
+ [resourceColumnNameInJunctionResource]: recordId,
114
+ [linkedColumnNameInJunctionResource]: linkedId,
115
+ });
116
+ }
117
+ }
118
+ }
119
+ return { ok: true };
120
+ }));
121
+ // ** HOOKS FOR DELETE **//
122
+ if (!this.options.dontDeleteJunctionRecords) {
123
+ resourceConfig.hooks.delete.beforeSave.push((_a) => __awaiter(this, [_a], void 0, function* ({ recordId, record }) {
124
+ const existingJunctionRecords = yield this.adminforth.resource(junctionResource.resourceId).list([Filters.EQ(resourceColumnNameInJunctionResource, recordId)]);
125
+ for (const jr of existingJunctionRecords) {
126
+ yield this.adminforth.resource(junctionResource.resourceId).delete(jr[junctionResource.columns.find(c => c.primaryKey).name]);
127
+ }
128
+ return { ok: true };
129
+ }));
130
+ const linkedResource = this.adminforth.config.resources.find(r => r.resourceId === this.options.linkedResourceId);
131
+ linkedResource.hooks.delete.beforeSave.push((_a) => __awaiter(this, [_a], void 0, function* ({ recordId, record }) {
132
+ const existingJunctionRecords = yield this.adminforth.resource(junctionResource.resourceId).list([Filters.EQ(linkedColumnNameInJunctionResource, recordId)]);
133
+ for (const jr of existingJunctionRecords) {
134
+ yield this.adminforth.resource(junctionResource.resourceId).delete(jr[junctionResource.columns.find(c => c.primaryKey).name]);
135
+ }
136
+ return { ok: true };
137
+ }));
138
+ }
139
+ });
140
+ }
141
+ validateConfigAfterDiscover(adminforth, resourceConfig) {
142
+ // optional method where you can safely check field types after database discovery was performed
143
+ }
144
+ instanceUniqueRepresentation(pluginOptions) {
145
+ // optional method to return unique string representation of plugin instance.
146
+ // Needed if plugin can have multiple instances on one resource
147
+ return `many2many-${this.resourceConfig.resourceId}-${this.options.linkedResourceId}`;
148
+ }
149
+ setupEndpoints(server) {
150
+ server.endpoint({
151
+ method: 'POST',
152
+ path: `/plugin/${this.pluginInstanceId}/get-junctionResource-records`,
153
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
154
+ const { recordId, returnLabels } = body;
155
+ const junctionRecords = yield this.adminforth.resource(junctionResource.resourceId).list([Filters.EQ(resourceColumnNameInJunctionResource, recordId)]);
156
+ let dataToReturn = [];
157
+ const junctionResourcePkColumn = junctionResource.columns.find(c => c.primaryKey);
158
+ const linkedResource = this.adminforth.resource(this.options.linkedResourceId);
159
+ for (const jr of junctionRecords) {
160
+ const record = yield this.adminforth.resource(this.options.linkedResourceId).get([Filters.EQ(junctionResourcePkColumn.name, jr[linkedColumnNameInJunctionResource])]);
161
+ if (!returnLabels) {
162
+ dataToReturn.push(record[junctionResourcePkColumn.name]);
163
+ }
164
+ else {
165
+ dataToReturn.push(linkedResource.resourceConfig.recordLabel ? {
166
+ label: linkedResource.resourceConfig.recordLabel(record),
167
+ value: record[junctionResourcePkColumn.name]
168
+ } : {
169
+ label: record[junctionResourcePkColumn.name],
170
+ value: record[junctionResourcePkColumn.name]
171
+ });
172
+ }
173
+ }
174
+ return { ok: true, data: dataToReturn };
175
+ })
176
+ });
177
+ }
178
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/index.ts ADDED
@@ -0,0 +1,182 @@
1
+ import { AdminForthPlugin, Filters } from "adminforth";
2
+ import type { IAdminForth, IHttpServer, AdminForthResourcePages, AdminForthResourceColumn, AdminForthDataTypes, AdminForthResource } from "adminforth";
3
+ import type { PluginOptions } from './types.js';
4
+
5
+ let junctionResource = null;
6
+ let linkedColumnNameInJunctionResource = null;
7
+ let resourceColumnNameInJunctionResource = null;
8
+ export default class extends AdminForthPlugin {
9
+ options: PluginOptions;
10
+
11
+ constructor(options: PluginOptions) {
12
+ super(options, import.meta.url);
13
+ this.options = options;
14
+ }
15
+
16
+ async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
17
+ super.modifyResourceConfig(adminforth, resourceConfig);
18
+
19
+ for(const resource of this.adminforth.config.resources) {
20
+ let wasLinkedResourceFound = false;
21
+ let wasCurrentResourceFound = false;
22
+ for(const column of resource.columns) {
23
+ if ( column.foreignResource?.resourceId === this.options.linkedResourceId ) {
24
+ wasLinkedResourceFound = true;
25
+ } else if ( column.foreignResource?.resourceId === resourceConfig.resourceId ) {
26
+ wasCurrentResourceFound = true;
27
+ }
28
+ }
29
+ if ( wasLinkedResourceFound && wasCurrentResourceFound ) {
30
+ junctionResource = resource;
31
+ break;
32
+ }
33
+ }
34
+ if (!junctionResource) {
35
+ throw new Error(`Junction resource not found for many-to-many relation between ${resourceConfig.resourceId} and ${this.options.linkedResourceId}`);
36
+ }
37
+
38
+ linkedColumnNameInJunctionResource = junctionResource.columns.find(c => c.foreignResource?.resourceId === this.options.linkedResourceId)?.name;
39
+ resourceColumnNameInJunctionResource = junctionResource.columns.find(c => c.foreignResource?.resourceId === resourceConfig.resourceId)?.name;
40
+
41
+ const pluginFrontendOptions = {
42
+ pluginInstanceId: this.pluginInstanceId,
43
+ resourceId: resourceConfig.resourceId,
44
+ linkedResourceId: this.options.linkedResourceId,
45
+ junctionResourceId: junctionResource ? junctionResource.resourceId : null,
46
+ linkedColumnName: linkedColumnNameInJunctionResource,
47
+ resourcePrimaryKeyColumnName: resourceConfig.columns.find(c => c.primaryKey)?.name,
48
+ }
49
+
50
+ const virtualColumn: AdminForthResourceColumn = {
51
+ virtual: true,
52
+ name: `many2many_${this.pluginInstanceId}`,
53
+ components: {
54
+ edit: {
55
+ file: this.componentPath('ManyToManyInput.vue'),
56
+ meta: pluginFrontendOptions,
57
+ },
58
+ create: {
59
+ file: this.componentPath('ManyToManyInput.vue'),
60
+ meta: pluginFrontendOptions,
61
+ },
62
+ show: {
63
+ file: this.componentPath('ManyToManyShow.vue'),
64
+ meta: pluginFrontendOptions,
65
+ },
66
+ },
67
+ showIn: {
68
+ create: true,
69
+ edit: true,
70
+ list: false,
71
+ show: true,
72
+ filter: false,
73
+ },
74
+ required: {
75
+ create: false,
76
+ edit: false
77
+ },
78
+ label: this.options.linkedResourceId
79
+ };
80
+ resourceConfig.columns.push(virtualColumn);
81
+
82
+ // ** HOOKS FOR CREATE **//
83
+
84
+ resourceConfig.hooks.create.afterSave.push(async ({ recordId, recordWithVirtualColumns }) => {
85
+ if ( recordWithVirtualColumns[`many2many_${this.pluginInstanceId}`] ) {
86
+ for(const linkedId of recordWithVirtualColumns[`many2many_${this.pluginInstanceId}`]) {
87
+ await this.adminforth.resource(junctionResource.resourceId).create({
88
+ [resourceColumnNameInJunctionResource]: recordId,
89
+ [linkedColumnNameInJunctionResource]: linkedId,
90
+ });
91
+ }
92
+ }
93
+ return { ok: true };
94
+ });
95
+
96
+ // ** HOOKS FOR EDIT **//
97
+
98
+ resourceConfig.hooks.edit.beforeSave.push(async ({recordId, updates }: { recordId: any, updates: any }) => {
99
+ if ( updates[`many2many_${this.pluginInstanceId}`] ) {
100
+ const existingJunctionRecords = await this.adminforth.resource(junctionResource.resourceId).list([Filters.EQ(resourceColumnNameInJunctionResource, recordId)]);
101
+ const updatedLinkedIds = updates[`many2many_${this.pluginInstanceId}`];
102
+ for(const jr of existingJunctionRecords) {
103
+ const linkedId = jr[linkedColumnNameInJunctionResource];
104
+ if ( !updatedLinkedIds.includes(linkedId) ) {
105
+ await this.adminforth.resource(junctionResource.resourceId).delete(jr[junctionResource.columns.find(c => c.primaryKey).name]);
106
+ }
107
+ }
108
+ for(const linkedId of updatedLinkedIds) {
109
+ const alreadyExists = existingJunctionRecords.find(jr => jr[linkedColumnNameInJunctionResource] === linkedId);
110
+ if ( !alreadyExists ) {
111
+ await this.adminforth.resource(junctionResource.resourceId).create({
112
+ [resourceColumnNameInJunctionResource]: recordId,
113
+ [linkedColumnNameInJunctionResource]: linkedId,
114
+ });
115
+ }
116
+ }
117
+ }
118
+ return { ok: true };
119
+ });
120
+
121
+ // ** HOOKS FOR DELETE **//
122
+ if (!this.options.dontDeleteJunctionRecords) {
123
+ resourceConfig.hooks.delete.beforeSave.push(async ({ recordId, record }: { recordId: any, record: any }) => {
124
+ const existingJunctionRecords = await this.adminforth.resource(junctionResource.resourceId).list([Filters.EQ(resourceColumnNameInJunctionResource, recordId)]);
125
+ for(const jr of existingJunctionRecords) {
126
+ await this.adminforth.resource(junctionResource.resourceId).delete(jr[junctionResource.columns.find(c => c.primaryKey).name]);
127
+ }
128
+ return { ok: true };
129
+ });
130
+ const linkedResource = this.adminforth.config.resources.find(r => r.resourceId === this.options.linkedResourceId);
131
+ linkedResource.hooks.delete.beforeSave.push(async ({ recordId, record }: { recordId: any, record: any }) => {
132
+ const existingJunctionRecords = await this.adminforth.resource(junctionResource.resourceId).list([Filters.EQ(linkedColumnNameInJunctionResource, recordId)]);
133
+ for(const jr of existingJunctionRecords) {
134
+ await this.adminforth.resource(junctionResource.resourceId).delete(jr[junctionResource.columns.find(c => c.primaryKey).name]);
135
+ }
136
+ return { ok: true };
137
+ });
138
+ }
139
+ }
140
+
141
+ validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
142
+ // optional method where you can safely check field types after database discovery was performed
143
+ }
144
+
145
+ instanceUniqueRepresentation(pluginOptions: any) : string {
146
+ // optional method to return unique string representation of plugin instance.
147
+ // Needed if plugin can have multiple instances on one resource
148
+ return `many2many-${this.resourceConfig.resourceId}-${this.options.linkedResourceId}`;
149
+ }
150
+
151
+ setupEndpoints(server: IHttpServer) {
152
+ server.endpoint({
153
+ method: 'POST',
154
+ path: `/plugin/${this.pluginInstanceId}/get-junctionResource-records`,
155
+ handler: async ({ body }) => {
156
+ const { recordId, returnLabels } = body;
157
+ const junctionRecords = await this.adminforth.resource(junctionResource.resourceId).list([Filters.EQ(resourceColumnNameInJunctionResource, recordId)]);
158
+ let dataToReturn = [];
159
+ const junctionResourcePkColumn = junctionResource.columns.find(c => c.primaryKey);
160
+ const linkedResource = this.adminforth.resource(this.options.linkedResourceId);
161
+ for(const jr of junctionRecords) {
162
+ const record = await this.adminforth.resource(this.options.linkedResourceId).get([Filters.EQ(junctionResourcePkColumn.name, jr[linkedColumnNameInJunctionResource])]);
163
+ if ( !returnLabels ) {
164
+ dataToReturn.push (record[junctionResourcePkColumn.name]);
165
+ } else {
166
+ dataToReturn.push (
167
+ (linkedResource as any).resourceConfig.recordLabel ? {
168
+ label: (linkedResource as any).resourceConfig.recordLabel(record),
169
+ value: record[junctionResourcePkColumn.name]
170
+ } : {
171
+ label: record[junctionResourcePkColumn.name],
172
+ value: record[junctionResourcePkColumn.name]
173
+ }
174
+ );
175
+ }
176
+ }
177
+ return { ok: true, data: dataToReturn };
178
+ }
179
+ });
180
+ }
181
+
182
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@adminforth/many2many",
3
+ "version": "1.0.1",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "type": "module",
10
+ "scripts": {
11
+ "build": "tsc && rsync -av --exclude 'node_modules' custom dist/"
12
+ },
13
+ "keywords": [],
14
+ "author": "",
15
+ "license": "ISC",
16
+ "description": "",
17
+ "release": {
18
+ "plugins": [
19
+ "@semantic-release/commit-analyzer",
20
+ "@semantic-release/release-notes-generator",
21
+ "@semantic-release/npm",
22
+ "@semantic-release/github",
23
+ [
24
+ "semantic-release-slack-bot",
25
+ {
26
+ "notifyOnSuccess": true,
27
+ "notifyOnFail": true,
28
+ "slackIcon": ":package:",
29
+ "markdownReleaseNotes": true
30
+ }
31
+ ]
32
+ ],
33
+ "branches": [
34
+ "main",
35
+ {
36
+ "name": "next",
37
+ "prerelease": true
38
+ }
39
+ ]
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "latest",
43
+ "typescript": "^5.7.3"
44
+ },
45
+ "dependencies": {
46
+ "adminforth": "^2.4.0-next.308",
47
+ "semantic-release-slack-bot": "^4.0.2"
48
+ }
49
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include*/
4
+ "module": "node16", /* Specify what module code is generated. */
5
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
6
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. */
7
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
8
+ "strict": false, /* Enable all strict type-checking options. */
9
+ "skipLibCheck": true, /* Skip type checking all .d.ts files. */
10
+ },
11
+ "exclude": ["node_modules", "dist", "custom"], /* Exclude files from compilation. */
12
+ }
13
+
package/types.ts ADDED
@@ -0,0 +1,4 @@
1
+ export interface PluginOptions {
2
+ linkedResourceId: string
3
+ dontDeleteJunctionRecords?: boolean
4
+ }