Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Advanced payments #542

Open
wants to merge 10 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -111,20 +111,23 @@ export default class BillsPayments extends BaseController {
check('vendor_id').exists().isNumeric().toInt(),
check('exchange_rate').optional().isFloat({ gt: 0 }).toFloat(),

check('amount').exists().isNumeric().toFloat(),
check('payment_account_id').exists().isNumeric().toInt(),
check('payment_number').optional({ nullable: true }).trim().escape(),
check('payment_date').exists(),
check('statement').optional().trim().escape(),
check('reference').optional().trim().escape(),
check('branch_id').optional({ nullable: true }).isNumeric().toInt(),

check('entries').exists().isArray({ min: 1 }),
check('entries').exists().isArray(),
check('entries.*.index').optional().isNumeric().toInt(),
check('entries.*.bill_id').exists().isNumeric().toInt(),
check('entries.*.payment_amount').exists().isNumeric().toFloat(),

check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),

check('prepard_expenses_account_id').optional().isNumeric().toInt(),
];
}

Expand Down
9 changes: 8 additions & 1 deletion packages/server/src/api/controllers/Sales/PaymentReceives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,14 +151,16 @@ export default class PaymentReceivesController extends BaseController {
check('exchange_rate').optional().isFloat({ gt: 0 }).toFloat(),

check('payment_date').exists(),
check('amount').exists().isNumeric().toFloat(),

check('reference_no').optional(),
check('deposit_account_id').exists().isNumeric().toInt(),
check('payment_receive_no').optional({ nullable: true }).trim().escape(),
check('statement').optional().trim().escape(),

check('branch_id').optional({ nullable: true }).isNumeric().toInt(),

check('entries').isArray({ min: 1 }),
check('entries').isArray(),

check('entries.*.id').optional({ nullable: true }).isNumeric().toInt(),
check('entries.*.index').optional().isNumeric().toInt(),
Expand All @@ -167,6 +169,11 @@ export default class PaymentReceivesController extends BaseController {

check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),

check('unearned_revenue_account_id')
.optional({ nullable: true })
.isNumeric()
.toInt(),
];
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
exports.up = function (knex) {
return knex.schema.table('payment_receives', (table) => {
table.decimal('applied_amount', 13, 3).defaultTo(0);
table
.integer('unearned_revenue_account_id')
.unsigned()
.references('id')
.inTable('accounts');
});
};

