@rockcarver/frodo-cli 0.18.2-8 → 0.18.2-9

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.
@@ -1,4 +1,27 @@
1
- import { EmailTemplateRaw } from '@rockcarver/frodo-lib';
1
+ import fs from 'fs';
2
+ import { EmailTemplate, ExportImportUtils } from '@rockcarver/frodo-lib';
3
+ import { getTypedFilename, saveJsonToFile } from '../utils/ExportImportUtils';
4
+ import { createProgressIndicator, updateProgressIndicator, stopProgressIndicator, printMessage, createTable } from '../utils/Console';
5
+ import wordwrap from './utils/Wordwrap';
6
+ const EMAIL_TEMPLATE_FILE_TYPE = 'template.email';
7
+ const {
8
+ EMAIL_TEMPLATE_TYPE,
9
+ getEmailTemplate,
10
+ getEmailTemplates,
11
+ putEmailTemplate
12
+ } = EmailTemplate;
13
+ const {
14
+ validateImport
15
+ } = ExportImportUtils;
16
+ const regexEmailTemplateType = new RegExp(`${EMAIL_TEMPLATE_TYPE}/`, 'g');
17
+
18
+ // use a function vs a template variable to avoid problems in loops
19
+ function getFileDataTemplate() {
20
+ return {
21
+ meta: {},
22
+ emailTemplate: {}
23
+ };
24
+ }
2
25
 
3
26
  /**
4
27
  * Get a one-line description of the email template
@@ -27,9 +50,251 @@ export function getTableHeaderMd() {
27
50
  * @returns {string} a table-row of the email template in markdown
28
51
  */
29
52
  export function getTableRowMd(templateObj) {
30
- const templateId = templateObj._id.replace(`${EmailTemplateRaw.EMAIL_TEMPLATE_TYPE}/`, '');
53
+ const templateId = templateObj._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '');
31
54
  const locales = `${templateObj.defaultLocale}${Object.keys(templateObj.subject).length > 1 ? ` (${Object.keys(templateObj.subject).filter(locale => locale !== templateObj.defaultLocale).join(',')})` : ''}`;
32
55
  const row = `| ${templateObj.name ? templateObj.name : templateId} | ${locales} | ${templateObj.subject[templateObj.defaultLocale]} | \`${templateId}\` |`;
33
56
  return row;
34
57
  }
