mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-19 14:20:31 +00:00
feat: organization setup form validation.
This commit is contained in:
@@ -56,6 +56,7 @@
|
|||||||
"lodash": "^4.17.15",
|
"lodash": "^4.17.15",
|
||||||
"mini-css-extract-plugin": "0.9.0",
|
"mini-css-extract-plugin": "0.9.0",
|
||||||
"moment": "^2.24.0",
|
"moment": "^2.24.0",
|
||||||
|
"moment-timezone": "^0.5.33",
|
||||||
"node-sass": "^4.13.1",
|
"node-sass": "^4.13.1",
|
||||||
"optimize-css-assets-webpack-plugin": "5.0.3",
|
"optimize-css-assets-webpack-plugin": "5.0.3",
|
||||||
"pnp-webpack-plugin": "1.6.0",
|
"pnp-webpack-plugin": "1.6.0",
|
||||||
|
|||||||
@@ -1,7 +1,23 @@
|
|||||||
import intl from 'react-intl-universal';
|
import intl from 'react-intl-universal';
|
||||||
|
import currencies from 'js-money/lib/currency';
|
||||||
|
import { sortBy } from 'lodash';
|
||||||
|
|
||||||
export const getCurrencies = () => [
|
export const getCurrencies = () => [
|
||||||
{ name: intl.get('us_dollar'), code: 'USD' },
|
{ name: intl.get('us_dollar'), code: 'USD' },
|
||||||
{ name: intl.get('euro'), code: 'EUR' },
|
{ name: intl.get('euro'), code: 'EUR' },
|
||||||
{ name: intl.get('libyan_diner'), code: 'LYD' },
|
{ name: intl.get('libyan_diner'), code: 'LYD' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
export const getAllCurrenciesOptions = () => {
|
||||||
|
const codes = Object.keys(currencies);
|
||||||
|
const sortedCodes = sortBy(codes);
|
||||||
|
|
||||||
|
return sortedCodes.map((code) => {
|
||||||
|
const currency = currencies[code];
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: code,
|
||||||
|
name: `${code} - ${currency.name}`,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|||||||
@@ -2,63 +2,51 @@ import intl from 'react-intl-universal';
|
|||||||
|
|
||||||
export const getFiscalYear = () => [
|
export const getFiscalYear = () => [
|
||||||
{
|
{
|
||||||
id: 0,
|
|
||||||
name: `${intl.get('january')} - ${intl.get('december')}`,
|
name: `${intl.get('january')} - ${intl.get('december')}`,
|
||||||
value: 'january',
|
key: 'january',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 1,
|
|
||||||
name: `${intl.get('february')} - ${intl.get('january')}`,
|
name: `${intl.get('february')} - ${intl.get('january')}`,
|
||||||
value: 'february',
|
key: 'february',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
|
||||||
name: `${intl.get('march')} - ${intl.get('february')}`,
|
name: `${intl.get('march')} - ${intl.get('february')}`,
|
||||||
value: 'March',
|
key: 'march',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 3,
|
|
||||||
name: `${intl.get('april')} - ${intl.get('march')}`,
|
name: `${intl.get('april')} - ${intl.get('march')}`,
|
||||||
value: 'april',
|
key: 'april',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 4,
|
|
||||||
name: `${intl.get('may')} - ${intl.get('april')}`,
|
name: `${intl.get('may')} - ${intl.get('april')}`,
|
||||||
value: 'may',
|
key: 'may',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 5,
|
|
||||||
name: `${intl.get('june')} - ${intl.get('may')}`,
|
name: `${intl.get('june')} - ${intl.get('may')}`,
|
||||||
value: 'june',
|
key: 'june',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 6,
|
|
||||||
name: `${intl.get('july')} - ${intl.get('june')}`,
|
name: `${intl.get('july')} - ${intl.get('june')}`,
|
||||||
value: 'july',
|
key: 'july',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 7,
|
|
||||||
name: `${intl.get('august')} - ${intl.get('july')}`,
|
name: `${intl.get('august')} - ${intl.get('july')}`,
|
||||||
value: 'August',
|
key: 'august',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 8,
|
|
||||||
name: `${intl.get('september')} - ${intl.get('august')}`,
|
name: `${intl.get('september')} - ${intl.get('august')}`,
|
||||||
value: 'september',
|
key: 'september',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 9,
|
|
||||||
name: `${intl.get('october')} - ${intl.get('november')}`,
|
name: `${intl.get('october')} - ${intl.get('november')}`,
|
||||||
value: 'october',
|
key: 'october',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 10,
|
|
||||||
name: `${intl.get('november')} - ${intl.get('october')}`,
|
name: `${intl.get('november')} - ${intl.get('october')}`,
|
||||||
value: 'november',
|
key: 'november',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 11,
|
|
||||||
name: `${intl.get('december')} - ${intl.get('november')}`,
|
name: `${intl.get('december')} - ${intl.get('november')}`,
|
||||||
value: 'december',
|
key: 'december',
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
@@ -4,10 +4,12 @@ import intl from 'react-intl-universal';
|
|||||||
// Retrieve the setup organization form validation.
|
// Retrieve the setup organization form validation.
|
||||||
export const getSetupOrganizationValidation = () =>
|
export const getSetupOrganizationValidation = () =>
|
||||||
Yup.object().shape({
|
Yup.object().shape({
|
||||||
organization_name: Yup.string()
|
organizationName: Yup.string()
|
||||||
.required()
|
.required()
|
||||||
.label(intl.get('organization_name_')),
|
.label(intl.get('organization_name_')),
|
||||||
financialDateStart: Yup.date().required().label(intl.get('date_start_')),
|
location: Yup.string()
|
||||||
|
.required()
|
||||||
|
.label(intl.get('setup.organization.location')),
|
||||||
baseCurrency: Yup.string().required().label(intl.get('base_currency_')),
|
baseCurrency: Yup.string().required().label(intl.get('base_currency_')),
|
||||||
language: Yup.string().required().label(intl.get('language')),
|
language: Yup.string().required().label(intl.get('language')),
|
||||||
fiscalYear: Yup.string().required().label(intl.get('fiscal_year_')),
|
fiscalYear: Yup.string().required().label(intl.get('fiscal_year_')),
|
||||||
|
|||||||
@@ -7,24 +7,18 @@ import {
|
|||||||
InputGroup,
|
InputGroup,
|
||||||
MenuItem,
|
MenuItem,
|
||||||
Classes,
|
Classes,
|
||||||
Position,
|
|
||||||
} from '@blueprintjs/core';
|
} from '@blueprintjs/core';
|
||||||
import { DateInput } from '@blueprintjs/datetime';
|
|
||||||
import classNames from 'classnames';
|
import classNames from 'classnames';
|
||||||
import { TimezonePicker } from '@blueprintjs/timezone';
|
import { TimezonePicker } from '@blueprintjs/timezone';
|
||||||
import { FormattedMessage as T } from 'components';
|
import { FormattedMessage as T } from 'components';
|
||||||
|
import { getCountries } from 'common/countries';
|
||||||
|
|
||||||
import { Col, Row, ListSelect } from 'components';
|
import { Col, Row, ListSelect } from 'components';
|
||||||
import {
|
import { inputIntent } from 'utils';
|
||||||
momentFormatter,
|
|
||||||
tansformDateValue,
|
|
||||||
inputIntent,
|
|
||||||
handleDateChange,
|
|
||||||
} from 'utils';
|
|
||||||
|
|
||||||
import { getFiscalYear } from 'common/fiscalYearOptions';
|
import { getFiscalYear } from 'common/fiscalYearOptions';
|
||||||
import { getLanguages } from 'common/languagesOptions';
|
import { getLanguages } from 'common/languagesOptions';
|
||||||
import { getCurrencies } from 'common/currencies';
|
import { getAllCurrenciesOptions } from 'common/currencies';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Setup organization form.
|
* Setup organization form.
|
||||||
@@ -32,7 +26,8 @@ import { getCurrencies } from 'common/currencies';
|
|||||||
export default function SetupOrganizationForm({ isSubmitting, values }) {
|
export default function SetupOrganizationForm({ isSubmitting, values }) {
|
||||||
const FiscalYear = getFiscalYear();
|
const FiscalYear = getFiscalYear();
|
||||||
const Languages = getLanguages();
|
const Languages = getLanguages();
|
||||||
const Currencies = getCurrencies();
|
const currencies = getAllCurrenciesOptions();
|
||||||
|
const countries = getCountries();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form>
|
<Form>
|
||||||
@@ -41,40 +36,41 @@ export default function SetupOrganizationForm({ isSubmitting, values }) {
|
|||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
{/* ---------- Organization name ---------- */}
|
{/* ---------- Organization name ---------- */}
|
||||||
<FastField name={'organization_name'}>
|
<FastField name={'organizationName'}>
|
||||||
{({ form, field, meta: { error, touched } }) => (
|
{({ form, field, meta: { error, touched } }) => (
|
||||||
<FormGroup
|
<FormGroup
|
||||||
label={<T id={'legal_organization_name'} />}
|
label={<T id={'legal_organization_name'} />}
|
||||||
className={'form-group--name'}
|
className={'form-group--name'}
|
||||||
intent={inputIntent({ error, touched })}
|
intent={inputIntent({ error, touched })}
|
||||||
helperText={<ErrorMessage name={'organization_name'} />}
|
helperText={<ErrorMessage name={'organizationName'} />}
|
||||||
>
|
>
|
||||||
<InputGroup {...field} intent={inputIntent({ error, touched })} />
|
<InputGroup {...field} intent={inputIntent({ error, touched })} />
|
||||||
</FormGroup>
|
</FormGroup>
|
||||||
)}
|
)}
|
||||||
</FastField>
|
</FastField>
|
||||||
|
|
||||||
{/* ---------- Financial starting date ---------- */}
|
{/* ---------- Location ---------- */}
|
||||||
<FastField name={'financialDateStart'}>
|
<FastField name={'location'}>
|
||||||
{({
|
{({ form, field: { value }, meta: { error, touched } }) => (
|
||||||
form: { setFieldValue },
|
|
||||||
field: { value },
|
|
||||||
meta: { error, touched },
|
|
||||||
}) => (
|
|
||||||
<FormGroup
|
<FormGroup
|
||||||
label={<T id={'financial_starting_date'} />}
|
label={<T id={'business_location'} />}
|
||||||
|
className={classNames(
|
||||||
|
'form-group--business-location',
|
||||||
|
Classes.FILL,
|
||||||
|
)}
|
||||||
|
helperText={<ErrorMessage name="location" />}
|
||||||
intent={inputIntent({ error, touched })}
|
intent={inputIntent({ error, touched })}
|
||||||
helperText={<ErrorMessage name="financialDateStart" />}
|
|
||||||
className={classNames('form-group--select-list', Classes.FILL)}
|
|
||||||
>
|
>
|
||||||
<DateInput
|
<ListSelect
|
||||||
{...momentFormatter('YYYY MMMM DD')}
|
items={countries}
|
||||||
value={tansformDateValue(value)}
|
onItemSelect={({ value }) => {
|
||||||
popoverProps={{ position: Position.BOTTOM, minimal: true }}
|
form.setFieldValue('location', value);
|
||||||
onChange={handleDateChange((formattedDate) => {
|
}}
|
||||||
setFieldValue('financialDateStart', formattedDate);
|
selectedItem={value}
|
||||||
})}
|
selectedItemProp={'value'}
|
||||||
intent={inputIntent({ error, touched })}
|
defaultText={<T id={'select_business_location'} />}
|
||||||
|
textProp={'name'}
|
||||||
|
popoverProps={{ minimal: true }}
|
||||||
/>
|
/>
|
||||||
</FormGroup>
|
</FormGroup>
|
||||||
)}
|
)}
|
||||||
@@ -100,15 +96,15 @@ export default function SetupOrganizationForm({ isSubmitting, values }) {
|
|||||||
helperText={<ErrorMessage name={'baseCurrency'} />}
|
helperText={<ErrorMessage name={'baseCurrency'} />}
|
||||||
>
|
>
|
||||||
<ListSelect
|
<ListSelect
|
||||||
items={Currencies}
|
items={currencies}
|
||||||
noResults={
|
noResults={
|
||||||
<MenuItem disabled={true} text={<T id={'no_results'} />} />
|
<MenuItem disabled={true} text={<T id={'no_results'} />} />
|
||||||
}
|
}
|
||||||
popoverProps={{ minimal: true }}
|
popoverProps={{ minimal: true }}
|
||||||
onItemSelect={(item) => {
|
onItemSelect={(item) => {
|
||||||
setFieldValue('baseCurrency', item.code);
|
setFieldValue('baseCurrency', item.key);
|
||||||
}}
|
}}
|
||||||
selectedItemProp={'code'}
|
selectedItemProp={'key'}
|
||||||
textProp={'name'}
|
textProp={'name'}
|
||||||
defaultText={<T id={'select_base_currency'} />}
|
defaultText={<T id={'select_base_currency'} />}
|
||||||
selectedItem={value}
|
selectedItem={value}
|
||||||
@@ -181,12 +177,12 @@ export default function SetupOrganizationForm({ isSubmitting, values }) {
|
|||||||
<MenuItem disabled={true} text={<T id={'no_results'} />} />
|
<MenuItem disabled={true} text={<T id={'no_results'} />} />
|
||||||
}
|
}
|
||||||
selectedItem={value}
|
selectedItem={value}
|
||||||
selectedItemProp={'value'}
|
selectedItemProp={'key'}
|
||||||
textProp={'name'}
|
textProp={'name'}
|
||||||
defaultText={<T id={'select_fiscal_year'} />}
|
defaultText={<T id={'select_fiscal_year'} />}
|
||||||
popoverProps={{ minimal: true }}
|
popoverProps={{ minimal: true }}
|
||||||
onItemSelect={(item) => {
|
onItemSelect={(item) => {
|
||||||
setFieldValue('fiscalYear', item.value);
|
setFieldValue('fiscalYear', item.key);
|
||||||
}}
|
}}
|
||||||
filterable={false}
|
filterable={false}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Formik } from 'formik';
|
import { Formik } from 'formik';
|
||||||
import moment from 'moment';
|
|
||||||
import { FormattedMessage as T } from 'components';
|
import { FormattedMessage as T } from 'components';
|
||||||
|
|
||||||
import 'style/pages/Setup/Organization.scss';
|
import 'style/pages/Setup/Organization.scss';
|
||||||
@@ -9,15 +8,14 @@ import SetupOrganizationForm from './SetupOrganizationForm';
|
|||||||
|
|
||||||
import { useOrganizationSetup } from 'hooks/query';
|
import { useOrganizationSetup } from 'hooks/query';
|
||||||
import withSettingsActions from 'containers/Settings/withSettingsActions';
|
import withSettingsActions from 'containers/Settings/withSettingsActions';
|
||||||
import withOrganizationActions from 'containers/Organization/withOrganizationActions';
|
|
||||||
|
|
||||||
import { compose, transfromToSnakeCase } from 'utils';
|
import { compose, transfromToSnakeCase } from 'utils';
|
||||||
import { getSetupOrganizationValidation } from './SetupOrganization.schema';
|
import { getSetupOrganizationValidation } from './SetupOrganization.schema';
|
||||||
|
|
||||||
// Initial values.
|
// Initial values.
|
||||||
const defaultValues = {
|
const defaultValues = {
|
||||||
organization_name: '',
|
organizationName: '',
|
||||||
financialDateStart: moment(new Date()).format('YYYY-MM-DD'),
|
location: 'libya',
|
||||||
baseCurrency: '',
|
baseCurrency: '',
|
||||||
language: 'en',
|
language: 'en',
|
||||||
fiscalYear: '',
|
fiscalYear: '',
|
||||||
@@ -27,7 +25,7 @@ const defaultValues = {
|
|||||||
/**
|
/**
|
||||||
* Setup organization form.
|
* Setup organization form.
|
||||||
*/
|
*/
|
||||||
function SetupOrganizationPage({ wizard, setOrganizationSetupCompleted }) {
|
function SetupOrganizationPage({ wizard }) {
|
||||||
const { mutateAsync: organizationSetupMutate } = useOrganizationSetup();
|
const { mutateAsync: organizationSetupMutate } = useOrganizationSetup();
|
||||||
|
|
||||||
// Validation schema.
|
// Validation schema.
|
||||||
@@ -73,5 +71,4 @@ function SetupOrganizationPage({ wizard, setOrganizationSetupCompleted }) {
|
|||||||
|
|
||||||
export default compose(
|
export default compose(
|
||||||
withSettingsActions,
|
withSettingsActions,
|
||||||
withOrganizationActions,
|
|
||||||
)(SetupOrganizationPage);
|
)(SetupOrganizationPage);
|
||||||
|
|||||||
@@ -1043,11 +1043,8 @@
|
|||||||
"total_rows": "",
|
"total_rows": "",
|
||||||
"always": "دائماً",
|
"always": "دائماً",
|
||||||
"none": "",
|
"none": "",
|
||||||
"us_dollar": "",
|
"english": "English",
|
||||||
"euro": "",
|
"arabic": "العربية",
|
||||||
"libyan_diner": "",
|
|
||||||
"english": "",
|
|
||||||
"arabic": "",
|
|
||||||
"just_a_moment_we_re_calculating_your_cost_transactions": "لحظة واحدة! نحن نحسب معاملات التكلفة الخاصة بك ، هذا لا يستغرق الكثير من الوقت ، يرجى التحقق بعد فترة.",
|
"just_a_moment_we_re_calculating_your_cost_transactions": "لحظة واحدة! نحن نحسب معاملات التكلفة الخاصة بك ، هذا لا يستغرق الكثير من الوقت ، يرجى التحقق بعد فترة.",
|
||||||
"refresh": "",
|
"refresh": "",
|
||||||
"total_name": "إجمالي {name}",
|
"total_name": "إجمالي {name}",
|
||||||
@@ -1280,6 +1277,7 @@
|
|||||||
"billing.suspend_message.title": "حسابك معلق :(",
|
"billing.suspend_message.title": "حسابك معلق :(",
|
||||||
"billing.suspend_message.description": "تم تعليق حسابك بسبب انتهاء فترة الاشتراك. الرجاء تجديد الاشتراك لتفعيل الحساب.",
|
"billing.suspend_message.description": "تم تعليق حسابك بسبب انتهاء فترة الاشتراك. الرجاء تجديد الاشتراك لتفعيل الحساب.",
|
||||||
"dashboard.subscription_msg.period_over": "انتهت فترة الاشتراك",
|
"dashboard.subscription_msg.period_over": "انتهت فترة الاشتراك",
|
||||||
"inventory_adjustment.details_drawer.title": "تفاصيل معاملة تسوية المخزون"
|
"inventory_adjustment.details_drawer.title": "تفاصيل معاملة تسوية المخزون",
|
||||||
|
"setup.organization.location": "الموقع"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -353,7 +353,7 @@ export default {
|
|||||||
once_delete_this_exchange_rate_you_will_able_to_restore_it: `Once you delete this exchange rate, you won\'t be able to restore it later. Are you sure you want to delete this exchange rate?`,
|
once_delete_this_exchange_rate_you_will_able_to_restore_it: `Once you delete this exchange rate, you won\'t be able to restore it later. Are you sure you want to delete this exchange rate?`,
|
||||||
once_delete_these_exchange_rates_you_will_not_able_restore_them: `Once you delete these exchange rates, you won't be able to retrieve them later. Are you sure you want to delete them?`,
|
once_delete_these_exchange_rates_you_will_not_able_restore_them: `Once you delete these exchange rates, you won't be able to retrieve them later. Are you sure you want to delete them?`,
|
||||||
once_delete_this_item_category_you_will_able_to_restore_it: `Once you delete this category, you won\'t be able to restore it later. Are you sure you want to delete this item?`,
|
once_delete_this_item_category_you_will_able_to_restore_it: `Once you delete this category, you won\'t be able to restore it later. Are you sure you want to delete this item?`,
|
||||||
select_business_location: 'Select Business Location',
|
select_business_location: 'Select business location',
|
||||||
select_base_currency: 'Select base currency',
|
select_base_currency: 'Select base currency',
|
||||||
select_fiscal_year: 'Select fiscal year',
|
select_fiscal_year: 'Select fiscal year',
|
||||||
select_language: 'Select Language',
|
select_language: 'Select Language',
|
||||||
|
|||||||
@@ -1248,5 +1248,6 @@
|
|||||||
"billing.suspend_message.title": "Your account is suspended :(",
|
"billing.suspend_message.title": "Your account is suspended :(",
|
||||||
"billing.suspend_message.description": "Your account has been suspended due to the expiration of the subscription period. Please renew the subscription to activate the account.",
|
"billing.suspend_message.description": "Your account has been suspended due to the expiration of the subscription period. Please renew the subscription to activate the account.",
|
||||||
"dashboard.subscription_msg.period_over": "Subscription period is over",
|
"dashboard.subscription_msg.period_over": "Subscription period is over",
|
||||||
"inventory_adjustment.details_drawer.title": "Inventory adjustment details"
|
"inventory_adjustment.details_drawer.title": "Inventory adjustment details",
|
||||||
|
"setup.organization.location": "Location"
|
||||||
}
|
}
|
||||||
@@ -19,8 +19,8 @@
|
|||||||
|
|
||||||
form {
|
form {
|
||||||
h3 {
|
h3 {
|
||||||
color: #4e5764;
|
color: #6b7382;
|
||||||
margin-bottom: 1.2rem;
|
margin-bottom: 1.6rem;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -41,11 +41,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
label.bp3-label{
|
label.bp3-label{
|
||||||
color: #313744;
|
color: #20242e;
|
||||||
}
|
|
||||||
|
|
||||||
.form-group--language {
|
|
||||||
margin-left: 10px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bp3-button:not([class*='bp3-intent-']):not(.bp3-minimal) {
|
.bp3-button:not([class*='bp3-intent-']):not(.bp3-minimal) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Inject, Service } from 'typedi';
|
import { Inject, Service } from 'typedi';
|
||||||
|
import moment from 'moment-timezone';
|
||||||
import { Router, Request, Response, NextFunction } from 'express';
|
import { Router, Request, Response, NextFunction } from 'express';
|
||||||
import { check, ValidationChain } from 'express-validator';
|
import { check, ValidationChain } from 'express-validator';
|
||||||
|
|
||||||
@@ -8,11 +9,16 @@ import TenancyMiddleware from 'api/middleware/TenancyMiddleware';
|
|||||||
import SubscriptionMiddleware from 'api/middleware/SubscriptionMiddleware';
|
import SubscriptionMiddleware from 'api/middleware/SubscriptionMiddleware';
|
||||||
import AttachCurrentTenantUser from 'api/middleware/AttachCurrentTenantUser';
|
import AttachCurrentTenantUser from 'api/middleware/AttachCurrentTenantUser';
|
||||||
import OrganizationService from 'services/Organization';
|
import OrganizationService from 'services/Organization';
|
||||||
|
import {
|
||||||
|
ACCEPTED_CURRENCIES,
|
||||||
|
MONTHS,
|
||||||
|
ACCEPTED_LOCALES,
|
||||||
|
DATE_FORMATS,
|
||||||
|
} from 'services/Organization/constants';
|
||||||
|
|
||||||
import { ServiceError } from 'exceptions';
|
import { ServiceError } from 'exceptions';
|
||||||
import BaseController from 'api/controllers/BaseController';
|
import BaseController from 'api/controllers/BaseController';
|
||||||
|
|
||||||
const DATE_FORMATS = ['MM/DD/YYYY', 'M/D/YYYY'];
|
|
||||||
const BASE_CURRENCY = ['USD', 'LYD'];
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class OrganizationController extends BaseController {
|
export default class OrganizationController extends BaseController {
|
||||||
@Inject()
|
@Inject()
|
||||||
@@ -40,6 +46,8 @@ export default class OrganizationController extends BaseController {
|
|||||||
);
|
);
|
||||||
router.put(
|
router.put(
|
||||||
'/',
|
'/',
|
||||||
|
this.buildValidationSchema,
|
||||||
|
this.validationResult,
|
||||||
this.asyncMiddleware(this.updateOrganization.bind(this)),
|
this.asyncMiddleware(this.updateOrganization.bind(this)),
|
||||||
this.handleServiceErrors.bind(this)
|
this.handleServiceErrors.bind(this)
|
||||||
);
|
);
|
||||||
@@ -57,10 +65,11 @@ export default class OrganizationController extends BaseController {
|
|||||||
private get buildValidationSchema(): ValidationChain[] {
|
private get buildValidationSchema(): ValidationChain[] {
|
||||||
return [
|
return [
|
||||||
check('organization_name').exists().trim(),
|
check('organization_name').exists().trim(),
|
||||||
check('base_currency').exists().isIn(BASE_CURRENCY),
|
check('base_currency').exists().isIn(ACCEPTED_CURRENCIES),
|
||||||
check('timezone').exists(),
|
check('timezone').exists().isIn(moment.tz.names()),
|
||||||
check('fiscal_year').exists(),
|
check('fiscal_year').exists().isIn(MONTHS),
|
||||||
check('industry').optional().isString(),
|
check('industry').optional().isString(),
|
||||||
|
check('language').optional().isString().isIn(ACCEPTED_LOCALES),
|
||||||
check('date_format').optional().isIn(DATE_FORMATS),
|
check('date_format').optional().isIn(DATE_FORMATS),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -80,7 +89,6 @@ export default class OrganizationController extends BaseController {
|
|||||||
tenantId,
|
tenantId,
|
||||||
buildDTO
|
buildDTO
|
||||||
);
|
);
|
||||||
|
|
||||||
return res.status(200).send({
|
return res.status(200).send({
|
||||||
type: 'success',
|
type: 'success',
|
||||||
code: 'ORGANIZATION.DATABASE.INITIALIZED',
|
code: 'ORGANIZATION.DATABASE.INITIALIZED',
|
||||||
@@ -117,10 +125,10 @@ export default class OrganizationController extends BaseController {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the organization information.
|
* Update the organization information.
|
||||||
* @param {Request} req
|
* @param {Request} req
|
||||||
* @param {Response} res
|
* @param {Response} res
|
||||||
* @param {NextFunction} next
|
* @param {NextFunction} next
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
private async updateOrganization(
|
private async updateOrganization(
|
||||||
req: Request,
|
req: Request,
|
||||||
|
|||||||
34
server/src/services/Organization/constants.ts
Normal file
34
server/src/services/Organization/constants.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import currencies from 'js-money/lib/currency';
|
||||||
|
|
||||||
|
export const DATE_FORMATS = [
|
||||||
|
'MM.dd.yy',
|
||||||
|
'dd.MM.yy',
|
||||||
|
'yy.MM.dd',
|
||||||
|
'MM.dd.yyyy',
|
||||||
|
'dd.MM.yyyy',
|
||||||
|
'yyyy.MM.dd',
|
||||||
|
'MM/DD/YYYY',
|
||||||
|
'M/D/YYYY',
|
||||||
|
'dd MMM YYYY',
|
||||||
|
'dd MMMM YYYY',
|
||||||
|
'MMMM dd, YYYY',
|
||||||
|
'EEE, MMMM dd, YYYY',
|
||||||
|
];
|
||||||
|
export const ACCEPTED_CURRENCIES = Object.keys(currencies);
|
||||||
|
|
||||||
|
export const MONTHS = [
|
||||||
|
'january',
|
||||||
|
'february',
|
||||||
|
'march',
|
||||||
|
'april',
|
||||||
|
'may',
|
||||||
|
'june',
|
||||||
|
'july',
|
||||||
|
'august',
|
||||||
|
'september',
|
||||||
|
'october',
|
||||||
|
'november',
|
||||||
|
'december',
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ACCEPTED_LOCALES = ['en', 'ar'];
|
||||||
@@ -1,20 +1,17 @@
|
|||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import { Container } from 'typedi';
|
|
||||||
// import { ObjectId } from 'mongoose';
|
|
||||||
import { ServiceError } from 'exceptions';
|
import { ServiceError } from 'exceptions';
|
||||||
import { IOrganizationBuildDTO, ISystemUser, ITenant } from 'interfaces';
|
import {
|
||||||
|
IOrganizationBuildDTO,
|
||||||
|
IOrganizationUpdateDTO,
|
||||||
|
ITenant,
|
||||||
|
} from 'interfaces';
|
||||||
import {
|
import {
|
||||||
EventDispatcher,
|
EventDispatcher,
|
||||||
EventDispatcherInterface,
|
EventDispatcherInterface,
|
||||||
} from 'decorators/eventDispatcher';
|
} from 'decorators/eventDispatcher';
|
||||||
import events from 'subscribers/events';
|
import events from 'subscribers/events';
|
||||||
import {
|
|
||||||
TenantAlreadyInitialized,
|
|
||||||
TenantAlreadySeeded,
|
|
||||||
TenantDatabaseNotBuilt,
|
|
||||||
} from 'exceptions';
|
|
||||||
import TenantsManager from 'services/Tenancy/TenantsManager';
|
import TenantsManager from 'services/Tenancy/TenantsManager';
|
||||||
import { Tenant, TenantMetadata } from 'system/models';
|
import { Tenant } from 'system/models';
|
||||||
import { ObjectId } from 'mongodb';
|
import { ObjectId } from 'mongodb';
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
@@ -60,10 +57,13 @@ export default class OrganizationService {
|
|||||||
await this.tenantsManager.createDatabase(tenant);
|
await this.tenantsManager.createDatabase(tenant);
|
||||||
|
|
||||||
// Migrate the tenant.
|
// Migrate the tenant.
|
||||||
const migratedTenant = await this.tenantsManager.migrateTenant(tenant);
|
await this.tenantsManager.migrateTenant(tenant);
|
||||||
|
|
||||||
|
// Migrated tenant.
|
||||||
|
const migratedTenant = await tenant.$query();
|
||||||
|
|
||||||
// Seed tenant.
|
// Seed tenant.
|
||||||
const seededTenant = await this.tenantsManager.seedTenant(migratedTenant);
|
await this.tenantsManager.seedTenant(migratedTenant);
|
||||||
|
|
||||||
// Markes the tenant as completed builing.
|
// Markes the tenant as completed builing.
|
||||||
await Tenant.markAsBuilt(tenantId);
|
await Tenant.markAsBuilt(tenantId);
|
||||||
@@ -71,7 +71,7 @@ export default class OrganizationService {
|
|||||||
|
|
||||||
// Throws `onOrganizationBuild` event.
|
// Throws `onOrganizationBuild` event.
|
||||||
this.eventDispatcher.dispatch(events.organization.build, {
|
this.eventDispatcher.dispatch(events.organization.build, {
|
||||||
tenant: seededTenant,
|
tenantId: tenant.id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,13 +91,14 @@ export default class OrganizationService {
|
|||||||
this.throwIfTenantIsBuilding(tenant);
|
this.throwIfTenantIsBuilding(tenant);
|
||||||
|
|
||||||
// Saves the tenant metadata.
|
// Saves the tenant metadata.
|
||||||
await this.saveTenantMetadata(tenant, buildDTO);
|
await tenant.saveMetadata(buildDTO);
|
||||||
|
|
||||||
// Send welcome mail to the user.
|
// Send welcome mail to the user.
|
||||||
const jobMeta = await this.agenda.now('organization-setup', {
|
const jobMeta = await this.agenda.now('organization-setup', {
|
||||||
tenantId,
|
tenantId,
|
||||||
buildDTO,
|
buildDTO,
|
||||||
});
|
});
|
||||||
|
// Transformes the mangodb id to string.
|
||||||
const jobId = new ObjectId(jobMeta.attrs._id).toString();
|
const jobId = new ObjectId(jobMeta.attrs._id).toString();
|
||||||
|
|
||||||
// Markes the tenant as currently building.
|
// Markes the tenant as currently building.
|
||||||
@@ -109,12 +110,11 @@ export default class OrganizationService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
throwIfTenantIsBuilding(tenant) {
|
/**
|
||||||
if (tenant.buildJobId) {
|
* Unlocks tenant build run job.
|
||||||
throw new ServiceError(ERRORS.TENANT_IS_BUILDING);
|
* @param {number} tenantId
|
||||||
}
|
* @param {number} jobId
|
||||||
}
|
*/
|
||||||
|
|
||||||
public async revertBuildRunJob(tenantId: number, jobId: string) {
|
public async revertBuildRunJob(tenantId: number, jobId: string) {
|
||||||
await Tenant.markAsBuildCompleted(tenantId, jobId);
|
await Tenant.markAsBuildCompleted(tenantId, jobId);
|
||||||
}
|
}
|
||||||
@@ -135,6 +135,23 @@ export default class OrganizationService {
|
|||||||
return tenant;
|
return tenant;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates organization information.
|
||||||
|
* @param {ITenant} tenantId
|
||||||
|
* @param {IOrganizationUpdateDTO} organizationDTO
|
||||||
|
*/
|
||||||
|
public async updateOrganization(
|
||||||
|
tenantId: number,
|
||||||
|
organizationDTO: IOrganizationUpdateDTO
|
||||||
|
): Promise<void> {
|
||||||
|
const tenant = await Tenant.query().findById(tenantId);
|
||||||
|
|
||||||
|
// Throw error if the tenant not exists.
|
||||||
|
this.throwIfTenantNotExists(tenant);
|
||||||
|
|
||||||
|
await tenant.saveMetadata(organizationDTO);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Throws error in case the given tenant is undefined.
|
* Throws error in case the given tenant is undefined.
|
||||||
* @param {ITenant} tenant
|
* @param {ITenant} tenant
|
||||||
@@ -156,16 +173,13 @@ export default class OrganizationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Saves the organization metadata.
|
* Throw error if the tenant is building.
|
||||||
* @param tenant
|
* @param {ITenant} tenant
|
||||||
* @param buildDTO
|
|
||||||
* @returns
|
|
||||||
*/
|
*/
|
||||||
private saveTenantMetadata(tenant: ITenant, buildDTO) {
|
private throwIfTenantIsBuilding(tenant) {
|
||||||
return TenantMetadata.query().insert({
|
if (tenant.buildJobId) {
|
||||||
tenantId: tenant.id,
|
throw new ServiceError(ERRORS.TENANT_IS_BUILDING);
|
||||||
...buildDTO,
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ exports.up = function (knex) {
|
|||||||
table.string('industry');
|
table.string('industry');
|
||||||
|
|
||||||
table.string('base_currency');
|
table.string('base_currency');
|
||||||
|
table.string('language');
|
||||||
|
|
||||||
table.string('timezone');
|
table.string('timezone');
|
||||||
table.string('date_format');
|
table.string('date_format');
|
||||||
|
|||||||
Reference in New Issue
Block a user