-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathadmin.store.js
More file actions
213 lines (197 loc) · 6.43 KB
/
admin.store.js
File metadata and controls
213 lines (197 loc) · 6.43 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
/**
* Module dependencies.
*/
import { defineStore } from 'pinia';
import { assign } from 'lodash-es';
import axios from '../../../lib/services/axios';
import config from '../../../lib/services/config';
import model from '../../../lib/middlewares/model';
import { createLogger } from '../../../lib/helpers/logger';
const logger = createLogger('admin');
/**
* Whitelists.
*/
const whitelists = ['firstName', 'lastName', 'bio', 'position', 'email', 'avatar', 'roles'];
/**
* Sanitize API error messages to avoid leaking internal details (stack traces, DB paths, etc.).
* @param {unknown} err - The caught error object.
* @returns {string} A safe, user-facing error message.
*/
const sanitizeApiError = (err) => {
const msg = err?.response?.data?.message || '';
if (msg && msg.length <= 200 && !/\b(collection|stack)\b|Error:|^\s*at\s+|\/[a-z]+\/|\.[jt]s:\d+/.test(msg)) {
return msg;
}
return 'Failed to load data. Please try again.';
};
/**
* Build the base API URL from config.
* @returns {string} The base API URL.
*/
const apiBase = () => `${config.api.protocol}://${config.api.host}:${config.api.port}/${config.api.base}`;
const defaultUser = () => ({
firstName: '',
lastName: '',
bio: '',
position: '',
email: '',
avatar: '',
roles: [],
memberships: [],
updated: '',
created: '',
});
/**
* Store definition.
*/
export const useAdminStore = defineStore('admin', {
state: () => ({
user: defaultUser(),
users: [],
organizations: [],
error: null,
currentBreadcrumb: null,
readiness: [],
auditLogs: [],
auditTotal: 0,
auditPage: 1,
}),
actions: {
async getUsers(params) {
this.error = null;
try {
const res = await axios.get(`${apiBase()}/admin/users/page/${params}`);
this.users = res.data.data;
} catch (err) {
this.error = sanitizeApiError(err);
console.error(err);
}
},
async getUser(params) {
this.error = null;
try {
const res = await axios.get(`${apiBase()}/admin/users/${params.id}`);
this.user = res.data.data;
} catch (err) {
this.error = sanitizeApiError(err);
this.resetUser();
console.error(err);
}
},
/**
* @desc Update a user via the admin API using a partial patch.
* Only the fields present in `formData` (after whitelist sanitization) are sent,
* so callers must provide every field they want persisted. Merging with the
* local `this.user` placeholder is intentionally avoided to prevent empty
* defaults from wiping persisted fields (e.g. role-toggle from the list view).
* @param {{ id: string }} params - Route params, must contain the target user id.
* @param {Object} [formData] - Partial user payload (whitelisted fields only).
* @returns {Promise<void>}
*/
async updateUser(params, formData) {
this.error = null;
try {
const obj = model.clean(formData || {}, whitelists);
const res = await axios.put(`${apiBase()}/admin/users/${params.id}`, obj);
assign(this.user, res.data.data);
} catch (err) {
this.error = sanitizeApiError(err);
console.error(err);
throw err;
}
},
async deleteUser(params) {
this.error = null;
try {
await axios.delete(`${apiBase()}/admin/users/${params.id}`);
this.resetUser();
} catch (err) {
this.error = sanitizeApiError(err);
console.error(err);
throw err;
}
},
resetUser() {
this.user = defaultUser();
},
/**
* @desc Set (or clear) the current breadcrumb published by an admin sub-view.
* A shallow copy is stored so callers cannot mutate the store state directly.
* Pass `null` to clear (identical effect to `clearBreadcrumb()`).
* @param {{ title: string, titleClass?: string } | null} payload - Breadcrumb data, or null to clear.
* @returns {void}
*/
setBreadcrumb(payload) {
this.currentBreadcrumb = payload ? { ...payload } : null;
},
/**
* @desc Clear the current breadcrumb (reset to null). Called by admin sub-views on unmount.
* @returns {void}
*/
clearBreadcrumb() {
this.currentBreadcrumb = null;
},
/**
* @desc Fetch SaaS readiness checklist from the admin API.
* @returns {Promise<void>}
*/
async getReadiness() {
this.error = null;
try {
const res = await axios.get(`${apiBase()}/admin/readiness`);
this.readiness = res.data.data;
} catch (err) {
this.readiness = [];
this.error = sanitizeApiError(err);
logger.error(err);
}
},
async getOrganizations(params) {
this.error = null;
try {
const url = params ? `${apiBase()}/admin/organizations/page/${params}` : `${apiBase()}/admin/organizations`;
const res = await axios.get(url);
this.organizations = res.data.data;
} catch (err) {
this.error = sanitizeApiError(err);
console.error(err);
}
},
/**
* @desc Fetch paginated audit logs from the admin API.
* Response shape: res.data = { type, message, data: { data: Array, total, page, perPage } }
* (standard responses.success() wrapper around AuditRepository.list() result).
* @param {Object} [params] - Query parameters.
* @param {string} [params.action] - Filter by action type.
* @param {string} [params.userId] - Filter by user ID.
* @param {number} [params.page] - Page number (1-based).
* @param {number} [params.perPage] - Items per page.
* @returns {Promise<void>}
*/
async getAuditLogs({ action, userId, page, perPage } = {}) {
this.error = null;
try {
const query = new URLSearchParams();
if (action) query.set('action', action);
if (userId) query.set('userId', userId);
if (page) query.set('page', String(page));
if (perPage) query.set('perPage', String(perPage));
const qs = query.toString();
const url = `${apiBase()}/audit${qs ? '?' + qs : ''}`;
const res = await axios.get(url);
this.auditLogs = res.data.data?.data || [];
this.auditTotal = res.data.data?.total || 0;
this.auditPage = res.data.data?.page || 1;
} catch (err) {
this.auditLogs = [];
this.auditTotal = 0;
this.error = sanitizeApiError(err);
logger.error(err);
}
},
},
});
/**
* Exports.
*/
export default useAdminStore;