import { A as APIBase } from './kimlikApi-ac700c81.js';
import { n as notImplemented } from './utils-2c1db0af.js';
import { U as User } from './User-d2ee8b71.js';
import { g as getSessionData, a as getCookieStorage } from './index-ef2fbee6.js';
import { M as Membership } from './membership-821de3c5.js';
import { D as DataApiImpl } from './dataApi-8221972c.js';
import { V as ViewPlacement, A as AppConfig } from './app-config-d490f9ae.js';
import { M as MembershipConfig } from './membership-config-68ed7772.js';
import { s as spaces } from './spaces-c4b46e5e.js';
import { R as ReferenceField } from './index-ef734a5e.js';
import { D as DateField, a as DateDataType } from './date-ce777316.js';
import { d as dataConfigs, R as RawDataField, V as ValidatorRegex, a as RelationReferenceField, D as DvnDataAdapter, T as TableListViewConfig } from './table-list-view-config-ff8c1b78.js';
import { D as DetailViewConfig } from './detail-view-config-e2344d5e.js';
import { C as Comparison } from './filter-cbaa3d7d.js';
import { A as AppViewType } from './view-config-efdeed6d.js';
import { I as ImagePosition } from './models-22fcdeab.js';
import { D as DataTransferField } from './data-transfer-field-918730a3.js';
import { T as TextField } from './index-336ef773.js';
import { r as registerInterceptor, I as InterceptorConfig, a as InterceptorHandler } from './InterceptorHandler-6474bcf4.js';
import { F as FormViewConfig, M as ModifierTrimmer } from './form-view-config-fb04db06.js';
import { V as ValidatorLength } from './ValidatorLength-f56a7c14.js';
import { I as InvalidationAction } from './actions-b9a0f808.js';
import { c as createMentornityApiInstance } from './instance-fe40f49f.js';
import './index-a1675f50.js';
import { N as NestedField } from './nested-395a4cd4.js';
import { B as BooleanField } from './index-47dfc023.js';
import { S as SingleChoiceField, M as MultipleChoiceField, b as MultipleChoiceFieldOption, a as SingleChoiceFieldOption } from './index-0e8b9ea2.js';
import './index-c3eacf05.js';
import './data-model-f5160369.js';
import { L as ListFetchState } from './list-fetch-state-623a5ba4.js';
import { z as zoneConfig } from './time-zones-cf1e6113.js';
import { a as AttachmentField } from './attachment-32decf79.js';

class KimlikApiMentornity {
  constructor(endpoint, headers) {
    this.api = new APIBase(endpoint, headers);
  }
  activateUser(_email, _firstName, _lastName, _password) {
    return Promise.reject(notImplemented('KimlikApiMentornity.activateUser'));
  }
  addAuthInterceptor(token) {
    console.log('addAuthInterceptor', token);
  }
  login(email, password) {
    return new Promise(async (resolve) => {
      const response = await this.api.post('login', { email, password });
      resolve({ userId: response.user._id, jwt: response.accessToken });
    });
  }
  logout() {
    return Promise.resolve({});
  }
  register(_email, _firstName, _lastName, _password) {
    return Promise.reject(notImplemented('KimlikApiMentornity.register'));
  }
  getSession() {
    return new Promise(async (resolve) => {
      const user = await this.api.get(`users/${getSessionData().uid}`);
      resolve({ user: User.decode(user) });
    });
  }
}

const mentornityApiEndpoint = 'https://api.mentornity.com';
// export const mentornityApiEndpoint = 'http://localhost:1707';
const dataApiEndpoint = 'https://data.api.mentornity.com/prod/mentornity/';
// export const dataApiEndpoint = 'http://localhost:1003/mentornity/';

const membershipConfigs = {
  // mentees table
  'system-admins': MembershipConfig.decode({
    _id: 'system-admins',
    _created: new Date(),
    _updated: new Date(),
    agreements: [],
    base: 'mentornity',
    fields: [
      {
        type: 'reference',
        id: 'user',
        otherCollection: 'users',
        isSingle: true,
        fields: [
          {
            type: 'text',
            id: 'firstName'
          },
          {
            type: 'text',
            id: 'lastName'
          },
        ]
      },
    ],
    name: 'system-admins',
    roleName: 'System Admin',
    space: spaces['mentornity'],
  }),
};

const ID$p = 'detail-view-error-log';
const viewConfig$i = DetailViewConfig.decode({
  _id: ID$p,
  base: 'mentornity',
  space: spaces['mentornity'],
  table: dataConfigs['errorlogs'],
  title: 'Error Log',
  ui: {
    cardConfig: {
      body: {
        fields: [
          {
            fieldId: 'createdAt',
            fieldDisplay: new DateField('createdAt', 'Date').setDateFormat('DD.MM.YYYY HH:mm').setDataType(DateDataType.Unix),
          },
          {
            fieldId: 'user',
            fieldDisplay: new RawDataField('user._id', 'User ID'),
          },
          {
            fieldId: 'session',
            fieldDisplay: new RawDataField('session._id', 'Session ID'),
          },
          {
            fieldId: 'res',
          },
          {
            fieldId: 'status',
          },
          {
            fieldId: 'message',
          },
        ]
      },
    }
  },
  query: {
    filter: {
      comparison: Comparison.Eq,
      id: '_id',
      value: '$id',
    },
  },
  type: AppViewType.DetailViewCard,
  params: {
    id: {
      required: true,
    },
  },
});

class ModifierRegexCharRemover extends InterceptorConfig {
  constructor(regex) {
    super('modifierNonAlphanumericCharRemover');
    this.regex = regex;
  }
}
ModifierRegexCharRemover.id = 'modifierNonAlphanumericCharRemover';
class ModifierRegexCharRemoverHandler extends InterceptorHandler {
  constructor(config) {
    super();
    this.config = config;
  }
  run(_context, _values, _field, value) {
    if (typeof value === 'string' || value instanceof String) {
      return {
        value: value.replace(new RegExp(this.config.regex, "gm"), ''),
      };
    }
    return { value };
  }
}
registerInterceptor(ModifierRegexCharRemover.id, (config) => new ModifierRegexCharRemoverHandler(config));

class ChangeOrganisationDomainFormHandler {
  constructor() {
    const { jwt, sessionId } = getCookieStorage().getAll();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, {
      'Authorization': `Bearer ${jwt}`,
      'Client': 'd2ViLWFkbWlu',
      'Session-Token': sessionId,
    });
  }
  onSubmit(event) {
    const { values: { domain, organisationId } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.changeOrganisationDomain({ domain, organisationId }).then(() => {
        resolve({
          events: [
            new InvalidationAction(ID$o, ID$n),
            new InvalidationAction(ID$o, ID$5),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(error => {
        if (error.data && error.data.message === 'domain-already-exists') {
          reject(['Domain is already used by another program.']);
          return;
        }
        reject(['Unexpected error']);
      });
    });
  }
}

const ID$o = 'form-view-organisation-change-domain';
const viewConfig$h = FormViewConfig.decode({
  _id: ID$o,
  base: 'mentornity',
  title: 'Change Organisation Domain',
  space: spaces['mentornity'],
  table: dataConfigs['organisations'],
  type: AppViewType.FormView,
  handler: new ChangeOrganisationDomainFormHandler(),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new DataTransferField('organisationId'),
      },
      {
        field: new TextField('domain', 'New domain').addInterceptor('onBlur', new ModifierRegexCharRemover(' '))
          .addInterceptor('onSubmit', new ValidatorRegex('[a-z0-9\-]'))
          .addInterceptor('onSubmit', new ValidatorLength(2, 100))
          .addInterceptor('onSubmit', new ModifierTrimmer())
          .require(),
      },
    ],
  },
  params: {
    organisationId: {
      required: true,
    },
    domain: {
      required: true,
    },
  },
});

const ID$n = 'detail-view-organisation';
const viewConfig$g = DetailViewConfig.decode({
  _id: ID$n,
  base: 'mentornity',
  space: spaces['mentornity'],
  table: dataConfigs['organisations'],
  title: 'Organisation',
  ui: {
    cardConfig: {
      header: {
        actions: [{
            ui: {
              name: 'change-domain',
              buttonType: 'button',
              label: 'Change Domain',
              scale: 'medium',
              view: 'solid'
            },
            data: {
              type: 'navigation',
              viewId: ID$o,
              direction: 'forward',
              placement: ViewPlacement.Dialog,
              params: {
                conversionConfig: {
                  'item._id': 'organisationId',
                  'item.domain': 'domain',
                }
              }
            }
          }],
        cover: {
          fieldId: 'coverUrl',
          size: 256,
        },
        image: {
          fieldId: 'logoUrl',
          shape: 'rounded',
          size: 96,
          position: ImagePosition.Center,
        },
        title: {
          fieldId: 'title',
        },
      },
      body: {
        fields: [
          {
            fieldId: 'domain',
          },
          {
            fieldId: 'status',
          },
          {
            fieldId: 'model',
          },
          {
            fieldId: 'description',
            lines: 0,
          },
          {
            fieldId: 'createdAt',
          },
          {
            fieldId: 'webSiteUrl',
          },
          {
            fieldId: 'facebookUrl',
          },
          {
            fieldId: 'twitterUrl',
          },
          {
            fieldId: 'linkedInUrl',
          },
          {
            fieldId: '_id',
          },
        ]
      },
    }
  },
  type: AppViewType.DetailViewCard,
  params: {
    itemId: {
      required: true,
    },
  },
});

