diff --git a/backend/database/bespoke.ts b/backend/database/bespoke.ts index b9b3af74..6aaed0e6 100644 --- a/backend/database/bespoke.ts +++ b/backend/database/bespoke.ts @@ -10,6 +10,7 @@ import DatabaseCore from './core'; import { BespokeFunction } from './types'; import { DocItem, ReturnDocItem } from 'models/inventory/types'; import { safeParseFloat } from 'utils/index'; +import { Money } from 'pesa'; export class BespokeQueries { [key: string]: BespokeFunction; @@ -390,4 +391,47 @@ export class BespokeQueries { } return returnBalanceItems; } + + static async getPOSTransactedAmount( + db: DatabaseCore, + fromDate: Date + ): Promise | undefined> { + const sinvNames = ( + await db.knex!(ModelNameEnum.SalesInvoice) + .select('name') + .where('isPOS', true) + .andWhereRaw('datetime(date) > datetime(?)', [ + new Date(fromDate.setHours(0, 0, 0)).toISOString(), + ]) + .andWhereRaw('datetime(date) < datetime(?)', [new Date().toISOString()]) + ).map((row: { name: string }) => row.name); + + if (!sinvNames.length) { + return; + } + + const paymentEntryNames: string[] = ( + await db.knex!(ModelNameEnum.PaymentFor) + .select('parent') + .whereIn('referenceName', sinvNames) + ).map((doc: { parent: string }) => doc.parent); + + const groupedAmounts = (await db.knex!(ModelNameEnum.Payment) + .select('paymentMethod') + .whereIn('name', paymentEntryNames) + .groupBy('paymentMethod') + .sum({ amount: 'amount' })) as { paymentMethod: string; amount: Money }[]; + + const transactedAmounts = {} as { [paymentMethod: string]: Money }; + + if (!groupedAmounts) { + return; + } + + for (const row of groupedAmounts) { + transactedAmounts[row.paymentMethod] = row.amount; + } + + return transactedAmounts; + } } diff --git a/fyo/core/dbHandler.ts b/fyo/core/dbHandler.ts index cb75cc9c..6a2c7d49 100644 --- a/fyo/core/dbHandler.ts +++ b/fyo/core/dbHandler.ts @@ -27,6 +27,7 @@ import { RawValueMap, } from './types'; import { ReturnDocItem } from 'models/inventory/types'; +import { Money } from 'pesa'; type FieldMap = Record>; @@ -342,6 +343,15 @@ export class DatabaseHandler extends DatabaseBase { )) as Promise | undefined>; } + async getPOSTransactedAmount( + fromDate: Date + ): Promise | undefined> { + return (await this.#demux.callBespoke( + 'getPOSTransactedAmount', + fromDate + )) as Promise | undefined>; + } + /** * Internal methods */