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: invoice returns #671

Closed
wants to merge 6 commits into from
Closed
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
63 changes: 63 additions & 0 deletions backend/database/bespoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
import { ModelNameEnum } from '../../models/types';
import DatabaseCore from './core';
import { BespokeFunction } from './types';
import { safeParseFloat } from 'utils/index';
import { DocValueMap } from 'fyo/core/types';

export class BespokeQueries {
[key: string]: BespokeFunction;
Expand Down Expand Up @@ -180,4 +182,65 @@ export class BespokeQueries {

return value[0][Object.keys(value[0])[0]];
}

static async getInvoiceReturnBalanceItemsQty(
db: DatabaseCore,
schemaName: string,
invoice: string
): Promise<DocValueMap[] | undefined> {
const invoiceItems = (await db.knex!(`${schemaName}Item`)
.select('item')
.where('parent', invoice)
.groupBy('item')
.sum({ quantity: 'quantity' })) as DocValueMap[];

const returnInvoiceNames = (
await db.knex!(schemaName)
.select('name')
.where('returnAgainst', invoice)
.andWhere('submitted', true)
.andWhere('cancelled', false)
).map((i: { name: string }) => i.name);

if (!returnInvoiceNames.length) {
return;
}

const returnedItems = (await db.knex!(`${schemaName}Item`)
.select('item')
.sum({ quantity: 'quantity' })
.whereIn('parent', returnInvoiceNames)
.groupBy('item')) as DocValueMap[];

if (!returnedItems.length) {
return;
}

const returnBalanceItemQty = [];

for (const item of returnedItems) {
const invoiceItem = invoiceItems.filter(
(invItem) => invItem.item === item.item
)[0];

if (!invoiceItem) {
continue;
}

let balanceQty = safeParseFloat(
(invoiceItem.quantity as number) - Math.abs(item.quantity as number)
);

if (balanceQty === 0) {
continue;
}

if (balanceQty > 0) {
balanceQty *= -1;
}
returnBalanceItemQty.push({ ...item, quantity: balanceQty });
}

return returnBalanceItemQty;
}
}
11 changes: 11 additions & 0 deletions fyo/core/dbHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,17 @@ export class DatabaseHandler extends DatabaseBase {
)) as number | null;
}

async getInvoiceReturnBalanceItemsQty(
schemaName: string,
invoice: string
): Promise<DocValueMap[] | undefined> {
return (await this.#demux.callBespoke(
'getInvoiceReturnBalanceItemsQty',
schemaName,
invoice
)) as DocValueMap[] | undefined;
}

/**
* Internal methods
*/
Expand Down
4 changes: 4 additions & 0 deletions models/baseModels/AccountingSettings/AccountingSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { getCountryInfo } from 'utils/misc';