const ID$m = 'detail-view-form-response';
const viewConfig$f = DetailViewConfig.decode({
  _id: ID$m,
  base: 'mentornity',
  space: spaces['mentornity'],
  table: dataConfigs['formResponses'],
  title: 'Form Response',
  ui: {
    cardConfig: {
      body: {
        fields: [
          {
            fieldId: 'createdAt',
          },
          {
            fieldDisplay: new TextField('data.phone', 'Phone'),
          },
          {
            fieldDisplay: new TextField('data.email', 'Email'),
          },
          {
            fieldDisplay: new TextField('data.name', 'Name'),
          },
          {
            fieldDisplay: new TextField('data.message', 'Message'),
            lines: 0,
          },
        ]
      },
    }
  },
  type: AppViewType.DetailViewCard,
  params: {
    itemId: {
      required: true,
    },
  },
});

class EraseUserFormHandler {
  constructor() {
    const { jwt, sessionId } = getCookieStorage().getAll();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, {
      'Authorization': `Bearer ${jwt}`,
      'Client': 'd2ViLWFkbWlu',
      'Session-Token': sessionId,
    });
  }
  onSubmit(event) {
    const { values: { userId } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.eraseUser(userId).then(() => {
        resolve({
          events: [
            new InvalidationAction(ID$l, ID$k),
            new InvalidationAction(ID$l, ID$1),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

const ID$l = 'form-view-user-erase';
const viewConfig$e = FormViewConfig.decode({
  _id: ID$l,
  base: 'mentornity',
  title: 'Erasing User',
  space: spaces['mentornity'],
  table: dataConfigs['users'],
  type: AppViewType.FormView,
  handler: new EraseUserFormHandler(),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new DataTransferField('userId'),
      },
      {
        field: new BooleanField('confirmation', 'Erasure confirmation', 'Please confirm that you are aware of what you are doing. This action cannot be undone! All the user details and metadata are going to be erased and the user will receive a notification.').setErrorTitle('Confirmation').require(),
      },
    ],
  },
  params: {
    userId: {
      required: true,
    },
  },
});

const ID$k = 'detail-view-user';
const viewConfig$d = DetailViewConfig.decode({
  _id: ID$k,
  base: 'mentornity',
  space: spaces['mentornity'],
  table: dataConfigs['users'],
  title: 'User',
  ui: {
    cardConfig: {
      header: {
        actions: [{
            ui: {
              name: 'erase-user',
              buttonType: 'icon-button',
              iconName: 'uil uil-trash-alt',
              // label: 'Erase User',
              scale: 'medium',
              tint: 'danger',
              view: 'solid',
            },
            data: {
              type: 'navigation',
              viewId: ID$l,
              direction: 'forward',
              placement: ViewPlacement.Dialog,
              params: {
                conversionConfig: {
                  'item._id': 'userId',
                }
              }
            }
          }],
        cover: {
          // fieldId: 'coverUrl',
          size: 128,
        },
        image: {
          fieldId: 'imageUrl',
          shape: 'circle',
          size: 96,
          position: ImagePosition.Center,
        },
        // title: {
        //   fieldId: 'title',
        // },
      },
      body: {
        fields: [
          {
            fieldId: '_id',
          },
          {
            fieldId: '_roles',
          },
          {
            fieldId: 'email',
          },
          {
            fieldId: 'firstName',
          },
          {
            fieldId: 'lastName',
          },
          {
            fieldId: 'status',
          },
          {
            fieldId: 'createdAt',
          },
          {
            fieldId: 'lastSession.updatedAt',
            fieldDisplay: new NestedField('lastSession.updatedAt', new DateField('updatedAt', 'Last Session')
              .setDataType(DateDataType.Unix)
              .setDateFormat('DD MMM YYYY HH:mm')),
          },
          { fieldId: 'memberships' },
          // {
          //   fieldId: 'memberships',
          // },
          // {
          //   fieldId: 'lastSession',
          // },
        ]
      },
    }
  },
  type: AppViewType.DetailViewCard,
  query: {
    fields: [
      new DataTransferField('_roles'),
      new DateField('createdAt', 'Created At').setDataType(DateDataType.Unix).setDateFormat('DD MMM YYYY'),
      new AttachmentField('imageUrl', ''),
      new TextField('email', 'Email'),
      new TextField('firstName', 'First Name'),
      new TextField('lastName', 'Last Name'),
      new TextField('status', 'Status'),
      new RelationReferenceField('memberships', 'Programs', 'title', 'logoUrl', 'memberships', 'user', 'organisations', 'organisation', [
        new DataTransferField('status'),
        new DataTransferField('updatedBy')
      ], [
        new DataTransferField('logoUrl'),
        new DataTransferField('title'),
      ]),
      {
        type: 'reverse-reference',
        id: 'lastSession',
        otherCollection: 'sessions',
        nameInOtherCollection: 'user',
        isSingle: true,
        fields: [{ id: 'updatedAt' }, { id: 'createdAt' }],
        limit: 1,
        sort: {
          order: -1,
          id: 'updatedAt'
        }
      }
    ],
    filter: {
      comparison: Comparison.Eq,
      id: '_id',
      value: '$itemId',
    },
  },
  params: {
    itemId: {
      required: false,
    },
  },
});

const ID$j = 'detail-view-user-auth';
const viewConfig$c = DetailViewConfig.decode({
  _id: ID$j,
  base: 'mentornity',
  space: spaces['mentornity'],
  table: dataConfigs['auth'],
  title: 'User Auth',
  ui: {
    cardConfig: {
      body: {
        fields: [
          {
            fieldId: 'createdAt',
          },
          {
            fieldId: 'google',
          },
          {
            fieldId: 'microsoft',
          },
          {
            fieldId: 'zoom',
          },
        ]
      },
    }
  },
  query: {
    filter: {
      comparison: Comparison.Eq,
      id: 'user._id',
      value: '$userId',
    },
  },
  type: AppViewType.DetailViewCard,
  params: {
    userId: {
      required: true,
    },
  },
});

const ID$i = 'detail-view-scheduled-job-send-email';
const viewConfig$b = DetailViewConfig.decode({
  _id: ID$i,
  base: 'mentornity',
  space: spaces['mentornity'],
  table: dataConfigs['scheduledjobs'],
  title: 'Send Email Job',
  ui: {
    cardConfig: {
      body: {
        fields: [
          {
            fieldId: 'name',
          },
          {
            fieldId: 'createdAt',
          },
          {
            fieldId: 'status',
          },
          {
            fieldDisplay: new DateField('metadata.sent', 'Sent On').setDateFormat('DD MMM YYYY, HH:mm'),
          },
          {
            fieldDisplay: new DateField('metadata.delivered', 'Delivered On').setDateFormat('DD MMM YYYY, HH:mm'),
          },
          {
            fieldDisplay: new DateField('metadata.opened', 'Opened On').setDateFormat('DD MMM YYYY, HH:mm'),
          },
          {
            fieldDisplay: new DateField('metadata.clicked', 'Clicked On').setDateFormat('DD MMM YYYY, HH:mm'),
          },
          {
            fieldId: 'output',
          },
          {
            fieldId: 'parameters',
          },
        ]
      },
    }
  },
  type: AppViewType.DetailViewCard,
  params: {
    itemId: {
      required: true,
    },
  },
});

class AddOrganisationAdminFormHandler {
  constructor() {
    const { jwt, sessionId } = getCookieStorage().getAll();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, {
      'Authorization': `Bearer ${jwt}`,
      'Client': 'd2ViLWFkbWlu',
      'Session-Token': sessionId,
    });
  }
  onSubmit(event) {
    const { values: { organisationId, admin: email } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.importUser(organisationId, 'admins', {
        email,
        firstName: '',
        lastName: '',
        metadata: {},
      }).then(() => {
        resolve({
          events: [
            new InvalidationAction(ID$f, ID$6),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

function buildQuery(query, quickFilter) {
  let queryFilter = query ? query.filter : undefined;
  if (quickFilter) {
    if (query && query.filter) {
      queryFilter = {
        operator: 'and',
        filters: [query.filter, quickFilter]
      };
    }
    else {
      queryFilter = quickFilter;
    }
  }
  return queryFilter;
}
function generateQuickSearchFilters(quickSearch, filter) {
  if (!quickSearch || !filter) {
    return undefined;
  }
  return {
    operator: 'or',
    filters: quickSearch.fields.map(field => ({
      comparison: Comparison.Contain,
      id: field.fieldId,
      value: filter,
    }))
  };
}
class DvnDataProvider {
  constructor(dataApi, collection, query, initialData, quickSearch) {
    this.didQuickSearchChangeAfterLastFetch = false;
    this.list = ListFetchState.init();
    this.collection = collection;
    this.query = query;
    this.initialData = initialData;
    this.quickSearch = quickSearch;
    this.api = dataApi;
  }
  getInitialData() {
    return this.initialData;
  }
  getData() {
    const { api, collection, query, quickSearchText } = this;
    const self = this;
    return new Promise(((resolve, reject) => {
      if (self.list.data && !this.didQuickSearchChangeAfterLastFetch) {
        // return already fetched data
        resolve(self.list.data);
        return;
      }
      const queryFilter = buildQuery(query, generateQuickSearchFilters(this.quickSearch, quickSearchText));
      api.query(collection, {
        fields: query.fields,
        filter: queryFilter,
        limit: 50,
        skip: 0,
        sort: query.sort,
      }).then(response => {
        self.list = ListFetchState.init().afterFetch(response);
        this.didQuickSearchChangeAfterLastFetch = false;
        resolve(self.list.data);
      }, error => {
        self.list = ListFetchState.init().afterFetchError(error);
        reject(error);
      });
    }));
  }
  setInitialData(initialData) {
    this.initialData = initialData;
  }
  setQuickSearchText(text) {
    this.quickSearchText = text;
    this.didQuickSearchChangeAfterLastFetch = true;
  }
  getQuickSearchText() {
    return this.quickSearchText;
  }
  isQuickSearchEnabled() {
    return !!this.quickSearch;
  }
}

const userDataProvider = (dataApi) => new DvnDataProvider(dataApi, 'users', {
  fields: [
    new TextField('email', ''),
    new TextField('firstName', ''),
    new TextField('lastName', ''),
    new TextField('status', ''),
  ],
  filter: {
    filters: [
      {
        comparison: Comparison.Eq,
        id: 'status',
        value: 'active',
      },
      {
        comparison: Comparison.Ne,
        id: 'lastName',
        value: '   ',
      },
      {
        comparison: Comparison.Ne,
        id: 'lastName',
        value: '   ',
      },
    ],
    operator: 'and'
  },
  sort: [{ id: 'firstName', order: 1 }]
}, undefined, {
  fields: [
    { fieldId: 'email' },
    { fieldId: 'firstName' },
    { fieldId: 'lastName' },
  ]
});

const ID$h = 'form-view-organisation-admin-add';
const config$6 = (dataApi) => FormViewConfig.decode({
  _id: ID$h,
  base: 'mentornity',
  title: 'Add New Admin',
  space: spaces['mentornity'],
  table: dataConfigs['users'],
  type: AppViewType.FormView,
  handler: new AddOrganisationAdminFormHandler(),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new DataTransferField('organisationId'),
      },
      {
        field: new SingleChoiceField('admin', '', undefined, '', 'select').setDataProvider(userDataProvider(dataApi))
          .setDataAdapter(new DvnDataAdapter('firstName+lastName', 'email'))
          .require(),
      },
    ],
  },
  params: {
    organisationId: {
      required: true,
    },
  },
});

class RemoveOrganisationAdminFormHandler {
  constructor() {
    const { jwt, sessionId } = getCookieStorage().getAll();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, {
      'Authorization': `Bearer ${jwt}`,
      'Client': 'd2ViLWFkbWlu',
      'Session-Token': sessionId,
    });
  }
  onSubmit(event) {
    const { values: { admin: userId, organisationDomain } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.removeOrganisationAdmin(userId, {
        _roles: [`admin@${organisationDomain}`]
      }).then(() => {
        resolve({
          events: [
            new InvalidationAction(ID$f, ID$6),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

const ID$g = 'form-view-organisation-admin-remove';
const config$5 = (_dataApi) => FormViewConfig.decode({
  _id: ID$g,
  base: 'mentornity',
  title: 'Remove Admin',
  space: spaces['mentornity'],
  table: dataConfigs['users'],
  type: AppViewType.FormView,
  handler: new RemoveOrganisationAdminFormHandler(),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new DataTransferField('organisationDomain'),
      },
      {
        field: new SingleChoiceField('admin', '', undefined, '', 'select').setDataProvider(new DvnDataProvider(undefined, 'users', {})).setDataAdapter(new DvnDataAdapter('firstName+lastName', '_id'))
          .disable()
          .require(),
      },
    ],
  },
  params: {
    admin: {
      required: true,
    },
    organisationDomain: {
      required: true,
    },
  },
});

class DvnDataProviderTimeZone extends DvnDataProvider {
  constructor() {
    super(undefined, undefined, undefined);
    this.options = [];
    this.filteredOptions = [];
    this.searchText = '';
    zoneConfig.forEach(group => {
      group.zones.forEach(zone => {
        this.options.push({
          label: `${zone.name} (${zone.value})`,
          value: zone.value,
        });
      });
    });
    this.filteredOptions = this.options;
  }
  getInitialData() {
    return this.options;
  }
  getData() {
    return Promise.resolve(this.filteredOptions);
  }
  setQuickSearchText(text) {
    this.searchText = text;
    if (text) {
      this.filteredOptions = this.options.filter(option => (option.label.toLocaleLowerCase().includes(text.toLocaleLowerCase())));
    }
    else {
      this.filteredOptions = this.options;
    }
  }
  getQuickSearchText() {
    return this.searchText;
  }
  isQuickSearchEnabled() {
    return true;
  }
}

class CreateOrganisationFormHandler {
  constructor() {
    const { jwt, sessionId } = getCookieStorage().getAll();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, {
      'Authorization': `Bearer ${jwt}`,
      'Client': 'd2ViLWFkbWlu',
      'Session-Token': sessionId,
    });
  }
  onSubmit(event) {
    const { values: { admin, sourceOrganisationId, newOrganisationDomain, newOrganisationTitle, timeZone, } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.cloneOrganisation({
        sourceOrganisationId,
        newOrganisationDomain,
        newOrganisationTitle,
        adminIds: [admin],
        timeZone,
      }).then(() => {
        resolve({
          events: [
            new InvalidationAction(ID$f, ID$5),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(error => {
        if (error.data && error.data.message === 'domain-already-exists') {
          reject(['Domain is already used by another program.']);
          return;
        }
        reject(['Unexpected error']);
      });
    });
  }
}

const ID$f = 'form-view-organisation-create';
const config$4 = (dataApi) => FormViewConfig.decode({
  _id: ID$f,
  base: 'mentornity',
  title: 'Create Organisation',
  space: spaces['mentornity'],
  table: dataConfigs['organisations'],
  type: AppViewType.FormView,
  handler: new CreateOrganisationFormHandler(),
  ui: {
    fields: [
      {
        field: new SingleChoiceField('sourceOrganisationId', 'Program to clone', undefined, 'Search for a template or another program to clone.', 'select').setDataProvider(new DvnDataProvider(dataApi, 'organisations', {
          fields: [
            new TextField('domain', 'Domain'),
            new TextField('title', 'Title'),
          ],
          sort: [{ id: 'title', order: 1 }]
        }, undefined, {
          fields: [
            { fieldId: 'domain' },
            { fieldId: 'title' },
          ]
        })).setDataAdapter(new DvnDataAdapter('title', '_id'))
          .require(),
      },
      {
        field: new SingleChoiceField('admin', 'Admin', undefined, 'Search and select admins.', 'select').setDataProvider(userDataProvider(dataApi))
          .setDataAdapter(new DvnDataAdapter('firstName+lastName', '_id'))
          .require(),
      },
      {
        field: new SingleChoiceField('timeZone', 'Time Zone', undefined, 'Time zone of the program. Original program\'s time zone is used if empty.', 'select').setDataProvider(new DvnDataProviderTimeZone())
          .setDataAdapter(new DvnDataAdapter('label', 'value')),
      },
      {
        field: new TextField('newOrganisationTitle', 'Program name', '', 'Shown to users in the UI, emails and notifications.').addInterceptor('onBlur', new ValidatorLength(2, 100))
          .addInterceptor('onSubmit', new ModifierTrimmer())
          .require(),
      },
      {
        field: new TextField('newOrganisationDomain', 'Program domain', '', 'Used in the url and visible in browser address bar.').addInterceptor('onBlur', new ModifierRegexCharRemover(' '))
          .addInterceptor('onBlur', new ValidatorRegex('[a-z0-9\-]'))
          .addInterceptor('onBlur', new ValidatorLength(2, 100))
          .addInterceptor('onSubmit', new ModifierTrimmer())
          .require(),
      },
    ],
  }
});

class EditOrganisationConfigFormHandler {
  constructor() {
    const { jwt, sessionId } = getCookieStorage().getAll();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, {
      'Authorization': `Bearer ${jwt}`,
      'Client': 'd2ViLWFkbWlu',
      'Session-Token': sessionId,
    });
  }
  onSubmit(event) {
    const { values } = event.detail;
    const { item, membershipForm, mentorList, pairOverviewAndDetail, adminRoutes: admin, menteeRoutes: mentee, mentorRoutes: mentor, anonymousRoutes: anonymous, } = values;
    const body = {
      routes: {
        admin,
        mentee,
        mentor,
        anonymous,
      },
      webAppConfiguration: {
        membershipForm,
        mentorList,
        pairOverviewAndDetail,
      }
    };
    return new Promise((resolve, reject) => {
      this.api.update('configs', item._id, body).then(() => {
        resolve({
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

const ID$e = 'form-view-organisation-config-edit';
const viewConfig$a = FormViewConfig.decode({
  _id: ID$e,
  base: 'mentornity',
  title: 'Edit Configuration',
  space: spaces['mentornity'],
  table: dataConfigs['configs'],
  type: AppViewType.FormView,
  handler: new EditOrganisationConfigFormHandler(),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new DataTransferField('item'),
      },
      {
        field: new BooleanField('membershipForm', 'Membership Form', `Shows "My Info" item on the left menu which opens a form page for editing profile, metadata and mentorship in a single form.`),
      },
      {
        field: new BooleanField('pairOverviewAndDetail', 'Pair Overview and Detail', 'Shows the new mentors/mentees and mentor selection page.'),
      },
      {
        field: new BooleanField('mentorList', 'Mentor List', 'Shows the new mentor list for pool programs.'),
      },
      {
        field: new MultipleChoiceField('adminRoutes', 'Admin routes', [
          new MultipleChoiceFieldOption('Mentors', 'mentors'),
          new MultipleChoiceFieldOption('Mentees', 'mentees'),
          new MultipleChoiceFieldOption('Groups', 'groups'),
          new MultipleChoiceFieldOption('Calendar', 'calendar'),
          new MultipleChoiceFieldOption('Feedbacks', 'feedbacks'),
          new MultipleChoiceFieldOption('MeetingGoals', 'meetingGoals'),
          new MultipleChoiceFieldOption('Announcements', 'announcements'),
          new MultipleChoiceFieldOption('Reports', 'reports'),
          new MultipleChoiceFieldOption('Subscriptions', 'subscriptions'),
          new MultipleChoiceFieldOption('Forms', 'forms'),
          new MultipleChoiceFieldOption('Applications', 'applications'),
          new MultipleChoiceFieldOption('Screens', 'viewSettings'),
        ], '', 'select'),
      },
      {
        field: new MultipleChoiceField('mentorRoutes', 'Mentor routes', [
          new MultipleChoiceFieldOption('Feed', 'feed'),
          new MultipleChoiceFieldOption('Mentors', 'mentors'),
          new MultipleChoiceFieldOption('Mentees', 'mentees'),
          new MultipleChoiceFieldOption('Groups', 'groups'),
          new MultipleChoiceFieldOption('Forms', 'forms'),
        ], '', 'select'),
      },
      {
        field: new MultipleChoiceField('menteeRoutes', 'Mentee routes', [
          new MultipleChoiceFieldOption('Feed', 'feed'),
          new MultipleChoiceFieldOption('Mentors', 'mentors'),
          new MultipleChoiceFieldOption('Mentees', 'mentees'),
          new MultipleChoiceFieldOption('Groups', 'groups'),
          new MultipleChoiceFieldOption('Forms', 'forms'),
        ], '', 'select'),
      },
      {
        field: new MultipleChoiceField('anonymousRoutes', 'Anonymous routes', [
          new MultipleChoiceFieldOption('Mentors', 'mentors'),
          new MultipleChoiceFieldOption('Groups', 'groups'),
        ], '', 'select'),
      },
    ],
  },
  query: {
    fields: [
      new DataTransferField('webAppConfiguration'),
      new DataTransferField('routes'),
    ],
    filter: {
      comparison: Comparison.Eq,
      id: 'organisation._id',
      value: '$itemId',
    },
  },
  conversionConfig: {
    'item.webAppConfiguration.membershipForm': 'membershipForm',
    'item.webAppConfiguration.mentorList': 'mentorList',
    'item.webAppConfiguration.pairOverviewAndDetail': 'pairOverviewAndDetail',
    'item.routes.admin': 'adminRoutes',
    'item.routes.mentee': 'menteeRoutes',
    'item.routes.mentor': 'mentorRoutes',
    'item.routes.anonymous': 'anonymousRoutes',
  },
  params: {
    itemId: {
      required: true,
    },
  },
});

const ID$d = 'table-list-view-error-logs';
const config$3 = (dataApi) => TableListViewConfig.decode({
  _id: ID$d,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Error Logs',
  space: spaces['mentornity'],
  table: dataConfigs['errorlogs'],
  query: {
    fields: [
      new DataTransferField('res'),
      new DataTransferField('command'),
      new DataTransferField('status'),
      new DataTransferField('message'),
      new DataTransferField('createdAt'),
      new DataTransferField('status'),
      new ReferenceField('user', 'User', 'firstName', 'imageUrl', 'users', [
        new AttachmentField('imageUrl', ''),
        new TextField('email', 'Email'),
        new TextField('firstName', 'First Name'),
        new TextField('lastName', 'Last Name'),
      ], true),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Ne,
          id: 'user._id',
          value: '',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: TableListViewConfig.decode({
    main: {
      actions: [
        {
          ui: {
            name: 'expand',
            buttonType: 'icon-button',
            iconName: 'uil uil-expand-alt',
            view: 'flat'
          },
          data: {
            type: 'navigation',
            direction: 'forward',
            placement: ViewPlacement.SideModal,
            viewId: ID$p,
            params: {
              conversionConfig: {
                'item._id': 'id',
              }
            }
          }
        },
      ],
      fields: [
        {
          fieldId: 'createdAt',
          fieldDisplay: new DateField('createdAt', 'Date').setDateFormat('DD.MM.YYYY HH:mm').setDataType(DateDataType.Unix),
        },
        {
          fieldId: 'user.imageUrl',
          fieldDisplay: new NestedField('user.imageUrl', new AttachmentField('imageUrl', '').setShape('circle'))
        },
        {
          fieldId: 'user.firstName',
          fieldDisplay: new NestedField('user.firstName', new TextField('firstName', 'First Name'))
        },
        {
          fieldId: 'user.lastName',
          fieldDisplay: new NestedField('user.lastName', new TextField('lastName', 'Last Name'))
        },
        {
          fieldId: 'user.email',
          fieldDisplay: new NestedField('user.email', new TextField('email', 'Email'))
        },
        {
          fieldId: 'status',
        },
        {
          fieldId: 'message',
        },
        {
          fieldId: 'res',
        },
      ],
      columns: {
        'user.imageUrl': {
          width: 50,
        },
        'user.firstName': {
          width: 120,
        },
        'user.lastName': {
          width: 120,
        },
        'user.email': {
          width: 220,
        },
        createdAt: {
          width: 150,
        },
        status: {
          width: 80,
        },
        message: {
          weight: 1,
          width: 180,
        },
        res: {
          weight: 1,
          width: 120,
        },
      },
    },
    quickSearch: {
      fields: [
        {
          field: new SingleChoiceField('user._id', 'Search user', undefined, '', 'select').setDataProvider(userDataProvider(dataApi))
            .setDataAdapter(new DvnDataAdapter('firstName+lastName', '_id')),
        },
      ],
      fieldUIConfigs: [
        {
          fieldId: 'user._id',
          width: '240px',
        },
        {
          fieldId: 'status',
          width: '150px',
        },
      ],
    },
  }),
});

const ID$c = 'table-list-view-error-logs-anonymous';
const viewConfig$9 = TableListViewConfig.decode({
  _id: ID$c,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Anonymous Error Logs',
  space: spaces['mentornity'],
  table: dataConfigs['errorlogs'],
  query: {
    fields: [
      new DataTransferField('res'),
      new DataTransferField('command'),
      new DataTransferField('status'),
      new DataTransferField('message'),
      new DataTransferField('createdAt'),
      new DataTransferField('status'),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Eq,
          id: 'user._id',
          value: '',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: TableListViewConfig.decode({
    main: {
      actions: [
        {
          ui: {
            name: 'expand',
            buttonType: 'icon-button',
            iconName: 'uil uil-expand-alt',
            view: 'flat'
          },
          data: {
            type: 'navigation',
            direction: 'forward',
            placement: ViewPlacement.SideModal,
            viewId: ID$p,
            params: {
              conversionConfig: {
                'item._id': 'id',
              }
            }
          }
        },
      ],
      fields: [
        {
          fieldId: 'createdAt',
          fieldDisplay: new DateField('createdAt', 'Creation Date').setDateFormat('DD.MM.YYYY HH:mm').setDataType(DateDataType.Unix),
        },
        {
          fieldId: 'status',
        },
        {
          fieldId: 'message',
        },
        {
          fieldId: 'res',
        },
      ],
      columns: {
        createdAt: {
          width: 150,
        },
        status: {
          width: 100,
        },
      },
    },
  }),
});

const ID$b = 'table-list-view-form-response-contact';
const formTableListViewUIConfig = TableListViewConfig.decode({
  main: {
    actions: [{
        ui: {
          name: 'expand',
          buttonType: 'icon-button',
          iconName: 'uil uil-expand-alt',
          view: 'flat'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.SideModal,
          viewId: ID$m,
          params: {
            conversionConfig: {
              'item._id': 'itemId',
            }
          }
        }
      }],
    fields: [
      {
        fieldId: 'createdAt',
        fieldDisplay: new DateField('createdAt', 'Date').setDateFormat('DD MMM HH:mm').setDataType(DateDataType.Unix),
      },
      {
        fieldId: 'data.phone',
        fieldDisplay: new NestedField('data.phone', new TextField('phone', 'Phone')),
      },
      {
        fieldId: 'data.email',
        fieldDisplay: new NestedField('data.email', new TextField('email', 'Email')),
      },
      {
        fieldId: 'data.fullName',
        fieldDisplay: new NestedField('data.fullName', new TextField('name', 'Name')),
      },
      {
        fieldId: 'data.message',
        fieldDisplay: new NestedField('data.message', new TextField('message', 'Message')),
      },
    ],
    columns: {
      createdAt: {
        width: 120,
      },
      'data.phone': {
        width: 140,
      },
      'data.email': {
        width: 200,
      },
      'data.fullName': {
        width: 180,
      },
      'data.message': {
        weight: 1,
        width: 200,
      },
    },
  },
  quickSearch: {
    fields: [
      { field: new TextField('data.name', 'Name') },
      { field: new TextField('data.email', 'Email') },
      { field: new TextField('data.message', 'Message') },
    ]
  },
});
const viewConfig$8 = TableListViewConfig.decode({
  _id: ID$b,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Contact Forms',
  space: spaces['mentornity'],
  table: dataConfigs['formResponses'],
  query: {
    fields: [
      new DateField('createdAt', 'Created At'),
      new TextField('data', 'Data'),
      new TextField('type', 'type'),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Eq,
          id: 'type',
          value: 'contact',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: formTableListViewUIConfig,
});

const ID$a = 'table-list-view-form-response-help';
const viewConfig$7 = TableListViewConfig.decode({
  _id: ID$a,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Help Forms',
  space: spaces['mentornity'],
  table: dataConfigs['formResponses'],
  query: {
    fields: [
      new DateField('createdAt', 'Created At'),
      new TextField('data', 'Data'),
      new TextField('type', 'type'),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Eq,
          id: 'type',
          value: 'help',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: formTableListViewUIConfig,
});

const ID$9 = 'table-list-view-scheduled-job-sync-events-google';
const config$2 = (dataApi) => TableListViewConfig.decode({
  _id: ID$9,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Sync Google Events Jobs',
  space: spaces['mentornity'],
  table: dataConfigs['scheduledjobs'],
  query: {
    fields: [
      new TextField('name', 'Name'),
      new TextField('status', 'Status'),
      new DateField('scheduledAt', 'Created At'),
      new DateField('createdAt', 'Created At'),
      new DataTransferField('parameters'),
      new DataTransferField('metadata'),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Eq,
          id: 'name',
          value: 'CreateEventInGoogle',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: TableListViewConfig.decode({
    main: {
      actions: [{
          ui: {
            name: 'expand',
            buttonType: 'icon-button',
            iconName: 'uil uil-expand-alt',
            view: 'flat'
          },
          data: {
            type: 'navigation',
            direction: 'forward',
            placement: ViewPlacement.SideModal,
            viewId: ID$i,
            params: {
              conversionConfig: {
                'item._id': 'itemId',
              }
            }
          }
        }],
      fields: [
        {
          fieldId: 'createdAt',
          fieldDisplay: new DateField('createdAt', 'Date').setDateFormat('DD MMM YYYY').setDataType(DateDataType.Unix),
        },
        {
          fieldId: 'createdAt',
          fieldDisplay: new DateField('createdAt', 'Hour').setDateFormat('HH:mm').setDataType(DateDataType.Unix),
        },
        {
          fieldId: 'parameters.googleEvent.summary',
          fieldDisplay: new NestedField('parameters.googleEvent.summary', new TextField('summary', 'Summary')),
        },
        {
          fieldId: 'parameters.googleEvent.start.dateTime',
          fieldDisplay: new NestedField('parameters.googleEvent.start.dateTime', new DateField('meetingStart', 'Meeting Start').setDateFormat('DD MMM HH:mm')),
        },
        {
          fieldId: 'parameters.googleEvent.end.dateTime',
          fieldDisplay: new NestedField('parameters.googleEvent.end.dateTime', new DateField('meetingEnd', 'Meeting End').setDateFormat('DD MMM HH:mm')),
        },
        {
          fieldId: 'status',
        },
      ],
      columns: {
        createdAt: {
          width: 120,
        },
        'parameters.googleEvent.start.dateTime': {
          width: 150,
        },
        'parameters.googleEvent.end.dateTime': {
          width: 150,
        },
        status: {
          width: 100,
        },
      },
    },
    quickSearch: {
      fields: [
        {
          field: new SingleChoiceField('parameters.userId', 'Search user', undefined, 'Search and select admins.', 'select').setDataProvider(userDataProvider(dataApi))
            .setDataAdapter(new DvnDataAdapter('firstName+lastName', '_id')),
        },
        {
          field: new SingleChoiceField('status', 'Status', [
            new SingleChoiceFieldOption('Done', 'done'),
            new SingleChoiceFieldOption('Failed', 'failed'),
          ]),
        }
      ],
      fieldUIConfigs: [
        {
          fieldId: 'parameters.userId',
          width: '256px',
        },
      ],
      requireFilters: false,
    },
  }),
});

const ID$8 = 'table-list-view-scheduled-job-sync-events-microsoft';
const config$1 = (dataApi) => TableListViewConfig.decode({
  _id: ID$8,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Sync Microsoft Events Jobs',
  space: spaces['mentornity'],
  table: dataConfigs['scheduledjobs'],
  query: {
    fields: [
      new TextField('_id', 'ID'),
      new TextField('name', 'Name'),
      new TextField('status', 'Status'),
      new DateField('scheduledAt', 'Created At'),
      new DateField('createdAt', 'Created At'),
      new DataTransferField('parameters'),
      new DataTransferField('metadata'),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Eq,
          id: 'name',
          value: 'CreateEventInMicrosoft',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: TableListViewConfig.decode({
    main: {
      actions: [{
          ui: {
            name: 'expand',
            buttonType: 'icon-button',
            iconName: 'uil uil-expand-alt',
            view: 'flat'
          },
          data: {
            type: 'navigation',
            direction: 'forward',
            placement: ViewPlacement.SideModal,
            viewId: ID$i,
            params: {
              conversionConfig: {
                'item._id': 'itemId',
              }
            }
          }
        }],
      fields: [
        {
          fieldId: 'createdAt',
          fieldDisplay: new DateField('createdAt', 'Date').setDateFormat('DD MMM YYYY').setDataType(DateDataType.Unix),
        },
        {
          fieldId: 'createdAt',
          fieldDisplay: new DateField('createdAt', 'Hour').setDateFormat('HH:mm').setDataType(DateDataType.Unix),
        },
        {
          fieldId: 'parameters.microsoftEvent.subject',
          fieldDisplay: new NestedField('parameters.microsoftEvent.subject', new TextField('summary', 'Subject')),
        },
        {
          fieldId: 'parameters.microsoftEvent.start.dateTime',
          fieldDisplay: new NestedField('parameters.microsoftEvent.start.dateTime', new DateField('meetingStart', 'Meeting Start').setDateFormat('DD MMM HH:mm')),
        },
        {
          fieldId: 'parameters.microsoftEvent.end.dateTime',
          fieldDisplay: new NestedField('parameters.microsoftEvent.end.dateTime', new DateField('meetingEnd', 'Meeting End').setDateFormat('DD MMM HH:mm')),
        },
        {
          fieldId: 'status',
        },
      ],
      columns: {
        createdAt: {
          width: 120,
        },
        'parameters.microsoftEvent.start.dateTime': {
          width: 150,
        },
        'parameters.microsoftEvent.end.dateTime': {
          width: 150,
        },
        status: {
          width: 100,
        },
      },
    },
    quickSearch: {
      fields: [
        {
          field: new SingleChoiceField('parameters.userId', 'Search user', undefined, 'Search and select admins.', 'select').setDataProvider(userDataProvider(dataApi))
            .setDataAdapter(new DvnDataAdapter('firstName+lastName', '_id'))
        },
        {
          field: new SingleChoiceField('status', 'Status', [
            new SingleChoiceFieldOption('Done', 'done'),
            new SingleChoiceFieldOption('Failed', 'failed'),
          ]),
        }
      ],
      fieldUIConfigs: [
        {
          fieldId: 'parameters.userId',
          width: '256px',
        },
      ],
      requireFilters: false,
    },
  }),
});

const ID$7 = 'table-list-view-scheduled-job-send-email';
const tableListViewUIConfigScheduledJobs = TableListViewConfig.decode({
  main: {
    actions: [{
        ui: {
          name: 'expand',
          buttonType: 'icon-button',
          iconName: 'uil uil-expand-alt',
          view: 'flat'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.SideModal,
          viewId: ID$i,
          params: {
            conversionConfig: {
              'item._id': 'itemId',
            }
          }
        }
      }],
    fields: [
      {
        fieldId: 'parameters.templateAndSubjectName',
        fieldDisplay: new NestedField('parameters.templateAndSubjectName', new TextField('templateAndSubjectName', 'Type')),
      },
      {
        fieldId: 'createdAt',
        fieldDisplay: new DateField('createdAt', 'Date').setDateFormat('DD MMM YYYY').setDataType(DateDataType.Unix),
      },
      {
        fieldId: 'createdAt',
        fieldDisplay: new DateField('createdAt', 'Hour').setDateFormat('HH:mm').setDataType(DateDataType.Unix),
      },
      {
        fieldId: 'parameters.senderName',
        fieldDisplay: new NestedField('parameters.senderName', new TextField('senderName', 'Sender')),
      },
      {
        fieldId: 'parameters.recipientEmail',
        fieldDisplay: new NestedField('parameters.recipientEmail', new TextField('recipientEmail', 'Recipient')),
      },
      {
        fieldId: 'metadata.sent',
        fieldDisplay: new NestedField('metadata.sent', new DateField('sentOn', 'Sent On').setDateFormat('DD MMM HH:mm')),
      },
      {
        fieldId: 'metadata.delivered',
        fieldDisplay: new NestedField('metadata.delivered', new DateField('deliveredOn', 'Delivered On').setDateFormat('DD MMM HH:mm')),
      },
      {
        fieldId: 'status',
      },
    ],
    columns: {
      createdAt: {
        width: 100,
      },
      status: {
        width: 100,
      },
    },
  },
  quickSearch: {
    fields: [
      { field: new TextField('parameters.recipientEmail', 'Recipient') },
      {
        field: new SingleChoiceField('parameters.templateAndSubjectName', 'Type', [
          new SingleChoiceFieldOption('Announcement', 'Announcement'),
          new SingleChoiceFieldOption('Accept Pair Request', 'AcceptSubscription'),
          new SingleChoiceFieldOption('Reject Pair Request', 'RejectSubscription'),
          new SingleChoiceFieldOption('New Pair', 'CreateSubscription'),
          new SingleChoiceFieldOption('New Availability', 'CreateAvailability'),
          new SingleChoiceFieldOption('Cancel Meeting', 'CancelEvent'),
          new SingleChoiceFieldOption('New Meeting', 'CreateEvent'),
          new SingleChoiceFieldOption('New Meeting for Goal', 'CreateEventForMeetingGoal'),
          new SingleChoiceFieldOption('Update Meeting', 'UpdateEvent'),
          new SingleChoiceFieldOption('Invitation', 'Invitation'),
          new SingleChoiceFieldOption('New Form Assignment', 'FormAssignment'),
          new SingleChoiceFieldOption('New Group Member', 'NewGroupMember'),
          new SingleChoiceFieldOption('New Message', 'NewMessage'),
          new SingleChoiceFieldOption('Reset Password Link', 'ResetPasswordLink'),
          new SingleChoiceFieldOption('Erase User', 'EraseUser'),
        ]),
      }
    ],
    fieldUIConfigs: [
      {
        fieldId: 'parameters.templateAndSubjectName',
        width: '240px',
      },
    ],
    requireFilters: true,
  },
});
const viewConfig$6 = TableListViewConfig.decode({
  _id: ID$7,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Send Email Jobs',
  space: spaces['mentornity'],
  table: dataConfigs['scheduledjobs'],
  query: {
    fields: [
      new TextField('name', 'Name'),
      new TextField('status', 'Status'),
      new DateField('scheduledAt', 'Created At'),
      new DateField('createdAt', 'Created At'),
      new DataTransferField('parameters'),
      new DataTransferField('metadata'),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Eq,
          id: 'name',
          value: 'SendEmail',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: tableListViewUIConfigScheduledJobs,
});

const ID$6 = 'table-list-view-organisation-admins';
const organisationTableListViewUIConfig$1 = TableListViewConfig.decode({
  header: {
    actions: [{
        ui: {
          name: 'add-admin',
          buttonType: 'button',
          label: 'Add New'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.Dialog,
          viewId: ID$h,
          params: {
            conversionConfig: {
              'organisationId': 'organisationId',
              'organisationDomain': 'organisationDomain',
            }
          }
        }
      }],
  },
  leanedHorizontally: false,
  main: {
    actions: [
      {
        ui: {
          name: 'remove-admins',
          buttonType: 'icon-button',
          iconName: 'uil uil-trash-alt',
          tint: 'danger',
          view: 'flat'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.Dialog,
          viewId: ID$g,
          params: {
            conversionConfig: {
              'item': 'admin',
              'organisationDomain': 'organisationDomain',
            }
          }
        }
      },
    ],
    fields: [
      { fieldId: 'imageUrl' },
      { fieldId: 'firstName' },
      { fieldId: 'lastName' },
      { fieldId: 'email' },
    ],
    columns: {
      firstName: {
        width: 150,
      },
      imageUrl: {
        width: 50,
      },
      lastName: {
        width: 150,
      },
    },
  },
});
const viewConfig$5 = TableListViewConfig.decode({
  _id: ID$6,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Admins',
  space: spaces['mentornity'],
  table: dataConfigs['users'],
  query: {
    fields: [
      new DataTransferField('imageUrl'),
      new DataTransferField('firstName'),
      new DataTransferField('lastName'),
      new DataTransferField('email'),
    ],
    filter: {
      comparison: Comparison.Eq,
      id: '_roles',
      value: 'admin@+$organisationDomain',
    },
    sort: [{ id: 'firstName', order: 1 }]
  },
  ui: organisationTableListViewUIConfig$1,
  params: {
    organisationDomain: {
      required: true,
    },
    organisationId: {
      required: true,
    },
  },
});

const ID$5 = 'table-list-view-organisation';
const organisationTableListViewUIConfig = TableListViewConfig.decode({
  header: {
    actions: [{
        ui: {
          name: 'new-organisation',
          buttonType: 'button',
          label: 'Create New'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.Dialog,
          viewId: ID$f,
        }
      }],
  },
  main: {
    actions: [
      {
        ui: {
          name: 'expand',
          buttonType: 'icon-button',
          iconName: 'uil uil-expand-alt',
          view: 'flat'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.SideModal,
          viewId: ID$n,
          params: {
            conversionConfig: {
              'item._id': 'itemId',
            }
          }
        }
      },
      {
        ui: {
          name: 'manage-admins',
          buttonType: 'icon-button',
          iconName: 'uil uil-users-alt',
          view: 'flat'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.SideModal,
          viewId: ID$6,
          params: {
            conversionConfig: {
              'item._id': 'organisationId',
              'item.domain': 'organisationDomain',
            }
          }
        }
      },
      {
        ui: {
          name: 'expand',
          buttonType: 'icon-button',
          iconName: 'uil uil-cog',
          view: 'flat'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.SideModal,
          viewId: ID$e,
          params: {
            conversionConfig: {
              'item._id': 'itemId',
            }
          }
        }
      },
    ],
    fields: [
      { fieldId: 'logoUrl' },
      { fieldId: 'status', isEditable: true },
      { fieldId: 'model', isEditable: true },
      { fieldId: 'title' },
      {
        fieldDisplay: new DateField('createdAt', 'Creation Date')
          .setDateFormat('DD MMM YYYY')
          .setDataType(DateDataType.Unix),
      },
      {
        fieldDisplay: new TextField('summary.metrics.mentorCount', 'Mentors'),
      },
      {
        fieldDisplay: new TextField('summary.metrics.menteeCount', 'Mentees'),
      },
    ],
    columns: {
      title: {
        weight: 1,
        width: 300,
      },
      status: {
        width: 100,
      },
      model: {
        width: 180,
      },
      logoUrl: {
        width: 50,
      },
      createdAt: {
        width: 150,
      },
      'summary.metrics.mentorCount': {
        width: 100,
      },
      'summary.metrics.menteeCount': {
        width: 100,
      },
    },
  },
  quickSearch: {
    fields: [
      { fieldId: 'domain' },
      { fieldId: 'title' },
      { fieldId: 'status' },
      { fieldId: 'model' },
    ],
    fieldUIConfigs: [
      {
        fieldId: 'model',
        width: '200px',
      },
    ],
    ui: {
      model: {
        width: '200px'
      }
    }
  },
});
const viewConfig$4 = TableListViewConfig.decode({
  _id: ID$5,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Organisations',
  space: spaces['mentornity'],
  table: dataConfigs['organisations'],
  query: {
    fields: [
      new DataTransferField('status'),
      new DataTransferField('model'),
      new DataTransferField('logoUrl'),
      new DataTransferField('domain'),
      new DataTransferField('title'),
      new DataTransferField('description'),
      new DataTransferField('createdAt'),
      {
        type: 'reverse-reference',
        id: 'summary',
        otherCollection: 'organisationSummaries',
        nameInOtherCollection: 'organisation',
        isSingle: true,
        fields: [{ id: 'metrics' }]
      }
    ],
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: organisationTableListViewUIConfig,
});

const ID$4 = 'table-list-view-scheduled-job-next-day-summary';
const tableListViewUIConfigScheduledJobsNextDaySummary = TableListViewConfig.decode({
  main: {
    fields: [
      {
        fieldId: 'createdAt',
        fieldDisplay: new DateField('createdAt', 'Creation Date').setDateFormat('DD MMM YYYY HH:mm').setDataType(DateDataType.Unix),
      },
      {
        fieldId: 'scheduledAt',
        fieldDisplay: new DateField('scheduledAt', 'Scheduled Date').setDateFormat('DD MMM YYYY HH:mm'),
      },
      {
        fieldId: 'status',
      },
    ],
    columns: {
      createdAt: {
        width: 250,
      },
      scheduledAt: {
        width: 250,
      },
      'status': {
        width: 200,
      },
    },
  },
});
const viewConfig$3 = TableListViewConfig.decode({
  _id: ID$4,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Next Day Events Summary Jobs',
  space: spaces['mentornity'],
  table: dataConfigs['scheduledjobs'],
  query: {
    fields: [
      new TextField('name', 'Name'),
      new TextField('status', 'Status'),
      new DateField('scheduledAt', 'Created At'),
      new DateField('createdAt', 'Created At'),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Eq,
          id: 'name',
          value: 'NotificationNextDayEventsSummary',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: tableListViewUIConfigScheduledJobsNextDaySummary,
});

const ID$3 = 'table-list-view-scheduled-job-daily-summary';
const viewConfig$2 = TableListViewConfig.decode({
  _id: ID$3,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Daily Events Summary Jobs',
  space: spaces['mentornity'],
  table: dataConfigs['scheduledjobs'],
  query: {
    fields: [
      new TextField('name', 'Name'),
      new TextField('status', 'Status'),
      new DateField('scheduledAt', 'Created At'),
      new DateField('createdAt', 'Created At'),
    ],
    filter: {
      filters: [
        {
          comparison: Comparison.Eq,
          id: 'name',
          value: 'NotificationDailyEventSummary',
        },
      ],
      operator: 'or'
    },
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: tableListViewUIConfigScheduledJobsNextDaySummary,
});

const ID$2 = 'table-list-view-session';
const config = (dataApi) => TableListViewConfig.decode({
  _id: ID$2,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'User Sessions',
  space: spaces['mentornity'],
  table: dataConfigs['sessions'],
  query: {
    fields: [
      new DataTransferField('client'),
      new DataTransferField('createdAt'),
      new DataTransferField('updatedAt'),
      new DataTransferField('failureReason'),
      new DataTransferField('status'),
      new ReferenceField('user', 'User', 'firstName', 'imageUrl', 'users', [
        new AttachmentField('imageUrl', ''),
        new TextField('email', 'Email'),
        new TextField('firstName', 'First Name'),
        new TextField('lastName', 'Last Name'),
      ], true),
    ],
    sort: [{ id: 'updatedAt', order: -1 }]
  },
  ui: TableListViewConfig.decode({
    header: {
      actions: [],
    },
    main: {
      actions: [],
      fields: [
        {
          fieldId: 'user.imageUrl',
          fieldDisplay: new NestedField('user.imageUrl', new AttachmentField('imageUrl', '').setShape('circle'))
        },
        {
          fieldId: 'user.firstName',
          fieldDisplay: new NestedField('user.firstName', new TextField('firstName', 'First Name'))
        },
        {
          fieldId: 'user.lastName',
          fieldDisplay: new NestedField('user.lastName', new TextField('lastName', 'Last Name'))
        },
        {
          fieldId: 'user.email',
          fieldDisplay: new NestedField('user.email', new TextField('email', 'Email'))
        },
        { fieldId: 'createdAt' },
        { fieldId: 'updatedAt' },
        { fieldId: 'client' },
        { fieldId: 'status' },
        { fieldId: 'failureReason' },
      ],
      columns: {
        'user.imageUrl': {
          width: 50,
        },
        'user.firstName': {
          width: 120,
        },
        'user.lastName': {
          width: 120,
        },
        'user.email': {
          width: 240,
        },
        createdAt: {
          width: 150,
        },
        updatedAt: {
          width: 150,
        },
        status: {
          width: 150,
        },
        client: {
          width: 120,
        },
        failureReason: {
          weight: 1,
          width: 240,
        },
      },
    },
    quickSearch: {
      fields: [
        {
          field: new SingleChoiceField('user._id', 'Search user', undefined, '', 'select').setDataProvider(userDataProvider(dataApi))
            .setDataAdapter(new DvnDataAdapter('firstName+lastName', '_id')),
        },
        {
          field: new SingleChoiceField('status', 'Status', [
            new SingleChoiceFieldOption('Successful', 'successful'),
            new SingleChoiceFieldOption('Failed', 'failed'),
            new SingleChoiceFieldOption('Logged Out', 'loggedOut'),
          ]),
        }
      ],
      fieldUIConfigs: [
        {
          fieldId: 'user._id',
          width: '240px',
        },
        {
          fieldId: 'status',
          width: '150px',
        },
      ],
    },
  }),
});

const ID$1 = 'table-list-view-user';
const listViewUIConfig = TableListViewConfig.decode({
  header: {
    actions: [],
  },
  main: {
    actions: [
      {
        ui: {
          name: 'expand',
          buttonType: 'icon-button',
          iconName: 'uil uil-expand-alt',
          view: 'flat'
        },
        data: {
          type: 'navigation',
          direction: 'forward',
          placement: ViewPlacement.SideModal,
          viewId: ID$k,
          params: {
            conversionConfig: {
              'item._id': 'itemId',
              // 'item': 'item',
            }
          }
        }
      },
      // {
      //   ui: {
      //     name: 'expand',
      //     buttonType: 'icon-button',
      //     iconName: 'uil uil-key-skeleton',
      //     view: 'flat'
      //   },
      //   data: {
      //     type: 'navigation',
      //     direction: 'forward',
      //     placement: ViewPlacement.SideModal,
      //     viewId: detailViewUserAuth.ID,
      //     params: {
      //       conversionConfig: {
      //         'item._id': 'userId',
      //       }
      //     }
      //   }
      // },
    ],
    fields: [
      { fieldId: 'imageUrl' },
      { fieldId: 'firstName' },
      { fieldId: 'lastName' },
      { fieldId: 'email' },
      { fieldId: 'status' },
      { fieldId: 'createdAt' },
      {
        fieldId: 'lastSession.updatedAt',
        fieldDisplay: new NestedField('lastSession.updatedAt', new DateField('updatedAt', 'Last Session')
          .setDataType(DateDataType.Unix)
          .setDateFormat('DD MMM YYYY HH:mm')),
      },
      // { fieldId: 'memberships' },
      { fieldId: '_id' },
    ],
    columns: {
      _id: {
        width: 256,
      },
      createdAt: {
        width: 120,
      },
      email: {
        width: 240,
      },
      firstName: {
        width: 150,
      },
      imageUrl: {
        width: 50,
      },
      lastName: {
        width: 150,
      },
      'lastSession.updatedAt': {
        width: 200,
      },
      status: {
        width: 100,
      },
      // memberships: {
      //   weight: 1,
      // },
    },
  },
  quickSearch: {
    fields: [
      { fieldId: 'email' },
      { fieldId: 'firstName' },
      { fieldId: 'lastName' },
      { fieldId: 'status' },
    ]
  },
});
const viewConfig$1 = TableListViewConfig.decode({
  _id: ID$1,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'Users',
  space: spaces['mentornity'],
  table: dataConfigs['users'],
  query: {
    fields: [
      new DateField('createdAt', 'Created At').setDataType(DateDataType.Unix).setDateFormat('DD MMM YYYY'),
      new AttachmentField('imageUrl', ''),
      new TextField('email', 'Email'),
      new TextField('firstName', 'First Name'),
      new TextField('lastName', 'Last Name'),
      new TextField('status', 'Status'),
      // new RelationReferenceField(
      //   'memberships',
      //   'Programs',
      //   'title',
      //   'logoUrl',
      //   'memberships',
      //   'user',
      //   'organisations',
      //   'organisation',
      //   [
      //     new TextField('status', '')
      //   ],
      //   [
      //     new TextField('logoUrl', ''),
      //     new TextField('title', ''),
      //   ],
      // ),
      {
        type: 'reverse-reference',
        id: 'lastSession',
        otherCollection: 'sessions',
        nameInOtherCollection: 'user',
        isSingle: true,
        fields: [{ id: 'updatedAt' }, { id: 'createdAt' }],
        limit: 1,
        sort: {
          order: -1,
          id: 'updatedAt'
        }
      }
    ],
    sort: [{ id: 'createdAt', order: -1 }]
  },
  ui: listViewUIConfig,
});

const ID = 'table-list-view-white-label';
const viewConfig = TableListViewConfig.decode({
  _id: ID,
  type: AppViewType.ListViewTable,
  base: 'mentornity',
  title: 'White Labels',
  space: spaces['mentornity'],
  table: dataConfigs['whiteLabels'],
  query: {
    fields: [
      new DataTransferField('title'),
      new DataTransferField('domain'),
      new DataTransferField('createdAt'),
    ],
    sort: [{ id: 'title', order: 1 }]
  },
  ui: TableListViewConfig.decode({
    main: {
      fields: [
        { fieldId: 'title' },
        { fieldId: 'domain' },
        {
          fieldId: 'createdAt',
          fieldDisplay: new DateField('createdAt', 'Date').setDateFormat('DD MMM YYYY').setDataType(DateDataType.Unix),
        },
      ],
      columns: {
        domain: {
          weight: 1,
        },
        title: {
          weight: 1,
        },
        createdAt: {
          width: 150,
        },
      },
    },
  }),
});

const dataApi = new DataApiImpl(dataApiEndpoint, { Authorization: `Bearer ${getSessionData().token}` });
const appConfigs = {
  // app for system admins
  'app-configs-system-admin': AppConfig.decode({
    _id: 'app-configs-system-admin',
    _created: new Date(),
    _updated: new Date(),
    mainContent: {
      centered: false,
    },
    mainNavigation: {
      items: [
        {
          ui: {
            icon: 'uil-building',
            title: 'Organisations',
          },
          viewId: ID$5,
        },
        {
          ui: {
            icon: 'uil-clock',
            parent: 'Scheduled Jobs',
            title: 'Send Email'
          },
          viewId: ID$7,
        },
        {
          ui: {
            icon: 'uil-clock',
            parent: 'Scheduled Jobs',
            title: 'Sync Google'
          },
          viewId: ID$9,
        },
        {
          ui: {
            icon: 'uil-clock',
            parent: 'Scheduled Jobs',
            title: 'Sync Microsoft'
          },
          viewId: ID$8,
        },
        {
          ui: {
            icon: 'uil-clock',
            parent: 'Scheduled Jobs',
            title: 'Next Day Summary'
          },
          viewId: ID$4,
        },
        {
          ui: {
            icon: 'uil-clock',
            parent: 'Scheduled Jobs',
            title: 'Daily Summary'
          },
          viewId: ID$3,
        },
        {
          ui: {
            icon: 'uil-signin',
            title: 'Sessions'
          },
          viewId: ID$2,
        },
        {
          ui: {
            icon: 'uil-file-alt',
            title: 'Contact',
            parent: 'Support Forms',
          },
          viewId: ID$b,
        },
        {
          ui: {
            icon: 'uil-file-alt',
            title: 'Help',
            parent: 'Support Forms',
          },
          viewId: ID$a,
        },
        {
          ui: {
            icon: 'uil-user',
            title: 'Users'
          },
          viewId: ID$1,
        },
        {
          ui: {
            icon: 'uil-university',
            title: 'White Labels'
          },
          viewId: ID,
        },
        {
          ui: {
            icon: 'uil-exclamation-triangle',
            title: 'User Errors',
            parent: 'Error Logs',
          },
          viewId: ID$d,
        },
        {
          ui: {
            icon: 'uil-exclamation-triangle',
            title: 'Anonymous Errors',
            parent: 'Error Logs',
          },
          viewId: ID$c,
        },
      ],
      aligned: 'left',
    },
    membership: membershipConfigs['system-admins'],
    space: spaces['mentornity'],
    views: [
      viewConfig$i,
      viewConfig$f,
      viewConfig$g,
      viewConfig$d,
      viewConfig$c,
      viewConfig$b,
      viewConfig$e,
      viewConfig$h,
      viewConfig$a,
      config$4(dataApi),
      config$6(dataApi),
      config$5(),
      config$3(dataApi),
      viewConfig$9,
      viewConfig$8,
      viewConfig$7,
      viewConfig$4,
      viewConfig$5,
      viewConfig$2,
      viewConfig$3,
      viewConfig$6,
      config$2(dataApi),
      config$1(dataApi),
      config(dataApi),
      viewConfig$1,
      viewConfig,
    ],
  }),
};

class UyeApiMentornity {
  constructor(endpoint, headers) {
    this.headers = headers;
    this.endpoint = endpoint;
  }
  getAppConfigOfMembership(_id) {
    return Promise.resolve(appConfigs['app-configs-system-admin']);
  }
  addAuthInterceptor(token) {
    console.log('addAuthInterceptor', token);
  }
  consentAgreement(_id) {
    return Promise.reject(notImplemented('UyeApiMentornity.consentAgreement'));
  }
  getAgreement(_id) {
    return Promise.reject(notImplemented('UyeApiMentornity.getAgreement'));
  }
  activateMembership(_membershipConfigId, _membershipId) {
    return Promise.reject(notImplemented('UyeApiMentornity.activateMembership'));
  }
  getMembership(_membershipConfigId, _membershipId) {
    return Promise.reject(notImplemented('UyeApiMentornity.getMembership'));
  }
  getMembershipsOfUser(userId) {
    return Promise.resolve({
      results: [
        Membership.decode({
          _id: `system-admin-membership-for-${userId}`,
          _created: new Date(),
          _updated: new Date(),
          config: membershipConfigs['system-admins'].toObject(),
          consents: [],
          status: 'active',
          user: User.decode({ _id: userId }),
        })
      ]
    });
  }
  getMembershipConfig(_id) {
    return Promise.reject(notImplemented('UyeApiMentornity.getMembershipConfig'));
  }
  getMembershipConfigWithName(_name) {
    return Promise.reject(notImplemented('UyeApiMentornity.getMembershipConfigWithName'));
  }
  updateMembership(_membershipConfigId, _membershipId, _data) {
    return Promise.reject(notImplemented('UyeApiMentornity.updateMembership'));
  }
}

export { KimlikApiMentornity as K, UyeApiMentornity as U, dataApiEndpoint as d, mentornityApiEndpoint as m };
