Compare commits

...

50 Commits

Author SHA1 Message Date
Ahmed Bouhuolia
f21b01b1d6 feat: Move billing to preferences (#566)
* feat: move billing to preferences

* chore: remove the commented lines
2024-08-06 12:12:41 +02:00
Ahmed Bouhuolia
3cbcfac333 Merge pull request #565 from bigcapitalhq/fix-edit-bank-rule
fix: Edit bank rule
2024-08-06 00:50:05 +02:00
Ahmed Bouhuolia
cc21e1856f fix: Edit bank rule 2024-08-06 00:48:58 +02:00
Ahmed Bouhuolia
efd0e1e225 Merge pull request #564 from bigcapitalhq/fix-banking-bugs
fix: Banking service bugs
2024-08-05 23:06:03 +02:00
Ahmed Bouhuolia
521b083ed7 fix: retrieve the excluded transactions count 2024-08-05 22:50:58 +02:00
Ahmed Bouhuolia
a09fe26df7 fix: group query key constants in seperate file 2024-08-05 21:36:34 +02:00
Ahmed Bouhuolia
c7a85c4cf8 fix: categorize transactions on recognized transactions table 2024-08-05 21:20:11 +02:00
Ahmed Bouhuolia
f6350d3d61 fix: Should not show the excluded transactions in recognized transactions 2024-08-05 21:11:15 +02:00
Ahmed Bouhuolia
64c0732e5f fix: infinity scrolling of bank account transactions 2024-08-05 20:57:13 +02:00
Ahmed Bouhuolia
8e99a31455 fix: validate exclude and unexclude uncategorized transaction 2024-08-05 15:56:11 +02:00
Ahmed Bouhuolia
6d0d0689e1 Merge pull request #533 from bigcapitalhq/bulk-categorize-bank-transactions
feat: Bulk categorize bank transactions
2024-08-04 22:23:11 +02:00
Ahmed Bouhuolia
9836129e49 Merge branch 'develop' into bulk-categorize-bank-transactions 2024-08-04 22:23:02 +02:00
Ahmed Bouhuolia
86631ea8c3 chore: fix typing 2024-08-04 22:20:31 +02:00
Ahmed Bouhuolia
475ccd4903 Merge pull request #563 from bigcapitalhq/pause-resume-bank-feeds-syncing
feat: pause/resume bank account feeds syncing
2024-08-04 21:47:32 +02:00
Ahmed Bouhuolia
8608144ec1 chore: components description 2024-08-04 21:47:16 +02:00
Ahmed Bouhuolia
f9cf6d325a feat: pause bank account feeds 2024-08-04 21:14:05 +02:00
Ahmed Bouhuolia
fc0240c692 feat: confimation dialog on disconnecting bank account 2024-08-04 19:44:36 +02:00
Ahmed Bouhuolia
b84675325f feat: alert messages of pause.resume bank feeds 2024-08-04 16:05:35 +02:00
Ahmed Bouhuolia
647bed5c67 feat: control the multi-select switch 2024-08-04 15:42:53 +02:00
Ahmed Bouhuolia
00f5bb1d73 fix: decrement uncategorized transactions count 2024-08-04 13:15:20 +02:00
Ahmed Bouhuolia
208800b411 feat: wip pause/resume bank feeds syncing 2024-08-04 11:22:21 +02:00
Ahmed Bouhuolia
5e12a4cea4 feat: pause/resume bank account feeds syncing 2024-08-04 00:36:19 +02:00
Ahmed Bouhuolia
fdf3e34f1c feat: wip uncategorize bank transaction 2024-08-03 23:30:23 +02:00
Ahmed Bouhuolia
d74337fb94 feat: wip multi-select transactions to categorization and matching 2024-08-03 22:01:21 +02:00
Ahmed Bouhuolia
940b4f9175 Merge pull request #553 from oleynikd/attachments
Download attachments (documents) with original filenames
2024-08-02 02:42:52 +02:00
Ahmed Bouhuolia
5d0dd1fe3f Merge branch 'main' into develop 2024-08-01 20:10:01 +02:00
Ahmed Bouhuolia
ded4e2bb59 Merge pull request #560 from bigcapitalhq/fix-onboarding-on-small-screens
fix: Onboarding layout on small screens
2024-08-01 19:53:09 +02:00
Ahmed Bouhuolia
219e6fb466 fix: onboarding page layout on small screens 2024-08-01 19:51:25 +02:00
Ahmed Bouhuolia
5ce11f192f feat: reset the state once closing categorization aside 2024-08-01 14:02:02 +02:00
Ahmed Bouhuolia
71e865e9b7 Merge remote-tracking branch 'refs/remotes/origin/bulk-categorize-bank-transactions' into bulk-categorize-bank-transactions 2024-08-01 13:46:19 +02:00
Ahmed Bouhuolia
590506f183 Merge branch 'develop' into bulk-categorize-bank-transactions 2024-08-01 13:46:03 +02:00
Ahmed Bouhuolia
bed281a637 feat: wip multipe transactions categorization 2024-08-01 13:44:49 +02:00
Ahmed Bouhuolia
47dd767b3a feat: getting matched transactiosn from multi uncategorized transactions 2024-08-01 12:11:54 +02:00
Ahmed Bouhuolia
8623b69991 feat: getting matched transactiosn from multi uncategorized transactions 2024-08-01 12:11:40 +02:00
Denis
a1ddc81dac Fixed double slash in attachments route 2024-07-30 23:54:46 +03:00
Denis
832cdacebf Download attachments with original filenames 2024-07-30 23:48:15 +03:00
Ahmed Bouhuolia
9f979080b6 fix: remove console.log 2024-07-30 21:55:44 +02:00
Ahmed Bouhuolia
7f7301b31e Merge pull request #544 from bigcapitalhq/billing-subscription-page
feat: Billing subscription page
2024-07-30 21:44:55 +02:00
allcontributors[bot]
305ce29ebb docs: add oleynikd as a contributor for bug (#551)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2024-07-30 11:14:12 +02:00
Ahmed Bouhuolia
4cd0405078 fix: quick payment received and payment made form initial values 2024-07-30 11:06:45 +02:00
Ahmed Bouhuolia
783102449f fix: create quick payment received and payment made transactions 2024-07-30 11:06:35 +02:00
Denis
ae617b2e1d Fixed Quick Payment Dialogs
PaymentReceives and BillsPayments Controllers expect 'amount' parameter, but webapp sends 'payment_amount'
2024-07-30 11:06:24 +02:00
Ahmed Bouhuolia
9090d0a7b2 Merge pull request #548 from oleynikd/oleynikd-dev
Fixed Quick Payment Dialogs
2024-07-30 11:04:25 +02:00
Ahmed Bouhuolia
ffc55fa81b fix: quick payment received and payment made form initial values 2024-07-30 11:02:49 +02:00
Ahmed Bouhuolia
c4e77e4e3b fix: create quick payment received and payment made transactions 2024-07-29 23:15:42 +02:00
Denis
4490c2d4b4 Fixed Quick Payment Dialogs
PaymentReceives and BillsPayments Controllers expect 'amount' parameter, but webapp sends 'payment_amount'
2024-07-29 22:49:07 +03:00
Ahmed Bouhuolia
f5e18fc1fe feat: document the Redux mutation methods 2024-07-29 14:03:37 +02:00
Ahmed Bouhuolia
f64cd32985 Merge branch 'develop' into bulk-categorize-bank-transactions 2024-07-29 13:03:35 +02:00
Ahmed Bouhuolia
6fb02f9869 feat: bulk categorize and match bank transactions 2024-07-18 19:41:23 +02:00
Ahmed Bouhuolia
449390143d feat: bulk categorizing bank transactions 2024-07-18 17:00:23 +02:00
118 changed files with 2463 additions and 740 deletions

View File

@@ -132,6 +132,15 @@
"contributions": [
"bug"
]
},
{
"login": "oleynikd",
"name": "Denis",
"avatar_url": "https://avatars.githubusercontent.com/u/3976868?v=4",
"profile": "https://github.com/oleynikd",
"contributions": [
"bug"
]
}
],
"contributorsPerLine": 7,

View File

@@ -126,6 +126,9 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center" valign="top" width="14.28%"><a href="http://vederis.id"><img src="https://avatars.githubusercontent.com/u/13505006?v=4?s=100" width="100px;" alt="Vederis Leunardus"/><br /><sub><b>Vederis Leunardus</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/commits?author=cloudsbird" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://www.pivoten.com"><img src="https://avatars.githubusercontent.com/u/104120598?v=4?s=100" width="100px;" alt="Chris Cantrell"/><br /><sub><b>Chris Cantrell</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Accantrell72" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/oleynikd"><img src="https://avatars.githubusercontent.com/u/3976868?v=4?s=100" width="100px;" alt="Denis"/><br /><sub><b>Denis</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Aoleynikd" title="Bug reports">🐛</a></td>
</tr>
</tbody>
</table>

View File

@@ -250,10 +250,12 @@ export class AttachmentsController extends BaseController {
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const { id: documentKey } = req.params;
try {
const presignedUrl = await this.attachmentsApplication.getPresignedUrl(
tenantId,
documentKey
);
return res.status(200).send({ presignedUrl });

View File

@@ -1,9 +1,9 @@
import { Inject, Service } from 'typedi';
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';
import { param } from 'express-validator';
@Service()
export class BankAccountsController extends BaseController {
@@ -25,6 +25,22 @@ export class BankAccountsController extends BaseController {
this.disconnectBankAccount.bind(this)
);
router.post('/:bankAccountId/update', this.refreshBankAccount.bind(this));
router.post(
'/:bankAccountId/pause_feeds',
[
param('bankAccountId').exists().isNumeric().toInt(),
],
this.validationResult,
this.pauseBankAccountFeeds.bind(this)
);
router.post(
'/:bankAccountId/resume_feeds',
[
param('bankAccountId').exists().isNumeric().toInt(),
],
this.validationResult,
this.resumeBankAccountFeeds.bind(this)
);
return router;
}
@@ -109,4 +125,58 @@ export class BankAccountsController extends BaseController {
next(error);
}
}
/**
* Resumes the bank account feeds sync.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response | void>}
*/
async resumeBankAccountFeeds(
req: Request<{ bankAccountId: number }>,
res: Response,
next: NextFunction
) {
const { bankAccountId } = req.params;
const { tenantId } = req;
try {
await this.bankAccountsApp.resumeBankAccount(tenantId, bankAccountId);
return res.status(200).send({
message: 'The bank account feeds syncing has been resumed.',
id: bankAccountId,
});
} catch (error) {
next(error);
}
}
/**
* Pauses the bank account feeds sync.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response | void>}
*/
async pauseBankAccountFeeds(
req: Request<{ bankAccountId: number }>,
res: Response,
next: NextFunction
) {
const { bankAccountId } = req.params;
const { tenantId } = req;
try {
await this.bankAccountsApp.pauseBankAccount(tenantId, bankAccountId);
return res.status(200).send({
message: 'The bank account feeds syncing has been paused.',
id: bankAccountId,
});
} catch (error) {
next(error);
}
}
}

View File