exports.down = function (knex) {
return knex.schema.table('payment_receives', (table) => {
table.dropColumn('applied_amount');
table.dropColumn('unearned_revenue_account_id');
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
exports.up = function (knex) {
return knex.schema.table('bills_payments', (table) => {
table.decimal('applied_amount', 13, 3).defaultTo(0);
table
.integer('prepard_expenses_account_id')
.unsigned()
.references('id')
.inTable('accounts');
});
};

exports.down = function (knex) {
return knex.schema.table('bills_payments', (table) => {
table.dropColumn('applied_amount');
table.dropColumn('prepard_expenses_account_id');
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ export default class SeedAccounts extends TenantSeeder {
description: this.i18n.__(account.description),
currencyCode: this.tenant.metadata.baseCurrency,
seededAt: new Date(),
})
);
}));
return knex('accounts').then(async () => {
// Inserts seed entries.
return knex('accounts').insert(data);
Expand Down
24 changes: 24 additions & 0 deletions packages/server/src/database/seeds/data/accounts.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@ export const TaxPayableAccount = {
predefined: 1,
};

export const UnearnedRevenueAccount = {
name: 'Unearned Revenue',
slug: 'unearned-revenue',
account_type: 'other-current-liability',
parent_account_id: null,
code: '50005',
active: true,
index: 1,
predefined: true,
};

export const PrepardExpenses = {
name: 'Prepaid Expenses',
slug: 'prepaid-expenses',
account_type: 'other-current-asset',
parent_account_id: null,
code: '100010',
active: true,
index: 1,
predefined: true,
};

export default [
{
name: 'Bank Account',
Expand Down Expand Up @@ -323,4 +345,6 @@ export default [
index: 1,
predefined: 0,
},
UnearnedRevenueAccount,
PrepardExpenses,
];
7 changes: 7 additions & 0 deletions packages/server/src/interfaces/Bill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,10 @@ export interface IBillOpenedPayload {
oldBill: IBill;
tenantId: number;
}


export interface IBillPrepardExpensesAppliedEventPayload {
tenantId: number;
billId: number;
trx?: Knex.Transaction;
}
13 changes: 13 additions & 0 deletions packages/server/src/interfaces/BillPayment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ export interface IBillPayment {

localAmount?: number;
branchId?: number;

prepardExpensesAccountId?: number;
isPrepardExpense: boolean;
}

export interface IBillPaymentEntryDTO {
Expand All @@ -38,6 +41,7 @@ export interface IBillPaymentEntryDTO {

export interface IBillPaymentDTO {
vendorId: number;
amount: number;
paymentAccountId: number;
paymentNumber?: string;
paymentDate: Date;
Expand All @@ -47,6 +51,7 @@ export interface IBillPaymentDTO {
entries: IBillPaymentEntryDTO[];
branchId?: number;
attachments?: AttachmentLinkDTO[];
prepardExpensesAccountId?: number;
}

export interface IBillReceivePageEntry {
Expand Down Expand Up @@ -119,3 +124,11 @@ export enum IPaymentMadeAction {
Delete = 'Delete',
View = 'View',
}

export interface IPaymentPrepardExpensesAppliedEventPayload {
tenantId: number;
billPaymentId: number;
billId: number;
appliedAmount: number;
trx?: Knex.Transaction;
}
2 changes: 1 addition & 1 deletion packages/server/src/interfaces/Ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export interface ILedgerEntry {
date: Date | string;

transactionType: string;
transactionSubType: string;
transactionSubType?: string;

transactionId: number;

Expand Down
17 changes: 15 additions & 2 deletions packages/server/src/interfaces/PaymentReceive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,13 @@ export interface IPaymentReceive {
updatedAt: Date;
localAmount?: number;
branchId?: number;
unearnedRevenueAccountId?: number;
}
export interface IPaymentReceiveCreateDTO {

interface IPaymentReceivedCommonDTO {
unearnedRevenueAccountId?: number;
}
export interface IPaymentReceiveCreateDTO extends IPaymentReceivedCommonDTO {
customerId: number;
paymentDate: Date;
amount: number;
Expand All @@ -41,7 +46,7 @@ export interface IPaymentReceiveCreateDTO {
attachments?: AttachmentLinkDTO[];
}

export interface IPaymentReceiveEditDTO {
export interface IPaymentReceiveEditDTO extends IPaymentReceivedCommonDTO {
customerId: number;
paymentDate: Date;
amount: number;
Expand Down Expand Up @@ -184,3 +189,11 @@ export interface PaymentReceiveMailPresendEvent {
paymentReceiveId: number;
messageOptions: PaymentReceiveMailOptsDTO;
}

export interface PaymentReceiveUnearnedRevenueAppliedEventPayload {
tenantId: number;
paymentReceiveId: number;
saleInvoiceId: number;
appliedAmount: number;
trx?: Knex.Transaction;
}
6 changes: 6 additions & 0 deletions packages/server/src/interfaces/SaleInvoice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,9 @@ export interface ISaleInvoiceMailSent {
saleInvoiceId: number;
messageOptions: SendInvoiceMailDTO;
}

export interface SaleInvoiceAppliedUnearnedRevenueOnCreatedEventPayload {
tenantId: number;
saleInvoiceId: number;
trx?: Knex.Transaction;
}
2 changes: 2 additions & 0 deletions packages/server/src/loaders/eventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ import { UnlinkBankRuleOnDeleteBankRule } from '@/services/Banking/Rules/events/
import { DecrementUncategorizedTransactionOnMatching } from '@/services/Banking/Matching/events/DecrementUncategorizedTransactionsOnMatch';
import { DecrementUncategorizedTransactionOnExclude } from '@/services/Banking/Exclude/events/DecrementUncategorizedTransactionOnExclude';
import { DecrementUncategorizedTransactionOnCategorize } from '@/services/Cashflow/subscribers/DecrementUncategorizedTransactionOnCategorize';
import { AutoApplyUnearnedRevenueOnInvoiceCreated } from '@/services/Sales/PaymentReceives/events/AutoApplyUnearnedRevenueOnInvoiceCreated';
import { AutoApplyPrepardExpensesOnBillCreated } from '@/services/Purchases/Bills/events/AutoApplyPrepardExpensesOnBillCreated';

export default () => {
return new EventPublisher();
Expand Down
4 changes: 2 additions & 2 deletions packages/server/src/models/Bill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -525,9 +525,9 @@ export default class Bill extends mixin(TenantModel, [
return notFoundBillsIds;
}

static changePaymentAmount(billId, amount) {
static changePaymentAmount(billId, amount, trx) {
const changeMethod = amount > 0 ? 'increment' : 'decrement';
return this.query()
return this.query(trx)
.where('id', billId)
[changeMethod]('payment_amount', Math.abs(amount));
}
Expand Down
10 changes: 10 additions & 0 deletions packages/server/src/models/BillPayment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export default class BillPayment extends mixin(TenantModel, [
CustomViewBaseModel,
ModelSearchable,
]) {
prepardExpensesAccountId: number;

/**
* Table name
*/
Expand Down Expand Up @@ -47,6 +49,14 @@ export default class BillPayment extends mixin(TenantModel, [
return BillPaymentSettings;
}

/**
* Detarmines whether the payment is prepard expense.
* @returns {boolean}
*/
get isPrepardExpense() {
return !!this.prepardExpensesAccountId;
}

/**
* Relationship mapping.
*/
Expand Down
70 changes: 69 additions & 1 deletion packages/server/src/repositories/AccountRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { Account } from 'models';
import TenantRepository from '@/repositories/TenantRepository';
import { IAccount } from '@/interfaces';
import { Knex } from 'knex';
import { TaxPayableAccount } from '@/database/seeds/data/accounts';
import {
PrepardExpenses,
TaxPayableAccount,
UnearnedRevenueAccount,
} from '@/database/seeds/data/accounts';
import { TenantMetadata } from '@/system/models';

export default class AccountRepository extends TenantRepository {
/**
Expand Down Expand Up @@ -179,4 +184,67 @@ export default class AccountRepository extends TenantRepository {
}
return result;
};

/**
* Finds or creates the unearned revenue.
* @param {Record<string, string>} extraAttrs
* @param {Knex.Transaction} trx
* @returns
*/
public async findOrCreateUnearnedRevenue(
extraAttrs: Record<string, string> = {},
trx?: Knex.Transaction
) {
// Retrieves the given tenant metadata.
const tenantMeta = await TenantMetadata.query().findOne({
tenantId: this.tenantId,
});
const _extraAttrs = {
currencyCode: tenantMeta.baseCurrency,
...extraAttrs,
};
let result = await this.model
.query(trx)
.findOne({ slug: UnearnedRevenueAccount.slug, ..._extraAttrs });

if (!result) {
result = await this.model.query(trx).insertAndFetch({
...UnearnedRevenueAccount,
..._extraAttrs,
});
}
return result;
}

/**
* Finds or creates the prepard expenses account.
* @param {Record<string, string>} extraAttrs
* @param {Knex.Transaction} trx
* @returns
*/
public async findOrCreatePrepardExpenses(
extraAttrs: Record<string, string> = {},
trx?: Knex.Transaction
) {
// Retrieves the given tenant metadata.
const tenantMeta = await TenantMetadata.query().findOne({
tenantId: this.tenantId,
});
const _extraAttrs = {
currencyCode: tenantMeta.baseCurrency,
...extraAttrs,
};

let result = await this.model
.query(trx)
.findOne({ slug: PrepardExpenses.slug, ..._extraAttrs });

if (!result) {
result = await this.model.query(trx).insertAndFetch({
...PrepardExpenses,
..._extraAttrs,
});
}
return result;
}
}
11 changes: 8 additions & 3 deletions packages/server/src/repositories/TenantRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ import CachableRepository from './CachableRepository';

export default class TenantRepository extends CachableRepository {
repositoryName: string;

tenantId: number;

/**
* Constructor method.
* @param {number} tenantId
* @param {number} tenantId
*/
constructor(knex, cache, i18n) {
super(knex, cache, i18n);
}
}

setTenantId(tenantId: number) {
this.tenantId = tenantId;
}
}
Loading