@flusys/nestjs-email 6.0.2 → 6.1.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.
Files changed (37) hide show
  1. package/cjs/controllers/email-config.controller.spec.js +85 -0
  2. package/cjs/controllers/email-send.controller.spec.js +139 -0
  3. package/cjs/controllers/email-template.controller.spec.js +89 -0
  4. package/cjs/docs/email-swagger.config.spec.js +62 -0
  5. package/cjs/entities/index.spec.js +18 -0
  6. package/cjs/modules/email.module.spec.js +142 -0
  7. package/cjs/providers/email-factory.service.spec.js +242 -0
  8. package/cjs/providers/email-provider.registry.spec.js +58 -0
  9. package/cjs/providers/mailgun-provider.spec.js +244 -0
  10. package/cjs/providers/sendgrid-provider.spec.js +346 -0
  11. package/cjs/providers/smtp-provider.js +12 -5
  12. package/cjs/providers/smtp-provider.spec.js +327 -0
  13. package/cjs/services/email-config.service.spec.js +69 -0
  14. package/cjs/services/email-datasource.provider.spec.js +135 -0
  15. package/cjs/services/email-provider-config.service.spec.js +247 -0
  16. package/cjs/services/email-send.service.spec.js +546 -0
  17. package/cjs/services/email-template.service.spec.js +257 -0
  18. package/cjs/utils/email-templates.util.spec.js +61 -0
  19. package/fesm/controllers/email-config.controller.spec.js +81 -0
  20. package/fesm/controllers/email-send.controller.spec.js +135 -0
  21. package/fesm/controllers/email-template.controller.spec.js +85 -0
  22. package/fesm/docs/email-swagger.config.spec.js +58 -0
  23. package/fesm/entities/index.spec.js +14 -0
  24. package/fesm/modules/email.module.spec.js +138 -0
  25. package/fesm/providers/email-factory.service.spec.js +238 -0
  26. package/fesm/providers/email-provider.registry.spec.js +54 -0
  27. package/fesm/providers/mailgun-provider.spec.js +240 -0
  28. package/fesm/providers/sendgrid-provider.spec.js +342 -0
  29. package/fesm/providers/smtp-provider.js +12 -5
  30. package/fesm/providers/smtp-provider.spec.js +282 -0
  31. package/fesm/services/email-config.service.spec.js +65 -0
  32. package/fesm/services/email-datasource.provider.spec.js +131 -0
  33. package/fesm/services/email-provider-config.service.spec.js +243 -0
  34. package/fesm/services/email-send.service.spec.js +542 -0
  35. package/fesm/services/email-template.service.spec.js +253 -0
  36. package/fesm/utils/email-templates.util.spec.js +57 -0
  37. package/package.json +3 -3
