All files / src/store/modules emailTemplates.module.js

98.55% Statements 68/69
91.42% Branches 32/35
100% Functions 17/17
100% Lines 66/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  2x         13x                 2x     2x     2x     2x     2x     4x         3x 3x     7x 7x 7x   7x 1x 1x     6x 6x   6x 6x   6x   4x   4x 2x 2x 1x 1x 1x     4x   2x       2x   2x                   7x             4x 4x 4x   4x 2x 2x   2x 2x                   2x   2x       2x 2x                 2x   4x                 3x 3x 3x   3x 3x   1x 1x                   2x 2x     2x 2x 2x 2x                   3x         3x 2x 2x 2x 2x      
import { createErrorObject, getErrorMessage } from '../../utils/errorUtils';
import createLogger from '../../utils/logger';
import {
  EMAIL_TEMPLATES_ACT,
  EMAIL_TEMPLATES_GET,
  EMAIL_TEMPLATES_MUT,
  NOTIF_FQ,
} from '../types';
 
const log = createLogger('emailTemplates');
 
export default {
  namespaced: true,
  state() {
    return {
      list: [],
      loading: false,
      creating: false,
      error: null,
    };
  },
  mutations: {
    [EMAIL_TEMPLATES_MUT.set](state, items) {
      state.list = items || [];
    },
    [EMAIL_TEMPLATES_MUT.setLoading](state, val) {
      state.loading = !!val;
    },
    [EMAIL_TEMPLATES_MUT.setCreating](state, val) {
      state.creating = !!val;
    },
    [EMAIL_TEMPLATES_MUT.setError](state, errorObject) {
      state.error = errorObject || null;
    },
    [EMAIL_TEMPLATES_MUT.addEmailTemplate](state, template) {
      state.list = [template, ...state.list];
    },
    [EMAIL_TEMPLATES_MUT.removeEmailTemplate](state, templateId) {
      state.list = state.list.filter((t) => t.id !== templateId);
    },
  },
  actions: {
    [EMAIL_TEMPLATES_ACT.hydrate]({ commit }, initial = {}) {
      const ssr = initial.pageData?.emailTemplates;
      if (Array.isArray(ssr)) commit(EMAIL_TEMPLATES_MUT.set, ssr);
    },
    async [EMAIL_TEMPLATES_ACT.load]({ commit, dispatch }, { api, env }) {
      try {
        commit(EMAIL_TEMPLATES_MUT.setLoading, true);
        commit(EMAIL_TEMPLATES_MUT.setError, null);
 
        if (!env) {
          commit(EMAIL_TEMPLATES_MUT.set, []);
          return;
        }
 
        const params = new URLSearchParams();
        params.append('env', env);
 
        const url = `/api/email-templates?${params.toString()}`;
        log.info('Fetching email templates:', url);
 
        const { data: response } = await api.get(url);
 
        let templates = [];
 
        if (response.success !== undefined && response.data) {
          templates = response.data.templates || [];
        } else if (response.templates) {
          templates = response.templates;
        } else Eif (Array.isArray(response)) {
          templates = response;
        }
 
        commit(EMAIL_TEMPLATES_MUT.set, templates);
      } catch (e) {
        const errorObject = createErrorObject(
          e,
          'Failed to load email templates',
        );
        commit(EMAIL_TEMPLATES_MUT.setError, errorObject);
 
        dispatch(
          NOTIF_FQ.actions.showError,
          {
            message: errorObject.message,
            type: 'api_error',
            closable: true,
          },
          { root: true },
        );
      } finally {
        commit(EMAIL_TEMPLATES_MUT.setLoading, false);
      }
    },
    async [EMAIL_TEMPLATES_ACT.create](
      { commit, dispatch },
      { api, env, name },
    ) {
      try {
        commit(EMAIL_TEMPLATES_MUT.setCreating, true);
        commit(EMAIL_TEMPLATES_MUT.setError, null);
 
        const { data } = await api.post('/api/email-templates', { env, name });
        const payload = data.data || data;
        const template = payload.emailTemplate || payload;
 
        commit(EMAIL_TEMPLATES_MUT.addEmailTemplate, template);
        dispatch(
          NOTIF_FQ.actions.showSuccess,
          {
            message: `Email template "${template.name}" created successfully`,
            type: 'success',
            closable: true,
          },
          { root: true },
        );
 
        return template;
      } catch (e) {
        const errorObject = createErrorObject(
          e,
          'Failed to create email template',
        );
        commit(EMAIL_TEMPLATES_MUT.setError, errorObject);
        dispatch(
          NOTIF_FQ.actions.showError,
          {
            message: errorObject.message,
            type: 'api_error',
            closable: true,
          },
          { root: true },
        );
        return null;
      } finally {
        commit(EMAIL_TEMPLATES_MUT.setCreating, false);
      }
    },
    async [EMAIL_TEMPLATES_ACT.delete](
      { commit, dispatch },
      {
        api, env, id, name,
      },
    ) {
      try {
        commit(EMAIL_TEMPLATES_MUT.setLoading, true);
        commit(EMAIL_TEMPLATES_MUT.setError, null);
 
        const params = new URLSearchParams({ env });
        await api.delete(`/api/email-templates/${id}?${params.toString()}`);
 
        commit(EMAIL_TEMPLATES_MUT.removeEmailTemplate, id);
        dispatch(
          NOTIF_FQ.actions.showSuccess,
          {
            message: `Email template "${name}" deleted successfully`,
            type: 'success',
            closable: true,
          },
          { root: true },
        );
      } catch (e) {
        const status = e.response?.status || e.response?.data?.error?.status;
        const fallback = status === 409
          ? `Cannot delete "${name}" because it is currently in use by one or more targets`
          : 'Failed to delete email template';
        const errorObject = createErrorObject(e, fallback);
        Iif (status === 409) errorObject.message = fallback;
        commit(EMAIL_TEMPLATES_MUT.setError, errorObject);
        dispatch(
          NOTIF_FQ.actions.showError,
          {
            message: errorObject.message,
            type: 'api_error',
            closable: true,
          },
          { root: true },
        );
      } finally {
        commit(EMAIL_TEMPLATES_MUT.setLoading, false);
      }
    },
  },
  getters: {
    [EMAIL_TEMPLATES_GET.templates]: (s, _g, root) => (s.list?.length ? s.list : root.pageData?.emailTemplates || []),
    [EMAIL_TEMPLATES_GET.isLoading]: (s) => !!s.loading,
    [EMAIL_TEMPLATES_GET.isCreating]: (s) => !!s.creating,
    [EMAIL_TEMPLATES_GET.error]: (s) => s.error || null,
    [EMAIL_TEMPLATES_GET.errorMessage]: (s) => getErrorMessage(s.error),
  },
};