58
+
59
+ /**
60
+ * List email templates
61
+ * @param {boolean} long Long list format with details
62
+ * @return {Promise<unknown[]>} a promise that resolves to an array of email template objects
63
+ */
64
+ export async function listEmailTemplates(long = false) {
65
+ let emailTemplates = [];
66
+ try {
67
+ emailTemplates = (await getEmailTemplates()).result;
68
+ } catch (error) {
69
+ printMessage(`Error retrieving email templates: ${error.message}`, 'error');
70
+ }
71
+ emailTemplates.sort((a, b) => a._id.localeCompare(b._id));
72
+ if (!long) {
73
+ for (const [, emailTemplate] of emailTemplates.entries()) {
74
+ printMessage(`${emailTemplate._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '')}`, 'data');
75
+ }
76
+ } else {
77
+ const table = createTable(['Id'['brightCyan'], 'Name'['brightCyan'], 'Status'['brightCyan'], 'Locale(s)'['brightCyan'], 'From'['brightCyan'], 'Subject'['brightCyan']]);
78
+ for (const emailTemplate of emailTemplates) {
79
+ table.push([
80
+ // Id
81
+ `${emailTemplate._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '')}`,
82
+ // Name
83
+ `${emailTemplate.displayName ? emailTemplate.displayName : ''}`,
84
+ // Status
85
+ emailTemplate.enabled === false ? 'disabled'['brightRed'] : 'enabled'['brightGreen'],
86
+ // Locale(s)
87
+ `${emailTemplate.defaultLocale}${Object.keys(emailTemplate.subject).length > 1 ? ` (${Object.keys(emailTemplate.subject).filter(locale => locale !== emailTemplate.defaultLocale).join(',')})` : ''}`,
88
+ // From
89
+ `${emailTemplate.from ? emailTemplate.from : ''}`,
90
+ // Subject
91
+ wordwrap(emailTemplate.subject[emailTemplate.defaultLocale], 40)]);
92
+ }
93
+ printMessage(table.toString(), 'data');
94
+ }
95
+ return emailTemplates;
96
+ }
97
+
98
+ /**
99
+ * Export single email template to a file
100
+ * @param {string} templateId email template id to export
101
+ * @param {string} file filename where to export the template data
102
+ */
103
+ export async function exportEmailTemplateToFile(templateId, file) {
104
+ let fileName = file;
105
+ if (!fileName) {
106
+ fileName = getTypedFilename(templateId, EMAIL_TEMPLATE_FILE_TYPE);
107
+ }
108
+ createProgressIndicator('determinate', 1, `Exporting ${templateId}`);
109
+ try {
110
+ const templateData = await getEmailTemplate(templateId);
111
+ updateProgressIndicator(`Writing file ${fileName}`);
112
+ const fileData = getFileDataTemplate();
113
+ fileData.emailTemplate[templateId] = templateData;
114
+ saveJsonToFile(fileData, fileName);
115
+ stopProgressIndicator(`Exported ${templateId['brightCyan']} to ${fileName['brightCyan']}.`);
116
+ } catch (err) {
117
+ stopProgressIndicator(`${err}`);
118
+ printMessage(err, 'error');
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Export all email templates to file
124
+ * @param {String} file optional filename
125
+ */
126
+ export async function exportEmailTemplatesToFile(file) {
127
+ let fileName = file;
128
+ if (!fileName) {
129
+ fileName = getTypedFilename(`allEmailTemplates`, EMAIL_TEMPLATE_FILE_TYPE);
130
+ }
131
+ try {
132
+ const fileData = getFileDataTemplate();
133
+ const response = await getEmailTemplates();
134
+ const templates = response.result;
135
+ createProgressIndicator('determinate', response.resultCount, 'Exporting email templates');
136
+ for (const template of templates) {
137
+ const templateId = template._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '');
138
+ updateProgressIndicator(`Exporting ${templateId}`);
139
+ fileData.emailTemplate[templateId] = template;
140
+ }
141
+ saveJsonToFile(fileData, fileName);
142
+ stopProgressIndicator(`${response.resultCount} templates exported to ${fileName}.`);
143
+ } catch (err) {
144
+ stopProgressIndicator(`${err}`);
145
+ printMessage(err, 'error');
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Export all email templates to separate files
151
+ */
152
+ export async function exportEmailTemplatesToFiles() {
153
+ try {
154
+ const response = await getEmailTemplates();
155
+ const templates = response.result;
156
+ createProgressIndicator('determinate', response.resultCount, 'Exporting email templates');
157
+ for (const template of templates) {
158
+ const templateId = template._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '');
159
+ const fileName = getTypedFilename(templateId, EMAIL_TEMPLATE_FILE_TYPE);
160
+ const fileData = getFileDataTemplate();
161
+ updateProgressIndicator(`Exporting ${templateId}`);
162
+ fileData.emailTemplate[templateId] = template;
163
+ saveJsonToFile(fileData, fileName);
164
+ }
165
+ stopProgressIndicator(`${response.resultCount} templates exported.`);
166
+ } catch (err) {
167
+ stopProgressIndicator(`${err}`);
168
+ printMessage(err, 'error');
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Import email template by id from file
174
+ * @param {String} templateId email template id
175
+ * @param {String} file optional filename
176
+ */
177
+ export async function importEmailTemplateFromFile(templateId, file) {
178
+ // eslint-disable-next-line no-param-reassign
179
+ templateId = templateId.replaceAll(`${EMAIL_TEMPLATE_TYPE}/`, '');
180
+ fs.readFile(file, 'utf8', async (err, data) => {
181
+ if (err) throw err;
182
+ const fileData = JSON.parse(data);
183
+ if (validateImport(fileData.meta)) {
184
+ createProgressIndicator('determinate', 1, `Importing ${templateId}`);
185
+ if (fileData.emailTemplate[templateId]) {
186
+ try {
187
+ await putEmailTemplate(templateId, fileData.emailTemplate[templateId]);
188
+ updateProgressIndicator(`Importing ${templateId}`);
189
+ stopProgressIndicator(`Imported ${templateId}`);
190
+ } catch (putEmailTemplateError) {
191
+ stopProgressIndicator(`${putEmailTemplateError}`);
192
+ printMessage(putEmailTemplateError, 'error');
193
+ }
194
+ } else {
195
+ stopProgressIndicator(`Email template ${templateId.brightCyan} not found in ${file.brightCyan}!`);
196
+ printMessage(`Email template ${templateId.brightCyan} not found in ${file.brightCyan}!`, 'error');
197
+ }
198
+ } else {
199
+ printMessage('Import validation failed...', 'error');
200
+ }
201
+ });
202
+ }
203
+
204
+ /**
205
+ * Import all email templates from file
206
+ * @param {String} file optional filename
207
+ */
208
+ export async function importEmailTemplatesFromFile(file) {
209
+ fs.readFile(file, 'utf8', async (err, data) => {
210
+ if (err) throw err;
211
+ const fileData = JSON.parse(data);
212
+ if (validateImport(fileData.meta)) {
213
+ createProgressIndicator('determinate', Object.keys(fileData.emailTemplate).length, `Importing email templates`);
214
+ for (const id in fileData.emailTemplate) {
215
+ if ({}.hasOwnProperty.call(fileData.emailTemplate, id)) {
216
+ const templateId = id.replace(regexEmailTemplateType, '');
217
+ try {
218
+ // eslint-disable-next-line no-await-in-loop
219
+ await putEmailTemplate(templateId, fileData.emailTemplate[templateId]);
220
+ updateProgressIndicator(`Imported ${templateId}`);
221
+ } catch (putEmailTemplateError) {
222
+ printMessage(`\nError importing ${templateId}`, 'error');
223
+ printMessage(putEmailTemplateError.response.data, 'error');
224
+ }
225
+ }
226
+ }
227
+ stopProgressIndicator(`Done.`);
228
+ } else {
229
+ printMessage('Import validation failed...', 'error');
230
+ }
231
+ });
232
+ }
233
+
234
+ /**
235
+ * Import all email templates from separate files
236
+ */
237
+ export async function importEmailTemplatesFromFiles() {
238
+ const names = fs.readdirSync('.');
239
+ const jsonFiles = names.filter(name => name.toLowerCase().endsWith(`${EMAIL_TEMPLATE_FILE_TYPE}.json`));
240
+ createProgressIndicator('determinate', jsonFiles.length, 'Importing email templates...');
241
+ let total = 0;
242
+ let totalErrors = 0;
243
+ for (const file of jsonFiles) {
244
+ const data = fs.readFileSync(file, 'utf8');
245
+ const fileData = JSON.parse(data);
246
+ if (validateImport(fileData.meta)) {
247
+ total += Object.keys(fileData.emailTemplate).length;
248
+ let errors = 0;
249
+ for (const id in fileData.emailTemplate) {
250
+ if ({}.hasOwnProperty.call(fileData.emailTemplate, id)) {
251
+ const templateId = id.replace(regexEmailTemplateType, '');
252
+ try {
253
+ // eslint-disable-next-line no-await-in-loop
254
+ await putEmailTemplate(templateId, fileData.emailTemplate[templateId]);
255
+ } catch (putEmailTemplateError) {
256
+ errors += 1;
257
+ printMessage(`\nError importing ${templateId}`, 'error');
258
+ printMessage(putEmailTemplateError.response.data, 'error');
259
+ }
260
+ }
261
+ }
262
+ totalErrors += errors;
263
+ updateProgressIndicator(`Imported ${file}`);
264
+ } else {
265
+ printMessage(`Validation of ${file} failed!`, 'error');
266
+ }
267
+ }
268
+ stopProgressIndicator(`Imported ${total - totalErrors} of ${total} email template(s) from ${jsonFiles.length} file(s).`);
269
+ }
270
+
271
+ /**
272
+ * Import first email template from file
273
+ * @param {String} file optional filename
274
+ */
275
+ export async function importFirstEmailTemplateFromFile(file) {
276
+ fs.readFile(file, 'utf8', async (err, data) => {
277
+ if (err) throw err;
278
+ const fileData = JSON.parse(data);
279
+ if (validateImport(fileData.meta)) {
280
+ createProgressIndicator('determinate', 1, `Importing first email template`);
281
+ for (const id in fileData.emailTemplate) {
282
+ if ({}.hasOwnProperty.call(fileData.emailTemplate, id)) {
283
+ try {
284
+ await putEmailTemplate(id.replace(regexEmailTemplateType, ''), fileData.emailTemplate[id]);
285
+ updateProgressIndicator(`Imported ${id}`);
286
+ stopProgressIndicator(`Imported ${id}`);
287
+ } catch (putEmailTemplateError) {
288
+ stopProgressIndicator(`Error importing email template ${id}`);
289
+ printMessage(`\nError importing email template ${id}`, 'error');
290
+ printMessage(putEmailTemplateError.response.data, 'error');
291
+ }
292
+ break;
293
+ }
294
+ }
295
+ } else {
296
+ printMessage('Import validation failed...', 'error');
297
+ }
298
+ });
299
+ }
35
300
  //# sourceMappingURL=EmailTemplateOps.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"EmailTemplateOps.js","names":["EmailTemplateRaw","getOneLineDescription","templateObj","description","_id","split","displayName","defaultLocale","subject","Object","values","getTableHeaderMd","markdown","getTableRowMd","templateId","replace","EMAIL_TEMPLATE_TYPE","locales","keys","length","filter","locale","join","row","name"],"sources":["ops/EmailTemplateOps.ts"],"sourcesContent":["import { EmailTemplateSkeleton } from '@rockcarver/frodo-lib/types/api/ApiTypes';\nimport { EmailTemplateRaw } from '@rockcarver/frodo-lib';\n\n/**\n * Get a one-line description of the email template\n * @param {EmailTemplateSkeleton} templateObj email template object to describe\n * @returns {string} a one-line description\n */\nexport function getOneLineDescription(\n templateObj: EmailTemplateSkeleton\n): string {\n const description = `[${templateObj._id.split('/')[1]['brightCyan']}] ${\n templateObj.displayName ? templateObj.displayName : ''\n } - ${\n templateObj.defaultLocale\n ? templateObj.subject[templateObj.defaultLocale]\n : Object.values(templateObj.subject)[0]\n }`;\n return description;\n}\n\n/**\n * Get markdown table header\n * @returns {string} markdown table header\n */\nexport function getTableHeaderMd(): string {\n let markdown = '';\n markdown += '| Display Name | Locale(s) | Subject | Id |\\n';\n markdown += '| ------------ | --------- | ------- | ---|';\n return markdown;\n}\n\n/**\n * Get a table-row of the email template in markdown\n * @param {EmailTemplateSkeleton} templateObj email template object to describe\n * @returns {string} a table-row of the email template in markdown\n */\nexport function getTableRowMd(templateObj: EmailTemplateSkeleton): string {\n const templateId = templateObj._id.replace(\n `${EmailTemplateRaw.EMAIL_TEMPLATE_TYPE}/`,\n ''\n );\n const locales = `${templateObj.defaultLocale}${\n Object.keys(templateObj.subject).length > 1\n ? ` (${Object.keys(templateObj.subject)\n .filter((locale) => locale !== templateObj.defaultLocale)\n .join(',')})`\n : ''\n }`;\n const row = `| ${\n templateObj.name ? templateObj.name : templateId\n } | ${locales} | ${\n templateObj.subject[templateObj.defaultLocale]\n } | \\`${templateId}\\` |`;\n return row;\n}\n"],"mappings":"AACA,SAASA,gBAAgB,QAAQ,uBAAuB;;AAExD;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqB,CACnCC,WAAkC,EAC1B;EACR,MAAMC,WAAW,GAAI,IAAGD,WAAW,CAACE,GAAG,CAACC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,CAAE,KAClEH,WAAW,CAACI,WAAW,GAAGJ,WAAW,CAACI,WAAW,GAAG,EACrD,MACCJ,WAAW,CAACK,aAAa,GACrBL,WAAW,CAACM,OAAO,CAACN,WAAW,CAACK,aAAa,CAAC,GAC9CE,MAAM,CAACC,MAAM,CAACR,WAAW,CAACM,OAAO,CAAC,CAAC,CAAC,CACzC,EAAC;EACF,OAAOL,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASQ,gBAAgB,GAAW;EACzC,IAAIC,QAAQ,GAAG,EAAE;EACjBA,QAAQ,IAAI,+CAA+C;EAC3DA,QAAQ,IAAI,6CAA6C;EACzD,OAAOA,QAAQ;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAa,CAACX,WAAkC,EAAU;EACxE,MAAMY,UAAU,GAAGZ,WAAW,CAACE,GAAG,CAACW,OAAO,CACvC,GAAEf,gBAAgB,CAACgB,mBAAoB,GAAE,EAC1C,EAAE,CACH;EACD,MAAMC,OAAO,GAAI,GAAEf,WAAW,CAACK,aAAc,GAC3CE,MAAM,CAACS,IAAI,CAAChB,WAAW,CAACM,OAAO,CAAC,CAACW,MAAM,GAAG,CAAC,GACtC,KAAIV,MAAM,CAACS,IAAI,CAAChB,WAAW,CAACM,OAAO,CAAC,CAClCY,MAAM,CAAEC,MAAM,IAAKA,MAAM,KAAKnB,WAAW,CAACK,aAAa,CAAC,CACxDe,IAAI,CAAC,GAAG,CAAE,GAAE,GACf,EACL,EAAC;EACF,MAAMC,GAAG,GAAI,KACXrB,WAAW,CAACsB,IAAI,GAAGtB,WAAW,CAACsB,IAAI,GAAGV,UACvC,MAAKG,OAAQ,MACZf,WAAW,CAACM,OAAO,CAACN,WAAW,CAACK,aAAa,CAC9C,QAAOO,UAAW,MAAK;EACxB,OAAOS,GAAG;AACZ"}
1
+ {"version":3,"file":"EmailTemplateOps.js","names":["fs","EmailTemplate","ExportImportUtils","getTypedFilename","saveJsonToFile","createProgressIndicator","updateProgressIndicator","stopProgressIndicator","printMessage","createTable","wordwrap","EMAIL_TEMPLATE_FILE_TYPE","EMAIL_TEMPLATE_TYPE","getEmailTemplate","getEmailTemplates","putEmailTemplate","validateImport","regexEmailTemplateType","RegExp","getFileDataTemplate","meta","emailTemplate","getOneLineDescription","templateObj","description","_id","split","displayName","defaultLocale","subject","Object","values","getTableHeaderMd","markdown","getTableRowMd","templateId","replace","locales","keys","length","filter","locale","join","row","name","listEmailTemplates","long","emailTemplates","result","error","message","sort","a","b","localeCompare","entries","table","push","enabled","from","toString","exportEmailTemplateToFile","file","fileName","templateData","fileData","err","exportEmailTemplatesToFile","response","templates","resultCount","template","exportEmailTemplatesToFiles","importEmailTemplateFromFile","replaceAll","readFile","data","JSON","parse","putEmailTemplateError","brightCyan","importEmailTemplatesFromFile","id","hasOwnProperty","call","importEmailTemplatesFromFiles","names","readdirSync","jsonFiles","toLowerCase","endsWith","total","totalErrors","readFileSync","errors","importFirstEmailTemplateFromFile"],"sources":["ops/EmailTemplateOps.ts"],"sourcesContent":["import fs from 'fs';\nimport { EmailTemplateSkeleton } from '@rockcarver/frodo-lib/types/api/ApiTypes';\nimport { EmailTemplate, ExportImportUtils } from '@rockcarver/frodo-lib';\nimport { getTypedFilename, saveJsonToFile } from '../utils/ExportImportUtils';\nimport {\n createProgressIndicator,\n updateProgressIndicator,\n stopProgressIndicator,\n printMessage,\n createTable,\n} from '../utils/Console';\nimport wordwrap from './utils/Wordwrap';\n\nconst EMAIL_TEMPLATE_FILE_TYPE = 'template.email';\nconst {\n EMAIL_TEMPLATE_TYPE,\n getEmailTemplate,\n getEmailTemplates,\n putEmailTemplate,\n} = EmailTemplate;\nconst { validateImport } = ExportImportUtils;\n\nconst regexEmailTemplateType = new RegExp(`${EMAIL_TEMPLATE_TYPE}/`, 'g');\n\n// use a function vs a template variable to avoid problems in loops\nfunction getFileDataTemplate() {\n return {\n meta: {},\n emailTemplate: {},\n };\n}\n\n/**\n * Get a one-line description of the email template\n * @param {EmailTemplateSkeleton} templateObj email template object to describe\n * @returns {string} a one-line description\n */\nexport function getOneLineDescription(\n templateObj: EmailTemplateSkeleton\n): string {\n const description = `[${templateObj._id.split('/')[1]['brightCyan']}] ${\n templateObj.displayName ? templateObj.displayName : ''\n } - ${\n templateObj.defaultLocale\n ? templateObj.subject[templateObj.defaultLocale]\n : Object.values(templateObj.subject)[0]\n }`;\n return description;\n}\n\n/**\n * Get markdown table header\n * @returns {string} markdown table header\n */\nexport function getTableHeaderMd(): string {\n let markdown = '';\n markdown += '| Display Name | Locale(s) | Subject | Id |\\n';\n markdown += '| ------------ | --------- | ------- | ---|';\n return markdown;\n}\n\n/**\n * Get a table-row of the email template in markdown\n * @param {EmailTemplateSkeleton} templateObj email template object to describe\n * @returns {string} a table-row of the email template in markdown\n */\nexport function getTableRowMd(templateObj: EmailTemplateSkeleton): string {\n const templateId = templateObj._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '');\n const locales = `${templateObj.defaultLocale}${\n Object.keys(templateObj.subject).length > 1\n ? ` (${Object.keys(templateObj.subject)\n .filter((locale) => locale !== templateObj.defaultLocale)\n .join(',')})`\n : ''\n }`;\n const row = `| ${\n templateObj.name ? templateObj.name : templateId\n } | ${locales} | ${\n templateObj.subject[templateObj.defaultLocale]\n } | \\`${templateId}\\` |`;\n return row;\n}\n\n/**\n * List email templates\n * @param {boolean} long Long list format with details\n * @return {Promise<unknown[]>} a promise that resolves to an array of email template objects\n */\nexport async function listEmailTemplates(long = false): Promise<unknown[]> {\n let emailTemplates = [];\n try {\n emailTemplates = (await getEmailTemplates()).result;\n } catch (error) {\n printMessage(`Error retrieving email templates: ${error.message}`, 'error');\n }\n emailTemplates.sort((a, b) => a._id.localeCompare(b._id));\n if (!long) {\n for (const [, emailTemplate] of emailTemplates.entries()) {\n printMessage(\n `${emailTemplate._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '')}`,\n 'data'\n );\n }\n } else {\n const table = createTable([\n 'Id'['brightCyan'],\n 'Name'['brightCyan'],\n 'Status'['brightCyan'],\n 'Locale(s)'['brightCyan'],\n 'From'['brightCyan'],\n 'Subject'['brightCyan'],\n ]);\n for (const emailTemplate of emailTemplates) {\n table.push([\n // Id\n `${emailTemplate._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '')}`,\n // Name\n `${emailTemplate.displayName ? emailTemplate.displayName : ''}`,\n // Status\n emailTemplate.enabled === false\n ? 'disabled'['brightRed']\n : 'enabled'['brightGreen'],\n // Locale(s)\n `${emailTemplate.defaultLocale}${\n Object.keys(emailTemplate.subject).length > 1\n ? ` (${Object.keys(emailTemplate.subject)\n .filter((locale) => locale !== emailTemplate.defaultLocale)\n .join(',')})`\n : ''\n }`,\n // From\n `${emailTemplate.from ? emailTemplate.from : ''}`,\n // Subject\n wordwrap(emailTemplate.subject[emailTemplate.defaultLocale], 40),\n ]);\n }\n printMessage(table.toString(), 'data');\n }\n return emailTemplates;\n}\n\n/**\n * Export single email template to a file\n * @param {string} templateId email template id to export\n * @param {string} file filename where to export the template data\n */\nexport async function exportEmailTemplateToFile(\n templateId: string,\n file: string\n) {\n let fileName = file;\n if (!fileName) {\n fileName = getTypedFilename(templateId, EMAIL_TEMPLATE_FILE_TYPE);\n }\n createProgressIndicator('determinate', 1, `Exporting ${templateId}`);\n try {\n const templateData = await getEmailTemplate(templateId);\n updateProgressIndicator(`Writing file ${fileName}`);\n const fileData = getFileDataTemplate();\n fileData.emailTemplate[templateId] = templateData;\n saveJsonToFile(fileData, fileName);\n stopProgressIndicator(\n `Exported ${templateId['brightCyan']} to ${fileName['brightCyan']}.`\n );\n } catch (err) {\n stopProgressIndicator(`${err}`);\n printMessage(err, 'error');\n }\n}\n\n/**\n * Export all email templates to file\n * @param {String} file optional filename\n */\nexport async function exportEmailTemplatesToFile(file) {\n let fileName = file;\n if (!fileName) {\n fileName = getTypedFilename(`allEmailTemplates`, EMAIL_TEMPLATE_FILE_TYPE);\n }\n try {\n const fileData = getFileDataTemplate();\n const response = await getEmailTemplates();\n const templates = response.result;\n createProgressIndicator(\n 'determinate',\n response.resultCount,\n 'Exporting email templates'\n );\n for (const template of templates) {\n const templateId = template._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '');\n updateProgressIndicator(`Exporting ${templateId}`);\n fileData.emailTemplate[templateId] = template;\n }\n saveJsonToFile(fileData, fileName);\n stopProgressIndicator(\n `${response.resultCount} templates exported to ${fileName}.`\n );\n } catch (err) {\n stopProgressIndicator(`${err}`);\n printMessage(err, 'error');\n }\n}\n\n/**\n * Export all email templates to separate files\n */\nexport async function exportEmailTemplatesToFiles() {\n try {\n const response = await getEmailTemplates();\n const templates = response.result;\n createProgressIndicator(\n 'determinate',\n response.resultCount,\n 'Exporting email templates'\n );\n for (const template of templates) {\n const templateId = template._id.replace(`${EMAIL_TEMPLATE_TYPE}/`, '');\n const fileName = getTypedFilename(templateId, EMAIL_TEMPLATE_FILE_TYPE);\n const fileData = getFileDataTemplate();\n updateProgressIndicator(`Exporting ${templateId}`);\n fileData.emailTemplate[templateId] = template;\n saveJsonToFile(fileData, fileName);\n }\n stopProgressIndicator(`${response.resultCount} templates exported.`);\n } catch (err) {\n stopProgressIndicator(`${err}`);\n printMessage(err, 'error');\n }\n}\n\n/**\n * Import email template by id from file\n * @param {String} templateId email template id\n * @param {String} file optional filename\n */\nexport async function importEmailTemplateFromFile(templateId, file) {\n // eslint-disable-next-line no-param-reassign\n templateId = templateId.replaceAll(`${EMAIL_TEMPLATE_TYPE}/`, '');\n fs.readFile(file, 'utf8', async (err, data) => {\n if (err) throw err;\n const fileData = JSON.parse(data);\n if (validateImport(fileData.meta)) {\n createProgressIndicator('determinate', 1, `Importing ${templateId}`);\n if (fileData.emailTemplate[templateId]) {\n try {\n await putEmailTemplate(\n templateId,\n fileData.emailTemplate[templateId]\n );\n updateProgressIndicator(`Importing ${templateId}`);\n stopProgressIndicator(`Imported ${templateId}`);\n } catch (putEmailTemplateError) {\n stopProgressIndicator(`${putEmailTemplateError}`);\n printMessage(putEmailTemplateError, 'error');\n }\n } else {\n stopProgressIndicator(\n `Email template ${templateId.brightCyan} not found in ${file.brightCyan}!`\n );\n printMessage(\n `Email template ${templateId.brightCyan} not found in ${file.brightCyan}!`,\n 'error'\n );\n }\n } else {\n printMessage('Import validation failed...', 'error');\n }\n });\n}\n\n/**\n * Import all email templates from file\n * @param {String} file optional filename\n */\nexport async function importEmailTemplatesFromFile(file) {\n fs.readFile(file, 'utf8', async (err, data) => {\n if (err) throw err;\n const fileData = JSON.parse(data);\n if (validateImport(fileData.meta)) {\n createProgressIndicator(\n 'determinate',\n Object.keys(fileData.emailTemplate).length,\n `Importing email templates`\n );\n for (const id in fileData.emailTemplate) {\n if ({}.hasOwnProperty.call(fileData.emailTemplate, id)) {\n const templateId = id.replace(regexEmailTemplateType, '');\n try {\n // eslint-disable-next-line no-await-in-loop\n await putEmailTemplate(\n templateId,\n fileData.emailTemplate[templateId]\n );\n updateProgressIndicator(`Imported ${templateId}`);\n } catch (putEmailTemplateError) {\n printMessage(`\\nError importing ${templateId}`, 'error');\n printMessage(putEmailTemplateError.response.data, 'error');\n }\n }\n }\n stopProgressIndicator(`Done.`);\n } else {\n printMessage('Import validation failed...', 'error');\n }\n });\n}\n\n/**\n * Import all email templates from separate files\n */\nexport async function importEmailTemplatesFromFiles() {\n const names = fs.readdirSync('.');\n const jsonFiles = names.filter((name) =>\n name.toLowerCase().endsWith(`${EMAIL_TEMPLATE_FILE_TYPE}.json`)\n );\n createProgressIndicator(\n 'determinate',\n jsonFiles.length,\n 'Importing email templates...'\n );\n let total = 0;\n let totalErrors = 0;\n for (const file of jsonFiles) {\n const data = fs.readFileSync(file, 'utf8');\n const fileData = JSON.parse(data);\n if (validateImport(fileData.meta)) {\n total += Object.keys(fileData.emailTemplate).length;\n let errors = 0;\n for (const id in fileData.emailTemplate) {\n if ({}.hasOwnProperty.call(fileData.emailTemplate, id)) {\n const templateId = id.replace(regexEmailTemplateType, '');\n try {\n // eslint-disable-next-line no-await-in-loop\n await putEmailTemplate(\n templateId,\n fileData.emailTemplate[templateId]\n );\n } catch (putEmailTemplateError) {\n errors += 1;\n printMessage(`\\nError importing ${templateId}`, 'error');\n printMessage(putEmailTemplateError.response.data, 'error');\n }\n }\n }\n totalErrors += errors;\n updateProgressIndicator(`Imported ${file}`);\n } else {\n printMessage(`Validation of ${file} failed!`, 'error');\n }\n }\n stopProgressIndicator(\n `Imported ${total - totalErrors} of ${total} email template(s) from ${\n jsonFiles.length\n } file(s).`\n );\n}\n\n/**\n * Import first email template from file\n * @param {String} file optional filename\n */\nexport async function importFirstEmailTemplateFromFile(file) {\n fs.readFile(file, 'utf8', async (err, data) => {\n if (err) throw err;\n const fileData = JSON.parse(data);\n if (validateImport(fileData.meta)) {\n createProgressIndicator(\n 'determinate',\n 1,\n `Importing first email template`\n );\n for (const id in fileData.emailTemplate) {\n if ({}.hasOwnProperty.call(fileData.emailTemplate, id)) {\n try {\n await putEmailTemplate(\n id.replace(regexEmailTemplateType, ''),\n fileData.emailTemplate[id]\n );\n updateProgressIndicator(`Imported ${id}`);\n stopProgressIndicator(`Imported ${id}`);\n } catch (putEmailTemplateError) {\n stopProgressIndicator(`Error importing email template ${id}`);\n printMessage(`\\nError importing email template ${id}`, 'error');\n printMessage(putEmailTemplateError.response.data, 'error');\n }\n break;\n }\n }\n } else {\n printMessage('Import validation failed...', 'error');\n }\n });\n}\n"],"mappings":"AAAA,OAAOA,EAAE,MAAM,IAAI;AAEnB,SAASC,aAAa,EAAEC,iBAAiB,QAAQ,uBAAuB;AACxE,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,4BAA4B;AAC7E,SACEC,uBAAuB,EACvBC,uBAAuB,EACvBC,qBAAqB,EACrBC,YAAY,EACZC,WAAW,QACN,kBAAkB;AACzB,OAAOC,QAAQ,MAAM,kBAAkB;AAEvC,MAAMC,wBAAwB,GAAG,gBAAgB;AACjD,MAAM;EACJC,mBAAmB;EACnBC,gBAAgB;EAChBC,iBAAiB;EACjBC;AACF,CAAC,GAAGd,aAAa;AACjB,MAAM;EAAEe;AAAe,CAAC,GAAGd,iBAAiB;AAE5C,MAAMe,sBAAsB,GAAG,IAAIC,MAAM,CAAE,GAAEN,mBAAoB,GAAE,EAAE,GAAG,CAAC;;AAEzE;AACA,SAASO,mBAAmB,GAAG;EAC7B,OAAO;IACLC,IAAI,EAAE,CAAC,CAAC;IACRC,aAAa,EAAE,CAAC;EAClB,CAAC;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqB,CACnCC,WAAkC,EAC1B;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printMessage, createTable, createProgressIndicator, updateProgressIndicator, stopProgressIndicator } from '../utils/Console';
4
+ import { saveToFile, getTypedFilename } from '../utils/ExportImportUtils';
5
+ const {
6
+ getTheme,
7
+ getThemes,
8
+ getThemeByName,
9
+ putThemeByName,
10
+ putTheme,
11
+ putThemes,
12
+ deleteTheme,
13
+ deleteThemeByName,
14
+ deleteThemes
15
+ } = Theme;
16
+ const {
17
+ getRealmString,
18
+ validateImport
19
+ } = ExportImportUtils;
1
20
  /**
2
21
  * Get a one-line description of the theme
3
22
  * @param {ThemeSkeleton} themeObj theme object to describe
@@ -28,4 +47,314 @@ export function getTableRowMd(themeObj) {
28
47
  const row = `| ${themeObj.name} | ${themeObj.linkedTrees ? themeObj.linkedTrees.join(', ') : ''} | \`${themeObj._id}\` |`;
29
48
  return row;
30
49
  }
50
+
51
+ /**
52
+ * List all the themes
53
+ * @param {boolean} long Long version, more fields
54
+ */
55
+ export async function listThemes(long = false) {
56
+ const themeList = await getThemes();
57
+ themeList.sort((a, b) => a.name.localeCompare(b.name));
58
+ if (!long) {
59
+ themeList.forEach(theme => {
60
+ printMessage(`${theme.isDefault ? theme.name['brightCyan'] : theme.name}`, 'data');
61
+ });
62
+ } else {
63
+ const table = createTable(['Name'['brightCyan'], 'Id'['brightCyan'], 'Default'['brightCyan']]);
64
+ themeList.forEach(theme => {
65
+ table.push([`${theme.name}`, `${theme._id}`, `${theme.isDefault ? 'Yes'['brightGreen'] : ''}`]);
66
+ });
67
+ printMessage(table.toString(), 'data');
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Export theme by name to file
73
+ * @param {String} name theme name
74
+ * @param {String} file optional export file name
75
+ */
76
+ export async function exportThemeByName(name, file) {
77
+ let fileName = getTypedFilename(name, 'theme');
78
+ if (file) {
79
+ fileName = file;
80
+ }
81
+ createProgressIndicator('determinate', 1, `Exporting ${name}`);
82
+ try {
83
+ const themeData = await getThemeByName(name);
84
+ updateProgressIndicator(`Writing file ${fileName}`);
85
+ saveToFile('theme', [themeData], '_id', fileName);
86
+ stopProgressIndicator(`Successfully exported theme ${name}.`);
87
+ } catch (error) {
88
+ stopProgressIndicator(`${error.message}`);
89
+ printMessage(`${error.message}`, 'error');
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Export theme by uuid to file
95
+ * @param {String} id theme uuid
96
+ * @param {String} file optional export file name
97
+ */
98
+ export async function exportThemeById(id, file) {
99
+ let fileName = getTypedFilename(id, 'theme');
100
+ if (file) {
101
+ fileName = file;
102
+ }
103
+ createProgressIndicator('determinate', 1, `Exporting ${id}`);
104
+ try {
105
+ const themeData = await getTheme(id);
106
+ updateProgressIndicator(`Writing file ${fileName}`);
107
+ saveToFile('theme', [themeData], '_id', fileName);
108
+ stopProgressIndicator(`Successfully exported theme ${id}.`);
109
+ } catch (error) {
110
+ stopProgressIndicator(`${error.message}`);
111
+ printMessage(`${error.message}`, 'error');
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Export all themes to file
117
+ * @param {String} file optional export file name
118
+ */
119
+ export async function exportThemesToFile(file) {
120
+ let fileName = getTypedFilename(`all${getRealmString()}Themes`, 'theme');
121
+ if (file) {
122
+ fileName = file;
123
+ }
124
+ const allThemesData = await getThemes();
125
+ createProgressIndicator('determinate', allThemesData.length, 'Exporting themes');
126
+ for (const themeData of allThemesData) {
127
+ updateProgressIndicator(`Exporting theme ${themeData.name}`);
128
+ }
129
+ saveToFile('theme', allThemesData, '_id', fileName);
130
+ stopProgressIndicator(`${allThemesData.length} themes exported to ${fileName}.`);
131
+ }
132
+
133
+ /**
134
+ * Export all themes to separate files
135
+ */
136
+ export async function exportThemesToFiles() {
137
+ const allThemesData = await getThemes();
138
+ createProgressIndicator('determinate', allThemesData.length, 'Exporting themes');
139
+ for (const themeData of allThemesData) {
140
+ updateProgressIndicator(`Writing theme ${themeData.name}`);
141
+ const fileName = getTypedFilename(themeData.name, 'theme');
142
+ saveToFile('theme', themeData, '_id', fileName);
143
+ }
144
+ stopProgressIndicator(`${allThemesData.length} themes exported.`);
145
+ }
146
+
147
+ /**
148
+ * Import theme by name from file
149
+ * @param {String} name theme name
150
+ * @param {String} file import file name
151
+ */
152
+ export async function importThemeByName(name, file) {
153
+ fs.readFile(file, 'utf8', async (err, data) => {
154
+ if (err) throw err;
155
+ const themeData = JSON.parse(data);
156
+ if (validateImport(themeData.meta)) {
157
+ createProgressIndicator('determinate', 1, 'Importing theme...');
158
+ let found = false;
159
+ for (const id in themeData.theme) {
160
+ if ({}.hasOwnProperty.call(themeData.theme, id)) {
161
+ if (themeData.theme[id].name === name) {
162
+ found = true;
163
+ updateProgressIndicator(`Importing ${themeData.theme[id].name}`);
164
+ try {
165
+ await putThemeByName(name, themeData.theme[id]);
166
+ stopProgressIndicator(`Successfully imported theme ${name}.`);
167
+ } catch (error) {
168
+ stopProgressIndicator(`Error importing theme ${themeData.theme[id].name}: ${error.message}`);
169
+ printMessage(`Error importing theme ${themeData.theme[id].name}: ${error.message}`, 'error');
170
+ }
171
+ break;
172
+ }
173
+ }
174
+ }
175
+ if (!found) {
176
+ stopProgressIndicator(`Theme ${name} not found!`);
177
+ }
178
+ } else {
179
+ printMessage('Import validation failed...', 'error');
180
+ }
181
+ });
182
+ }
183
+
184
+ /**
185
+ * Import theme by uuid from file
186
+ * @param {String} id theme uuid
187
+ * @param {String} file import file name
188
+ */
189
+ export async function importThemeById(id, file) {
190
+ fs.readFile(file, 'utf8', async (err, data) => {
191
+ if (err) throw err;
192
+ const themeData = JSON.parse(data);
193
+ if (validateImport(themeData.meta)) {
194
+ createProgressIndicator('determinate', 1, 'Importing theme...');
195
+ let found = false;
196
+ for (const themeId in themeData.theme) {
197
+ if ({}.hasOwnProperty.call(themeData.theme, themeId)) {
198
+ if (themeId === id) {
199
+ found = true;
200
+ updateProgressIndicator(`Importing ${themeData.theme[themeId]._id}`);
201
+ try {
202
+ await putTheme(themeId, themeData.theme[themeId]);
203
+ stopProgressIndicator(`Successfully imported theme ${id}.`);
204
+ } catch (error) {
205
+ stopProgressIndicator(`Error importing theme ${themeData.theme[themeId]._id}: ${error.message}`);
206
+ printMessage(`Error importing theme ${themeData.theme[themeId]._id}: ${error.message}`, 'error');
207
+ }
208
+ break;
209
+ }
210
+ }
211
+ }
212
+ if (!found) {
213
+ stopProgressIndicator(`Theme ${id} not found!`);
214
+ }
215
+ } else {
216
+ printMessage('Import validation failed...', 'error');
217
+ }
218
+ });
219
+ }
220
+
221
+ /**
222
+ * Import all themes from single file
223
+ * @param {String} file import file name
224
+ */
225
+ export async function importThemesFromFile(file) {
226
+ fs.readFile(file, 'utf8', (err, data) => {
227
+ if (err) throw err;
228
+ const fileData = JSON.parse(data);
229
+ if (validateImport(fileData.meta)) {
230
+ createProgressIndicator('determinate', Object.keys(fileData.theme).length, 'Importing themes...');
231
+ for (const id in fileData.theme) {
232
+ if ({}.hasOwnProperty.call(fileData.theme, id)) {
233
+ updateProgressIndicator(`Importing ${fileData.theme[id].name}`);
234
+ }
235
+ }
236
+ putThemes(fileData.theme).then(result => {
237
+ if (result == null) {
238
+ stopProgressIndicator(`Error importing ${Object.keys(fileData.theme).length} themes!`);
239
+ printMessage(`Error importing ${Object.keys(fileData.theme).length} themes from ${file}`, 'error');
240
+ } else {
241
+ stopProgressIndicator(`Successfully imported ${Object.keys(fileData.theme).length} themes.`);
242
+ }
243
+ });
244
+ } else {
245
+ printMessage('Import validation failed...', 'error');
246
+ }
247
+ });
248
+ }
249
+
250
+ /**
251
+ * Import themes from separate files
252
+ */
253
+ export async function importThemesFromFiles() {
254
+ const names = fs.readdirSync('.');
255
+ const jsonFiles = names.filter(name => name.toLowerCase().endsWith('.theme.json'));
256
+ createProgressIndicator('determinate', jsonFiles.length, 'Importing themes...');
257
+ let fileData = null;
258
+ let count = 0;
259
+ let total = 0;
260
+ let files = 0;
261
+ for (const file of jsonFiles) {
262
+ const data = fs.readFileSync(file, 'utf8');
263
+ fileData = JSON.parse(data);
264
+ if (validateImport(fileData.meta)) {
265
+ count = Object.keys(fileData.theme).length;
266
+ // eslint-disable-next-line no-await-in-loop
267
+ const result = await putThemes(fileData.theme);
268
+ if (result == null) {
269
+ printMessage(`Error importing ${count} themes from ${file}`, 'error');
270
+ } else {
271
+ files += 1;
272
+ total += count;
273
+ updateProgressIndicator(`Imported ${count} theme(s) from ${file}`);
274
+ }
275
+ } else {
276
+ printMessage(`Validation of ${file} failed!`, 'error');
277
+ }
278
+ }
279
+ stopProgressIndicator(`Finished importing ${total} theme(s) from ${files} file(s).`);
280
+ }
281
+
282
+ /**
283
+ * Import first theme from file
284
+ * @param {String} file import file name
285
+ */
286
+ export async function importFirstThemeFromFile(file) {
287
+ fs.readFile(file, 'utf8', (err, data) => {
288
+ if (err) throw err;
289
+ const themeData = JSON.parse(data);
290
+ if (validateImport(themeData.meta)) {
291
+ createProgressIndicator('determinate', 1, 'Importing theme...');
292
+ for (const id in themeData.theme) {
293
+ if ({}.hasOwnProperty.call(themeData.theme, id)) {
294
+ updateProgressIndicator(`Importing ${themeData.theme[id].name}`);
295
+ putTheme(id, themeData.theme[id]).then(result => {
296
+ if (result == null) {
297
+ stopProgressIndicator(`Error importing theme ${themeData.theme[id].name}`);
298
+ printMessage(`Error importing theme ${themeData.theme[id].name}`, 'error');
299
+ } else {
300
+ stopProgressIndicator(`Successfully imported theme ${themeData.theme[id].name}`);
301
+ }
302
+ });
303
+ break;
304
+ }
305
+ }
306
+ } else {
307
+ printMessage('Import validation failed...', 'error');
308
+ }
309
+ });
310
+ }
311
+
312
+ /**
313
+ * Delete theme by id
314
+ * @param {String} id theme id
315
+ */
316
+ export async function deleteThemeCmd(id) {
317
+ createProgressIndicator('indeterminate', undefined, `Deleting ${id}...`);
318
+ try {
319
+ await deleteTheme(id);
320
+ stopProgressIndicator(`Deleted ${id}.`, 'success');
321
+ } catch (error) {
322
+ stopProgressIndicator(`Error: ${error.message}`, 'fail');
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Delete theme by name
328
+ * @param {String} name theme name
329
+ */
330
+ export async function deleteThemeByNameCmd(name) {
331
+ createProgressIndicator('indeterminate', undefined, `Deleting ${name}...`);
332
+ try {
333
+ await deleteThemeByName(name);
334
+ stopProgressIndicator(`Deleted ${name}.`, 'success');
335
+ } catch (error) {
336
+ stopProgressIndicator(`Error: ${error.message}`, 'fail');
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Delete all themes
342
+ */
343
+ export async function deleteAllThemes() {
344
+ createProgressIndicator('indeterminate', undefined, `Deleting all realm themes...`);
345
+ try {
346
+ await deleteThemes();
347
+ stopProgressIndicator(`Deleted all realm themes.`, 'success');
348
+ } catch (error) {
349
+ stopProgressIndicator(`Error: ${error.message}`, 'fail');
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Delete all themes
355
+ * @deprecated since version 0.14.0
356
+ */
357
+ export async function deleteThemesCmd() {
358
+ return deleteAllThemes();
359
+ }
31
360
  //# sourceMappingURL=ThemeOps.js.map