mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-17 13:20:31 +00:00
Merge branch 'develop' into bulk-categorize-bank-transactions
This commit is contained in:
@@ -3,12 +3,16 @@ import { NextFunction, Request, Response, Router } from 'express';
|
||||
import BaseController from '@/api/controllers/BaseController';
|
||||
import { CashflowApplication } from '@/services/Cashflow/CashflowApplication';
|
||||
import { GetBankAccountSummary } from '@/services/Banking/BankAccounts/GetBankAccountSummary';
|
||||
import { BankAccountsApplication } from '@/services/Banking/BankAccounts/BankAccountsApplication';
|
||||
|
||||
@Service()
|
||||
export class BankAccountsController extends BaseController {
|
||||
@Inject()
|
||||
private getBankAccountSummaryService: GetBankAccountSummary;
|
||||
|
||||
@Inject()
|
||||
private bankAccountsApp: BankAccountsApplication;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
@@ -16,6 +20,11 @@ export class BankAccountsController extends BaseController {
|
||||
const router = Router();
|
||||
|
||||
router.get('/:bankAccountId/meta', this.getBankAccountSummary.bind(this));
|
||||
router.post(
|
||||
'/:bankAccountId/disconnect',
|
||||
this.disconnectBankAccount.bind(this)
|
||||
);
|
||||
router.post('/:bankAccountId/update', this.refreshBankAccount.bind(this));
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -46,4 +55,58 @@ export class BankAccountsController extends BaseController {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disonnect the given bank account.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
* @returns {Promise<Response|null>}
|
||||
*/
|
||||
async disconnectBankAccount(
|
||||
req: Request<{ bankAccountId: number }>,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const { bankAccountId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
try {
|
||||
await this.bankAccountsApp.disconnectBankAccount(tenantId, bankAccountId);
|
||||
|
||||
return res.status(200).send({
|
||||
id: bankAccountId,
|
||||
message: 'The bank account has been disconnected.',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the given bank account.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
* @returns {Promise<Response|null>}
|
||||
*/
|
||||
async refreshBankAccount(
|
||||
req: Request<{ bankAccountId: number }>,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const { bankAccountId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
try {
|
||||
await this.bankAccountsApp.refreshBankAccount(tenantId, bankAccountId);
|
||||
|
||||
return res.status(200).send({
|
||||
id: bankAccountId,
|
||||
message: 'The bank account has been disconnected.',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import SubscriptionService from '@/services/Subscription/SubscriptionService';
|
||||
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
|
||||
import BaseController from '../BaseController';
|
||||
import { LemonSqueezyService } from '@/services/Subscription/LemonSqueezyService';
|
||||
import { SubscriptionApplication } from '@/services/Subscription/SubscriptionApplication';
|
||||
|
||||
@Service()
|
||||
export class SubscriptionController extends BaseController {
|
||||
@@ -17,6 +18,9 @@ export class SubscriptionController extends BaseController {
|
||||
@Inject()
|
||||
private lemonSqueezyService: LemonSqueezyService;
|
||||
|
||||
@Inject()
|
||||
private subscriptionApp: SubscriptionApplication;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
@@ -33,6 +37,14 @@ export class SubscriptionController extends BaseController {
|
||||
this.validationResult,
|
||||
this.getCheckoutUrl.bind(this)
|
||||
);
|
||||
router.post('/cancel', asyncMiddleware(this.cancelSubscription.bind(this)));
|
||||
router.post('/resume', asyncMiddleware(this.resumeSubscription.bind(this)));
|
||||
router.post(
|
||||
'/change',
|
||||
[body('variant_id').exists().trim()],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.changeSubscriptionPlan.bind(this))
|
||||
);
|
||||
router.get('/', asyncMiddleware(this.getSubscriptions.bind(this)));
|
||||
|
||||
return router;
|
||||
@@ -85,4 +97,84 @@ export class SubscriptionController extends BaseController {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels the subscription of the current organization.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
* @returns {Promise<Response|null>}
|
||||
*/
|
||||
private async cancelSubscription(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const { tenantId } = req;
|
||||
|
||||
try {
|
||||
await this.subscriptionApp.cancelSubscription(tenantId, '455610');
|
||||
|
||||
return res.status(200).send({
|
||||
status: 200,
|
||||
message: 'The organization subscription has been canceled.',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes the subscription of the current organization.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
* @returns {Promise<Response | null>}
|
||||
*/
|
||||
private async resumeSubscription(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const { tenantId } = req;
|
||||
|
||||
try {
|
||||
await this.subscriptionApp.resumeSubscription(tenantId);
|
||||
|
||||
return res.status(200).send({
|
||||
status: 200,
|
||||
message: 'The organization subscription has been resumed.',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the main subscription plan of the current organization.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
* @returns {Promise<Response | null>}
|
||||
*/
|
||||
public async changeSubscriptionPlan(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const { tenantId } = req;
|
||||
const body = this.matchedBodyData(req);
|
||||
|
||||
try {
|
||||
await this.subscriptionApp.changeSubscriptionPlan(
|
||||
tenantId,
|
||||
body.variantId
|
||||
);
|
||||
return res.status(200).send({
|
||||
message: 'The subscription plan has been changed.',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,6 +236,10 @@ module.exports = {
|
||||
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
|
||||
endpoint: process.env.S3_ENDPOINT,
|
||||
bucket: process.env.S3_BUCKET || 'bigcapital-documents',
|
||||
forcePathStyle: parseBoolean(
|
||||
defaultTo(process.env.S3_FORCE_PATH_STYLE, false),
|
||||
false
|
||||
),
|
||||
},
|
||||
|
||||
loops: {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
exports.up = function (knex) {
|
||||
return knex.schema.table('accounts', (table) => {
|
||||
table.string('plaid_item_id').nullable();
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function (knex) {
|
||||
return knex.schema.table('accounts', (table) => {
|
||||
table.dropColumn('plaid_item_id');
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
exports.up = function (knex) {
|
||||
return knex.schema
|
||||
.table('accounts', (table) => {
|
||||
table
|
||||
.boolean('is_syncing_owner')
|
||||
.defaultTo(false)
|
||||
.after('is_feeds_active');
|
||||
})
|
||||
.then(() => {
|
||||
return knex('accounts')
|
||||
.whereNotNull('plaid_item_id')
|
||||
.orWhereNotNull('plaid_account_id')
|
||||
.update('is_syncing_owner', true);
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function (knex) {
|
||||
table.dropColumn('is_syncing_owner');
|
||||
};
|
||||
@@ -15,6 +15,7 @@ export interface IAccountDTO {
|
||||
export interface IAccountCreateDTO extends IAccountDTO {
|
||||
currencyCode?: string;
|
||||
plaidAccountId?: string;
|
||||
plaidItemId?: string;
|
||||
}
|
||||
|
||||
export interface IAccountEditDTO extends IAccountDTO {}
|
||||
@@ -37,6 +38,8 @@ export interface IAccount {
|
||||
accountNormal: string;
|
||||
accountParentType: string;
|
||||
bankBalance: string;
|
||||
plaidItemId: number | null
|
||||
lastFeedsUpdatedAt: Date;
|
||||
}
|
||||
|
||||
export enum AccountNormal {
|
||||
|
||||
@@ -1,69 +1,12 @@
|
||||
import { forEach } from 'lodash';
|
||||
import { Configuration, PlaidApi, PlaidEnvironments } from 'plaid';
|
||||
import { createPlaidApiEvent } from './PlaidApiEventsDBSync';
|
||||
import config from '@/config';
|
||||
|
||||
const OPTIONS = { clientApp: 'Plaid-Pattern' };
|
||||
|
||||
// We want to log requests to / responses from the Plaid API (via the Plaid client), as this data
|
||||
// can be useful for troubleshooting.
|
||||
|
||||
/**
|
||||
* Logging function for Plaid client methods that use an access_token as an argument. Associates
|
||||
* the Plaid API event log entry with the item and user the request is for.
|
||||
*
|
||||
* @param {string} clientMethod the name of the Plaid client method called.
|
||||
* @param {Array} clientMethodArgs the arguments passed to the Plaid client method.
|
||||
* @param {Object} response the response from the Plaid client.
|
||||
*/
|
||||
const defaultLogger = async (clientMethod, clientMethodArgs, response) => {
|
||||
const accessToken = clientMethodArgs[0].access_token;
|
||||
// const { id: itemId, user_id: userId } = await retrieveItemByPlaidAccessToken(
|
||||
// accessToken
|
||||
// );
|
||||
// await createPlaidApiEvent(1, 1, clientMethod, clientMethodArgs, response);
|
||||
|
||||
// console.log(response);
|
||||
};
|
||||
|
||||
/**
|
||||
* Logging function for Plaid client methods that do not use access_token as an argument. These
|
||||
* Plaid API event log entries will not be associated with an item or user.
|
||||
*
|
||||
* @param {string} clientMethod the name of the Plaid client method called.
|
||||
* @param {Array} clientMethodArgs the arguments passed to the Plaid client method.
|
||||
* @param {Object} response the response from the Plaid client.
|
||||
*/
|
||||
const noAccessTokenLogger = async (
|
||||
clientMethod,
|
||||
clientMethodArgs,
|
||||
response
|
||||
) => {
|
||||
// console.log(response);
|
||||
|
||||
// await createPlaidApiEvent(
|
||||
// undefined,
|
||||
// undefined,
|
||||
// clientMethod,
|
||||
// clientMethodArgs,
|
||||
// response
|
||||
// );
|
||||
};
|
||||
|
||||
// Plaid client methods used in this app, mapped to their appropriate logging functions.
|
||||
const clientMethodLoggingFns = {
|
||||
accountsGet: defaultLogger,
|
||||
institutionsGet: noAccessTokenLogger,
|
||||
institutionsGetById: noAccessTokenLogger,
|
||||
itemPublicTokenExchange: noAccessTokenLogger,
|
||||
itemRemove: defaultLogger,
|
||||
linkTokenCreate: noAccessTokenLogger,
|
||||
transactionsSync: defaultLogger,
|
||||
sandboxItemResetLogin: defaultLogger,
|
||||
};
|
||||
// Wrapper for the Plaid client. This allows us to easily log data for all Plaid client requests.
|
||||
export class PlaidClientWrapper {
|
||||
constructor() {
|
||||
private static instance: PlaidClientWrapper;
|
||||
private client: PlaidApi;
|
||||
|
||||
private constructor() {
|
||||
// Initialize the Plaid client.
|
||||
const configuration = new Configuration({
|
||||
basePath: PlaidEnvironments[config.plaid.env],
|
||||
@@ -75,26 +18,13 @@ export class PlaidClientWrapper {
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.client = new PlaidApi(configuration);
|
||||
|
||||
// Wrap the Plaid client methods to add a logging function.
|
||||
forEach(clientMethodLoggingFns, (logFn, method) => {
|
||||
this[method] = this.createWrappedClientMethod(method, logFn);
|
||||
});
|
||||
}
|
||||
|
||||
// Allows us to log API request data for troubleshooting purposes.
|
||||
createWrappedClientMethod(clientMethod, log) {
|
||||
return async (...args) => {
|
||||
try {
|
||||
const res = await this.client[clientMethod](...args);
|
||||
await log(clientMethod, args, res);
|
||||
return res;
|
||||
} catch (err) {
|
||||
await log(clientMethod, args, err?.response?.data);
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
public static getClient(): PlaidApi {
|
||||
if (!PlaidClientWrapper.instance) {
|
||||
PlaidClientWrapper.instance = new PlaidClientWrapper();
|
||||
}
|
||||
return PlaidClientWrapper.instance.client;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,4 +8,5 @@ export const s3 = new S3Client({
|
||||
secretAccessKey: config.s3.secretAccessKey,
|
||||
},
|
||||
endpoint: config.s3.endpoint,
|
||||
forcePathStyle: config.s3.forcePathStyle,
|
||||
});
|
||||
|
||||
@@ -113,6 +113,7 @@ import { UnlinkBankRuleOnDeleteBankRule } from '@/services/Banking/Rules/events/
|
||||
import { DecrementUncategorizedTransactionOnMatching } from '@/services/Banking/Matching/events/DecrementUncategorizedTransactionsOnMatch';
|
||||
import { DecrementUncategorizedTransactionOnExclude } from '@/services/Banking/Exclude/events/DecrementUncategorizedTransactionOnExclude';
|
||||
import { DecrementUncategorizedTransactionOnCategorize } from '@/services/Cashflow/subscribers/DecrementUncategorizedTransactionOnCategorize';
|
||||
import { DisconnectPlaidItemOnAccountDeleted } from '@/services/Banking/BankAccounts/events/DisconnectPlaidItemOnAccountDeleted';
|
||||
import { LoopsEventsSubscriber } from '@/services/Loops/LoopsEventsSubscriber';
|
||||
|
||||
export default () => {
|
||||
@@ -275,6 +276,7 @@ export const susbcribers = () => {
|
||||
|
||||
// Plaid
|
||||
RecognizeSyncedBankTranasctions,
|
||||
DisconnectPlaidItemOnAccountDeleted,
|
||||
|
||||
// Loops
|
||||
LoopsEventsSubscriber
|
||||
|
||||
@@ -197,6 +197,7 @@ export default class Account extends mixin(TenantModel, [
|
||||
const ExpenseEntry = require('models/ExpenseCategory');
|
||||
const ItemEntry = require('models/ItemEntry');
|
||||
const UncategorizedTransaction = require('models/UncategorizedCashflowTransaction');
|
||||
const PlaidItem = require('models/PlaidItem');
|
||||
|
||||
return {
|
||||
/**
|
||||
@@ -321,6 +322,18 @@ export default class Account extends mixin(TenantModel, [
|
||||
query.where('categorized', false);
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Account model may belongs to a Plaid item.
|
||||
*/
|
||||
plaidItem: {
|
||||
relation: Model.BelongsToOneRelation,
|
||||
modelClass: PlaidItem.default,
|
||||
join: {
|
||||
from: 'accounts.plaidItemId',
|
||||
to: 'plaid_items.plaidItemId',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,12 @@ export class AccountTransformer extends Transformer {
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['formattedAmount', 'flattenName', 'bankBalanceFormatted'];
|
||||
return [
|
||||
'formattedAmount',
|
||||
'flattenName',
|
||||
'bankBalanceFormatted',
|
||||
'lastFeedsUpdatedAtFormatted',
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -52,6 +57,15 @@ export class AccountTransformer extends Transformer {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted last feeds update at.
|
||||
* @param {IAccount} account
|
||||
* @returns {string}
|
||||
*/
|
||||
protected lastFeedsUpdatedAtFormatted = (account: IAccount): string => {
|
||||
return this.formatDate(account.lastFeedsUpdatedAt);
|
||||
};
|
||||
|
||||
/**
|
||||
* Transformes the accounts collection to flat or nested array.
|
||||
* @param {IAccount[]}
|
||||
|
||||
@@ -96,6 +96,11 @@ export class CreateAccount {
|
||||
...createAccountDTO,
|
||||
slug: kebabCase(createAccountDTO.name),
|
||||
currencyCode: createAccountDTO.currencyCode || baseCurrency,
|
||||
|
||||
// Mark the account is Plaid owner since Plaid item/account is defined on creating.
|
||||
isSyncingOwner: Boolean(
|
||||
createAccountDTO.plaidAccountId || createAccountDTO.plaidItemId
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -117,12 +122,7 @@ export class CreateAccount {
|
||||
const tenantMeta = await TenantMetadata.query().findOne({ tenantId });
|
||||
|
||||
// Authorize the account creation.
|
||||
await this.authorize(
|
||||
tenantId,
|
||||
accountDTO,
|
||||
tenantMeta.baseCurrency,
|
||||
params
|
||||
);
|
||||
await this.authorize(tenantId, accountDTO, tenantMeta.baseCurrency, params);
|
||||
// Transformes the DTO to model.
|
||||
const accountInputModel = this.transformDTOToModel(
|
||||
accountDTO,
|
||||
@@ -157,4 +157,3 @@ export class CreateAccount {
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { DisconnectBankAccount } from './DisconnectBankAccount';
|
||||
import { RefreshBankAccountService } from './RefreshBankAccount';
|
||||
|
||||
@Service()
|
||||
export class BankAccountsApplication {
|
||||
@Inject()
|
||||
private disconnectBankAccountService: DisconnectBankAccount;
|
||||
|
||||
@Inject()
|
||||
private refreshBankAccountService: RefreshBankAccountService;
|
||||
|
||||
/**
|
||||
* Disconnects the given bank account.
|
||||
* @param {number} tenantId
|
||||
* @param {number} bankAccountId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async disconnectBankAccount(tenantId: number, bankAccountId: number) {
|
||||
return this.disconnectBankAccountService.disconnectBankAccount(
|
||||
tenantId,
|
||||
bankAccountId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the bank transactions of the given bank account.
|
||||
* @param {number} tenantId
|
||||
* @param {number} bankAccountId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async refreshBankAccount(tenantId: number, bankAccountId: number) {
|
||||
return this.refreshBankAccountService.refreshBankAccount(
|
||||
tenantId,
|
||||
bankAccountId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import { PlaidClientWrapper } from '@/lib/Plaid';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import UnitOfWork from '@/services/UnitOfWork';
|
||||
import events from '@/subscribers/events';
|
||||
import {
|
||||
ERRORS,
|
||||
IBankAccountDisconnectedEventPayload,
|
||||
IBankAccountDisconnectingEventPayload,
|
||||
} from './types';
|
||||
import { ACCOUNT_TYPE } from '@/data/AccountTypes';
|
||||
|
||||
@Service()
|
||||
export class DisconnectBankAccount {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
@Inject()
|
||||
private uow: UnitOfWork;
|
||||
|
||||
/**
|
||||
* Disconnects the given bank account.
|
||||
* @param {number} tenantId
|
||||
* @param {number} bankAccountId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public async disconnectBankAccount(tenantId: number, bankAccountId: number) {
|
||||
const { Account, PlaidItem } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve the bank account or throw not found error.
|
||||
const account = await Account.query()
|
||||
.findById(bankAccountId)
|
||||
.whereIn('account_type', [ACCOUNT_TYPE.CASH, ACCOUNT_TYPE.BANK])
|
||||
.withGraphFetched('plaidItem')
|
||||
.throwIfNotFound();
|
||||
|
||||
const oldPlaidItem = account.plaidItem;
|
||||
|
||||
if (!oldPlaidItem) {
|
||||
throw new ServiceError(ERRORS.BANK_ACCOUNT_NOT_CONNECTED);
|
||||
}
|
||||
const plaidInstance = PlaidClientWrapper.getClient();
|
||||
|
||||
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
|
||||
// Triggers `onBankAccountDisconnecting` event.
|
||||
await this.eventPublisher.emitAsync(events.bankAccount.onDisconnecting, {
|
||||
tenantId,
|
||||
bankAccountId,
|
||||
} as IBankAccountDisconnectingEventPayload);
|
||||
|
||||
// Remove the Plaid item from the system.
|
||||
await PlaidItem.query(trx).findById(account.plaidItemId).delete();
|
||||
|
||||
// Remove the plaid item association to the bank account.
|
||||
await Account.query(trx).findById(bankAccountId).patch({
|
||||
plaidAccountId: null,
|
||||
plaidItemId: null,
|
||||
isFeedsActive: false,
|
||||
});
|
||||
// Remove the Plaid item.
|
||||
await plaidInstance.itemRemove({
|
||||
access_token: oldPlaidItem.plaidAccessToken,
|
||||
});
|
||||
// Triggers `onBankAccountDisconnected` event.
|
||||
await this.eventPublisher.emitAsync(events.bankAccount.onDisconnected, {
|
||||
tenantId,
|
||||
bankAccountId,
|
||||
trx,
|
||||
} as IBankAccountDisconnectedEventPayload);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { PlaidClientWrapper } from '@/lib/Plaid';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { ERRORS } from './types';
|
||||
|
||||
@Service()
|
||||
export class RefreshBankAccountService {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Asks Plaid to trigger syncing the given bank account.
|
||||
* @param {number} tenantId
|
||||
* @param {number} bankAccountId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public async refreshBankAccount(tenantId: number, bankAccountId: number) {
|
||||
const { Account } = this.tenancy.models(tenantId);
|
||||
|
||||
const bankAccount = await Account.query()
|
||||
.findById(bankAccountId)
|
||||
.withGraphFetched('plaidItem')
|
||||
.throwIfNotFound();
|
||||
|
||||
// Can't continue if the given account is not linked with Plaid item.
|
||||
if (!bankAccount.plaidItem) {
|
||||
throw new ServiceError(ERRORS.BANK_ACCOUNT_NOT_CONNECTED);
|
||||
}
|
||||
const plaidInstance = PlaidClientWrapper.getClient();
|
||||
|
||||
await plaidInstance.transactionsRefresh({
|
||||
access_token: bankAccount.plaidItem.plaidAccessToken,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { IAccountEventDeletedPayload } from '@/interfaces';
|
||||
import { PlaidClientWrapper } from '@/lib/Plaid';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import events from '@/subscribers/events';
|
||||
|
||||
@Service()
|
||||
export class DisconnectPlaidItemOnAccountDeleted {
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
*/
|
||||
public attach(bus) {
|
||||
bus.subscribe(
|
||||
events.accounts.onDeleted,
|
||||
this.handleDisconnectPlaidItemOnAccountDelete.bind(this)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes Plaid item from the system and Plaid once the account deleted.
|
||||
* @param {IAccountEventDeletedPayload} payload
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private async handleDisconnectPlaidItemOnAccountDelete({
|
||||
tenantId,
|
||||
oldAccount,
|
||||
trx,
|
||||
}: IAccountEventDeletedPayload) {
|
||||
const { PlaidItem, Account } = this.tenancy.models(tenantId);
|
||||
|
||||
// Can't continue if the deleted account is not linked to Plaid item.
|
||||
if (!oldAccount.plaidItemId) return;
|
||||
|
||||
// Retrieves the Plaid item that associated to the deleted account.
|
||||
const oldPlaidItem = await PlaidItem.query(trx).findOne(
|
||||
'plaidItemId',
|
||||
oldAccount.plaidItemId
|
||||
);
|
||||
// Unlink the Plaid item from all account before deleting it.
|
||||
await Account.query(trx)
|
||||
.where('plaidItemId', oldAccount.plaidItemId)
|
||||
.patch({
|
||||
plaidAccountId: null,
|
||||
plaidItemId: null,
|
||||
});
|
||||
// Remove the Plaid item from the system.
|
||||
await PlaidItem.query(trx)
|
||||
.findOne('plaidItemId', oldAccount.plaidItemId)
|
||||
.delete();
|
||||
|
||||
if (oldPlaidItem) {
|
||||
const plaidInstance = PlaidClientWrapper.getClient();
|
||||
|
||||
// Remove the Plaid item.
|
||||
await plaidInstance.itemRemove({
|
||||
access_token: oldPlaidItem.plaidAccessToken,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
17
packages/server/src/services/Banking/BankAccounts/types.ts
Normal file
17
packages/server/src/services/Banking/BankAccounts/types.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Knex } from 'knex';
|
||||
|
||||
export interface IBankAccountDisconnectingEventPayload {
|
||||
tenantId: number;
|
||||
bankAccountId: number;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface IBankAccountDisconnectedEventPayload {
|
||||
tenantId: number;
|
||||
bankAccountId: number;
|
||||
trx: Knex.Transaction;
|
||||
}
|
||||
|
||||
export const ERRORS = {
|
||||
BANK_ACCOUNT_NOT_CONNECTED: 'BANK_ACCOUNT_NOT_CONNECTED',
|
||||
};
|
||||
@@ -28,7 +28,7 @@ export class PlaidItemService {
|
||||
const { PlaidItem } = this.tenancy.models(tenantId);
|
||||
const { publicToken, institutionId } = itemDTO;
|
||||
|
||||
const plaidInstance = new PlaidClientWrapper();
|
||||
const plaidInstance = PlaidClientWrapper.getClient();
|
||||
|
||||
// Exchange the public token for a private access token and store with the item.
|
||||
const response = await plaidInstance.itemPublicTokenExchange({
|
||||
|
||||
@@ -26,7 +26,7 @@ export class PlaidLinkTokenService {
|
||||
webhook: config.plaid.linkWebhook,
|
||||
access_token: accessToken,
|
||||
};
|
||||
const plaidInstance = new PlaidClientWrapper();
|
||||
const plaidInstance = PlaidClientWrapper.getClient();
|
||||
const createResponse = await plaidInstance.linkTokenCreate(linkTokenParams);
|
||||
|
||||
return createResponse.data;
|
||||
|
||||
@@ -2,6 +2,11 @@ import * as R from 'ramda';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import bluebird from 'bluebird';
|
||||
import { entries, groupBy } from 'lodash';
|
||||
import {
|
||||
AccountBase as PlaidAccountBase,
|
||||
Item as PlaidItem,
|
||||
Institution as PlaidInstitution,
|
||||
} from 'plaid';
|
||||
import { CreateAccount } from '@/services/Accounts/CreateAccount';
|
||||
import {
|
||||
IAccountCreateDTO,
|
||||
@@ -53,6 +58,7 @@ export class PlaidSyncDb {
|
||||
trx?: Knex.Transaction
|
||||
) {
|
||||
const { Account } = this.tenancy.models(tenantId);
|
||||
|
||||
const plaidAccount = await Account.query().findOne(
|
||||
'plaidAccountId',
|
||||
createBankAccountDTO.plaidAccountId
|
||||
@@ -77,13 +83,15 @@ export class PlaidSyncDb {
|
||||
*/
|
||||
public async syncBankAccounts(
|
||||
tenantId: number,
|
||||
plaidAccounts: PlaidAccount[],
|
||||
institution: any,
|
||||
plaidAccounts: PlaidAccountBase[],
|
||||
institution: PlaidInstitution,
|
||||
item: PlaidItem,
|
||||
trx?: Knex.Transaction
|
||||
): Promise<void> {
|
||||
const transformToPlaidAccounts =
|
||||
transformPlaidAccountToCreateAccount(institution);
|
||||
|
||||
const transformToPlaidAccounts = transformPlaidAccountToCreateAccount(
|
||||
item,
|
||||
institution
|
||||
);
|
||||
const accountCreateDTOs = R.map(transformToPlaidAccounts)(plaidAccounts);
|
||||
|
||||
await bluebird.map(
|
||||
|
||||
@@ -53,7 +53,7 @@ export class PlaidUpdateTransactions {
|
||||
await this.fetchTransactionUpdates(tenantId, plaidItemId);
|
||||
|
||||
const request = { access_token: accessToken };
|
||||
const plaidInstance = new PlaidClientWrapper();
|
||||
const plaidInstance = PlaidClientWrapper.getClient();
|
||||
const {
|
||||
data: { accounts, item },
|
||||
} = await plaidInstance.accountsGet(request);
|
||||
@@ -66,7 +66,13 @@ export class PlaidUpdateTransactions {
|
||||
country_codes: ['US', 'UK'],
|
||||
});
|
||||
// Sync bank accounts.
|
||||
await this.plaidSync.syncBankAccounts(tenantId, accounts, institution, trx);
|
||||
await this.plaidSync.syncBankAccounts(
|
||||
tenantId,
|
||||
accounts,
|
||||
institution,
|
||||
item,
|
||||
trx
|
||||
);
|
||||
// Sync bank account transactions.
|
||||
await this.plaidSync.syncAccountsTransactions(
|
||||
tenantId,
|
||||
@@ -141,7 +147,7 @@ export class PlaidUpdateTransactions {
|
||||
cursor: cursor,
|
||||
count: batchSize,
|
||||
};
|
||||
const plaidInstance = new PlaidClientWrapper();
|
||||
const plaidInstance = PlaidClientWrapper.getClient();
|
||||
const response = await plaidInstance.transactionsSync(request);
|
||||
const data = response.data;
|
||||
// Add this page of results
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
import * as R from 'ramda';
|
||||
import {
|
||||
Item as PlaidItem,
|
||||
Institution as PlaidInstitution,
|
||||
AccountBase as PlaidAccount,
|
||||
} from 'plaid';
|
||||
import {
|
||||
CreateUncategorizedTransactionDTO,
|
||||
IAccountCreateDTO,
|
||||
PlaidAccount,
|
||||
PlaidTransaction,
|
||||
} from '@/interfaces';
|
||||
|
||||
/**
|
||||
* Transformes the Plaid account to create cashflow account DTO.
|
||||
* @param {PlaidAccount} plaidAccount
|
||||
* @param {PlaidItem} item -
|
||||
* @param {PlaidInstitution} institution -
|
||||
* @param {PlaidAccount} plaidAccount -
|
||||
* @returns {IAccountCreateDTO}
|
||||
*/
|
||||
export const transformPlaidAccountToCreateAccount = R.curry(
|
||||
(institution: any, plaidAccount: PlaidAccount): IAccountCreateDTO => {
|
||||
(
|
||||
item: PlaidItem,
|
||||
institution: PlaidInstitution,
|
||||
plaidAccount: PlaidAccount
|
||||
): IAccountCreateDTO => {
|
||||
return {
|
||||
name: `${institution.name} - ${plaidAccount.name}`,
|
||||
code: '',
|
||||
@@ -20,9 +30,10 @@ export const transformPlaidAccountToCreateAccount = R.curry(
|
||||
currencyCode: plaidAccount.balances.iso_currency_code,
|
||||
accountType: 'cash',
|
||||
active: true,
|
||||
plaidAccountId: plaidAccount.account_id,
|
||||
bankBalance: plaidAccount.balances.current,
|
||||
accountMask: plaidAccount.mask,
|
||||
plaidAccountId: plaidAccount.account_id,
|
||||
plaidItemId: item.item_id,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { IFeatureAllItem, ISystemUser } from '@/interfaces';
|
||||
import { FeaturesManager } from '@/services/Features/FeaturesManager';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import config from '@/config';
|
||||
|
||||
interface IRoleAbility {
|
||||
subject: string;
|
||||
@@ -11,15 +12,16 @@ interface IRoleAbility {
|
||||
interface IDashboardBootMeta {
|
||||
abilities: IRoleAbility[];
|
||||
features: IFeatureAllItem[];
|
||||
isBigcapitalCloud: boolean;
|
||||
}
|
||||
|
||||
@Service()
|
||||
export default class DashboardService {
|
||||
@Inject()
|
||||
tenancy: HasTenancyService;
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
@Inject()
|
||||
featuresManager: FeaturesManager;
|
||||
private featuresManager: FeaturesManager;
|
||||
|
||||
/**
|
||||
* Retrieve dashboard meta.
|
||||
@@ -39,6 +41,7 @@ export default class DashboardService {
|
||||
return {
|
||||
abilities,
|
||||
features,
|
||||
isBigcapitalCloud: config.hostedOnBigcapitalCloud
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
|
||||
export class GetSubscriptionsTransformer extends Transformer {
|
||||
/**
|
||||
* Include these attributes to sale invoice object.
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return [
|
||||
'canceledAtFormatted',
|
||||
'endsAtFormatted',
|
||||
'trialStartsAtFormatted',
|
||||
'trialEndsAtFormatted',
|
||||
'statusFormatted',
|
||||
'planName',
|
||||
'planSlug',
|
||||
'planPrice',
|
||||
'planPriceCurrency',
|
||||
'planPriceFormatted',
|
||||
'planPeriod',
|
||||
'lemonUrls',
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Exclude attributes.
|
||||
* @returns {string[]}
|
||||
*/
|
||||
public excludeAttributes = (): string[] => {
|
||||
return ['id', 'plan'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the canceled at formatted.
|
||||
* @param subscription
|
||||
* @returns {string}
|
||||
*/
|
||||
public canceledAtFormatted = (subscription) => {
|
||||
return subscription.canceledAt
|
||||
? this.formatDate(subscription.canceledAt)
|
||||
: null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the ends at date formatted.
|
||||
* @param subscription
|
||||
* @returns {string}
|
||||
*/
|
||||
public endsAtFormatted = (subscription) => {
|
||||
return subscription.cancelsAt
|
||||
? this.formatDate(subscription.endsAt)
|
||||
: null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the trial starts at formatted date.
|
||||
* @returns {string}
|
||||
*/
|
||||
public trialStartsAtFormatted = (subscription) => {
|
||||
return subscription.trialStartsAt
|
||||
? this.formatDate(subscription.trialStartsAt)
|
||||
: null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the trial ends at formatted date.
|
||||
* @returns {string}
|
||||
*/
|
||||
public trialEndsAtFormatted = (subscription) => {
|
||||
return subscription.trialEndsAt
|
||||
? this.formatDate(subscription.trialEndsAt)
|
||||
: null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the Lemon subscription metadata.
|
||||
* @param subscription
|
||||
* @returns
|
||||
*/
|
||||
public lemonSubscription = (subscription) => {
|
||||
return (
|
||||
this.options.lemonSubscriptions[subscription.lemonSubscriptionId] || null
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted subscription status.
|
||||
* @param subscription
|
||||
* @returns {string}
|
||||
*/
|
||||
public statusFormatted = (subscription) => {
|
||||
const pairs = {
|
||||
canceled: 'Canceled',
|
||||
active: 'Active',
|
||||
inactive: 'Inactive',
|
||||
expired: 'Expired',
|
||||
on_trial: 'On Trial',
|
||||
};
|
||||
return pairs[subscription.status] || '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the subscription plan name.
|
||||
* @param subscription
|
||||
* @returns {string}
|
||||
*/
|
||||
public planName(subscription) {
|
||||
return subscription.plan?.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the subscription plan slug.
|
||||
* @param subscription
|
||||
* @returns {string}
|
||||
*/
|
||||
public planSlug(subscription) {
|
||||
return subscription.plan?.slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the subscription plan price.
|
||||
* @param subscription
|
||||
* @returns {number}
|
||||
*/
|
||||
public planPrice(subscription) {
|
||||
return subscription.plan?.price;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the subscription plan price currency.
|
||||
* @param subscription
|
||||
* @returns {string}
|
||||
*/
|
||||
public planPriceCurrency(subscription) {
|
||||
return subscription.plan?.currency;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the subscription plan formatted price.
|
||||
* @param subscription
|
||||
* @returns {string}
|
||||
*/
|
||||
public planPriceFormatted(subscription) {
|
||||
return this.formatMoney(subscription.plan?.price, {
|
||||
currencyCode: subscription.plan?.currency,
|
||||
precision: 0
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the subscription plan period.
|
||||
* @param subscription
|
||||
* @returns {string}
|
||||
*/
|
||||
public planPeriod(subscription) {
|
||||
return subscription?.plan?.period;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the subscription Lemon Urls.
|
||||
* @param subscription
|
||||
* @returns
|
||||
*/
|
||||
public lemonUrls = (subscription) => {
|
||||
const lemonSusbcription = this.lemonSubscription(subscription);
|
||||
return lemonSusbcription?.data?.attributes?.urls;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { cancelSubscription } from '@lemonsqueezy/lemonsqueezy.js';
|
||||
import { configureLemonSqueezy } from './utils';
|
||||
import { PlanSubscription } from '@/system/models';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import events from '@/subscribers/events';
|
||||
import { ERRORS, IOrganizationSubscriptionCanceled } from './types';
|
||||
|
||||
@Service()
|
||||
export class LemonCancelSubscription {
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
/**
|
||||
* Cancels the subscription of the given tenant.
|
||||
* @param {number} tenantId
|
||||
* @param {number} subscriptionId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public async cancelSubscription(tenantId: number) {
|
||||
configureLemonSqueezy();
|
||||
|
||||
const subscription = await PlanSubscription.query().findOne({
|
||||
tenantId,
|
||||
slug: 'main',
|
||||
});
|
||||
if (!subscription) {
|
||||
throw new ServiceError(ERRORS.SUBSCRIPTION_ID_NOT_ASSOCIATED_TO_TENANT);
|
||||
}
|
||||
const lemonSusbcriptionId = subscription.lemonSubscriptionId;
|
||||
const subscriptionId = subscription.id;
|
||||
const cancelledSub = await cancelSubscription(lemonSusbcriptionId);
|
||||
|
||||
if (cancelledSub.error) {
|
||||
throw new Error(cancelledSub.error.message);
|
||||
}
|
||||
await PlanSubscription.query().findById(subscriptionId).patch({
|
||||
canceledAt: new Date(),
|
||||
});
|
||||
// Triggers `onSubscriptionCanceled` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.subscription.onSubscriptionCanceled,
|
||||
{ tenantId, subscriptionId } as IOrganizationSubscriptionCanceled
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { updateSubscription } from '@lemonsqueezy/lemonsqueezy.js';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { PlanSubscription } from '@/system/models';
|
||||
import { configureLemonSqueezy } from './utils';
|
||||
import events from '@/subscribers/events';
|
||||
import { IOrganizationSubscriptionChanged } from './types';
|
||||
|
||||
@Service()
|
||||
export class LemonChangeSubscriptionPlan {
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
/**
|
||||
* Changes the given organization subscription plan.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {number} newVariantId - New variant id.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public async changeSubscriptionPlan(tenantId: number, newVariantId: number) {
|
||||
configureLemonSqueezy();
|
||||
|
||||
const subscription = await PlanSubscription.query().findOne({
|
||||
tenantId,
|
||||
slug: 'main',
|
||||
});
|
||||
const lemonSubscriptionId = subscription.lemonSubscriptionId;
|
||||
|
||||
// Send request to Lemon Squeezy to change the subscription.
|
||||
const updatedSub = await updateSubscription(lemonSubscriptionId, {
|
||||
variantId: newVariantId,
|
||||
});
|
||||
if (updatedSub.error) {
|
||||
throw new ServiceError('SOMETHING_WENT_WRONG');
|
||||
}
|
||||
// Triggers `onSubscriptionPlanChanged` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.subscription.onSubscriptionPlanChanged,
|
||||
{
|
||||
tenantId,
|
||||
lemonSubscriptionId,
|
||||
newVariantId,
|
||||
} as IOrganizationSubscriptionChanged
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import events from '@/subscribers/events';
|
||||
import { configureLemonSqueezy } from './utils';
|
||||
import { PlanSubscription } from '@/system/models';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { ERRORS, IOrganizationSubscriptionResumed } from './types';
|
||||
import { updateSubscription } from '@lemonsqueezy/lemonsqueezy.js';
|
||||
|
||||
@Service()
|
||||
export class LemonResumeSubscription {
|
||||
@Inject()
|
||||
private eventPublisher: EventPublisher;
|
||||
|
||||
/**
|
||||
* Resumes the main subscription of the given tenant.
|
||||
* @param {number} tenantId -
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public async resumeSubscription(tenantId: number) {
|
||||
configureLemonSqueezy();
|
||||
|
||||
const subscription = await PlanSubscription.query().findOne({
|
||||
tenantId,
|
||||
slug: 'main',
|
||||
});
|
||||
if (!subscription) {
|
||||
throw new ServiceError(ERRORS.SUBSCRIPTION_ID_NOT_ASSOCIATED_TO_TENANT);
|
||||
}
|
||||
const subscriptionId = subscription.id;
|
||||
const lemonSubscriptionId = subscription.lemonSubscriptionId;
|
||||
const returnedSub = await updateSubscription(lemonSubscriptionId, {
|
||||
cancelled: false,
|
||||
});
|
||||
if (returnedSub.error) {
|
||||
throw new ServiceError('');
|
||||
}
|
||||
// Update the subscription of the organization.
|
||||
await PlanSubscription.query().findById(subscriptionId).patch({
|
||||
canceledAt: null,
|
||||
});
|
||||
// Triggers `onSubscriptionCanceled` event.
|
||||
await this.eventPublisher.emitAsync(
|
||||
events.subscription.onSubscriptionResumed,
|
||||
{ tenantId, subscriptionId } as IOrganizationSubscriptionResumed
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { LemonCancelSubscription } from './LemonCancelSubscription';
|
||||
import { LemonChangeSubscriptionPlan } from './LemonChangeSubscriptionPlan';
|
||||
import { LemonResumeSubscription } from './LemonResumeSubscription';
|
||||
|
||||
@Service()
|
||||
export class SubscriptionApplication {
|
||||
@Inject()
|
||||
private cancelSubscriptionService: LemonCancelSubscription;
|
||||
|
||||
@Inject()
|
||||
private resumeSubscriptionService: LemonResumeSubscription;
|
||||
|
||||
@Inject()
|
||||
private changeSubscriptionPlanService: LemonChangeSubscriptionPlan;
|
||||
|
||||
/**
|
||||
* Cancels the subscription of the given tenant.
|
||||
* @param {number} tenantId
|
||||
* @param {string} id
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public cancelSubscription(tenantId: number, id: string) {
|
||||
return this.cancelSubscriptionService.cancelSubscription(tenantId, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes the subscription of the given tenant.
|
||||
* @param {number} tenantId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public resumeSubscription(tenantId: number) {
|
||||
return this.resumeSubscriptionService.resumeSubscription(tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the given organization subscription plan.
|
||||
* @param {number} tenantId
|
||||
* @param {number} newVariantId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public changeSubscriptionPlan(tenantId: number, newVariantId: number) {
|
||||
return this.changeSubscriptionPlanService.changeSubscriptionPlan(
|
||||
tenantId,
|
||||
newVariantId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,50 @@
|
||||
import { Service } from 'typedi';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { getSubscription } from '@lemonsqueezy/lemonsqueezy.js';
|
||||
import { PromisePool } from '@supercharge/promise-pool';
|
||||
import { PlanSubscription } from '@/system/models';
|
||||
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
|
||||
import { GetSubscriptionsTransformer } from './GetSubscriptionsTransformer';
|
||||
import { configureLemonSqueezy } from './utils';
|
||||
import { fromPairs } from 'lodash';
|
||||
|
||||
@Service()
|
||||
export default class SubscriptionService {
|
||||
@Inject()
|
||||
private transformer: TransformerInjectable;
|
||||
|
||||
/**
|
||||
* Retrieve all subscription of the given tenant.
|
||||
* @param {number} tenantId
|
||||
*/
|
||||
public async getSubscriptions(tenantId: number) {
|
||||
const subscriptions = await PlanSubscription.query().where(
|
||||
'tenant_id',
|
||||
tenantId
|
||||
configureLemonSqueezy();
|
||||
|
||||
const subscriptions = await PlanSubscription.query()
|
||||
.where('tenant_id', tenantId)
|
||||
.withGraphFetched('plan');
|
||||
|
||||
const lemonSubscriptionsResult = await PromisePool.withConcurrency(1)
|
||||
.for(subscriptions)
|
||||
.process(async (subscription, index, pool) => {
|
||||
if (subscription.lemonSubscriptionId) {
|
||||
const res = await getSubscription(subscription.lemonSubscriptionId);
|
||||
|
||||
if (res.error) {
|
||||
return;
|
||||
}
|
||||
return [subscription.lemonSubscriptionId, res.data];
|
||||
}
|
||||
});
|
||||
const lemonSubscriptions = fromPairs(
|
||||
lemonSubscriptionsResult?.results.filter((result) => !!result[1])
|
||||
);
|
||||
return this.transformer.transform(
|
||||
tenantId,
|
||||
subscriptions,
|
||||
new GetSubscriptionsTransformer(),
|
||||
{
|
||||
lemonSubscriptions,
|
||||
}
|
||||
);
|
||||
return subscriptions;
|
||||
}
|
||||
}
|
||||
|
||||
20
packages/server/src/services/Subscription/types.ts
Normal file
20
packages/server/src/services/Subscription/types.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
export const ERRORS = {
|
||||
SUBSCRIPTION_ID_NOT_ASSOCIATED_TO_TENANT:
|
||||
'SUBSCRIPTION_ID_NOT_ASSOCIATED_TO_TENANT',
|
||||
};
|
||||
|
||||
export interface IOrganizationSubscriptionChanged {
|
||||
tenantId: number;
|
||||
lemonSubscriptionId: string;
|
||||
newVariantId: number;
|
||||
}
|
||||
|
||||
export interface IOrganizationSubscriptionCanceled {
|
||||
tenantId: number;
|
||||
subscriptionId: string;
|
||||
}
|
||||
|
||||
export interface IOrganizationSubscriptionResumed {
|
||||
tenantId: number;
|
||||
subscriptionId: number;
|
||||
}
|
||||
@@ -41,9 +41,12 @@ export default {
|
||||
},
|
||||
|
||||
/**
|
||||
* User subscription events.
|
||||
* Organization subscription.
|
||||
*/
|
||||
subscription: {
|
||||
onSubscriptionCanceled: 'onSubscriptionCanceled',
|
||||
onSubscriptionResumed: 'onSubscriptionResumed',
|
||||
onSubscriptionPlanChanged: 'onSubscriptionPlanChanged',
|
||||
onSubscribed: 'onOrganizationSubscribed',
|
||||
},
|
||||
|
||||
@@ -658,6 +661,11 @@ export default {
|
||||
onUnexcluded: 'onBankTransactionUnexcluded',
|
||||
},
|
||||
|
||||
bankAccount: {
|
||||
onDisconnecting: 'onBankAccountDisconnecting',
|
||||
onDisconnected: 'onBankAccountDisconnected',
|
||||
},
|
||||
|
||||
// Import files.
|
||||
import: {
|
||||
onImportCommitted: 'onImportFileCommitted',
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
exports.up = function (knex) {
|
||||
return knex.schema.table('subscription_plan_subscriptions', (table) => {
|
||||
table.string('lemon_subscription_id').nullable();
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function (knex) {
|
||||
return knex.schema.table('subscription_plan_subscriptions', (table) => {
|
||||
table.dropColumn('lemon_subscription_id');
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
exports.up = function (knex) {
|
||||
return knex.schema.table('subscription_plan_subscriptions', (table) => {
|
||||
table.dateTime('trial_ends_at').nullable();
|
||||
table.dropColumn('cancels_at');
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function (knex) {
|
||||
return knex.schema.table('subscription_plan_subscriptions', (table) => {
|
||||
table.dropColumn('trial_ends_at').nullable();
|
||||
table.dateTime('cancels_at').nullable();
|
||||
});
|
||||
};
|
||||
@@ -4,6 +4,15 @@ import moment from 'moment';
|
||||
import SubscriptionPeriod from '@/services/Subscription/SubscriptionPeriod';
|
||||
|
||||
export default class PlanSubscription extends mixin(SystemModel) {
|
||||
public lemonSubscriptionId: number;
|
||||
|
||||
public endsAt: Date;
|
||||
public startsAt: Date;
|
||||
|
||||
public canceledAt: Date;
|
||||
|
||||
public trialEndsAt: Date;
|
||||
|
||||
/**
|
||||
* Table name.
|
||||
*/
|
||||
@@ -22,7 +31,7 @@ export default class PlanSubscription extends mixin(SystemModel) {
|
||||
* Defined virtual attributes.
|
||||
*/
|
||||
static get virtualAttributes() {
|
||||
return ['active', 'inactive', 'ended', 'onTrial'];
|
||||
return ['active', 'inactive', 'ended', 'canceled', 'onTrial', 'status'];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,7 +47,7 @@ export default class PlanSubscription extends mixin(SystemModel) {
|
||||
builder.where('trial_ends_at', '>', now);
|
||||
},
|
||||
|
||||
inactiveSubscriptions() {
|
||||
inactiveSubscriptions(builder) {
|
||||
builder.modify('endedTrial');
|
||||
builder.modify('endedPeriod');
|
||||
},
|
||||
@@ -98,35 +107,65 @@ export default class PlanSubscription extends mixin(SystemModel) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if subscription is active.
|
||||
* Check if the subscription is active.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
active() {
|
||||
return !this.ended() || this.onTrial();
|
||||
public active() {
|
||||
return this.onTrial() || !this.ended();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if subscription is inactive.
|
||||
* Check if the subscription is inactive.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
inactive() {
|
||||
public inactive() {
|
||||
return !this.active();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if subscription period has ended.
|
||||
* Check if paid subscription period has ended.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
ended() {
|
||||
public ended() {
|
||||
return this.endsAt ? moment().isAfter(this.endsAt) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the paid subscription has started.
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
public started() {
|
||||
return this.startsAt ? moment().isAfter(this.startsAt) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if subscription is currently on trial.
|
||||
* @return {Boolean}
|
||||
*/
|
||||
onTrial() {
|
||||
return this.trailEndsAt ? moment().isAfter(this.trailEndsAt) : false;
|
||||
public onTrial() {
|
||||
return this.trialEndsAt ? moment().isBefore(this.trialEndsAt) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the subscription is canceled.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
public canceled() {
|
||||
return !!this.canceledAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the subscription status.
|
||||
* @returns {string}
|
||||
*/
|
||||
public status() {
|
||||
return this.canceled()
|
||||
? 'canceled'
|
||||
: this.onTrial()
|
||||
? 'on_trial'
|
||||
: this.active()
|
||||
? 'active'
|
||||
: 'inactive';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,7 +180,7 @@ export default class PlanSubscription extends mixin(SystemModel) {
|
||||
const period = new SubscriptionPeriod(
|
||||
invoiceInterval,
|
||||
invoicePeriod,
|
||||
start,
|
||||
start
|
||||
);
|
||||
|
||||
const startsAt = period.getStartDate();
|
||||
@@ -157,7 +196,7 @@ export default class PlanSubscription extends mixin(SystemModel) {
|
||||
renew(invoiceInterval, invoicePeriod) {
|
||||
const { startsAt, endsAt } = PlanSubscription.setNewPeriod(
|
||||
invoiceInterval,
|
||||
invoicePeriod,
|
||||
invoicePeriod
|
||||
);
|
||||
return this.$query().update({ startsAt, endsAt });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user