@@ -0,0 +1,253 @@
1
+ import { Test } from '@nestjs/testing';
2
+ import { UtilsService } from '@flusys/nestjs-shared/modules';
3
+ import { createMockDataSourceProvider, createMockRepository } from '@test-utils/mocks/repository.mock';
4
+ import { buildMockUser } from '@test-utils/mocks/logged-user.mock';
5
+ import { EmailTemplate, EmailTemplateWithCompany } from '../entities';
6
+ import { EmailConfigService } from './email-config.service';
7
+ import { EmailDataSourceProvider } from './email-datasource.provider';
8
+ import { EmailTemplateService } from './email-template.service';
9
+ function buildTemplate(overrides = {}) {
10
+ return {
11
+ id: 'template-uuid-1',
12
+ name: 'Welcome Email',
13
+ slug: 'welcome-email',
14
+ description: null,
15
+ subject: 'Welcome {{firstName}}!',
16
+ schema: {
17
+ fields: []
18
+ },
19
+ htmlContent: '<h1>Welcome {{firstName}}!</h1>',
20
+ textContent: 'Welcome {{firstName}}!',
21
+ schemaVersion: 1,
22
+ isActive: true,
23
+ isHtml: true,
24
+ createdAt: new Date(),
25
+ updatedAt: new Date(),
26
+ deletedAt: null,
27
+ createdById: null,
28
+ updatedById: null,
29
+ deletedById: null,
30
+ ...overrides
31
+ };
32
+ }
33
+ function buildQuery() {
34
+ return {
35
+ select: jest.fn().mockReturnThis(),
36
+ andWhere: jest.fn().mockReturnThis(),
37
+ orderBy: jest.fn().mockReturnThis()
38
+ };
39
+ }
40
+ describe('EmailTemplateService', ()=>{
41
+ let service;
42
+ let mockRepo;
43
+ let mockEmailConfig;
44
+ beforeEach(async ()=>{
45
+ mockRepo = createMockRepository();
46
+ const mockDataSourceProvider = createMockDataSourceProvider(mockRepo);
47
+ mockEmailConfig = {
48
+ isCompanyFeatureEnabled: jest.fn().mockReturnValue(false)
49
+ };
50
+ const module = await Test.createTestingModule({
51
+ providers: [
52
+ EmailTemplateService,
53
+ {
54
+ provide: 'CACHE_INSTANCE',
55
+ useValue: {}
56
+ },
57
+ {
58
+ provide: UtilsService,
59
+ useValue: {}
60
+ },
61
+ {
62
+ provide: EmailConfigService,
63
+ useValue: mockEmailConfig
64
+ },
65
+ {
66
+ provide: EmailDataSourceProvider,
67
+ useValue: mockDataSourceProvider
68
+ }
69
+ ]
70
+ }).compile();
71
+ service = await module.resolve(EmailTemplateService);
72
+ // convertSingleDtoToEntity accesses `this.repository` directly; normally it is
73
+ // lazily initialized by insert()/update() via ensureDataSourceRepository() first.
74
+ await service.ensureDataSourceRepository();
75
+ });
76
+ describe('resolveEntity', ()=>{
77
+ it('resolves the plain EmailTemplate entity when the company feature is disabled', ()=>{
78
+ expect(service.resolveEntity()).toBe(EmailTemplate);
79
+ });
80
+ it('resolves EmailTemplateWithCompany when the company feature is enabled', ()=>{
81
+ mockEmailConfig.isCompanyFeatureEnabled.mockReturnValue(true);
82
+ expect(service.resolveEntity()).toBe(EmailTemplateWithCompany);
83
+ });
84
+ });
85
+ describe('convertSingleDtoToEntity', ()=>{
86
+ it('creates a new entity (no schema-version bump) for an insert without id', async ()=>{
87
+ mockRepo.create.mockReturnValue({});
88
+ const entity = await service.convertSingleDtoToEntity({
89
+ name: 'Welcome',
90
+ slug: 'welcome',
91
+ subject: 'Hi {{name}}',
92
+ schema: {
93
+ fields: []
94
+ },
95
+ htmlContent: '<p>Hi {{name}}</p>'
96
+ }, buildMockUser());
97
+ expect(entity.schemaVersion).toBeUndefined();
98
+ expect(mockRepo.findOne).not.toHaveBeenCalled();
99
+ });
100
+ it('increments schemaVersion on update when the schema payload changed', async ()=>{
101
+ // convertSingleDtoToEntity (ApiService base) mutates the fetched row in place via
102
+ // Object.assign, and incrementSchemaVersionIfChanged re-fetches by id afterwards —
103
+ // so the mock must return a fresh clone per call, like a real repository would.
104
+ mockRepo.findOne.mockImplementation(async ()=>buildTemplate({
105
+ schema: {
106
+ fields: []
107
+ },
108
+ schemaVersion: 3
109
+ }));
110
+ const entity = await service.convertSingleDtoToEntity({
111
+ id: 'template-uuid-1',
112
+ schema: {
113
+ fields: [
114
+ {
115
+ name: 'x'
116
+ }
117
+ ]
118
+ }
119
+ }, buildMockUser());
120
+ expect(entity.schemaVersion).toBe(4);
121
+ });
122
+ it('does not increment schemaVersion on update when the schema payload is unchanged', async ()=>{
123
+ mockRepo.findOne.mockImplementation(async ()=>buildTemplate({
124
+ schema: {
125
+ fields: []
126
+ },
127
+ schemaVersion: 3
128
+ }));
129
+ const entity = await service.convertSingleDtoToEntity({
130
+ id: 'template-uuid-1',
131
+ schema: {
132
+ fields: []
133
+ }
134
+ }, buildMockUser());
135
+ expect(entity.schemaVersion).toBe(3);
136
+ });
137
+ it('does not touch schemaVersion when the update payload has no schema field', async ()=>{
138
+ const existing = buildTemplate({
139
+ schema: {
140
+ fields: []
141
+ },
142
+ schemaVersion: 3
143
+ });
144
+ mockRepo.findOne.mockResolvedValue(existing);
145
+ const entity = await service.convertSingleDtoToEntity({
146
+ id: 'template-uuid-1',
147
+ name: 'Renamed'
148
+ }, buildMockUser());
149
+ expect(entity.schemaVersion).toBe(3);
150
+ // ensureDataSourceRepository/findOne should only be hit once — by the base
151
+ // convertSingleDtoToEntity — not a second time by incrementSchemaVersionIfChanged.
152
+ expect(mockRepo.findOne).toHaveBeenCalledTimes(1);
153
+ });
154
+ it('attaches the current user companyId when the company feature is enabled', async ()=>{
155
+ mockEmailConfig.isCompanyFeatureEnabled.mockReturnValue(true);
156
+ mockRepo.create.mockReturnValue({});
157
+ const entity = await service.convertSingleDtoToEntity({
158
+ name: 'Welcome',
159
+ slug: 'welcome',
160
+ subject: 'Hi',
161
+ schema: {},
162
+ htmlContent: '<p/>'
163
+ }, buildMockUser({
164
+ companyId: 'company-uuid-7'
165
+ }));
166
+ expect(entity.companyId).toBe('company-uuid-7');
167
+ });
168
+ });
169
+ describe('getSelectQuery', ()=>{
170
+ it('selects the default whitelisted fields (without companyId) when company feature is disabled', async ()=>{
171
+ const query = buildQuery();
172
+ await service.getSelectQuery(query, buildMockUser());
173
+ const [selected] = query.select.mock.calls[0];
174
+ expect(selected).toEqual(expect.arrayContaining([
175
+ 'emailTemplate.id',
176
+ 'emailTemplate.name',
177
+ 'emailTemplate.slug',
178
+ 'emailTemplate.subject',
179
+ 'emailTemplate.htmlContent',
180
+ 'emailTemplate.textContent',
181
+ 'emailTemplate.schemaVersion',
182
+ 'emailTemplate.isActive',
183
+ 'emailTemplate.isHtml'
184
+ ]));
185
+ expect(selected).not.toContain('emailTemplate.companyId');
186
+ });
187
+ it('appends companyId to the default field list when company feature is enabled', async ()=>{
188
+ mockEmailConfig.isCompanyFeatureEnabled.mockReturnValue(true);
189
+ const query = buildQuery();
190
+ await service.getSelectQuery(query, buildMockUser());
191
+ const [selected] = query.select.mock.calls[0];
192
+ expect(selected).toContain('emailTemplate.companyId');
193
+ });
194
+ });
195
+ describe('getExtraManipulateQuery', ()=>{
196
+ it('applies the company filter and orders by createdAt DESC when company feature is enabled', async ()=>{
197
+ mockEmailConfig.isCompanyFeatureEnabled.mockReturnValue(true);
198
+ const query = buildQuery();
199
+ await service.getExtraManipulateQuery(query, {}, buildMockUser({
200
+ companyId: 'c-1'
201
+ }));
202
+ expect(query.andWhere).toHaveBeenCalledWith('emailTemplate.companyId = :companyId', {
203
+ companyId: 'c-1'
204
+ });
205
+ expect(query.orderBy).toHaveBeenCalledWith('emailTemplate.createdAt', 'DESC');
206
+ });
207
+ });
208
+ describe('findByIdDirect', ()=>{
209
+ it('returns the matching template', async ()=>{
210
+ const template = buildTemplate();
211
+ mockRepo.findOne.mockResolvedValue(template);
212
+ const result = await service.findByIdDirect('template-uuid-1');
213
+ expect(result).toBe(template);
214
+ expect(mockRepo.findOne).toHaveBeenCalledWith({
215
+ where: {
216
+ id: 'template-uuid-1'
217
+ }
218
+ });
219
+ });
220
+ });
221
+ describe('findBySlug', ()=>{
222
+ it('finds an active template by slug', async ()=>{
223
+ const template = buildTemplate();
224
+ mockRepo.findOne.mockResolvedValue(template);
225
+ const result = await service.findBySlug('welcome-email', buildMockUser());
226
+ expect(result).toBe(template);
227
+ expect(mockRepo.findOne).toHaveBeenCalledWith({
228
+ where: {
229
+ slug: 'welcome-email',
230
+ isActive: true
231
+ }
232
+ });
233
+ });
234
+ it('scopes the slug lookup to the current company when the company feature is enabled', async ()=>{
235
+ mockEmailConfig.isCompanyFeatureEnabled.mockReturnValue(true);
236
+ mockRepo.findOne.mockResolvedValue(null);
237
+ await service.findBySlug('welcome-email', buildMockUser({
238
+ companyId: 'company-uuid-3'
239
+ }));
240
+ expect(mockRepo.findOne).toHaveBeenCalledWith({
241
+ where: {
242
+ slug: 'welcome-email',
243
+ isActive: true,
244
+ companyId: 'company-uuid-3'
245
+ }
246
+ });
247
+ });
248
+ it('returns null when no template matches the slug', async ()=>{
249
+ mockRepo.findOne.mockResolvedValue(null);
250
+ await expect(service.findBySlug('missing-slug', buildMockUser())).resolves.toBeNull();
251
+ });
252
+ });
253
+ });
@@ -0,0 +1,57 @@
1
+ import { getOtpEmailFormat, getResetPasswordEmailFormat } from './email-templates.util';
2
+ describe('email-templates.util', ()=>{
3
+ describe('getOtpEmailFormat', ()=>{
4
+ it('renders the OTP inside the generated HTML document', ()=>{
5
+ const html = getOtpEmailFormat(123456, 'Jane');
6
+ expect(html).toContain('<!DOCTYPE html>');
7
+ expect(html).toContain('123456');
8
+ expect(html).toContain('Hi Jane,');
9
+ expect(html).toContain('Your OTP Code');
10
+ });
11
+ it('falls back to a generic greeting when userName is not provided', ()=>{
12
+ const html = getOtpEmailFormat(654321);
13
+ expect(html).toContain('Hi Sir/Madam,');
14
+ });
15
+ it('falls back to a generic greeting when userName is null', ()=>{
16
+ const html = getOtpEmailFormat(111111, null);
17
+ expect(html).toContain('Hi Sir/Madam,');
18
+ });
19
+ it('does not escape HTML special characters in userName (XSS caveat)', ()=>{
20
+ const html = getOtpEmailFormat(999999, '<script>alert(1)</script>');
21
+ // Documents CURRENT behavior: userName is interpolated verbatim, unescaped.
22
+ expect(html).toContain('<script>alert(1)</script>');
23
+ expect(html).not.toContain('&lt;script&gt;');
24
+ });
25
+ it('includes styling for the OTP action box', ()=>{
26
+ const html = getOtpEmailFormat(1, 'A');
27
+ expect(html).toContain('letter-spacing: 6px');
28
+ });
29
+ });
30
+ describe('getResetPasswordEmailFormat', ()=>{
31
+ it('renders the reset link as the href of the action button', ()=>{
32
+ const html = getResetPasswordEmailFormat('https://app.example.com/reset?token=abc', 'Bob');
33
+ expect(html).toContain('href="https://app.example.com/reset?token=abc"');
34
+ expect(html).toContain('Hi Bob,');
35
+ expect(html).toContain('Reset Your Password');
36
+ });
37
+ it('falls back to a generic greeting when userName is omitted', ()=>{
38
+ const html = getResetPasswordEmailFormat('https://app.example.com/reset?token=abc');
39
+ expect(html).toContain('Hi Sir/Madam,');
40
+ });
41
+ it('does not escape or validate the reset link (XSS/HTML-injection caveat)', ()=>{
42
+ const maliciousLink = '"><script>alert(1)</script>';
43
+ const html = getResetPasswordEmailFormat(maliciousLink, 'Bob');
44
+ // Documents CURRENT behavior: resetLink is interpolated verbatim, unescaped,
45
+ // allowing HTML attribute breakout if the value is attacker-influenced.
46
+ expect(html).toContain(`href="${maliciousLink}"`);
47
+ });
48
+ it('does not escape HTML special characters in userName', ()=>{
49
+ const html = getResetPasswordEmailFormat('https://x.test/reset', '<img src=x onerror=alert(1)>');
50
+ expect(html).toContain('<img src=x onerror=alert(1)>');
51
+ });
52
+ it('produces a single-line action-box style for the reset button', ()=>{
53
+ const html = getResetPasswordEmailFormat('https://x.test/reset', 'A');
54
+ expect(html).toContain('font-size: 16px');
55
+ });
56
+ });
57
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flusys/nestjs-email",
3
- "version": "6.0.2",
3
+ "version": "6.1.1",
4
4
  "description": "Modular email package with SMTP, SendGrid, and Mailgun providers",
5
5
  "main": "cjs/index.js",
6
6
  "module": "fesm/index.js",
@@ -105,7 +105,7 @@
105
105
  }
106
106
  },
107
107
  "dependencies": {
108
- "@flusys/nestjs-core": "6.0.2",
109
- "@flusys/nestjs-shared": "6.0.2"
108
+ "@flusys/nestjs-core": "6.1.1",
109
+ "@flusys/nestjs-shared": "6.1.1"
110
110
  }
111
111
  }