@@ -1,12 +1,8 @@
import { Inject, Service } from 'typedi';
import { body, param } from 'express-validator';
import { NextFunction, Request, Response, Router } from 'express';
import BaseController from '@/api/controllers/BaseController';
import { MatchBankTransactionsApplication } from '@/services/Banking/Matching/MatchBankTransactionsApplication';
import { body, param } from 'express-validator';
import {
GetMatchedTransactionsFilter,
IMatchTransactionsDTO,
} from '@/services/Banking/Matching/types';
@Service()
export class BankTransactionsMatchingController extends BaseController {
@@ -20,9 +16,17 @@ export class BankTransactionsMatchingController extends BaseController {
const router = Router();
router.post(
'/:transactionId',
'/unmatch/:transactionId',
[param('transactionId').exists()],
this.validationResult,
this.unmatchMatchedBankTransaction.bind(this)
);
router.post(
'/match',
[
param('transactionId').exists(),
body('uncategorizedTransactions').exists().isArray({ min: 1 }),
body('uncategorizedTransactions.*').isNumeric().toInt(),
body('matchedTransactions').isArray({ min: 1 }),
body('matchedTransactions.*.reference_type').exists(),
body('matchedTransactions.*.reference_id').isNumeric().toInt(),
@@ -30,12 +34,6 @@ export class BankTransactionsMatchingController extends BaseController {
this.validationResult,
this.matchBankTransaction.bind(this)
);
router.post(
'/unmatch/:transactionId',
[param('transactionId').exists()],
this.validationResult,
this.unmatchMatchedBankTransaction.bind(this)
);
return router;
}
@@ -50,21 +48,21 @@ export class BankTransactionsMatchingController extends BaseController {
req: Request<{ transactionId: number }>,
res: Response,
next: NextFunction
) {
): Promise<Response | null> {
const { tenantId } = req;
const { transactionId } = req.params;
const matchTransactionDTO = this.matchedBodyData(
req
) as IMatchTransactionsDTO;
const bodyData = this.matchedBodyData(req);
const uncategorizedTransactions = bodyData?.uncategorizedTransactions;
const matchedTransactions = bodyData?.matchedTransactions;
try {
await this.bankTransactionsMatchingApp.matchTransaction(
tenantId,
transactionId,
matchTransactionDTO
uncategorizedTransactions,
matchedTransactions
);
return res.status(200).send({
id: transactionId,
ids: uncategorizedTransactions,
message: 'The bank transaction has been matched.',
});
} catch (error) {

View File

@@ -6,6 +6,7 @@ import { BankingRulesController } from './BankingRulesController';
import { BankTransactionsMatchingController } from './BankTransactionsMatchingController';
import { RecognizedTransactionsController } from './RecognizedTransactionsController';
import { BankAccountsController } from './BankAccountsController';
import { BankingUncategorizedController } from './BankingUncategorizedController';
@Service()
export class BankingController extends BaseController {
@@ -29,6 +30,10 @@ export class BankingController extends BaseController {
'/bank_accounts',
Container.get(BankAccountsController).router()
);
router.use(
'/categorize',
Container.get(BankingUncategorizedController).router()
);
return router;
}
}

View File

@@ -34,8 +34,9 @@ export class BankingRulesController extends BaseController {
body('conditions.*.comparator')
.exists()
.isIn(['equals', 'contains', 'not_contain'])
.default('contain'),
body('conditions.*.value').exists(),
.default('contain')
.trim(),
body('conditions.*.value').exists().trim(),
// Assign
body('assign_category').isString(),

View File

@@ -0,0 +1,57 @@
import { Inject, Service } from 'typedi';
import { NextFunction, Request, Response, Router } from 'express';
import { query } from 'express-validator';
import BaseController from '../BaseController';
import { GetAutofillCategorizeTransaction } from '@/services/Banking/RegonizeTranasctions/GetAutofillCategorizeTransaction';
@Service()
export class BankingUncategorizedController extends BaseController {
@Inject()
private getAutofillCategorizeTransactionService: GetAutofillCategorizeTransaction;
/**
* Router constructor.
*/
router() {
const router = Router();
router.get(
'/autofill',
[
query('uncategorizedTransactionIds').isArray({ min: 1 }),
query('uncategorizedTransactionIds.*').isNumeric().toInt(),
],
this.validationResult,
this.getAutofillCategorizeTransaction.bind(this)
);
return router;
}
/**
* Retrieves the autofill values of the categorize form of the given
* uncategorized transactions.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response | null>}
*/
public async getAutofillCategorizeTransaction(
req: Request,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const uncategorizedTransactionIds = req.query.uncategorizedTransactionIds;
try {
const data =
await this.getAutofillCategorizeTransactionService.getAutofillCategorizeTransaction(
tenantId,
uncategorizedTransactionIds
);
return res.status(200).send({ data });
} catch (error) {
next(error);
}
}
}

View File

@@ -1,6 +1,6 @@
import { Service, Inject } from 'typedi';
import { Router, Request, Response, NextFunction } from 'express';
import { param } from 'express-validator';
import { param, query } from 'express-validator';
import BaseController from '../BaseController';
import { ServiceError } from '@/exceptions';
import CheckPolicies from '@/api/middleware/CheckPolicies';
@@ -24,7 +24,12 @@ export default class GetCashflowAccounts extends BaseController {
const router = Router();
router.get(
'/transactions/:transactionId/matches',
'/transactions/matches',
[
query('uncategorizeTransactionsIds').exists().isArray({ min: 1 }),
query('uncategorizeTransactionsIds.*').exists().isNumeric().toInt(),
],
this.validationResult,
this.getMatchedTransactions.bind(this)
);
router.get(
@@ -44,7 +49,7 @@ export default class GetCashflowAccounts extends BaseController {
* @param {NextFunction} next
*/
private getCashflowTransaction = async (
req: Request,
req: Request<{ transactionId: number }>,
res: Response,
next: NextFunction
) => {
@@ -71,19 +76,24 @@ export default class GetCashflowAccounts extends BaseController {
* @param {NextFunction} next
*/
private async getMatchedTransactions(
req: Request<{ transactionId: number }>,
req: Request<
{ transactionId: number },
null,
null,
{ uncategorizeTransactionsIds: Array<number> }
>,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const { transactionId } = req.params;
const uncategorizeTransactionsIds = req.query.uncategorizeTransactionsIds;
const filter = this.matchedQueryData(req) as GetMatchedTransactionsFilter;
try {
const data =
await this.bankTransactionsMatchingApp.getMatchedTransactions(
tenantId,
transactionId,
uncategorizeTransactionsIds,
filter
);
return res.status(200).send(data);

View File

@@ -1,10 +1,15 @@
import { Service, Inject } from 'typedi';
import { ValidationChain, check, param, query } from 'express-validator';
import { Router, Request, Response, NextFunction } from 'express';
import { omit } from 'lodash';
import BaseController from '../BaseController';
import { ServiceError } from '@/exceptions';
import CheckPolicies from '@/api/middleware/CheckPolicies';
import { AbilitySubject, CashflowAction } from '@/interfaces';
import {
AbilitySubject,
CashflowAction,
ICategorizeCashflowTransactioDTO,
} from '@/interfaces';
import { CashflowApplication } from '@/services/Cashflow/CashflowApplication';
@Service()
@@ -44,7 +49,7 @@ export default class NewCashflowTransactionController extends BaseController {
this.catchServiceErrors
);
router.post(
'/transactions/:id/categorize',
'/transactions/categorize',
this.categorizeCashflowTransactionValidationSchema,
this.validationResult,
this.categorizeCashflowTransaction,
@@ -89,6 +94,7 @@ export default class NewCashflowTransactionController extends BaseController {
*/
public get categorizeCashflowTransactionValidationSchema() {
return [
check('uncategorized_transaction_ids').exists().isArray({ min: 1 }),
check('date').exists().isISO8601().toDate(),
check('credit_account_id').exists().isInt().toInt(),
check('transaction_number').optional(),
@@ -161,7 +167,7 @@ export default class NewCashflowTransactionController extends BaseController {
* @param {NextFunction} next
*/
private revertCategorizedCashflowTransaction = async (
req: Request,
req: Request<{ id: number }>,
res: Response,
next: NextFunction
) => {
@@ -191,14 +197,19 @@ export default class NewCashflowTransactionController extends BaseController {
next: NextFunction
) => {
const { tenantId } = req;
const { id: cashflowTransactionId } = req.params;
const cashflowTransaction = this.matchedBodyData(req);
const matchedObject = this.matchedBodyData(req);
const categorizeDTO = omit(matchedObject, [
'uncategorizedTransactionIds',
]) as ICategorizeCashflowTransactioDTO;
const uncategorizedTransactionIds =
matchedObject.uncategorizedTransactionIds;
try {
await this.cashflowApplication.categorizeTransaction(
tenantId,
cashflowTransactionId,
cashflowTransaction
uncategorizedTransactionIds,
categorizeDTO
);
return res.status(200).send({
message: 'The cashflow transaction has been created successfully.',
@@ -269,7 +280,7 @@ export default class NewCashflowTransactionController extends BaseController {
* @param {NextFunction} next
*/
public getUncategorizedCashflowTransactions = async (
req: Request,
req: Request<{ id: number }>,
res: Response,
next: NextFunction
) => {

View File

@@ -0,0 +1,11 @@
exports.up = function (knex) {
return knex.schema.table('plaid_items', (table) => {
table.datetime('paused_at');
});
};
exports.down = function (knex) {
return knex.schema.table('plaid_items', (table) => {
table.dropColumn('paused_at');
});
};

View File

@@ -236,6 +236,7 @@ export interface ICashflowTransactionSchema {
export interface ICashflowTransactionInput extends ICashflowTransactionSchema {}
export interface ICategorizeCashflowTransactioDTO {
date: Date;
creditAccountId: number;
referenceNo: string;
transactionNumber: string;

View File

@@ -130,20 +130,23 @@ export interface ICommandCashflowDeletedPayload {
export interface ICashflowTransactionCategorizedPayload {
tenantId: number;
uncategorizedTransaction: any;
uncategorizedTransactions: Array<IUncategorizedCashflowTransaction>;
cashflowTransaction: ICashflowTransaction;
oldUncategorizedTransactions: Array<IUncategorizedCashflowTransaction>;
categorizeDTO: any;
trx: Knex.Transaction;
}
export interface ICashflowTransactionUncategorizingPayload {
tenantId: number;
uncategorizedTransaction: IUncategorizedCashflowTransaction;
uncategorizedTransactionId: number;
oldUncategorizedTransactions: Array<IUncategorizedCashflowTransaction>;
trx: Knex.Transaction;
}
export interface ICashflowTransactionUncategorizedPayload {
tenantId: number;
uncategorizedTransaction: IUncategorizedCashflowTransaction;
oldUncategorizedTransaction: IUncategorizedCashflowTransaction;
uncategorizedTransactionId: number;
uncategorizedTransactions: Array<IUncategorizedCashflowTransaction>;
oldUncategorizedTransactions: Array<IUncategorizedCashflowTransaction>;
trx: Knex.Transaction;
}

View File

@@ -1,6 +1,8 @@
import TenantModel from 'models/TenantModel';
export default class PlaidItem extends TenantModel {
pausedAt: Date;
/**
* Table name.
*/
@@ -21,4 +23,19 @@ export default class PlaidItem extends TenantModel {
static get relationMappings() {
return {};
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return ['isPaused'];
}
/**
* Detarmines whether the Plaid item feeds syncing is paused.
* @return {boolean}
*/
get isPaused() {
return !!this.pausedAt;
}
}

View File

@@ -20,6 +20,7 @@ export default class UncategorizedCashflowTransaction extends mixin(
description!: string;
plaidTransactionId!: string;
recognizedTransactionId!: number;
excludedAt: Date;
/**
* Table name.
@@ -31,7 +32,7 @@ export default class UncategorizedCashflowTransaction extends mixin(
/**
* Timestamps columns.
*/
static get timestamps() {
get timestamps() {
return ['createdAt', 'updatedAt'];
}
@@ -45,6 +46,7 @@ export default class UncategorizedCashflowTransaction extends mixin(
'isDepositTransaction',
'isWithdrawalTransaction',
'isRecognized',
'isExcluded'
];
}
@@ -89,6 +91,14 @@ export default class UncategorizedCashflowTransaction extends mixin(
return !!this.recognizedTransactionId;
}
/**
* Detarmines whether the transaction is excluded.
* @returns {boolean}
*/
public get isExcluded(): boolean {
return !!this.excludedAt;
}
/**
* Model modifiers.
*/

View File

@@ -18,9 +18,18 @@ export class AccountTransformer extends Transformer {
'flattenName',
'bankBalanceFormatted',
'lastFeedsUpdatedAtFormatted',
'isFeedsPaused',
];
};
/**
* Exclude attributes.
* @returns {string[]}
*/
public excludeAttributes = (): string[] => {
return ['plaidItem'];
};
/**
* Retrieves the flatten name with all dependants accounts names.
* @param {IAccount} account -
@@ -66,6 +75,15 @@ export class AccountTransformer extends Transformer {
return this.formatDate(account.lastFeedsUpdatedAt);
};
/**
* Detarmines whether the bank account connection is paused.
* @param account
* @returns {boolean}
*/
protected isFeedsPaused = (account: any): boolean => {
return account.plaidItem?.isPaused || false;
};
/**
* Transformes the accounts collection to flat or nested array.
* @param {IAccount[]}

View File

@@ -25,7 +25,10 @@ export class GetAccount {
const { accountRepository } = this.tenancy.repositories(tenantId);
// Find the given account or throw not found error.
const account = await Account.query().findById(accountId).throwIfNotFound();
const account = await Account.query()
.findById(accountId)
.withGraphFetched('plaidItem')
.throwIfNotFound();
const accountsGraph = await accountRepository.getDependencyGraph();

View File

@@ -96,10 +96,11 @@ export class AttachmentsApplication {
/**
* Retrieves the presigned url of the given attachment key.
* @param {number} tenantId
* @param {string} key
* @returns {Promise<string>}
*/
public getPresignedUrl(key: string): Promise<string> {
return this.getPresignedUrlService.getPresignedUrl(key);
public getPresignedUrl(tenantId: number, key: string): Promise<string> {
return this.getPresignedUrlService.getPresignedUrl(tenantId, key);
}
}

View File

@@ -1,20 +1,34 @@
import { Service } from 'typedi';
import { Inject, Service } from 'typedi';
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { s3 } from '@/lib/S3/S3';
import config from '@/config';
import HasTenancyService from '../Tenancy/TenancyService';
@Service()
export class getAttachmentPresignedUrl {
@Inject()
private tenancy: HasTenancyService;
/**
* Retrieves the presigned url of the given attachment key.
* Retrieves the presigned url of the given attachment key with the original filename.
* @param {number} tenantId
* @param {string} key
* @returns {Promise<string?>}
* @returns {string}
*/
async getPresignedUrl(key: string) {
async getPresignedUrl(tenantId: number, key: string) {
const { Document } = this.tenancy.models(tenantId);
const foundDocument = await Document.query().findOne({ key });
let ResponseContentDisposition = 'attachment';
if (foundDocument && foundDocument.originName) {
ResponseContentDisposition += `; filename="${foundDocument.originName}"`;
}
const command = new GetObjectCommand({
Bucket: config.s3.bucket,
Key: key,
ResponseContentDisposition,
});
const signedUrl = await getSignedUrl(s3, command, { expiresIn: 300 });

View File

@@ -1,6 +1,8 @@
import { Inject, Service } from 'typedi';
import { DisconnectBankAccount } from './DisconnectBankAccount';
import { RefreshBankAccountService } from './RefreshBankAccount';
import { PauseBankAccountFeeds } from './PauseBankAccountFeeds';
import { ResumeBankAccountFeeds } from './ResumeBankAccountFeeds';
@Service()
export class BankAccountsApplication {
@@ -10,6 +12,12 @@ export class BankAccountsApplication {
@Inject()
private refreshBankAccountService: RefreshBankAccountService;
@Inject()
private resumeBankAccountFeedsService: ResumeBankAccountFeeds;
@Inject()
private pauseBankAccountFeedsService: PauseBankAccountFeeds;
/**
* Disconnects the given bank account.
* @param {number} tenantId
@@ -27,7 +35,7 @@ export class BankAccountsApplication {
* Refresh the bank transactions of the given bank account.
* @param {number} tenantId
* @param {number} bankAccountId
* @returns {Promise<void>}
* @returns {Promise<void>}
*/
async refreshBankAccount(tenantId: number, bankAccountId: number) {
return this.refreshBankAccountService.refreshBankAccount(
@@ -35,4 +43,30 @@ export class BankAccountsApplication {
bankAccountId
);
}
/**
* Pauses the feeds sync of the given bank account.
* @param {number} tenantId
* @param {number} bankAccountId
* @returns {Promise<void>}
*/
async pauseBankAccount(tenantId: number, bankAccountId: number) {
return this.pauseBankAccountFeedsService.pauseBankAccountFeeds(
tenantId,
bankAccountId
);
}
/**
* Resumes the feeds sync of the given bank account.
* @param {number} tenantId
* @param {number} bankAccountId
* @returns {Promise<void>}
*/
async resumeBankAccount(tenantId: number, bankAccountId: number) {
return this.resumeBankAccountFeedsService.resumeBankAccountFeeds(
tenantId,
bankAccountId
);
}
}

View File

@@ -1,6 +1,7 @@
import { Inject, Service } from 'typedi';
import { initialize } from 'objection';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import { UncategorizedTransactionTransformer } from '@/services/Cashflow/UncategorizedTransactionTransformer';
@Service()
export class GetBankAccountSummary {
@@ -31,17 +32,21 @@ export class GetBankAccountSummary {
.findById(bankAccountId)
.throwIfNotFound();
const commonQuery = (q) => {
// Include just the given account.
q.where('accountId', bankAccountId);
// Only the not excluded.
q.modify('notExcluded');
// Only the not categorized.
q.modify('notCategorized');
};
// Retrieves the uncategorized transactions count of the given bank account.
const uncategorizedTranasctionsCount =
await UncategorizedCashflowTransaction.query().onBuild((q) => {
// Include just the given account.
q.where('accountId', bankAccountId);
// Only the not excluded.
q.modify('notExcluded');
// Only the not categorized.
q.modify('notCategorized');
commonQuery(q);
// Only the not matched bank transactions.
q.withGraphJoined('matchedBankTransactions');
@@ -52,25 +57,40 @@ export class GetBankAccountSummary {
q.first();
});
// Retrieves the recognized transactions count of the given bank account.
const recognizedTransactionsCount = await RecognizedBankTransaction.query()
.whereExists(
UncategorizedCashflowTransaction.query().where(
'accountId',
bankAccountId
)
)
.count('id as total')
.first();
// Retrives the recognized transactions count.
const recognizedTransactionsCount =
await UncategorizedCashflowTransaction.query().onBuild((q) => {
commonQuery(q);
q.withGraphJoined('recognizedTransaction');
q.whereNotNull('recognizedTransaction.id');
// Count the results.
q.count('uncategorized_cashflow_transactions.id as total');
q.first();
});
const excludedTransactionsCount =
await UncategorizedCashflowTransaction.query().onBuild((q) => {
q.where('accountId', bankAccountId);
q.modify('excluded');
// Count the results.
q.count('uncategorized_cashflow_transactions.id as total');
q.first();
});
const totalUncategorizedTransactions =
uncategorizedTranasctionsCount?.total || 0;
const totalRecognizedTransactions = recognizedTransactionsCount?.total || 0;
const totalExcludedTransactions = excludedTransactionsCount?.total || 0;
return {
name: bankAccount.name,
totalUncategorizedTransactions,
totalRecognizedTransactions,
totalExcludedTransactions,
};
}
}

View File

@@ -0,0 +1,44 @@
import { Inject, Service } from 'typedi';
import { Knex } from 'knex';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import UnitOfWork from '@/services/UnitOfWork';
import { ServiceError } from '@/exceptions';
import { ERRORS } from './types';
@Service()
export class PauseBankAccountFeeds {
@Inject()
private tenancy: HasTenancyService;
@Inject()
private uow: UnitOfWork;
/**
* Pauses the bankfeed syncing of the given bank account.
* @param {number} tenantId
* @param {number} bankAccountId
* @returns {Promise<void>}
*/
public async pauseBankAccountFeeds(tenantId: number, bankAccountId: number) {
const { Account, PlaidItem } = this.tenancy.models(tenantId);
const oldAccount = await Account.query()
.findById(bankAccountId)
.withGraphFetched('plaidItem')
.throwIfNotFound();
// Can't continue if the bank account is not connected.
if (!oldAccount.plaidItem) {
throw new ServiceError(ERRORS.BANK_ACCOUNT_NOT_CONNECTED);
}
// Cannot continue if the bank account feeds is already paused.
if (oldAccount.plaidItem.isPaused) {
throw new ServiceError(ERRORS.BANK_ACCOUNT_FEEDS_ALREADY_PAUSED);
}
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
await PlaidItem.query(trx).findById(oldAccount.plaidItem.id).patch({
pausedAt: new Date(),
});
});
}
}

View File

@@ -0,0 +1,43 @@
import { Inject, Service } from 'typedi';
import { Knex } from 'knex';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import UnitOfWork from '@/services/UnitOfWork';
import { ServiceError } from '@/exceptions';
import { ERRORS } from './types';
@Service()
export class ResumeBankAccountFeeds {
@Inject()
private tenancy: HasTenancyService;
@Inject()
private uow: UnitOfWork;
/**
* Resumes the bank feeds syncing of the bank account.
* @param {number} tenantId
* @param {number} bankAccountId
* @returns {Promise<void>}
*/
public async resumeBankAccountFeeds(tenantId: number, bankAccountId: number) {
const { Account, PlaidItem } = this.tenancy.models(tenantId);
const oldAccount = await Account.query()
.findById(bankAccountId)
.withGraphFetched('plaidItem');
// Can't continue if the bank account is not connected.
if (!oldAccount.plaidItem) {
throw new ServiceError(ERRORS.BANK_ACCOUNT_NOT_CONNECTED);
}
// Cannot continue if the bank account feeds is already paused.
if (!oldAccount.plaidItem.isPaused) {
throw new ServiceError(ERRORS.BANK_ACCOUNT_FEEDS_ALREADY_RESUMED);
}
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
await PlaidItem.query(trx).findById(oldAccount.plaidItem.id).patch({
pausedAt: null,
});
});
}
}

View File

@@ -14,4 +14,6 @@ export interface IBankAccountDisconnectedEventPayload {
export const ERRORS = {
BANK_ACCOUNT_NOT_CONNECTED: 'BANK_ACCOUNT_NOT_CONNECTED',
BANK_ACCOUNT_FEEDS_ALREADY_PAUSED: 'BANK_ACCOUNT_FEEDS_ALREADY_PAUSED',
BANK_ACCOUNT_FEEDS_ALREADY_RESUMED: 'BANK_ACCOUNT_FEEDS_ALREADY_RESUMED',
};

View File

@@ -1,7 +1,11 @@
import { Knex } from 'knex';
import { Inject, Service } from 'typedi';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import UnitOfWork from '@/services/UnitOfWork';
import { Inject, Service } from 'typedi';
import { validateTransactionNotCategorized } from './utils';
import {
validateTransactionNotCategorized,
validateTransactionNotExcluded,
} from './utils';
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
import events from '@/subscribers/events';
import {
@@ -37,9 +41,13 @@ export class ExcludeBankTransaction {
.findById(uncategorizedTransactionId)
.throwIfNotFound();
// Validate the transaction shouldn't be excluded.
validateTransactionNotExcluded(oldUncategorizedTransaction);
// Validate the transaction shouldn't be categorized.
validateTransactionNotCategorized(oldUncategorizedTransaction);
return this.uow.withTransaction(tenantId, async (trx) => {
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
await this.eventPublisher.emitAsync(events.bankTransactions.onExcluding, {
tenantId,
uncategorizedTransactionId,

View File

@@ -1,6 +1,6 @@
import { Inject, Service } from 'typedi';
import PromisePool from '@supercharge/promise-pool';
import { castArray } from 'lodash';
import { castArray, uniq } from 'lodash';
import { ExcludeBankTransaction } from './ExcludeBankTransaction';
@Service()
@@ -18,7 +18,7 @@ export class ExcludeBankTransactions {
tenantId: number,
bankTransactionIds: Array<number> | number
) {
const _bankTransactionIds = castArray(bankTransactionIds);
const _bankTransactionIds = uniq(castArray(bankTransactionIds));
await PromisePool.withConcurrency(1)
.for(_bankTransactionIds)

View File

@@ -1,7 +1,11 @@
import { Knex } from 'knex';
import { Inject, Service } from 'typedi';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import UnitOfWork from '@/services/UnitOfWork';
import { Inject, Service } from 'typedi';
import { validateTransactionNotCategorized } from './utils';
import {
validateTransactionNotCategorized,
validateTransactionShouldBeExcluded,
} from './utils';
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
import events from '@/subscribers/events';
import {
@@ -37,9 +41,13 @@ export class UnexcludeBankTransaction {
.findById(uncategorizedTransactionId)
.throwIfNotFound();
// Validate the transaction should be excludded.
validateTransactionShouldBeExcluded(oldUncategorizedTransaction);
// Validate the transaction shouldn't be categorized.
validateTransactionNotCategorized(oldUncategorizedTransaction);
return this.uow.withTransaction(tenantId, async (trx) => {
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
await this.eventPublisher.emitAsync(
events.bankTransactions.onUnexcluding,
{

View File

@@ -1,7 +1,7 @@
import { Inject, Service } from 'typedi';
import PromisePool from '@supercharge/promise-pool';
import { UnexcludeBankTransaction } from './UnexcludeBankTransaction';
import { castArray } from 'lodash';
import { castArray, uniq } from 'lodash';
@Service()
export class UnexcludeBankTransactions {
@@ -17,7 +17,7 @@ export class UnexcludeBankTransactions {
tenantId: number,
bankTransactionIds: Array<number> | number
) {
const _bankTransactionIds = castArray(bankTransactionIds);
const _bankTransactionIds = uniq(castArray(bankTransactionIds));
await PromisePool.withConcurrency(1)
.for(_bankTransactionIds)

View File

@@ -3,6 +3,8 @@ import UncategorizedCashflowTransaction from '@/models/UncategorizedCashflowTran
const ERRORS = {
TRANSACTION_ALREADY_CATEGORIZED: 'TRANSACTION_ALREADY_CATEGORIZED',
TRANSACTION_ALREADY_EXCLUDED: 'TRANSACTION_ALREADY_EXCLUDED',
TRANSACTION_NOT_EXCLUDED: 'TRANSACTION_NOT_EXCLUDED',
};
export const validateTransactionNotCategorized = (
@@ -12,3 +14,19 @@ export const validateTransactionNotCategorized = (
throw new ServiceError(ERRORS.TRANSACTION_ALREADY_CATEGORIZED);
}
};
export const validateTransactionNotExcluded = (
transaction: UncategorizedCashflowTransaction
) => {
if (transaction.isExcluded) {
throw new ServiceError(ERRORS.TRANSACTION_ALREADY_EXCLUDED);
}
};
export const validateTransactionShouldBeExcluded = (
transaction: UncategorizedCashflowTransaction
) => {
if (!transaction.isExcluded) {
throw new ServiceError(ERRORS.TRANSACTION_NOT_EXCLUDED);
}
};

View File

@@ -1,6 +1,7 @@
import { Inject, Service } from 'typedi';
import * as R from 'ramda';
import moment from 'moment';
import { first, sumBy } from 'lodash';
import { PromisePool } from '@supercharge/promise-pool';
import { GetMatchedTransactionsFilter, MatchedTransactionsPOJO } from './types';
import { GetMatchedTransactionsByExpenses } from './GetMatchedTransactionsByExpenses';
@@ -47,21 +48,24 @@ export class GetMatchedTransactions {
/**
* Retrieves the matched transactions.
* @param {number} tenantId -
* @param {Array<number>} uncategorizedTransactionIds - Uncategorized transactions ids.
* @param {GetMatchedTransactionsFilter} filter -
* @returns {Promise<MatchedTransactionsPOJO>}
*/
public async getMatchedTransactions(
tenantId: number,
uncategorizedTransactionId: number,
uncategorizedTransactionIds: Array<number>,
filter: GetMatchedTransactionsFilter
): Promise<MatchedTransactionsPOJO> {
const { UncategorizedCashflowTransaction } = this.tenancy.models(tenantId);
const uncategorizedTransaction =
const uncategorizedTransactions =
await UncategorizedCashflowTransaction.query()
.findById(uncategorizedTransactionId)
.whereIn('id', uncategorizedTransactionIds)
.throwIfNotFound();
const totalPending = Math.abs(sumBy(uncategorizedTransactions, 'amount'));
const filtered = filter.transactionType
? this.registered.filter((item) => item.type === filter.transactionType)
: this.registered;
@@ -71,14 +75,14 @@ export class GetMatchedTransactions {
.process(async ({ type, service }) => {
return service.getMatchedTransactions(tenantId, filter);
});
const { perfectMatches, possibleMatches } = this.groupMatchedResults(
uncategorizedTransaction,
uncategorizedTransactions,
matchedTransactions
);
return {
perfectMatches,
possibleMatches,
totalPending,
};
}
@@ -90,20 +94,20 @@ export class GetMatchedTransactions {
* @returns {MatchedTransactionsPOJO}
*/
private groupMatchedResults(
uncategorizedTransaction,
uncategorizedTransactions: Array<any>,
matchedTransactions
): MatchedTransactionsPOJO {
const results = R.compose(R.flatten)(matchedTransactions?.results);
const firstUncategorized = first(uncategorizedTransactions);
const amount = sumBy(uncategorizedTransactions, 'amount');
const date = firstUncategorized.date;
// Sort the results based on amount, date, and transaction type
const closestResullts = sortClosestMatchTransactions(
uncategorizedTransaction,
results
);
const closestResullts = sortClosestMatchTransactions(amount, date, results);
const perfectMatches = R.filter(
(match) =>
match.amount === uncategorizedTransaction.amount &&
moment(match.date).isSame(uncategorizedTransaction.date, 'day'),
match.amount === amount && moment(match.date).isSame(date, 'day'),
closestResullts
);
const possibleMatches = R.difference(closestResullts, perfectMatches);

View File

@@ -7,6 +7,7 @@ import {
MatchedTransactionsPOJO,
} from './types';
import { Inject, Service } from 'typedi';
import PromisePool from '@supercharge/promise-pool';
export abstract class GetMatchedTransactionsByType {
@Inject()
@@ -43,24 +44,28 @@ export abstract class GetMatchedTransactionsByType {
}
/**
*
* Creates the common matched transaction.
* @param {number} tenantId
* @param {number} uncategorizedTransactionId
* @param {Array<number>} uncategorizedTransactionIds
* @param {IMatchTransactionDTO} matchTransactionDTO
* @param {Knex.Transaction} trx
*/
public async createMatchedTransaction(
tenantId: number,
uncategorizedTransactionId: number,
uncategorizedTransactionIds: Array<number>,
matchTransactionDTO: IMatchTransactionDTO,
trx?: Knex.Transaction
) {
const { MatchedBankTransaction } = this.tenancy.models(tenantId);
await MatchedBankTransaction.query(trx).insert({
uncategorizedTransactionId,
referenceType: matchTransactionDTO.referenceType,
referenceId: matchTransactionDTO.referenceId,
});
await PromisePool.withConcurrency(2)
.for(uncategorizedTransactionIds)
.process(async (uncategorizedTransactionId) => {
await MatchedBankTransaction.query(trx).insert({
uncategorizedTransactionId,
referenceType: matchTransactionDTO.referenceType,
referenceId: matchTransactionDTO.referenceId,
});
});
}
}

View File

@@ -2,7 +2,7 @@ import { Inject, Service } from 'typedi';
import { GetMatchedTransactions } from './GetMatchedTransactions';
import { MatchBankTransactions } from './MatchTransactions';
import { UnmatchMatchedBankTransaction } from './UnmatchMatchedTransaction';
import { GetMatchedTransactionsFilter, IMatchTransactionsDTO } from './types';
import { GetMatchedTransactionsFilter, IMatchTransactionDTO } from './types';
@Service()
export class MatchBankTransactionsApplication {
@@ -23,12 +23,12 @@ export class MatchBankTransactionsApplication {
*/
public getMatchedTransactions(
tenantId: number,
uncategorizedTransactionId: number,
uncategorizedTransactionsIds: Array<number>,
filter: GetMatchedTransactionsFilter
) {
return this.getMatchedTransactionsService.getMatchedTransactions(
tenantId,
uncategorizedTransactionId,
uncategorizedTransactionsIds,
filter
);
}
@@ -42,13 +42,13 @@ export class MatchBankTransactionsApplication {
*/
public matchTransaction(
tenantId: number,
uncategorizedTransactionId: number,
matchTransactionsDTO: IMatchTransactionsDTO
uncategorizedTransactionId: number | Array<number>,
matchedTransactions: Array<IMatchTransactionDTO>
): Promise<void> {
return this.matchTransactionService.matchTransaction(
tenantId,
uncategorizedTransactionId,
matchTransactionsDTO
matchedTransactions
);
}

View File

@@ -1,4 +1,4 @@
import { isEmpty } from 'lodash';
import { castArray } from 'lodash';
import { Knex } from 'knex';
import { Inject, Service } from 'typedi';
import { PromisePool } from '@supercharge/promise-pool';
@@ -10,11 +10,16 @@ import {
ERRORS,
IBankTransactionMatchedEventPayload,
IBankTransactionMatchingEventPayload,
IMatchTransactionsDTO,
IMatchTransactionDTO,
} from './types';
import { MatchTransactionsTypes } from './MatchTransactionsTypes';
import { ServiceError } from '@/exceptions';
import { sumMatchTranasctions } from './_utils';
import {
sumMatchTranasctions,
sumUncategorizedTransactions,
validateUncategorizedTransactionsExcluded,
validateUncategorizedTransactionsNotMatched,
} from './_utils';
@Service()
export class MatchBankTransactions {
@@ -39,27 +44,25 @@ export class MatchBankTransactions {
*/
async validate(
tenantId: number,
uncategorizedTransactionId: number,
matchTransactionsDTO: IMatchTransactionsDTO
uncategorizedTransactionId: number | Array<number>,
matchedTransactions: Array<IMatchTransactionDTO>
) {
const { UncategorizedCashflowTransaction } = this.tenancy.models(tenantId);
const { matchedTransactions } = matchTransactionsDTO;
const uncategorizedTransactionIds = castArray(uncategorizedTransactionId);
// Validates the uncategorized transaction existance.
const uncategorizedTransaction =
const uncategorizedTransactions =
await UncategorizedCashflowTransaction.query()
.findById(uncategorizedTransactionId)
.whereIn('id', uncategorizedTransactionIds)
.withGraphFetched('matchedBankTransactions')
.throwIfNotFound();
// Validates the uncategorized transaction is not already matched.
if (!isEmpty(uncategorizedTransaction.matchedBankTransactions)) {
throw new ServiceError(ERRORS.TRANSACTION_ALREADY_MATCHED);
}
validateUncategorizedTransactionsNotMatched(uncategorizedTransactions);
// Validate the uncategorized transaction is not excluded.
if (uncategorizedTransaction.excluded) {
throw new ServiceError(ERRORS.CANNOT_MATCH_EXCLUDED_TRANSACTION);
}
validateUncategorizedTransactionsExcluded(uncategorizedTransactions);
// Validates the given matched transaction.
const validateMatchedTransaction = async (matchedTransaction) => {
const getMatchedTransactionsService =
@@ -94,9 +97,12 @@ export class MatchBankTransactions {
const totalMatchedTranasctions = sumMatchTranasctions(
validatationResult.results
);
const totalUncategorizedTransactions = sumUncategorizedTransactions(
uncategorizedTransactions
);
// Validates the total given matching transcations whether is not equal
// uncategorized transaction amount.
if (totalMatchedTranasctions !== uncategorizedTransaction.amount) {
if (totalUncategorizedTransactions !== totalMatchedTranasctions) {
throw new ServiceError(ERRORS.TOTAL_MATCHING_TRANSACTIONS_INVALID);
}
}
@@ -109,23 +115,23 @@ export class MatchBankTransactions {
*/
public async matchTransaction(
tenantId: number,
uncategorizedTransactionId: number,
matchTransactionsDTO: IMatchTransactionsDTO
uncategorizedTransactionId: number | Array<number>,
matchedTransactions: Array<IMatchTransactionDTO>
): Promise<void> {
const { matchedTransactions } = matchTransactionsDTO;
const uncategorizedTransactionIds = castArray(uncategorizedTransactionId);
// Validates the given matching transactions DTO.
await this.validate(
tenantId,
uncategorizedTransactionId,
matchTransactionsDTO
uncategorizedTransactionIds,
matchedTransactions
);
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
// Triggers the event `onBankTransactionMatching`.
await this.eventPublisher.emitAsync(events.bankMatch.onMatching, {
tenantId,
uncategorizedTransactionId,
matchTransactionsDTO,
uncategorizedTransactionIds,
matchedTransactions,
trx,
} as IBankTransactionMatchingEventPayload);
@@ -139,17 +145,16 @@ export class MatchBankTransactions {
);
await getMatchedTransactionsService.createMatchedTransaction(
tenantId,
uncategorizedTransactionId,
uncategorizedTransactionIds,
matchedTransaction,
trx
);
});
// Triggers the event `onBankTransactionMatched`.
await this.eventPublisher.emitAsync(events.bankMatch.onMatched, {
tenantId,
uncategorizedTransactionId,
matchTransactionsDTO,
uncategorizedTransactionIds,
matchedTransactions,
trx,
} as IBankTransactionMatchedEventPayload);
});

View File

@@ -1,22 +1,23 @@
import moment from 'moment';
import * as R from 'ramda';
import UncategorizedCashflowTransaction from '@/models/UncategorizedCashflowTransaction';
import { MatchedTransactionPOJO } from './types';
import { ERRORS, MatchedTransactionPOJO } from './types';
import { isEmpty, sumBy } from 'lodash';
import { ServiceError } from '@/exceptions';
export const sortClosestMatchTransactions = (
uncategorizedTransaction: UncategorizedCashflowTransaction,
amount: number,
date: Date,
matches: MatchedTransactionPOJO[]
) => {
return R.sortWith([
// Sort by amount difference (closest to uncategorized transaction amount first)
R.ascend((match: MatchedTransactionPOJO) =>
Math.abs(match.amount - uncategorizedTransaction.amount)
Math.abs(match.amount - amount)
),
// Sort by date difference (closest to uncategorized transaction date first)
R.ascend((match: MatchedTransactionPOJO) =>
Math.abs(
moment(match.date).diff(moment(uncategorizedTransaction.date), 'days')
)
Math.abs(moment(match.date).diff(moment(date), 'days'))
),
])(matches);
};
@@ -29,3 +30,36 @@ export const sumMatchTranasctions = (transactions: Array<any>) => {
0
);
};
export const sumUncategorizedTransactions = (
uncategorizedTransactions: Array<any>
) => {
return sumBy(uncategorizedTransactions, 'amount');
};
export const validateUncategorizedTransactionsNotMatched = (
uncategorizedTransactions: any
) => {
const matchedTransactions = uncategorizedTransactions.filter(
(trans) => !isEmpty(trans.matchedBankTransactions)
);
//
if (matchedTransactions.length > 0) {
throw new ServiceError(ERRORS.TRANSACTION_ALREADY_MATCHED, '', {
matchedTransactionsIds: matchedTransactions?.map((m) => m.id),
});
}
};
export const validateUncategorizedTransactionsExcluded = (
uncategorizedTransactions: any
) => {
const excludedTransactions = uncategorizedTransactions.filter(
(trans) => trans.excluded
);
if (excludedTransactions.length > 0) {
throw new ServiceError(ERRORS.CANNOT_MATCH_EXCLUDED_TRANSACTION, '', {
excludedTransactionsIds: excludedTransactions.map((e) => e.id),
});
}
};

View File

@@ -5,6 +5,7 @@ import {
IBankTransactionUnmatchedEventPayload,
} from '../types';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import PromisePool from '@supercharge/promise-pool';
@Service()
export class DecrementUncategorizedTransactionOnMatching {
@@ -30,18 +31,24 @@ export class DecrementUncategorizedTransactionOnMatching {
*/
public async decrementUnCategorizedTransactionsOnMatching({
tenantId,
uncategorizedTransactionId,
uncategorizedTransactionIds,
trx,
}: IBankTransactionMatchedEventPayload) {
const { UncategorizedCashflowTransaction, Account } =
this.tenancy.models(tenantId);
const transaction = await UncategorizedCashflowTransaction.query().findById(
uncategorizedTransactionId
);
await Account.query(trx)
.findById(transaction.accountId)
.decrement('uncategorizedTransactions', 1);
const uncategorizedTransactions =
await UncategorizedCashflowTransaction.query().whereIn(
'id',
uncategorizedTransactionIds
);
await PromisePool.withConcurrency(1)
.for(uncategorizedTransactions)
.process(async (transaction) => {
await Account.query(trx)
.findById(transaction.accountId)
.decrement('uncategorizedTransactions', 1);
});
}
/**

View File

@@ -2,15 +2,15 @@ import { Knex } from 'knex';
export interface IBankTransactionMatchingEventPayload {
tenantId: number;
uncategorizedTransactionId: number;
matchTransactionsDTO: IMatchTransactionsDTO;
uncategorizedTransactionIds: Array<number>;
matchedTransactions: Array<IMatchTransactionDTO>;
trx?: Knex.Transaction;
}
export interface IBankTransactionMatchedEventPayload {
tenantId: number;
uncategorizedTransactionId: number;
matchTransactionsDTO: IMatchTransactionsDTO;
uncategorizedTransactionIds: Array<number>;
matchedTransactions: Array<IMatchTransactionDTO>;
trx?: Knex.Transaction;
}
@@ -32,6 +32,7 @@ export interface IMatchTransactionDTO {
}
export interface IMatchTransactionsDTO {
uncategorizedTransactionIds: Array<number>;
matchedTransactions: Array<IMatchTransactionDTO>;
}
@@ -57,6 +58,7 @@ export interface MatchedTransactionPOJO {
export type MatchedTransactionsPOJO = {
perfectMatches: Array<MatchedTransactionPOJO>;
possibleMatches: Array<MatchedTransactionPOJO>;
totalPending: number;
};
export const ERRORS = {

View File

@@ -1,11 +1,15 @@
import { Inject, Service } from 'typedi';
import { PlaidUpdateTransactions } from './PlaidUpdateTransactions';
import HasTenancyService from '@/services/Tenancy/TenancyService';
@Service()
export class PlaidWebooks {
@Inject()
private updateTransactionsService: PlaidUpdateTransactions;
@Inject()
private tenancy: HasTenancyService;
/**
* Listens to Plaid webhooks
* @param {number} tenantId - Tenant Id.
@@ -61,7 +65,7 @@ export class PlaidWebooks {
plaidItemId: string
): void {
console.log(
`WEBHOOK: TRANSACTIONS: ${webhookCode}: Plaid_item_id ${plaidItemId}: ${additionalInfo}`
`PLAID WEBHOOK: TRANSACTIONS: ${webhookCode}: Plaid_item_id ${plaidItemId}: ${additionalInfo}`
);
}
@@ -78,8 +82,21 @@ export class PlaidWebooks {
plaidItemId: string,
webhookCode: string
): Promise<void> {
const { PlaidItem } = this.tenancy.models(tenantId);
const plaidItem = await PlaidItem.query()
.findById(plaidItemId)
.throwIfNotFound();
switch (webhookCode) {
case 'SYNC_UPDATES_AVAILABLE': {
if (plaidItem.isPaused) {
this.serverLogAndEmitSocket(
'Plaid item syncing is paused.',
webhookCode,
plaidItemId
);
return;
}
// Fired when new transactions data becomes available.
const { addedCount, modifiedCount, removedCount } =
await this.updateTransactionsService.updateTransactions(

View File

@@ -0,0 +1,45 @@
import { Inject, Service } from 'typedi';
import { castArray, first, uniq } from 'lodash';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import { TransformerInjectable } from '@/lib/Transformer/TransformerInjectable';
import { GetAutofillCategorizeTransctionTransformer } from './GetAutofillCategorizeTransactionTransformer';
@Service()
export class GetAutofillCategorizeTransaction {
@Inject()
private tenancy: HasTenancyService;
@Inject()
private transformer: TransformerInjectable;
/**
* Retrieves the autofill values of categorize transactions form.
* @param {number} tenantId - Tenant id.
* @param {Array<number> | number} uncategorizeTransactionsId - Uncategorized transactions ids.
*/
public async getAutofillCategorizeTransaction(
tenantId: number,
uncategorizeTransactionsId: Array<number> | number
) {
const { UncategorizedCashflowTransaction } = this.tenancy.models(tenantId);
const uncategorizeTransactionsIds = uniq(
castArray(uncategorizeTransactionsId)
);
const uncategorizedTransactions =
await UncategorizedCashflowTransaction.query()
.whereIn('id', uncategorizeTransactionsIds)
.withGraphFetched('recognizedTransaction.assignAccount')
.withGraphFetched('recognizedTransaction.bankRule')
.throwIfNotFound();
return this.transformer.transform(
tenantId,
{},
new GetAutofillCategorizeTransctionTransformer(),
{
uncategorizedTransactions,
firstUncategorizedTransaction: first(uncategorizedTransactions),
}
);
}
}

View File

@@ -0,0 +1,176 @@
import { Transformer } from '@/lib/Transformer/Transformer';
import { sumBy } from 'lodash';
export class GetAutofillCategorizeTransctionTransformer extends Transformer {
/**
* Included attributes to the object.
* @returns {Array}
*/
public includeAttributes = (): string[] => {
return [
'amount',
'formattedAmount',
'isRecognized',
'date',
'formattedDate',
'creditAccountId',
'debitAccountId',
'referenceNo',
'transactionType',
'recognizedByRuleId',
'recognizedByRuleName',
'isWithdrawalTransaction',
'isDepositTransaction',
];
};
/**
* Detarmines whether the transaction is recognized.
* @returns {boolean}
*/
public isRecognized() {
return !!this.options.firstUncategorizedTransaction?.recognizedTransaction;
}
/**
* Retrieves the total amount of uncategorized transactions.
* @returns {number}
*/
public amount() {
return sumBy(this.options.uncategorizedTransactions, 'amount');
}
/**
* Retrieves the formatted total amount of uncategorized transactions.
* @returns {string}
*/
public formattedAmount() {
return this.formatNumber(this.amount(), {
currencyCode: 'USD',
money: true,
});
}
/**
* Detarmines whether the transaction is deposit.
* @returns {boolean}
*/
public isDepositTransaction() {
const amount = this.amount();
return amount > 0;
}
/**
* Detarmines whether the transaction is withdrawal.
* @returns {boolean}
*/
public isWithdrawalTransaction() {
const amount = this.amount();
return amount < 0;
}
/**
*
* @param {string}
*/
public date() {
return this.options.firstUncategorizedTransaction?.date || null;
}
/**
* Retrieves the formatted date of uncategorized transaction.
* @returns {string}
*/
public formattedDate() {
return this.formatDate(this.date());
}
/**
*
* @param {string}
*/
public referenceNo() {
return this.options.firstUncategorizedTransaction?.referenceNo || null;
}
/**
*
* @returns {number}
*/
public creditAccountId() {
return (
this.options.firstUncategorizedTransaction?.recognizedTransaction
?.assignedAccountId || null
);
}
/**
*
* @returns {number}
*/
public debitAccountId() {
return this.options.firstUncategorizedTransaction?.accountId || null;
}
/**
* Retrieves the assigned category of recognized transaction, if is not recognized
* returns the default transaction type depends on the transaction normal.
* @returns {string}
*/
public transactionType() {
const assignedCategory =
this.options.firstUncategorizedTransaction?.recognizedTransaction
?.assignedCategory;
return (
assignedCategory ||
(this.isDepositTransaction() ? 'other_income' : 'other_expense')
);
}
/**
*
* @returns {string}
*/
public payee() {
return (
this.options.firstUncategorizedTransaction?.recognizedTransaction
?.assignedPayee || null
);
}
/**
*
* @returns {string}
*/
public memo() {
return (
this.options.firstUncategorizedTransaction?.recognizedTransaction
?.assignedMemo || null
);
}
/**
* Retrieves the rule id the transaction recongized by.
* @returns {string}
*/
public recognizedByRuleId() {
return (
this.options.firstUncategorizedTransaction?.recognizedTransaction
?.bankRuleId || null
);
}
/**
* Retrieves the rule name the transaction recongized by.
* @returns {string}
*/
public recognizedByRuleName() {
return (
this.options.firstUncategorizedTransaction?.recognizedTransaction
?.bankRule?.name || null
);
}
}

View File

@@ -1,8 +1,8 @@
import { Knex } from 'knex';
import { Inject, Service } from 'typedi';
import UncategorizedCashflowTransaction from '@/models/UncategorizedCashflowTransaction';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import { transformToMapBy } from '@/utils';
import { Inject, Service } from 'typedi';
import { PromisePool } from '@supercharge/promise-pool';
import { BankRule } from '@/models/BankRule';
import { bankRulesMatchTransaction } from './_utils';

View File

@@ -1,3 +1,4 @@
import { lowerCase } from 'lodash';
import UncategorizedCashflowTransaction from '@/models/UncategorizedCashflowTransaction';
import {
BankRuleApplyIfTransactionType,
@@ -51,12 +52,15 @@ const matchNumberCondition = (
const matchTextCondition = (
transaction: UncategorizedCashflowTransaction,
condition: IBankRuleCondition
) => {
): boolean => {
switch (condition.comparator) {
case BankRuleConditionComparator.Equals:
return transaction[condition.field] === condition.value;
case BankRuleConditionComparator.Contains:
return transaction[condition.field]?.includes(condition.value.toString());
const fieldValue = lowerCase(transaction[condition.field]);
const conditionValue = lowerCase(condition.value);
return fieldValue.includes(conditionValue);
case BankRuleConditionComparator.NotContain:
return !transaction[condition.field]?.includes(
condition.value.toString()
@@ -101,4 +105,4 @@ const determineFieldType = (field: string): string => {
default:
return 'unknown';
}
};
};

View File

@@ -64,9 +64,10 @@ export class EditBankRuleService {
} as IBankRuleEventEditingPayload);
// Updates the given bank rule.
await BankRule.query(trx)
.findById(ruleId)
.patch({ ...tranformDTO });
await BankRule.query(trx).upsertGraphAndFetch({
...tranformDTO,
id: ruleId,
});
// Triggers `onBankRuleEdited` event.
await this.eventPublisher.emitAsync(events.bankRules.onEdited, {

View File

@@ -16,7 +16,7 @@ export interface IBankRuleCondition {
id?: number;
field: BankRuleConditionField;
comparator: BankRuleConditionComparator;
value: number;
value: string;
}
export enum BankRuleConditionType {

View File

@@ -164,12 +164,12 @@ export class CashflowApplication {
*/
public categorizeTransaction(
tenantId: number,
cashflowTransactionId: number,
uncategorizeTransactionIds: Array<number>,
categorizeDTO: ICategorizeCashflowTransactioDTO
) {
return this.categorizeTransactionService.categorize(
tenantId,
cashflowTransactionId,
uncategorizeTransactionIds,
categorizeDTO
);
}

View File

@@ -1,4 +1,6 @@
import { Inject, Service } from 'typedi';
import { castArray } from 'lodash';
import { Knex } from 'knex';
import HasTenancyService from '../Tenancy/TenancyService';
import events from '@/subscribers/events';
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
@@ -8,12 +10,12 @@ import {
ICashflowTransactionUncategorizingPayload,
ICategorizeCashflowTransactioDTO,
} from '@/interfaces';
import { Knex } from 'knex';
import { transformCategorizeTransToCashflow } from './utils';
import {
transformCategorizeTransToCashflow,
validateUncategorizedTransactionsNotExcluded,
} from './utils';
import { CommandCashflowValidator } from './CommandCasflowValidator';
import NewCashflowTransactionService from './NewCashflowTransactionService';
import { ServiceError } from '@/exceptions';
import { ERRORS } from './constants';
@Service()
export class CategorizeCashflowTransaction {
@@ -39,27 +41,29 @@ export class CategorizeCashflowTransaction {
*/
public async categorize(
tenantId: number,
uncategorizedTransactionId: number,
uncategorizedTransactionId: number | Array<number>,
categorizeDTO: ICategorizeCashflowTransactioDTO
) {
const { UncategorizedCashflowTransaction } = this.tenancy.models(tenantId);
const uncategorizedTransactionIds = castArray(uncategorizedTransactionId);
// Retrieves the uncategorized transaction or throw an error.
const transaction = await UncategorizedCashflowTransaction.query()
.findById(uncategorizedTransactionId)
.throwIfNotFound();
const oldUncategorizedTransactions =
await UncategorizedCashflowTransaction.query()
.whereIn('id', uncategorizedTransactionIds)
.throwIfNotFound();
// Validate cannot categorize excluded transaction.
if (transaction.excluded) {
throw new ServiceError(ERRORS.CANNOT_CATEGORIZE_EXCLUDED_TRANSACTION);
}
// Validates the transaction shouldn't be categorized before.
this.commandValidators.validateTransactionShouldNotCategorized(transaction);
validateUncategorizedTransactionsNotExcluded(oldUncategorizedTransactions);
// Validates the transaction shouldn't be categorized before.
this.commandValidators.validateTransactionsShouldNotCategorized(
oldUncategorizedTransactions
);
// Validate the uncateogirzed transaction if it's deposit the transaction direction
// should `IN` and the same thing if it's withdrawal the direction should be OUT.
this.commandValidators.validateUncategorizeTransactionType(
transaction,
oldUncategorizedTransactions,
categorizeDTO.transactionType
);
// Edits the cashflow transaction under UOW env.
@@ -69,12 +73,13 @@ export class CategorizeCashflowTransaction {
events.cashflow.onTransactionCategorizing,
{
tenantId,
oldUncategorizedTransactions,
trx,
} as ICashflowTransactionUncategorizingPayload
);
// Transformes the categorize DTO to the cashflow transaction.
const cashflowTransactionDTO = transformCategorizeTransToCashflow(
transaction,
oldUncategorizedTransactions,
categorizeDTO
);
// Creates a new cashflow transaction.
@@ -83,15 +88,20 @@ export class CategorizeCashflowTransaction {
tenantId,
cashflowTransactionDTO
);
// Updates the uncategorized transaction as categorized.
const uncategorizedTransaction =
await UncategorizedCashflowTransaction.query(trx).patchAndFetchById(
uncategorizedTransactionId,
{
categorized: true,
categorizeRefType: 'CashflowTransaction',
categorizeRefId: cashflowTransaction.id,
}
await UncategorizedCashflowTransaction.query(trx)
.whereIn('id', uncategorizedTransactionIds)
.patch({
categorized: true,
categorizeRefType: 'CashflowTransaction',
categorizeRefId: cashflowTransaction.id,
});
// Fetch the new updated uncategorized transactions.
const uncategorizedTransactions =
await UncategorizedCashflowTransaction.query(trx).whereIn(
'id',
uncategorizedTransactionIds
);
// Triggers `onCashflowTransactionCategorized` event.
await this.eventPublisher.emitAsync(
@@ -99,7 +109,8 @@ export class CategorizeCashflowTransaction {
{
tenantId,
cashflowTransaction,
uncategorizedTransaction,
uncategorizedTransactions,
oldUncategorizedTransactions,
categorizeDTO,
trx,
} as ICashflowTransactionCategorizedPayload

View File

@@ -1,5 +1,5 @@
import { Service } from 'typedi';
import { includes, camelCase, upperFirst } from 'lodash';
import { includes, camelCase, upperFirst, sumBy } from 'lodash';
import { IAccount, IUncategorizedCashflowTransaction } from '@/interfaces';
import { getCashflowTransactionType } from './utils';
import { ServiceError } from '@/exceptions';
@@ -68,11 +68,15 @@ export class CommandCashflowValidator {
* Validate the given transcation shouldn't be categorized.
* @param {CashflowTransaction} cashflowTransaction
*/
public validateTransactionShouldNotCategorized(
cashflowTransaction: CashflowTransaction
public validateTransactionsShouldNotCategorized(
cashflowTransactions: Array<IUncategorizedCashflowTransaction>
) {
if (cashflowTransaction.uncategorize) {
throw new ServiceError(ERRORS.TRANSACTION_ALREADY_CATEGORIZED);
const categorized = cashflowTransactions.filter((t) => t.categorized);
if (categorized?.length > 0) {
throw new ServiceError(ERRORS.TRANSACTION_ALREADY_CATEGORIZED, '', {
ids: categorized.map((t) => t.id),
});
}
}
@@ -83,17 +87,19 @@ export class CommandCashflowValidator {
* @throws {ServiceError(ERRORS.UNCATEGORIZED_TRANSACTION_TYPE_INVALID)}
*/
public validateUncategorizeTransactionType(
uncategorizeTransaction: IUncategorizedCashflowTransaction,
uncategorizeTransactions: Array<IUncategorizedCashflowTransaction>,
transactionType: string
) {
const amount = sumBy(uncategorizeTransactions, 'amount');
const isDepositTransaction = amount > 0;
const isWithdrawalTransaction = amount <= 0;
const type = getCashflowTransactionType(
upperFirst(camelCase(transactionType)) as CASHFLOW_TRANSACTION_TYPE
transactionType as CASHFLOW_TRANSACTION_TYPE
);
if (
(type.direction === CASHFLOW_DIRECTION.IN &&
uncategorizeTransaction.isDepositTransaction) ||
(type.direction === CASHFLOW_DIRECTION.OUT &&
uncategorizeTransaction.isWithdrawalTransaction)
(type.direction === CASHFLOW_DIRECTION.IN && isDepositTransaction) ||
(type.direction === CASHFLOW_DIRECTION.OUT && isWithdrawalTransaction)
) {
return;
}

View File

@@ -34,6 +34,7 @@ export class GetRecognizedTransactionsService {
q.withGraphFetched('recognizedTransaction.assignAccount');
q.withGraphFetched('recognizedTransaction.bankRule');
q.whereNotNull('recognizedTransactionId');
q.modify('notExcluded');
if (_filter.accountId) {
q.where('accountId', _filter.accountId);

View File

@@ -8,6 +8,7 @@ import {
ICashflowTransactionUncategorizedPayload,
ICashflowTransactionUncategorizingPayload,
} from '@/interfaces';
import { validateTransactionShouldBeCategorized } from './utils';
@Service()
export class UncategorizeCashflowTransaction {
@@ -24,11 +25,12 @@ export class UncategorizeCashflowTransaction {
* Uncategorizes the given cashflow transaction.
* @param {number} tenantId
* @param {number} cashflowTransactionId
* @returns {Promise<Array<number>>}
*/
public async uncategorize(
tenantId: number,
uncategorizedTransactionId: number
) {
): Promise<Array<number>> {
const { UncategorizedCashflowTransaction } = this.tenancy.models(tenantId);
const oldUncategorizedTransaction =
@@ -36,6 +38,22 @@ export class UncategorizeCashflowTransaction {
.findById(uncategorizedTransactionId)
.throwIfNotFound();
validateTransactionShouldBeCategorized(oldUncategorizedTransaction);
const associatedUncategorizedTransactions =
await UncategorizedCashflowTransaction.query()
.where('categorizeRefId', oldUncategorizedTransaction.categorizeRefId)
.where(
'categorizeRefType',
oldUncategorizedTransaction.categorizeRefType
);
const oldUncategorizedTransactions = [
oldUncategorizedTransaction,
...associatedUncategorizedTransactions,
];
const oldUncategoirzedTransactionsIds = oldUncategorizedTransactions.map(
(t) => t.id
);
// Updates the transaction under UOW.
return this.uow.withTransaction(tenantId, async (trx: Knex.Transaction) => {
// Triggers `onTransactionUncategorizing` event.
@@ -43,30 +61,36 @@ export class UncategorizeCashflowTransaction {
events.cashflow.onTransactionUncategorizing,
{
tenantId,
uncategorizedTransactionId,
oldUncategorizedTransactions,
trx,
} as ICashflowTransactionUncategorizingPayload
);
// Removes the ref relation with the related transaction.
const uncategorizedTransaction =
await UncategorizedCashflowTransaction.query(trx).updateAndFetchById(
uncategorizedTransactionId,
{
categorized: false,
categorizeRefId: null,
categorizeRefType: null,
}
await UncategorizedCashflowTransaction.query(trx)
.whereIn('id', oldUncategoirzedTransactionsIds)
.patch({
categorized: false,
categorizeRefId: null,
categorizeRefType: null,
});
const uncategorizedTransactions =
await UncategorizedCashflowTransaction.query(trx).whereIn(
'id',
oldUncategoirzedTransactionsIds
);
// Triggers `onTransactionUncategorized` event.
await this.eventPublisher.emitAsync(
events.cashflow.onTransactionUncategorized,
{
tenantId,
uncategorizedTransaction,
oldUncategorizedTransaction,
uncategorizedTransactionId,
uncategorizedTransactions,
oldUncategorizedTransactions,
trx,
} as ICashflowTransactionUncategorizedPayload
);
return uncategorizedTransaction;
return oldUncategoirzedTransactionsIds;
});
}
}

View File

@@ -16,7 +16,9 @@ export const ERRORS = {
CANNOT_DELETE_TRANSACTION_CONVERTED_FROM_UNCATEGORIZED:
'CANNOT_DELETE_TRANSACTION_CONVERTED_FROM_UNCATEGORIZED',
CANNOT_CATEGORIZE_EXCLUDED_TRANSACTION: 'CANNOT_CATEGORIZE_EXCLUDED_TRANSACTION'
CANNOT_CATEGORIZE_EXCLUDED_TRANSACTION: 'CANNOT_CATEGORIZE_EXCLUDED_TRANSACTION',
TRANSACTION_NOT_CATEGORIZED: 'TRANSACTION_NOT_CATEGORIZED'
};
export enum CASHFLOW_DIRECTION {

View File

@@ -5,6 +5,7 @@ import {
ICashflowTransactionCategorizedPayload,
ICashflowTransactionUncategorizedPayload,
} from '@/interfaces';
import PromisePool from '@supercharge/promise-pool';
@Service()
export class DecrementUncategorizedTransactionOnCategorize {
@@ -34,13 +35,18 @@ export class DecrementUncategorizedTransactionOnCategorize {
*/
public async decrementUnCategorizedTransactionsOnCategorized({
tenantId,
uncategorizedTransaction,
uncategorizedTransactions,
trx
}: ICashflowTransactionCategorizedPayload) {
const { Account } = this.tenancy.models(tenantId);
await Account.query()
.findById(uncategorizedTransaction.accountId)
.decrement('uncategorizedTransactions', 1);
await PromisePool.withConcurrency(1)
.for(uncategorizedTransactions)
.process(async (uncategorizedTransaction) => {
await Account.query(trx)
.findById(uncategorizedTransaction.accountId)
.decrement('uncategorizedTransactions', 1);
});
}
/**
@@ -49,13 +55,18 @@ export class DecrementUncategorizedTransactionOnCategorize {
*/
public async incrementUnCategorizedTransactionsOnUncategorized({
tenantId,
uncategorizedTransaction,
uncategorizedTransactions,
trx
}: ICashflowTransactionUncategorizedPayload) {
const { Account } = this.tenancy.models(tenantId);
await Account.query()
.findById(uncategorizedTransaction.accountId)
.increment('uncategorizedTransactions', 1);
await PromisePool.withConcurrency(1)
.for(uncategorizedTransactions)
.process(async (uncategorizedTransaction) => {
await Account.query(trx)
.findById(uncategorizedTransaction.accountId)
.increment('uncategorizedTransactions', 1);
});
}
/**

View File

@@ -1,8 +1,10 @@
import { Inject, Service } from 'typedi';
import { PromisePool } from '@supercharge/promise-pool';
import events from '@/subscribers/events';
import { ICashflowTransactionUncategorizedPayload } from '@/interfaces';
import { DeleteCashflowTransaction } from '../DeleteCashflowTransactionService';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import { ServiceError } from '@/exceptions';
@Service()
export class DeleteCashflowTransactionOnUncategorize {
@@ -25,18 +27,27 @@ export class DeleteCashflowTransactionOnUncategorize {
*/
public async deleteCashflowTransactionOnUncategorize({
tenantId,
oldUncategorizedTransaction,
oldUncategorizedTransactions,
trx,
}: ICashflowTransactionUncategorizedPayload) {
// Deletes the cashflow transaction.
if (
oldUncategorizedTransaction.categorizeRefType === 'CashflowTransaction'
) {
await this.deleteCashflowTransactionService.deleteCashflowTransaction(
tenantId,
const _oldUncategorizedTransactions = oldUncategorizedTransactions.filter(
(transaction) => transaction.categorizeRefType === 'CashflowTransaction'
);
oldUncategorizedTransaction.categorizeRefId
);
// Deletes the cashflow transaction.
if (_oldUncategorizedTransactions.length > 0) {
const result = await PromisePool.withConcurrency(1)
.for(_oldUncategorizedTransactions)
.process(async (oldUncategorizedTransaction) => {
await this.deleteCashflowTransactionService.deleteCashflowTransaction(
tenantId,
oldUncategorizedTransaction.categorizeRefId,
trx
);
});
if (result.errors.length > 0) {
throw new ServiceError('SOMETHING_WRONG');
}
}
}
}

View File

@@ -1,7 +1,8 @@
import { upperFirst, camelCase } from 'lodash';
import { upperFirst, camelCase, first, sum, sumBy } from 'lodash';
import {
CASHFLOW_TRANSACTION_TYPE,
CASHFLOW_TRANSACTION_TYPE_META,
ERRORS,
ICashflowTransactionTypeMeta,
} from './constants';
import {
@@ -9,6 +10,8 @@ import {
ICategorizeCashflowTransactioDTO,
IUncategorizedCashflowTransaction,
} from '@/interfaces';
import { UncategorizeCashflowTransaction } from './UncategorizeCashflowTransaction';
import { ServiceError } from '@/exceptions';
/**
* Ensures the given transaction type to transformed to appropriate format.
@@ -27,7 +30,9 @@ export const transformCashflowTransactionType = (type) => {
export function getCashflowTransactionType(
transactionType: CASHFLOW_TRANSACTION_TYPE
): ICashflowTransactionTypeMeta {
return CASHFLOW_TRANSACTION_TYPE_META[transactionType];
const _transactionType = transformCashflowTransactionType(transactionType);
return CASHFLOW_TRANSACTION_TYPE_META[_transactionType];
}
/**
@@ -46,22 +51,46 @@ export const getCashflowAccountTransactionsTypes = () => {
* @returns {ICashflowNewCommandDTO}
*/
export const transformCategorizeTransToCashflow = (
uncategorizeModel: IUncategorizedCashflowTransaction,
uncategorizeTransactions: Array<IUncategorizedCashflowTransaction>,
categorizeDTO: ICategorizeCashflowTransactioDTO
): ICashflowNewCommandDTO => {
const uncategorizeTransaction = first(uncategorizeTransactions);
const amount = sumBy(uncategorizeTransactions, 'amount');
const amountAbs = Math.abs(amount);
return {
date: uncategorizeModel.date,
referenceNo: categorizeDTO.referenceNo || uncategorizeModel.referenceNo,
description: categorizeDTO.description || uncategorizeModel.description,
cashflowAccountId: uncategorizeModel.accountId,
date: categorizeDTO.date,
referenceNo: categorizeDTO.referenceNo,
description: categorizeDTO.description,
cashflowAccountId: uncategorizeTransaction.accountId,
creditAccountId: categorizeDTO.creditAccountId,
exchangeRate: categorizeDTO.exchangeRate || 1,
currencyCode: uncategorizeModel.currencyCode,
amount: uncategorizeModel.amount,
currencyCode: categorizeDTO.currencyCode,
amount: amountAbs,
transactionNumber: categorizeDTO.transactionNumber,
transactionType: categorizeDTO.transactionType,
uncategorizedTransactionId: uncategorizeModel.id,
branchId: categorizeDTO?.branchId,
publish: true,
};
};
export const validateUncategorizedTransactionsNotExcluded = (
transactions: Array<UncategorizeCashflowTransaction>
) => {
const excluded = transactions.filter((tran) => tran.excluded);
if (excluded?.length > 0) {
throw new ServiceError(ERRORS.CANNOT_CATEGORIZE_EXCLUDED_TRANSACTION, '', {
ids: excluded.map((t) => t.id),
});
}
};
export const validateTransactionShouldBeCategorized = (
uncategorizedTransaction: any
) => {
if (!uncategorizedTransaction.categorized) {
throw new ServiceError(ERRORS.TRANSACTION_NOT_CATEGORIZED);
}
};

View File

@@ -163,8 +163,6 @@ export class GetSubscriptionsTransformer extends Transformer {
*/
public lemonUrls = (subscription) => {
const lemonSusbcription = this.lemonSubscription(subscription);
console.log(lemonSusbcription);
return lemonSusbcription?.data?.attributes?.urls;
};
}

View File

@@ -1,5 +1,9 @@
import React from 'react';
import { AppShellProvider, useAppShellContext } from './AppContentShellProvider';
// @ts-nocheck
import React, { forwardRef, Ref } from 'react';
import {
AppShellProvider,
useAppShellContext,
} from './AppContentShellProvider';
import { Box, BoxProps } from '../../Layout';
import styles from './AppContentShell.module.scss';
@@ -12,50 +16,73 @@ interface AppContentShellProps {
hideMain?: boolean;
}
export function AppContentShell({
asideProps,
mainProps,
topbarOffset = 0,
hideAside = false,
hideMain = false,
...restProps
}: AppContentShellProps) {
return (
<AppShellProvider
mainProps={mainProps}
asideProps={asideProps}
topbarOffset={topbarOffset}
hideAside={hideAside}
hideMain={hideMain}
>
<Box {...restProps} className={styles.root} />
</AppShellProvider>
);
}
export const AppContentShell = forwardRef(
(
{
asideProps,
mainProps,
topbarOffset = 0,
hideAside = false,
hideMain = false,
...restProps
}: AppContentShellProps,
ref: Ref<HTMLDivElement>,
) => {
return (
<AppShellProvider
mainProps={mainProps}
asideProps={asideProps}
topbarOffset={topbarOffset}
hideAside={hideAside}
hideMain={hideMain}
>
<Box {...restProps} className={styles.root} ref={ref} />
</AppShellProvider>
);
},
);
AppContentShell.displayName = 'AppContentShell';
interface AppContentShellMainProps extends BoxProps {}
function AppContentShellMain({ ...props }: AppContentShellMainProps) {
const { hideMain } = useAppShellContext();
/**
* Main content of the app shell.
* @param {AppContentShellMainProps} props -
* @returns {React.ReactNode}
*/
const AppContentShellMain = forwardRef(
({ ...props }: AppContentShellMainProps, ref: Ref<HTMLDivElement>) => {
const { hideMain } = useAppShellContext();
if (hideMain === true) {
return null;
}
return <Box {...props} className={styles.main} />;
}
if (hideMain === true) {
return null;
}
return <Box {...props} className={styles.main} ref={ref} />;
},
);
AppContentShellMain.displayName = 'AppContentShellMain';
interface AppContentShellAsideProps extends BoxProps {
children: React.ReactNode;
}
function AppContentShellAside({ ...props }: AppContentShellAsideProps) {
const { hideAside } = useAppShellContext();
/**
* Aside content of the app shell.
* @param {AppContentShellAsideProps} props
* @returns {React.ReactNode}
*/
const AppContentShellAside = forwardRef(
({ ...props }: AppContentShellAsideProps, ref: Ref<HTMLDivElement>) => {
const { hideAside } = useAppShellContext();
if (hideAside === true) {
return null;
}
return <Box {...props} className={styles.aside} />;
}
if (hideAside === true) {
return null;
}
return <Box {...props} className={styles.aside} ref={ref} />;
},
);
AppContentShellAside.displayName = 'AppContentShellAside';
AppContentShell.Main = AppContentShellMain;
AppContentShell.Aside = AppContentShellAside;

View File

@@ -15,7 +15,7 @@ import { useAuthActions } from '@/hooks/state';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import { useAuthenticatedAccount, useDashboardMeta } from '@/hooks/query';
import { useAuthenticatedAccount } from '@/hooks/query';
import { firstLettersArgs, compose } from '@/utils';
/**
@@ -31,9 +31,6 @@ function DashboardTopbarUser({
// Retrieve authenticated user information.
const { data: user } = useAuthenticatedAccount();
const { data: dashboardMeta } = useDashboardMeta({
keepPreviousData: true,
});
const onClickLogout = () => {
setLogout();
};
@@ -61,12 +58,6 @@ function DashboardTopbarUser({
}
/>
<MenuDivider />
{dashboardMeta.is_bigcapital_cloud && (
<MenuItem
text={'Billing'}
onClick={() => history.push('/billing')}
/>
)}
<MenuItem
text={<T id={'keyboard_shortcuts'} />}
onClick={onKeyboardShortcut}

View File

@@ -25,14 +25,13 @@ function TableVirtualizedListRow({ index, isScrolling, isVisible, style }) {
export function TableVirtualizedListRows() {
const {
table: { page },
props: { vListrowHeight, vListOverscanRowCount },
props: { vListrowHeight, vListOverscanRowCount, windowScrollerProps },
} = useContext(TableContext);
// Dashboard content pane.
const dashboardContentPane = React.useMemo(
() => document.querySelector(`.${CLASSES.DASHBOARD_CONTENT_PANE}`),
[],
);
const scrollElement =
windowScrollerProps?.scrollElement ||
document.querySelector(`.${CLASSES.DASHBOARD_CONTENT_PANE}`);
const rowRenderer = React.useCallback(
({ key, ...args }) => <TableVirtualizedListRow {...args} key={key} />,
@@ -40,7 +39,7 @@ export function TableVirtualizedListRows() {
);
return (
<WindowScroller scrollElement={dashboardContentPane}>
<WindowScroller scrollElement={scrollElement}>
{({ height, isScrolling, onChildScroll, scrollTop }) => (
<AutoSizer disableHeight>
{({ width }) => (

View File

@@ -52,6 +52,7 @@ import ReceiptMailDialog from '@/containers/Sales/Receipts/ReceiptMailDialog/Rec
import PaymentMailDialog from '@/containers/Sales/PaymentReceives/PaymentMailDialog/PaymentMailDialog';
import { ExportDialog } from '@/containers/Dialogs/ExportDialog';
import { RuleFormDialog } from '@/containers/Banking/Rules/RuleFormDialog/RuleFormDialog';
import { DisconnectBankAccountDialog } from '@/containers/CashFlow/AccountTransactions/dialogs/DisconnectBankAccountDialog/DisconnectBankAccountDialog';
/**
* Dialogs container.
@@ -148,7 +149,10 @@ export default function DialogsContainer() {
<ReceiptMailDialog dialogName={DialogsName.ReceiptMail} />
<PaymentMailDialog dialogName={DialogsName.PaymentMail} />
<ExportDialog dialogName={DialogsName.Export} />
<RuleFormDialog dialogName={DialogsName.BankRuleForm} />
<RuleFormDialog dialogName={DialogsName.BankRuleForm} />
<DisconnectBankAccountDialog
dialogName={DialogsName.DisconnectBankAccountConfirmation}
/>
</div>
);
}

View File

@@ -1,12 +1,15 @@
import React from 'react';
import React, { forwardRef, Ref } from 'react';
import { HTMLDivProps, Props } from '@blueprintjs/core';
export interface BoxProps extends Props, HTMLDivProps {
className?: string;
}
export function Box({ className, ...rest }: BoxProps) {
const Element = 'div';
export const Box = forwardRef(
({ className, ...rest }: BoxProps, ref: Ref<HTMLDivElement>) => {
const Element = 'div';
return <Element className={className} {...rest} />;
}
return <Element className={className} ref={ref} {...rest} />;
},
);
Box.displayName = '@bigcapital/Box';

View File

@@ -75,5 +75,6 @@ export enum DialogsName {
GeneralLedgerPdfPreview = 'GeneralLedgerPdfPreview',
SalesTaxLiabilitySummaryPdfPreview = 'SalesTaxLiabilitySummaryPdfPreview',
Export = 'Export',
BankRuleForm = 'BankRuleForm'
BankRuleForm = 'BankRuleForm',
DisconnectBankAccountConfirmation = 'DisconnectBankAccountConfirmation',
}

View File

@@ -8,6 +8,10 @@ export default [
disabled: false,
href: '/preferences/general',
},
{
text: 'Billing',
href: '/preferences/billing',
},
{
text: <T id={'users'} />,
href: '/preferences/users',

View File

@@ -0,0 +1,10 @@
export const BANK_QUERY_KEY = {
BANK_RULES: 'BANK_RULE',
BANK_TRANSACTION_MATCHES: 'BANK_TRANSACTION_MATCHES',
RECOGNIZED_BANK_TRANSACTION: 'RECOGNIZED_BANK_TRANSACTION',
EXCLUDED_BANK_TRANSACTIONS_INFINITY: 'EXCLUDED_BANK_TRANSACTIONS_INFINITY',
RECOGNIZED_BANK_TRANSACTIONS_INFINITY:
'RECOGNIZED_BANK_TRANSACTIONS_INFINITY',
BANK_ACCOUNT_SUMMARY_META: 'BANK_ACCOUNT_SUMMARY_META',
AUTOFILL_CATEGORIZE_BANK_TRANSACTION: 'AUTOFILL_CATEGORIZE_BANK_TRANSACTION',
};

View File

@@ -28,6 +28,7 @@ import TaxRatesAlerts from '@/containers/TaxRates/alerts';
import { CashflowAlerts } from '../CashFlow/CashflowAlerts';
import { BankRulesAlerts } from '../Banking/Rules/RulesList/BankRulesAlerts';
import { SubscriptionAlerts } from '../Subscriptions/alerts/alerts';
import { BankAccountAlerts } from '@/containers/CashFlow/AccountTransactions/alerts';
export default [
...AccountsAlerts,
@@ -58,5 +59,6 @@ export default [
...TaxRatesAlerts,
...CashflowAlerts,
...BankRulesAlerts,
...SubscriptionAlerts
...SubscriptionAlerts,
...BankAccountAlerts,
];

View File

@@ -12,6 +12,7 @@ import {
PopoverInteractionKind,
Position,
Intent,
Switch,
Tooltip,
MenuDivider,
} from '@blueprintjs/core';
@@ -40,12 +41,14 @@ import withSettingsActions from '@/containers/Settings/withSettingsActions';
import { compose } from '@/utils';
import {
useDisconnectBankAccount,
useUpdateBankAccount,
useExcludeUncategorizedTransactions,
useUnexcludeUncategorizedTransactions,
} from '@/hooks/query/bank-rules';
import { withBankingActions } from '../withBankingActions';
import { withBanking } from '../withBanking';
import withAlertActions from '@/containers/Alert/withAlertActions';
import { DialogsName } from '@/constants/dialogs';
function AccountTransactionsActionsBar({
// #withDialogActions
@@ -60,6 +63,13 @@ function AccountTransactionsActionsBar({
// #withBanking
uncategorizedTransationsIdsSelected,
excludedTransactionsIdsSelected,
openMatchingTransactionAside,
// #withBankingActions
enableMultipleCategorization,
// #withAlerts
openAlert,
}) {
const history = useHistory();
const { accountId, currentAccount } = useAccountTransactionsContext();
@@ -67,7 +77,6 @@ function AccountTransactionsActionsBar({
// Refresh cashflow infinity transactions hook.
const { refresh } = useRefreshCashflowTransactionsInfinity();
const { mutateAsync: disconnectBankAccount } = useDisconnectBankAccount();
const { mutateAsync: updateBankAccount } = useUpdateBankAccount();
// Retrieves the money in/out buttons options.
@@ -75,6 +84,7 @@ function AccountTransactionsActionsBar({
const addMoneyOutOptions = useMemo(() => getAddMoneyOutOptions(), []);
const isFeedsActive = !!currentAccount.is_feeds_active;
const isFeedsPaused = currentAccount.is_feeds_paused;
const isSyncingOwner = currentAccount.is_syncing_owner;
// Handle table row size change.
@@ -108,19 +118,9 @@ function AccountTransactionsActionsBar({
// Handles the bank account disconnect click.
const handleDisconnectClick = () => {
disconnectBankAccount({ bankAccountId: accountId })
.then(() => {
AppToaster.show({
message: 'The bank account has been disconnected.',
intent: Intent.SUCCESS,
});
})
.catch((error) => {
AppToaster.show({
message: 'Something went wrong.',
intent: Intent.DANGER,
});
});
openDialog(DialogsName.DisconnectBankAccountConfirmation, {
bankAccountId: accountId,
});
};
// handles the bank update button click.
const handleBankUpdateClick = () => {
@@ -191,6 +191,23 @@ function AccountTransactionsActionsBar({
});
};
// Handle multi select transactions for categorization or matching.
const handleMultipleCategorizingSwitch = (event) => {
enableMultipleCategorization(event.currentTarget.checked);
}
// Handle resume bank feeds syncing.
const handleResumeFeedsSyncing = () => {
openAlert('resume-feeds-syncing-bank-accounnt', {
bankAccountId: accountId,
});
};
// Handles pause bank feeds syncing.
const handlePauseFeedsSyncing = () => {
openAlert('pause-feeds-syncing-bank-accounnt', {
bankAccountId: accountId,
});
};
return (
<DashboardActionsBar>
<NavbarGroup>
@@ -238,7 +255,9 @@ function AccountTransactionsActionsBar({
<Tooltip
content={
isFeedsActive
? 'The bank syncing is active'
? isFeedsPaused
? 'The bank syncing is paused'
: 'The bank syncing is active'
: 'The bank syncing is disconnected'
}
minimal={true}
@@ -247,7 +266,13 @@ function AccountTransactionsActionsBar({
<Button
className={Classes.MINIMAL}
icon={<Icon icon="feed" iconSize={16} />}
intent={isFeedsActive ? Intent.SUCCESS : Intent.DANGER}
intent={
isFeedsActive
? isFeedsPaused
? Intent.WARNING
: Intent.SUCCESS
: Intent.DANGER
}
/>
</Tooltip>
</If>
@@ -275,6 +300,22 @@ function AccountTransactionsActionsBar({
</NavbarGroup>
<NavbarGroup align={Alignment.RIGHT}>
{openMatchingTransactionAside && (
<Tooltip
content={
'Enables to categorize or matching multiple bank transactions into one transaction.'
}
position={Position.BOTTOM}
minimal
>
<Switch
label={'Multi Select'}
inline
onChange={handleMultipleCategorizingSwitch}
/>
</Tooltip>
)}
<NavbarDivider />
<Popover
minimal={true}
interactionKind={PopoverInteractionKind.CLICK}
@@ -288,6 +329,23 @@ function AccountTransactionsActionsBar({
<MenuItem onClick={handleBankUpdateClick} text={'Update'} />
<MenuDivider />
</If>
<If condition={isSyncingOwner && isFeedsActive && !isFeedsPaused}>
<MenuItem
onClick={handlePauseFeedsSyncing}
text={'Pause bank feeds'}
/>
<MenuDivider />
</If>
<If condition={isSyncingOwner && isFeedsActive && isFeedsPaused}>
<MenuItem
onClick={handleResumeFeedsSyncing}
text={'Resume bank feeds'}
/>
<MenuDivider />
</If>
<MenuItem onClick={handleBankRulesClick} text={'Bank rules'} />
<If condition={isSyncingOwner && isFeedsActive}>
@@ -311,6 +369,7 @@ function AccountTransactionsActionsBar({
export default compose(
withDialogActions,
withAlertActions,
withSettingsActions,
withSettings(({ cashflowTransactionsSettings }) => ({
cashflowTansactionsTableSize: cashflowTransactionsSettings?.tableSize,
@@ -319,9 +378,12 @@ export default compose(
({
uncategorizedTransationsIdsSelected,
excludedTransactionsIdsSelected,
openMatchingTransactionAside,
}) => ({
uncategorizedTransationsIdsSelected,
excludedTransactionsIdsSelected,
openMatchingTransactionAside,
}),
),
withBankingActions,
)(AccountTransactionsActionsBar);

View File

@@ -1,4 +1,5 @@
// @ts-nocheck
import { useMemo } from 'react';
import styled from 'styled-components';
import { ContentTabs } from '@/components/ContentTabs/ContentTabs';
import { useAccountTransactionsContext } from './AccountTransactionsProvider';
@@ -8,15 +9,19 @@ const AccountContentTabs = styled(ContentTabs)`
`;
export function AccountTransactionsFilterTabs() {
const { filterTab, setFilterTab, currentAccount } =
const { filterTab, setFilterTab, bankAccountMetaSummary, currentAccount } =
useAccountTransactionsContext();
const handleChange = (value) => {
setFilterTab(value);
};
const hasUncategorizedTransx = Boolean(
currentAccount.uncategorized_transactions,
// Detarmines whether show the uncategorized transactions tab.
const hasUncategorizedTransx = useMemo(
() =>
bankAccountMetaSummary?.totalUncategorizedTransactions > 0 ||
bankAccountMetaSummary?.totalExcludedTransactions > 0,
[bankAccountMetaSummary],
);
return (

View File

@@ -29,28 +29,41 @@ function AccountTransactionsListRoot({
return (
<AccountTransactionsProvider>
<AppContentShell hideAside={!openMatchingTransactionAside}>
<AppContentShell.Main>
<AccountTransactionsActionsBar />
<AccountTransactionsDetailsBar />
<AccountTransactionsProgressBar />
<DashboardPageContent>
<AccountTransactionsFilterTabs />
<Suspense fallback={<Spinner size={30} />}>
<AccountTransactionsContent />
</Suspense>
</DashboardPageContent>
</AppContentShell.Main>
<AppContentShell.Aside>
<CategorizeTransactionAside />
</AppContentShell.Aside>
<AccountTransactionsMain />
<AccountTransactionsAside />
</AppContentShell>
</AccountTransactionsProvider>
);
}
function AccountTransactionsMain() {
const { setScrollableRef } = useAccountTransactionsContext();
return (
<AppContentShell.Main ref={(e) => setScrollableRef(e)}>
<AccountTransactionsActionsBar />
<AccountTransactionsDetailsBar />
<AccountTransactionsProgressBar />
<DashboardPageContent>
<AccountTransactionsFilterTabs />
<Suspense fallback={<Spinner size={30} />}>
<AccountTransactionsContent />
</Suspense>
</DashboardPageContent>
</AppContentShell.Main>
);
}
function AccountTransactionsAside() {
return (
<AppContentShell.Aside>
<CategorizeTransactionAside />
</AppContentShell.Aside>
);
}
export default R.compose(
withBanking(
({ selectedUncategorizedTransactionId, openMatchingTransactionAside }) => ({

View File

@@ -1,5 +1,5 @@
// @ts-nocheck
import React from 'react';
import React, { useRef, useState } from 'react';
import { useParams } from 'react-router-dom';
import { DashboardInsider } from '@/components';
import { useCashflowAccounts, useAccount } from '@/hooks/query';
@@ -41,6 +41,8 @@ function AccountTransactionsProvider({ query, ...props }) {
isLoading: isBankAccountMetaSummaryLoading,
} = useGetBankAccountSummaryMeta(accountId);
const [scrollableRef, setScrollableRef] = useState();
// Provider payload.
const provider = {
accountId,
@@ -56,6 +58,9 @@ function AccountTransactionsProvider({ query, ...props }) {
filterTab,
setFilterTab,
scrollableRef,
setScrollableRef
};
return (

View File

@@ -16,6 +16,7 @@ import { TABLES } from '@/constants/tables';
import { useMemorizedColumnsWidths } from '@/hooks';
import { useExcludedTransactionsColumns } from './_utils';
import { useExcludedTransactionsBoot } from './ExcludedTransactionsTableBoot';
import { useAccountTransactionsContext } from '../AccountTransactionsProvider';
import { ActionsMenu } from './_components';
import { useUnexcludeUncategorizedTransaction } from '@/hooks/query/bank-rules';
@@ -37,6 +38,8 @@ function ExcludedTransactionsTableRoot({
const { mutateAsync: unexcludeBankTransaction } =
useUnexcludeUncategorizedTransaction();
const { scrollableRef } = useAccountTransactionsContext();
// Retrieve table columns.
const columns = useExcludedTransactionsColumns();
@@ -97,6 +100,7 @@ function ExcludedTransactionsTableRoot({
className="table-constrant"
selectionColumn={true}
onSelectedRowsChange={handleSelectedRowsChange}
windowScrollerProps={{ scrollElement: scrollableRef }}
payload={{
onRestore: handleRestoreClick,
}}

View File

@@ -20,6 +20,7 @@ import { useRecognizedTransactionsBoot } from './RecognizedTransactionsTableBoot
import { ActionsMenu } from './_components';
import { compose } from '@/utils';
import { useAccountTransactionsContext } from '../AccountTransactionsProvider';
import { useExcludeUncategorizedTransaction } from '@/hooks/query/bank-rules';
import {
WithBankingActionsProps,
@@ -33,8 +34,8 @@ interface RecognizedTransactionsTableProps extends WithBankingActionsProps {}
* Renders the recognized account transactions datatable.
*/
function RecognizedTransactionsTableRoot({
// #withBanking
setUncategorizedTransactionIdForMatching,
// #withBankingActions
setTransactionsToCategorizeSelected,
}: RecognizedTransactionsTableProps) {
const { mutateAsync: excludeBankTransaction } =
useExcludeUncategorizedTransaction();
@@ -49,9 +50,11 @@ function RecognizedTransactionsTableRoot({
const [initialColumnsWidths, , handleColumnResizing] =
useMemorizedColumnsWidths(TABLES.UNCATEGORIZED_ACCOUNT_TRANSACTIONS);
const { scrollableRef } = useAccountTransactionsContext();
// Handle cell click.
const handleCellClick = (cell, event) => {
setUncategorizedTransactionIdForMatching(
setTransactionsToCategorizeSelected(
cell.row.original.uncategorized_transaction_id,
);
};
@@ -74,7 +77,7 @@ function RecognizedTransactionsTableRoot({
// Handles categorize button click.
const handleCategorizeClick = (transaction) => {
setUncategorizedTransactionIdForMatching(
setTransactionsToCategorizeSelected(
transaction.uncategorized_transaction_id,
);
};
@@ -102,6 +105,7 @@ function RecognizedTransactionsTableRoot({
vListOverscanRowCount={0}
initialColumnsWidths={initialColumnsWidths}
onColumnResizing={handleColumnResizing}
windowScrollerProps={{ scrollElement: scrollableRef }}
noResults={<RecognizedTransactionsTableNoResults />}
className="table-constrant"
payload={{

View File

@@ -0,0 +1,15 @@
.table :global .td.categorize_include,
.table :global .th.categorize_include {
display: none;
}
.table.showCategorizeColumn :global .td.categorize_include,
.table.showCategorizeColumn :global .th.categorize_include {
display: flex;
}
.categorizeCheckbox:global(.bp4-checkbox) :global .bp4-control-indicator {
border-radius: 20px;
}

View File

@@ -1,5 +1,6 @@
// @ts-nocheck
import React from 'react';
import clsx from 'classnames';
import styled from 'styled-components';
import { Intent } from '@blueprintjs/core';
import {
@@ -12,17 +13,20 @@ import {
AppToaster,
} from '@/components';
import { TABLES } from '@/constants/tables';
import { ActionsMenu } from './UncategorizedTransactions/components';
import { ActionsMenu } from './components';
import withSettings from '@/containers/Settings/withSettings';
import { withBankingActions } from '../withBankingActions';
import { withBankingActions } from '../../withBankingActions';
import { useMemorizedColumnsWidths } from '@/hooks';
import { useAccountUncategorizedTransactionsColumns } from './components';
import { useAccountUncategorizedTransactionsContext } from './AllTransactionsUncategorizedBoot';
import { useAccountUncategorizedTransactionsContext } from '../AllTransactionsUncategorizedBoot';
import { useExcludeUncategorizedTransaction } from '@/hooks/query/bank-rules';
import { useAccountUncategorizedTransactionsColumns } from './hooks';
import { useAccountTransactionsContext } from '../AccountTransactionsProvider';
import { compose } from '@/utils';
import { withBanking } from '../../withBanking';
import styles from './AccountTransactionsUncategorizedTable.module.scss';
/**
* Account transactions data table.
@@ -31,13 +35,22 @@ function AccountTransactionsDataTable({
// #withSettings
cashflowTansactionsTableSize,
// #withBanking
openMatchingTransactionAside,
enableMultipleCategorization,
// #withBankingActions
setUncategorizedTransactionIdForMatching,
setUncategorizedTransactionsSelected,
addTransactionsToCategorizeSelected,
setTransactionsToCategorizeSelected,
}) {
// Retrieve table columns.
const columns = useAccountUncategorizedTransactionsColumns();
const { scrollableRef } = useAccountTransactionsContext();
// Retrieve list context.
const { uncategorizedTransactions, isUncategorizedTransactionsLoading } =
useAccountUncategorizedTransactionsContext();
@@ -51,12 +64,21 @@ function AccountTransactionsDataTable({
// Handle cell click.
const handleCellClick = (cell) => {
setUncategorizedTransactionIdForMatching(cell.row.original.id);
if (enableMultipleCategorization) {
addTransactionsToCategorizeSelected(cell.row.original.id);
} else {
setTransactionsToCategorizeSelected(cell.row.original.id);
}
};
// Handles categorize button click.
const handleCategorizeBtnClick = (transaction) => {
setUncategorizedTransactionIdForMatching(transaction.id);
};
// handles table selected rows change.
const handleSelectedRowsChange = (selected) => {
const transactionIds = selected.map((r) => r.original.id);
setUncategorizedTransactionsSelected(transactionIds);
};
// Handle exclude transaction.
const handleExcludeTransaction = (transaction) => {
excludeTransaction(transaction.id)
@@ -66,7 +88,7 @@ function AccountTransactionsDataTable({
message: 'The bank transaction has been excluded successfully.',
});
})
.catch((error) => {
.catch(() => {
AppToaster.show({
intent: Intent.DANGER,
message: 'Something went wrong.',
@@ -74,12 +96,6 @@ function AccountTransactionsDataTable({
});
};
// Handle selected rows change.
const handleSelectedRowsChange = (selected) => {
const _selectedIds = selected?.map((row) => row.original.id);
setUncategorizedTransactionsSelected(_selectedIds);
};
return (
<CashflowTransactionsTable
noInitialFetch={true}
@@ -106,12 +122,15 @@ function AccountTransactionsDataTable({
noResults={
'There is no uncategorized transactions in the current account.'
}
className="table-constrant"
onSelectedRowsChange={handleSelectedRowsChange}
payload={{
onExclude: handleExcludeTransaction,
onCategorize: handleCategorizeBtnClick,
}}
onSelectedRowsChange={handleSelectedRowsChange}
windowScrollerProps={{ scrollElement: scrollableRef }}
className={clsx('table-constrant', styles.table, {
[styles.showCategorizeColumn]: enableMultipleCategorization,
})}
/>
);
}
@@ -121,6 +140,12 @@ export default compose(
cashflowTansactionsTableSize: cashflowTransactionsSettings?.tableSize,
})),
withBankingActions,
withBanking(
({ openMatchingTransactionAside, enableMultipleCategorization }) => ({
openMatchingTransactionAside,
enableMultipleCategorization,
}),
),
)(AccountTransactionsDataTable);
const DashboardConstrantTable = styled(DataTable)`

View File

@@ -1,6 +1,6 @@
import * as R from 'ramda';
import { useEffect } from 'react';
import AccountTransactionsUncategorizedTable from '../AccountTransactionsUncategorizedTable';
import AccountTransactionsUncategorizedTable from './AccountTransactionsUncategorizedTable';
import { AccountUncategorizedTransactionsBoot } from '../AllTransactionsUncategorizedBoot';
import { AccountTransactionsCard } from './AccountTransactionsCard';
import {

View File

@@ -0,0 +1,157 @@
// @ts-nocheck
import React from 'react';
import intl from 'react-intl-universal';
import {
Checkbox,
Intent,
PopoverInteractionKind,
Position,
Tag,
Tooltip,
} from '@blueprintjs/core';
import {
useAddTransactionsToCategorizeSelected,
useIsTransactionToCategorizeSelected,
useRemoveTransactionsToCategorizeSelected,
} from '@/hooks/state/banking';
import { Box, Icon } from '@/components';
import styles from './AccountTransactionsUncategorizedTable.module.scss';
function statusAccessor(transaction) {
return transaction.is_recognized ? (
<Tooltip
interactionKind={PopoverInteractionKind.HOVER}
position={Position.RIGHT}
content={
<Box>
<span>{transaction.assigned_category_formatted}</span>
<Icon
icon={'arrowRight'}
color={'#8F99A8'}
iconSize={12}
style={{ marginLeft: 8, marginRight: 8 }}
/>
<span>{transaction.assigned_account_name}</span>
</Box>
}
>
<Box>
<Tag intent={Intent.SUCCESS} interactive>
Recognized
</Tag>
</Box>
</Tooltip>
) : null;
}
interface TransactionSelectCheckboxProps {
transactionId: number;
}
function TransactionSelectCheckbox({
transactionId,
}: TransactionSelectCheckboxProps) {
const addTransactionsToCategorizeSelected =
useAddTransactionsToCategorizeSelected();
const removeTransactionsToCategorizeSelected =
useRemoveTransactionsToCategorizeSelected();
const isTransactionSelected =
useIsTransactionToCategorizeSelected(transactionId);
const handleChange = (event) => {
isTransactionSelected
? removeTransactionsToCategorizeSelected(transactionId)
: addTransactionsToCategorizeSelected(transactionId);
};
return (
<Checkbox
large
checked={isTransactionSelected}
onChange={handleChange}
className={styles.categorizeCheckbox}
/>
);
}
/**
* Retrieve account uncategorized transctions table columns.
*/
export function useAccountUncategorizedTransactionsColumns() {
return React.useMemo(
() => [
{
id: 'date',
Header: intl.get('date'),
accessor: 'formatted_date',
width: 40,
clickable: true,
textOverview: true,
},
{
id: 'description',
Header: 'Description',
accessor: 'description',
width: 160,
textOverview: true,
clickable: true,
},
{
id: 'payee',
Header: 'Payee',
accessor: 'payee',
width: 60,
clickable: true,
textOverview: true,
},
{
id: 'reference_number',
Header: 'Ref.#',
accessor: 'reference_no',
width: 50,
clickable: true,
textOverview: true,
},
{
id: 'status',
Header: 'Status',
accessor: statusAccessor,
},
{
id: 'deposit',
Header: intl.get('cash_flow.label.deposit'),
accessor: 'formatted_deposit_amount',
width: 40,
className: 'deposit',
textOverview: true,
align: 'right',
clickable: true,
},
{
id: 'withdrawal',
Header: intl.get('cash_flow.label.withdrawal'),
accessor: 'formatted_withdrawal_amount',
className: 'withdrawal',
width: 40,
textOverview: true,
align: 'right',
clickable: true,
},
{
id: 'categorize_include',
Header: '',
accessor: (value) => (
<TransactionSelectCheckbox transactionId={value.id} />
),
width: 20,
minWidth: 20,
maxWidth: 20,
align: 'right',
className: 'categorize_include selection-checkbox',
},
],
[],
);
}

View File

@@ -0,0 +1,68 @@
// @ts-nocheck
import React from 'react';
import { Intent, Alert } from '@blueprintjs/core';
import { AppToaster, FormattedMessage as T } from '@/components';
import withAlertStoreConnect from '@/containers/Alert/withAlertStoreConnect';
import withAlertActions from '@/containers/Alert/withAlertActions';
import { usePauseFeedsBankAccount } from '@/hooks/query/bank-accounts';
import { compose } from '@/utils';
/**
* Pause feeds of the bank account alert.
*/
function PauseFeedsBankAccountAlert({
name,
// #withAlertStoreConnect
isOpen,
payload: { bankAccountId },
// #withAlertActions
closeAlert,
}) {
const { mutateAsync: pauseBankAccountFeeds, isLoading } =
usePauseFeedsBankAccount();
// Handle activate item alert cancel.
const handleCancelActivateItem = () => {
closeAlert(name);
};
// Handle confirm item activated.
const handleConfirmItemActivate = () => {
pauseBankAccountFeeds({ bankAccountId })
.then(() => {
AppToaster.show({
message: 'The bank feeds of the bank account has been paused.',
intent: Intent.SUCCESS,
});
})
.catch((error) => {})
.finally(() => {
closeAlert(name);
});
};
return (
<Alert
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={'Pause bank feeds'}
intent={Intent.WARNING}
isOpen={isOpen}
onCancel={handleCancelActivateItem}
loading={isLoading}
onConfirm={handleConfirmItemActivate}
>
<p>
Are you sure want to pause bank feeds syncing of this bank account, you
can always resume it again?
</p>
</Alert>
);
}
export default compose(
withAlertStoreConnect(),
withAlertActions,
)(PauseFeedsBankAccountAlert);

View File

@@ -0,0 +1,69 @@
// @ts-nocheck
import React from 'react';
import { Intent, Alert } from '@blueprintjs/core';
import { AppToaster, FormattedMessage as T } from '@/components';
import withAlertStoreConnect from '@/containers/Alert/withAlertStoreConnect';
import withAlertActions from '@/containers/Alert/withAlertActions';
import { useResumeFeedsBankAccount } from '@/hooks/query/bank-accounts';
import { compose } from '@/utils';
/**
* Resume bank account feeds alert.
*/
function ResumeFeedsBankAccountAlert({
name,
// #withAlertStoreConnect
isOpen,
payload: { bankAccountId },
// #withAlertActions
closeAlert,
}) {
const { mutateAsync: resumeFeedsBankAccount, isLoading } =
useResumeFeedsBankAccount();
// Handle activate item alert cancel.
const handleCancelActivateItem = () => {
closeAlert(name);
};
// Handle confirm item activated.
const handleConfirmItemActivate = () => {
resumeFeedsBankAccount({ bankAccountId })
.then(() => {
AppToaster.show({
message: 'The bank feeds of the bank account has been resumed.',
intent: Intent.SUCCESS,
});
})
.catch((error) => {})
.finally(() => {
closeAlert(name);
});
};
return (
<Alert
cancelButtonText={<T id={'cancel'} />}
confirmButtonText={'Resume bank feeds'}
intent={Intent.SUCCESS}
isOpen={isOpen}
onCancel={handleCancelActivateItem}
loading={isLoading}
onConfirm={handleConfirmItemActivate}
>
<p>
Are you sure want to resume bank feeds syncing of this bank account, you
can always pause it again?
</p>
</Alert>
);
}
export default compose(
withAlertStoreConnect(),
withAlertActions,
)(ResumeFeedsBankAccountAlert);

View File

@@ -0,0 +1,24 @@
// @ts-nocheck
import React from 'react';
const ResumeFeedsBankAccountAlert = React.lazy(
() => import('./ResumeFeedsBankAccount'),
);
const PauseFeedsBankAccountAlert = React.lazy(
() => import('./PauseFeedsBankAccount'),
);
/**
* Bank account alerts.
*/
export const BankAccountAlerts = [
{
name: 'resume-feeds-syncing-bank-accounnt',
component: ResumeFeedsBankAccountAlert,
},
{
name: 'pause-feeds-syncing-bank-accounnt',
component: PauseFeedsBankAccountAlert,
},
];

View File

@@ -150,99 +150,3 @@ export function AccountTransactionsProgressBar() {
<MaterialProgressBar />
) : null;
}
function statusAccessor(transaction) {
return transaction.is_recognized ? (
<Tooltip
compact
interactionKind={PopoverInteractionKind.HOVER}
position={Position.RIGHT}
content={
<Box>
<span>{transaction.assigned_category_formatted}</span>
<Icon
icon={'arrowRight'}
color={'#8F99A8'}
iconSize={12}
style={{ marginLeft: 8, marginRight: 8 }}
/>
<span>{transaction.assigned_account_name}</span>
</Box>
}
>
<Box>
<Tag intent={Intent.SUCCESS} interactive>
Recognized
</Tag>
</Box>
</Tooltip>
) : null;
}
/**
* Retrieve account uncategorized transctions table columns.
*/
export function useAccountUncategorizedTransactionsColumns() {
return React.useMemo(
() => [
{
id: 'date',
Header: intl.get('date'),
accessor: 'formatted_date',
width: 40,
clickable: true,
textOverview: true,
},
{
id: 'description',
Header: 'Description',
accessor: 'description',
width: 160,
textOverview: true,
clickable: true,
},
{
id: 'payee',
Header: 'Payee',
accessor: 'payee',
width: 60,
clickable: true,
textOverview: true,
},
{
id: 'reference_number',
Header: 'Ref.#',
accessor: 'reference_no',
width: 50,
clickable: true,
textOverview: true,
},
{
id: 'status',
Header: 'Status',
accessor: statusAccessor,
},
{
id: 'deposit',
Header: intl.get('cash_flow.label.deposit'),
accessor: 'formatted_deposit_amount',
width: 40,
className: 'deposit',
textOverview: true,
align: 'right',
clickable: true,
},
{
id: 'withdrawal',
Header: intl.get('cash_flow.label.withdrawal'),
accessor: 'formatted_withdrawal_amount',
className: 'withdrawal',
width: 40,
textOverview: true,
align: 'right',
clickable: true,
},
],
[],
);
}

View File

@@ -0,0 +1,42 @@
// @ts-nocheck
import React from 'react';
import { Dialog, DialogSuspense } from '@/components';
import withDialogRedux from '@/components/DialogReduxConnect';
import { compose } from '@/utils';
const DisconnectBankAccountDialogContent = React.lazy(
() => import('./DisconnectBankAccountDialogContent'),
);
/**
* Disconnect bank account confirmation dialog.
*/
function DisconnectBankAccountDialogRoot({
dialogName,
payload: { bankAccountId },
isOpen,
}) {
return (
<Dialog
name={dialogName}
title={'Disconnect Bank Account'}
isOpen={isOpen}
canEscapeJeyClose={true}
autoFocus={true}
style={{ width: 400 }}
>
<DialogSuspense>
<DisconnectBankAccountDialogContent
dialogName={dialogName}
bankAccountId={bankAccountId}
/>
</DialogSuspense>
</Dialog>
);
}
export const DisconnectBankAccountDialog = compose(withDialogRedux())(
DisconnectBankAccountDialogRoot,
);
DisconnectBankAccountDialog.displayName = 'DisconnectBankAccountDialog';

View File

@@ -0,0 +1,104 @@
// @ts-nocheck
import * as Yup from 'yup';
import { Button, Intent, Classes } from '@blueprintjs/core';
import * as R from 'ramda';
import { Form, Formik, FormikHelpers } from 'formik';
import { AppToaster, FFormGroup, FInputGroup } from '@/components';
import { useDisconnectBankAccount } from '@/hooks/query/bank-rules';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import { DialogsName } from '@/constants/dialogs';
interface DisconnectFormValues {
label: string;
}
const initialValues = {
label: '',
};
const Schema = Yup.object().shape({
label: Yup.string().required().label('Confirmation'),
});
interface DisconnectBankAccountDialogContentProps {
bankAccountId: number;
}
function DisconnectBankAccountDialogContent({
bankAccountId,
// #withDialogActions
closeDialog,
}: DisconnectBankAccountDialogContentProps) {
const { mutateAsync: disconnectBankAccount } = useDisconnectBankAccount();
const handleSubmit = (
values: DisconnectFormValues,
{ setErrors, setSubmitting }: FormikHelpers<DisconnectFormValues>,
) => {
debugger;
setSubmitting(true);
if (values.label !== 'DISCONNECT ACCOUNT') {
setErrors({
label: 'The entered value is incorrect.',
});
setSubmitting(false);
return;
}
disconnectBankAccount({ bankAccountId })
.then(() => {
setSubmitting(false);
AppToaster.show({
message: 'The bank account has been disconnected.',
intent: Intent.SUCCESS,
});
closeDialog(DialogsName.DisconnectBankAccountConfirmation);
})
.catch((error) => {
setSubmitting(false);
AppToaster.show({
message: 'Something went wrong.',
intent: Intent.DANGER,
});
});
};
const handleCancelBtnClick = () => {
closeDialog(DialogsName.DisconnectBankAccountConfirmation);
};
return (
<Formik
onSubmit={handleSubmit}
validationSchema={Schema}
initialValues={initialValues}
>
<Form>
<div className={Classes.DIALOG_BODY}>
<FFormGroup
label={`Type "DISCONNECT ACCOUNT"`}
name={'label'}
fastField
>
<FInputGroup name={'label'} fastField />
</FFormGroup>
</div>
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button type="submit" intent={Intent.DANGER}>
Disconnect Bank Account
</Button>
<Button intent={Intent.NONE} onClick={handleCancelBtnClick}>
Cancel
</Button>
</div>
</div>
</Form>
</Formik>
);
}
export default R.compose(withDialogActions)(DisconnectBankAccountDialogContent);

View File

@@ -6,10 +6,13 @@ import { useAccounts, useBranches } from '@/hooks/query';
import { useFeatureCan } from '@/hooks/state';
import { Features } from '@/constants';
import { Spinner } from '@blueprintjs/core';
import { useGetRecognizedBankTransaction } from '@/hooks/query/bank-rules';
import { useCategorizeTransactionTabsBoot } from '@/containers/CashFlow/CategorizeTransactionAside/CategorizeTransactionTabsBoot';
import {
GetAutofillCategorizeTransaction,
useGetAutofillCategorizeTransaction,
} from '@/hooks/query/bank-rules';
interface CategorizeTransactionBootProps {
uncategorizedTransactionsIds: Array<number>;
children: React.ReactNode;
}
@@ -19,8 +22,8 @@ interface CategorizeTransactionBootValue {
isBranchesLoading: boolean;
isAccountsLoading: boolean;
primaryBranch: any;
recognizedTranasction: any;
isRecognizedTransactionLoading: boolean;
autofillCategorizeValues: null | GetAutofillCategorizeTransaction;
isAutofillCategorizeValuesLoading: boolean;
}
const CategorizeTransactionBootContext =
@@ -32,11 +35,9 @@ const CategorizeTransactionBootContext =
* Categorize transcation boot.
*/
function CategorizeTransactionBoot({
uncategorizedTransactionsIds,
...props
}: CategorizeTransactionBootProps) {
const { uncategorizedTransaction, uncategorizedTransactionId } =
useCategorizeTransactionTabsBoot();
// Detarmines whether the feature is enabled.
const { featureCan } = useFeatureCan();
const isBranchFeatureCan = featureCan(Features.Branches);
@@ -49,13 +50,11 @@ function CategorizeTransactionBoot({
{},
{ enabled: isBranchFeatureCan },
);
// Fetches the recognized transaction.
// Fetches the autofill values of categorize transaction.
const {
data: recognizedTranasction,
isLoading: isRecognizedTransactionLoading,
} = useGetRecognizedBankTransaction(uncategorizedTransactionId, {
enabled: !!uncategorizedTransaction.is_recognized,
});
data: autofillCategorizeValues,
isLoading: isAutofillCategorizeValuesLoading,
} = useGetAutofillCategorizeTransaction(uncategorizedTransactionsIds, {});
// Retrieves the primary branch.
const primaryBranch = useMemo(
@@ -69,11 +68,11 @@ function CategorizeTransactionBoot({
isBranchesLoading,
isAccountsLoading,
primaryBranch,
recognizedTranasction,
isRecognizedTransactionLoading,
autofillCategorizeValues,
isAutofillCategorizeValuesLoading,
};
const isLoading =
isBranchesLoading || isAccountsLoading || isRecognizedTransactionLoading;
isBranchesLoading || isAccountsLoading || isAutofillCategorizeValuesLoading;
if (isLoading) {
<Spinner size={30} />;

View File

@@ -8,15 +8,15 @@ export function CategorizeTransactionBranchField() {
const { branches } = useCategorizeTransactionBoot();
return (
<FFormGroup name={'branchId'} label={'Branch'} fastField inline>
<FeatureCan feature={Features.Branches}>
<FeatureCan feature={Features.Branches}>
<FFormGroup name={'branchId'} label={'Branch'} fastField inline>
<BranchSuggestField
name={'branchId'}
items={branches}
popoverProps={{ minimal: true }}
fill
/>
</FeatureCan>
</FFormGroup>
</FFormGroup>
</FeatureCan>
);
}

View File

@@ -1,15 +1,16 @@
// @ts-nocheck
import styled from 'styled-components';
import * as R from 'ramda';
import { CategorizeTransactionBoot } from './CategorizeTransactionBoot';
import { CategorizeTransactionForm } from './CategorizeTransactionForm';
import { useCategorizeTransactionTabsBoot } from '@/containers/CashFlow/CategorizeTransactionAside/CategorizeTransactionTabsBoot';
export function CategorizeTransactionContent() {
const { uncategorizedTransactionId } = useCategorizeTransactionTabsBoot();
import { withBanking } from '@/containers/CashFlow/withBanking';
function CategorizeTransactionContentRoot({
transactionsToCategorizeIdsSelected,
}) {
return (
<CategorizeTransactionBoot
uncategorizedTransactionId={uncategorizedTransactionId}
uncategorizedTransactionsIds={transactionsToCategorizeIdsSelected}
>
<CategorizeTransactionDrawerBody>
<CategorizeTransactionForm />
@@ -18,6 +19,12 @@ export function CategorizeTransactionContent() {
);
}
export const CategorizeTransactionContent = R.compose(
withBanking(({ transactionsToCategorizeIdsSelected }) => ({
transactionsToCategorizeIdsSelected,
})),
)(CategorizeTransactionContentRoot);
const CategorizeTransactionDrawerBody = styled.div`
display: flex;
flex-direction: column;

View File

@@ -22,7 +22,7 @@ function CategorizeTransactionFormRoot({
// #withBankingActions
closeMatchingTransactionAside,
}) {
const { uncategorizedTransactionId } = useCategorizeTransactionTabsBoot();
const { uncategorizedTransactionIds } = useCategorizeTransactionTabsBoot();
const { mutateAsync: categorizeTransaction } = useCategorizeTransaction();
// Form initial values in create and edit mode.
@@ -30,10 +30,10 @@ function CategorizeTransactionFormRoot({
// Callbacks handles form submit.
const handleFormSubmit = (values, { setSubmitting, setErrors }) => {
const transformedValues = tranformToRequest(values);
const _values = tranformToRequest(values, uncategorizedTransactionIds);
setSubmitting(true);
categorizeTransaction([uncategorizedTransactionId, transformedValues])
categorizeTransaction(_values)
.then(() => {
setSubmitting(false);

View File

@@ -6,6 +6,7 @@ import { Box, FFormGroup, FSelect } from '@/components';
import { getAddMoneyInOptions, getAddMoneyOutOptions } from '@/constants';
import { useFormikContext } from 'formik';
import { useCategorizeTransactionTabsBoot } from '@/containers/CashFlow/CategorizeTransactionAside/CategorizeTransactionTabsBoot';
import { useCategorizeTransactionBoot } from './CategorizeTransactionBoot';
// Retrieves the add money in button options.
const MoneyInOptions = getAddMoneyInOptions();
@@ -18,16 +19,18 @@ const Title = styled('h3')`
`;
export function CategorizeTransactionFormContent() {
const { uncategorizedTransaction } = useCategorizeTransactionTabsBoot();
const { autofillCategorizeValues } = useCategorizeTransactionBoot();
const transactionTypes = uncategorizedTransaction?.is_deposit_transaction
const transactionTypes = autofillCategorizeValues?.isDepositTransaction
? MoneyInOptions
: MoneyOutOptions;
const formattedAmount = autofillCategorizeValues?.formattedAmount;
return (
<Box style={{ flex: 1, margin: 20 }}>
<FormGroup label={'Amount'} inline>
<Title>{uncategorizedTransaction.formatted_amount}</Title>
<Title>{formattedAmount}</Title>
</FormGroup>
<FFormGroup name={'category'} label={'Category'} fastField inline>

View File

@@ -1,8 +1,8 @@
// @ts-nocheck
import * as R from 'ramda';
import { transformToForm, transfromToSnakeCase } from '@/utils';
import { useCategorizeTransactionTabsBoot } from '@/containers/CashFlow/CategorizeTransactionAside/CategorizeTransactionTabsBoot';
import { useCategorizeTransactionBoot } from './CategorizeTransactionBoot';
import { GetAutofillCategorizeTransaction } from '@/hooks/query/bank-rules';
// Default initial form values.
export const defaultInitialValues = {
@@ -18,48 +18,28 @@ export const defaultInitialValues = {
};
export const transformToCategorizeForm = (
uncategorizedTransaction: any,
recognizedTransaction?: any,
autofillCategorizeTransaction: GetAutofillCategorizeTransaction,
) => {
let defaultValues = {
debitAccountId: uncategorizedTransaction.account_id,
transactionType: uncategorizedTransaction.is_deposit_transaction
? 'other_income'
: 'other_expense',
amount: uncategorizedTransaction.amount,
date: uncategorizedTransaction.date,
};
if (recognizedTransaction) {
const recognizedDefaults = getRecognizedTransactionDefaultValues(
recognizedTransaction,
);
defaultValues = R.merge(defaultValues, recognizedDefaults);
}
return transformToForm(defaultValues, defaultInitialValues);
return transformToForm(autofillCategorizeTransaction, defaultInitialValues);
};
export const getRecognizedTransactionDefaultValues = (
recognizedTransaction: any,
export const tranformToRequest = (
formValues: Record<string, any>,
uncategorizedTransactionIds: Array<number>,
) => {
return {
creditAccountId: recognizedTransaction.assignedAccountId || '',
// transactionType: recognizedTransaction.assignCategory,
referenceNo: recognizedTransaction.referenceNo || '',
uncategorized_transaction_ids: uncategorizedTransactionIds,
...transfromToSnakeCase(formValues),
};
};
export const tranformToRequest = (formValues: Record<string, any>) => {
return transfromToSnakeCase(formValues);
};
/**
* Categorize transaction form initial values.
* @returns
*/
export const useCategorizeTransactionFormInitialValues = () => {
const { primaryBranch, recognizedTranasction } =
const { primaryBranch, autofillCategorizeValues } =
useCategorizeTransactionBoot();
const { uncategorizedTransaction } = useCategorizeTransactionTabsBoot();
return {
...defaultInitialValues,
@@ -68,10 +48,7 @@ export const useCategorizeTransactionFormInitialValues = () => {
* values such as `notes` come back from the API as null, so remove those
* as well.
*/
...transformToCategorizeForm(
uncategorizedTransaction,
recognizedTranasction,
),
...transformToCategorizeForm(autofillCategorizeValues),
/** Assign the primary branch id as default value. */
branchId: primaryBranch?.id || null,

View File

@@ -19,20 +19,32 @@ function CategorizeTransactionAsideRoot({
// #withBanking
selectedUncategorizedTransactionId,
resetTransactionsToCategorizeSelected,
enableMultipleCategorization,
}: CategorizeTransactionAsideProps) {
//
//
useEffect(
() => () => {
// Close the reconcile matching form.
closeReconcileMatchingTransaction();
// Reset the selected transactions to categorize.
resetTransactionsToCategorizeSelected();
// Disable multi matching.
enableMultipleCategorization(false);
},
[closeReconcileMatchingTransaction],
[
closeReconcileMatchingTransaction,
resetTransactionsToCategorizeSelected,
enableMultipleCategorization,
],
);
const handleClose = () => {
closeMatchingTransactionAside();
};
const uncategorizedTransactionId = selectedUncategorizedTransactionId;
}
// Cannot continue if there is no selected transactions.;
if (!selectedUncategorizedTransactionId) {
return null;
}
@@ -40,7 +52,7 @@ function CategorizeTransactionAsideRoot({
<Aside title={'Categorize Bank Transaction'} onClose={handleClose}>
<Aside.Body>
<CategorizeTransactionTabsBoot
uncategorizedTransactionId={uncategorizedTransactionId}
uncategorizedTransactionId={selectedUncategorizedTransactionId}
>
<CategorizeTransactionTabs />
</CategorizeTransactionTabsBoot>
@@ -51,7 +63,7 @@ function CategorizeTransactionAsideRoot({
export const CategorizeTransactionAside = R.compose(
withBankingActions,
withBanking(({ selectedUncategorizedTransactionId }) => ({
selectedUncategorizedTransactionId,
withBanking(({ transactionsToCategorizeIdsSelected }) => ({
selectedUncategorizedTransactionId: transactionsToCategorizeIdsSelected,
})),
)(CategorizeTransactionAsideRoot);

View File

@@ -2,14 +2,10 @@
import { Tab, Tabs } from '@blueprintjs/core';
import { MatchingBankTransaction } from './MatchingTransaction';
import { CategorizeTransactionContent } from '../CategorizeTransaction/drawers/CategorizeTransactionDrawer/CategorizeTransactionContent';
import { useCategorizeTransactionTabsBoot } from './CategorizeTransactionTabsBoot';
import styles from './CategorizeTransactionTabs.module.scss';
export function CategorizeTransactionTabs() {
const { uncategorizedTransaction } = useCategorizeTransactionTabsBoot();
const defaultSelectedTabId = uncategorizedTransaction?.is_recognized
? 'categorize'
: 'matching';
const defaultSelectedTabId = 'categorize';
return (
<Tabs

View File

@@ -1,16 +1,13 @@
// @ts-nocheck
import React from 'react';
import { Spinner } from '@blueprintjs/core';
import { useUncategorizedTransaction } from '@/hooks/query';
import React, { useMemo } from 'react';
import { castArray, uniq } from 'lodash';
interface CategorizeTransactionTabsValue {
uncategorizedTransactionId: number;
isUncategorizedTransactionLoading: boolean;
uncategorizedTransaction: any;
uncategorizedTransactionIds: Array<number>;
}
interface CategorizeTransactionTabsBootProps {
uncategorizedTransactionId: number;
uncategorizedTransactionIds: number | Array<number>;
children: React.ReactNode;
}
@@ -26,28 +23,23 @@ export function CategorizeTransactionTabsBoot({
uncategorizedTransactionId,
children,
}: CategorizeTransactionTabsBootProps) {
const {
data: uncategorizedTransaction,
isLoading: isUncategorizedTransactionLoading,
} = useUncategorizedTransaction(uncategorizedTransactionId);
const uncategorizedTransactionIds = useMemo(
() => uniq(castArray(uncategorizedTransactionId)),
[uncategorizedTransactionId],
);
const provider = {
uncategorizedTransactionId,
uncategorizedTransaction,
isUncategorizedTransactionLoading,
uncategorizedTransactionIds,
};
const isLoading = isUncategorizedTransactionLoading;
// Use a key prop to force re-render of children when uncategorizedTransactionId changes
// Use a key prop to force re-render of children when `uncategorizedTransactionIds` changes
const childrenPerKey = React.useMemo(() => {
return React.Children.map(children, (child) =>
React.cloneElement(child, { key: uncategorizedTransactionId }),
React.cloneElement(child, {
key: uncategorizedTransactionIds?.join(','),
}),
);
}, [children, uncategorizedTransactionId]);
}, [children, uncategorizedTransactionIds]);
if (isLoading) {
return <Spinner size={30} />;
}
return (
<CategorizeTransactionTabsBootContext.Provider value={provider}>
{childrenPerKey}

View File

@@ -25,9 +25,9 @@ import {
WithBankingActionsProps,
withBankingActions,
} from '../withBankingActions';
import styles from './CategorizeTransactionAside.module.scss';
import { MatchingReconcileTransactionForm } from './MatchingReconcileTransactionAside/MatchingReconcileTransactionForm';
import { withBanking } from '../withBanking';
import { MatchingReconcileTransactionForm } from './MatchingReconcileTransactionAside/MatchingReconcileTransactionForm';
import styles from './CategorizeTransactionAside.module.scss';
const initialValues = {
matched: {},
@@ -40,8 +40,11 @@ const initialValues = {
function MatchingBankTransactionRoot({
// #withBankingActions
closeMatchingTransactionAside,
// #withBanking
transactionsToCategorizeIdsSelected,
}) {
const { uncategorizedTransactionId } = useCategorizeTransactionTabsBoot();
const { uncategorizedTransactionIds } = useCategorizeTransactionTabsBoot();
const { mutateAsync: matchTransaction } = useMatchUncategorizedTransaction();
// Handles the form submitting.
@@ -49,7 +52,7 @@ function MatchingBankTransactionRoot({
values: MatchingTransactionFormValues,
{ setSubmitting }: FormikHelpers<MatchingTransactionFormValues>,
) => {
const _values = transformToReq(values);
const _values = transformToReq(values, uncategorizedTransactionIds);
if (_values.matchedTransactions?.length === 0) {
AppToaster.show({
@@ -59,7 +62,7 @@ function MatchingBankTransactionRoot({
return;
}
setSubmitting(true);
matchTransaction({ id: uncategorizedTransactionId, value: _values })
matchTransaction(_values)
.then(() => {
AppToaster.show({
intent: Intent.SUCCESS,
@@ -78,7 +81,7 @@ function MatchingBankTransactionRoot({
message: `The total amount does not equal the uncategorized transaction.`,
intent: Intent.DANGER,
});
setSubmitting(false);
return;
}
AppToaster.show({
@@ -91,7 +94,7 @@ function MatchingBankTransactionRoot({
return (
<MatchingTransactionBoot
uncategorizedTransactionId={uncategorizedTransactionId}
uncategorizedTransactionsIds={uncategorizedTransactionIds}
>
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
<MatchingBankTransactionFormContent />
@@ -100,9 +103,12 @@ function MatchingBankTransactionRoot({
);
}
export const MatchingBankTransaction = R.compose(withBankingActions)(
MatchingBankTransactionRoot,
);
export const MatchingBankTransaction = R.compose(
withBankingActions,
withBanking(({ transactionsToCategorizeIdsSelected }) => ({
transactionsToCategorizeIdsSelected,
})),
)(MatchingBankTransactionRoot);
/**
* Matching bank transaction form content.

View File

@@ -10,6 +10,7 @@ interface MatchingTransactionBootValues {
possibleMatches: Array<any>;
perfectMatchesCount: number;
perfectMatches: Array<any>;
totalPending: number;
matches: Array<any>;
}
@@ -18,12 +19,12 @@ const RuleFormBootContext = createContext<MatchingTransactionBootValues>(
);
interface RuleFormBootProps {
uncategorizedTransactionId: number;
uncategorizedTransactionsIds: Array<number>;
children: React.ReactNode;
}
function MatchingTransactionBoot({
uncategorizedTransactionId,
uncategorizedTransactionsIds,
...props
}: RuleFormBootProps) {
const {
@@ -31,11 +32,12 @@ function MatchingTransactionBoot({
isLoading: isMatchingTransactionsLoading,
isFetching: isMatchingTransactionsFetching,
isSuccess: isMatchingTransactionsSuccess,
} = useGetBankTransactionsMatches(uncategorizedTransactionId);
} = useGetBankTransactionsMatches(uncategorizedTransactionsIds);
const possibleMatches = defaultTo(matchingTransactions?.possibleMatches, []);
const perfectMatchesCount = matchingTransactions?.perfectMatches?.length || 0;
const perfectMatches = defaultTo(matchingTransactions?.perfectMatches, []);
const totalPending = defaultTo(matchingTransactions?.totalPending, 0);
const matches = R.concat(perfectMatches, possibleMatches);
@@ -46,6 +48,7 @@ function MatchingTransactionBoot({
possibleMatches,
perfectMatchesCount,
perfectMatches,
totalPending,
matches,
} as MatchingTransactionBootValues;

View File

@@ -4,7 +4,10 @@ import { useMatchingTransactionBoot } from './MatchingTransactionBoot';
import { useCategorizeTransactionTabsBoot } from './CategorizeTransactionTabsBoot';
import { useMemo } from 'react';
export const transformToReq = (values: MatchingTransactionFormValues) => {
export const transformToReq = (
values: MatchingTransactionFormValues,
uncategorizedTransactions: Array<number>,
) => {
const matchedTransactions = Object.entries(values.matched)
.filter(([key, value]) => value)
.map(([key]) => {
@@ -12,14 +15,13 @@ export const transformToReq = (values: MatchingTransactionFormValues) => {
return { reference_type, reference_id: parseInt(reference_id, 10) };
});
return { matchedTransactions };
return { matchedTransactions, uncategorizedTransactions };
};
export const useGetPendingAmountMatched = () => {
const { values } = useFormikContext<MatchingTransactionFormValues>();
const { perfectMatches, possibleMatches } = useMatchingTransactionBoot();
const { uncategorizedTransaction } = useCategorizeTransactionTabsBoot();
const { perfectMatches, possibleMatches, totalPending } =
useMatchingTransactionBoot();
return useMemo(() => {
const matchedItems = [...perfectMatches, ...possibleMatches].filter(
@@ -34,11 +36,10 @@ export const useGetPendingAmountMatched = () => {
(item.transactionNormal === 'debit' ? 1 : -1) * parseFloat(item.amount),
0,
);
const amount = uncategorizedTransaction.amount;
const pendingAmount = amount - totalMatchedAmount;
const pendingAmount = totalPending - totalMatchedAmount;
return pendingAmount;
}, [uncategorizedTransaction, perfectMatches, possibleMatches, values]);
}, [totalPending, perfectMatches, possibleMatches, values]);
};
export const useAtleastOneMatchedSelected = () => {

View File

@@ -18,6 +18,10 @@ export const withBanking = (mapState) => {
state.plaid.uncategorizedTransactionsSelected,
excludedTransactionsIdsSelected: state.plaid.excludedTransactionsSelected,
enableMultipleCategorization: state.plaid.enableMultipleCategorization,
transactionsToCategorizeIdsSelected:
state.plaid.transactionsToCategorizeSelected,
};
return mapState ? mapState(mapped, state, props) : mapped;
};

View File

@@ -8,6 +8,11 @@ import {
resetUncategorizedTransactionsSelected,
resetExcludedTransactionsSelected,
setExcludedTransactionsSelected,
resetTransactionsToCategorizeSelected,
setTransactionsToCategorizeSelected,
enableMultipleCategorization,
addTransactionsToCategorizeSelected,
removeTransactionsToCategorizeSelected,
} from '@/store/banking/banking.reducer';
export interface WithBankingActionsProps {
@@ -23,6 +28,13 @@ export interface WithBankingActionsProps {
setExcludedTransactionsSelected: (ids: Array<string | number>) => void;
resetExcludedTransactionsSelected: () => void;
setTransactionsToCategorizeSelected: (ids: Array<string | number>) => void;
addTransactionsToCategorizeSelected: (id: string | number) => void;
removeTransactionsToCategorizeSelected: (id: string | number) => void;
resetTransactionsToCategorizeSelected: () => void;
enableMultipleCategorization: (enable: boolean) => void;
}
const mapDipatchToProps = (dispatch: any): WithBankingActionsProps => ({
@@ -41,7 +53,7 @@ const mapDipatchToProps = (dispatch: any): WithBankingActionsProps => ({
/**
* Sets the selected uncategorized transactions.
* @param {Array<string | number>} ids
* @param {Array<string | number>} ids
*/
setUncategorizedTransactionsSelected: (ids: Array<string | number>) =>
dispatch(
@@ -68,10 +80,46 @@ const mapDipatchToProps = (dispatch: any): WithBankingActionsProps => ({
),
/**
* Resets the excluded selected transactions
* Resets the excluded selected transactions.
*/
resetExcludedTransactionsSelected: () =>
dispatch(resetExcludedTransactionsSelected()),
/**
* Sets the selected transactions to categorize or match.
* @param {Array<string | number>} ids
*/
setTransactionsToCategorizeSelected: (ids: Array<string | number>) =>
dispatch(setTransactionsToCategorizeSelected({ ids })),
/**
* Adds selected transactions to categorize.
* @param {string | number} id
* @returns
*/
addTransactionsToCategorizeSelected: (id: string | number) =>
dispatch(addTransactionsToCategorizeSelected({ id })),
/**
* Removes the selected transactions.
* @param {string | number} id
* @returns
*/
removeTransactionsToCategorizeSelected: (id: string | number) =>
dispatch(removeTransactionsToCategorizeSelected({ id })),
/**
* Resets the selected transactions to categorize or match.
*/
resetTransactionsToCategorizeSelected: () =>
dispatch(resetTransactionsToCategorizeSelected()),
/**
* Enables/Disables the multiple selection to categorize or match.
* @param {boolean} enable
*/
enableMultipleCategorization: (enable: boolean) =>
dispatch(enableMultipleCategorization({ enable })),
});
export const withBankingActions = connect<

View File

@@ -3,15 +3,14 @@ import React from 'react';
import intl from 'react-intl-universal';
import { Formik } from 'formik';
import { Intent } from '@blueprintjs/core';
import { pick } from 'lodash';
import { omit } from 'lodash';
import { AppToaster } from '@/components';
import { CreateQuickPaymentMadeFormSchema } from './QuickPaymentMade.schema';
import { useQuickPaymentMadeContext } from './QuickPaymentMadeFormProvider';
import QuickPaymentMadeFormContent from './QuickPaymentMadeFormContent';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import { defaultPaymentMade, transformErrors } from './utils';
import { defaultPaymentMade, transformBillToForm, transformErrors } from './utils';
import { compose } from '@/utils';
/**
@@ -21,31 +20,24 @@ function QuickPaymentMadeForm({
// #withDialogActions
closeDialog,
}) {
const {
bill,
dialogName,
createPaymentMadeMutate,
} = useQuickPaymentMadeContext();
const { bill, dialogName, createPaymentMadeMutate } =
useQuickPaymentMadeContext();
// Initial form values
// Initial form values.
const initialValues = {
...defaultPaymentMade,
...bill,
...transformBillToForm(bill),
};
// Handles the form submit.
const handleFormSubmit = (values, { setSubmitting, setFieldError }) => {
const entries = [values]
.filter((entry) => entry.id && entry.payment_amount)
.map((entry) => ({
bill_id: entry.id,
...pick(entry, ['payment_amount']),
}));
const entries = [
{
payment_amount: values.amount,
bill_id: values.bill_id,
},
];
const form = {
...values,
vendor_id: values?.vendor?.id,
...omit(values, ['bill_id']),
entries,
};

View File

@@ -124,7 +124,7 @@ function QuickPaymentMadeFormFields({
</Col>
</Row>
{/*------------ Amount Received -----------*/}
<FastField name={'payment_amount'}>
<FastField name={'amount'}>
{({
form: { values, setFieldValue },
field: { value },
@@ -135,7 +135,7 @@ function QuickPaymentMadeFormFields({
labelInfo={<FieldRequiredHint />}
className={classNames('form-group--payment_amount', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="payment_amount" />}
helperText={<ErrorMessage name="amount" />}
>
<ControlGroup>
<InputPrependText text={values.currency_code} />
@@ -144,7 +144,7 @@ function QuickPaymentMadeFormFields({
value={value}
minimal={true}
onChange={(amount) => {
setFieldValue('payment_amount', amount);
setFieldValue('amount', amount);
}}
intent={inputIntent({ error, touched })}
inputRef={(ref) => (paymentMadeFieldRef.current = ref)}

View File

@@ -1,5 +1,5 @@
// @ts-nocheck
import React from 'react';
import React, { useMemo } from 'react';
import { DialogContent } from '@/components';
import {
useBill,
@@ -11,7 +11,6 @@ import { Features } from '@/constants';
import { useFeatureCan } from '@/hooks/state';
import { pick } from 'lodash';
const QuickPaymentMadeContext = React.createContext();
/**
@@ -40,13 +39,14 @@ function QuickPaymentMadeFormProvider({ query, billId, dialogName, ...props }) {
isSuccess: isBranchesSuccess,
} = useBranches(query, { enabled: isBranchFeatureCan });
const paymentBill = useMemo(
() => pick(bill, ['id', 'due_amount', 'vendor_id', 'currency_code']),
[bill],
);
// State provider.
const provider = {
bill: {
...pick(bill, ['id', 'due_amount', 'vendor', 'currency_code']),
vendor_id: bill?.vendor?.display_name,
payment_amount: bill?.due_amount,
},
bill: paymentBill,
accounts,
branches,
dialogName,

View File

@@ -2,24 +2,25 @@
import React from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import { first } from 'lodash';
import { first, pick } from 'lodash';
import { useFormikContext } from 'formik';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from '@/components';
import { useFormikContext } from 'formik';
import { useQuickPaymentMadeContext } from './QuickPaymentMadeFormProvider';
import { PAYMENT_MADE_ERRORS } from '@/containers/Purchases/PaymentMades/constants';
// Default initial values of payment made.
export const defaultPaymentMade = {
bill_id: '',
vendor_id: '',
payment_account_id: '',
payment_date: moment(new Date()).format('YYYY-MM-DD'),
reference: '',
payment_number: '',
amount: '',
// statement: '',
exchange_rate: 1,
branch_id: '',
entries: [{ bill_id: '', payment_amount: '' }],
};
export const transformErrors = (errors, { setFieldError }) => {
@@ -58,3 +59,11 @@ export const useSetPrimaryBranchToForm = () => {
}
}, [isBranchesSuccess, setFieldValue, branches]);
};
export const transformBillToForm = (bill) => {
return {
...pick(bill, ['vendor_id', 'currency_code']),
amount: bill.due_amount,
bill_id: bill.id,
};
}

View File

@@ -3,7 +3,7 @@ import React from 'react';
import intl from 'react-intl-universal';
import { Formik } from 'formik';
import { Intent } from '@blueprintjs/core';
import { pick, defaultTo, omit } from 'lodash';
import { defaultTo, omit } from 'lodash';
import { AppToaster } from '@/components';
import { useQuickPaymentReceiveContext } from './QuickPaymentReceiveFormProvider';
@@ -12,7 +12,11 @@ import QuickPaymentReceiveFormContent from './QuickPaymentReceiveFormContent';
import withSettings from '@/containers/Settings/withSettings';
import withDialogActions from '@/containers/Dialog/withDialogActions';
import { defaultInitialValues, transformErrors } from './utils';
import {
defaultInitialValues,
transformErrors,
transformInvoiceToForm,
} from './utils';
import { compose, transactionNumber } from '@/utils';
/**
@@ -26,14 +30,10 @@ function QuickPaymentReceiveForm({
paymentReceiveAutoIncrement,
paymentReceiveNumberPrefix,
paymentReceiveNextNumber,
preferredDepositAccount
preferredDepositAccount,
}) {
const {
dialogName,
invoice,
createPaymentReceiveMutate,
} = useQuickPaymentReceiveContext();
const { dialogName, invoice, createPaymentReceiveMutate } =
useQuickPaymentReceiveContext();
// Payment receive number.
const nextPaymentNumber = transactionNumber(
@@ -48,24 +48,22 @@ function QuickPaymentReceiveForm({
payment_receive_no: nextPaymentNumber,
}),
deposit_account_id: defaultTo(preferredDepositAccount, ''),
...invoice,
...transformInvoiceToForm(invoice),
};
// Handles the form submit.
const handleFormSubmit = (values, { setSubmitting, setFieldError }) => {
const entries = [values]
.filter((entry) => entry.id && entry.payment_amount)
.map((entry) => ({
invoice_id: entry.id,
...pick(entry, ['payment_amount']),
}));
const entries = [
{
invoice_id: values.invoice_id,
payment_amount: values.amount,
},
];
const form = {
...omit(values, ['payment_receive_no']),
...omit(values, ['payment_receive_no', 'invoice_id']),
...(!paymentReceiveAutoIncrement && {
payment_receive_no: values.payment_receive_no,
}),
customer_id: values.customer.id,
entries,
};

View File

@@ -128,7 +128,7 @@ function QuickPaymentReceiveFormFields({
</Col>
</Row>
{/*------------ Amount Received -----------*/}
<FastField name={'payment_amount'}>
<FastField name={'amount'}>
{({
form: { values, setFieldValue },
field: { value },
@@ -139,7 +139,7 @@ function QuickPaymentReceiveFormFields({
labelInfo={<FieldRequiredHint />}
className={classNames('form-group--payment_amount', CLASSES.FILL)}
intent={inputIntent({ error, touched })}
helperText={<ErrorMessage name="payment_amount" />}
helperText={<ErrorMessage name="amount" />}
>
<ControlGroup>
<InputPrependText text={values.currency_code} />
@@ -148,7 +148,7 @@ function QuickPaymentReceiveFormFields({
value={value}
minimal={true}
onChange={(amount) => {
setFieldValue('payment_amount', amount);
setFieldValue('amount', amount);
}}
intent={inputIntent({ error, touched })}
inputRef={(ref) => (paymentReceiveFieldRef.current = ref)}

View File

@@ -1,5 +1,5 @@
// @ts-nocheck
import React, { useContext, createContext } from 'react';
import React, { useContext, createContext, useMemo } from 'react';
import { pick } from 'lodash';
import { DialogContent } from '@/components';
import { Features } from '@/constants';
@@ -47,15 +47,16 @@ function QuickPaymentReceiveFormProvider({
isSuccess: isBranchesSuccess,
} = useBranches(query, { enabled: isBranchFeatureCan });
const invoicePayment = useMemo(
() => pick(invoice, ['id', 'due_amount', 'customer_id', 'currency_code']),
[invoice],
);
// State provider.
const provider = {
accounts,
branches,
invoice: {
...pick(invoice, ['id', 'due_amount', 'customer', 'currency_code']),
customer_id: invoice?.customer?.display_name,
payment_amount: invoice.due_amount,
},
invoice: invoicePayment,
isAccountsLoading,
isSettingsLoading,
isBranchesSuccess,

View File

@@ -2,7 +2,7 @@
import React from 'react';
import moment from 'moment';
import intl from 'react-intl-universal';
import { first } from 'lodash';
import { first, pick } from 'lodash';
import { Intent } from '@blueprintjs/core';
import { AppToaster } from '@/components';
@@ -10,15 +10,16 @@ import { useFormikContext } from 'formik';
import { useQuickPaymentReceiveContext } from './QuickPaymentReceiveFormProvider';
export const defaultInitialValues = {
invoice_id: '',
customer_id: '',
deposit_account_id: '',
payment_receive_no: '',
payment_date: moment(new Date()).format('YYYY-MM-DD'),
reference_no: '',
amount: '',
// statement: '',
exchange_rate: 1,
branch_id: '',
entries: [{ invoice_id: '', payment_amount: '' }],
};
export const transformErrors = (errors, { setFieldError }) => {
@@ -44,7 +45,9 @@ export const transformErrors = (errors, { setFieldError }) => {
}
if (getError('PAYMENT_ACCOUNT_CURRENCY_INVALID')) {
AppToaster.show({
message: intl.get('payment_Receive.error.payment_account_currency_invalid'),
message: intl.get(
'payment_Receive.error.payment_account_currency_invalid',
),
intent: Intent.DANGER,
});
}
@@ -64,3 +67,11 @@ export const useSetPrimaryBranchToForm = () => {
}
}, [isBranchesSuccess, setFieldValue, branches]);
};
export const transformInvoiceToForm = (invoice) => {
return {
...pick(invoice, ['customer_id', 'currency_code']),
amount: invoice.due_amount,
invoice_id: invoice.id,
};
};

Some files were not shown because too many files have changed in this diff Show More