-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom-roles.ts
More file actions
225 lines (190 loc) · 8.6 KB
/
custom-roles.ts
File metadata and controls
225 lines (190 loc) · 8.6 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
223
224
225
import keys from 'lodash/keys';
import find from 'lodash/find';
import forEach from 'lodash/forEach';
import values from 'lodash/values';
import { resolve as pResolve } from 'node:path';
import { handleAndLogError, messageHandler, log } from '@contentstack/cli-utilities';
import BaseClass from './base-class';
import {
fsUtil,
getExportBasePath,
PROCESS_NAMES,
MODULE_CONTEXTS,
PROCESS_STATUS,
MODULE_NAMES,
} from '../../utils';
import { CustomRoleConfig, ModuleClassParams } from '../../types';
export default class ExportCustomRoles extends BaseClass {
private customRoles: Record<string, unknown>;
private existingRoles: Record<string, number>;
private customRolesConfig: CustomRoleConfig;
private sourceLocalesMap: Record<string, unknown>;
private localesMap: Record<string, unknown>;
public rolesFolderPath: string;
public customRolesLocalesFilepath: string;
constructor({ exportConfig, stackAPIClient }: ModuleClassParams) {
super({ exportConfig, stackAPIClient });
this.customRoles = {};
this.customRolesConfig = exportConfig.modules.customRoles;
this.existingRoles = { Admin: 1, Developer: 1, 'Content Manager': 1 };
this.localesMap = {};
this.sourceLocalesMap = {};
this.exportConfig.context.module = MODULE_CONTEXTS.CUSTOM_ROLES;
this.currentModuleName = MODULE_NAMES[MODULE_CONTEXTS.CUSTOM_ROLES];
}
async start(): Promise<void> {
try {
log.debug('Starting custom roles export process...', this.exportConfig.context);
const [totalRoles, totalLocales] = await this.withLoadingSpinner(
'CUSTOM-ROLES: Analyzing roles and locales...',
async () => {
this.rolesFolderPath = pResolve(
getExportBasePath(this.exportConfig),
this.customRolesConfig.dirName,
);
await fsUtil.makeDirectory(this.rolesFolderPath);
this.customRolesLocalesFilepath = pResolve(
this.rolesFolderPath,
this.customRolesConfig.customRolesLocalesFileName,
);
// Get counts for progress tracking
const rolesResponse = await this.stack.role().fetchAll({ include_rules: true, include_permissions: true });
const customRolesCount = rolesResponse?.items?.filter((role: any) => !this.existingRoles[role.name]).length;
const localesResponse = await this.stack.locale().query({ include_count: true, limit: 1 }).find();
const localesCount = localesResponse?.count || 0;
return [customRolesCount, localesCount];
},
);
if (totalRoles === 0) {
log.info(messageHandler.parse('ROLES_NO_CUSTOM_ROLES'), this.exportConfig.context);
return;
}
// Create nested progress manager
const progress = this.createNestedProgress(this.currentModuleName)
.addProcess(PROCESS_NAMES.FETCH_ROLES, totalRoles)
.addProcess(PROCESS_NAMES.FETCH_LOCALES, totalLocales)
.addProcess(PROCESS_NAMES.PROCESS_MAPPINGS, 1);
progress
.startProcess(PROCESS_NAMES.FETCH_ROLES)
.updateStatus(
PROCESS_STATUS[PROCESS_NAMES.FETCH_ROLES].FETCHING,
PROCESS_NAMES.FETCH_ROLES,
);
await this.getCustomRoles();
progress.completeProcess(PROCESS_NAMES.FETCH_ROLES, true);
progress
.startProcess(PROCESS_NAMES.FETCH_LOCALES)
.updateStatus(
PROCESS_STATUS[PROCESS_NAMES.FETCH_LOCALES].FETCHING,
PROCESS_NAMES.FETCH_LOCALES,
);
await this.getLocales();
progress.completeProcess(PROCESS_NAMES.FETCH_LOCALES, true);
progress
.startProcess(PROCESS_NAMES.PROCESS_MAPPINGS)
.updateStatus(
PROCESS_STATUS[PROCESS_NAMES.PROCESS_MAPPINGS].PROCESSING,
PROCESS_NAMES.PROCESS_MAPPINGS,
);
await this.getCustomRolesLocales();
progress.completeProcess(PROCESS_NAMES.PROCESS_MAPPINGS, true);
log.debug(
`Custom roles export completed. Total custom roles: ${Object.keys(this.customRoles || {}).length}`,
this.exportConfig.context,
);
this.completeProgressWithMessage();
} catch (error) {
handleAndLogError(error, { ...this.exportConfig.context });
this.completeProgress(false, error?.message || 'Custom roles export failed');
}
}
async getCustomRoles(): Promise<void> {
log.debug('Fetching all roles from the stack...', this.exportConfig.context);
const roles = await this.stack
.role()
.fetchAll({ include_rules: true, include_permissions: true })
.then((data: any) => {
log.debug(`Fetched ${data.items?.length || 0} total roles`, this.exportConfig.context);
return data;
})
.catch((err: any) => {
log.debug('Error occurred while fetching roles', this.exportConfig.context);
return handleAndLogError(err, { ...this.exportConfig.context });
});
const customRoles = roles.items.filter((role: any) => !this.existingRoles[role.name]);
log.debug(
`Found ${customRoles.length} custom roles out of ${roles.items?.length || 0} total roles`,
this.exportConfig.context,
);
if (!customRoles.length) {
log.info(messageHandler.parse('ROLES_NO_CUSTOM_ROLES'), this.exportConfig.context);
return;
}
customRoles.forEach((role: any) => {
log.debug(`Processing custom role: ${role.name} (${role.uid})`, this.exportConfig.context);
log.info(messageHandler.parse('ROLES_EXPORTING_ROLE', role.name), this.exportConfig.context);
this.customRoles[role.uid] = role;
this.progressManager?.tick(true, `role: ${role.name}`, null, PROCESS_NAMES.FETCH_ROLES);
});
const customRolesFilePath = pResolve(this.rolesFolderPath, this.customRolesConfig.fileName);
log.debug(`Writing custom roles to: ${customRolesFilePath}`, this.exportConfig.context);
fsUtil.writeFile(customRolesFilePath, this.customRoles);
}
async getLocales() {
log.debug('Fetching locales for custom roles mapping...', this.exportConfig.context);
const locales = await this.stack
.locale()
.query({})
.find()
.then((data: any) => {
log.debug(`Fetched ${data?.items?.length || 0} locales`, this.exportConfig.context);
return data;
})
.catch((err: any) => {
log.debug('Error occurred while fetching locales', this.exportConfig.context);
return handleAndLogError(err, { ...this.exportConfig.context });
});
for (const locale of locales?.items) {
log.debug(`Mapping locale: ${locale.name} (${locale.uid})`, this.exportConfig.context);
this.sourceLocalesMap[locale.uid] = locale;
// Track progress for each locale
this.progressManager?.tick(true, `locale: ${locale.name}`, null, PROCESS_NAMES.FETCH_LOCALES);
}
log.debug(`Mapped ${Object.keys(this.sourceLocalesMap || {}).length} locales`, this.exportConfig.context);
}
async getCustomRolesLocales() {
log.debug('Processing custom roles locales mapping...', this.exportConfig.context);
for (const role of values(this.customRoles)) {
const customRole = role as Record<string, any>;
log.debug(`Processing locales for custom role: ${customRole.name}`, this.exportConfig.context);
const rulesLocales = find(customRole.rules, (rule: any) => rule.module === 'locale');
if (rulesLocales?.locales?.length) {
log.debug(
`Found ${rulesLocales.locales.length} locales for role: ${customRole.name}`,
this.exportConfig.context,
);
forEach(rulesLocales.locales, (locale: any) => {
log.debug(`Adding locale ${locale} to custom roles mapping`, this.exportConfig.context);
this.localesMap[locale] = 1;
});
}
}
if (keys(this.localesMap)?.length) {
log.debug(`Processing ${keys(this.localesMap).length} custom role locales`, this.exportConfig.context);
for (const locale in this.localesMap) {
if (this.sourceLocalesMap[locale] !== undefined) {
const sourceLocale = this.sourceLocalesMap[locale] as Record<string, any>;
log.debug(`Mapping locale ${locale} (${sourceLocale.name})`, this.exportConfig.context);
delete sourceLocale?.stackHeaders;
}
this.localesMap[locale] = this.sourceLocalesMap[locale];
}
log.debug(`Writing custom roles locales to: ${this.customRolesLocalesFilepath}`, this.exportConfig.context);
fsUtil.writeFile(this.customRolesLocalesFilepath, this.localesMap);
} else {
log.debug('No custom role locales found to process', this.exportConfig.context);
}
// Track progress for mapping completion
this.progressManager?.tick(true, 'role-locale mappings', null, PROCESS_NAMES.PROCESS_MAPPINGS);
}
}