export class AccountingSettings extends Doc {
enableDiscounting?: boolean;
enableInvoiceReturns?: boolean;
enableInventory?: boolean;
enablePriceList?: boolean;

Expand Down Expand Up @@ -43,6 +44,9 @@ export class AccountingSettings extends Doc {
enableDiscounting: () => {
return !!this.enableDiscounting;
},
enableInvoiceReturns: () => {
return !!this.enableInvoiceReturns;
},
enableInventory: () => {
return !!this.enableInventory;
},
Expand Down
182 changes: 176 additions & 6 deletions models/baseModels/Invoice/Invoice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { Party } from '../Party/Party';
import { Payment } from '../Payment/Payment';
import { Tax } from '../Tax/Tax';
import { TaxSummary } from '../TaxSummary/TaxSummary';
import { isPesa } from 'fyo/utils';

export abstract class Invoice extends Transactional {
_taxes: Record<string, Tax> = {};
Expand All @@ -47,6 +48,10 @@ export abstract class Invoice extends Transactional {
stockNotTransferred?: number;
backReference?: string;

isItemsReturned?: boolean;
returnAgainst?: string;
returnCompleted?: boolean;

submitted?: boolean;
cancelled?: boolean;
makeAutoPayment?: boolean;
Expand Down Expand Up @@ -159,12 +164,16 @@ export abstract class Invoice extends Transactional {
await stockTransfer?.submit();
await this.load();
}
await this._updateIsItemsReturned();
await this._updateReturnInvoiceOutStanding();
}

async afterCancel() {
await super.afterCancel();
await this._cancelPayments();
await this._updatePartyOutStanding();
await this._updateIsItemsReturned();
await this._updateReturnInvoiceOutStanding();
}

async _cancelPayments() {
Expand Down Expand Up @@ -368,6 +377,127 @@ export abstract class Invoice extends Transactional {
return discountAmount;
}

async getReturnDoc() {
if (!this.items?.length) {
return;
}

const invoiceData = this.getValidDict(true, true);
const invoiceItems = invoiceData.items as InvoiceItem[];
const returnInvoiceItems: InvoiceItem[] = [];

const returnBalanceItemsQty =
await this.fyo.db.getInvoiceReturnBalanceItemsQty(
this.schema.name,
this.name!
);

for (const item of invoiceItems) {
if (!item.quantity) {
continue;
}

let quantity = -1 * item.quantity;

if (returnBalanceItemsQty) {
const balanceItemQty = returnBalanceItemsQty.filter(
(i) => i.item === item.item
)[0];

if (!balanceItemQty) {
continue;
}
quantity = balanceItemQty.quantity as number;
}

item.quantity = safeParseFloat(quantity);
delete item.name;
returnInvoiceItems.push(item);
}

const returnDocData = {
...invoiceData,
name: null,
date: new Date(),
items: returnInvoiceItems,
isReturn: true,
returnAgainst: invoiceData.name,
netTotal: this.fyo.pesa(0),
baseGrandTotal: this.fyo.pesa(0),
grandTotal: this.fyo.pesa(0),
outstandingAmount: this.fyo.pesa(0),
};

const rawReturnDoc = this.fyo.doc.getNewDoc(
this.schema.name,
returnDocData
);

rawReturnDoc.once('beforeSync', async () => {
await rawReturnDoc.runFormulas();
});
return rawReturnDoc;
}

async _updateIsItemsReturned() {
if (!this.isReturn || !this.returnAgainst) {
return;
}

const returnInvoices = await this.fyo.db.getAll(this.schema.name, {
filters: {
submitted: true,
cancelled: false,
returnAgainst: this.returnAgainst,
},
});

const isItemsReturned = returnInvoices.length;

const invoiceDoc = await this.fyo.doc.getDoc(
this.schemaName,
this.returnAgainst
);
await invoiceDoc.setAndSync({ isItemsReturned });
await invoiceDoc.submit();
}

async _updateReturnInvoiceOutStanding() {
if (!this.isReturn || !this.returnAgainst || !this.grandTotal) {
return;
}

const invoiceOutstandingAmount = Object.values(
await this.fyo.db.get(
this.schema.name,
this.returnAgainst,
'outstandingAmount'
)
)[0];

if (!isPesa(invoiceOutstandingAmount)) {
return;
}

const returnInvoiceGrandTotal = this.grandTotal.abs();
let outstandingAmount = this.fyo.pesa(0);

if (this.submitted && !this.cancelled) {
outstandingAmount = invoiceOutstandingAmount.sub(returnInvoiceGrandTotal);
}

if (this.isCancelled) {
outstandingAmount = invoiceOutstandingAmount.add(returnInvoiceGrandTotal);
}

const invoiceDoc = await this.fyo.doc.getDoc(
this.schemaName,
this.returnAgainst
);
await invoiceDoc.setAndSync({ outstandingAmount });
await invoiceDoc.submit();
}

formulas: FormulaMap = {
account: {
formula: async () => {
Expand Down Expand Up @@ -447,6 +577,9 @@ export abstract class Invoice extends Transactional {
!!this.autoStockTransferLocation,
dependsOn: [],
},
returnCompleted: {
formula: () => false,
},
};

getStockTransferred() {
Expand Down Expand Up @@ -518,6 +651,8 @@ export abstract class Invoice extends Transactional {
!(this.attachment || !(this.isSubmitted || this.isCancelled)),
backReference: () => !this.backReference,
priceList: () => !this.fyo.singles.AccountingSettings?.enablePriceList,
isReturn: () => !this.fyo.singles.AccountingSettings?.enableInvoiceReturns,
returnAgainst: () => !this.isReturn,
};

static defaults: DefaultMap = {
Expand Down Expand Up @@ -552,6 +687,12 @@ export abstract class Invoice extends Transactional {
isEnabled: true,
...(doc.isSales ? { isSales: true } : { isPurchase: true }),
}),
returnAgainst: () => ({
submitted: true,
isReturn: false,
cancelled: false,
returnCompleted: false,
}),
};

static createFilters: FiltersMap = {
Expand Down Expand Up @@ -591,16 +732,19 @@ export abstract class Invoice extends Transactional {
return null;
}

if (this.outstandingAmount?.isZero()) {
return null;
}
const accountField =
this.isSales && !this.outstandingAmount?.isNegative()
? 'account'
: 'paymentAccount';

const accountField = this.isSales ? 'account' : 'paymentAccount';
const data = {
party: this.party,
date: new Date().toISOString().slice(0, 10),
paymentType: this.isSales ? 'Receive' : 'Pay',
amount: this.outstandingAmount,
paymentType:
this.isSales && !this.outstandingAmount?.isNegative()
? 'Receive'
: 'Pay',
amount: this.outstandingAmount?.abs(),
[accountField]: this.account,
for: [
{
Expand Down Expand Up @@ -720,6 +864,7 @@ export abstract class Invoice extends Transactional {
async beforeCancel(): Promise<void> {
await super.beforeCancel();
await this._validateStockTransferCancelled();
await this._validateHasLinkedReturnInvoices();
}

async beforeDelete(): Promise<void> {
Expand Down Expand Up @@ -753,6 +898,31 @@ export abstract class Invoice extends Transactional {
);
}

async _validateHasLinkedReturnInvoices() {
if (!this.name || this.isReturn) {
return;
}

const returnInvoices = await this.fyo.db.getAll(this.schemaName, {
filters: {
returnAgainst: this.name,
},
});

if (!returnInvoices.length) {
return;
}

const names = returnInvoices.map(({ name }) => name).join(', ');
const label =
this.fyo.schemaMap[this.schemaName]?.label ?? this.schema.name;

throw new ValidationError(
this.fyo
.t`Cannot cancel ${this.schema.label} ${this.name} because of the following ${label}: ${names}`
);
}

async _getLinkedStockTransferNames(cancelled: boolean) {
const name = this.name;
if (!name) {
Expand Down
Loading