code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
from setuptools import find_packages, setup with open("requirements.txt") as f: install_requires = f.read().strip().split("\n") # get version from __version__ variable in print_designer/__init__.py from print_designer import __version__ as version setup( name="print_designer", version=version, description="Frappe App to Design Print Formats using interactive UI.", author="Frappe Technologies Pvt Ltd.", author_email="hello@frappe.io", packages=find_packages(), zip_safe=False, include_package_data=True, install_requires=install_requires, )
2302_79757062/print_designer
setup.py
Python
agpl-3.0
557
import { Cashflow, IncomeExpense, TopExpenses, TotalCreditAndDebit, TotalOutstanding, } from 'utils/db/types'; import { ModelNameEnum } from '../../models/types'; import DatabaseCore from './core'; import { BespokeFunction } from './types'; import { DateTime } from 'luxon'; import { DocItem, ReturnDocItem } from 'models/inventory/types'; import { safeParseFloat } from 'utils/index'; import { Money } from 'pesa'; export class BespokeQueries { [key: string]: BespokeFunction; static async getLastInserted( db: DatabaseCore, schemaName: string ): Promise<number> { const lastInserted = (await db.knex!.raw( 'select cast(name as int) as num from ?? order by num desc limit 1', [schemaName] )) as { num: number }[]; const num = lastInserted?.[0]?.num; if (num === undefined) { return 0; } return num; } static async getTopExpenses( db: DatabaseCore, fromDate: string, toDate: string ) { const expenseAccounts = db .knex!.select('name') .from('Account') .where('rootType', 'Expense'); const topExpenses = await db .knex!.select({ total: db.knex!.raw('sum(cast(debit as real) - cast(credit as real))'), }) .select('account') .from('AccountingLedgerEntry') .where('reverted', false) .where('account', 'in', expenseAccounts) .whereBetween('date', [fromDate, toDate]) .groupBy('account') .orderBy('total', 'desc') .limit(5); return topExpenses as TopExpenses; } static async getTotalOutstanding( db: DatabaseCore, schemaName: string, fromDate: string, toDate: string ) { return (await db.knex!(schemaName) .sum({ total: 'baseGrandTotal' }) .sum({ outstanding: 'outstandingAmount' }) .where('submitted', true) .where('cancelled', false) .whereBetween('date', [fromDate, toDate]) .first()) as TotalOutstanding; } static async getCashflow(db: DatabaseCore, fromDate: string, toDate: string) { const cashAndBankAccounts = db.knex!('Account') .select('name') .where('accountType', 'in', ['Cash', 'Bank']) .andWhere('isGroup', false); const dateAsMonthYear = db.knex!.raw(`strftime('%Y-%m', ??)`, 'date'); return (await db.knex!('AccountingLedgerEntry') .where('reverted', false) .sum({ inflow: 'debit', outflow: 'credit', }) .select({ yearmonth: dateAsMonthYear, }) .where('account', 'in', cashAndBankAccounts) .whereBetween('date', [fromDate, toDate]) .groupBy(dateAsMonthYear)) as Cashflow; } static async getIncomeAndExpenses( db: DatabaseCore, fromDate: string, toDate: string ) { const income = (await db.knex!.raw( ` select sum(cast(credit as real) - cast(debit as real)) as balance, strftime('%Y-%m', date) as yearmonth from AccountingLedgerEntry where reverted = false and date between date(?) and date(?) and account in ( select name from Account where rootType = 'Income' ) group by yearmonth`, [fromDate, toDate] )) as IncomeExpense['income']; const expense = (await db.knex!.raw( ` select sum(cast(debit as real) - cast(credit as real)) as balance, strftime('%Y-%m', date) as yearmonth from AccountingLedgerEntry where reverted = false and date between date(?) and date(?) and account in ( select name from Account where rootType = 'Expense' ) group by yearmonth`, [fromDate, toDate] )) as IncomeExpense['expense']; return { income, expense }; } static async getTotalCreditAndDebit(db: DatabaseCore) { return (await db.knex!.raw(` select account, sum(cast(credit as real)) as totalCredit, sum(cast(debit as real)) as totalDebit from AccountingLedgerEntry group by account `)) as unknown as TotalCreditAndDebit; } static async getStockQuantity( db: DatabaseCore, item: string, location?: string, fromDate?: string, toDate?: string, batch?: string, serialNumbers?: string[] ): Promise<number | null> { /* eslint-disable @typescript-eslint/no-floating-promises */ const query = db.knex!(ModelNameEnum.StockLedgerEntry) .sum('quantity') .where('item', item); if (location) { query.andWhere('location', location); } if (batch) { query.andWhere('batch', batch); } if (serialNumbers?.length) { query.andWhere('serialNumber', 'in', serialNumbers); } if (fromDate) { query.andWhereRaw('datetime(date) > datetime(?)', [fromDate]); } if (toDate) { query.andWhereRaw('datetime(date) < datetime(?)', [toDate]); } const value = (await query) as Record<string, number | null>[]; if (!value.length) { return null; } return value[0][Object.keys(value[0])[0]]; } static async getReturnBalanceItemsQty( db: DatabaseCore, schemaName: ModelNameEnum, docName: string ): Promise<Record<string, ReturnDocItem> | undefined> { const returnDocNames = ( await db.knex!(schemaName) .select('name') .where('returnAgainst', docName) .andWhere('submitted', true) .andWhere('cancelled', false) ).map((i: { name: string }) => i.name); if (!returnDocNames.length) { return; } const returnedItemsQuery = db.knex!(`${schemaName}Item`) .sum({ quantity: 'quantity' }) .whereIn('parent', returnDocNames); const docItemsQuery = db.knex!(`${schemaName}Item`) .where('parent', docName) .sum({ quantity: 'quantity' }); if ( [ModelNameEnum.SalesInvoice, ModelNameEnum.PurchaseInvoice].includes( schemaName ) ) { returnedItemsQuery.select('item', 'batch').groupBy('item', 'batch'); docItemsQuery.select('name', 'item', 'batch').groupBy('item', 'batch'); } if ( [ModelNameEnum.Shipment, ModelNameEnum.PurchaseReceipt].includes( schemaName ) ) { returnedItemsQuery .select('item', 'batch', 'serialNumber') .groupBy('item', 'batch', 'serialNumber'); docItemsQuery .select('name', 'item', 'batch', 'serialNumber') .groupBy('item', 'batch', 'serialNumber'); } const returnedItems = (await returnedItemsQuery) as DocItem[]; if (!returnedItems.length) { return; } const docItems = (await docItemsQuery) as DocItem[]; const docItemsMap = BespokeQueries.#getDocItemMap(docItems); const returnedItemsMap = BespokeQueries.#getDocItemMap(returnedItems); const returnBalanceItems = BespokeQueries.#getReturnBalanceItemQtyMap( docItemsMap, returnedItemsMap ); return returnBalanceItems; } static #getDocItemMap(docItems: DocItem[]): Record<string, ReturnDocItem> { const docItemsMap: Record<string, ReturnDocItem> = {}; const batchesMap: | Record< string, { quantity: number; serialNumbers?: string[] | undefined } > | undefined = {}; for (const item of docItems) { if (!!docItemsMap[item.item]) { if (item.batch) { let serialNumbers: string[] | undefined; if (item.serialNumber) { serialNumbers = item.serialNumber.split('\n'); docItemsMap[item.item].batches![item.batch] = { quantity: item.quantity, serialNumbers, }; } docItemsMap[item.item].batches![item.batch] = { quantity: item.quantity, serialNumbers, }; } else { docItemsMap[item.item].quantity += item.quantity; } if (item.serialNumber) { const serialNumbers: string[] = []; if (docItemsMap[item.item].serialNumbers) { serialNumbers.push(...(docItemsMap[item.item].serialNumbers ?? [])); } serialNumbers.push(...item.serialNumber.split('\n')); docItemsMap[item.item].serialNumbers = serialNumbers; } continue; } if (item.batch) { let serialNumbers: string[] | undefined = undefined; if (item.serialNumber) { serialNumbers = item.serialNumber.split('\n'); } batchesMap[item.batch] = { serialNumbers, quantity: item.quantity, }; } let serialNumbers: string[] | undefined = undefined; if (!item.batch && item.serialNumber) { serialNumbers = item.serialNumber.split('\n'); } docItemsMap[item.item] = { serialNumbers, batches: batchesMap, quantity: item.quantity, }; } return docItemsMap; } static #getReturnBalanceItemQtyMap( docItemsMap: Record<string, ReturnDocItem>, returnedItemsMap: Record<string, ReturnDocItem> ): Record<string, ReturnDocItem> { const returnBalanceItems: Record<string, ReturnDocItem> | undefined = {}; const balanceBatchQtyMap: | Record< string, { quantity: number; serialNumbers: string[] | undefined } > | undefined = {}; for (const row in returnedItemsMap) { const balanceSerialNumbersMap: string[] | undefined = []; if (!docItemsMap[row]) { continue; } const returnedItem = returnedItemsMap[row]; const docItem = docItemsMap[row]; let balanceQty = 0; const docItemHasBatch = !!Object.keys(docItem.batches ?? {}).length; const returnedItemHasBatch = !!Object.keys(returnedItem.batches ?? {}) .length; if (docItemHasBatch && returnedItemHasBatch && docItem.batches) { for (const batch in returnedItem.batches) { const returnedItemQty = Math.abs( returnedItem.batches[batch].quantity ); const docBatchItemQty = docItem.batches[batch].quantity; const balanceQty = returnedItemQty - docBatchItemQty; const docItemSerialNumbers = docItem.batches[batch].serialNumbers; const returnItemSerialNumbers = returnedItem.batches[batch].serialNumbers; let balanceSerialNumbers: string[] | undefined; if (docItemSerialNumbers && returnItemSerialNumbers) { balanceSerialNumbers = docItemSerialNumbers.filter( (serialNumber: string) => returnItemSerialNumbers.indexOf(serialNumber) == -1 ); } balanceBatchQtyMap[batch] = { quantity: balanceQty, serialNumbers: balanceSerialNumbers, }; } } if (docItem.serialNumbers && returnedItem.serialNumbers) { for (const serialNumber of docItem.serialNumbers) { if (!returnedItem.serialNumbers.includes(serialNumber)) { balanceSerialNumbersMap.push(serialNumber); } } } balanceQty = safeParseFloat( Math.abs(returnedItem.quantity) - docItemsMap[row].quantity ); returnBalanceItems[row] = { quantity: balanceQty, batches: balanceBatchQtyMap, serialNumbers: balanceSerialNumbersMap, }; } return returnBalanceItems; } static async getPOSTransactedAmount( db: DatabaseCore, fromDate: Date, toDate: Date, lastShiftClosingDate?: Date ): Promise<Record<string, Money> | undefined> { const sinvNamesQuery = db.knex!(ModelNameEnum.SalesInvoice) .select('name') .where('isPOS', true) .andWhereBetween('date', [ DateTime.fromJSDate(fromDate).toSQLDate(), DateTime.fromJSDate(toDate).toSQLDate(), ]); if (lastShiftClosingDate) { sinvNamesQuery.andWhere( 'created', '>', DateTime.fromJSDate(lastShiftClosingDate).toUTC().toString() ); } const sinvNames = (await sinvNamesQuery).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; } }
2302_79757062/books
backend/database/bespoke.ts
TypeScript
agpl-3.0
12,842
import { getDbError, NotFoundError, ValueError } from 'fyo/utils/errors'; import { knex, Knex } from 'knex'; import { Field, FieldTypeEnum, RawValue, Schema, SchemaMap, TargetField, } from '../../schemas/types'; import { getIsNullOrUndef, getRandomString, getValueMapFromList, } from '../../utils'; import { DatabaseBase, GetAllOptions, QueryFilter } from '../../utils/db/types'; import { getDefaultMetaFieldValueMap, sqliteTypeMap, SYSTEM } from '../helpers'; import { AlterConfig, ColumnDiff, FieldValueMap, GetQueryBuilderOptions, MigrationConfig, NonExtantConfig, SingleValue, UpdateSinglesConfig, } from './types'; /** * # DatabaseCore * This is the ORM, the DatabaseCore interface (function signatures) should be * replicated by the frontend demuxes and all the backend muxes. * * ## Db Core Call Sequence * * 1. Init core: `const db = new DatabaseCore(dbPath)`. * 2. Connect db: `db.connect()`. This will allow for raw queries to be executed. * 3. Set schemas: `db.setSchemaMap(schemaMap)`. This will allow for ORM functions to be executed. * 4. Migrate: `await db.migrate()`. This will create absent tables and update the tables' shape. * 5. ORM function execution: `db.get(...)`, `db.insert(...)`, etc. * 6. Close connection: `await db.close()`. * * Note: Meta values: created, modified, createdBy, modifiedBy are set by DatabaseCore * only for schemas that are SingleValue. Else they have to be passed by the caller in * the `fieldValueMap`. */ export default class DatabaseCore extends DatabaseBase { knex?: Knex; typeMap = sqliteTypeMap; dbPath: string; schemaMap: SchemaMap = {}; connectionParams: Knex.Config; constructor(dbPath?: string) { super(); this.dbPath = dbPath ?? ':memory:'; this.connectionParams = { client: 'better-sqlite3', connection: { filename: this.dbPath, }, useNullAsDefault: true, asyncStackTraces: process.env.NODE_ENV === 'development', }; } static async getCountryCode(dbPath: string): Promise<string> { let countryCode = 'in'; const db = new DatabaseCore(dbPath); await db.connect(); let query: { value: string }[] = []; try { query = (await db.knex!('SingleValue').where({ fieldname: 'countryCode', parent: 'SystemSettings', })) as { value: string }[]; } catch { // Database not inialized and no countryCode passed } if (query.length > 0) { countryCode = query[0].value; } await db.close(); return countryCode; } setSchemaMap(schemaMap: SchemaMap) { this.schemaMap = schemaMap; } async connect() { this.knex = knex(this.connectionParams); await this.knex.raw('PRAGMA foreign_keys=ON'); } async close() { await this.knex!.destroy(); } async migrate(config: MigrationConfig = {}) { const { create, alter } = await this.#getCreateAlterList(); const hasSingleValueTable = !create.includes('SingleValue'); let singlesConfig: UpdateSinglesConfig = { update: [], updateNonExtant: [], }; if (hasSingleValueTable) { singlesConfig = await this.#getSinglesUpdateList(); } const shouldMigrate = !!( create.length || alter.length || singlesConfig.update.length || singlesConfig.updateNonExtant.length ); if (!shouldMigrate) { return; } await config.pre?.(); for (const schemaName of create) { await this.#createTable(schemaName); } for (const config of alter) { await this.#alterTable(config); } if (!hasSingleValueTable) { singlesConfig = await this.#getSinglesUpdateList(); } await this.#initializeSingles(singlesConfig); await config.post?.(); } async #getCreateAlterList() { const create: string[] = []; const alter: AlterConfig[] = []; for (const [schemaName, schema] of Object.entries(this.schemaMap)) { if (!schema || schema.isSingle) { continue; } const exists = await this.#tableExists(schemaName); if (!exists) { create.push(schemaName); continue; } const diff: ColumnDiff = await this.#getColumnDiff(schemaName); const newForeignKeys: Field[] = await this.#getNewForeignKeys(schemaName); if (diff.added.length || diff.removed.length || newForeignKeys.length) { alter.push({ schemaName, diff, newForeignKeys, }); } } return { create, alter }; } async exists(schemaName: string, name?: string): Promise<boolean> { const schema = this.schemaMap[schemaName] as Schema; if (schema.isSingle) { return this.#singleExists(schemaName); } let row = []; try { const qb = this.knex!(schemaName); if (name !== undefined) { // eslint-disable-next-line @typescript-eslint/no-floating-promises qb.where({ name }); } row = await qb.limit(1); } catch (err) { if (getDbError(err as Error) !== NotFoundError) { throw err; } } return row.length > 0; } async insert( schemaName: string, fieldValueMap: FieldValueMap ): Promise<FieldValueMap> { // insert parent if (this.schemaMap[schemaName]!.isSingle) { await this.#updateSingleValues(schemaName, fieldValueMap); } else { await this.#insertOne(schemaName, fieldValueMap); } // insert children await this.#insertOrUpdateChildren(schemaName, fieldValueMap, false); return fieldValueMap; } async get( schemaName: string, name = '', fields?: string | string[] ): Promise<FieldValueMap> { const schema = this.schemaMap[schemaName] as Schema; if (!schema.isSingle && !name) { throw new ValueError('name is mandatory'); } /** * If schema is single return all the values * of the single type schema, in this case field * is ignored. */ let fieldValueMap: FieldValueMap = {}; if (schema.isSingle) { return await this.#getSingle(schemaName); } if (typeof fields === 'string') { fields = [fields]; } if (fields === undefined) { fields = schema.fields.filter((f) => !f.computed).map((f) => f.fieldname); } /** * Separate table fields and non table fields */ const allTableFields: TargetField[] = this.#getTableFields(schemaName); const allTableFieldNames: string[] = allTableFields.map((f) => f.fieldname); const tableFields: TargetField[] = allTableFields.filter((f) => fields!.includes(f.fieldname) ); const nonTableFieldNames: string[] = fields.filter( (f) => !allTableFieldNames.includes(f) ); /** * If schema is not single then return specific fields * if child fields are selected, all child fields are returned. */ if (nonTableFieldNames.length) { fieldValueMap = (await this.#getOne(schemaName, name, nonTableFieldNames)) ?? {}; } if (tableFields.length) { await this.#loadChildren(name, fieldValueMap, tableFields); } return fieldValueMap; } async getAll( schemaName: string, options: GetAllOptions = {} ): Promise<FieldValueMap[]> { const schema = this.schemaMap[schemaName] as Schema; if (schema === undefined) { throw new NotFoundError(`schema ${schemaName} not found`); } const hasCreated = !!schema.fields.find((f) => f.fieldname === 'created'); const { fields = ['name'], filters, offset, limit, groupBy, orderBy = hasCreated ? 'created' : undefined, order = 'desc', } = options; return (await this.#getQueryBuilder( schemaName, typeof fields === 'string' ? [fields] : fields, filters ?? {}, { offset, limit, groupBy, orderBy, order, } )) as FieldValueMap[]; } async deleteAll(schemaName: string, filters: QueryFilter): Promise<number> { const builder = this.knex!(schemaName); this.#applyFiltersToBuilder(builder, filters); return await builder.delete(); } async getSingleValues( ...fieldnames: ({ fieldname: string; parent?: string } | string)[] ): Promise<SingleValue<RawValue>> { const fieldnameList = fieldnames.map((fieldname) => { if (typeof fieldname === 'string') { return { fieldname }; } return fieldname; }); let builder = this.knex!('SingleValue'); builder = builder.where(fieldnameList[0]); fieldnameList.slice(1).forEach(({ fieldname, parent }) => { if (typeof parent === 'undefined') { builder = builder.orWhere({ fieldname }); } else { builder = builder.orWhere({ fieldname, parent }); } }); let values: { fieldname: string; parent: string; value: RawValue }[] = []; try { values = await builder.select('fieldname', 'value', 'parent'); } catch (err) { if (getDbError(err as Error) === NotFoundError) { return []; } throw err; } return values; } async rename(schemaName: string, oldName: string, newName: string) { /** * Rename is expensive mostly won't allow it. * TODO: rename all links * TODO: rename in childtables */ await this.knex!(schemaName) .update({ name: newName }) .where('name', oldName); } async update(schemaName: string, fieldValueMap: FieldValueMap) { // update parent if (this.schemaMap[schemaName]!.isSingle) { await this.#updateSingleValues(schemaName, fieldValueMap); } else { await this.#updateOne(schemaName, fieldValueMap); } // insert or update children await this.#insertOrUpdateChildren(schemaName, fieldValueMap, true); } async delete(schemaName: string, name: string) { const schema = this.schemaMap[schemaName] as Schema; if (schema.isSingle) { await this.#deleteSingle(schemaName, name); return; } await this.#deleteOne(schemaName, name); // delete children const tableFields = this.#getTableFields(schemaName); for (const field of tableFields) { await this.#deleteChildren(field.target, name); } } async #tableExists(schemaName: string): Promise<boolean> { return await this.knex!.schema.hasTable(schemaName); } async #singleExists(singleSchemaName: string): Promise<boolean> { const res = await this.knex!('SingleValue') .count('parent as count') .where('parent', singleSchemaName) .first(); if (typeof res?.count === 'number') { return res.count > 0; } return false; } async #dropColumns(schemaName: string, targetColumns: string[]) { await this.knex!.schema.table(schemaName, (table) => { table.dropColumns(...targetColumns); }); } async prestigeTheTable(schemaName: string, tableRows: FieldValueMap[]) { // Alter table hacx for sqlite in case of schema change. const tempName = `__${schemaName}`; // Create replacement table await this.knex!.schema.dropTableIfExists(tempName); await this.knex!.raw('PRAGMA foreign_keys=OFF'); await this.#createTable(schemaName, tempName); // Insert rows from source table into the replacement table await this.knex!.batchInsert(tempName, tableRows, 200); // Replace with the replacement table await this.knex!.schema.dropTable(schemaName); await this.knex!.schema.renameTable(tempName, schemaName); await this.knex!.raw('PRAGMA foreign_keys=ON'); } async #getTableColumns(schemaName: string): Promise<string[]> { const info: FieldValueMap[] = await this.knex!.raw( `PRAGMA table_info(${schemaName})` ); return info.map((d) => d.name as string); } async truncate(tableNames?: string[]) { if (tableNames === undefined) { const q = (await this.knex!.raw(` select name from sqlite_schema where type='table' and name not like 'sqlite_%'`)) as { name: string }[]; tableNames = q.map((i) => i.name); } for (const name of tableNames) { await this.knex!(name).del(); } } async #getForeignKeys(schemaName: string): Promise<string[]> { const foreignKeyList: FieldValueMap[] = await this.knex!.raw( `PRAGMA foreign_key_list(${schemaName})` ); return foreignKeyList.map((d) => d.from as string); } #getQueryBuilder( schemaName: string, fields: string[], filters: QueryFilter, options: GetQueryBuilderOptions ): Knex.QueryBuilder { /* eslint-disable @typescript-eslint/no-floating-promises */ const builder = this.knex!.select(fields).from(schemaName); this.#applyFiltersToBuilder(builder, filters); const { orderBy, groupBy, order } = options; if (Array.isArray(orderBy)) { builder.orderBy(orderBy.map((column) => ({ column, order }))); } if (typeof orderBy === 'string') { builder.orderBy(orderBy, order); } if (Array.isArray(groupBy)) { builder.groupBy(...groupBy); } if (typeof groupBy === 'string') { builder.groupBy(groupBy); } if (options.offset) { builder.offset(options.offset); } if (options.limit) { builder.limit(options.limit); } return builder; } #applyFiltersToBuilder(builder: Knex.QueryBuilder, filters: QueryFilter) { // {"status": "Open"} => `status = "Open"` // {"status": "Open", "name": ["like", "apple%"]} // => `status="Open" and name like "apple%" // {"date": [">=", "2017-09-09", "<=", "2017-11-01"]} // => `date >= 2017-09-09 and date <= 2017-11-01` const filtersArray = this.#getFiltersArray(filters); for (let i = 0; i < filtersArray.length; i++) { const filter = filtersArray[i]; const field = filter[0] as string; const operator = filter[1]; const comparisonValue = filter[2]; const type = i === 0 ? 'where' : 'andWhere'; if (operator === '=') { builder[type](field, comparisonValue); } else if ( operator === 'in' && (comparisonValue as (string | null)[]).includes(null) ) { const nonNulls = (comparisonValue as (string | null)[]).filter( Boolean ) as string[]; builder[type](field, operator, nonNulls).orWhere(field, null); } else { builder[type](field, operator as string, comparisonValue as string); } } } #getFiltersArray(filters: QueryFilter) { const filtersArray = []; for (const field in filters) { const value = filters[field]; let operator: string | number = '='; let comparisonValue = value as string | number | (string | number)[]; if (Array.isArray(value)) { operator = (value[0] as string).toLowerCase(); comparisonValue = value[1] as string | number | (string | number)[]; if (operator === 'includes') { operator = 'like'; } if ( operator === 'like' && typeof comparisonValue === 'string' && !comparisonValue.includes('%') ) { comparisonValue = `%${comparisonValue}%`; } } filtersArray.push([field, operator, comparisonValue]); if (Array.isArray(value) && value.length > 2) { // multiple conditions const operator = value[2]; const comparisonValue = value[3]; filtersArray.push([field, operator, comparisonValue]); } } return filtersArray; } async #getColumnDiff(schemaName: string): Promise<ColumnDiff> { const tableColumns = await this.#getTableColumns(schemaName); const validFields = this.schemaMap[schemaName]!.fields.filter( (f) => !f.computed ); const diff: ColumnDiff = { added: [], removed: [] }; for (const field of validFields) { const hasDbType = this.typeMap.hasOwnProperty(field.fieldtype); if (!tableColumns.includes(field.fieldname) && hasDbType) { diff.added.push(field); } } const validFieldNames = validFields.map((field) => field.fieldname); for (const column of tableColumns) { if (!validFieldNames.includes(column)) { diff.removed.push(column); } } return diff; } async #getNewForeignKeys(schemaName: string): Promise<Field[]> { const foreignKeys = await this.#getForeignKeys(schemaName); const newForeignKeys: Field[] = []; const schema = this.schemaMap[schemaName] as Schema; for (const field of schema.fields) { if ( field.fieldtype === 'Link' && !foreignKeys.includes(field.fieldname) ) { newForeignKeys.push(field); } } return newForeignKeys; } #buildColumnForTable(table: Knex.AlterTableBuilder, field: Field) { if (field.fieldtype === FieldTypeEnum.Table) { // In case columnType is "Table" // childTable links are handled using the childTable's "parent" field return; } const columnType = this.typeMap[field.fieldtype]; if (!columnType) { return; } const column = table[columnType]( field.fieldname ) as Knex.SqlLiteColumnBuilder; // primary key if (field.fieldname === 'name') { column.primary(); } // iefault value if (field.default !== undefined) { column.defaultTo(field.default); } // required if (field.required) { column.notNullable(); } // link if (field.fieldtype === FieldTypeEnum.Link && field.target) { const targetSchemaName = field.target; const schema = this.schemaMap[targetSchemaName] as Schema; table .foreign(field.fieldname) .references('name') .inTable(schema.name) .onUpdate('CASCADE') .onDelete('RESTRICT'); } } async #alterTable({ schemaName, diff, newForeignKeys }: AlterConfig) { await this.knex!.schema.table(schemaName, (table) => { if (!diff.added.length) { return; } for (const field of diff.added) { this.#buildColumnForTable(table, field); } }); if (diff.removed.length) { await this.#dropColumns(schemaName, diff.removed); } if (newForeignKeys.length) { await this.#addForeignKeys(schemaName); } } async #createTable(schemaName: string, tableName?: string) { tableName ??= schemaName; const fields = this.schemaMap[schemaName]!.fields.filter( (f) => !f.computed ); return await this.#runCreateTableQuery(tableName, fields); } #runCreateTableQuery(schemaName: string, fields: Field[]) { return this.knex!.schema.createTable(schemaName, (table) => { for (const field of fields) { this.#buildColumnForTable(table, field); } }); } async #getNonExtantSingleValues(singleSchemaName: string) { const existingFields = ( (await this.knex!('SingleValue') .where({ parent: singleSchemaName }) .select('fieldname')) as { fieldname: string }[] ).map(({ fieldname }) => fieldname); const nonExtant: NonExtantConfig['nonExtant'] = []; const fields = this.schemaMap[singleSchemaName]?.fields ?? []; for (const { fieldname, default: value } of fields) { if (existingFields.includes(fieldname) || value === undefined) { continue; } nonExtant.push({ fieldname, value }); } return nonExtant; } async #deleteOne(schemaName: string, name: string) { return await this.knex!(schemaName).where('name', name).delete(); } async #deleteSingle(schemaName: string, fieldname: string) { return await this.knex!('SingleValue') .where({ parent: schemaName, fieldname }) .delete(); } #deleteChildren(schemaName: string, parentName: string) { return this.knex!(schemaName).where('parent', parentName).delete(); } #runDeleteOtherChildren( field: TargetField, parentName: string, added: string[] ) { // delete other children return this.knex!(field.target) .where('parent', parentName) .andWhere('name', 'not in', added) .delete(); } #prepareChild( parentSchemaName: string, parentName: string, child: FieldValueMap, field: Field, idx: number ) { if (!child.name) { child.name ??= getRandomString(); } child.parent = parentName; child.parentSchemaName = parentSchemaName; child.parentFieldname = field.fieldname; child.idx ??= idx; } async #addForeignKeys(schemaName: string) { const tableRows = await this.knex!.select().from(schemaName); await this.prestigeTheTable(schemaName, tableRows); } async #loadChildren( parentName: string, fieldValueMap: FieldValueMap, tableFields: TargetField[] ) { for (const field of tableFields) { fieldValueMap[field.fieldname] = await this.getAll(field.target, { fields: ['*'], filters: { parent: parentName }, orderBy: 'idx', order: 'asc', }); } } async #getOne(schemaName: string, name: string, fields: string[]) { const fieldValueMap = (await this.knex!.select(fields) .from(schemaName) .where('name', name) .first()) as FieldValueMap; return fieldValueMap; } async #getSingle(schemaName: string): Promise<FieldValueMap> { const values = await this.getAll('SingleValue', { fields: ['fieldname', 'value'], filters: { parent: schemaName }, orderBy: 'fieldname', order: 'asc', }); const fieldValueMap = getValueMapFromList( values, 'fieldname', 'value' ) as FieldValueMap; const tableFields: TargetField[] = this.#getTableFields(schemaName); if (tableFields.length) { await this.#loadChildren(schemaName, fieldValueMap, tableFields); } return fieldValueMap; } #insertOne(schemaName: string, fieldValueMap: FieldValueMap) { if (!fieldValueMap.name) { fieldValueMap.name = getRandomString(); } // Column fields const fields = this.schemaMap[schemaName]!.fields.filter( (f) => f.fieldtype !== FieldTypeEnum.Table && !f.computed ); const validMap: FieldValueMap = {}; for (const { fieldname } of fields) { validMap[fieldname] = fieldValueMap[fieldname]; } return this.knex!(schemaName).insert(validMap); } async #updateSingleValues( singleSchemaName: string, fieldValueMap: FieldValueMap ) { const fields = this.schemaMap[singleSchemaName]!.fields.filter( (f) => !f.computed && f.fieldtype !== 'Table' ); for (const field of fields) { const value = fieldValueMap[field.fieldname] as RawValue | undefined; if (value === undefined) { continue; } await this.#updateSingleValue(singleSchemaName, field.fieldname, value); } } async #updateSingleValue( singleSchemaName: string, fieldname: string, value: RawValue ) { const updateKey = { parent: singleSchemaName, fieldname, }; const names = (await this.knex!('SingleValue') .select('name') .where(updateKey)) as { name: string }[]; if (!names?.length) { this.#insertSingleValue(singleSchemaName, fieldname, value); } else { return await this.knex!('SingleValue').where(updateKey).update({ value, modifiedBy: SYSTEM, modified: new Date().toISOString(), }); } } async #insertSingleValue( singleSchemaName: string, fieldname: string, value: RawValue ) { const updateMap = getDefaultMetaFieldValueMap(); const fieldValueMap: FieldValueMap = Object.assign({}, updateMap, { parent: singleSchemaName, fieldname, value, name: getRandomString(), }); return await this.knex!('SingleValue').insert(fieldValueMap); } async #getSinglesUpdateList() { const update: string[] = []; const updateNonExtant: NonExtantConfig[] = []; for (const [schemaName, schema] of Object.entries(this.schemaMap)) { if (!schema || !schema.isSingle) { continue; } const exists = await this.#singleExists(schemaName); if (!exists && schema.fields.some((f) => f.default !== undefined)) { update.push(schemaName); } if (!exists) { continue; } const nonExtant = await this.#getNonExtantSingleValues(schemaName); if (nonExtant.length) { updateNonExtant.push({ schemaName, nonExtant, }); } } return { update, updateNonExtant }; } async #initializeSingles({ update, updateNonExtant }: UpdateSinglesConfig) { for (const config of updateNonExtant) { await this.#updateNonExtantSingleValues(config); } for (const schemaName of update) { const fields = this.schemaMap[schemaName]!.fields; const defaultValues: FieldValueMap = fields.reduce((acc, f) => { if (f.default !== undefined) { acc[f.fieldname] = f.default; } return acc; }, {} as FieldValueMap); await this.#updateSingleValues(schemaName, defaultValues); } } async #updateNonExtantSingleValues({ schemaName, nonExtant, }: NonExtantConfig) { for (const { fieldname, value } of nonExtant) { await this.#updateSingleValue(schemaName, fieldname, value); } } async #updateOne(schemaName: string, fieldValueMap: FieldValueMap) { const updateMap = { ...fieldValueMap }; delete updateMap.name; const schema = this.schemaMap[schemaName] as Schema; for (const { fieldname, fieldtype, computed } of schema.fields) { if (fieldtype !== FieldTypeEnum.Table && !computed) { continue; } delete updateMap[fieldname]; } if (Object.keys(updateMap).length === 0) { return; } return await this.knex!(schemaName) .where('name', fieldValueMap.name as string) .update(updateMap); } async #insertOrUpdateChildren( schemaName: string, fieldValueMap: FieldValueMap, isUpdate: boolean ) { let parentName = fieldValueMap.name as string; if (this.schemaMap[schemaName]?.isSingle) { parentName = schemaName; } const tableFields = this.#getTableFields(schemaName); for (const field of tableFields) { const added: string[] = []; const tableFieldValue = fieldValueMap[field.fieldname] as | FieldValueMap[] | undefined | null; if (getIsNullOrUndef(tableFieldValue)) { continue; } for (const child of tableFieldValue) { this.#prepareChild(schemaName, parentName, child, field, added.length); if ( isUpdate && (await this.exists(field.target, child.name as string)) ) { await this.#updateOne(field.target, child); } else { await this.#insertOne(field.target, child); } added.push(child.name as string); } if (isUpdate) { await this.#runDeleteOtherChildren(field, parentName, added); } } } #getTableFields(schemaName: string): TargetField[] { return this.schemaMap[schemaName]!.fields.filter( (f) => f.fieldtype === FieldTypeEnum.Table ) as TargetField[]; } }
2302_79757062/books
backend/database/core.ts
TypeScript
agpl-3.0
27,236
import BetterSQLite3 from 'better-sqlite3'; import fs from 'fs-extra'; import { DatabaseError } from 'fyo/utils/errors'; import path from 'path'; import { DatabaseDemuxBase, DatabaseMethod } from 'utils/db/types'; import { getMapFromList } from 'utils/index'; import { Version } from 'utils/version'; import { getSchemas } from '../../schemas'; import { databaseMethodSet, unlinkIfExists } from '../helpers'; import patches from '../patches'; import { BespokeQueries } from './bespoke'; import DatabaseCore from './core'; import { runPatches } from './runPatch'; import { BespokeFunction, Patch, RawCustomField } from './types'; export class DatabaseManager extends DatabaseDemuxBase { db?: DatabaseCore; rawCustomFields: RawCustomField[] = []; get #isInitialized(): boolean { return this.db !== undefined && this.db.knex !== undefined; } getSchemaMap() { if (this.#isInitialized) { return this.db?.schemaMap ?? getSchemas('-', this.rawCustomFields); } return getSchemas('-', this.rawCustomFields); } async createNewDatabase(dbPath: string, countryCode: string) { await unlinkIfExists(dbPath); return await this.connectToDatabase(dbPath, countryCode); } async connectToDatabase(dbPath: string, countryCode?: string) { countryCode = await this._connect(dbPath, countryCode); await this.#migrate(); return countryCode; } async _connect(dbPath: string, countryCode?: string) { countryCode ??= await DatabaseCore.getCountryCode(dbPath); this.db = new DatabaseCore(dbPath); await this.db.connect(); await this.setRawCustomFields(); const schemaMap = getSchemas(countryCode, this.rawCustomFields); this.db.setSchemaMap(schemaMap); return countryCode; } async setRawCustomFields() { try { this.rawCustomFields = (await this.db?.knex?.( 'CustomField' )) as RawCustomField[]; } catch {} } async #migrate(): Promise<void> { if (!this.#isInitialized) { return; } const isFirstRun = await this.#getIsFirstRun(); if (isFirstRun) { await this.db!.migrate(); } await this.#executeMigration(); } async #executeMigration() { const version = await this.#getAppVersion(); const patches = await this.#getPatchesToExecute(version); const hasPatches = !!patches.pre.length || !!patches.post.length; if (hasPatches) { await this.#createBackup(); } await runPatches(patches.pre, this, version); await this.db!.migrate({ pre: async () => { if (hasPatches) { return; } await this.#createBackup(); }, }); await runPatches(patches.post, this, version); } async #getPatchesToExecute( version: string ): Promise<{ pre: Patch[]; post: Patch[] }> { if (this.db === undefined) { return { pre: [], post: [] }; } const query = (await this.db.knex!('PatchRun').select()) as { name: string; version?: string; failed?: boolean; }[]; const runPatchesMap = getMapFromList(query, 'name'); /** * A patch is run only if: * - it hasn't run and was added in a future version * i.e. app version is before patch added version * - it ran but failed in some other version (i.e fixed) */ const filtered = patches .filter((p) => { const exec = runPatchesMap[p.name]; if (!exec && Version.lte(version, p.version)) { return true; } if (exec?.failed && exec?.version !== version) { return true; } return false; }) .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)); return { pre: filtered.filter((p) => p.patch.beforeMigrate), post: filtered.filter((p) => !p.patch.beforeMigrate), }; } async call(method: DatabaseMethod, ...args: unknown[]) { if (!this.#isInitialized) { return; } if (!databaseMethodSet.has(method)) { return; } // @ts-ignore const response = await this.db[method](...args); if (method === 'close') { delete this.db; } return response; } async callBespoke(method: string, ...args: unknown[]): Promise<unknown> { if (!this.#isInitialized) { return; } if (!BespokeQueries.hasOwnProperty(method)) { throw new DatabaseError(`invalid bespoke db function ${method}`); } const queryFunction: BespokeFunction = BespokeQueries[method as keyof BespokeFunction]; return await queryFunction(this.db!, ...args); } async #getIsFirstRun(): Promise<boolean> { const knex = this.db?.knex; if (!knex) { return true; } const query = await knex('sqlite_master').where({ type: 'table', name: 'PatchRun', }); return !query.length; } async #createBackup() { const { dbPath } = this.db ?? {}; if (!dbPath || process.env.IS_TEST) { return; } const backupPath = await this.#getBackupFilePath(); if (!backupPath) { return; } const db = this.getDriver(); await db?.backup(backupPath).then(() => db.close()); } async #getBackupFilePath() { const { dbPath } = this.db ?? {}; if (dbPath === ':memory:' || !dbPath) { return null; } let fileName = path.parse(dbPath).name; if (fileName.endsWith('.books')) { fileName = fileName.slice(0, -6); } const backupFolder = path.join(path.dirname(dbPath), 'backups'); const date = new Date().toISOString().split('T')[0]; const version = await this.#getAppVersion(); const backupFile = `${fileName}_${version}_${date}.books.db`; fs.ensureDirSync(backupFolder); return path.join(backupFolder, backupFile); } async #getAppVersion(): Promise<string> { const knex = this.db?.knex; if (!knex) { return '0.0.0'; } const query = await knex('SingleValue') .select('value') .where({ fieldname: 'version', parent: 'SystemSettings' }); const value = (query[0] as undefined | { value: string })?.value; return value || '0.0.0'; } getDriver() { const { dbPath } = this.db ?? {}; if (!dbPath) { return null; } return BetterSQLite3(dbPath, { readonly: true }); } } export default new DatabaseManager();
2302_79757062/books
backend/database/manager.ts
TypeScript
agpl-3.0
6,291
import { emitMainProcessError, getDefaultMetaFieldValueMap } from '../helpers'; import { DatabaseManager } from './manager'; import { FieldValueMap, Patch } from './types'; export async function runPatches( patches: Patch[], dm: DatabaseManager, version: string ) { const list: { name: string; success: boolean }[] = []; for (const patch of patches) { const success = await runPatch(patch, dm, version); list.push({ name: patch.name, success }); } return list; } async function runPatch( patch: Patch, dm: DatabaseManager, version: string ): Promise<boolean> { let failed = false; try { await patch.patch.execute(dm); } catch (error) { failed = true; if (error instanceof Error) { error.message = `Patch Failed: ${patch.name}\n${error.message}`; emitMainProcessError(error, { patchName: patch.name, notifyUser: false }); } } await makeEntry(patch.name, version, failed, dm); return true; } async function makeEntry( patchName: string, version: string, failed: boolean, dm: DatabaseManager ) { const defaultFieldValueMap = getDefaultMetaFieldValueMap() as FieldValueMap; defaultFieldValueMap.name = patchName; defaultFieldValueMap.failed = failed; defaultFieldValueMap.version = version; try { await dm.db!.insert('PatchRun', defaultFieldValueMap); } catch { /** * Error is thrown if PatchRun table hasn't been migrated. * In this case, PatchRun will migrated post pre-migration-patches * are run and rerun the patch. */ return; } }
2302_79757062/books
backend/database/runPatch.ts
TypeScript
agpl-3.0
1,560
import assert from 'assert'; import { cloneDeep } from 'lodash'; import { addMetaFields, cleanSchemas, getAbstractCombinedSchemas, } from '../../../schemas'; import SingleValue from '../../../schemas/core/SingleValue.json'; import { SchemaMap, SchemaStub, SchemaStubMap } from '../../../schemas/types'; const Customer = { name: 'Customer', label: 'Customer', fields: [ { fieldname: 'name', label: 'Name', fieldtype: 'Data', required: true, }, { fieldname: 'email', label: 'Email', fieldtype: 'Data', placeholder: 'john@thoe.com', }, { fieldname: 'phone', label: 'Phone', fieldtype: 'Data', placeholder: '9999999999', }, ], quickEditFields: ['email'], keywordFields: ['name'], }; const SalesInvoiceItem = { name: 'SalesInvoiceItem', label: 'Sales Invoice Item', isChild: true, fields: [ { fieldname: 'item', label: 'Item', fieldtype: 'Data', required: true, }, { fieldname: 'quantity', label: 'Quantity', fieldtype: 'Float', required: true, default: 1, }, { fieldname: 'rate', label: 'Rate', fieldtype: 'Float', required: true, }, { fieldname: 'amount', label: 'Amount', fieldtype: 'Float', readOnly: true, }, ], tableFields: ['item', 'quantity', 'rate', 'amount'], }; const SalesInvoice = { name: 'SalesInvoice', label: 'Sales Invoice', isSingle: false, isChild: false, isSubmittable: true, keywordFields: ['name', 'customer'], fields: [ { label: 'Invoice No', fieldname: 'name', fieldtype: 'Data', required: true, readOnly: true, }, { fieldname: 'date', label: 'Date', fieldtype: 'Date', }, { fieldname: 'customer', label: 'Customer', fieldtype: 'Link', target: 'Customer', required: true, }, { fieldname: 'account', label: 'Account', fieldtype: 'Data', required: true, }, { fieldname: 'items', label: 'Items', fieldtype: 'Table', target: 'SalesInvoiceItem', required: true, }, { fieldname: 'grandTotal', label: 'Grand Total', fieldtype: 'Currency', readOnly: true, }, ], }; const SystemSettings = { name: 'SystemSettings', label: 'System Settings', isSingle: true, isChild: false, fields: [ { fieldname: 'dateFormat', label: 'Date Format', fieldtype: 'Select', options: [ { label: '23/03/2022', value: 'dd/MM/yyyy', }, { label: '03/23/2022', value: 'MM/dd/yyyy', }, ], default: 'dd/MM/yyyy', required: true, }, { fieldname: 'locale', label: 'Locale', fieldtype: 'Data', default: 'en-IN', }, ], quickEditFields: ['locale', 'dateFormat'], keywordFields: [], }; export function getBuiltTestSchemaMap(): SchemaMap { const testSchemaMap: SchemaStubMap = { SingleValue: SingleValue as SchemaStub, Customer: Customer as SchemaStub, SalesInvoice: SalesInvoice as SchemaStub, SalesInvoiceItem: SalesInvoiceItem as SchemaStub, SystemSettings: SystemSettings as SchemaStub, }; const schemaMapClone = cloneDeep(testSchemaMap); const abstractCombined = getAbstractCombinedSchemas(schemaMapClone); const cleanedSchemas = cleanSchemas(abstractCombined); return addMetaFields(cleanedSchemas); } export function getBaseMeta() { return { createdBy: 'Administrator', modifiedBy: 'Administrator', created: new Date().toISOString(), modified: new Date().toISOString(), }; } export async function assertThrows( func: () => Promise<unknown>, message?: string ) { let threw = true; try { await func(); threw = false; } catch { } finally { if (!threw) { throw new assert.AssertionError({ message: `Missing expected exception${message ? `: ${message}` : ''}`, }); } } } export async function assertDoesNotThrow( func: () => Promise<unknown>, message?: string ) { try { await func(); } catch (err) { throw new assert.AssertionError({ message: `Got unwanted exception${ message ? `: ${message}` : '' }\nError: ${(err as Error).message}\n${(err as Error).stack ?? ''}`, }); } } export type BaseMetaKey = 'created' | 'modified' | 'createdBy' | 'modifiedBy';
2302_79757062/books
backend/database/tests/helpers.ts
TypeScript
agpl-3.0
4,534
import type { Field, FieldType, RawValue } from '../../schemas/types'; import type DatabaseCore from './core'; import type { DatabaseManager } from './manager'; export interface GetQueryBuilderOptions { offset?: number; limit?: number; groupBy?: string | string[]; orderBy?: string | string[]; order?: 'desc' | 'asc'; } export type ColumnDiff = { added: Field[]; removed: string[] }; export type FieldValueMap = Record< string, RawValue | undefined | FieldValueMap[] >; export type AlterConfig = { schemaName: string; diff: ColumnDiff; newForeignKeys: Field[]; }; export type NonExtantConfig = { schemaName: string; nonExtant: { fieldname: string; value: RawValue; }[]; }; export type UpdateSinglesConfig = { update: string[]; updateNonExtant: NonExtantConfig[]; }; export type MigrationConfig = { pre?: () => Promise<void> | void; post?: () => Promise<void> | void; }; export interface Patch { name: string; version: string; patch: { execute: (dm: DatabaseManager) => Promise<void>; beforeMigrate?: boolean; }; priority?: number; } export type KnexColumnType = | 'text' | 'integer' | 'float' | 'boolean' | 'date' | 'datetime' | 'time' | 'binary'; // Returned by pragma table_info export interface SqliteTableInfo { pk: number; cid: number; name: string; type: string; notnull: number; // 0 | 1 dflt_value: string | null; } export type BespokeFunction = ( db: DatabaseCore, ...args: unknown[] ) => Promise<unknown>; export type SingleValue<T> = { fieldname: string; parent: string; value: T; }[]; export type RawCustomField = { parent: string; label: string; fieldname: string; fieldtype: FieldType; isRequired?: boolean; section?: string; tab?: string; options?: string; target?: string; references?: string; default?: string; };
2302_79757062/books
backend/database/types.ts
TypeScript
agpl-3.0
1,863
import { constants } from 'fs'; import fs from 'fs/promises'; import { DatabaseMethod } from 'utils/db/types'; import { CUSTOM_EVENTS } from 'utils/messages'; import { KnexColumnType } from './database/types'; export const sqliteTypeMap: Record<string, KnexColumnType> = { AutoComplete: 'text', Currency: 'text', Int: 'integer', Float: 'float', Percent: 'float', Check: 'boolean', Code: 'text', Date: 'date', Datetime: 'datetime', Time: 'time', Text: 'text', Data: 'text', Link: 'text', DynamicLink: 'text', Password: 'text', Select: 'text', Attachment: 'text', AttachImage: 'text', Color: 'text', }; export const SYSTEM = '__SYSTEM__'; export const validTypes = Object.keys(sqliteTypeMap); export function getDefaultMetaFieldValueMap() { const now = new Date().toISOString(); return { createdBy: SYSTEM, modifiedBy: SYSTEM, created: now, modified: now, }; } export const databaseMethodSet: Set<DatabaseMethod> = new Set([ 'insert', 'get', 'getAll', 'getSingleValues', 'rename', 'update', 'delete', 'deleteAll', 'close', 'exists', ]); export function emitMainProcessError( error: unknown, more?: Record<string, unknown> ) { ( process.emit as ( event: string, error: unknown, more?: Record<string, unknown> ) => void )(CUSTOM_EVENTS.MAIN_PROCESS_ERROR, error, more); } export async function checkFileAccess(filePath: string, mode?: number) { mode ??= constants.W_OK; return await fs .access(filePath, mode) .then(() => true) .catch(() => false); } export async function unlinkIfExists(filePath: unknown) { if (!filePath || typeof filePath !== 'string') { return false; } const exists = await checkFileAccess(filePath); if (exists) { await fs.unlink(filePath); return true; } return false; }
2302_79757062/books
backend/helpers.ts
TypeScript
agpl-3.0
1,852
import { ModelNameEnum } from '../../models/types'; import { DatabaseManager } from '../database/manager'; import { getDefaultMetaFieldValueMap } from '../helpers'; const defaultUOMs = [ { name: `Unit`, isWhole: true, }, { name: `Kg`, isWhole: false, }, { name: `Gram`, isWhole: false, }, { name: `Meter`, isWhole: false, }, { name: `Hour`, isWhole: false, }, { name: `Day`, isWhole: false, }, ]; async function execute(dm: DatabaseManager) { for (const uom of defaultUOMs) { const defaults = getDefaultMetaFieldValueMap(); await dm.db?.insert(ModelNameEnum.UOM, { ...uom, ...defaults }); } } export default { execute };
2302_79757062/books
backend/patches/addUOMs.ts
TypeScript
agpl-3.0
708
import { getDefaultMetaFieldValueMap } from '../../backend/helpers'; import { DatabaseManager } from '../database/manager'; async function execute(dm: DatabaseManager) { const s = (await dm.db?.getAll('SingleValue', { fields: ['value'], filters: { fieldname: 'setupComplete' }, })) as { value: string }[]; if (!Number(s?.[0]?.value ?? '0')) { return; } const names: Record<string, string> = { StockMovement: 'SMOV-', PurchaseReceipt: 'PREC-', Shipment: 'SHPM-', }; for (const referenceType in names) { const name = names[referenceType]; await createNumberSeries(name, referenceType, dm); } } async function createNumberSeries( name: string, referenceType: string, dm: DatabaseManager ) { const exists = await dm.db?.exists('NumberSeries', name); if (exists) { return; } await dm.db?.insert('NumberSeries', { name, start: 1001, padZeros: 4, current: 0, referenceType, ...getDefaultMetaFieldValueMap(), }); } export default { execute, beforeMigrate: true };
2302_79757062/books
backend/patches/createInventoryNumberSeries.ts
TypeScript
agpl-3.0
1,055
import { ModelNameEnum } from '../../models/types'; import { DatabaseManager } from '../database/manager'; const FIELDNAME = 'roundOffAccount'; async function execute(dm: DatabaseManager) { const accounts = await dm.db!.getSingleValues(FIELDNAME); if (!accounts.length) { await testAndSetRoundOffAccount(dm); } await dm.db!.delete(ModelNameEnum.AccountingSettings, FIELDNAME); let isSet = false; for (const { parent, value } of accounts) { if (parent !== ModelNameEnum.AccountingSettings) { continue; } isSet = await setRoundOffAccountIfExists(value as string, dm); if (isSet) { break; } } if (!isSet) { await testAndSetRoundOffAccount(dm); } } async function testAndSetRoundOffAccount(dm: DatabaseManager) { const isSet = await setRoundOffAccountIfExists('Round Off', dm); if (!isSet) { await setRoundOffAccountIfExists('Rounded Off', dm); } return; } async function setRoundOffAccountIfExists( roundOffAccount: string, dm: DatabaseManager ) { const exists = await dm.db!.exists(ModelNameEnum.Account, roundOffAccount); if (!exists) { return false; } await dm.db!.insert(ModelNameEnum.AccountingSettings, { roundOffAccount, }); return true; } export default { execute, beforeMigrate: true };
2302_79757062/books
backend/patches/fixRoundOffAccount.ts
TypeScript
agpl-3.0
1,298
import { Patch } from '../database/types'; import addUOMs from './addUOMs'; import createInventoryNumberSeries from './createInventoryNumberSeries'; import fixRoundOffAccount from './fixRoundOffAccount'; import testPatch from './testPatch'; import updateSchemas from './updateSchemas'; import setPaymentReferenceType from './setPaymentReferenceType'; import fixLedgerDateTime from './v0_21_0/fixLedgerDateTime'; export default [ { name: 'testPatch', version: '0.5.0-beta.0', patch: testPatch }, { name: 'updateSchemas', version: '0.5.0-beta.0', patch: updateSchemas, priority: 100, }, { name: 'addUOMs', version: '0.6.0-beta.0', patch: addUOMs, }, { name: 'fixRoundOffAccount', version: '0.6.3-beta.0', patch: fixRoundOffAccount, }, { name: 'createInventoryNumberSeries', version: '0.6.6-beta.0', patch: createInventoryNumberSeries, }, { name: 'setPaymentReferenceType', version: '0.20.1', patch: setPaymentReferenceType, }, { name: 'fixLedgerDateTime', version: '0.21.2', patch: fixLedgerDateTime, }, ] as Patch[];
2302_79757062/books
backend/patches/index.ts
TypeScript
agpl-3.0
1,119
import { DatabaseManager } from '../database/manager'; async function execute(dm: DatabaseManager) { await dm.db!.knex!('Payment') .where({ referenceType: null, paymentType: 'Pay' }) .update({ referenceType: 'PurchaseInvoice' }); await dm.db!.knex!('Payment') .where({ referenceType: null, paymentType: 'Receive' }) .update({ referenceType: 'SalesInvoice' }); } export default { execute, beforeMigrate: true };
2302_79757062/books
backend/patches/setPaymentReferenceType.ts
TypeScript
agpl-3.0
433
import { DatabaseManager } from '../database/manager'; // eslint-disable-next-line @typescript-eslint/no-unused-vars async function execute(dm: DatabaseManager) { /** * Execute function will receive the DatabaseManager which is to be used * to apply database patches. */ } export default { execute, beforeMigrate: true };
2302_79757062/books
backend/patches/testPatch.ts
TypeScript
agpl-3.0
335
import fs from 'fs/promises'; import { RawValueMap } from 'fyo/core/types'; import { Knex } from 'knex'; import path from 'path'; import { changeKeys, deleteKeys, getIsNullOrUndef, invertMap } from 'utils'; import { getCountryCodeFromCountry } from 'utils/misc'; import { Version } from 'utils/version'; import { ModelNameEnum } from '../../models/types'; import { FieldTypeEnum, Schema, SchemaMap } from '../../schemas/types'; import { DatabaseManager } from '../database/manager'; const ignoreColumns = ['keywords']; const columnMap = { creation: 'created', owner: 'createdBy' }; const childTableColumnMap = { parenttype: 'parentSchemaName', parentfield: 'parentFieldname', }; const defaultNumberSeriesMap = { [ModelNameEnum.Payment]: 'PAY-', [ModelNameEnum.JournalEntry]: 'JV-', [ModelNameEnum.SalesInvoice]: 'SINV-', [ModelNameEnum.PurchaseInvoice]: 'PINV-', [ModelNameEnum.SalesQuote]: 'SQUOT-', } as Record<ModelNameEnum, string>; async function execute(dm: DatabaseManager) { if (dm.db?.dbPath === ':memory:') { return; } const sourceKnex = dm.db!.knex!; const version = ( (await sourceKnex('SingleValue') .select('value') .where({ fieldname: 'version' })) as { value: string }[] )?.[0]?.value; /** * Versions after this should have the new schemas */ if (version && Version.gt(version, '0.4.3-beta.0')) { return; } /** * Initialize a different db to copy all the updated * data into. */ const countryCode = await getCountryCode(sourceKnex); const destDm = await getDestinationDM(dm.db!.dbPath, countryCode); /** * Copy data from all the relevant tables * the other tables will be empty cause unused. */ try { await copyData(sourceKnex, destDm); } catch (err) { const destPath = destDm.db!.dbPath; await destDm.db!.close(); await fs.unlink(destPath); throw err; } /** * Version will update when migration completes, this * is set to prevent this patch from running again. */ await destDm.db!.update(ModelNameEnum.SystemSettings, { version: '0.5.0-beta.0', }); /** * Replace the database with the new one. */ await replaceDatabaseCore(dm, destDm); } async function replaceDatabaseCore( dm: DatabaseManager, destDm: DatabaseManager ) { const newDbPath = destDm.db!.dbPath; // new db with new schema const oldDbPath = dm.db!.dbPath; // old db to be replaced await dm.db!.close(); await destDm.db!.close(); await fs.unlink(oldDbPath); await fs.rename(newDbPath, oldDbPath); await dm._connect(oldDbPath); } async function copyData(sourceKnex: Knex, destDm: DatabaseManager) { const destKnex = destDm.db!.knex!; const schemaMap = destDm.getSchemaMap(); await destKnex.raw('PRAGMA foreign_keys=OFF'); await copySingleValues(sourceKnex, destKnex, schemaMap); await copyParty(sourceKnex, destKnex, schemaMap[ModelNameEnum.Party]!); await copyItem(sourceKnex, destKnex, schemaMap[ModelNameEnum.Item]!); await copyChildTables(sourceKnex, destKnex, schemaMap); await copyOtherTables(sourceKnex, destKnex, schemaMap); await copyTransactionalTables(sourceKnex, destKnex, schemaMap); await copyLedgerEntries( sourceKnex, destKnex, schemaMap[ModelNameEnum.AccountingLedgerEntry]! ); await copyNumberSeries( sourceKnex, destKnex, schemaMap[ModelNameEnum.NumberSeries]! ); await destKnex.raw('PRAGMA foreign_keys=ON'); } async function copyNumberSeries( sourceKnex: Knex, destKnex: Knex, schema: Schema ) { const values = (await sourceKnex( ModelNameEnum.NumberSeries )) as RawValueMap[]; const refMap = invertMap(defaultNumberSeriesMap); for (const value of values) { if (value.referenceType) { continue; } const name = value.name as string; const referenceType = refMap[name]; if (!referenceType) { delete value.name; continue; } const indices = (await sourceKnex.raw( ` select cast(substr(name, ??) as int) as idx from ?? order by idx desc limit 1`, [name.length + 1, referenceType] )) as { idx: number }[]; value.start = 1001; value.current = indices[0]?.idx ?? value.current ?? value.start; value.referenceType = referenceType; } await copyValues( destKnex, ModelNameEnum.NumberSeries, values.filter((v) => v.name), [], {}, schema ); } async function copyLedgerEntries( sourceKnex: Knex, destKnex: Knex, schema: Schema ) { const values = (await sourceKnex( ModelNameEnum.AccountingLedgerEntry )) as RawValueMap[]; await copyValues( destKnex, ModelNameEnum.AccountingLedgerEntry, values, ['description', 'againstAccount', 'balance'], {}, schema ); } async function copyOtherTables( sourceKnex: Knex, destKnex: Knex, schemaMap: SchemaMap ) { const schemaNames = [ ModelNameEnum.Account, ModelNameEnum.Currency, ModelNameEnum.Address, ModelNameEnum.Color, ModelNameEnum.Tax, ModelNameEnum.PatchRun, ]; for (const sn of schemaNames) { const values = (await sourceKnex(sn)) as RawValueMap[]; await copyValues(destKnex, sn, values, [], {}, schemaMap[sn]); } } async function copyTransactionalTables( sourceKnex: Knex, destKnex: Knex, schemaMap: SchemaMap ) { const schemaNames = [ ModelNameEnum.JournalEntry, ModelNameEnum.Payment, ModelNameEnum.SalesInvoice, ModelNameEnum.PurchaseInvoice, ModelNameEnum.SalesQuote, ]; for (const sn of schemaNames) { const values = (await sourceKnex(sn)) as RawValueMap[]; values.forEach((v) => { if (!v.submitted) { v.submitted = 0; } if (!v.cancelled) { v.cancelled = 0; } if (!v.numberSeries) { v.numberSeries = defaultNumberSeriesMap[sn]; } if (v.customer) { v.party = v.customer; } if (v.supplier) { v.party = v.supplier; } }); await copyValues( destKnex, sn, values, [], childTableColumnMap, schemaMap[sn] ); } } async function copyChildTables( sourceKnex: Knex, destKnex: Knex, schemaMap: SchemaMap ) { const childSchemaNames = Object.keys(schemaMap).filter( (sn) => schemaMap[sn]?.isChild ); for (const sn of childSchemaNames) { const values = (await sourceKnex(sn)) as RawValueMap[]; await copyValues( destKnex, sn, values, [], childTableColumnMap, schemaMap[sn] ); } } async function copyItem(sourceKnex: Knex, destKnex: Knex, schema: Schema) { const values = (await sourceKnex(ModelNameEnum.Item)) as RawValueMap[]; values.forEach((value) => { value.for = 'Both'; }); await copyValues(destKnex, ModelNameEnum.Item, values, [], {}, schema); } async function copyParty(sourceKnex: Knex, destKnex: Knex, schema: Schema) { const values = (await sourceKnex(ModelNameEnum.Party)) as RawValueMap[]; values.forEach((value) => { // customer will be mapped onto role if (Number(value.supplier) === 1) { value.customer = 'Supplier'; } else { value.customer = 'Customer'; } }); await copyValues( destKnex, ModelNameEnum.Party, values, ['supplier', 'addressDisplay'], { customer: 'role' }, schema ); } async function copySingleValues( sourceKnex: Knex, destKnex: Knex, schemaMap: SchemaMap ) { const singleSchemaNames = Object.keys(schemaMap).filter( (k) => schemaMap[k]?.isSingle ); const singleValues = (await sourceKnex(ModelNameEnum.SingleValue).whereIn( 'parent', singleSchemaNames )) as RawValueMap[]; await copyValues(destKnex, ModelNameEnum.SingleValue, singleValues); } async function copyValues( destKnex: Knex, destTableName: string, values: RawValueMap[], keysToDelete: string[] = [], keyMap: Record<string, string> = {}, schema?: Schema ) { keysToDelete = [...keysToDelete, ...ignoreColumns]; keyMap = { ...keyMap, ...columnMap }; values = values.map((sv) => deleteKeys(sv, keysToDelete)); values = values.map((sv) => changeKeys(sv, keyMap)); if (schema) { values.forEach((v) => notNullify(v, schema)); } if (schema) { const newKeys = schema?.fields.map((f) => f.fieldname); values.forEach((v) => deleteOldKeys(v, newKeys)); } await destKnex.batchInsert(destTableName, values, 100); } async function getDestinationDM(sourceDbPath: string, countryCode: string) { /** * This is where all the stuff from the old db will be copied. * That won't be altered cause schema update will cause data loss. */ const dir = path.parse(sourceDbPath).dir; const dbPath = path.join(dir, '__update_schemas_temp.db'); const dm = new DatabaseManager(); await dm._connect(dbPath, countryCode); await dm.db!.migrate(); await dm.db!.truncate(); return dm; } async function getCountryCode(knex: Knex) { /** * Need to account for schema changes, in 0.4.3-beta.0 */ const country = ( (await knex('SingleValue') .select('value') .where({ fieldname: 'country' })) as { value: string }[] )?.[0]?.value; if (!country) { return ''; } return getCountryCodeFromCountry(country); } function notNullify(map: RawValueMap, schema: Schema) { for (const field of schema.fields) { if (!field.required || !getIsNullOrUndef(map[field.fieldname])) { continue; } switch (field.fieldtype) { case FieldTypeEnum.Float: case FieldTypeEnum.Int: case FieldTypeEnum.Check: map[field.fieldname] = 0; break; case FieldTypeEnum.Currency: map[field.fieldname] = '0.00000000000'; break; case FieldTypeEnum.Table: continue; default: map[field.fieldname] = ''; } } } function deleteOldKeys(map: RawValueMap, newKeys: string[]) { for (const key of Object.keys(map)) { if (newKeys.includes(key)) { continue; } delete map[key]; } } export default { execute, beforeMigrate: true };
2302_79757062/books
backend/patches/updateSchemas.ts
TypeScript
agpl-3.0
10,046
import { DatabaseManager } from '../../database/manager'; /* eslint-disable */ async function execute(dm: DatabaseManager) { const sourceTables = [ "PurchaseInvoice", "SalesInvoice", "JournalEntry", "Payment", "StockMovement", "StockTransfer" ]; await dm.db!.knex!('AccountingLedgerEntry') .select('name', 'date', 'referenceName') .then((trx: Array<{name: string; date: Date; referenceName: string;}> ) => { trx.forEach(async entry => { sourceTables.forEach(async table => { await dm.db!.knex! .select('name','date') .from(table) .where({ name: entry['referenceName'] }) .then(async (resp: Array<{name: string; date: Date;}>) => { if (resp.length !== 0) { const dateTimeValue = new Date(resp[0]['date']); await dm.db!.knex!('AccountingLedgerEntry') .where({ name: entry['name'] }) .update({ date: dateTimeValue.toISOString() }); } }) }); }); }); } export default { execute, beforeMigrate: true }; /* eslint-enable */
2302_79757062/books
backend/patches/v0_21_0/fixLedgerDateTime.ts
TypeScript
agpl-3.0
1,374
import { DateTime } from 'luxon'; // prettier-ignore export const partyPurchaseItemMap: Record<string, string[]> = { 'Janky Office Spaces': ['Office Rent', 'Office Cleaning'], "Josféña's 611s": ['611 Jeans - PCH', '611 Jeans - SHR'], 'Lankness Feet Fomenters': ['Bominga Shoes', 'Jade Slippers'], 'The Overclothes Company': ['Jacket - RAW', 'Cryo Gloves', 'Cool Cloth'], 'Adani Electricity Mumbai Limited': ['Electricity'], 'Only Fulls': ['Full Sleeve - BLK', 'Full Sleeve - COL'], 'Just Epaulettes': ['Epaulettes - 4POR'], 'Le Socials': ['Social Ads'], 'Maxwell': ['Marketing - Video'], }; export const purchaseItemPartyMap: Record<string, string> = Object.keys( partyPurchaseItemMap ).reduce((acc, party) => { for (const item of partyPurchaseItemMap[party]) { acc[item] = party; } return acc; }, {} as Record<string, string>); export const flow = [ 0.35, // Jan 0.25, // Feb 0.15, // Mar 0.15, // Apr 0.25, // May 0.05, // Jun 0.05, // Jul 0.15, // Aug 0.25, // Sep 0.35, // Oct 0.45, // Nov 0.55, // Dec ]; export function getFlowConstant(months: number) { // Jan to December const d = DateTime.now().minus({ months }); return flow[d.month - 1]; } export function getRandomDates(count: number, months: number): Date[] { /** * Returns `count` number of dates for a month, `months` back from the * current date. */ let endDate = DateTime.now(); if (months !== 0) { const back = endDate.minus({ months }); endDate = DateTime.local(back.year, back.month, back.daysInMonth); } const dates: Date[] = []; for (let i = 0; i < count; i++) { const day = Math.ceil(endDate.day * Math.random()); const date = DateTime.local(endDate.year, endDate.month, day); dates.push(date.toJSDate()); } return dates; }
2302_79757062/books
dummy/helpers.ts
TypeScript
agpl-3.0
1,810
import { Fyo, t } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { range, sample } from 'lodash'; import { DateTime } from 'luxon'; import { Invoice } from 'models/baseModels/Invoice/Invoice'; import { Payment } from 'models/baseModels/Payment/Payment'; import { PurchaseInvoice } from 'models/baseModels/PurchaseInvoice/PurchaseInvoice'; import { SalesInvoice } from 'models/baseModels/SalesInvoice/SalesInvoice'; import { ModelNameEnum } from 'models/types'; import setupInstance from 'src/setup/setupInstance'; import { getMapFromList, safeParseInt } from 'utils'; import { getFiscalYear } from 'utils/misc'; import { flow, getFlowConstant, getRandomDates, purchaseItemPartyMap, } from './helpers'; import items from './items.json'; import logo from './logo'; import parties from './parties.json'; type Notifier = (stage: string, percent: number) => void; export async function setupDummyInstance( dbPath: string, fyo: Fyo, years = 1, baseCount = 1000, notifier?: Notifier ) { await fyo.purgeCache(); notifier?.(fyo.t`Setting Up Instance`, -1); const options = { logo: null, companyName: "Flo's Clothes", country: 'India', fullname: 'Lin Florentine', email: 'lin@flosclothes.com', bankName: 'Supreme Bank', currency: 'INR', fiscalYearStart: getFiscalYear('04-01', true)!.toISOString(), fiscalYearEnd: getFiscalYear('04-01', false)!.toISOString(), chartOfAccounts: 'India - Chart of Accounts', }; await setupInstance(dbPath, options, fyo); fyo.store.skipTelemetryLogging = true; years = Math.floor(years); notifier?.(fyo.t`Creating Items and Parties`, -1); await generateStaticEntries(fyo); await generateDynamicEntries(fyo, years, baseCount, notifier); await setOtherSettings(fyo); const instanceId = (await fyo.getValue( ModelNameEnum.SystemSettings, 'instanceId' )) as string; await fyo.singles.SystemSettings?.setAndSync('hideGetStarted', true); fyo.store.skipTelemetryLogging = false; return { companyName: options.companyName, instanceId }; } async function setOtherSettings(fyo: Fyo) { const doc = await fyo.doc.getDoc(ModelNameEnum.PrintSettings); const address = fyo.doc.getNewDoc(ModelNameEnum.Address); await address.setAndSync({ addressLine1: '1st Column, Fitzgerald Bridge', city: 'Pune', state: 'Maharashtra', pos: 'Maharashtra', postalCode: '411001', country: 'India', }); await doc.setAndSync({ color: '#F687B3', template: 'Business', displayLogo: true, phone: '+91 8983-000418', logo, address: address.name, }); const acc = await fyo.doc.getDoc(ModelNameEnum.AccountingSettings); await acc.setAndSync({ gstin: '27LIN180000A1Z5', }); } /** * warning: long functions ahead! */ async function generateDynamicEntries( fyo: Fyo, years: number, baseCount: number, notifier?: Notifier ) { const salesInvoices = await getSalesInvoices(fyo, years, baseCount, notifier); notifier?.(fyo.t`Creating Purchase Invoices`, -1); const purchaseInvoices = await getPurchaseInvoices(fyo, years, salesInvoices); notifier?.(fyo.t`Creating Journal Entries`, -1); const journalEntries = await getJournalEntries(fyo, salesInvoices); await syncAndSubmit(journalEntries, notifier); const invoices = ([salesInvoices, purchaseInvoices].flat() as Invoice[]).sort( (a, b) => +(a.date as Date) - +(b.date as Date) ); await syncAndSubmit(invoices, notifier); const payments = await getPayments(fyo, invoices); await syncAndSubmit(payments, notifier); } async function getJournalEntries(fyo: Fyo, salesInvoices: SalesInvoice[]) { const entries = []; const amount = salesInvoices .map((i) => i.items!) .flat() .reduce((a, b) => a.add(b.amount!), fyo.pesa(0)) .percent(75) .clip(0); const lastInv = salesInvoices.sort((a, b) => +a.date! - +b.date!).at(-1)! .date!; const date = DateTime.fromJSDate(lastInv).minus({ months: 6 }).toJSDate(); // Bank Entry let doc = fyo.doc.getNewDoc( ModelNameEnum.JournalEntry, { date, entryType: 'Bank Entry', }, false ); await doc.append('accounts', { account: 'Supreme Bank', debit: amount, credit: fyo.pesa(0), }); await doc.append('accounts', { account: 'Secured Loans', credit: amount, debit: fyo.pesa(0), }); entries.push(doc); // Cash Entry doc = fyo.doc.getNewDoc( ModelNameEnum.JournalEntry, { date, entryType: 'Cash Entry', }, false ); await doc.append('accounts', { account: 'Cash', debit: amount.percent(30), credit: fyo.pesa(0), }); await doc.append('accounts', { account: 'Supreme Bank', credit: amount.percent(30), debit: fyo.pesa(0), }); entries.push(doc); return entries; } async function getPayments(fyo: Fyo, invoices: Invoice[]) { const payments = []; for (const invoice of invoices) { // Defaulters if (invoice.isSales && Math.random() < 0.007) { continue; } const doc = fyo.doc.getNewDoc(ModelNameEnum.Payment, {}, false) as Payment; doc.party = invoice.party as string; doc.paymentType = invoice.isSales ? 'Receive' : 'Pay'; doc.paymentMethod = 'Cash'; doc.date = DateTime.fromJSDate(invoice.date as Date) .plus({ hours: 1 }) .toJSDate(); if (doc.paymentType === 'Receive') { doc.account = 'Debtors'; doc.paymentAccount = 'Cash'; } else { doc.account = 'Cash'; doc.paymentAccount = 'Creditors'; } doc.amount = invoice.outstandingAmount; // Discount if (invoice.isSales && Math.random() < 0.05) { await doc.set('writeOff', invoice.outstandingAmount?.percent(15)); } doc.push('for', { referenceType: invoice.schemaName, referenceName: invoice.name, amount: invoice.outstandingAmount, }); if (doc.amount!.isZero()) { continue; } payments.push(doc); } return payments; } function getSalesInvoiceDates(years: number, baseCount: number): Date[] { const dates: Date[] = []; for (const months of range(0, years * 12)) { const flow = getFlowConstant(months); const count = Math.ceil(flow * baseCount * (Math.random() * 0.25 + 0.75)); dates.push(...getRandomDates(count, months)); } return dates; } async function getSalesInvoices( fyo: Fyo, years: number, baseCount: number, notifier?: Notifier ) { const invoices: SalesInvoice[] = []; const salesItems = items.filter((i) => i.for !== 'Purchases'); const customers = parties.filter((i) => i.role !== 'Supplier'); /** * Get certain number of entries for each month of the count * of years. */ const dates = getSalesInvoiceDates(years, baseCount); /** * For each date create a Sales Invoice. */ for (let d = 0; d < dates.length; d++) { const date = dates[d]; notifier?.( `Creating Sales Invoices, ${d} out of ${dates.length}`, safeParseInt(d) / dates.length ); const customer = sample(customers); const doc = fyo.doc.getNewDoc( ModelNameEnum.SalesInvoice, { date, }, false ) as SalesInvoice; await doc.set('party', customer!.name); if (!doc.account) { doc.account = 'Debtors'; } /** * Add `numItems` number of items to the invoice. */ const numItems = Math.ceil(Math.random() * 5); for (let i = 0; i < numItems; i++) { const item = sample(salesItems); if ((doc.items ?? []).find((i) => i.item === item)) { continue; } let quantity = 1; /** * Increase quantity depending on the rate. */ if (item!.rate < 100 && Math.random() < 0.4) { quantity = Math.ceil(Math.random() * 10); } else if (item!.rate < 1000 && Math.random() < 0.2) { quantity = Math.ceil(Math.random() * 4); } else if (Math.random() < 0.01) { quantity = Math.ceil(Math.random() * 3); } let fc = flow[date.getMonth()]; if (baseCount < 500) { fc += 1; } const rate = fyo.pesa(item!.rate * (fc + 1)).clip(0); await doc.append('items', {}); await doc.items!.at(-1)!.set({ item: item!.name, rate, quantity, account: item!.incomeAccount, amount: rate.mul(quantity), tax: item!.tax, description: item!.description, hsnCode: item!.hsnCode, }); } invoices.push(doc); } return invoices; } async function getPurchaseInvoices( fyo: Fyo, years: number, salesInvoices: SalesInvoice[] ): Promise<PurchaseInvoice[]> { return [ await getSalesPurchaseInvoices(fyo, salesInvoices), await getNonSalesPurchaseInvoices(fyo, years), ].flat(); } async function getSalesPurchaseInvoices( fyo: Fyo, salesInvoices: SalesInvoice[] ): Promise<PurchaseInvoice[]> { const invoices = [] as PurchaseInvoice[]; /** * Group all sales invoices by their YYYY-MM. */ const dateGrouped = salesInvoices .map((si) => { const date = DateTime.fromJSDate(si.date as Date); const key = `${date.year}-${String(date.month).padStart(2, '0')}`; return { key, si }; }) .reduce((acc, item) => { acc[item.key] ??= []; acc[item.key].push(item.si); return acc; }, {} as Record<string, SalesInvoice[]>); /** * Sort the YYYY-MM keys in ascending order. */ const dates = Object.keys(dateGrouped) .map((k) => ({ key: k, date: new Date(k) })) .sort((a, b) => +a.date - +b.date); const purchaseQty: Record<string, number> = {}; /** * For each date create a set of Purchase Invoices. */ for (const { key, date } of dates) { /** * Group items by name to get the total quantity used in a month. */ const itemGrouped = dateGrouped[key].reduce((acc, si) => { for (const item of si.items!) { if (item.item === 'Dry-Cleaning') { continue; } acc[item.item as string] ??= 0; acc[item.item as string] += item.quantity as number; } return acc; }, {} as Record<string, number>); /** * Set order quantity for the first of the month. */ Object.keys(itemGrouped).forEach((name) => { const quantity = itemGrouped[name]; purchaseQty[name] ??= 0; let prevQty = purchaseQty[name]; if (prevQty <= quantity) { prevQty = quantity - prevQty; } purchaseQty[name] = Math.ceil(prevQty / 10) * 10; }); const supplierGrouped = Object.keys(itemGrouped).reduce((acc, item) => { const supplier = purchaseItemPartyMap[item]; acc[supplier] ??= []; acc[supplier].push(item); return acc; }, {} as Record<string, string[]>); /** * For each supplier create a Purchase Invoice */ for (const supplier in supplierGrouped) { const doc = fyo.doc.getNewDoc( ModelNameEnum.PurchaseInvoice, { date, }, false ) as PurchaseInvoice; await doc.set('party', supplier); if (!doc.account) { doc.account = 'Creditors'; } /** * For each item create a row */ for (const item of supplierGrouped[supplier]) { await doc.append('items', {}); const quantity = purchaseQty[item]; await doc.items!.at(-1)!.set({ item, quantity }); } invoices.push(doc); } } return invoices; } async function getNonSalesPurchaseInvoices( fyo: Fyo, years: number ): Promise<PurchaseInvoice[]> { const purchaseItems = items.filter((i) => i.for !== 'Sales'); const itemMap = getMapFromList(purchaseItems, 'name'); const periodic: Record<string, number> = { 'Marketing - Video': 2, 'Social Ads': 1, Electricity: 1, 'Office Cleaning': 1, 'Office Rent': 1, }; const invoices: SalesInvoice[] = []; for (const months of range(0, years * 12)) { /** * All purchases on the first of the month. */ const temp = DateTime.now().minus({ months }); const date = DateTime.local(temp.year, temp.month, 1).toJSDate(); for (const name in periodic) { if (months % periodic[name] !== 0) { continue; } const doc = fyo.doc.getNewDoc( ModelNameEnum.PurchaseInvoice, { date, }, false ) as PurchaseInvoice; const party = purchaseItemPartyMap[name]; await doc.set('party', party); if (!doc.account) { doc.account = 'Creditors'; } await doc.append('items', {}); const row = doc.items!.at(-1)!; const item = itemMap[name]; let quantity = 1; let rate = item.rate; if (name === 'Social Ads') { quantity = Math.ceil(Math.random() * 200); } else if (name !== 'Office Rent') { rate = rate * (Math.random() * 0.4 + 0.8); } await row.set({ item: item.name, quantity, rate: fyo.pesa(rate).clip(0), }); invoices.push(doc); } } return invoices; } async function generateStaticEntries(fyo: Fyo) { await generateItems(fyo); await generateParties(fyo); } async function generateItems(fyo: Fyo) { for (const item of items) { const doc = fyo.doc.getNewDoc('Item', item, false); await doc.sync(); } } async function generateParties(fyo: Fyo) { for (const party of parties) { const doc = fyo.doc.getNewDoc('Party', party, false); await doc.sync(); } } async function syncAndSubmit(docs: Doc[], notifier?: Notifier) { const nameMap: Record<string, string> = { [ModelNameEnum.PurchaseInvoice]: t`Invoices`, [ModelNameEnum.SalesInvoice]: t`Invoices`, [ModelNameEnum.Payment]: t`Payments`, [ModelNameEnum.JournalEntry]: t`Journal Entries`, }; const total = docs.length; for (let i = 0; i < docs.length; i++) { const doc = docs[i]; notifier?.( `Syncing ${nameMap[doc.schemaName]}, ${i} out of ${total}`, safeParseInt(i) / total ); await doc.sync(); await doc.submit(); } }
2302_79757062/books
dummy/index.ts
TypeScript
agpl-3.0
14,061
// App is tagged with a .mjs extension to allow import path from 'path'; import { fileURLToPath } from 'url'; /** * electron-builder doesn't look for the APPLE_TEAM_ID environment variable for some reason. * This workaround allows an environment variable to be added to the electron-builder.yml config * collection. See: https://github.com/electron-userland/electron-builder/issues/7812 */ const dirname = path.dirname(fileURLToPath(import.meta.url)); // const root = path.join(dirname, '..', '..'); const root = dirname; // redundant, but is meant to keep with the previous line const buildDirPath = path.join(root, 'dist_electron', 'build'); const packageDirPath = path.join(root, 'dist_electron', 'bundled'); const frappeBooksConfig = { productName: 'Frappe Books', appId: 'io.frappe.books', asarUnpack: '**/*.node', extraResources: [ { from: 'log_creds.txt', to: '../creds/log_creds.txt' }, { from: 'translations', to: '../translations' }, { from: 'templates', to: '../templates' }, ], files: '**', extends: null, directories: { output: packageDirPath, app: buildDirPath, }, mac: { type: 'distribution', category: 'public.app-category.finance', icon: 'build/icon.icns', notarize: { teamId: process.env.APPLE_TEAM_ID || '', }, hardenedRuntime: true, gatekeeperAssess: false, darkModeSupport: false, entitlements: 'build/entitlements.mac.plist', entitlementsInherit: 'build/entitlements.mac.plist', publish: ['github'], }, win: { publisherName: 'Frappe Technologies Pvt. Ltd.', signDlls: true, icon: 'build/icon.ico', publish: ['github'], target: ['nsis', 'portable'], }, nsis: { oneClick: false, perMachine: false, allowToChangeInstallationDirectory: true, installerIcon: 'build/installericon.ico', uninstallerIcon: 'build/uninstallericon.ico', publish: ['github'], }, linux: { icon: 'build/icons', category: 'Finance', publish: ['github'], target: ['deb', 'AppImage', 'rpm'], }, }; export default frappeBooksConfig;
2302_79757062/books
electron-builder-config.mjs
JavaScript
agpl-3.0
2,092
import { Fyo } from 'fyo'; import { AuthDemux } from 'fyo/demux/auth'; import { AuthDemuxBase } from 'utils/auth/types'; import { Creds } from 'utils/types'; import { AuthDemuxConstructor } from './types'; interface AuthConfig { serverURL: string; backend: string; port: number; } interface Session { user: string; token: string; } export class AuthHandler { #config: AuthConfig; #session: Session; fyo: Fyo; #demux: AuthDemuxBase; #creds?: Creds; constructor(fyo: Fyo, Demux?: AuthDemuxConstructor) { this.fyo = fyo; this.#config = { serverURL: '', backend: 'sqlite', port: 8000, }; this.#session = { user: '', token: '', }; if (Demux !== undefined) { this.#demux = new Demux(fyo.isElectron); } else { this.#demux = new AuthDemux(fyo.isElectron); } } set user(value: string) { this.#session.user = value; } get user(): string { return this.#session.user; } get session(): Readonly<Session> { return { ...this.#session }; } get config(): Readonly<AuthConfig> { return { ...this.#config }; } init() { return null; } async getCreds(): Promise<Creds> { if (!this.#creds) { this.#creds = await this.#demux.getCreds(); } return this.#creds; } }
2302_79757062/books
fyo/core/authHandler.ts
TypeScript
agpl-3.0
1,313
import { Fyo } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { isPesa } from 'fyo/utils'; import { ValueError } from 'fyo/utils/errors'; import { DateTime } from 'luxon'; import { Field, FieldTypeEnum, RawValue, TargetField } from 'schemas/types'; import { getIsNullOrUndef, safeParseFloat, safeParseInt } from 'utils'; import { DatabaseHandler } from './dbHandler'; import { Attachment, DocValue, DocValueMap, RawValueMap } from './types'; /** * # Converter * * Basically converts serializable RawValues from the db to DocValues used * by the frontend and vice versa. * * ## Value Conversion * It exposes two static methods: `toRawValue` and `toDocValue` that can be * used elsewhere given the fieldtype. * * ## Map Conversion * Two methods `toDocValueMap` and `toRawValueMap` are exposed but should be * used only from the `dbHandler`. */ export class Converter { db: DatabaseHandler; fyo: Fyo; constructor(db: DatabaseHandler, fyo: Fyo) { this.db = db; this.fyo = fyo; } toDocValueMap( schemaName: string, rawValueMap: RawValueMap | RawValueMap[] ): DocValueMap | DocValueMap[] { rawValueMap ??= {}; if (Array.isArray(rawValueMap)) { return rawValueMap.map((dv) => this.#toDocValueMap(schemaName, dv)); } else { return this.#toDocValueMap(schemaName, rawValueMap); } } toRawValueMap( schemaName: string, docValueMap: DocValueMap | DocValueMap[] ): RawValueMap | RawValueMap[] { docValueMap ??= {}; if (Array.isArray(docValueMap)) { return docValueMap.map((dv) => this.#toRawValueMap(schemaName, dv)); } else { return this.#toRawValueMap(schemaName, docValueMap); } } static toDocValue(value: RawValue, field: Field, fyo: Fyo): DocValue { switch (field.fieldtype) { case FieldTypeEnum.Currency: return toDocCurrency(value, field, fyo); case FieldTypeEnum.Date: return toDocDate(value, field); case FieldTypeEnum.Datetime: return toDocDate(value, field); case FieldTypeEnum.Int: return toDocInt(value, field); case FieldTypeEnum.Float: return toDocFloat(value, field); case FieldTypeEnum.Check: return toDocCheck(value, field); case FieldTypeEnum.Attachment: return toDocAttachment(value, field); default: return toDocString(value, field); } } static toRawValue(value: DocValue, field: Field, fyo: Fyo): RawValue { switch (field.fieldtype) { case FieldTypeEnum.Currency: return toRawCurrency(value, fyo, field); case FieldTypeEnum.Date: return toRawDate(value, field); case FieldTypeEnum.Datetime: return toRawDateTime(value, field); case FieldTypeEnum.Int: return toRawInt(value, field); case FieldTypeEnum.Float: return toRawFloat(value, field); case FieldTypeEnum.Check: return toRawCheck(value, field); case FieldTypeEnum.Link: return toRawLink(value, field); case FieldTypeEnum.Attachment: return toRawAttachment(value, field); default: return toRawString(value, field); } } #toDocValueMap(schemaName: string, rawValueMap: RawValueMap): DocValueMap { const fieldValueMap = this.db.fieldMap[schemaName]; const docValueMap: DocValueMap = {}; for (const fieldname in rawValueMap) { const field = fieldValueMap[fieldname]; const rawValue = rawValueMap[fieldname]; if (!field) { continue; } if (Array.isArray(rawValue)) { const parentSchemaName = (field as TargetField).target; docValueMap[fieldname] = rawValue.map((rv) => this.#toDocValueMap(parentSchemaName, rv) ); } else { docValueMap[fieldname] = Converter.toDocValue( rawValue, field, this.fyo ); } } return docValueMap; } #toRawValueMap(schemaName: string, docValueMap: DocValueMap): RawValueMap { const fieldValueMap = this.db.fieldMap[schemaName]; const rawValueMap: RawValueMap = {}; for (const fieldname in docValueMap) { const field = fieldValueMap[fieldname]; const docValue = docValueMap[fieldname]; if (Array.isArray(docValue)) { const parentSchemaName = (field as TargetField).target; rawValueMap[fieldname] = docValue.map((value) => { if (value instanceof Doc) { return this.#toRawValueMap(parentSchemaName, value.getValidDict()); } return this.#toRawValueMap(parentSchemaName, value); }); } else { rawValueMap[fieldname] = Converter.toRawValue( docValue, field, this.fyo ); } } return rawValueMap; } } function toDocString(value: RawValue, field: Field) { if (value === null) { return null; } if (value === undefined) { return null; } if (typeof value === 'string') { return value; } throwError(value, field, 'doc'); } function toDocDate(value: RawValue, field: Field) { if ((value as unknown) instanceof Date) { return value; } if (value === null || value === '') { return null; } if (typeof value !== 'string') { throwError(value, field, 'doc'); } const date = DateTime.fromISO(value).toJSDate(); if (date.toString() === 'Invalid Date') { throwError(value, field, 'doc'); } return date; } function toDocCurrency(value: RawValue, field: Field, fyo: Fyo) { if (isPesa(value)) { return value; } if (value === '') { return fyo.pesa(0); } if (typeof value === 'string') { return fyo.pesa(value); } if (typeof value === 'number') { return fyo.pesa(value); } if (typeof value === 'boolean') { return fyo.pesa(Number(value)); } if (value === null) { return fyo.pesa(0); } throwError(value, field, 'doc'); } function toDocInt(value: RawValue, field: Field): number { if (value === '') { return 0; } if (typeof value === 'string') { value = safeParseInt(value); } return toDocFloat(value, field); } function toDocFloat(value: RawValue, field: Field): number { if (value === '') { return 0; } if (typeof value === 'boolean') { return Number(value); } if (typeof value === 'string') { value = safeParseFloat(value); } if (value === null) { value = 0; } if (typeof value === 'number' && !Number.isNaN(value)) { return value; } throwError(value, field, 'doc'); } function toDocCheck(value: RawValue, field: Field): boolean { if (typeof value === 'boolean') { return value; } if (typeof value === 'string') { return !!safeParseFloat(value); } if (typeof value === 'number') { return Boolean(value); } throwError(value, field, 'doc'); } function toDocAttachment(value: RawValue, field: Field): null | Attachment { if (!value) { return null; } if (typeof value !== 'string') { throwError(value, field, 'doc'); } try { return (JSON.parse(value) as Attachment) || null; } catch { throwError(value, field, 'doc'); } } function toRawCurrency(value: DocValue, fyo: Fyo, field: Field): string { if (isPesa(value)) { return value.store; } if (getIsNullOrUndef(value)) { return fyo.pesa(0).store; } if (typeof value === 'number') { return fyo.pesa(value).store; } if (typeof value === 'string') { return fyo.pesa(value).store; } throwError(value, field, 'raw'); } function toRawInt(value: DocValue, field: Field): number { if (typeof value === 'string') { return safeParseInt(value); } if (getIsNullOrUndef(value)) { return 0; } if (typeof value === 'number') { return Math.floor(value); } throwError(value, field, 'raw'); } function toRawFloat(value: DocValue, field: Field): number { if (typeof value === 'string') { return safeParseFloat(value); } if (getIsNullOrUndef(value)) { return 0; } if (typeof value === 'number') { return value; } throwError(value, field, 'raw'); } function toRawDate(value: DocValue, field: Field): string | null { if (value === null) { return null; } if (typeof value === 'string' || typeof value === 'number') { value = new Date(value); } if (value instanceof Date) { return DateTime.fromJSDate(value).toISODate(); } if (value instanceof DateTime) { return value.toISODate(); } throwError(value, field, 'raw'); } function toRawDateTime(value: DocValue, field: Field): string | null { if (value === null) { return null; } if (typeof value === 'string') { return value; } if (value instanceof Date) { return value.toISOString(); } if (value instanceof DateTime) { return value.toJSDate().toISOString(); } throwError(value, field, 'raw'); } function toRawCheck(value: DocValue, field: Field): number { if (typeof value === 'number') { value = Boolean(value); } if (typeof value === 'boolean') { return Number(value); } throwError(value, field, 'raw'); } function toRawString(value: DocValue, field: Field): string | null { if (value === null) { return null; } if (value === undefined) { return null; } if (typeof value === 'string') { return value; } throwError(value, field, 'raw'); } function toRawLink(value: DocValue, field: Field): string | null { if (value === null || !(value as string)?.length) { return null; } if (typeof value === 'string') { return value; } throwError(value, field, 'raw'); } function toRawAttachment(value: DocValue, field: Field): null | string { if (!value) { return null; } if ( (value as Attachment)?.name && (value as Attachment)?.data && (value as Attachment)?.type ) { return JSON.stringify(value); } throwError(value, field, 'raw'); } function throwError<T>(value: T, field: Field, type: 'raw' | 'doc'): never { throw new ValueError( `invalid ${type} conversion '${String( value )}' of type ${typeof value} found, field: ${JSON.stringify(field)}` ); }
2302_79757062/books
fyo/core/converter.ts
TypeScript
agpl-3.0
10,150
import { SingleValue } from 'backend/database/types'; import { Fyo } from 'fyo'; import { DatabaseDemux } from 'fyo/demux/db'; import { ValueError } from 'fyo/utils/errors'; import Observable from 'fyo/utils/observable'; import { translateSchema } from 'fyo/utils/translation'; import { Field, RawValue, SchemaMap } from 'schemas/types'; import { getMapFromList } from 'utils'; import { Cashflow, DatabaseBase, DatabaseDemuxBase, GetAllOptions, IncomeExpense, QueryFilter, TopExpenses, TotalCreditAndDebit, TotalOutstanding, } from 'utils/db/types'; import { schemaTranslateables } from 'utils/translationHelpers'; import { LanguageMap } from 'utils/types'; import { Converter } from './converter'; import { DatabaseDemuxConstructor, DocValue, DocValueMap, RawValueMap, } from './types'; import { ReturnDocItem } from 'models/inventory/types'; import { Money } from 'pesa'; type FieldMap = Record<string, Record<string, Field>>; export class DatabaseHandler extends DatabaseBase { /* eslint-disable @typescript-eslint/no-floating-promises */ #fyo: Fyo; converter: Converter; #demux: DatabaseDemuxBase; dbPath?: string; #schemaMap: SchemaMap = {}; #fieldMap: FieldMap = {}; observer: Observable<never> = new Observable(); constructor(fyo: Fyo, Demux?: DatabaseDemuxConstructor) { super(); this.#fyo = fyo; this.converter = new Converter(this, this.#fyo); if (Demux !== undefined) { this.#demux = new Demux(fyo.isElectron); } else { this.#demux = new DatabaseDemux(fyo.isElectron); } } get schemaMap(): Readonly<SchemaMap> { return this.#schemaMap; } get fieldMap(): Readonly<FieldMap> { return this.#fieldMap; } get isConnected() { return !!this.dbPath; } async createNewDatabase(dbPath: string, countryCode: string) { countryCode = await this.#demux.createNewDatabase(dbPath, countryCode); await this.init(); this.dbPath = dbPath; return countryCode; } async connectToDatabase(dbPath: string, countryCode?: string) { countryCode = await this.#demux.connectToDatabase(dbPath, countryCode); await this.init(); this.dbPath = dbPath; return countryCode; } async init() { this.#schemaMap = await this.#demux.getSchemaMap(); this.#setFieldMap(); this.observer = new Observable(); } async translateSchemaMap(languageMap?: LanguageMap) { if (languageMap) { translateSchema(this.#schemaMap, languageMap, schemaTranslateables); } else { this.#schemaMap = await this.#demux.getSchemaMap(); this.#setFieldMap(); } } async purgeCache() { await this.close(); this.dbPath = undefined; this.#schemaMap = {}; this.#fieldMap = {}; } async insert( schemaName: string, docValueMap: DocValueMap ): Promise<DocValueMap> { let rawValueMap = this.converter.toRawValueMap( schemaName, docValueMap ) as RawValueMap; rawValueMap = (await this.#demux.call( 'insert', schemaName, rawValueMap )) as RawValueMap; this.observer.trigger(`insert:${schemaName}`, docValueMap); return this.converter.toDocValueMap(schemaName, rawValueMap) as DocValueMap; } // Read async get( schemaName: string, name: string, fields?: string | string[] ): Promise<DocValueMap> { const rawValueMap = (await this.#demux.call( 'get', schemaName, name, fields )) as RawValueMap; this.observer.trigger(`get:${schemaName}`, { name, fields }); return this.converter.toDocValueMap(schemaName, rawValueMap) as DocValueMap; } async getAll( schemaName: string, options: GetAllOptions = {} ): Promise<DocValueMap[]> { const rawValueMap = await this.#getAll(schemaName, options); this.observer.trigger(`getAll:${schemaName}`, options); return this.converter.toDocValueMap( schemaName, rawValueMap ) as DocValueMap[]; } async getAllRaw( schemaName: string, options: GetAllOptions = {} ): Promise<RawValueMap[]> { const all = await this.#getAll(schemaName, options); this.observer.trigger(`getAllRaw:${schemaName}`, options); return all; } async getSingleValues( ...fieldnames: ({ fieldname: string; parent?: string } | string)[] ): Promise<SingleValue<DocValue>> { const rawSingleValue = (await this.#demux.call( 'getSingleValues', ...fieldnames )) as SingleValue<RawValue>; const docSingleValue: SingleValue<DocValue> = []; for (const sv of rawSingleValue) { const field = this.fieldMap[sv.parent][sv.fieldname]; const value = Converter.toDocValue(sv.value, field, this.#fyo); docSingleValue.push({ value, parent: sv.parent, fieldname: sv.fieldname, }); } this.observer.trigger(`getSingleValues`, fieldnames); return docSingleValue; } async count( schemaName: string, options: GetAllOptions = {} ): Promise<number> { const rawValueMap = await this.#getAll(schemaName, options); const count = rawValueMap.length; this.observer.trigger(`count:${schemaName}`, options); return count; } // Update async rename( schemaName: string, oldName: string, newName: string ): Promise<void> { await this.#demux.call('rename', schemaName, oldName, newName); this.observer.trigger(`rename:${schemaName}`, { oldName, newName }); } async update(schemaName: string, docValueMap: DocValueMap): Promise<void> { const rawValueMap = this.converter.toRawValueMap(schemaName, docValueMap); await this.#demux.call('update', schemaName, rawValueMap); this.observer.trigger(`update:${schemaName}`, docValueMap); } // Delete async delete(schemaName: string, name: string): Promise<void> { await this.#demux.call('delete', schemaName, name); this.observer.trigger(`delete:${schemaName}`, name); } async deleteAll(schemaName: string, filters: QueryFilter): Promise<number> { const count = (await this.#demux.call( 'deleteAll', schemaName, filters )) as number; this.observer.trigger(`deleteAll:${schemaName}`, filters); return count; } // Other async exists(schemaName: string, name?: string): Promise<boolean> { const doesExist = (await this.#demux.call( 'exists', schemaName, name )) as boolean; this.observer.trigger(`exists:${schemaName}`, name); return doesExist; } async close(): Promise<void> { await this.#demux.call('close'); } /** * Bespoke function * * These are functions to run custom queries that are too complex for * DatabaseCore and require use of knex or raw queries. The output * of these is not converted to DocValue and is used as is (RawValue). * * The query logic for these is in backend/database/bespoke.ts */ async getLastInserted(schemaName: string): Promise<number> { if (this.schemaMap[schemaName]?.naming !== 'autoincrement') { throw new ValueError( `invalid schema, ${schemaName} does not have autoincrement naming` ); } return (await this.#demux.callBespoke( 'getLastInserted', schemaName )) as number; } async getTopExpenses(fromDate: string, toDate: string): Promise<TopExpenses> { return (await this.#demux.callBespoke( 'getTopExpenses', fromDate, toDate )) as TopExpenses; } async getTotalOutstanding( schemaName: string, fromDate: string, toDate: string ): Promise<TotalOutstanding> { return (await this.#demux.callBespoke( 'getTotalOutstanding', schemaName, fromDate, toDate )) as TotalOutstanding; } async getCashflow(fromDate: string, toDate: string): Promise<Cashflow> { return (await this.#demux.callBespoke( 'getCashflow', fromDate, toDate )) as Cashflow; } async getIncomeAndExpenses( fromDate: string, toDate: string ): Promise<IncomeExpense> { return (await this.#demux.callBespoke( 'getIncomeAndExpenses', fromDate, toDate )) as IncomeExpense; } async getTotalCreditAndDebit(): Promise<TotalCreditAndDebit[]> { return (await this.#demux.callBespoke( 'getTotalCreditAndDebit' )) as TotalCreditAndDebit[]; } async getStockQuantity( item: string, location?: string, fromDate?: string, toDate?: string, batch?: string, serialNumbers?: string[] ): Promise<number | null> { return (await this.#demux.callBespoke( 'getStockQuantity', item, location, fromDate, toDate, batch, serialNumbers )) as number | null; } async getReturnBalanceItemsQty( schemaName: string, docName: string ): Promise<Record<string, ReturnDocItem> | undefined> { return (await this.#demux.callBespoke( 'getReturnBalanceItemsQty', schemaName, docName )) as Promise<Record<string, ReturnDocItem> | undefined>; } async getPOSTransactedAmount( fromDate: Date, toDate: Date, lastShiftClosingDate?: Date ): Promise<Record<string, Money> | undefined> { return (await this.#demux.callBespoke( 'getPOSTransactedAmount', fromDate, toDate, lastShiftClosingDate )) as Promise<Record<string, Money> | undefined>; } /** * Internal methods */ async #getAll( schemaName: string, options: GetAllOptions = {} ): Promise<RawValueMap[]> { return (await this.#demux.call( 'getAll', schemaName, options )) as RawValueMap[]; } #setFieldMap() { this.#fieldMap = Object.values(this.schemaMap).reduce((acc, sch) => { if (!sch?.name) { return acc; } acc[sch?.name] = getMapFromList(sch?.fields, 'fieldname'); return acc; }, {} as FieldMap); } }
2302_79757062/books
fyo/core/dbHandler.ts
TypeScript
agpl-3.0
9,875
import { Doc } from 'fyo/model/doc'; import { DocMap, ModelMap, SinglesMap } from 'fyo/model/types'; import { coreModels } from 'fyo/models'; import { NotFoundError, ValueError } from 'fyo/utils/errors'; import Observable from 'fyo/utils/observable'; import { Schema } from 'schemas/types'; import { getRandomString } from 'utils'; import { Fyo } from '..'; import { DocValueMap, RawValueMap } from './types'; export class DocHandler { fyo: Fyo; models: ModelMap = {}; singles: SinglesMap = {}; docs: Observable<DocMap | undefined> = new Observable(); observer: Observable<never> = new Observable(); #temporaryNameCounters: Record<string, number>; constructor(fyo: Fyo) { this.fyo = fyo; this.#temporaryNameCounters = {}; } init() { this.models = {}; this.singles = {}; this.docs = new Observable(); this.observer = new Observable(); } purgeCache() { this.init(); } registerModels(models: ModelMap, regionalModels: ModelMap = {}) { for (const schemaName in this.fyo.db.schemaMap) { if (coreModels[schemaName] !== undefined) { this.models[schemaName] = coreModels[schemaName]; } else if (regionalModels[schemaName] !== undefined) { this.models[schemaName] = regionalModels[schemaName]; } else if (models[schemaName] !== undefined) { this.models[schemaName] = models[schemaName]; } else { this.models[schemaName] = Doc; } } } /** * Doc Operations */ async getDoc( schemaName: string, name?: string, options = { skipDocumentCache: false } ) { if (name === undefined) { name = schemaName; } if (name === schemaName && !this.fyo.schemaMap[schemaName]?.isSingle) { throw new ValueError(`${schemaName} is not a Single Schema`); } let doc: Doc | undefined; if (!options?.skipDocumentCache) { doc = this.#getFromCache(schemaName, name); } if (doc) { return doc; } doc = this.getNewDoc(schemaName, { name }, false); await doc.load(); this.#addToCache(doc); return doc; } getNewDoc( schemaName: string, data: DocValueMap | RawValueMap = {}, cacheDoc = true, schema?: Schema, Model?: typeof Doc, isRawValueMap = true ): Doc { if (!this.models[schemaName] && Model) { this.models[schemaName] = Model; } Model ??= this.models[schemaName]; schema ??= this.fyo.schemaMap[schemaName]; if (schema === undefined) { throw new NotFoundError(`Schema not found for ${schemaName}`); } const doc = new Model!(schema, data, this.fyo, isRawValueMap); doc.name ??= this.getTemporaryName(schema); if (cacheDoc) { this.#addToCache(doc); } return doc; } isTemporaryName(name: string, schema: Schema): boolean { const label = schema.label ?? schema.name; const template = this.fyo.t`New ${label} `; return name.includes(template); } getTemporaryName(schema: Schema): string { if (schema.naming === 'random') { return getRandomString(); } this.#temporaryNameCounters[schema.name] ??= 1; const idx = this.#temporaryNameCounters[schema.name]; this.#temporaryNameCounters[schema.name] = idx + 1; const label = schema.label ?? schema.name; return this.fyo.t`New ${label} ${String(idx).padStart(2, '0')}`; } /** * Cache operations */ #addToCache(doc: Doc) { if (!doc.name) { return; } const name = doc.name; const schemaName = doc.schemaName; if (!this.docs[schemaName]) { this.docs.set(schemaName, {}); this.#setCacheUpdationListeners(schemaName); } this.docs.get(schemaName)![name] = doc; // singles available as first level objects too if (schemaName === doc.name) { this.singles[name] = doc; } // propagate change to `docs` doc.on('change', (params: unknown) => { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.docs.trigger('change', params); }); doc.on('afterSync', () => { if (doc.name === name && this.#cacheHas(schemaName, name)) { return; } this.removeFromCache(doc.schemaName, name); this.#addToCache(doc); }); } #setCacheUpdationListeners(schemaName: string) { this.fyo.db.observer.on(`delete:${schemaName}`, (name) => { if (typeof name !== 'string') { return; } this.removeFromCache(schemaName, name); }); this.fyo.db.observer.on(`rename:${schemaName}`, (names) => { const { oldName } = names as { oldName: string }; const doc = this.#getFromCache(schemaName, oldName); if (doc === undefined) { return; } this.removeFromCache(schemaName, oldName); this.#addToCache(doc); }); } removeFromCache(schemaName: string, name: string) { const docMap = this.docs.get(schemaName); delete docMap?.[name]; } #getFromCache(schemaName: string, name: string): Doc | undefined { const docMap = this.docs.get(schemaName); return docMap?.[name]; } #cacheHas(schemaName: string, name: string): boolean { return !!this.#getFromCache(schemaName, name); } }
2302_79757062/books
fyo/core/docHandler.ts
TypeScript
agpl-3.0
5,210
import type { Doc } from 'fyo/model/doc'; import type { Money } from 'pesa'; import type { RawValue } from 'schemas/types'; import type { AuthDemuxBase } from 'utils/auth/types'; import type { DatabaseDemuxBase } from 'utils/db/types'; export type Attachment = { name: string; type: string; data: string }; export type DocValue = | string | number | boolean | Date | Money | null | Attachment | undefined; export type DocValueMap = Record<string, DocValue | Doc[] | DocValueMap[]>; export type RawValueMap = Record<string, RawValue | RawValueMap[]>; /** * DatabaseDemuxConstructor: type for a constructor that returns a DatabaseDemuxBase * it's typed this way because `typeof AbstractClass` is invalid as abstract classes * can't be initialized using `new`. * * AuthDemuxConstructor: same as the above but for AuthDemuxBase */ export type DatabaseDemuxConstructor = new ( isElectron?: boolean ) => DatabaseDemuxBase; export type AuthDemuxConstructor = new (isElectron?: boolean) => AuthDemuxBase; export type ConfigMap = { files: ConfigFile[]; lastSelectedFilePath: null | string; language: string deviceId: string }; export interface ConfigFile { id: string; companyName: string; dbPath: string; openCount: number; } export interface FyoConfig { DatabaseDemux?: DatabaseDemuxConstructor; AuthDemux?: AuthDemuxConstructor; isElectron?: boolean; isTest?: boolean; }
2302_79757062/books
fyo/core/types.ts
TypeScript
agpl-3.0
1,421
import { AuthDemuxBase } from 'utils/auth/types'; import { Creds } from 'utils/types'; export class AuthDemux extends AuthDemuxBase { #isElectron = false; constructor(isElectron: boolean) { super(); this.#isElectron = isElectron; } async getCreds(): Promise<Creds> { if (this.#isElectron) { return await ipc.getCreds(); } else { return { errorLogUrl: '', tokenString: '', telemetryUrl: '' }; } } }
2302_79757062/books
fyo/demux/auth.ts
TypeScript
agpl-3.0
442
import { ConfigMap } from 'fyo/core/types'; import type { IPC } from 'main/preload'; export class Config { config: Map<string, unknown> | IPC['store']; constructor(isElectron: boolean) { this.config = new Map(); if (isElectron) { this.config = ipc.store; } } get<K extends keyof ConfigMap>( key: K, defaultValue?: ConfigMap[K] ): ConfigMap[K] | undefined { const value = this.config.get(key) as ConfigMap[K] | undefined; return value ?? defaultValue; } set<K extends keyof ConfigMap>(key: K, value: ConfigMap[K]) { this.config.set(key, value); } delete(key: keyof ConfigMap) { this.config.delete(key); } }
2302_79757062/books
fyo/demux/config.ts
TypeScript
agpl-3.0
672
import { DatabaseError, NotImplemented } from 'fyo/utils/errors'; import { SchemaMap } from 'schemas/types'; import { DatabaseDemuxBase, DatabaseMethod } from 'utils/db/types'; import { BackendResponse } from 'utils/ipc/types'; export class DatabaseDemux extends DatabaseDemuxBase { #isElectron = false; constructor(isElectron: boolean) { super(); this.#isElectron = isElectron; } async #handleDBCall(func: () => Promise<BackendResponse>): Promise<unknown> { const response = await func(); if (response.error?.name) { const { name, message, stack } = response.error; const dberror = new DatabaseError(`${name}\n${message}`); dberror.stack = stack; throw dberror; } return response.data; } async getSchemaMap(): Promise<SchemaMap> { if (!this.#isElectron) { throw new NotImplemented(); } return (await this.#handleDBCall(async () => { return await ipc.db.getSchema(); })) as SchemaMap; } async createNewDatabase( dbPath: string, countryCode?: string ): Promise<string> { if (!this.#isElectron) { throw new NotImplemented(); } return (await this.#handleDBCall(async () => { return ipc.db.create(dbPath, countryCode); })) as string; } async connectToDatabase( dbPath: string, countryCode?: string ): Promise<string> { if (!this.#isElectron) { throw new NotImplemented(); } return (await this.#handleDBCall(async () => { return ipc.db.connect(dbPath, countryCode); })) as string; } async call(method: DatabaseMethod, ...args: unknown[]): Promise<unknown> { if (!this.#isElectron) { throw new NotImplemented(); } return await this.#handleDBCall(async () => { return await ipc.db.call(method, ...args); }); } async callBespoke(method: string, ...args: unknown[]): Promise<unknown> { if (!this.#isElectron) { throw new NotImplemented(); } return await this.#handleDBCall(async () => { return await ipc.db.bespoke(method, ...args); }); } }
2302_79757062/books
fyo/demux/db.ts
TypeScript
agpl-3.0
2,085
import { getMoneyMaker, MoneyMaker } from 'pesa'; import { Field, FieldType } from 'schemas/types'; import { getIsNullOrUndef } from 'utils'; import { markRaw } from 'vue'; import { AuthHandler } from './core/authHandler'; import { DatabaseHandler } from './core/dbHandler'; import { DocHandler } from './core/docHandler'; import { DocValue, FyoConfig } from './core/types'; import { Config } from './demux/config'; import { Doc } from './model/doc'; import { ModelMap } from './model/types'; import { TelemetryManager } from './telemetry/telemetry'; import { DEFAULT_CURRENCY, DEFAULT_DISPLAY_PRECISION, DEFAULT_INTERNAL_PRECISION, } from './utils/consts'; import * as errors from './utils/errors'; import { format } from './utils/format'; import { t, T } from './utils/translation'; import { ErrorLog } from './utils/types'; import type { reports } from 'reports/index'; import type { Report } from 'reports/Report'; export class Fyo { t = t; T = T; errors = errors; isElectron: boolean; pesa: MoneyMaker; auth: AuthHandler; doc: DocHandler; db: DatabaseHandler; _initialized = false; errorLog: ErrorLog[] = []; temp?: Record<string, unknown>; currencyFormatter?: Intl.NumberFormat; currencySymbols: Record<string, string | undefined> = {}; isTest: boolean; telemetry: TelemetryManager; config: Config; constructor(conf: FyoConfig = {}) { this.isTest = conf.isTest ?? false; this.isElectron = conf.isElectron ?? true; this.auth = new AuthHandler(this, conf.AuthDemux); this.db = new DatabaseHandler(this, conf.DatabaseDemux); this.doc = new DocHandler(this); this.pesa = getMoneyMaker({ currency: DEFAULT_CURRENCY, precision: DEFAULT_INTERNAL_PRECISION, display: DEFAULT_DISPLAY_PRECISION, wrapper: markRaw, }); this.telemetry = new TelemetryManager(this); this.config = new Config(this.isElectron && !this.isTest); } get initialized() { return this._initialized; } get docs() { return this.doc.docs; } get models() { return this.doc.models; } get singles() { return this.doc.singles; } get schemaMap() { return this.db.schemaMap; } get fieldMap() { return this.db.fieldMap; } format(value: unknown, field: FieldType | Field, doc?: Doc) { return format(value, field, doc ?? null, this); } setIsElectron() { try { this.isElectron = !!window?.ipc; } catch { this.isElectron = false; } } async initializeAndRegister( models: ModelMap = {}, regionalModels: ModelMap = {}, force = false ) { if (this._initialized && !force) return; await this.#initializeModules(); await this.#initializeMoneyMaker(); this.doc.registerModels(models, regionalModels); await this.doc.getDoc('SystemSettings'); this._initialized = true; } async #initializeModules() { // temp params while calling routes this.temp = {}; this.doc.init(); this.auth.init(); await this.db.init(); } async #initializeMoneyMaker() { const values = (await this.db?.getSingleValues( { fieldname: 'internalPrecision', parent: 'SystemSettings', }, { fieldname: 'displayPrecision', parent: 'SystemSettings', }, { fieldname: 'currency', parent: 'SystemSettings', } )) ?? []; const acc = values.reduce((acc, sv) => { acc[sv.fieldname] = sv.value as string | number | undefined; return acc; }, {} as Record<string, string | number | undefined>); const precision: number = (acc.internalPrecision as number) ?? DEFAULT_INTERNAL_PRECISION; const display: number = (acc.displayPrecision as number) ?? DEFAULT_DISPLAY_PRECISION; const currency: string = (acc.currency as string) ?? DEFAULT_CURRENCY; this.pesa = getMoneyMaker({ currency, precision, display, wrapper: markRaw, }); } async close() { await this.db.close(); } getField(schemaName: string, fieldname: string) { return this.fieldMap[schemaName]?.[fieldname]; } async getValue( schemaName: string, name: string, fieldname?: string ): Promise<DocValue | Doc[]> { if (fieldname === undefined && this.schemaMap[schemaName]?.isSingle) { fieldname = name; name = schemaName; } if (getIsNullOrUndef(name) || getIsNullOrUndef(fieldname)) { return undefined; } let doc: Doc; let value: DocValue | Doc[]; try { doc = await this.doc.getDoc(schemaName, name); value = doc.get(fieldname); } catch (err) { value = undefined; } if (value === undefined && schemaName === name) { const sv = await this.db.getSingleValues({ fieldname: fieldname, parent: schemaName, }); return sv?.[0]?.value; } return value; } async purgeCache() { this.pesa = getMoneyMaker({ currency: DEFAULT_CURRENCY, precision: DEFAULT_INTERNAL_PRECISION, display: DEFAULT_DISPLAY_PRECISION, wrapper: markRaw, }); this._initialized = false; this.temp = {}; this.currencyFormatter = undefined; this.currencySymbols = {}; this.errorLog = []; this.temp = {}; await this.db.purgeCache(); this.doc.purgeCache(); } store = { isDevelopment: false, skipTelemetryLogging: false, appVersion: '', platform: '', language: '', instanceId: '', deviceId: '', openCount: -1, appFlags: {} as Record<string, boolean>, reports: {} as Record<keyof typeof reports, Report | undefined>, }; } export { T, t };
2302_79757062/books
fyo/index.ts
TypeScript
agpl-3.0
5,704
import { Fyo } from 'fyo'; import { Converter } from 'fyo/core/converter'; import { DocValue, DocValueMap, RawValueMap } from 'fyo/core/types'; import { Verb } from 'fyo/telemetry/types'; import { DEFAULT_USER } from 'fyo/utils/consts'; import { ConflictError, MandatoryError, NotFoundError } from 'fyo/utils/errors'; import Observable from 'fyo/utils/observable'; import { DynamicLinkField, Field, FieldTypeEnum, RawValue, Schema, TargetField, } from 'schemas/types'; import { getIsNullOrUndef, getMapFromList, getRandomString } from 'utils'; import { markRaw, reactive } from 'vue'; import { isPesa } from '../utils/index'; import { getDbSyncError } from './errorHelpers'; import { areDocValuesEqual, getFormulaSequence, getMissingMandatoryMessage, getPreDefaultValues, setChildDocIdx, shouldApplyFormula, } from './helpers'; import { setName } from './naming'; import { Action, ChangeArg, CurrenciesMap, DefaultMap, EmptyMessageMap, FiltersMap, FormulaMap, FormulaReturn, HiddenMap, ListViewSettings, ListsMap, ReadOnlyMap, RequiredMap, TreeViewSettings, ValidationMap, } from './types'; import { validateOptions, validateRequired } from './validationFunction'; export class Doc extends Observable<DocValue | Doc[]> { /* eslint-disable @typescript-eslint/no-floating-promises */ name?: string; schema: Readonly<Schema>; fyo: Fyo; fieldMap: Record<string, Field>; /** * Fields below are used by child docs to maintain * reference w.r.t their parent doc. */ idx?: number; parentdoc?: Doc; parentFieldname?: string; parentSchemaName?: string; links?: Record<string, Doc>; _dirty = true; _notInserted = true; _syncing = false; constructor( schema: Schema, data: DocValueMap, fyo: Fyo, convertToDocValue = true ) { super(); this.fyo = markRaw(fyo); this.schema = schema; this.fieldMap = getMapFromList(schema.fields, 'fieldname'); if (this.schema.isSingle) { this.name = this.schemaName; } this._setDefaults(); this._setValuesWithoutChecks(data, convertToDocValue); return reactive(this) as Doc; } get schemaName(): string { return this.schema.name; } get notInserted(): boolean { return this._notInserted; } get inserted(): boolean { return !this._notInserted; } get tableFields(): TargetField[] { return this.schema.fields.filter( (f) => f.fieldtype === FieldTypeEnum.Table ) as TargetField[]; } get dirty() { return this._dirty; } get quickEditFields() { let fieldnames = this.schema.quickEditFields; if (fieldnames === undefined) { fieldnames = []; } if (fieldnames.length === 0 && this.fieldMap['name']) { fieldnames = ['name']; } return fieldnames.map((f) => this.fieldMap[f]); } get isSubmitted() { return !!this.submitted && !this.cancelled; } get isCancelled() { return !!this.submitted && !!this.cancelled; } get isSyncing() { return this._syncing; } get canDelete() { if (this.notInserted) { return false; } if (this.schema.isSingle) { return false; } if (this.schema.isChild) { return false; } if (!this.schema.isSubmittable) { return true; } if (this.schema.isSubmittable && this.isCancelled) { return true; } if (this.schema.isSubmittable && !this.isSubmitted) { return true; } return false; } get canEdit() { if (!this.schema.isSubmittable) { return true; } if (this.submitted) { return false; } if (this.cancelled) { return false; } return true; } get canSave() { const isSubmittable = this.schema.isSubmittable; if (isSubmittable && !!this.submitted) { return false; } if (isSubmittable && !!this.cancelled) { return false; } if (!this.dirty) { return false; } if (this.schema.isChild) { return false; } return true; } get canSubmit() { if (!this.schema.isSubmittable) { return false; } if (this.dirty) { return false; } if (this.notInserted) { return false; } if (!!this.submitted) { return false; } if (!!this.cancelled) { return false; } return true; } get canCancel() { if (!this.schema.isSubmittable) { return false; } if (this.dirty) { return false; } if (this.notInserted) { return false; } if (!!this.cancelled) { return false; } if (!this.submitted) { return false; } return true; } _setValuesWithoutChecks(data: DocValueMap, convertToDocValue: boolean) { for (const field of this.schema.fields) { const { fieldname, fieldtype } = field; const value = data[field.fieldname]; if (Array.isArray(value)) { for (const row of value) { this.push(fieldname, row, convertToDocValue); } } else if ( fieldtype === FieldTypeEnum.Currency && typeof value === 'number' ) { this[fieldname] = this.fyo.pesa(value); } else if (value !== undefined && !convertToDocValue) { this[fieldname] = value; } else if (value !== undefined) { this[fieldname] = Converter.toDocValue( value as RawValue, field, this.fyo ); } else { this[fieldname] = this[fieldname] ?? null; } if (field.fieldtype === FieldTypeEnum.Table && !this[fieldname]) { this[fieldname] = []; } } } _setDirty(value: boolean) { this._dirty = value; if (this.schema.isChild && this.parentdoc) { this.parentdoc._dirty = value; } } // set value and trigger change async set( fieldname: string | DocValueMap, value?: DocValue | Doc[] | DocValueMap[], retriggerChildDocApplyChange = false ): Promise<boolean> { if (typeof fieldname === 'object') { return await this.setMultiple(fieldname); } if (!this._canSet(fieldname, value)) { return false; } this._setDirty(true); if (typeof value === 'string') { value = value.trim(); } if (Array.isArray(value)) { for (const row of value) { this.push(fieldname, row); } } else { const field = this.fieldMap[fieldname]; await this._validateField(field, value); this[fieldname] = value; } // always run applyChange from the parentdoc if (this.schema.isChild && this.parentdoc) { await this._applyChange(fieldname); await this.parentdoc._applyChange(this.parentFieldname as string); } else { await this._applyChange(fieldname, retriggerChildDocApplyChange); } return true; } async setMultiple(docValueMap: DocValueMap): Promise<boolean> { let hasSet = false; for (const fieldname in docValueMap) { const isSet = await this.set( fieldname, docValueMap[fieldname] as DocValue | Doc[] ); hasSet ||= isSet; } return hasSet; } _canSet( fieldname: string, value?: DocValue | Doc[] | DocValueMap[] ): boolean { if (fieldname === 'numberSeries' && !this.notInserted) { return false; } if (value === undefined) { return false; } if (this.fieldMap[fieldname] === undefined) { return false; } const currentValue = this.get(fieldname); if (currentValue === undefined) { return true; } return !areDocValuesEqual(currentValue as DocValue, value as DocValue); } async _applyChange( changedFieldname: string, retriggerChildDocApplyChange?: boolean ): Promise<boolean> { await this._applyFormula(changedFieldname, retriggerChildDocApplyChange); await this.trigger('change', { doc: this, changed: changedFieldname, }); return true; } _setDefaults() { for (const field of this.schema.fields) { let defaultValue: DocValue | Doc[] = getPreDefaultValues( field.fieldtype, this.fyo ); const defaultFunction = this.fyo.models[this.schemaName]?.defaults?.[field.fieldname]; if (defaultFunction !== undefined) { defaultValue = defaultFunction(this); } else if (field.default !== undefined) { defaultValue = field.default; } if (field.fieldtype === FieldTypeEnum.Currency && !isPesa(defaultValue)) { defaultValue = this.fyo.pesa(defaultValue as string | number); } this[field.fieldname] = defaultValue; } } async remove(fieldname: string, idx: number) { const childDocs = ((this[fieldname] ?? []) as Doc[]).filter( (row, i) => row.idx !== idx || i !== idx ); setChildDocIdx(childDocs); this[fieldname] = childDocs; this._setDirty(true); return await this._applyChange(fieldname); } async append(fieldname: string, docValueMap: DocValueMap = {}) { this.push(fieldname, docValueMap); this._setDirty(true); return await this._applyChange(fieldname); } push( fieldname: string, docValueMap: Doc | DocValueMap | RawValueMap = {}, convertToDocValue = false ) { const childDocs = [ (this[fieldname] ?? []) as Doc[], this._getChildDoc(docValueMap, fieldname, convertToDocValue), ].flat(); setChildDocIdx(childDocs); this[fieldname] = childDocs; } _setChildDocsParent() { for (const { fieldname } of this.tableFields) { const value = this.get(fieldname); if (!Array.isArray(value)) { continue; } for (const childDoc of value) { if (childDoc.parent) { continue; } childDoc.parent = this.name; } } } _getChildDoc( docValueMap: Doc | DocValueMap | RawValueMap, fieldname: string, convertToDocValue = false ): Doc { if (!this.name && this.schema.naming !== 'manual') { this.name = this.fyo.doc.getTemporaryName(this.schema); } docValueMap.name ??= getRandomString(); // Child Meta Fields docValueMap.parent ??= this.name; docValueMap.parentSchemaName ??= this.schemaName; docValueMap.parentFieldname ??= fieldname; if (docValueMap instanceof Doc) { docValueMap.parentdoc ??= this; return docValueMap; } const childSchemaName = (this.fieldMap[fieldname] as TargetField).target; const childDoc = this.fyo.doc.getNewDoc( childSchemaName, docValueMap, false, undefined, undefined, convertToDocValue ); childDoc.parentdoc = this; return childDoc; } async _validateSync() { this._validateMandatory(); await this._validateFields(); } _validateMandatory() { const checkForMandatory: Doc[] = [this]; const tableFields = this.schema.fields.filter( (f) => f.fieldtype === FieldTypeEnum.Table ) as TargetField[]; for (const field of tableFields) { const childDocs = this.get(field.fieldname) as Doc[]; if (!childDocs) { continue; } checkForMandatory.push(...childDocs); } const missingMandatoryMessage = checkForMandatory .map((doc) => getMissingMandatoryMessage(doc)) .filter(Boolean); if (missingMandatoryMessage.length > 0) { const fields = missingMandatoryMessage.join('\n'); const message = this.fyo.t`Value missing for ${fields}`; throw new MandatoryError(message); } } async _validateFields() { const fields = this.schema.fields; for (const field of fields) { if (field.fieldtype === FieldTypeEnum.Table) { continue; } const value = this.get(field.fieldname) as DocValue; await this._validateField(field, value); } } async _validateField(field: Field, value: DocValue) { if ( field.fieldtype === FieldTypeEnum.Select || field.fieldtype === FieldTypeEnum.AutoComplete ) { validateOptions(field, value as string, this); } validateRequired(field, value, this); if (getIsNullOrUndef(value)) { return; } const validator = this.validations[field.fieldname]; if (validator === undefined) { return; } await validator(value); } getValidDict(filterMeta = false, filterComputed = false): DocValueMap { let fields = this.schema.fields; if (filterMeta) { fields = this.schema.fields.filter((f) => !f.meta); } if (filterComputed) { fields = fields.filter((f) => !f.computed); } const data: DocValueMap = {}; for (const field of fields) { let value = this[field.fieldname] as DocValue | DocValueMap[]; if (Array.isArray(value)) { value = value.map((doc) => (doc as Doc).getValidDict(filterMeta, filterComputed) ); } if (isPesa(value)) { value = value.copy(); } if (value === null && this.schema.isSingle) { continue; } data[field.fieldname] = value; } return data; } _setBaseMetaValues() { if (this.schema.isSubmittable) { this.submitted = false; this.cancelled = false; } if (!this.createdBy) { this.createdBy = this.fyo.auth.session.user || DEFAULT_USER; } if (!this.created) { this.created = new Date(); } this._updateModifiedMetaValues(); } _updateModifiedMetaValues() { this.modifiedBy = this.fyo.auth.session.user || DEFAULT_USER; this.modified = new Date(); } async load() { if (this.name === undefined) { return; } const data = await this.fyo.db.get(this.schemaName, this.name); if (this.schema.isSingle && !data?.name) { data.name = this.name!; } if (data && data.name) { await this._syncValues(data); await this.loadLinks(); } else { throw new NotFoundError(`Not Found: ${this.schemaName} ${this.name}`); } this._setDirty(false); this._notInserted = false; this.fyo.doc.observer.trigger(`load:${this.schemaName}`, this.name); } async loadLinks() { this.links ??= {}; const linkFields = this.schema.fields.filter( ({ fieldtype }) => fieldtype === FieldTypeEnum.Link || fieldtype === FieldTypeEnum.DynamicLink ); for (const field of linkFields) { await this._loadLink(field); } } async _loadLink(field: Field) { if (field.fieldtype === FieldTypeEnum.Link) { return await this._loadLinkField(field); } if (field.fieldtype === FieldTypeEnum.DynamicLink) { return await this._loadDynamicLinkField(field); } } async _loadLinkField(field: TargetField) { const { fieldname, target } = field; const value = this.get(fieldname) as string | undefined; if (!value || !target) { return; } await this._loadLinkDoc(fieldname, target, value); } async _loadDynamicLinkField(field: DynamicLinkField) { const { fieldname, references } = field; const value = this.get(fieldname) as string | undefined; const reference = this.get(references) as string | undefined; if (!value || !reference) { return; } await this._loadLinkDoc(fieldname, reference, value); } async _loadLinkDoc(fieldname: string, schemaName: string, name: string) { this.links![fieldname] = await this.fyo.doc.getDoc(schemaName, name); } getLink(fieldname: string): Doc | null { return this.links?.[fieldname] ?? null; } async loadAndGetLink(fieldname: string): Promise<Doc | null> { if (!this?.[fieldname]) { return null; } if (this.links?.[fieldname]?.name !== this[fieldname]) { await this.loadLinks(); } return this.links?.[fieldname] ?? null; } async _syncValues(data: DocValueMap) { this._clearValues(); this._setValuesWithoutChecks(data, false); await this._setComputedValuesFromFormulas(); this._dirty = false; this.trigger('change', { doc: this, }); } async _setComputedValuesFromFormulas() { for (const field of this.schema.fields) { await this._setComputedValuesForChildren(field); if (!field.computed) { continue; } const value = await this._getValueFromFormula(field, this); this[field.fieldname] = value ?? null; } } async _setComputedValuesForChildren(field: Field) { if (field.fieldtype !== 'Table') { return; } const childDocs: Doc[] = (this[field.fieldname] as Doc[]) ?? []; for (const doc of childDocs) { await doc._setComputedValuesFromFormulas(); } } _clearValues() { for (const { fieldname } of this.schema.fields) { this[fieldname] = null; } this._dirty = true; this._notInserted = true; } _setChildDocsIdx() { const childFields = this.schema.fields.filter( (f) => f.fieldtype === FieldTypeEnum.Table ) as TargetField[]; for (const field of childFields) { const childDocs = (this.get(field.fieldname) as Doc[]) ?? []; setChildDocIdx(childDocs); } } async _validateDbNotModified() { if (this.notInserted || !this.name || this.schema.isSingle) { return; } const dbValues = await this.fyo.db.get(this.schemaName, this.name); const docModified = (this.modified as Date)?.toISOString(); const dbModified = (dbValues.modified as Date)?.toISOString(); if (dbValues && docModified !== dbModified) { throw new ConflictError( this.fyo .t`${this.schema.label} ${this.name} has been modified after loading please reload entry.` + ` ${dbModified}, ${docModified}` ); } } async runFormulas() { await this._applyFormula(); } async _applyFormula( changedFieldname?: string, retriggerChildDocApplyChange?: boolean ): Promise<boolean> { let changed = await this._callAllTableFieldsApplyFormula(changedFieldname); changed = (await this._applyFormulaForFields(this, changedFieldname)) || changed; if (changed && retriggerChildDocApplyChange) { await this._callAllTableFieldsApplyFormula(changedFieldname); await this._applyFormulaForFields(this, changedFieldname); } return changed; } async _callAllTableFieldsApplyFormula( changedFieldname?: string ): Promise<boolean> { let changed = false; for (const { fieldname } of this.tableFields) { const childDocs = this.get(fieldname) as Doc[]; if (!childDocs) { continue; } changed = (await this._callChildDocApplyFormula(childDocs, changedFieldname)) || changed; } return changed; } async _callChildDocApplyFormula( childDocs: Doc[], fieldname?: string ): Promise<boolean> { let changed = false; for (const childDoc of childDocs) { if (!childDoc._applyFormula) { continue; } changed = (await childDoc._applyFormula(fieldname)) || changed; } return changed; } async _applyFormulaForFields(doc: Doc, fieldname?: string) { const formulaFields = getFormulaSequence(this.formulas) .map((f) => this.fyo.getField(this.schemaName, f)) .filter(Boolean); let changed = false; for (const field of formulaFields) { const shouldApply = shouldApplyFormula(field, doc, fieldname); if (!shouldApply) { continue; } const newVal = await this._getValueFromFormula(field, doc, fieldname); const previousVal = doc.get(field.fieldname); const isSame = areDocValuesEqual(newVal as DocValue, previousVal); if (newVal === undefined || isSame) { continue; } doc[field.fieldname] = newVal; changed ||= true; } return changed; } async _getValueFromFormula(field: Field, doc: Doc, fieldname?: string) { const { formula } = doc.formulas[field.fieldname] ?? {}; if (formula === undefined) { return; } let value: FormulaReturn; try { value = await formula(fieldname); } catch { return; } if (Array.isArray(value) && field.fieldtype === FieldTypeEnum.Table) { value = value.map((row) => this._getChildDoc(row, field.fieldname)); } return value; } async _preSync() { this._setChildDocsIdx(); this._setChildDocsParent(); await this._applyFormula(); await this._validateSync(); await this.trigger('validate'); } async _insert() { this._setBaseMetaValues(); await this._preSync(); await setName(this, this.fyo); const validDict = this.getValidDict(false, true); let data: DocValueMap; try { data = await this.fyo.db.insert(this.schemaName, validDict); } catch (err) { throw await getDbSyncError(err as Error, this, this.fyo); } await this._syncValues(data); this.fyo.telemetry.log(Verb.Created, this.schemaName); return this; } async _update() { await this._validateDbNotModified(); this._updateModifiedMetaValues(); await this._preSync(); const data = this.getValidDict(false, true); try { await this.fyo.db.update(this.schemaName, data); } catch (err) { throw await getDbSyncError(err as Error, this, this.fyo); } await this._syncValues(data); return this; } async sync(): Promise<Doc> { this._syncing = true; await this.trigger('beforeSync'); let doc; if (this.notInserted) { doc = await this._insert(); } else { doc = await this._update(); } this._notInserted = false; await this.trigger('afterSync'); this.fyo.doc.observer.trigger(`sync:${this.schemaName}`, this.name); this._syncing = false; return doc; } async delete() { if (this.notInserted && this.name) { this.fyo.doc.removeFromCache(this.schemaName, this.name); } if (!this.canDelete) { return; } await this.trigger('beforeDelete'); await this.fyo.db.delete(this.schemaName, this.name!); await this.trigger('afterDelete'); this.fyo.telemetry.log(Verb.Deleted, this.schemaName); this.fyo.doc.observer.trigger(`delete:${this.schemaName}`, this.name); } async submit() { if (!this.schema.isSubmittable || this.submitted || this.cancelled) { return; } await this.trigger('beforeSubmit'); await this.setAndSync('submitted', true); await this.trigger('afterSubmit'); this.fyo.telemetry.log(Verb.Submitted, this.schemaName); this.fyo.doc.observer.trigger(`submit:${this.schemaName}`, this.name); } async cancel() { if (!this.schema.isSubmittable || !this.submitted || this.cancelled) { return; } await this.trigger('beforeCancel'); await this.setAndSync('cancelled', true); await this.trigger('afterCancel'); this.fyo.telemetry.log(Verb.Cancelled, this.schemaName); this.fyo.doc.observer.trigger(`cancel:${this.schemaName}`, this.name); } async rename(newName: string) { if (this.submitted) { return; } const oldName = this.name; await this.trigger('beforeRename', { oldName, newName }); await this.fyo.db.rename(this.schemaName, this.name!, newName); this.name = newName; await this.trigger('afterRename', { oldName, newName }); this.fyo.doc.observer.trigger(`rename:${this.schemaName}`, this.name); } async trigger(event: string, params?: unknown) { if (this[event]) { await (this[event] as (args: unknown) => Promise<void>)(params); } await super.trigger(event, params); } getSum(tablefield: string, childfield: string, convertToFloat = true) { const childDocs = (this.get(tablefield) as Doc[]) ?? []; const sum = childDocs .map((d) => { const value = d.get(childfield) ?? 0; if (!isPesa(value)) { try { return this.fyo.pesa(value as string | number); } catch (err) { (err as Error).message += ` value: '${String( value )}' of type: ${typeof value}, fieldname: '${tablefield}', childfield: '${childfield}'`; throw err; } } return value; }) .reduce((a, b) => a.add(b), this.fyo.pesa(0)); if (convertToFloat) { return sum.float; } return sum; } async setAndSync(fieldname: string | DocValueMap, value?: DocValue | Doc[]) { await this.set(fieldname, value); return await this.sync(); } duplicate(): Doc { const updateMap = this.getValidDict(true, true); for (const field in updateMap) { const value = updateMap[field]; if (!Array.isArray(value)) { continue; } for (const row of value) { delete row.name; } } if (this.numberSeries) { delete updateMap.name; } else { updateMap.name = String(updateMap.name) + ' CPY'; } const rawUpdateMap = this.fyo.db.converter.toRawValueMap( this.schemaName, updateMap ) as RawValueMap; return this.fyo.doc.getNewDoc(this.schemaName, rawUpdateMap, true); } /** * Lifecycle Methods * * Abstractish methods that are called using `this.trigger`. * These are to be overridden if required when subclassing. * * Refrain from running methods that call `this.sync` * in the `beforeLifecycle` methods. * * This may cause the lifecycle function to execute incorrectly. */ /* eslint-disable @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars */ async change(ch: ChangeArg) {} async validate() {} async beforeSync() {} async afterSync() {} async beforeSubmit() {} async afterSubmit() {} async beforeRename() {} async afterRename() {} async beforeCancel() {} async afterCancel() {} async beforeDelete() {} async afterDelete() {} formulas: FormulaMap = {}; validations: ValidationMap = {}; required: RequiredMap = {}; hidden: HiddenMap = {}; readOnly: ReadOnlyMap = {}; getCurrencies: CurrenciesMap = {}; static lists: ListsMap = {}; static filters: FiltersMap = {}; static createFilters: FiltersMap = {}; // Used by the *Create* dropdown option static defaults: DefaultMap = {}; static emptyMessages: EmptyMessageMap = {}; static getListViewSettings(fyo: Fyo): ListViewSettings { return {}; } static getTreeSettings(fyo: Fyo): TreeViewSettings | void { return; } static getActions(fyo: Fyo): Action[] { return []; } }
2302_79757062/books
fyo/model/doc.ts
TypeScript
agpl-3.0
26,463
import { Fyo } from 'fyo'; import { DuplicateEntryError, NotFoundError } from 'fyo/utils/errors'; import { DynamicLinkField, Field, FieldTypeEnum, TargetField, } from 'schemas/types'; import { Doc } from './doc'; type NotFoundDetails = { label: string; value: string }; export async function getDbSyncError( err: Error, doc: Doc, fyo: Fyo ): Promise<Error> { if (err.message.includes('UNIQUE constraint failed:')) { return getDuplicateEntryError(err, doc); } if (err.message.includes('FOREIGN KEY constraint failed')) { return getNotFoundError(err, doc, fyo); } return err; } function getDuplicateEntryError( err: Error, doc: Doc ): Error | DuplicateEntryError { const matches = err.message.match(/UNIQUE constraint failed:\s(\w+)\.(\w+)$/); if (!matches) { return err; } const schemaName = matches[1]; const fieldname = matches[2]; if (!schemaName || !fieldname) { return err; } const duplicateEntryError = new DuplicateEntryError(err.message, false); const validDict = doc.getValidDict(false, true); duplicateEntryError.stack = err.stack; duplicateEntryError.more = { schemaName, fieldname, value: validDict[fieldname], }; return duplicateEntryError; } async function getNotFoundError( err: Error, doc: Doc, fyo: Fyo ): Promise<NotFoundError> { const notFoundError = new NotFoundError(fyo.t`Cannot perform operation.`); notFoundError.stack = err.stack; notFoundError.more.message = err.message; const details = await getNotFoundDetails(doc, fyo); if (!details) { notFoundError.shouldStore = true; return notFoundError; } notFoundError.shouldStore = false; notFoundError.message = fyo.t`${details.label} value ${details.value} does not exist.`; return notFoundError; } async function getNotFoundDetails( doc: Doc, fyo: Fyo ): Promise<NotFoundDetails | null> { /** * Since 'FOREIGN KEY constraint failed' doesn't inform * how the operation failed, all Link and DynamicLink fields * must be checked for value existance so as to provide a * decent error message. */ for (const field of doc.schema.fields) { const details = await getNotFoundDetailsIfDoesNotExists(field, doc, fyo); if (details) { return details; } } return null; } async function getNotFoundDetailsIfDoesNotExists( field: Field, doc: Doc, fyo: Fyo ): Promise<NotFoundDetails | null> { const value = doc.get(field.fieldname); if (field.fieldtype === FieldTypeEnum.Link && value) { return getNotFoundLinkDetails(field, value as string, fyo); } if (field.fieldtype === FieldTypeEnum.DynamicLink && value) { return getNotFoundDynamicLinkDetails(field, value as string, fyo, doc); } if ( field.fieldtype === FieldTypeEnum.Table && (value as Doc[] | undefined)?.length ) { return await getNotFoundTableDetails(value as Doc[], fyo); } return null; } async function getNotFoundLinkDetails( field: TargetField, value: string, fyo: Fyo ): Promise<NotFoundDetails | null> { const { target } = field; const exists = await fyo.db.exists(target, value); if (!exists) { return { label: field.label, value }; } return null; } async function getNotFoundDynamicLinkDetails( field: DynamicLinkField, value: string, fyo: Fyo, doc: Doc ): Promise<NotFoundDetails | null> { const { references } = field; const target = doc.get(references); if (!target) { return null; } const exists = await fyo.db.exists(target as string, value); if (!exists) { return { label: field.label, value }; } return null; } async function getNotFoundTableDetails( value: Doc[], fyo: Fyo ): Promise<NotFoundDetails | null> { for (const childDoc of value) { const details = await getNotFoundDetails(childDoc, fyo); if (details) { return details; } } return null; }
2302_79757062/books
fyo/model/errorHelpers.ts
TypeScript
agpl-3.0
3,888
import { Fyo } from 'fyo'; import { DocValue } from 'fyo/core/types'; import { isPesa } from 'fyo/utils'; import { cloneDeep, isEqual } from 'lodash'; import { Field, FieldType, FieldTypeEnum } from 'schemas/types'; import { getIsNullOrUndef } from 'utils'; import { Doc } from './doc'; import { FormulaMap } from './types'; export function areDocValuesEqual( dvOne: DocValue | Doc[], dvTwo: DocValue | Doc[] ): boolean { if (['string', 'number'].includes(typeof dvOne) || dvOne instanceof Date) { return dvOne === dvTwo; } if (isPesa(dvOne)) { try { return dvOne.eq(dvTwo as string | number); } catch { return false; } } return isEqual(dvOne, dvTwo); } export function getPreDefaultValues( fieldtype: FieldType, fyo: Fyo ): DocValue | Doc[] { switch (fieldtype) { case FieldTypeEnum.Table: return [] as Doc[]; case FieldTypeEnum.Currency: return fyo.pesa(0.0); case FieldTypeEnum.Int: case FieldTypeEnum.Float: return 0; default: return null; } } export function getMissingMandatoryMessage(doc: Doc) { const mandatoryFields = getMandatory(doc); const message = mandatoryFields .filter((f) => { const value = doc.get(f.fieldname); const isNullOrUndef = getIsNullOrUndef(value); if (f.fieldtype === FieldTypeEnum.Table) { return isNullOrUndef || (value as Doc[])?.length === 0; } return isNullOrUndef || value === ''; }) .map((f) => f.label ?? f.fieldname) .join(', '); if (message && doc.schema.isChild && doc.parentdoc && doc.parentFieldname) { const parentfield = doc.parentdoc.fieldMap[doc.parentFieldname]; return `${parentfield.label} Row ${(doc.idx ?? 0) + 1}: ${message}`; } return message; } function getMandatory(doc: Doc): Field[] { const mandatoryFields: Field[] = []; for (const field of doc.schema.fields) { if (field.required) { mandatoryFields.push(field); } const requiredFunction = doc.required[field.fieldname]; if (requiredFunction?.()) { mandatoryFields.push(field); } } return mandatoryFields; } export function shouldApplyFormula(field: Field, doc: Doc, fieldname?: string) { if (!doc.formulas[field.fieldname]) { return false; } if (field.readOnly) { return true; } const { dependsOn } = doc.formulas[field.fieldname] ?? {}; if (dependsOn === undefined) { return true; } if (dependsOn.length === 0) { return false; } if (fieldname && dependsOn.includes(fieldname)) { return true; } if (doc.isSyncing && dependsOn.length > 0) { return shouldApplyFormulaPreSync(field.fieldname, dependsOn, doc); } const value = doc.get(field.fieldname); return getIsNullOrUndef(value); } function shouldApplyFormulaPreSync( fieldname: string, dependsOn: string[], doc: Doc ): boolean { if (isDocValueTruthy(doc.get(fieldname))) { return false; } for (const d of dependsOn) { const isSet = isDocValueTruthy(doc.get(d)); if (isSet) { return true; } } return false; } export function isDocValueTruthy(docValue: DocValue | Doc[]) { if (isPesa(docValue)) { return !docValue.isZero(); } if (Array.isArray(docValue)) { return docValue.length > 0; } return !!docValue; } export function setChildDocIdx(childDocs: Doc[]) { childDocs.forEach((cd, idx) => { cd.idx = idx; }); } export function getFormulaSequence(formulas: FormulaMap) { const depMap = Object.keys(formulas).reduce((acc, k) => { acc[k] = formulas[k]?.dependsOn; return acc; }, {} as Record<string, string[] | undefined>); return sequenceDependencies(cloneDeep(depMap)); } function sequenceDependencies( depMap: Record<string, string[] | undefined> ): string[] { /** * Sufficiently okay algo to sequence dependents after * their dependencies */ const keys = Object.keys(depMap); const independent = keys.filter((k) => !depMap[k]?.length); const dependent = keys.filter((k) => depMap[k]?.length); const keyset = new Set(independent); for (const k of dependent) { const deps = depMap[k] ?? []; deps.push(k); while (deps.length) { const d = deps.shift()!; if (keyset.has(d)) { continue; } keyset.add(d); } } return Array.from(keyset).filter((k) => k in depMap); }
2302_79757062/books
fyo/model/helpers.ts
TypeScript
agpl-3.0
4,367
import { Fyo } from 'fyo'; import NumberSeries from 'fyo/models/NumberSeries'; import { DEFAULT_SERIES_START } from 'fyo/utils/consts'; import { BaseError } from 'fyo/utils/errors'; import { getRandomString } from 'utils'; import { Doc } from './doc'; export function isNameAutoSet(schemaName: string, fyo: Fyo): boolean { const schema = fyo.schemaMap[schemaName]!; if (schema.naming === 'manual') { return false; } if (schema.naming === 'autoincrement') { return true; } if (schema.naming === 'random') { return true; } const numberSeries = fyo.getField(schema.name, 'numberSeries'); if (numberSeries) { return true; } return false; } export async function setName(doc: Doc, fyo: Fyo) { if (doc.schema.naming === 'manual') { return; } if (doc.schema.naming === 'autoincrement') { return (doc.name = await getNextId(doc.schemaName, fyo)); } if (doc.numberSeries !== undefined) { return (doc.name = await getSeriesNext( doc.numberSeries as string, doc.schemaName, fyo )); } // name === schemaName for Single if (doc.schema.isSingle) { return (doc.name = doc.schemaName); } // Assign a random name by default if (!doc.name) { doc.name = getRandomString(); } return doc.name; } export async function getNextId(schemaName: string, fyo: Fyo): Promise<string> { const lastInserted = await fyo.db.getLastInserted(schemaName); return String(lastInserted + 1).padStart(9, '0'); } export async function getSeriesNext( prefix: string, schemaName: string, fyo: Fyo ) { let series: NumberSeries; try { series = (await fyo.doc.getDoc('NumberSeries', prefix)) as NumberSeries; } catch (e) { const { statusCode } = e as BaseError; if (!statusCode || statusCode !== 404) { throw e; } await createNumberSeries(prefix, schemaName, DEFAULT_SERIES_START, fyo); series = (await fyo.doc.getDoc('NumberSeries', prefix)) as NumberSeries; } return await series.next(schemaName); } export async function createNumberSeries( prefix: string, referenceType: string, start: number, fyo: Fyo ) { const exists = await fyo.db.exists('NumberSeries', prefix); if (exists) { return; } const series = fyo.doc.getNewDoc('NumberSeries', { name: prefix, start, referenceType, }); await series.sync(); }
2302_79757062/books
fyo/model/naming.ts
TypeScript
agpl-3.0
2,373
import type { Fyo } from 'fyo'; import type { DocValue, DocValueMap } from 'fyo/core/types'; import type SystemSettings from 'fyo/models/SystemSettings'; import type { FieldType, Schema, SelectOption } from 'schemas/types'; import type { QueryFilter } from 'utils/db/types'; import type { RouteLocationRaw, Router } from 'vue-router'; import type { Doc } from './doc'; import type { AccountingSettings } from 'models/baseModels/AccountingSettings/AccountingSettings'; import type { Defaults } from 'models/baseModels/Defaults/Defaults'; import type { PrintSettings } from 'models/baseModels/PrintSettings/PrintSettings'; import type { InventorySettings } from 'models/inventory/InventorySettings'; import type { Misc } from 'models/baseModels/Misc'; import type { POSSettings } from 'models/inventory/Point of Sale/POSSettings'; import type { POSShift } from 'models/inventory/Point of Sale/POSShift'; /** * The functions below are used for dynamic evaluation * and setting of field types. * * Since they are set directly on the doc, they can * access the doc by using `this`. * * - `Formula`: Async function used for obtaining a computed value such as amount (rate * qty). * - `Default`: Regular function used to dynamically set the default value, example new Date(). * - `Validation`: Async function that throw an error if the value is invalid. * - `Required`: Regular function used to decide if a value is mandatory (there are !notnul in the db). */ export type FormulaReturn = DocValue | DocValueMap[] | undefined | Doc[]; export type Formula = (fieldname?: string) => Promise<FormulaReturn> | FormulaReturn; export type FormulaConfig = { dependsOn?: string[]; formula: Formula }; export type Default = (doc: Doc) => DocValue; export type Validation = (value: DocValue) => Promise<void> | void; export type Required = () => boolean; export type Hidden = () => boolean; export type ReadOnly = () => boolean; export type GetCurrency = () => string; export type FormulaMap = Record<string, FormulaConfig | undefined>; export type DefaultMap = Record<string, Default | undefined>; export type ValidationMap = Record<string, Validation | undefined>; export type RequiredMap = Record<string, Required | undefined>; export type CurrenciesMap = Record<string, GetCurrency | undefined>; export type HiddenMap = Record<string, Hidden | undefined>; export type ReadOnlyMap = Record<string, ReadOnly | undefined>; export type ChangeArg = { doc: Doc; changed: string }; /** * Should add this for hidden too */ export type ModelMap = Record<string, typeof Doc | undefined>; export type DocMap = Record<string, Doc | undefined>; export interface SinglesMap { SystemSettings?: SystemSettings; AccountingSettings?: AccountingSettings; InventorySettings?: InventorySettings; POSSettings?: POSSettings; POSShift?: POSShift; PrintSettings?: PrintSettings; Defaults?: Defaults; Misc?: Misc; [key: string]: Doc | undefined; } // Static Config properties export type FilterFunction = (doc: Doc) => QueryFilter | Promise<QueryFilter>; export type FiltersMap = Record<string, FilterFunction>; export type EmptyMessageFunction = (doc: Doc) => string; export type EmptyMessageMap = Record<string, EmptyMessageFunction>; export type ListFunction = (doc?: Doc) => string[] | SelectOption[]; export type ListsMap = Record<string, ListFunction | undefined>; export interface Action { label: string; action: (doc: Doc, router: Router) => Promise<void> | void | unknown; condition?: (doc: Doc) => boolean; group?: string; type?: 'primary' | 'secondary'; component?: { template: string; }; } export interface RenderData { schema: Schema, [key: string]: DocValue | Schema } export type ColumnConfig = { label: string; fieldtype: FieldType; fieldname: string; render?: (doc: RenderData) => { template: string }; display?: (value: unknown, fyo: Fyo) => string; } export type ListViewColumn = string | ColumnConfig; export interface ListViewSettings { formRoute?: (name: string) => RouteLocationRaw; columns?: ListViewColumn[]; } export interface TreeViewSettings { parentField: string; getRootLabel: () => Promise<string>; } export type DocStatus = | '' | 'Draft' | 'Saved' | 'NotSaved' | 'Submitted' | 'Cancelled'; export type LeadStatus = | '' | 'Open' | 'Replied' | 'Interested' | 'Opportunity' | 'Converted' | 'Quotation' | 'DonotContact'
2302_79757062/books
fyo/model/types.ts
TypeScript
agpl-3.0
4,428
import { DocValue } from 'fyo/core/types'; import { getOptionList } from 'fyo/utils'; import { ValidationError, ValueError } from 'fyo/utils/errors'; import { t } from 'fyo/utils/translation'; import { Field, OptionField } from 'schemas/types'; import { getIsNullOrUndef } from 'utils'; import { Doc } from './doc'; export function validateEmail(value: DocValue) { if (typeof value !== 'string') { throw new TypeError( `Invalid email ${String(value)} of type ${typeof value}` ); } const isValid = /(.+)@(.+){2,}\.(.+){2,}/.test(value); if (!isValid) { throw new ValidationError(`Invalid email: ${value}`); } } export function validatePhoneNumber(value: DocValue) { if (typeof value !== 'string') { throw new TypeError( `Invalid phone ${String(value)} of type ${typeof value}` ); } const isValid = /[+]{0,1}[\d ]+/.test(value); if (!isValid) { throw new ValidationError(`Invalid phone: ${value}`); } } export function validateOptions(field: OptionField, value: string, doc: Doc) { const options = getOptionList(field, doc); if (!options.length) { return; } if (!field.required && !value) { return; } const validValues = options.map((o) => o.value); if (validValues.includes(value) || field.allowCustom) { return; } throw new ValueError(t`Invalid value ${value} for ${field.label}`); } export function validateRequired(field: Field, value: DocValue, doc: Doc) { if (!getIsNullOrUndef(value)) { return; } if (field.required) { throw new ValidationError(`${field.label} is required`); } const requiredFunction = doc.required[field.fieldname]; if (requiredFunction && requiredFunction()) { throw new ValidationError(`${field.label} is required`); } }
2302_79757062/books
fyo/model/validationFunction.ts
TypeScript
agpl-3.0
1,770
import { DocValue } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import type { FormulaMap, HiddenMap, ListsMap, RequiredMap, ValidationMap, } from 'fyo/model/types'; import { ValueError } from 'fyo/utils/errors'; import { camelCase } from 'lodash'; import { ModelNameEnum } from 'models/types'; import type { FieldType } from 'schemas/types'; import { FieldTypeEnum } from 'schemas/types'; import type { CustomForm } from './CustomForm'; export class CustomField extends Doc { parentdoc?: CustomForm; label?: string; fieldname?: string; fieldtype?: FieldType; isRequired?: boolean; section?: string; tab?: string; options?: string; target?: string; references?: string; get parentSchema() { return this.parentdoc?.parentSchema ?? null; } get parentFields() { return this.parentdoc?.parentFields; } formulas: FormulaMap = { fieldname: { formula: () => { if (!this.label?.length) { return; } return camelCase(this.label); }, dependsOn: ['label'], }, }; hidden: HiddenMap = { options: () => this.fieldtype !== 'Select' && this.fieldtype !== 'AutoComplete' && this.fieldtype !== 'Color', target: () => this.fieldtype !== 'Link' && this.fieldtype !== 'Table', references: () => this.fieldtype !== 'DynamicLink', }; validations: ValidationMap = { label: (value) => { if (typeof value !== 'string') { return; } const fieldname = camelCase(value); (this.validations.fieldname as (value: DocValue) => void)(fieldname); }, fieldname: (value) => { if (typeof value !== 'string') { return; } const field = this.parentFields?.[value]; if (field && !field.isCustom) { throw new ValueError( this.fyo.t`Fieldname ${value} already exists for ${this.parentdoc! .name!}` ); } const cf = this.parentdoc?.customFields?.find( (cf) => cf.fieldname === value ); if (cf) { throw new ValueError( this.fyo.t`Fieldname ${value} already used for Custom Field ${ (cf.idx ?? 0) + 1 }` ); } }, }; static lists: ListsMap = { target: (doc) => { const schemaMap = doc?.fyo.schemaMap ?? {}; return Object.values(schemaMap) .filter( (s) => !s?.isSingle && ![ ModelNameEnum.PatchRun, ModelNameEnum.SingleValue, ModelNameEnum.CustomField, ModelNameEnum.CustomForm, ModelNameEnum.SetupWizard, ].includes(s?.name as ModelNameEnum) ) .map((s) => ({ label: s?.label ?? '', value: s?.name ?? '', })); }, references: (doc) => { if (!(doc instanceof CustomField)) { return []; } const referenceType: string[] = [ FieldTypeEnum.AutoComplete, FieldTypeEnum.Data, FieldTypeEnum.Text, FieldTypeEnum.Select, ]; const customFields = doc.parentdoc?.customFields ?.filter( (cf) => cf.fieldname && cf.label && referenceType.includes(cf.fieldtype ?? '') ) ?.map((cf) => ({ value: cf.fieldname!, label: cf.label! })) ?? []; const schemaFields = doc.parentSchema?.fields .filter( (f) => f.fieldname && f.label && referenceType.includes(f.fieldtype) ) .map((f) => ({ value: f.fieldname, label: f.label })) ?? []; return [customFields, schemaFields].flat(); }, }; required: RequiredMap = { options: () => this.fieldtype === 'Select' || this.fieldtype === 'AutoComplete', target: () => this.fieldtype === 'Link' || this.fieldtype === 'Table', references: () => this.fieldtype === 'DynamicLink', default: () => !!this.isRequired, }; }
2302_79757062/books
fyo/models/CustomField.ts
TypeScript
agpl-3.0
4,007
import { Doc } from 'fyo/model/doc'; import { HiddenMap, ListsMap } from 'fyo/model/types'; import { ValidationError } from 'fyo/utils/errors'; import { ModelNameEnum } from 'models/types'; import { Field } from 'schemas/types'; import { getMapFromList } from 'utils/index'; import { CustomField } from './CustomField'; export class CustomForm extends Doc { name?: string; customFields?: CustomField[]; get parentSchema() { return this.fyo.schemaMap[this.name ?? ''] ?? null; } get parentFields(): Record<string, Field> { const fields = this.parentSchema?.fields; if (!fields) { return {}; } return getMapFromList(fields, 'fieldname'); } static lists: ListsMap = { name: (doc) => Object.values(doc?.fyo.schemaMap ?? {}) .filter((s) => { if (!s || !s.label || !s.name) { return false; } if (s.isSingle) { return false; } return ![ ModelNameEnum.PatchRun, ModelNameEnum.SingleValue, ModelNameEnum.CustomField, ModelNameEnum.CustomForm, ModelNameEnum.SetupWizard, ].includes(s.name as ModelNameEnum); }) .map((s) => ({ value: s!.name, label: s!.label, })), }; hidden: HiddenMap = { customFields: () => !this.name }; // eslint-disable-next-line @typescript-eslint/require-await override async validate(): Promise<void> { for (const row of this.customFields ?? []) { if (row.fieldtype === 'Select' || row.fieldtype === 'AutoComplete') { this.validateOptions(row); } } } validateOptions(row: CustomField) { const optionString = row.options ?? ''; const options = optionString .split('\n') .map((s) => s.trim()) .filter(Boolean); if (options.length > 1) { return; } throw new ValidationError( `At least two options need to be set for the selected fieldtype` ); } }
2302_79757062/books
fyo/models/CustomForm.ts
TypeScript
agpl-3.0
2,012
import { Doc } from 'fyo/model/doc'; import { ReadOnlyMap, ValidationMap } from 'fyo/model/types'; import { ValidationError } from 'fyo/utils/errors'; const invalidNumberSeries = /[/\=\?\&\%]/; function getPaddedName(prefix: string, next: number, padZeros: number): string { return prefix + next.toString().padStart(padZeros ?? 4, '0'); } export default class NumberSeries extends Doc { validations: ValidationMap = { name: (value) => { if (typeof value !== 'string') { return; } if (invalidNumberSeries.test(value)) { throw new ValidationError( this.fyo .t`The following characters cannot be used ${'/, ?, &, =, %'} in a Number Series name.` ); } }, }; setCurrent() { let current = this.get('current') as number | null; /** * Increment current if it isn't the first entry. This * is to prevent reassignment of NumberSeries document ids. */ if (!current) { current = this.get('start') as number; } else { current = current + 1; } this.current = current; } async next(schemaName: string) { this.setCurrent(); const exists = await this.checkIfCurrentExists(schemaName); if (exists) { this.current = (this.current as number) + 1; } await this.sync(); return this.getPaddedName(this.current as number); } async checkIfCurrentExists(schemaName: string) { if (!schemaName) { return true; } const name = this.getPaddedName(this.current as number); return await this.fyo.db.exists(schemaName, name); } getPaddedName(next: number): string { return getPaddedName(this.name as string, next, this.padZeros as number); } readOnly: ReadOnlyMap = { referenceType: () => this.inserted, padZeros: () => this.inserted, start: () => this.inserted, }; }
2302_79757062/books
fyo/models/NumberSeries.ts
TypeScript
agpl-3.0
1,872
import { DocValue } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { ListsMap, ValidationMap } from 'fyo/model/types'; import { ValidationError } from 'fyo/utils/errors'; import { t } from 'fyo/utils/translation'; import { SelectOption } from 'schemas/types'; import { getCountryInfo } from 'utils/misc'; export default class SystemSettings extends Doc { dateFormat?: string; locale?: string; displayPrecision?: number; internalPrecision?: number; hideGetStarted?: boolean; countryCode?: string; currency?: string; version?: string; instanceId?: string; validations: ValidationMap = { displayPrecision(value: DocValue) { if ((value as number) >= 0 && (value as number) <= 9) { return; } throw new ValidationError( t`Display Precision should have a value between 0 and 9.` ); }, }; static lists: ListsMap = { locale() { const countryInfo = getCountryInfo(); return Object.keys(countryInfo) .filter((c) => !!countryInfo[c]?.locale) .map( (c) => ({ value: countryInfo[c]?.locale, label: `${c} (${countryInfo[c]?.locale ?? t`Not Found`})`, } as SelectOption) ); }, currency() { const countryInfo = getCountryInfo(); const currencies = Object.values(countryInfo) .map((ci) => ci?.currency as string) .filter(Boolean); return [...new Set(currencies)]; }, }; }
2302_79757062/books
fyo/models/SystemSettings.ts
TypeScript
agpl-3.0
1,500
import { ModelMap } from 'fyo/model/types'; import NumberSeries from './NumberSeries'; import SystemSettings from './SystemSettings'; import { CustomField } from './CustomField'; import { CustomForm } from './CustomForm'; export const coreModels = { NumberSeries, SystemSettings, CustomForm, CustomField, } as ModelMap;
2302_79757062/books
fyo/models/index.ts
TypeScript
agpl-3.0
329
import { Fyo } from 'fyo'; import { Noun, Telemetry, Verb } from './types'; import { ModelNameEnum } from 'models/types'; /** * # Telemetry * Used to check if people are using Books or not. All logging * happens using navigator.sendBeacon * * ## `start` * Used to initialize state. It should be called before any logging and after an * instance has loaded. * It is called on three events: * 1. When Desk is opened, i.e. when the usage starts, this also sends a * Opened instance log. * 2. On visibility change if not started, eg: when user minimizes Books and * then comes back later. * 3. When `log` is called, but telemetry isn't initialized. * * ## `log` * Used to log activity. * * ## `stop` * This is to be called when a session is being stopped. It's called on two events * 1. When the db is being changed. * 2. When the visiblity has changed which happens when either the app is being shut or * the app is hidden. */ const ignoreList: string[] = [ ModelNameEnum.AccountingLedgerEntry, ModelNameEnum.StockLedgerEntry, ]; export class TelemetryManager { #url = ''; #token = ''; #started = false; fyo: Fyo; constructor(fyo: Fyo) { this.fyo = fyo; } get hasCreds() { return !!this.#url && !!this.#token; } get started() { return this.#started; } async start(isOpened?: boolean) { this.#started = true; await this.#setCreds(); if (isOpened) { this.log(Verb.Opened, 'instance'); } else { this.log(Verb.Resumed, 'instance'); } } stop() { if (!this.started) { return; } this.log(Verb.Closed, 'instance'); this.#started = false; } log(verb: Verb, noun: Noun, more?: Record<string, unknown>) { if (!this.#started && this.fyo.db.isConnected) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.start().then(() => this.#sendBeacon(verb, noun, more)); return; } this.#sendBeacon(verb, noun, more); } async logOpened() { await this.#setCreds(); this.#sendBeacon(Verb.Opened, 'app'); } #sendBeacon(verb: Verb, noun: Noun, more?: Record<string, unknown>) { if ( !this.hasCreds || this.fyo.store.skipTelemetryLogging || ignoreList.includes(noun) ) { return; } const telemetryData: Telemetry = this.#getTelemtryData(verb, noun, more); const data = JSON.stringify({ token: this.#token, telemetryData, }); navigator.sendBeacon(this.#url, data); } async #setCreds() { if (this.hasCreds) { return; } const { telemetryUrl, tokenString } = await this.fyo.auth.getCreds(); this.#url = telemetryUrl; this.#token = tokenString; } #getTelemtryData( verb: Verb, noun: Noun, more?: Record<string, unknown> ): Telemetry { const countryCode = this.fyo.singles.SystemSettings?.countryCode; return { country: countryCode ?? '', language: this.fyo.store.language, deviceId: this.fyo.store.deviceId || (this.fyo.config.get('deviceId') ?? '-'), instanceId: this.fyo.store.instanceId, version: this.fyo.store.appVersion, openCount: this.fyo.store.openCount, timestamp: new Date().toISOString().replace('T', ' ').slice(0, -1), platform: this.fyo.store.platform, verb, noun, more, }; } }
2302_79757062/books
fyo/telemetry/telemetry.ts
TypeScript
agpl-3.0
3,381
export type AppVersion = string; export type UniqueId = string; export type Timestamp = string; export enum Verb { Started = 'started', Completed = 'completed', Created = 'created', Deleted = 'deleted', Submitted = 'submitted', Cancelled = 'cancelled', Imported = 'imported', Exported = 'exported', Printed = 'printed', Closed = 'closed', Opened = 'opened', Resumed = 'resumed', } export type Noun = string; export interface Telemetry { deviceId: UniqueId; instanceId: UniqueId; platform?: string; country: string; language: string; version: AppVersion; timestamp: Timestamp; openCount: number; verb: Verb; noun: Noun; more?: Record<string, unknown>; }
2302_79757062/books
fyo/telemetry/types.ts
TypeScript
agpl-3.0
702
import { AuthDemuxBase } from 'utils/auth/types'; import { Creds } from 'utils/types'; export class DummyAuthDemux extends AuthDemuxBase { // eslint-disable-next-line @typescript-eslint/require-await async getCreds(): Promise<Creds> { return { errorLogUrl: '', tokenString: '', telemetryUrl: '' }; } }
2302_79757062/books
fyo/tests/helpers.ts
TypeScript
agpl-3.0
313
export default class CacheManager { _keyValueCache: Map<string, unknown | undefined>; _hashCache: Map<string, Map<string, unknown> | undefined>; constructor() { this._keyValueCache = new Map(); this._hashCache = new Map(); } // Regular Cache Ops getValue(key: string) { return this._keyValueCache.get(key); } setValue(key: string, value: unknown) { this._keyValueCache.set(key, value); } clearValue(key: string) { this._keyValueCache.delete(key); } // Hash Cache Ops hget(hashName: string, key: string) { const hc = this._hashCache.get(hashName); if (hc === undefined) { return hc; } return hc.get(key); } hset(hashName: string, key: string, value: unknown) { const hc = this._hashCache.get(hashName); if (hc === undefined) { this._hashCache.set(hashName, new Map()); } this._hashCache.get(hashName)!.set(key, value); } hclear(hashName: string, key?: string) { if (key) { this._hashCache.get(hashName)?.delete(key); } else { this._hashCache.get(hashName)?.clear(); } } hexists(hashName: string) { return this._hashCache.get(hashName) !== undefined; } }
2302_79757062/books
fyo/utils/cacheManager.ts
TypeScript
agpl-3.0
1,194
export const DEFAULT_INTERNAL_PRECISION = 11; export const DEFAULT_DISPLAY_PRECISION = 2; export const DEFAULT_DATE_FORMAT = 'MMM d, y'; export const DEFAULT_LOCALE = 'en-IN'; export const DEFAULT_COUNTRY_CODE = 'in'; export const DEFAULT_CURRENCY = 'INR'; export const DEFAULT_LANGUAGE = 'English'; export const DEFAULT_SERIES_START = 1001; export const DEFAULT_USER = 'Admin'; export const RTL_LANGUAGES = [ 'Arabic', 'Aramaic', 'Azeri', 'Dhivehi', 'Maldivian', 'Hebrew', 'Kurdish', 'Sorani', 'Persian', 'Farsi', 'Urdu', ];
2302_79757062/books
fyo/utils/consts.ts
TypeScript
agpl-3.0
548
export class BaseError extends Error { more: Record<string, unknown> = {}; message: string; statusCode: number; shouldStore: boolean; constructor(statusCode: number, message: string, shouldStore = true) { super(message); this.name = 'BaseError'; this.statusCode = statusCode; this.message = message; this.shouldStore = shouldStore; } } export class ValidationError extends BaseError { constructor(message: string, shouldStore = false) { super(417, message, shouldStore); this.name = 'ValidationError'; } } export class NotFoundError extends BaseError { constructor(message: string, shouldStore = true) { super(404, message, shouldStore); this.name = 'NotFoundError'; } } export class ForbiddenError extends BaseError { constructor(message: string, shouldStore = true) { super(403, message, shouldStore); this.name = 'ForbiddenError'; } } export class DuplicateEntryError extends ValidationError { constructor(message: string, shouldStore = false) { super(message, shouldStore); this.name = 'DuplicateEntryError'; } } export class LinkValidationError extends ValidationError { constructor(message: string, shouldStore = false) { super(message, shouldStore); this.name = 'LinkValidationError'; } } export class MandatoryError extends ValidationError { constructor(message: string, shouldStore = false) { super(message, shouldStore); this.name = 'MandatoryError'; } } export class DatabaseError extends BaseError { constructor(message: string, shouldStore = true) { super(500, message, shouldStore); this.name = 'DatabaseError'; } } export class CannotCommitError extends DatabaseError { constructor(message: string, shouldStore = true) { super(message, shouldStore); this.name = 'CannotCommitError'; } } export class NotImplemented extends BaseError { constructor(message = '', shouldStore = false) { super(501, message, shouldStore); this.name = 'NotImplemented'; } } export class ValueError extends ValidationError {} export class ConflictError extends ValidationError {} export class InvalidFieldError extends ValidationError {} export function getDbError(err: Error) { if (!err.message) { return DatabaseError; } if (err.message.includes('SQLITE_ERROR: no such table')) { return NotFoundError; } if (err.message.includes('FOREIGN KEY')) { return LinkValidationError; } if (err.message.includes('SQLITE_ERROR: cannot commit')) { return CannotCommitError; } if (err.message.includes('UNIQUE constraint failed:')) { return DuplicateEntryError; } return DatabaseError; }
2302_79757062/books
fyo/utils/errors.ts
TypeScript
agpl-3.0
2,668
import { Fyo } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { DateTime } from 'luxon'; import { Field, FieldType, FieldTypeEnum } from 'schemas/types'; import { getIsNullOrUndef, safeParseFloat, titleCase } from 'utils'; import { isPesa } from '.'; import { DEFAULT_CURRENCY, DEFAULT_DATE_FORMAT, DEFAULT_DISPLAY_PRECISION, DEFAULT_LOCALE, } from './consts'; export function format( value: unknown, df: string | Field | null, doc: Doc | null, fyo: Fyo ): string { if (!df) { return String(value); } const field: Field = getField(df); if (field.fieldtype === FieldTypeEnum.Float) { return Number(value).toFixed(fyo.singles.SystemSettings?.displayPrecision); } if (field.fieldtype === FieldTypeEnum.Int) { return Math.trunc(Number(value)).toString(); } if (field.fieldtype === FieldTypeEnum.Currency) { return formatCurrency(value, field, doc, fyo); } if (field.fieldtype === FieldTypeEnum.Date) { return formatDate(value, fyo); } if (field.fieldtype === FieldTypeEnum.Datetime) { return formatDatetime(value, fyo); } if (field.fieldtype === FieldTypeEnum.Check) { return titleCase(Boolean(value).toString()); } if (getIsNullOrUndef(value)) { return ''; } return String(value); } function toDatetime(value: unknown): DateTime | null { if (typeof value === 'string') { return DateTime.fromISO(value); } else if (value instanceof Date) { return DateTime.fromJSDate(value); } else if (typeof value === 'number') { return DateTime.fromSeconds(value); } return null; } function formatDatetime(value: unknown, fyo: Fyo): string { if (value == null) { return ''; } const dateFormat = (fyo.singles.SystemSettings?.dateFormat as string) ?? DEFAULT_DATE_FORMAT; const dateTime = toDatetime(value); if (!dateTime) { return ''; } const formattedDatetime = dateTime.toFormat(`${dateFormat} HH:mm:ss`); if (value === 'Invalid DateTime') { return ''; } return formattedDatetime; } function formatDate(value: unknown, fyo: Fyo): string { if (value == null) { return ''; } const dateFormat = (fyo.singles.SystemSettings?.dateFormat as string) ?? DEFAULT_DATE_FORMAT; const dateTime = toDatetime(value); if (!dateTime) { return ''; } const formattedDate = dateTime.toFormat(dateFormat); if (value === 'Invalid DateTime') { return ''; } return formattedDate; } function formatCurrency( value: unknown, field: Field, doc: Doc | null, fyo: Fyo ): string { const currency = getCurrency(field, doc, fyo); let valueString; try { valueString = formatNumber(value, fyo); } catch (err) { (err as Error).message += ` value: '${String( value )}', type: ${typeof value}`; throw err; } const currencySymbol = fyo.currencySymbols[currency]; if (currencySymbol !== undefined) { return currencySymbol + ' ' + valueString; } return valueString; } function formatNumber(value: unknown, fyo: Fyo): string { const numberFormatter = getNumberFormatter(fyo); if (typeof value === 'number') { value = fyo.pesa(value.toFixed(20)); } if (isPesa(value)) { const floatValue = safeParseFloat(value.round()); return numberFormatter.format(floatValue); } const floatValue = safeParseFloat(value as string); const formattedNumber = numberFormatter.format(floatValue); if (formattedNumber === 'NaN') { throw Error( `invalid value passed to formatNumber: '${String( value )}' of type ${typeof value}` ); } return formattedNumber; } function getNumberFormatter(fyo: Fyo) { if (fyo.currencyFormatter) { return fyo.currencyFormatter; } const locale = (fyo.singles.SystemSettings?.locale as string) ?? DEFAULT_LOCALE; const display = (fyo.singles.SystemSettings?.displayPrecision as number) ?? DEFAULT_DISPLAY_PRECISION; return (fyo.currencyFormatter = Intl.NumberFormat(locale, { style: 'decimal', minimumFractionDigits: display, })); } function getCurrency(field: Field, doc: Doc | null, fyo: Fyo): string { const defaultCurrency = fyo.singles.SystemSettings?.currency ?? DEFAULT_CURRENCY; let getCurrency = doc?.getCurrencies?.[field.fieldname]; if (getCurrency !== undefined) { return getCurrency(); } getCurrency = doc?.parentdoc?.getCurrencies[field.fieldname]; if (getCurrency !== undefined) { return getCurrency(); } return defaultCurrency; } function getField(df: string | Field): Field { if (typeof df === 'string') { return { label: '', fieldname: '', fieldtype: df as FieldType, } as Field; } return df; }
2302_79757062/books
fyo/utils/format.ts
TypeScript
agpl-3.0
4,698
import { Fyo } from 'fyo'; import { DocValue } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { Action } from 'fyo/model/types'; import { Money } from 'pesa'; import { Field, FieldType, OptionField, SelectOption } from 'schemas/types'; import { getIsNullOrUndef, safeParseInt } from 'utils'; export function slug(str: string) { return str .replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) => { return index == 0 ? letter.toLowerCase() : letter.toUpperCase(); }) .replace(/\s+/g, ''); } export function unique<T>(list: T[], key = (it: T) => String(it)) { const seen: Record<string, boolean> = {}; return list.filter((item) => { const k = key(item); return seen.hasOwnProperty(k) ? false : (seen[k] = true); }); } export function getDuplicates(array: unknown[]) { const duplicates: unknown[] = []; for (let i = 0; i < array.length; i++) { const previous = array[safeParseInt(i) - 1]; const current = array[i]; if (current === previous) { if (!duplicates.includes(current)) { duplicates.push(current); } } } return duplicates; } export function isPesa(value: unknown): value is Money { return value instanceof Money; } export function isFalsy(value: unknown): boolean { if (!value) { return true; } if (isPesa(value) && value.isZero()) { return true; } if (Array.isArray(value) && value.length === 0) { return true; } if (typeof value === 'object' && Object.keys(value).length === 0) { return true; } return false; } export function getActions(doc: Doc): Action[] { const Model = doc.fyo.models[doc.schemaName]; if (Model === undefined) { return []; } return Model.getActions(doc.fyo); } export async function getSingleValue( fieldname: string, parent: string, fyo: Fyo ) { if (!fyo.db.isConnected) { return undefined; } const res = await fyo.db.getSingleValues({ fieldname, parent }); const singleValue = res.find( (f) => f.fieldname === fieldname && f.parent === parent ); if (singleValue === undefined) { return undefined; } return singleValue.value; } export function getOptionList( field: Field, doc: Doc | undefined | null ): SelectOption[] { const list = getRawOptionList(field, doc); return list.map((option) => { if (typeof option === 'string') { return { label: option, value: option, }; } return option; }); } function getRawOptionList(field: Field, doc: Doc | undefined | null) { const options = (field as OptionField).options; if (options && options.length > 0) { return (field as OptionField).options; } if (getIsNullOrUndef(doc)) { return []; } const Model = doc.fyo.models[doc.schemaName]; if (Model === undefined) { return []; } const getList = Model.lists[field.fieldname]; if (getList === undefined) { return []; } return getList(doc); } export function getEmptyValuesByFieldTypes( fieldtype: FieldType, fyo: Fyo ): DocValue { switch (fieldtype) { case 'Date': case 'Datetime': return new Date(); case 'Float': case 'Int': return 0; case 'Currency': return fyo.pesa(0); case 'Check': return false; case 'DynamicLink': case 'Link': case 'Select': case 'AutoComplete': case 'Text': case 'Data': case 'Color': return null; case 'Table': case 'Attachment': case 'AttachImage': default: return null; } }
2302_79757062/books
fyo/utils/index.ts
TypeScript
agpl-3.0
3,519
enum EventType { Listeners = '_listeners', OnceListeners = '_onceListeners', } // eslint-disable-next-line @typescript-eslint/no-explicit-any type Listener = (...args: any[]) => unknown | Promise<unknown>; export default class Observable<T> { [key: string]: unknown | T; _isHot: Map<string, boolean>; _eventQueue: Map<string, unknown[]>; _map: Map<string, unknown>; _listeners: Map<string, Listener[]>; _onceListeners: Map<string, Listener[]>; constructor() { this._map = new Map(); this._isHot = new Map(); this._eventQueue = new Map(); this._listeners = new Map(); this._onceListeners = new Map(); } /** * Getter to use Observable as a regular document. * * @param key * @returns */ get(key: string): T { return this[key] as T; } /** * Setter to use Observable as a regular document. * * @param key * @param value */ set(key: string, value: T) { this[key] = value; // eslint-disable-next-line @typescript-eslint/no-floating-promises this.trigger('change', { doc: this, changed: key, }); } /** * Checks if any `listener` or the given `listener` has been registered * for the passed `event`. * * @param event : name of the event for which the listener is checked * @param listener : specific listener that is checked for */ hasListener(event: string, listener?: Listener) { const listeners = this[EventType.Listeners].get(event) ?? []; const onceListeners = this[EventType.OnceListeners].get(event) ?? []; if (listener === undefined) { return [...listeners, ...onceListeners].length > 0; } let has = listeners.includes(listener); has ||= onceListeners.includes(listener); return has; } /** * Sets a `listener` that executes every time `event` is triggered * * @param event : name of the event for which the listener is set * @param listener : listener that is executed when the event is triggered */ on(event: string, listener: Listener) { this._addListener(EventType.Listeners, event, listener); } /** * Sets a `listener` that execture `once`: executes once when `event` is * triggered then deletes itself * * @param event : name of the event for which the listener is set * @param listener : listener that is executed when the event is triggered */ once(event: string, listener: Listener) { this._addListener(EventType.OnceListeners, event, listener); } /** * Remove a listener from an event for both 'on' and 'once' * * @param event : name of the event from which to remove the listener * @param listener : listener that was set for the event */ off(event: string, listener: Listener) { this._removeListener(EventType.Listeners, event, listener); this._removeListener(EventType.OnceListeners, event, listener); } /** * Remove all the listeners. */ clear() { this._listeners.clear(); this._onceListeners.clear(); } /** * Triggers the event's listener function. * * @param event : name of the event to be triggered. * @param params : params to pass to the listeners. * @param throttle : wait time before triggering the event. */ async trigger(event: string, params?: unknown, throttle = 0) { let isHot = false; if (throttle > 0) { isHot = this._throttled(event, params, throttle); params = [params]; } if (isHot) { return; } await this._executeTriggers(event, params); } _removeListener(type: EventType, event: string, listener: Listener) { const listeners = (this[type].get(event) ?? []).filter( (l) => l !== listener ); this[type].set(event, listeners); } async _executeTriggers(event: string, params?: unknown) { await this._triggerEvent(EventType.Listeners, event, params); await this._triggerEvent(EventType.OnceListeners, event, params); this._onceListeners.delete(event); } _throttled(event: string, params: unknown, throttle: number) { /** * Throttled events execute after `throttle` ms, during this period * isHot is true, i.e it's going to execute. */ if (!this._eventQueue.has(event)) { this._eventQueue.set(event, []); } if (this._isHot.get(event)) { this._eventQueue.get(event)!.push(params); return true; } this._isHot.set(event, true); setTimeout(() => { this._isHot.set(event, false); const params = this._eventQueue.get(event); if (params !== undefined) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this._executeTriggers(event, params); this._eventQueue.delete(event); } }, throttle); return false; } _addListener(type: EventType, event: string, listener: Listener) { this._initLiseners(type, event); const list = this[type].get(event)!; if (list.includes(listener)) { return; } list.push(listener); } _initLiseners(type: EventType, event: string) { if (this[type].has(event)) { return; } this[type].set(event, []); } async _triggerEvent(type: EventType, event: string, params?: unknown) { const listeners = this[type].get(event) ?? []; for (const listener of listeners) { await listener(params); } } }
2302_79757062/books
fyo/utils/observable.ts
TypeScript
agpl-3.0
5,349
import { LanguageMap, UnknownMap } from 'utils/types'; import { getIndexFormat, getIndexList, getSnippets, getWhitespaceSanitized, } from '../../utils/translationHelpers'; import { ValueError } from './errors'; export type TranslationArgs = boolean | number | string; export type TranslationLiteral = TemplateStringsArray | TranslationArgs; export class TranslationString { args: TranslationLiteral[]; argList?: TranslationArgs[]; strList?: string[]; context?: string; languageMap?: LanguageMap; constructor(...args: TranslationLiteral[]) { this.args = args; } get s() { return this.toString(); } ctx(context?: string) { this.context = context; return this; } #formatArg(arg: string | number | boolean) { return String(arg ?? ''); } #translate() { let indexFormat = getIndexFormat(this.args[0] as string); indexFormat = getWhitespaceSanitized(indexFormat); const translatedIndexFormat = this.languageMap![indexFormat]?.translation ?? indexFormat; this.argList = getIndexList(translatedIndexFormat).map( (i) => this.argList![i] ); this.strList = getSnippets(translatedIndexFormat); } #stitch() { if (!((this.args[0] as unknown) instanceof Array)) { throw new ValueError( `invalid args passed to TranslationString ${String( this.args )} of type ${typeof this.args[0]}` ); } this.strList = this.args[0] as unknown as string[]; this.argList = this.args.slice(1) as TranslationArgs[]; if (this.languageMap) { this.#translate(); } return this.strList .map((s, i) => s + this.#formatArg(this.argList![i])) .join('') .replace(/\s+/g, ' ') .trim(); } toString() { return this.#stitch(); } toJSON() { return this.#stitch(); } valueOf() { return this.#stitch(); } } export function T(...args: string[]): TranslationString { return new TranslationString(...args); } export function t(...args: TranslationLiteral[]): string { return new TranslationString(...args).s; } export function setLanguageMapOnTranslationString( languageMap: LanguageMap | undefined ) { TranslationString.prototype.languageMap = languageMap; } export function translateSchema( map: UnknownMap | UnknownMap[], languageMap: LanguageMap, translateables: string[] ) { if (Array.isArray(map)) { for (const item of map) { translateSchema(item, languageMap, translateables); } return; } if (typeof map !== 'object') { return; } for (const key of Object.keys(map)) { const value = map[key]; if ( typeof value === 'string' && translateables.includes(key) && languageMap[value]?.translation ) { map[key] = languageMap[value].translation; } if (typeof value !== 'object') { continue; } translateSchema( value as UnknownMap | UnknownMap[], languageMap, translateables ); } }
2302_79757062/books
fyo/utils/translation.ts
TypeScript
agpl-3.0
2,994
export interface ErrorLog { name: string; message: string; stack?: string; more?: Record<string, unknown>; }
2302_79757062/books
fyo/utils/types.ts
TypeScript
agpl-3.0
117
import { app } from 'electron'; import fs from 'fs'; import fetch from 'node-fetch'; import path from 'path'; import { Creds } from 'utils/types'; import { rendererLog } from './helpers'; import type { Main } from 'main'; export function getUrlAndTokenString(): Creds { const inProduction = app.isPackaged; const empty: Creds = { errorLogUrl: '', telemetryUrl: '', tokenString: '' }; let errLogCredsPath = path.join( process.resourcesPath, '../creds/log_creds.txt' ); if (!fs.existsSync(errLogCredsPath)) { errLogCredsPath = path.join(__dirname, '..', '..', 'log_creds.txt'); } if (!fs.existsSync(errLogCredsPath)) { // eslint-disable-next-line no-console !inProduction && console.log(`${errLogCredsPath} doesn't exist, can't log`); return empty; } let apiKey, apiSecret, errorLogUrl, telemetryUrl; try { [apiKey, apiSecret, errorLogUrl, telemetryUrl] = fs .readFileSync(errLogCredsPath, 'utf-8') .split('\n') .filter((f) => f.length); } catch (err) { if (!inProduction) { // eslint-disable-next-line no-console console.log(`logging error using creds at: ${errLogCredsPath} failed`); // eslint-disable-next-line no-console console.log(err); } return empty; } return { errorLogUrl: encodeURI(errorLogUrl), telemetryUrl: encodeURI(telemetryUrl), tokenString: `token ${apiKey}:${apiSecret}`, }; } export async function sendError(body: string, main: Main) { const { errorLogUrl, tokenString } = getUrlAndTokenString(); const headers = { Authorization: tokenString, Accept: 'application/json', 'Content-Type': 'application/json', }; await fetch(errorLogUrl, { method: 'POST', headers, body }).catch((err) => { rendererLog(main, err); }); }
2302_79757062/books
main/contactMothership.ts
TypeScript
agpl-3.0
1,789
/** * Language files are packaged into the binary, if * newer files are available (if internet available) * then those will replace the current file. * * Language files are fetched from the frappe/books repo * the language files before storage have a ISO timestamp * prepended to the file. * * This timestamp denotes the commit datetime, update of the file * takes place only if a new update has been pushed. */ import { constants } from 'fs'; import fs from 'fs/promises'; import path from 'path'; import { parseCSV } from 'utils/csvParser'; import { LanguageMap } from 'utils/types'; import fetch from 'node-fetch'; const VALENTINES_DAY = 1644796800000; export async function getLanguageMap(code: string): Promise<LanguageMap> { const contents = await getContents(code); return getMapFromCsv(contents); } function getMapFromCsv(csv: string): LanguageMap { const matrix = parseCSV(csv); const languageMap: LanguageMap = {}; for (const row of matrix) { /** * Ignore lines that have no translations */ if (!row[0] || !row[1]) { continue; } const source = row[0]; const translation = row[1]; const context = row[3]; languageMap[source] = { translation }; if (context?.length) { languageMap[source].context = context; } } return languageMap; } async function getContents(code: string) { let contents = await getContentsIfExists(code); if (contents.length === 0) { contents = (await fetchAndStoreFile(code)) || contents; } else { contents = (await getUpdatedContent(code, contents)) || contents; } if (!contents || contents.length === 0) { throwCouldNotFetchFile(code); } return contents; } async function getContentsIfExists(code: string): Promise<string> { const filePath = await getTranslationFilePath(code); if (!filePath) { return ''; } return await fs.readFile(filePath, { encoding: 'utf-8' }); } async function fetchAndStoreFile(code: string, date?: Date) { let contents = await fetchContentsFromApi(code); if (!contents) { contents = await fetchContentsFromRaw(code); } if (!date && contents) { date = await getLastUpdated(code); } if (contents) { contents = [date!.toISOString(), contents].join('\n'); await storeFile(code, contents); } return contents ?? ''; } async function fetchContentsFromApi(code: string) { const url = `https://api.github.com/repos/frappe/books/contents/translations/${code}.csv`; const res = await errorHandledFetch(url); if (res === null || res.status !== 200) { return null; } const resJson = (await res.json()) as { content: string }; return Buffer.from(resJson.content, 'base64').toString(); } async function fetchContentsFromRaw(code: string) { const url = `https://raw.githubusercontent.com/frappe/books/master/translations/${code}.csv`; const res = await errorHandledFetch(url); if (res === null || res.status !== 200) { return null; } return await res.text(); } async function getUpdatedContent(code: string, contents: string) { const { shouldUpdate, date } = await shouldUpdateFile(code, contents); if (!shouldUpdate) { return contents; } return await fetchAndStoreFile(code, date); } async function shouldUpdateFile(code: string, contents: string) { const date = await getLastUpdated(code); const oldDate = new Date(contents.split('\n')[0]); const shouldUpdate = date > oldDate || +oldDate === VALENTINES_DAY; return { shouldUpdate, date }; } async function getLastUpdated(code: string): Promise<Date> { const url = `https://api.github.com/repos/frappe/books/commits?path=translations%2F${code}.csv&page=1&per_page=1`; const res = await errorHandledFetch(url); if (res === null || res.status !== 200) { return new Date(VALENTINES_DAY); } const resJson = (await res.json()) as { commit: { author: { date: string } }; }[]; try { return new Date(resJson[0].commit.author.date); } catch { return new Date(VALENTINES_DAY); } } async function getTranslationFilePath(code: string) { let filePath = path.join( process.resourcesPath, `../translations/${code}.csv` ); try { await fs.access(filePath, constants.R_OK); } catch { /** * This will be used for in Development mode */ filePath = path.join(__dirname, `../../translations/${code}.csv`); } try { await fs.access(filePath, constants.R_OK); } catch { return ''; } return filePath; } function throwCouldNotFetchFile(code: string) { throw new Error(`Could not fetch translations for '${code}'.`); } async function storeFile(code: string, contents: string) { const filePath = await getTranslationFilePath(code); if (!filePath) { return; } const dirname = path.dirname(filePath); await fs.mkdir(dirname, { recursive: true }); await fs.writeFile(filePath, contents, { encoding: 'utf-8' }); } async function errorHandledFetch(url: string) { try { return await fetch(url); } catch { return null; } }
2302_79757062/books
main/getLanguageMap.ts
TypeScript
agpl-3.0
5,038
import fs from 'fs/promises'; import path from 'path'; import { TemplateFile } from 'utils/types'; export async function getTemplates() { const paths = await getPrintTemplatePaths(); if (!paths) { return []; } const templates: TemplateFile[] = []; for (const file of paths.files) { const filePath = path.join(paths.root, file); const template = await fs.readFile(filePath, 'utf-8'); const { mtime } = await fs.stat(filePath); templates.push({ template, file, modified: mtime.toISOString() }); } return templates; } async function getPrintTemplatePaths(): Promise<{ files: string[]; root: string; } | null> { let root = path.join(process.resourcesPath, `../templates`); try { const files = await fs.readdir(root); return { files, root }; } catch { root = path.join(__dirname, '..', '..', `templates`); } try { const files = await fs.readdir(root); return { files, root }; } catch { return null; } }
2302_79757062/books
main/getPrintTemplates.ts
TypeScript
agpl-3.0
980
import { constants } from 'fs'; import fs from 'fs/promises'; import { ConfigFile } from 'fyo/core/types'; import { Main } from 'main'; import config from 'utils/config'; import { BackendResponse } from 'utils/ipc/types'; import { IPC_CHANNELS } from 'utils/messages'; import type { ConfigFilesWithModified } from 'utils/types'; export async function setAndGetCleanedConfigFiles() { const files = config.get('files', []); const cleanedFileMap: Map<string, ConfigFile> = new Map(); for (const file of files) { const exists = await fs .access(file.dbPath, constants.W_OK) .then(() => true) .catch(() => false); if (!file.companyName) { continue; } const key = `${file.companyName}-${file.dbPath}`; if (!exists || cleanedFileMap.has(key)) { continue; } cleanedFileMap.set(key, file); } const cleanedFiles = Array.from(cleanedFileMap.values()); config.set('files', cleanedFiles); return cleanedFiles; } export async function getConfigFilesWithModified(files: ConfigFile[]) { const filesWithModified: ConfigFilesWithModified[] = []; for (const { dbPath, id, companyName, openCount } of files) { const { mtime } = await fs.stat(dbPath); filesWithModified.push({ id, dbPath, companyName, modified: mtime.toISOString(), openCount, }); } return filesWithModified; } export async function getErrorHandledReponse( func: () => Promise<unknown> | unknown ) { const response: BackendResponse = {}; try { response.data = await func(); } catch (err) { response.error = { name: (err as NodeJS.ErrnoException).name, message: (err as NodeJS.ErrnoException).message, stack: (err as NodeJS.ErrnoException).stack, code: (err as NodeJS.ErrnoException).code, }; } return response; } export function rendererLog(main: Main, ...args: unknown[]) { main.mainWindow?.webContents.send(IPC_CHANNELS.CONSOLE_LOG, ...args); } export function isNetworkError(error: Error) { switch (error?.message) { case 'net::ERR_INTERNET_DISCONNECTED': case 'net::ERR_NETWORK_CHANGED': case 'net::ERR_PROXY_CONNECTION_FAILED': case 'net::ERR_CONNECTION_RESET': case 'net::ERR_CONNECTION_CLOSE': case 'net::ERR_NAME_NOT_RESOLVED': case 'net::ERR_TIMED_OUT': case 'net::ERR_CONNECTION_TIMED_OUT': return true; default: return false; } }
2302_79757062/books
main/helpers.ts
TypeScript
agpl-3.0
2,424
import type { OpenDialogOptions, OpenDialogReturnValue, SaveDialogOptions, SaveDialogReturnValue, } from 'electron'; import { contextBridge, ipcRenderer } from 'electron'; import type { ConfigMap } from 'fyo/core/types'; import config from 'utils/config'; import type { DatabaseMethod } from 'utils/db/types'; import type { BackendResponse } from 'utils/ipc/types'; import { IPC_ACTIONS, IPC_CHANNELS, IPC_MESSAGES } from 'utils/messages'; import type { ConfigFilesWithModified, Creds, LanguageMap, SelectFileOptions, SelectFileReturn, TemplateFile, } from 'utils/types'; type IPCRendererListener = Parameters<typeof ipcRenderer.on>[1]; const ipc = { desktop: true, reloadWindow() { return ipcRenderer.send(IPC_MESSAGES.RELOAD_MAIN_WINDOW); }, minimizeWindow() { return ipcRenderer.send(IPC_MESSAGES.MINIMIZE_MAIN_WINDOW); }, toggleMaximize() { return ipcRenderer.send(IPC_MESSAGES.MAXIMIZE_MAIN_WINDOW); }, isMaximized() { return new Promise((resolve, reject) => { ipcRenderer.send(IPC_MESSAGES.ISMAXIMIZED_MAIN_WINDOW); ipcRenderer.once( IPC_MESSAGES.ISMAXIMIZED_RESULT, (_event, isMaximized) => { resolve(isMaximized); } ); }); }, isFullscreen() { return new Promise((resolve, reject) => { ipcRenderer.send(IPC_MESSAGES.ISFULLSCREEN_MAIN_WINDOW); ipcRenderer.once( IPC_MESSAGES.ISFULLSCREEN_RESULT, (_event, isFullscreen) => { resolve(isFullscreen); } ); }); }, closeWindow() { return ipcRenderer.send(IPC_MESSAGES.CLOSE_MAIN_WINDOW); }, async getCreds() { return (await ipcRenderer.invoke(IPC_ACTIONS.GET_CREDS)) as Creds; }, async getLanguageMap(code: string) { return (await ipcRenderer.invoke(IPC_ACTIONS.GET_LANGUAGE_MAP, code)) as { languageMap: LanguageMap; success: boolean; message: string; }; }, async getTemplates(): Promise<TemplateFile[]> { return (await ipcRenderer.invoke( IPC_ACTIONS.GET_TEMPLATES )) as TemplateFile[]; }, async selectFile(options: SelectFileOptions): Promise<SelectFileReturn> { return (await ipcRenderer.invoke( IPC_ACTIONS.SELECT_FILE, options )) as SelectFileReturn; }, async getSaveFilePath(options: SaveDialogOptions) { return (await ipcRenderer.invoke( IPC_ACTIONS.GET_SAVE_FILEPATH, options )) as SaveDialogReturnValue; }, async getOpenFilePath(options: OpenDialogOptions) { return (await ipcRenderer.invoke( IPC_ACTIONS.GET_OPEN_FILEPATH, options )) as OpenDialogReturnValue; }, async checkDbAccess(filePath: string) { return (await ipcRenderer.invoke( IPC_ACTIONS.CHECK_DB_ACCESS, filePath )) as boolean; }, async checkForUpdates() { await ipcRenderer.invoke(IPC_ACTIONS.CHECK_FOR_UPDATES); }, openLink(link: string) { ipcRenderer.send(IPC_MESSAGES.OPEN_EXTERNAL, link); }, async deleteFile(filePath: string) { return (await ipcRenderer.invoke( IPC_ACTIONS.DELETE_FILE, filePath )) as BackendResponse; }, async saveData(data: string, savePath: string) { await ipcRenderer.invoke(IPC_ACTIONS.SAVE_DATA, data, savePath); }, showItemInFolder(filePath: string) { ipcRenderer.send(IPC_MESSAGES.SHOW_ITEM_IN_FOLDER, filePath); }, async makePDF( html: string, savePath: string, width: number, height: number ): Promise<boolean> { return (await ipcRenderer.invoke( IPC_ACTIONS.SAVE_HTML_AS_PDF, html, savePath, width, height )) as boolean; }, async getDbList() { return (await ipcRenderer.invoke( IPC_ACTIONS.GET_DB_LIST )) as ConfigFilesWithModified[]; }, async getDbDefaultPath(companyName: string) { return (await ipcRenderer.invoke( IPC_ACTIONS.GET_DB_DEFAULT_PATH, companyName )) as string; }, async getEnv() { return (await ipcRenderer.invoke(IPC_ACTIONS.GET_ENV)) as { isDevelopment: boolean; platform: string; version: string; }; }, openExternalUrl(url: string) { ipcRenderer.send(IPC_MESSAGES.OPEN_EXTERNAL, url); }, async showError(title: string, content: string) { await ipcRenderer.invoke(IPC_ACTIONS.SHOW_ERROR, { title, content }); }, async sendError(body: string) { await ipcRenderer.invoke(IPC_ACTIONS.SEND_ERROR, body); }, registerMainProcessErrorListener(listener: IPCRendererListener) { ipcRenderer.on(IPC_CHANNELS.LOG_MAIN_PROCESS_ERROR, listener); }, registerConsoleLogListener(listener: IPCRendererListener) { ipcRenderer.on(IPC_CHANNELS.CONSOLE_LOG, listener); }, db: { async getSchema() { return (await ipcRenderer.invoke( IPC_ACTIONS.DB_SCHEMA )) as BackendResponse; }, async create(dbPath: string, countryCode?: string) { return (await ipcRenderer.invoke( IPC_ACTIONS.DB_CREATE, dbPath, countryCode )) as BackendResponse; }, async connect(dbPath: string, countryCode?: string) { return (await ipcRenderer.invoke( IPC_ACTIONS.DB_CONNECT, dbPath, countryCode )) as BackendResponse; }, async call(method: DatabaseMethod, ...args: unknown[]) { return (await ipcRenderer.invoke( IPC_ACTIONS.DB_CALL, method, ...args )) as BackendResponse; }, async bespoke(method: string, ...args: unknown[]) { return (await ipcRenderer.invoke( IPC_ACTIONS.DB_BESPOKE, method, ...args )) as BackendResponse; }, }, store: { get<K extends keyof ConfigMap>(key: K) { return config.get(key); }, set<K extends keyof ConfigMap>(key: K, value: ConfigMap[K]) { return config.set(key, value); }, delete(key: keyof ConfigMap) { return config.delete(key); }, }, } as const; contextBridge.exposeInMainWorld('ipc', ipc); export type IPC = typeof ipc;
2302_79757062/books
main/preload.ts
TypeScript
agpl-3.0
6,033
import { app } from 'electron'; import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'; import { Main } from '../main'; import { rendererLog } from './helpers'; import { emitMainProcessError } from 'backend/helpers'; export default function registerAppLifecycleListeners(main: Main) { app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (main.mainWindow === null) { main.createWindow().catch((err) => emitMainProcessError(err)); } }); app.on('ready', () => { if (main.isDevelopment && !main.isTest) { installDevTools(main).catch((err) => emitMainProcessError(err)); } main.createWindow().catch((err) => emitMainProcessError(err)); }); } async function installDevTools(main: Main) { try { await installExtension(VUEJS3_DEVTOOLS); } catch (e) { rendererLog(main, 'Vue Devtools failed to install', e); } }
2302_79757062/books
main/registerAppLifecycleListeners.ts
TypeScript
agpl-3.0
974
import { app, dialog } from 'electron'; import { autoUpdater, UpdateInfo } from 'electron-updater'; import { emitMainProcessError } from '../backend/helpers'; import { Main } from '../main'; import { isNetworkError } from './helpers'; export default function registerAutoUpdaterListeners(main: Main) { autoUpdater.autoDownload = false; autoUpdater.allowPrerelease = true; autoUpdater.autoInstallOnAppQuit = true; autoUpdater.on('error', (error) => { if (!main.checkedForUpdate) { main.checkedForUpdate = true; } if (isNetworkError(error)) { return; } emitMainProcessError(error); }); // eslint-disable-next-line @typescript-eslint/no-misused-promises autoUpdater.on('update-available', async (info: UpdateInfo) => { const currentVersion = app.getVersion(); const nextVersion = info.version; const isCurrentBeta = currentVersion.includes('beta'); const isNextBeta = nextVersion.includes('beta'); let downloadUpdate = true; if (!isCurrentBeta && isNextBeta) { const option = await dialog.showMessageBox({ type: 'info', title: 'Update Available', message: `Download version ${nextVersion}?`, buttons: ['Yes', 'No'], }); downloadUpdate = option.response === 0; } if (!downloadUpdate) { return; } await autoUpdater.downloadUpdate(); }); // eslint-disable-next-line @typescript-eslint/no-misused-promises autoUpdater.on('update-downloaded', async () => { const option = await dialog.showMessageBox({ type: 'info', title: 'Update Downloaded', message: 'Restart Frappe Books to install update?', buttons: ['Yes', 'No'], }); if (option.response === 1) { return; } autoUpdater.quitAndInstall(); }); }
2302_79757062/books
main/registerAutoUpdaterListeners.ts
TypeScript
agpl-3.0
1,803
import { MessageBoxOptions, OpenDialogOptions, SaveDialogOptions, app, dialog, ipcMain, } from 'electron'; import { autoUpdater } from 'electron-updater'; import { constants } from 'fs'; import fs from 'fs-extra'; import path from 'path'; import { SelectFileOptions, SelectFileReturn } from 'utils/types'; import databaseManager from '../backend/database/manager'; import { emitMainProcessError } from '../backend/helpers'; import { Main } from '../main'; import { DatabaseMethod } from '../utils/db/types'; import { IPC_ACTIONS } from '../utils/messages'; import { getUrlAndTokenString, sendError } from './contactMothership'; import { getLanguageMap } from './getLanguageMap'; import { getTemplates } from './getPrintTemplates'; import { getConfigFilesWithModified, getErrorHandledReponse, isNetworkError, setAndGetCleanedConfigFiles, } from './helpers'; import { saveHtmlAsPdf } from './saveHtmlAsPdf'; export default function registerIpcMainActionListeners(main: Main) { ipcMain.handle(IPC_ACTIONS.CHECK_DB_ACCESS, async (_, filePath: string) => { try { await fs.access(filePath, constants.W_OK | constants.R_OK); } catch (err) { return false; } return true; }); ipcMain.handle( IPC_ACTIONS.GET_DB_DEFAULT_PATH, async (_, companyName: string) => { let root: string; try { root = app.getPath('documents'); } catch { root = app.getPath('userData'); } if (main.isDevelopment) { root = 'dbs'; } const dbsPath = path.join(root, 'Frappe Books'); const backupPath = path.join(dbsPath, 'backups'); await fs.ensureDir(backupPath); return path.join(dbsPath, `${companyName}.books.db`); } ); ipcMain.handle( IPC_ACTIONS.GET_OPEN_FILEPATH, async (_, options: OpenDialogOptions) => { return await dialog.showOpenDialog(main.mainWindow!, options); } ); ipcMain.handle( IPC_ACTIONS.GET_SAVE_FILEPATH, async (_, options: SaveDialogOptions) => { return await dialog.showSaveDialog(main.mainWindow!, options); } ); ipcMain.handle( IPC_ACTIONS.GET_DIALOG_RESPONSE, async (_, options: MessageBoxOptions) => { if (main.isDevelopment || main.isLinux) { Object.assign(options, { icon: main.icon }); } return await dialog.showMessageBox(main.mainWindow!, options); } ); ipcMain.handle( IPC_ACTIONS.SHOW_ERROR, (_, { title, content }: { title: string; content: string }) => { return dialog.showErrorBox(title, content); } ); ipcMain.handle( IPC_ACTIONS.SAVE_HTML_AS_PDF, async ( _, html: string, savePath: string, width: number, height: number ) => { return await saveHtmlAsPdf(html, savePath, app, width, height); } ); ipcMain.handle( IPC_ACTIONS.SAVE_DATA, async (_, data: string, savePath: string) => { return await fs.writeFile(savePath, data, { encoding: 'utf-8' }); } ); ipcMain.handle(IPC_ACTIONS.SEND_ERROR, async (_, bodyJson: string) => { await sendError(bodyJson, main); }); ipcMain.handle(IPC_ACTIONS.CHECK_FOR_UPDATES, async () => { if (main.isDevelopment || main.checkedForUpdate) { return; } try { await autoUpdater.checkForUpdates(); } catch (error) { if (isNetworkError(error as Error)) { return; } emitMainProcessError(error); } main.checkedForUpdate = true; }); ipcMain.handle(IPC_ACTIONS.GET_LANGUAGE_MAP, async (_, code: string) => { const obj = { languageMap: {}, success: true, message: '' }; try { obj.languageMap = await getLanguageMap(code); } catch (err) { obj.success = false; obj.message = (err as Error).message; } return obj; }); ipcMain.handle( IPC_ACTIONS.SELECT_FILE, async (_, options: SelectFileOptions): Promise<SelectFileReturn> => { const response: SelectFileReturn = { name: '', filePath: '', success: false, data: Buffer.from('', 'utf-8'), canceled: false, }; const { filePaths, canceled } = await dialog.showOpenDialog( main.mainWindow!, { ...options, properties: ['openFile'] } ); response.filePath = filePaths?.[0]; response.canceled = canceled; if (!response.filePath) { return response; } response.success = true; if (canceled) { return response; } response.name = path.basename(response.filePath); response.data = await fs.readFile(response.filePath); return response; } ); ipcMain.handle(IPC_ACTIONS.GET_CREDS, () => { return getUrlAndTokenString(); }); ipcMain.handle(IPC_ACTIONS.DELETE_FILE, async (_, filePath: string) => { return getErrorHandledReponse(async () => await fs.unlink(filePath)); }); ipcMain.handle(IPC_ACTIONS.GET_DB_LIST, async () => { const files = await setAndGetCleanedConfigFiles(); return await getConfigFilesWithModified(files); }); ipcMain.handle(IPC_ACTIONS.GET_ENV, async () => { let version = app.getVersion(); if (main.isDevelopment) { const packageJson = await fs.readFile('package.json', 'utf-8'); version = (JSON.parse(packageJson) as { version: string }).version; } return { isDevelopment: main.isDevelopment, platform: process.platform, version, }; }); ipcMain.handle(IPC_ACTIONS.GET_TEMPLATES, async () => { return getTemplates(); }); /** * Database Related Actions */ ipcMain.handle( IPC_ACTIONS.DB_CREATE, async (_, dbPath: string, countryCode: string) => { return await getErrorHandledReponse(async () => { return await databaseManager.createNewDatabase(dbPath, countryCode); }); } ); ipcMain.handle( IPC_ACTIONS.DB_CONNECT, async (_, dbPath: string, countryCode?: string) => { return await getErrorHandledReponse(async () => { return await databaseManager.connectToDatabase(dbPath, countryCode); }); } ); ipcMain.handle( IPC_ACTIONS.DB_CALL, async (_, method: DatabaseMethod, ...args: unknown[]) => { return await getErrorHandledReponse(async () => { return await databaseManager.call(method, ...args); }); } ); ipcMain.handle( IPC_ACTIONS.DB_BESPOKE, async (_, method: string, ...args: unknown[]) => { return await getErrorHandledReponse(async () => { return await databaseManager.callBespoke(method, ...args); }); } ); ipcMain.handle(IPC_ACTIONS.DB_SCHEMA, async () => { return await getErrorHandledReponse(() => { return databaseManager.getSchemaMap(); }); }); }
2302_79757062/books
main/registerIpcMainActionListeners.ts
TypeScript
agpl-3.0
6,755
import { ipcMain, Menu, shell } from 'electron'; import { Main } from '../main'; import { IPC_MESSAGES } from '../utils/messages'; import { emitMainProcessError } from 'backend/helpers'; export default function registerIpcMainMessageListeners(main: Main) { ipcMain.on(IPC_MESSAGES.OPEN_MENU, (event) => { if (event.sender === null) { return; } const menu = Menu.getApplicationMenu(); if (menu === null) { return; } menu.popup({ window: main.mainWindow! }); }); ipcMain.on(IPC_MESSAGES.RELOAD_MAIN_WINDOW, () => { main.mainWindow!.reload(); }); ipcMain.on(IPC_MESSAGES.MINIMIZE_MAIN_WINDOW, () => { main.mainWindow!.minimize(); }); ipcMain.on(IPC_MESSAGES.MAXIMIZE_MAIN_WINDOW, () => { main.mainWindow!.isMaximized() ? main.mainWindow!.unmaximize() : main.mainWindow!.maximize(); }); ipcMain.on(IPC_MESSAGES.ISMAXIMIZED_MAIN_WINDOW, (event) => { const isMaximized = main.mainWindow?.isMaximized() ?? false; event.sender.send(IPC_MESSAGES.ISMAXIMIZED_RESULT, isMaximized); }); ipcMain.on(IPC_MESSAGES.ISFULLSCREEN_MAIN_WINDOW, (event) => { const isFullscreen = main.mainWindow?.isFullScreen() ?? false; event.sender.send(IPC_MESSAGES.ISFULLSCREEN_RESULT, isFullscreen); }); ipcMain.on(IPC_MESSAGES.CLOSE_MAIN_WINDOW, () => { main.mainWindow!.close(); }); ipcMain.on(IPC_MESSAGES.OPEN_EXTERNAL, (_, link: string) => { shell.openExternal(link).catch((err) => emitMainProcessError(err)); }); ipcMain.on(IPC_MESSAGES.SHOW_ITEM_IN_FOLDER, (_, filePath: string) => { return shell.showItemInFolder(filePath); }); }
2302_79757062/books
main/registerIpcMainMessageListeners.ts
TypeScript
agpl-3.0
1,641
import { app } from 'electron'; import { CUSTOM_EVENTS, IPC_CHANNELS } from 'utils/messages'; import { Main } from '../main'; export default function registerProcessListeners(main: Main) { if (main.isDevelopment) { if (process.platform === 'win32') { process.on('message', (data) => { if (data === 'graceful-exit') { app.quit(); } }); } else { process.on('SIGTERM', () => { app.quit(); }); } } process.on(CUSTOM_EVENTS.MAIN_PROCESS_ERROR, (error, more) => { main.mainWindow!.webContents.send( IPC_CHANNELS.LOG_MAIN_PROCESS_ERROR, error, more ); }); process.on('unhandledRejection', (error) => { main.mainWindow!.webContents.send( IPC_CHANNELS.LOG_MAIN_PROCESS_ERROR, error ); }); process.on('uncaughtException', (error) => { main.mainWindow!.webContents.send( IPC_CHANNELS.LOG_MAIN_PROCESS_ERROR, error ); setTimeout(() => process.exit(1), 10000); }); }
2302_79757062/books
main/registerProcessListeners.ts
TypeScript
agpl-3.0
1,014
import { App, BrowserWindow } from 'electron'; import fs from 'fs/promises'; import path from 'path'; export async function saveHtmlAsPdf( html: string, savePath: string, app: App, width: number, // centimeters height: number // centimeters ): Promise<boolean> { /** * Store received html as a file in a tempdir, * this will be loaded into the print view */ const tempRoot = app.getPath('temp'); const filename = path.parse(savePath).name; const htmlPath = path.join(tempRoot, `${filename}.html`); await fs.writeFile(htmlPath, html, { encoding: 'utf-8' }); const printWindow = await getInitializedPrintWindow(htmlPath, width, height); const printOptions = { margins: { top: 0, bottom: 0, left: 0, right: 0 }, // equivalent to previous 'marginType: 1' pageSize: { height: height / 2.54, // Convert from centimeters to inches width: width / 2.54, // Convert from centimeters to inches }, printBackground: true, }; const data = await printWindow.webContents.printToPDF(printOptions); await fs.writeFile(savePath, data); printWindow.close(); await fs.unlink(htmlPath); return true; } async function getInitializedPrintWindow( printFilePath: string, width: number, height: number ) { const printWindow = new BrowserWindow({ width: Math.floor(width * 28.333333), // pixels height: Math.floor(height * 28.333333), // pixels show: false, }); await printWindow.loadFile(printFilePath); return printWindow; }
2302_79757062/books
main/saveHtmlAsPdf.ts
TypeScript
agpl-3.0
1,503
// eslint-disable-next-line require('source-map-support').install({ handleUncaughtException: false, environment: 'node', }); import { emitMainProcessError } from 'backend/helpers'; import { app, BrowserWindow, BrowserWindowConstructorOptions, protocol, ProtocolRequest, ProtocolResponse, } from 'electron'; import { autoUpdater } from 'electron-updater'; import fs from 'fs'; import path from 'path'; import registerAppLifecycleListeners from './main/registerAppLifecycleListeners'; import registerAutoUpdaterListeners from './main/registerAutoUpdaterListeners'; import registerIpcMainActionListeners from './main/registerIpcMainActionListeners'; import registerIpcMainMessageListeners from './main/registerIpcMainMessageListeners'; import registerProcessListeners from './main/registerProcessListeners'; export class Main { title = 'Frappe Books'; icon: string; winURL = ''; checkedForUpdate = false; mainWindow: BrowserWindow | null = null; WIDTH = 1200; HEIGHT = process.platform === 'win32' ? 826 : 800; constructor() { this.icon = this.isDevelopment ? path.resolve('./build/icon.png') : path.join(__dirname, 'icons', '512x512.png'); protocol.registerSchemesAsPrivileged([ { scheme: 'app', privileges: { secure: true, standard: true } }, ]); if (this.isDevelopment) { autoUpdater.logger = console; } // https://github.com/electron-userland/electron-builder/issues/4987 app.commandLine.appendSwitch('disable-http2'); autoUpdater.requestHeaders = { 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0', }; this.registerListeners(); if (this.isMac && this.isDevelopment) { app.dock.setIcon(this.icon); } } get isDevelopment() { return process.env.NODE_ENV === 'development'; } get isTest() { return !!process.env.IS_TEST; } get isMac() { return process.platform === 'darwin'; } get isLinux() { return process.platform === 'linux'; } registerListeners() { registerIpcMainMessageListeners(this); registerIpcMainActionListeners(this); registerAutoUpdaterListeners(this); registerAppLifecycleListeners(this); registerProcessListeners(this); } getOptions(): BrowserWindowConstructorOptions { const preload = path.join(__dirname, 'main', 'preload.js'); const options: BrowserWindowConstructorOptions = { width: this.WIDTH, height: this.HEIGHT, title: this.title, titleBarStyle: 'hidden', trafficLightPosition: { x: 16, y: 16 }, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: false, preload, }, autoHideMenuBar: true, frame: !this.isMac, resizable: true, }; if (this.isDevelopment || this.isLinux) { Object.assign(options, { icon: this.icon }); } if (this.isLinux) { Object.assign(options, { icon: path.join(__dirname, '/icons/512x512.png'), }); } return options; } async createWindow() { const options = this.getOptions(); this.mainWindow = new BrowserWindow(options); if (this.isDevelopment) { this.setViteServerURL(); } else { this.registerAppProtocol(); } await this.mainWindow.loadURL(this.winURL); if (this.isDevelopment && !this.isTest) { this.mainWindow.webContents.openDevTools(); } this.setMainWindowListeners(); } setViteServerURL() { let port = 6969; let host = '0.0.0.0'; if (process.env.VITE_PORT && process.env.VITE_HOST) { port = Number(process.env.VITE_PORT); host = process.env.VITE_HOST; } // Load the url of the dev server if in development mode this.winURL = `http://${host}:${port}/`; } registerAppProtocol() { protocol.registerBufferProtocol('app', bufferProtocolCallback); // Use the registered protocol url to load the files. this.winURL = 'app://./index.html'; } setMainWindowListeners() { if (this.mainWindow === null) { return; } this.mainWindow.on('closed', () => { this.mainWindow = null; }); this.mainWindow.webContents.on('did-fail-load', () => { this.mainWindow!.loadURL(this.winURL).catch((err) => emitMainProcessError(err) ); }); } } /** * Callback used to register the custom app protocol, * during prod, files are read and served by using this * protocol. */ function bufferProtocolCallback( request: ProtocolRequest, callback: (response: ProtocolResponse) => void ) { const { pathname, host } = new URL(request.url); const filePath = path.join( __dirname, 'src', decodeURI(host), decodeURI(pathname) ); fs.readFile(filePath, (_, data) => { const extension = path.extname(filePath).toLowerCase(); const mimeType = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.svg': 'image/svg+xml', '.json': 'application/json', }[extension] ?? ''; callback({ mimeType, data }); }); } export default new Main();
2302_79757062/books
main.ts
TypeScript
agpl-3.0
5,153
import { Fyo, t } from 'fyo'; import { NotFoundError, ValidationError } from 'fyo/utils/errors'; import { AccountingLedgerEntry } from 'models/baseModels/AccountingLedgerEntry/AccountingLedgerEntry'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { Transactional } from './Transactional'; import { TransactionType } from './types'; /** * # LedgerPosting * * Class that maintains a set of AccountingLedgerEntries pertaining to * a single Transactional doc, example a Payment entry. * * For each account touched in a transactional doc a separate ledger entry is * created. * * This is done using the `debit(...)` and `credit(...)` methods. * * Unless `post()` or `postReverese()` is called the entries aren't made. */ export class LedgerPosting { fyo: Fyo; refDoc: Transactional; entries: AccountingLedgerEntry[]; creditMap: Record<string, AccountingLedgerEntry>; debitMap: Record<string, AccountingLedgerEntry>; reverted: boolean; constructor(refDoc: Transactional, fyo: Fyo) { this.fyo = fyo; this.refDoc = refDoc; this.entries = []; this.creditMap = {}; this.debitMap = {}; this.reverted = false; } async debit(account: string, amount: Money) { const ledgerEntry = this._getLedgerEntry(account, 'debit'); await ledgerEntry.set('debit', ledgerEntry.debit!.add(amount)); } async credit(account: string, amount: Money) { const ledgerEntry = this._getLedgerEntry(account, 'credit'); await ledgerEntry.set('credit', ledgerEntry.credit!.add(amount)); } async post() { this._validateIsEqual(); await this._sync(); } async postReverse() { this._validateIsEqual(); await this._syncReverse(); } validate() { this._validateIsEqual(); } timezoneDateTimeAdjuster(setDate: string | Date) { const dateTimeValue = new Date(setDate); const dtFixedValue = dateTimeValue; const dtMinutes = dtFixedValue.getTimezoneOffset() % 60; const dtHours = (dtFixedValue.getTimezoneOffset() - dtMinutes) / 60; // Forcing the time to always be set to 00:00.000 for locale time dtFixedValue.setHours(0 - dtHours); dtFixedValue.setMinutes(0 - dtMinutes); dtFixedValue.setSeconds(0); dtFixedValue.setMilliseconds(0); return dtFixedValue; } async makeRoundOffEntry() { const { debit, credit } = this._getTotalDebitAndCredit(); const difference = debit.sub(credit); const absoluteValue = difference.abs(); if (absoluteValue.eq(0)) { return; } const roundOffAccount = await this._getRoundOffAccount(); if (difference.gt(0)) { await this.credit(roundOffAccount, absoluteValue); } else { await this.debit(roundOffAccount, absoluteValue); } } _getLedgerEntry( account: string, type: TransactionType ): AccountingLedgerEntry { let map = this.creditMap; if (type === 'debit') { map = this.debitMap; } if (map[account]) { return map[account]; } // end ugly timezone fix code const ledgerEntry = this.fyo.doc.getNewDoc( ModelNameEnum.AccountingLedgerEntry, { account: account, party: (this.refDoc.party as string) ?? '', date: this.timezoneDateTimeAdjuster(this.refDoc.date as string | Date), referenceType: this.refDoc.schemaName, referenceName: this.refDoc.name!, reverted: this.reverted, debit: this.fyo.pesa(0), credit: this.fyo.pesa(0), }, false ) as AccountingLedgerEntry; this.entries.push(ledgerEntry); map[account] = ledgerEntry; return map[account]; } _validateIsEqual() { const { debit, credit } = this._getTotalDebitAndCredit(); if (debit.eq(credit)) { return; } throw new ValidationError( t`Total Debit: ${this.fyo.format( debit, 'Currency' )} must be equal to Total Credit: ${this.fyo.format(credit, 'Currency')}` ); } _getTotalDebitAndCredit() { let debit = this.fyo.pesa(0); let credit = this.fyo.pesa(0); for (const entry of this.entries) { debit = debit.add(entry.debit!); credit = credit.add(entry.credit!); } return { debit, credit }; } async _sync() { await this._syncLedgerEntries(); } async _syncLedgerEntries() { for (const entry of this.entries) { await entry.sync(); } } async _syncReverse() { await this._syncReverseLedgerEntries(); } async _syncReverseLedgerEntries() { const data = (await this.fyo.db.getAll('AccountingLedgerEntry', { fields: ['name'], filters: { referenceType: this.refDoc.schemaName, referenceName: this.refDoc.name!, reverted: false, }, })) as { name: string }[]; for (const { name } of data) { const doc = (await this.fyo.doc.getDoc( 'AccountingLedgerEntry', name )) as AccountingLedgerEntry; await doc.revert(); } } async _getRoundOffAccount() { const roundOffAccount = (await this.fyo.getValue( ModelNameEnum.AccountingSettings, 'roundOffAccount' )) as string; if (!roundOffAccount) { const notFoundError = new NotFoundError( t`Please set Round Off Account in the Settings.`, false ); notFoundError.name = t`Round Off Account Not Found`; throw notFoundError; } return roundOffAccount; } }
2302_79757062/books
models/Transactional/LedgerPosting.ts
TypeScript
agpl-3.0
5,433
import { Doc } from 'fyo/model/doc'; import { ModelNameEnum } from 'models/types'; import { LedgerPosting } from './LedgerPosting'; /** * # Transactional * * Any model that creates ledger entries on submit should extend the * `Transactional` model. * * Example of transactional models: * - Invoice * - Payment * - JournalEntry * * Basically it does the following: * - `afterSubmit`: create the ledger entries. * - `afterCancel`: create reverse ledger entries. * - `afterDelete`: delete the normal and reversed ledger entries. */ export abstract class Transactional extends Doc { date?: Date; get isTransactional() { return true; } abstract getPosting(): Promise<LedgerPosting | null>; async validate() { await super.validate(); if (!this.isTransactional) { return; } const posting = await this.getPosting(); if (posting === null) { return; } posting.validate(); } async afterSubmit(): Promise<void> { await super.afterSubmit(); if (!this.isTransactional) { return; } const posting = await this.getPosting(); if (posting === null) { return; } await posting.post(); } async afterCancel(): Promise<void> { await super.afterCancel(); if (!this.isTransactional) { return; } const posting = await this.getPosting(); if (posting === null) { return; } await posting.postReverse(); } async afterDelete(): Promise<void> { await super.afterDelete(); if (!this.isTransactional) { return; } const ledgerEntryIds = (await this.fyo.db.getAll( ModelNameEnum.AccountingLedgerEntry, { fields: ['name'], filters: { referenceType: this.schemaName, referenceName: this.name!, }, } )) as { name: string }[]; for (const { name } of ledgerEntryIds) { const ledgerEntryDoc = await this.fyo.doc.getDoc( ModelNameEnum.AccountingLedgerEntry, name ); await ledgerEntryDoc.delete(); } } }
2302_79757062/books
models/Transactional/Transactional.ts
TypeScript
agpl-3.0
2,068
import { Doc } from 'fyo/model/doc'; import { Money } from 'pesa'; export interface LedgerPostingOptions { reference: Doc; party?: string; } export interface LedgerEntry { account: string; party: string; date: string; referenceType: string; referenceName: string; reverted: boolean; debit: Money; credit: Money; } export type TransactionType = 'credit' | 'debit';
2302_79757062/books
models/Transactional/types.ts
TypeScript
agpl-3.0
387
import { Fyo } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { DefaultMap, FiltersMap, ListViewSettings, RequiredMap, TreeViewSettings, ReadOnlyMap, FormulaMap, } from 'fyo/model/types'; import { ModelNameEnum } from 'models/types'; import { QueryFilter } from 'utils/db/types'; import { AccountRootType, AccountRootTypeEnum, AccountType } from './types'; export class Account extends Doc { rootType?: AccountRootType; accountType?: AccountType; parentAccount?: string; get isDebit() { if (this.rootType === AccountRootTypeEnum.Asset) { return true; } if (this.rootType === AccountRootTypeEnum.Expense) { return true; } return false; } get isCredit() { return !this.isDebit; } required: RequiredMap = { /** * Added here cause rootAccounts don't have parents * they are created during initialization. if this is * added to the schema it will cause NOT NULL errors */ parentAccount: () => !!this.fyo.singles?.AccountingSettings?.setupComplete, }; static defaults: DefaultMap = { /** * NestedSet indices are actually not used * this needs updation as they may be required * later on. */ lft: () => 0, rgt: () => 0, }; async beforeSync() { if (this.accountType || !this.parentAccount) { return; } const account = await this.fyo.db.get('Account', this.parentAccount); this.accountType = account.accountType as AccountType; } static getListViewSettings(): ListViewSettings { return { columns: ['name', 'rootType', 'isGroup', 'parentAccount'], }; } static getTreeSettings(fyo: Fyo): void | TreeViewSettings { return { parentField: 'parentAccount', async getRootLabel(): Promise<string> { const accountingSettings = await fyo.doc.getDoc('AccountingSettings'); return accountingSettings.companyName as string; }, }; } formulas: FormulaMap = { rootType: { formula: async () => { if (!this.parentAccount) { return; } return await this.fyo.getValue( ModelNameEnum.Account, this.parentAccount, 'rootType' ); }, }, }; static filters: FiltersMap = { parentAccount: (doc: Doc) => { const filter: QueryFilter = { isGroup: true, }; if (doc?.rootType) { filter.rootType = doc.rootType as string; } return filter; }, }; readOnly: ReadOnlyMap = { rootType: () => this.inserted, parentAccount: () => this.inserted, accountType: () => !!this.accountType && this.inserted, isGroup: () => this.inserted, }; }
2302_79757062/books
models/baseModels/Account/Account.ts
TypeScript
agpl-3.0
2,708
export enum AccountRootTypeEnum { 'Asset'='Asset', 'Liability'='Liability', 'Equity'='Equity', 'Income'='Income', 'Expense'='Expense', } export enum AccountTypeEnum { 'Accumulated Depreciation' = 'Accumulated Depreciation', 'Bank' = 'Bank', 'Cash' = 'Cash', 'Chargeable' = 'Chargeable', 'Cost of Goods Sold' = 'Cost of Goods Sold', 'Depreciation' = 'Depreciation', 'Equity' = 'Equity', 'Expense Account' = 'Expense Account', 'Expenses Included In Valuation' = 'Expenses Included In Valuation', 'Fixed Asset' = 'Fixed Asset', 'Income Account' = 'Income Account', 'Payable' = 'Payable', 'Receivable' = 'Receivable', 'Round Off' = 'Round Off', 'Stock' = 'Stock', 'Stock Adjustment' = 'Stock Adjustment', 'Stock Received But Not Billed' = 'Stock Received But Not Billed', 'Tax' = 'Tax', 'Temporary' = 'Temporary', } export type AccountType = keyof typeof AccountTypeEnum; export type AccountRootType = keyof typeof AccountRootTypeEnum export interface COARootAccount { rootType: AccountRootType; [key: string]: COAChildAccount | AccountRootType; } export interface COAChildAccount { accountType?: AccountType; accountNumber?: string; isGroup?: boolean; [key: string]: COAChildAccount | boolean | AccountType | string | undefined; } export interface COATree { [key: string]: COARootAccount; }
2302_79757062/books
models/baseModels/Account/types.ts
TypeScript
agpl-3.0
1,346
import { Doc } from 'fyo/model/doc'; import { ListViewSettings } from 'fyo/model/types'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; export class AccountingLedgerEntry extends Doc { date?: string | Date; account?: string; party?: string; debit?: Money; credit?: Money; referenceType?: string; referenceName?: string; reverted?: boolean; async revert() { if (this.reverted) { return; } await this.set('reverted', true); const revertedEntry = this.fyo.doc.getNewDoc( ModelNameEnum.AccountingLedgerEntry, { account: this.account, party: this.party, date: new Date(), referenceType: this.referenceType, referenceName: this.referenceName, debit: this.credit, credit: this.debit, reverted: true, reverts: this.name, } ); await this.sync(); await revertedEntry.sync(); } static getListViewSettings(): ListViewSettings { return { columns: ['date', 'account', 'party', 'debit', 'credit', 'referenceName'], }; } }
2302_79757062/books
models/baseModels/AccountingLedgerEntry/AccountingLedgerEntry.ts
TypeScript
agpl-3.0
1,103
import { Doc } from 'fyo/model/doc'; import { ChangeArg, FiltersMap, HiddenMap, ListsMap, ReadOnlyMap, ValidationMap, } from 'fyo/model/types'; import { validateEmail } from 'fyo/model/validationFunction'; import { createDiscountAccount } from 'src/setup/setupInstance'; import { getCountryInfo } from 'utils/misc'; export class AccountingSettings extends Doc { enableDiscounting?: boolean; enableInventory?: boolean; enablePriceList?: boolean; enableLead?: boolean; enableFormCustomization?: boolean; enableInvoiceReturns?: boolean; enableLoyaltyProgram?: boolean; enablePricingRule?: boolean; static filters: FiltersMap = { writeOffAccount: () => ({ isGroup: false, rootType: 'Expense', }), roundOffAccount: () => ({ isGroup: false, rootType: 'Expense', }), discountAccount: () => ({ isGroup: false, rootType: 'Income', }), }; validations: ValidationMap = { email: validateEmail, }; static lists: ListsMap = { country: () => Object.keys(getCountryInfo()), }; readOnly: ReadOnlyMap = { enableDiscounting: () => { return !!this.enableDiscounting; }, enableInventory: () => { return !!this.enableInventory; }, enableLead: () => { return !!this.enableLead; }, enableInvoiceReturns: () => { return !!this.enableInvoiceReturns; }, enableLoyaltyProgram: () => { return !!this.enableLoyaltyProgram; }, }; override hidden: HiddenMap = { discountAccount: () => !this.enableDiscounting, gstin: () => this.fyo.singles.SystemSettings?.countryCode !== 'in', enablePricingRule: () => !this.fyo.singles.AccountingSettings?.enableDiscounting, }; async change(ch: ChangeArg) { const discountingEnabled = ch.changed === 'enableDiscounting' && this.enableDiscounting; const discountAccountNotSet = !this.discountAccount; if (discountingEnabled && discountAccountNotSet) { await createDiscountAccount(this.fyo); } } }
2302_79757062/books
models/baseModels/AccountingSettings/AccountingSettings.ts
TypeScript
agpl-3.0
2,043
import { t } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { EmptyMessageMap, FormulaMap, ListViewSettings, ListsMap, } from 'fyo/model/types'; import { codeStateMap } from 'regional/in'; import { getCountryInfo } from 'utils/misc'; export class Address extends Doc { formulas: FormulaMap = { addressDisplay: { formula: () => { return [ this.addressLine1, this.addressLine2, this.city, this.state, this.country, this.postalCode, ] .filter(Boolean) .join(', '); }, dependsOn: [ 'addressLine1', 'addressLine2', 'city', 'state', 'country', 'postalCode', ], }, }; static lists: ListsMap = { state(doc?: Doc) { const country = doc?.country as string | undefined; switch (country) { case 'India': return Object.values(codeStateMap).sort(); default: return [] as string[]; } }, country() { return Object.keys(getCountryInfo()).sort(); }, }; static emptyMessages: EmptyMessageMap = { state: (doc: Doc) => { if (doc.country) { return t`Enter State`; } return t`Enter Country to load States`; }, }; static override getListViewSettings(): ListViewSettings { return { columns: ['name', 'addressLine1', 'city', 'state', 'country'], }; } }
2302_79757062/books
models/baseModels/Address/Address.ts
TypeScript
agpl-3.0
1,465
import { Doc } from 'fyo/model/doc'; import { Money } from 'pesa'; export class CollectionRulesItems extends Doc { tierName?: string; collectionFactor?: number; minimumTotalSpent?: Money; }
2302_79757062/books
models/baseModels/CollectionRulesItems/CollectionRulesItems.ts
TypeScript
agpl-3.0
197
import { DefaultCashDenominations } from 'models/inventory/Point of Sale/DefaultCashDenominations'; import { Doc } from 'fyo/model/doc'; import { FiltersMap, HiddenMap } from 'fyo/model/types'; import { ModelNameEnum } from 'models/types'; import { PartyRoleEnum } from '../Party/types'; export class Defaults extends Doc { // Auto Payments salesPaymentAccount?: string; purchasePaymentAccount?: string; // Auto Stock Transfer shipmentLocation?: string; purchaseReceiptLocation?: string; // Number Series salesQuoteNumberSeries?: string; salesInvoiceNumberSeries?: string; purchaseInvoiceNumberSeries?: string; journalEntryNumberSeries?: string; paymentNumberSeries?: string; stockMovementNumberSeries?: string; shipmentNumberSeries?: string; purchaseReceiptNumberSeries?: string; // Terms salesInvoiceTerms?: string; purchaseInvoiceTerms?: string; shipmentTerms?: string; purchaseReceiptTerms?: string; // Print Templates salesQuotePrintTemplate?: string; salesInvoicePrintTemplate?: string; purchaseInvoicePrintTemplate?: string; journalEntryPrintTemplate?: string; paymentPrintTemplate?: string; shipmentPrintTemplate?: string; purchaseReceiptPrintTemplate?: string; stockMovementPrintTemplate?: string; // Point of Sale posCashDenominations?: DefaultCashDenominations[]; posCustomer?: string; static commonFilters = { // Auto Payments salesPaymentAccount: () => ({ isGroup: false, accountType: 'Cash' }), purchasePaymentAccount: () => ({ isGroup: false, accountType: 'Cash' }), // Number Series salesQuoteNumberSeries: () => ({ referenceType: ModelNameEnum.SalesQuote, }), salesInvoiceNumberSeries: () => ({ referenceType: ModelNameEnum.SalesInvoice, }), purchaseInvoiceNumberSeries: () => ({ referenceType: ModelNameEnum.PurchaseInvoice, }), journalEntryNumberSeries: () => ({ referenceType: ModelNameEnum.JournalEntry, }), paymentNumberSeries: () => ({ referenceType: ModelNameEnum.Payment, }), stockMovementNumberSeries: () => ({ referenceType: ModelNameEnum.StockMovement, }), shipmentNumberSeries: () => ({ referenceType: ModelNameEnum.Shipment, }), purchaseReceiptNumberSeries: () => ({ referenceType: ModelNameEnum.PurchaseReceipt, }), // Print Templates salesQuotePrintTemplate: () => ({ type: ModelNameEnum.SalesQuote }), salesInvoicePrintTemplate: () => ({ type: ModelNameEnum.SalesInvoice }), purchaseInvoicePrintTemplate: () => ({ type: ModelNameEnum.PurchaseInvoice, }), journalEntryPrintTemplate: () => ({ type: ModelNameEnum.JournalEntry }), paymentPrintTemplate: () => ({ type: ModelNameEnum.Payment }), shipmentPrintTemplate: () => ({ type: ModelNameEnum.Shipment }), purchaseReceiptPrintTemplate: () => ({ type: ModelNameEnum.PurchaseReceipt, }), stockMovementPrintTemplate: () => ({ type: ModelNameEnum.StockMovement }), posCustomer: () => ({ role: PartyRoleEnum.Customer }), }; static filters: FiltersMap = this.commonFilters; static createFilters: FiltersMap = this.commonFilters; getInventoryHidden() { return () => !this.fyo.singles.AccountingSettings?.enableInventory; } getPointOfSaleHidden() { return () => !this.fyo.singles.InventorySettings?.enablePointOfSale; } hidden: HiddenMap = { stockMovementNumberSeries: this.getInventoryHidden(), shipmentNumberSeries: this.getInventoryHidden(), purchaseReceiptNumberSeries: this.getInventoryHidden(), shipmentTerms: this.getInventoryHidden(), purchaseReceiptTerms: this.getInventoryHidden(), shipmentPrintTemplate: this.getInventoryHidden(), purchaseReceiptPrintTemplate: this.getInventoryHidden(), stockMovementPrintTemplate: this.getInventoryHidden(), posCashDenominations: this.getPointOfSaleHidden(), posCustomer: this.getPointOfSaleHidden(), }; } export const numberSeriesDefaultsMap: Record< string, keyof Defaults | undefined > = { [ModelNameEnum.SalesInvoice]: 'salesInvoiceNumberSeries', [ModelNameEnum.PurchaseInvoice]: 'purchaseInvoiceNumberSeries', [ModelNameEnum.JournalEntry]: 'journalEntryNumberSeries', [ModelNameEnum.Payment]: 'paymentNumberSeries', [ModelNameEnum.StockMovement]: 'stockMovementNumberSeries', [ModelNameEnum.Shipment]: 'shipmentNumberSeries', [ModelNameEnum.PurchaseReceipt]: 'purchaseReceiptNumberSeries', [ModelNameEnum.SalesQuote]: 'salesQuoteNumberSeries', };
2302_79757062/books
models/baseModels/Defaults/Defaults.ts
TypeScript
agpl-3.0
4,525
import { Fyo, t } from 'fyo'; import { DocValueMap } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { CurrenciesMap, DefaultMap, FiltersMap, FormulaMap, HiddenMap, } from 'fyo/model/types'; import { DEFAULT_CURRENCY } from 'fyo/utils/consts'; import { ValidationError } from 'fyo/utils/errors'; import { Transactional } from 'models/Transactional/Transactional'; import { addItem, canApplyPricingRule, createLoyaltyPointEntry, filterPricingRules, getAddedLPWithGrandTotal, getExchangeRate, getNumberSeries, getPricingRulesConflicts, removeLoyaltyPoint, roundFreeItemQty, } from 'models/helpers'; import { StockTransfer } from 'models/inventory/StockTransfer'; import { validateBatch } from 'models/inventory/helpers'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { FieldTypeEnum, Schema } from 'schemas/types'; import { getIsNullOrUndef, joinMapLists, safeParseFloat } from 'utils'; import { Defaults } from '../Defaults/Defaults'; import { InvoiceItem } from '../InvoiceItem/InvoiceItem'; import { Item } from '../Item/Item'; import { Party } from '../Party/Party'; import { Payment } from '../Payment/Payment'; import { Tax } from '../Tax/Tax'; import { TaxSummary } from '../TaxSummary/TaxSummary'; import { ReturnDocItem } from 'models/inventory/types'; import { AccountFieldEnum, PaymentTypeEnum } from '../Payment/types'; import { PricingRule } from '../PricingRule/PricingRule'; import { ApplicablePricingRules } from './types'; import { PricingRuleDetail } from '../PricingRuleDetail/PricingRuleDetail'; import { LoyaltyProgram } from '../LoyaltyProgram/LoyaltyProgram'; export type TaxDetail = { account: string; payment_account?: string; rate: number; }; export type InvoiceTaxItem = { details: TaxDetail; exchangeRate?: number; fullAmount: Money; taxAmount: Money; }; export abstract class Invoice extends Transactional { _taxes: Record<string, Tax> = {}; taxes?: TaxSummary[]; items?: InvoiceItem[]; party?: string; account?: string; currency?: string; priceList?: string; netTotal?: Money; grandTotal?: Money; baseGrandTotal?: Money; outstandingAmount?: Money; exchangeRate?: number; setDiscountAmount?: boolean; discountAmount?: Money; discountPercent?: number; loyaltyPoints?: number; discountAfterTax?: boolean; stockNotTransferred?: number; loyaltyProgram?: string; backReference?: string; submitted?: boolean; cancelled?: boolean; makeAutoPayment?: boolean; makeAutoStockTransfer?: boolean; isReturned?: boolean; returnAgainst?: string; pricingRuleDetail?: PricingRuleDetail[]; get isSales() { return ( this.schemaName === 'SalesInvoice' || this.schemaName == 'SalesQuote' ); } get isQuote() { return this.schemaName == 'SalesQuote'; } get enableDiscounting() { return !!this.fyo.singles?.AccountingSettings?.enableDiscounting; } get isMultiCurrency() { if (!this.currency) { return false; } return this.fyo.singles.SystemSettings!.currency !== this.currency; } get companyCurrency() { return this.fyo.singles.SystemSettings?.currency ?? DEFAULT_CURRENCY; } get stockTransferSchemaName() { return this.isSales ? ModelNameEnum.Shipment : ModelNameEnum.PurchaseReceipt; } get hasLinkedTransfers() { if (!this.submitted) { return false; } return this.getStockTransferred() > 0; } get hasLinkedPayments() { if (!this.submitted) { return false; } return !this.baseGrandTotal?.eq(this.outstandingAmount!); } get autoPaymentAccount(): string | null { const fieldname = this.isSales ? 'salesPaymentAccount' : 'purchasePaymentAccount'; const value = this.fyo.singles.Defaults?.[fieldname]; if (typeof value === 'string' && value.length) { return value; } return null; } get autoStockTransferLocation(): string | null { const fieldname = this.isSales ? 'shipmentLocation' : 'purchaseReceiptLocation'; const value = this.fyo.singles.Defaults?.[fieldname]; if (typeof value === 'string' && value.length) { return value; } return null; } get isReturn(): boolean { return !!this.returnAgainst; } constructor(schema: Schema, data: DocValueMap, fyo: Fyo) { super(schema, data, fyo); this._setGetCurrencies(); } async validate() { await super.validate(); if ( this.enableDiscounting && !this.fyo.singles?.AccountingSettings?.discountAccount ) { throw new ValidationError(this.fyo.t`Discount Account is not set.`); } await validateBatch(this); await this._validatePricingRule(); } async afterSubmit() { await super.afterSubmit(); if (this.isReturn) { await this._removeLoyaltyPointEntry(); } if (this.isQuote) { return; } let lpAddedBaseGrandTotal: Money | undefined; if (this.redeemLoyaltyPoints) { lpAddedBaseGrandTotal = await this.getLPAddedBaseGrandTotal(); } // update outstanding amounts await this.fyo.db.update(this.schemaName, { name: this.name as string, outstandingAmount: lpAddedBaseGrandTotal! || this.baseGrandTotal!, }); const party = (await this.fyo.doc.getDoc( ModelNameEnum.Party, this.party )) as Party; await party.updateOutstandingAmount(); if (this.makeAutoPayment && this.autoPaymentAccount) { const payment = this.getPayment(); await payment?.sync(); await payment?.submit(); await this.load(); } if (this.makeAutoStockTransfer && this.autoStockTransferLocation) { const stockTransfer = await this.getStockTransfer(true); await stockTransfer?.sync(); await stockTransfer?.submit(); await this.load(); } await this._updateIsItemsReturned(); await this._createLoyaltyPointEntry(); } async afterCancel() { await super.afterCancel(); await this._cancelPayments(); await this._updatePartyOutStanding(); await this._updateIsItemsReturned(); await this._removeLoyaltyPointEntry(); } async _removeLoyaltyPointEntry() { if (!this.loyaltyProgram) { return; } await removeLoyaltyPoint(this); } async _cancelPayments() { const paymentIds = await this.getPaymentIds(); for (const paymentId of paymentIds) { const paymentDoc = (await this.fyo.doc.getDoc( 'Payment', paymentId )) as Payment; await paymentDoc.cancel(); } } async _updatePartyOutStanding() { const partyDoc = (await this.fyo.doc.getDoc( ModelNameEnum.Party, this.party )) as Party; await partyDoc.updateOutstandingAmount(); } async afterDelete() { await super.afterDelete(); const paymentIds = await this.getPaymentIds(); for (const name of paymentIds) { const paymentDoc = await this.fyo.doc.getDoc(ModelNameEnum.Payment, name); await paymentDoc.delete(); } } async getPaymentIds() { const payments = (await this.fyo.db.getAll('PaymentFor', { fields: ['parent'], filters: { referenceType: this.schemaName, referenceName: this.name! }, orderBy: 'name', })) as { parent: string }[]; if (payments.length != 0) { return [...new Set(payments.map(({ parent }) => parent))]; } return []; } async getExchangeRate() { if (!this.currency) { return 1.0; } const currency = await this.fyo.getValue( ModelNameEnum.SystemSettings, 'currency' ); if (this.currency === currency) { return 1.0; } const exchangeRate = await getExchangeRate({ fromCurrency: this.currency, toCurrency: currency as string, }); return safeParseFloat(exchangeRate.toFixed(2)); } async getTaxItems(): Promise<InvoiceTaxItem[]> { const taxItems: InvoiceTaxItem[] = []; for (const item of this.items ?? []) { if (!item.tax) { continue; } const tax = await this.getTax(item.tax); for (const details of (tax.details ?? []) as TaxDetail[]) { let amount = item.amount!; if ( this.enableDiscounting && !this.discountAfterTax && !item.itemDiscountedTotal?.isZero() ) { amount = item.itemDiscountedTotal!; } const taxItem: InvoiceTaxItem = { details, exchangeRate: this.exchangeRate ?? 1, fullAmount: amount, taxAmount: amount.mul(details.rate / 100), }; taxItems.push(taxItem); } } return taxItems; } async getTaxSummary() { const taxes: Record< string, { account: string; rate: number; amount: Money; } > = {}; for (const { details, taxAmount } of await this.getTaxItems()) { const account = details.account; taxes[account] ??= { account, rate: details.rate, amount: this.fyo.pesa(0), }; taxes[account].amount = taxes[account].amount.add(taxAmount); } type Summary = typeof taxes[string] & { idx: number }; const taxArr: Summary[] = []; let idx = 0; for (const account in taxes) { const tax = taxes[account]; if (tax.amount.isZero()) { continue; } taxArr.push({ ...tax, idx, }); idx += 1; } return taxArr; } async getTax(tax: string) { if (!this._taxes[tax]) { this._taxes[tax] = await this.fyo.doc.getDoc('Tax', tax); } return this._taxes[tax]; } getTotalDiscount() { if (!this.enableDiscounting) { return this.fyo.pesa(0); } const itemDiscountAmount = this.getItemDiscountAmount(); const invoiceDiscountAmount = this.getInvoiceDiscountAmount(); return itemDiscountAmount.add(invoiceDiscountAmount); } getGrandTotal() { const totalDiscount = this.getTotalDiscount(); return ((this.taxes ?? []) as Doc[]) .map((doc) => doc.amount as Money) .reduce((a, b) => a.add(b), this.netTotal!) .sub(totalDiscount); } getInvoiceDiscountAmount() { if (!this.enableDiscounting) { return this.fyo.pesa(0); } if (this.setDiscountAmount) { return this.discountAmount ?? this.fyo.pesa(0); } let totalItemAmounts = this.fyo.pesa(0); for (const item of this.items ?? []) { if (this.discountAfterTax) { totalItemAmounts = totalItemAmounts.add(item.itemTaxedTotal!); } else { totalItemAmounts = totalItemAmounts.add(item.itemDiscountedTotal!); } } return totalItemAmounts.percent(this.discountPercent ?? 0); } getItemDiscountAmount() { if (!this.enableDiscounting) { return this.fyo.pesa(0); } if (!this?.items?.length) { return this.fyo.pesa(0); } let discountAmount = this.fyo.pesa(0); for (const item of this.items) { if (item.setItemDiscountAmount) { discountAmount = discountAmount.add( item.itemDiscountAmount ?? this.fyo.pesa(0) ); } else if (!this.discountAfterTax) { discountAmount = discountAmount.add( (item.amount ?? this.fyo.pesa(0)).mul( (item.itemDiscountPercent ?? 0) / 100 ) ); } else if (this.discountAfterTax) { discountAmount = discountAmount.add( (item.itemTaxedTotal ?? this.fyo.pesa(0)).mul( (item.itemDiscountPercent ?? 0) / 100 ) ); } } return discountAmount; } async getReturnDoc(): Promise<Invoice | undefined> { if (!this.name) { return; } const docData = this.getValidDict(true, true); const docItems = docData.items as DocValueMap[]; if (!docItems) { return; } let returnDocItems: DocValueMap[] = []; const returnBalanceItemsQty = await this.fyo.db.getReturnBalanceItemsQty( this.schemaName, this.name ); for (const item of docItems) { if (!returnBalanceItemsQty) { returnDocItems = docItems; returnDocItems.map((row) => { row.name = undefined; (row.quantity as number) *= -1; return row; }); break; } const isItemExist = !!returnDocItems.filter( (balanceItem) => balanceItem.item === item.item ).length; if (isItemExist) { continue; } const returnedItem: ReturnDocItem | undefined = returnBalanceItemsQty[item.item as string]; let quantity = returnedItem.quantity; let serialNumber: string | undefined = returnedItem.serialNumbers?.join('\n'); if ( item.batch && returnedItem.batches && returnedItem.batches[item.batch as string] ) { quantity = returnedItem.batches[item.batch as string].quantity; if (returnedItem.batches[item.batch as string].serialNumbers) { serialNumber = returnedItem.batches[item.batch as string].serialNumbers?.join( '\n' ); } } returnDocItems.push({ ...item, serialNumber, name: undefined, quantity: quantity, }); } const returnDocData = { ...docData, name: undefined, date: new Date(), items: returnDocItems, returnAgainst: docData.name, } as DocValueMap; const newReturnDoc = this.fyo.doc.getNewDoc( this.schema.name, returnDocData ) as Invoice; await newReturnDoc.runFormulas(); return newReturnDoc; } async _updateIsItemsReturned() { if (!this.isReturn || !this.returnAgainst || this.isQuote) { return; } const returnInvoices = await this.fyo.db.getAll(this.schema.name, { filters: { submitted: true, cancelled: false, returnAgainst: this.returnAgainst, }, }); const isReturned = !!returnInvoices.length; const invoiceDoc = await this.fyo.doc.getDoc( this.schemaName, this.returnAgainst ); await invoiceDoc.setAndSync({ isReturned }); await invoiceDoc.submit(); } async _createLoyaltyPointEntry() { if (!this.loyaltyProgram) { return; } const loyaltyProgramDoc = (await this.fyo.doc.getDoc( ModelNameEnum.LoyaltyProgram, this.loyaltyProgram )) as LoyaltyProgram; const expiryDate = this.date as Date; const fromDate = loyaltyProgramDoc.fromDate as Date; const toDate = loyaltyProgramDoc.toDate as Date; if (fromDate <= expiryDate && toDate >= expiryDate) { const party = (await this.loadAndGetLink('party')) as Party; await createLoyaltyPointEntry(this); await party.updateLoyaltyPoints(); } } async _validateHasLinkedReturnInvoices() { if (!this.name || this.isReturn || this.isQuote) { 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(', '); throw new ValidationError( this.fyo .t`Cannot cancel ${this.name} because of the following ${this.schema.label}: ${names}` ); } async getLPAddedBaseGrandTotal() { const totalLotaltyAmount = await getAddedLPWithGrandTotal( this.fyo, this.loyaltyProgram as string, this.loyaltyPoints as number ); return totalLotaltyAmount.sub(this.baseGrandTotal as Money).abs(); } formulas: FormulaMap = { account: { formula: async () => { return (await this.fyo.getValue( 'Party', this.party!, 'defaultAccount' )) as string; }, dependsOn: ['party'], }, loyaltyProgram: { formula: async () => { const partyDoc = await this.fyo.doc.getDoc( ModelNameEnum.Party, this.party ); return partyDoc?.loyaltyProgram as string; }, dependsOn: ['party', 'name'], }, currency: { formula: async () => { const currency = (await this.fyo.getValue( 'Party', this.party!, 'currency' )) as string; if (!getIsNullOrUndef(currency)) { return currency; } return this.fyo.singles.SystemSettings!.currency as string; }, dependsOn: ['party'], }, exchangeRate: { formula: async () => { if ( this.currency === (this.fyo.singles.SystemSettings?.currency ?? DEFAULT_CURRENCY) ) { return 1; } if (this.exchangeRate && this.exchangeRate !== 1) { return this.exchangeRate; } return await this.getExchangeRate(); }, dependsOn: ['party', 'currency'], }, netTotal: { formula: () => this.getSum('items', 'amount', false) }, taxes: { formula: async () => await this.getTaxSummary() }, grandTotal: { formula: () => this.getGrandTotal() }, baseGrandTotal: { formula: () => (this.grandTotal as Money).mul(this.exchangeRate! ?? 1), dependsOn: ['grandTotal', 'exchangeRate'], }, outstandingAmount: { formula: async () => { if (this.submitted) { return; } if (this.redeemLoyaltyPoints) { return await this.getLPAddedBaseGrandTotal(); } return this.baseGrandTotal; }, }, stockNotTransferred: { formula: () => { if (this.submitted) { return; } return this.getStockNotTransferred(); }, dependsOn: ['items'], }, makeAutoPayment: { formula: () => !!this.autoPaymentAccount, dependsOn: [], }, makeAutoStockTransfer: { formula: () => !!this.fyo.singles.AccountingSettings?.enableInventory && !!this.autoStockTransferLocation, dependsOn: [], }, isPricingRuleApplied: { formula: async () => { if (!this.fyo.singles.AccountingSettings?.enablePricingRule) { return false; } const pricingRule = await this.getPricingRule(); if (!pricingRule) { return false; } await this.appendPricingRuleDetail(pricingRule); return !!pricingRule; }, dependsOn: ['items'], }, }; getStockTransferred() { return (this.items ?? []).reduce( (acc, item) => (item.quantity ?? 0) - (item.stockNotTransferred ?? 0) + acc, 0 ); } getTotalQuantity() { return (this.items ?? []).reduce( (acc, item) => acc + (item.quantity ?? 0), 0 ); } getStockNotTransferred() { return (this.items ?? []).reduce( (acc, item) => (item.stockNotTransferred ?? 0) + acc, 0 ); } getItemDiscountedAmounts() { let itemDiscountedAmounts = this.fyo.pesa(0); for (const item of this.items ?? []) { itemDiscountedAmounts = itemDiscountedAmounts.add( item.itemDiscountedTotal ?? item.amount! ); } return itemDiscountedAmounts; } hidden: HiddenMap = { makeAutoPayment: () => { if (this.submitted) { return true; } return !this.autoPaymentAccount; }, makeAutoStockTransfer: () => { if (this.submitted) { return true; } if (!this.fyo.singles.AccountingSettings?.enableInventory) { return true; } return !this.autoStockTransferLocation; }, setDiscountAmount: () => true || !this.enableDiscounting, discountAmount: () => true || !(this.enableDiscounting && !!this.setDiscountAmount), discountPercent: () => true || !(this.enableDiscounting && !this.setDiscountAmount), discountAfterTax: () => !this.enableDiscounting, taxes: () => !this.taxes?.length, baseGrandTotal: () => this.exchangeRate === 1 || this.baseGrandTotal!.isZero(), grandTotal: () => !this.taxes?.length, stockNotTransferred: () => !this.stockNotTransferred, outstandingAmount: () => !!this.outstandingAmount?.isZero() || !this.isSubmitted, terms: () => !(this.terms || !(this.isSubmitted || this.isCancelled)), attachment: () => !(this.attachment || !(this.isSubmitted || this.isCancelled)), backReference: () => !this.backReference, quote: () => !this.quote, loyaltyProgram: () => !this.loyaltyProgram, loyaltyPoints: () => !this.redeemLoyaltyPoints || this.isReturn, redeemLoyaltyPoints: () => !this.loyaltyProgram || this.isReturn, priceList: () => !this.fyo.singles.AccountingSettings?.enablePriceList || (!this.canEdit && !this.priceList), returnAgainst: () => (this.isSubmitted || this.isCancelled) && !this.returnAgainst, pricingRuleDetail: () => !this.fyo.singles.AccountingSettings?.enablePricingRule || !this.pricingRuleDetail?.length, }; static defaults: DefaultMap = { makeAutoPayment: (doc) => doc instanceof Invoice && !!doc.autoPaymentAccount, makeAutoStockTransfer: (doc) => !!doc.fyo.singles.AccountingSettings?.enableInventory && doc instanceof Invoice && !!doc.autoStockTransferLocation, numberSeries: (doc) => getNumberSeries(doc.schemaName, doc.fyo), terms: (doc) => { const defaults = doc.fyo.singles.Defaults; if (doc.schemaName === ModelNameEnum.SalesInvoice) { return defaults?.salesInvoiceTerms ?? ''; } return defaults?.purchaseInvoiceTerms ?? ''; }, date: () => new Date(), }; static filters: FiltersMap = { party: (doc: Doc) => ({ role: ['in', [doc.isSales ? 'Customer' : 'Supplier', 'Both']], }), account: (doc: Doc) => ({ isGroup: false, accountType: doc.isSales ? 'Receivable' : 'Payable', }), numberSeries: (doc: Doc) => ({ referenceType: doc.schemaName }), priceList: (doc: Doc) => ({ isEnabled: true, ...(doc.isSales ? { isSales: true } : { isPurchase: true }), }), }; static createFilters: FiltersMap = { party: (doc: Doc) => ({ role: doc.isSales ? 'Customer' : 'Supplier', }), }; getCurrencies: CurrenciesMap = { baseGrandTotal: () => this.companyCurrency, outstandingAmount: () => this.companyCurrency, }; _getCurrency() { if (this.exchangeRate === 1) { return this.companyCurrency; } return this.currency ?? DEFAULT_CURRENCY; } _setGetCurrencies() { const currencyFields = this.schema.fields.filter( ({ fieldtype }) => fieldtype === FieldTypeEnum.Currency ); for (const { fieldname } of currencyFields) { this.getCurrencies[fieldname] ??= this._getCurrency.bind(this); } } getPayment(): Payment | null { if (!this.isSubmitted) { return null; } const outstandingAmount = this.outstandingAmount; if (!outstandingAmount) { return null; } if (this.outstandingAmount?.isZero()) { return null; } let accountField: AccountFieldEnum = AccountFieldEnum.Account; let paymentType: PaymentTypeEnum = PaymentTypeEnum.Receive; if (this.isSales && this.isReturn) { accountField = AccountFieldEnum.PaymentAccount; paymentType = PaymentTypeEnum.Pay; } if (!this.isSales) { accountField = AccountFieldEnum.PaymentAccount; paymentType = PaymentTypeEnum.Pay; if (this.isReturn) { accountField = AccountFieldEnum.Account; paymentType = PaymentTypeEnum.Receive; } } const data = { party: this.party, date: new Date().toISOString().slice(0, 10), paymentType, amount: this.outstandingAmount?.abs(), [accountField]: this.account, for: [ { referenceType: this.schemaName, referenceName: this.name, amount: this.outstandingAmount, }, ], }; if (this.makeAutoPayment && this.autoPaymentAccount) { const autoPaymentAccount = this.isSales ? 'paymentAccount' : 'account'; data[autoPaymentAccount] = this.autoPaymentAccount; } return this.fyo.doc.getNewDoc(ModelNameEnum.Payment, data) as Payment; } async getStockTransfer(isAuto = false): Promise<StockTransfer | null> { if (!this.isSubmitted) { return null; } if (!this.stockNotTransferred) { return null; } const schemaName = this.stockTransferSchemaName; const defaults = (this.fyo.singles.Defaults as Defaults) ?? {}; let terms; let numberSeries; if (this.isSales) { terms = defaults.shipmentTerms ?? ''; numberSeries = defaults.shipmentNumberSeries ?? undefined; } else { terms = defaults.purchaseReceiptTerms ?? ''; numberSeries = defaults.purchaseReceiptNumberSeries ?? undefined; } const data = { party: this.party, date: new Date().toISOString(), terms, numberSeries, backReference: this.name, }; let location = this.autoStockTransferLocation; if (!location) { location = this.fyo.singles.InventorySettings?.defaultLocation ?? null; } if (isAuto && !location) { return null; } const transfer = this.fyo.doc.getNewDoc(schemaName, data) as StockTransfer; for (const row of this.items ?? []) { if (!row.item) { continue; } const itemDoc = (await row.loadAndGetLink('item')) as Item; if (isAuto && (itemDoc.hasBatch || itemDoc.hasSerialNumber)) { continue; } const item = row.item; const quantity = row.stockNotTransferred; const trackItem = itemDoc.trackItem; const batch = row.batch || null; const description = row.description; const hsnCode = row.hsnCode; let rate = row.rate as Money; if (this.exchangeRate && this.exchangeRate > 1) { rate = rate.mul(this.exchangeRate); } if (!quantity || !trackItem) { continue; } if (isAuto) { const stock = (await this.fyo.db.getStockQuantity( item, location!, undefined, data.date )) ?? 0; if (stock < quantity) { continue; } } await transfer.append('items', { item, quantity, location, rate, batch, description, hsnCode, }); } if (!transfer.items?.length) { return null; } return transfer; } async beforeSync(): Promise<void> { await super.beforeSync(); if (this.pricingRuleDetail?.length) { await this.applyProductDiscount(); } else { this.clearFreeItems(); } } async beforeCancel(): Promise<void> { await super.beforeCancel(); await this._validateStockTransferCancelled(); await this._validateHasLinkedReturnInvoices(); } async beforeDelete(): Promise<void> { await super.beforeCancel(); await this._validateStockTransferCancelled(); await this._deleteCancelledStockTransfers(); } async _deleteCancelledStockTransfers() { const schemaName = this.stockTransferSchemaName; const transfers = await this._getLinkedStockTransferNames(true); for (const { name } of transfers) { const st = await this.fyo.doc.getDoc(schemaName, name); await st.delete(); } } async _validateStockTransferCancelled() { const schemaName = this.stockTransferSchemaName; const transfers = await this._getLinkedStockTransferNames(false); if (!transfers?.length) { return; } const names = transfers.map(({ name }) => name).join(', '); const label = this.fyo.schemaMap[schemaName]?.label ?? schemaName; 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) { throw new ValidationError(`Name not found for ${this.schema.label}`); } const schemaName = this.stockTransferSchemaName; const transfers = (await this.fyo.db.getAllRaw(schemaName, { fields: ['name'], filters: { backReference: this.name!, cancelled }, })) as { name: string }[]; return transfers; } async getLinkedPayments() { if (!this.hasLinkedPayments) { return []; } const paymentFors = (await this.fyo.db.getAllRaw('PaymentFor', { fields: ['parent', 'amount'], filters: { referenceName: this.name!, referenceType: this.schemaName }, })) as { parent: string; amount: string }[]; const payments = (await this.fyo.db.getAllRaw('Payment', { fields: ['name', 'date', 'submitted', 'cancelled'], filters: { name: ['in', paymentFors.map((p) => p.parent)] }, })) as { name: string; date: string; submitted: number; cancelled: number; }[]; return joinMapLists(payments, paymentFors, 'name', 'parent') .map((j) => ({ name: j.name, date: new Date(j.date), submitted: !!j.submitted, cancelled: !!j.cancelled, amount: this.fyo.pesa(j.amount), })) .sort((a, b) => a.date.valueOf() - b.date.valueOf()); } async getLinkedStockTransfers() { if (!this.hasLinkedTransfers) { return []; } const schemaName = this.stockTransferSchemaName; const transfers = (await this.fyo.db.getAllRaw(schemaName, { fields: ['name', 'date', 'submitted', 'cancelled'], filters: { backReference: this.name! }, })) as { name: string; date: string; submitted: number; cancelled: number; }[]; const itemSchemaName = schemaName + 'Item'; const transferItems = (await this.fyo.db.getAllRaw(itemSchemaName, { fields: ['parent', 'quantity', 'location', 'amount'], filters: { parent: ['in', transfers.map((t) => t.name)], item: ['in', this.items!.map((i) => i.item!)], }, })) as { parent: string; quantity: number; location: string; amount: string; }[]; return joinMapLists(transfers, transferItems, 'name', 'parent') .map((j) => ({ name: j.name, date: new Date(j.date), submitted: !!j.submitted, cancelled: !!j.cancelled, amount: this.fyo.pesa(j.amount), location: j.location, quantity: j.quantity, })) .sort((a, b) => a.date.valueOf() - b.date.valueOf()); } async addItem(name: string) { return await addItem(name, this); } async appendPricingRuleDetail( applicablePricingRule: ApplicablePricingRules[] ) { await this.set('pricingRuleDetail', null); for (const doc of applicablePricingRule) { await this.append('pricingRuleDetail', { referenceName: doc.pricingRule.name, referenceItem: doc.applyOnItem, }); } } clearFreeItems() { if (this.pricingRuleDetail?.length || !this.items) { return; } for (const item of this.items) { if (item.isFreeItem) { this.items = this.items?.filter( (invoiceItem) => invoiceItem.name !== item.name ); } } } async applyProductDiscount() { if (!this.items) { return; } this.items = this.items.filter((item) => !item.isFreeItem); for (const item of this.items) { const pricingRuleDetailForItem = this.pricingRuleDetail?.filter( (doc) => doc.referenceItem === item.item ); if (!pricingRuleDetailForItem?.length) { continue; } const pricingRuleDoc = (await this.fyo.doc.getDoc( ModelNameEnum.PricingRule, pricingRuleDetailForItem[0].referenceName )) as PricingRule; if (pricingRuleDoc.discountType === 'Price Discount') { continue; } const appliedItems = pricingRuleDoc.appliedItems?.map((doc) => doc.item); if (!appliedItems?.includes(item.item)) { continue; } const canApplyPRLOnItem = canApplyPricingRule( pricingRuleDoc, this.date as Date, item.quantity as number, item.amount as Money ); if (!canApplyPRLOnItem) { continue; } let freeItemQty = pricingRuleDoc.freeItemQuantity as number; if (pricingRuleDoc.isRecursive) { freeItemQty = (item.quantity as number) / (pricingRuleDoc.recurseEvery as number); } if (pricingRuleDoc.roundFreeItemQty) { freeItemQty = roundFreeItemQty( freeItemQty, pricingRuleDoc.roundingMethod as 'round' | 'floor' | 'ceil' ); } await this.append('items', { item: pricingRuleDoc.freeItem as string, quantity: freeItemQty, isFreeItem: true, pricingRule: pricingRuleDoc.title, rate: pricingRuleDoc.freeItemRate, unit: pricingRuleDoc.freeItemUnit, }); } } async getPricingRule(): Promise<ApplicablePricingRules[] | undefined> { if (!this.isSales || !this.items) { return; } const pricingRules: ApplicablePricingRules[] = []; for (const item of this.items) { if (item.isFreeItem) { continue; } const duplicatePricingRule = this.pricingRuleDetail?.filter( (pricingrule: PricingRuleDetail) => pricingrule.referenceItem == item.item ); if (duplicatePricingRule && duplicatePricingRule?.length >= 2) { const { showToast } = await import('src/utils/interactive'); const message = t`Pricing Rule '${ duplicatePricingRule[0]?.referenceName as string }' is already applied to item '${ item.item as string }' in another batch.`; showToast({ type: 'error', message }); continue; } const pricingRuleDocNames = ( await this.fyo.db.getAll(ModelNameEnum.PricingRuleItem, { fields: ['parent'], filters: { item: item.item as string, unit: item.unit as string, }, }) ).map((doc) => doc.parent) as string[]; const pricingRuleDocsForItem = (await this.fyo.db.getAll( ModelNameEnum.PricingRule, { fields: ['*'], filters: { name: ['in', pricingRuleDocNames], isEnabled: true, }, orderBy: 'priority', order: 'desc', } )) as PricingRule[]; const filtered = filterPricingRules( pricingRuleDocsForItem, this.date as Date, item.quantity as number, item.amount as Money ); if (!filtered.length) { continue; } const isPricingRuleHasConflicts = getPricingRulesConflicts(filtered); if (isPricingRuleHasConflicts) { continue; } pricingRules.push({ applyOnItem: item.item as string, pricingRule: filtered[0], }); } return pricingRules; } async _validatePricingRule() { if (!this.fyo.singles.AccountingSettings?.enablePricingRule) { return; } if (!this.items) { return; } await this.getPricingRule(); } }
2302_79757062/books
models/baseModels/Invoice/Invoice.ts
TypeScript
agpl-3.0
35,252
import { PricingRule } from '../PricingRule/PricingRule'; export interface ApplicablePricingRules { applyOnItem: string; pricingRule: PricingRule; }
2302_79757062/books
models/baseModels/Invoice/types.ts
TypeScript
agpl-3.0
154
import { Fyo, t } from 'fyo'; import { DocValue, DocValueMap } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { CurrenciesMap, FiltersMap, FormulaMap, HiddenMap, ValidationMap, } from 'fyo/model/types'; import { DEFAULT_CURRENCY } from 'fyo/utils/consts'; import { ValidationError } from 'fyo/utils/errors'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { FieldTypeEnum, Schema } from 'schemas/types'; import { safeParseFloat } from 'utils/index'; import { Invoice } from '../Invoice/Invoice'; import { Item } from '../Item/Item'; import { StockTransfer } from 'models/inventory/StockTransfer'; import { PriceList } from '../PriceList/PriceList'; import { isPesa } from 'fyo/utils'; import { PricingRule } from '../PricingRule/PricingRule'; export abstract class InvoiceItem extends Doc { item?: string; account?: string; amount?: Money; parentdoc?: Invoice; rate?: Money; description?: string; hsnCode?: number; unit?: string; transferUnit?: string; quantity?: number; transferQuantity?: number; unitConversionFactor?: number; batch?: string; tax?: string; stockNotTransferred?: number; setItemDiscountAmount?: boolean; itemDiscountAmount?: Money; itemDiscountPercent?: number; itemDiscountedTotal?: Money; itemTaxedTotal?: Money; isFreeItem?: boolean; get isSales() { return ( this.schemaName === 'SalesInvoiceItem' || this.schemaName === 'SalesQuoteItem' ); } get date() { return this.parentdoc?.date ?? undefined; } get party() { return this.parentdoc?.party ?? undefined; } get priceList() { return this.parentdoc?.priceList ?? undefined; } get discountAfterTax() { return !!this?.parentdoc?.discountAfterTax; } get enableDiscounting() { return !!this.fyo.singles?.AccountingSettings?.enableDiscounting; } get enableInventory() { return !!this.fyo.singles?.AccountingSettings?.enableInventory; } get currency() { return this.parentdoc?.currency ?? DEFAULT_CURRENCY; } get exchangeRate() { return this.parentdoc?.exchangeRate ?? 1; } get isMultiCurrency() { return this.parentdoc?.isMultiCurrency ?? false; } get isReturn() { return !!this.parentdoc?.isReturn; } get pricingRuleDetail() { return this.parentdoc?.pricingRuleDetail; } constructor(schema: Schema, data: DocValueMap, fyo: Fyo) { super(schema, data, fyo); this._setGetCurrencies(); } async getTotalTaxRate(): Promise<number> { if (!this.tax) { return 0; } const details = ((await this.fyo.getValue('Tax', this.tax, 'details')) as Doc[]) ?? []; return details.reduce((acc, doc) => { return (doc.rate as number) + acc; }, 0); } formulas: FormulaMap = { description: { formula: async () => (await this.fyo.getValue( 'Item', this.item as string, 'description' )) as string, dependsOn: ['item'], }, rate: { formula: async (fieldname) => { const rate = await getItemRate(this); if (!rate?.float && this.rate?.float) { return this.rate; } if ( fieldname !== 'itemTaxedTotal' && fieldname !== 'itemDiscountedTotal' ) { return rate?.div(this.exchangeRate) ?? this.fyo.pesa(0); } const quantity = this.quantity ?? 0; const itemDiscountPercent = this.itemDiscountPercent ?? 0; const itemDiscountAmount = this.itemDiscountAmount ?? this.fyo.pesa(0); const totalTaxRate = await this.getTotalTaxRate(); const itemTaxedTotal = this.itemTaxedTotal ?? this.fyo.pesa(0); const itemDiscountedTotal = this.itemDiscountedTotal ?? this.fyo.pesa(0); const isItemTaxedTotal = fieldname === 'itemTaxedTotal'; const discountAfterTax = this.discountAfterTax; const setItemDiscountAmount = !!this.setItemDiscountAmount; const rateFromTotals = getRate( quantity, itemDiscountPercent, itemDiscountAmount, totalTaxRate, itemTaxedTotal, itemDiscountedTotal, isItemTaxedTotal, discountAfterTax, setItemDiscountAmount ); return rateFromTotals ?? rate ?? this.fyo.pesa(0); }, dependsOn: [ 'date', 'priceList', 'batch', 'party', 'exchangeRate', 'item', 'itemTaxedTotal', 'itemDiscountedTotal', 'setItemDiscountAmount', 'pricingRuleDetail', ], }, unit: { formula: async () => (await this.fyo.getValue( 'Item', this.item as string, 'unit' )) as string, dependsOn: ['item'], }, transferUnit: { formula: async (fieldname) => { if (fieldname === 'quantity' || fieldname === 'unit') { return this.unit; } return (await this.fyo.getValue( 'Item', this.item as string, 'unit' )) as string; }, dependsOn: ['item', 'unit'], }, transferQuantity: { formula: (fieldname) => { if (fieldname === 'quantity' || this.unit === this.transferUnit) { return this.quantity; } return this.transferQuantity; }, dependsOn: ['item', 'quantity'], }, quantity: { formula: async (fieldname) => { if (!this.item) { return this.quantity as number; } const itemDoc = await this.fyo.doc.getDoc( ModelNameEnum.Item, this.item ); const unitDoc = itemDoc.getLink('uom'); let quantity: number = this.quantity ?? 1; if (this.isReturn && quantity > 0) { quantity *= -1; } if (!this.isReturn && quantity < 0) { quantity *= -1; } if (fieldname === 'transferQuantity') { quantity = this.transferQuantity! * this.unitConversionFactor!; } if (unitDoc?.isWhole) { return Math.round(quantity); } return safeParseFloat(quantity); }, dependsOn: [ 'quantity', 'transferQuantity', 'transferUnit', 'unitConversionFactor', 'item', 'isReturn', ], }, unitConversionFactor: { formula: async () => { if (this.unit === this.transferUnit) { return 1; } const conversionFactor = await this.fyo.db.getAll( ModelNameEnum.UOMConversionItem, { fields: ['conversionFactor'], filters: { parent: this.item! }, } ); return safeParseFloat(conversionFactor[0]?.conversionFactor ?? 1); }, dependsOn: ['transferUnit'], }, account: { formula: () => { let accountType = 'expenseAccount'; if (this.isSales) { accountType = 'incomeAccount'; } return this.fyo.getValue('Item', this.item as string, accountType); }, dependsOn: ['item'], }, tax: { formula: async () => { return (await this.fyo.getValue( 'Item', this.item as string, 'tax' )) as string; }, dependsOn: ['item'], }, amount: { formula: () => (this.rate as Money).mul(this.quantity as number), dependsOn: ['item', 'rate', 'quantity'], }, hsnCode: { formula: async () => await this.fyo.getValue('Item', this.item as string, 'hsnCode'), dependsOn: ['item'], }, itemDiscountedTotal: { formula: async () => { const totalTaxRate = await this.getTotalTaxRate(); const rate = this.rate ?? this.fyo.pesa(0); const quantity = this.quantity ?? 1; const itemDiscountAmount = this.itemDiscountAmount ?? this.fyo.pesa(0); const itemDiscountPercent = this.itemDiscountPercent ?? 0; if (this.setItemDiscountAmount && this.itemDiscountAmount?.isZero()) { return rate.mul(quantity); } if (!this.setItemDiscountAmount && this.itemDiscountPercent === 0) { return rate.mul(quantity); } if (!this.discountAfterTax) { return getDiscountedTotalBeforeTaxation( rate, quantity, itemDiscountAmount, itemDiscountPercent, !!this.setItemDiscountAmount ); } return getDiscountedTotalAfterTaxation( totalTaxRate, rate, quantity, itemDiscountAmount, itemDiscountPercent, !!this.setItemDiscountAmount ); }, dependsOn: [ 'itemDiscountAmount', 'itemDiscountPercent', 'itemTaxedTotal', 'setItemDiscountAmount', 'tax', 'rate', 'quantity', 'item', ], }, itemTaxedTotal: { formula: async () => { const totalTaxRate = await this.getTotalTaxRate(); const rate = this.rate ?? this.fyo.pesa(0); const quantity = this.quantity ?? 1; const itemDiscountAmount = this.itemDiscountAmount ?? this.fyo.pesa(0); const itemDiscountPercent = this.itemDiscountPercent ?? 0; if (!this.discountAfterTax) { return getTaxedTotalAfterDiscounting( totalTaxRate, rate, quantity, itemDiscountAmount, itemDiscountPercent, !!this.setItemDiscountAmount ); } return getTaxedTotalBeforeDiscounting(totalTaxRate, rate, quantity); }, dependsOn: [ 'itemDiscountAmount', 'itemDiscountPercent', 'itemDiscountedTotal', 'setItemDiscountAmount', 'tax', 'rate', 'quantity', 'item', ], }, stockNotTransferred: { formula: async () => { if (this.parentdoc?.isSubmitted) { return; } const item = (await this.loadAndGetLink('item')) as Item; if (!item.trackItem) { return 0; } const { backReference, stockTransferSchemaName } = this.parentdoc ?? {}; if ( !backReference || !stockTransferSchemaName || typeof this.quantity !== 'number' ) { return this.quantity; } const refdoc = (await this.fyo.doc.getDoc( stockTransferSchemaName, backReference )) as StockTransfer; const transferred = refdoc.items ?.filter((i) => i.item === this.item) .reduce((acc, i) => i.quantity ?? 0 + acc, 0) ?? 0; return Math.max(0, this.quantity - transferred); }, dependsOn: ['item', 'quantity'], }, setItemDiscountAmount: { formula: async () => { if ( !this.fyo.singles.AccountingSettings?.enablePricingRule || !this.parentdoc?.pricingRuleDetail ) { return this.setItemDiscountAmount; } const pricingRule = this.parentdoc?.pricingRuleDetail?.filter( (prDetail) => prDetail.referenceItem === this.item ); if (!pricingRule) { return this.setItemDiscountAmount; } const pricingRuleDoc = (await this.fyo.doc.getDoc( ModelNameEnum.PricingRule, pricingRule[0].referenceName )) as PricingRule; if (pricingRuleDoc.discountType === 'Product Discount') { return this.setItemDiscountAmount; } if (pricingRuleDoc.priceDiscountType === 'amount') { const discountAmount = pricingRuleDoc.discountAmount?.mul( this.quantity as number ); await this.set('itemDiscountAmount', discountAmount); return true; } return this.setItemDiscountAmount; }, dependsOn: ['pricingRuleDetail'], }, itemDiscountPercent: { formula: async () => { if ( !this.fyo.singles.AccountingSettings?.enablePricingRule || !this.parentdoc?.pricingRuleDetail ) { return this.itemDiscountPercent; } const pricingRule = this.parentdoc?.pricingRuleDetail?.filter( (prDetail) => prDetail.referenceItem === this.item ); if (!pricingRule) { return this.itemDiscountPercent; } const pricingRuleDoc = (await this.fyo.doc.getDoc( ModelNameEnum.PricingRule, pricingRule[0].referenceName )) as PricingRule; if (pricingRuleDoc.discountType === 'Product Discount') { return this.itemDiscountPercent; } if (pricingRuleDoc.priceDiscountType === 'percentage') { await this.set('setItemDiscountAmount', false); return pricingRuleDoc.discountPercentage; } return this.itemDiscountPercent; }, dependsOn: ['pricingRuleDetail'], }, }; validations: ValidationMap = { rate: (value: DocValue) => { if ((value as Money).gte(0)) { return; } throw new ValidationError( this.fyo.t`Rate (${this.fyo.format( value, 'Currency' )}) cannot be less zero.` ); }, itemDiscountAmount: (value: DocValue) => { if ((value as Money).lte(this.amount!)) { return; } throw new ValidationError( this.fyo.t`Discount Amount (${this.fyo.format( value, 'Currency' )}) cannot be greated than Amount (${this.fyo.format( this.amount!, 'Currency' )}).` ); }, itemDiscountPercent: (value: DocValue) => { if ((value as number) < 100) { return; } throw new ValidationError( this.fyo.t`Discount Percent (${ value as number }) cannot be greater than 100.` ); }, transferUnit: async (value: DocValue) => { if (!this.item) { return; } const item = await this.fyo.db.getAll(ModelNameEnum.UOMConversionItem, { fields: ['parent'], filters: { uom: value as string, parent: this.item }, }); if (item.length < 1) throw new ValidationError( t`Transfer Unit ${value as string} is not applicable for Item ${ this.item }` ); }, }; hidden: HiddenMap = { itemDiscountedTotal: () => { if (!this.enableDiscounting) { return true; } if (!!this.setItemDiscountAmount && this.itemDiscountAmount?.isZero()) { return true; } if (!this.setItemDiscountAmount && this.itemDiscountPercent === 0) { return true; } return false; }, setItemDiscountAmount: () => !this.enableDiscounting, itemDiscountAmount: () => !(this.enableDiscounting && !!this.setItemDiscountAmount), itemDiscountPercent: () => !(this.enableDiscounting && !this.setItemDiscountAmount), batch: () => !this.fyo.singles.InventorySettings?.enableBatches, transferUnit: () => !this.fyo.singles.InventorySettings?.enableUomConversions, transferQuantity: () => !this.fyo.singles.InventorySettings?.enableUomConversions, unitConversionFactor: () => !this.fyo.singles.InventorySettings?.enableUomConversions, }; static filters: FiltersMap = { item: (doc: Doc) => { let itemNotFor = 'Sales'; if (doc.isSales) { itemNotFor = 'Purchases'; } return { for: ['not in', [itemNotFor]] }; }, }; static createFilters: FiltersMap = { item: (doc: Doc) => { return { for: doc.isSales ? 'Sales' : 'Purchases' }; }, }; getCurrencies: CurrenciesMap = {}; _getCurrency() { if (this.exchangeRate === 1) { return this.fyo.singles.SystemSettings?.currency ?? DEFAULT_CURRENCY; } return this.currency; } _setGetCurrencies() { const currencyFields = this.schema.fields.filter( ({ fieldtype }) => fieldtype === FieldTypeEnum.Currency ); for (const { fieldname } of currencyFields) { this.getCurrencies[fieldname] ??= this._getCurrency.bind(this); } } } async function getItemRate(doc: InvoiceItem): Promise<Money | undefined> { if (doc.isFreeItem) { return doc.rate; } let pricingRuleRate: Money | undefined; if (doc.fyo.singles.AccountingSettings?.enablePricingRule) { pricingRuleRate = await getItemRateFromPricingRule(doc); } if (pricingRuleRate) { return pricingRuleRate; } let priceListRate: Money | undefined; if (doc.fyo.singles.AccountingSettings?.enablePriceList) { priceListRate = await getItemRateFromPriceList(doc); } if (priceListRate) { return priceListRate; } if (!doc.item) { return; } const itemRate = await doc.fyo.getValue(ModelNameEnum.Item, doc.item, 'rate'); if (isPesa(itemRate)) { return itemRate; } return; } async function getItemRateFromPricingRule( doc: InvoiceItem ): Promise<Money | undefined> { const pricingRule = doc.parentdoc?.pricingRuleDetail?.filter( (prDetail) => prDetail.referenceItem === doc.item ); if (!pricingRule) { return; } const pricingRuleDoc = (await doc.fyo.doc.getDoc( ModelNameEnum.PricingRule, pricingRule[0].referenceName )) as PricingRule; if (pricingRuleDoc.discountType !== 'Price Discount') { return; } if (pricingRuleDoc.priceDiscountType !== 'rate') { return; } return pricingRuleDoc.discountRate; } async function getItemRateFromPriceList( doc: InvoiceItem ): Promise<Money | undefined> { const priceListName = doc.parentdoc?.priceList; const item = doc.item; if (!priceListName || !item) { return; } const priceList = await doc.fyo.doc.getDoc( ModelNameEnum.PriceList, priceListName ); if (!(priceList instanceof PriceList)) { return; } const unit = doc.unit; const transferUnit = doc.transferUnit; const plItem = priceList.priceListItem?.find((pli) => { if (pli.item !== item) { return false; } if (transferUnit && pli.unit !== transferUnit) { return false; } else if (unit && pli.unit !== unit) { return false; } return true; }); return plItem?.rate; } function getDiscountedTotalBeforeTaxation( rate: Money, quantity: number, itemDiscountAmount: Money, itemDiscountPercent: number, setDiscountAmount: boolean ) { /** * If Discount is applied before taxation * Use different formulas depending on how discount is set * - if amount : Quantity * Rate - DiscountAmount * - if percent: Quantity * Rate (1 - DiscountPercent / 100) */ const amount = rate.mul(quantity); if (setDiscountAmount) { return amount.sub(itemDiscountAmount); } return amount.mul(1 - itemDiscountPercent / 100); } function getTaxedTotalAfterDiscounting( totalTaxRate: number, rate: Money, quantity: number, itemDiscountAmount: Money, itemDiscountPercent: number, setItemDiscountAmount: boolean ) { /** * If Discount is applied before taxation * Formula: Discounted Total * (1 + TotalTaxRate / 100) */ const discountedTotal = getDiscountedTotalBeforeTaxation( rate, quantity, itemDiscountAmount, itemDiscountPercent, setItemDiscountAmount ); return discountedTotal.mul(1 + totalTaxRate / 100); } function getDiscountedTotalAfterTaxation( totalTaxRate: number, rate: Money, quantity: number, itemDiscountAmount: Money, itemDiscountPercent: number, setItemDiscountAmount: boolean ) { /** * If Discount is applied after taxation * Use different formulas depending on how discount is set * - if amount : Taxed Total - Discount Amount * - if percent: Taxed Total * (1 - Discount Percent / 100) */ const taxedTotal = getTaxedTotalBeforeDiscounting( totalTaxRate, rate, quantity ); if (setItemDiscountAmount) { return taxedTotal.sub(itemDiscountAmount); } return taxedTotal.mul(1 - itemDiscountPercent / 100); } function getTaxedTotalBeforeDiscounting( totalTaxRate: number, rate: Money, quantity: number ) { /** * If Discount is applied after taxation * Formula: Rate * Quantity * (1 + Total Tax Rate / 100) */ return rate.mul(quantity).mul(1 + totalTaxRate / 100); } function getRate( quantity: number, itemDiscountPercent: number, itemDiscountAmount: Money, totalTaxRate: number, itemTaxedTotal: Money, itemDiscountedTotal: Money, isItemTaxedTotal: boolean, discountAfterTax: boolean, setItemDiscountAmount: boolean ) { const isItemDiscountedTotal = !isItemTaxedTotal; const discountBeforeTax = !discountAfterTax; /** * Rate calculated from itemDiscountedTotal */ if (isItemDiscountedTotal && discountBeforeTax && setItemDiscountAmount) { return itemDiscountedTotal.add(itemDiscountAmount).div(quantity); } if (isItemDiscountedTotal && discountBeforeTax && !setItemDiscountAmount) { return itemDiscountedTotal.div(quantity * (1 - itemDiscountPercent / 100)); } if (isItemDiscountedTotal && discountAfterTax && setItemDiscountAmount) { return itemDiscountedTotal .add(itemDiscountAmount) .div(quantity * (1 + totalTaxRate / 100)); } if (isItemDiscountedTotal && discountAfterTax && !setItemDiscountAmount) { return itemDiscountedTotal.div( (quantity * (100 - itemDiscountPercent) * (100 + totalTaxRate)) / 100 ); } /** * Rate calculated from itemTaxedTotal */ if (isItemTaxedTotal && discountAfterTax) { return itemTaxedTotal.div(quantity * (1 + totalTaxRate / 100)); } if (isItemTaxedTotal && discountBeforeTax && setItemDiscountAmount) { return itemTaxedTotal .div(1 + totalTaxRate / 100) .add(itemDiscountAmount) .div(quantity); } if (isItemTaxedTotal && discountBeforeTax && !setItemDiscountAmount) { return itemTaxedTotal.div( quantity * (1 - itemDiscountPercent / 100) * (1 + totalTaxRate / 100) ); } return null; }
2302_79757062/books
models/baseModels/InvoiceItem/InvoiceItem.ts
TypeScript
agpl-3.0
22,122
import { Fyo } from 'fyo'; import { DocValue } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { Action, FiltersMap, FormulaMap, HiddenMap, ListViewSettings, ReadOnlyMap, ValidationMap, } from 'fyo/model/types'; import { ValidationError } from 'fyo/utils/errors'; import { Money } from 'pesa'; import { AccountRootTypeEnum, AccountTypeEnum } from '../Account/types'; export class Item extends Doc { trackItem?: boolean; itemType?: 'Product' | 'Service'; for?: 'Purchases' | 'Sales' | 'Both'; hasBatch?: boolean; hasSerialNumber?: boolean; formulas: FormulaMap = { incomeAccount: { formula: async () => { let accountName = 'Service'; if (this.itemType === 'Product') { accountName = 'Sales'; } const accountExists = await this.fyo.db.exists('Account', accountName); return accountExists ? accountName : ''; }, dependsOn: ['itemType'], }, expenseAccount: { formula: async () => { if (this.trackItem) { return this.fyo.singles.InventorySettings ?.stockReceivedButNotBilled as string; } const cogs = await this.fyo.db.getAllRaw('Account', { filters: { accountType: AccountTypeEnum['Cost of Goods Sold'], }, }); if (cogs.length === 0) { return ''; } else { return cogs[0].name as string; } }, dependsOn: ['itemType', 'trackItem'], }, }; static filters: FiltersMap = { incomeAccount: () => ({ isGroup: false, rootType: AccountRootTypeEnum.Income, }), expenseAccount: (doc) => ({ isGroup: false, rootType: doc.trackItem ? AccountRootTypeEnum.Liability : AccountRootTypeEnum.Expense, }), }; validations: ValidationMap = { rate: (value: DocValue) => { if ((value as Money).isNegative()) { throw new ValidationError(this.fyo.t`Rate can't be negative.`); } }, }; static getActions(fyo: Fyo): Action[] { return [ { group: fyo.t`Create`, label: fyo.t`Sales Invoice`, condition: (doc) => !doc.notInserted && doc.for !== 'Purchases', action: async (doc, router) => { const invoice = fyo.doc.getNewDoc('SalesInvoice'); await invoice.append('items', { item: doc.name as string, rate: doc.rate as Money, tax: doc.tax as string, }); await router.push(`/edit/SalesInvoice/${invoice.name!}`); }, }, { group: fyo.t`Create`, label: fyo.t`Purchase Invoice`, condition: (doc) => !doc.notInserted && doc.for !== 'Sales', action: async (doc, router) => { const invoice = fyo.doc.getNewDoc('PurchaseInvoice'); await invoice.append('items', { item: doc.name as string, rate: doc.rate as Money, tax: doc.tax as string, }); await router.push(`/edit/PurchaseInvoice/${invoice.name!}`); }, }, ]; } static getListViewSettings(): ListViewSettings { return { columns: ['name', 'unit', 'tax', 'rate'], }; } hidden: HiddenMap = { trackItem: () => !this.fyo.singles.AccountingSettings?.enableInventory || this.itemType !== 'Product' || (this.inserted && !this.trackItem), barcode: () => !this.fyo.singles.InventorySettings?.enableBarcodes, hasBatch: () => !(this.fyo.singles.InventorySettings?.enableBatches && this.trackItem), hasSerialNumber: () => !( this.fyo.singles.InventorySettings?.enableSerialNumber && this.trackItem ), uomConversions: () => !this.fyo.singles.InventorySettings?.enableUomConversions, }; readOnly: ReadOnlyMap = { unit: () => this.inserted, itemType: () => this.inserted, trackItem: () => this.inserted, hasBatch: () => this.inserted, hasSerialNumber: () => this.inserted, }; }
2302_79757062/books
models/baseModels/Item/Item.ts
TypeScript
agpl-3.0
4,031
import { Fyo, t } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { Action, DefaultMap, FiltersMap, HiddenMap, ListViewSettings, } from 'fyo/model/types'; import { getDocStatus, getLedgerLinkAction, getNumberSeries, getStatusText, statusColor, } from 'models/helpers'; import { Transactional } from 'models/Transactional/Transactional'; import { Money } from 'pesa'; import { LedgerPosting } from '../../Transactional/LedgerPosting'; export class JournalEntry extends Transactional { accounts?: Doc[]; async getPosting() { const posting: LedgerPosting = new LedgerPosting(this, this.fyo); for (const row of this.accounts ?? []) { const debit = row.debit as Money; const credit = row.credit as Money; const account = row.account as string; if (!debit.isZero()) { await posting.debit(account, debit); } else if (!credit.isZero()) { await posting.credit(account, credit); } } return posting; } hidden: HiddenMap = { referenceNumber: () => !(this.referenceNumber || !(this.isSubmitted || this.isCancelled)), referenceDate: () => !(this.referenceDate || !(this.isSubmitted || this.isCancelled)), userRemark: () => !(this.userRemark || !(this.isSubmitted || this.isCancelled)), attachment: () => !(this.attachment || !(this.isSubmitted || this.isCancelled)), }; static defaults: DefaultMap = { numberSeries: (doc) => getNumberSeries(doc.schemaName, doc.fyo), date: () => new Date(), }; static filters: FiltersMap = { numberSeries: () => ({ referenceType: 'JournalEntry' }), }; static getActions(fyo: Fyo): Action[] { return [getLedgerLinkAction(fyo)]; } static getListViewSettings(): ListViewSettings { return { columns: [ 'name', { label: t`Status`, fieldname: 'status', fieldtype: 'Select', render(doc) { const status = getDocStatus(doc); const color = statusColor[status] ?? 'gray'; const label = getStatusText(status); return { template: `<Badge class="text-xs" color="${color}">${label}</Badge>`, }; }, }, 'date', 'entryType', 'referenceNumber', ], }; } }
2302_79757062/books
models/baseModels/JournalEntry/JournalEntry.ts
TypeScript
agpl-3.0
2,336
import { Doc } from 'fyo/model/doc'; import { FiltersMap, FormulaMap } from 'fyo/model/types'; import { Money } from 'pesa'; export class JournalEntryAccount extends Doc { getAutoDebitCredit(type: 'debit' | 'credit') { const currentValue = this.get(type) as Money; if (!currentValue.isZero()) { return; } const otherType = type === 'debit' ? 'credit' : 'debit'; const otherTypeValue = this.get(otherType) as Money; if (!otherTypeValue.isZero()) { return this.fyo.pesa(0); } const totalType = this.parentdoc!.getSum('accounts', type, false) as Money; const totalOtherType = this.parentdoc!.getSum( 'accounts', otherType, false ) as Money; if (totalType.lt(totalOtherType)) { return totalOtherType.sub(totalType); } } formulas: FormulaMap = { debit: { formula: () => this.getAutoDebitCredit('debit'), }, credit: { formula: () => this.getAutoDebitCredit('credit'), }, }; static filters: FiltersMap = { account: () => ({ isGroup: false }), }; }
2302_79757062/books
models/baseModels/JournalEntryAccount/JournalEntryAccount.ts
TypeScript
agpl-3.0
1,075
import { Fyo } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { Action, LeadStatus, ListViewSettings, ValidationMap, } from 'fyo/model/types'; import { getLeadActions, getLeadStatusColumn } from 'models/helpers'; import { validateEmail, validatePhoneNumber, } from 'fyo/model/validationFunction'; import { ModelNameEnum } from 'models/types'; export class Lead extends Doc { status?: LeadStatus; validations: ValidationMap = { email: validateEmail, mobile: validatePhoneNumber, }; createCustomer() { return this.fyo.doc.getNewDoc(ModelNameEnum.Party, { ...this.getValidDict(), fromLead: this.name, phone: this.mobile as string, role: 'Customer', }); } createSalesQuote() { const data: { party: string | undefined; referenceType: string } = { party: this.name, referenceType: ModelNameEnum.Lead, }; return this.fyo.doc.getNewDoc(ModelNameEnum.SalesQuote, data); } static getActions(fyo: Fyo): Action[] { return getLeadActions(fyo); } static getListViewSettings(): ListViewSettings { return { columns: ['name', getLeadStatusColumn(), 'email', 'mobile'], }; } }
2302_79757062/books
models/baseModels/Lead/Lead.ts
TypeScript
agpl-3.0
1,191
import { Doc } from 'fyo/model/doc'; import { ListViewSettings } from 'fyo/model/types'; export class LoyaltyPointEntry extends Doc { loyaltyProgram?: string; customer?: string; invoice?: string; purchaseAmount?: number; expiryDate?: Date; static override getListViewSettings(): ListViewSettings { return { columns: [ 'loyaltyProgram', 'customer', 'purchaseAmount', 'loyaltyPoints', ], }; } }
2302_79757062/books
models/baseModels/LoyaltyPointEntry/LoyaltyPointEntry.ts
TypeScript
agpl-3.0
461
import { Doc } from 'fyo/model/doc'; import { FiltersMap, ListViewSettings } from 'fyo/model/types'; import { CollectionRulesItems } from '../CollectionRulesItems/CollectionRulesItems'; import { AccountRootTypeEnum } from '../Account/types'; export class LoyaltyProgram extends Doc { collectionRules?: CollectionRulesItems[]; expiryDuration?: number; static filters: FiltersMap = { expenseAccount: () => ({ rootType: AccountRootTypeEnum.Liability, isGroup: false, }), }; static getListViewSettings(): ListViewSettings { return { columns: ['name', 'fromDate', 'toDate', 'expiryDuration'], }; } }
2302_79757062/books
models/baseModels/LoyaltyProgram/LoyaltyProgram.ts
TypeScript
agpl-3.0
644
import { Doc } from 'fyo/model/doc'; import { HiddenMap } from 'fyo/model/types'; export class Misc extends Doc { openCount?: number; useFullWidth?: boolean; override hidden: HiddenMap = {}; }
2302_79757062/books
models/baseModels/Misc.ts
TypeScript
agpl-3.0
200
import { Fyo } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { Action, FiltersMap, FormulaMap, ListViewSettings, ValidationMap, } from 'fyo/model/types'; import { validateEmail, validatePhoneNumber, } from 'fyo/model/validationFunction'; import { Money } from 'pesa'; import { PartyRole } from './types'; import { ModelNameEnum } from 'models/types'; export class Party extends Doc { role?: PartyRole; party?: string; fromLead?: string; defaultAccount?: string; loyaltyPoints?: number; outstandingAmount?: Money; async updateOutstandingAmount() { /** * If Role === "Both" then outstanding Amount * will be the amount to be paid to the party. */ const role = this.role as PartyRole; let outstandingAmount = this.fyo.pesa(0); if (role === 'Customer' || role === 'Both') { const outstandingReceive = await this._getTotalOutstandingAmount( 'SalesInvoice' ); outstandingAmount = outstandingAmount.add(outstandingReceive); } if (role === 'Supplier') { const outstandingPay = await this._getTotalOutstandingAmount( 'PurchaseInvoice' ); outstandingAmount = outstandingAmount.add(outstandingPay); } if (role === 'Both') { const outstandingPay = await this._getTotalOutstandingAmount( 'PurchaseInvoice' ); outstandingAmount = outstandingAmount.sub(outstandingPay); } await this.setAndSync({ outstandingAmount }); } async updateLoyaltyPoints() { let loyaltyPoints = 0; if (this.role === 'Customer' || this.role === 'Both') { loyaltyPoints = await this._getTotalLoyaltyPoints(); } await this.setAndSync({ loyaltyPoints }); } async _getTotalLoyaltyPoints() { const data = (await this.fyo.db.getAll(ModelNameEnum.LoyaltyPointEntry, { fields: ['name', 'loyaltyPoints', 'expiryDate', 'postingDate'], filters: { customer: this.name as string, }, })) as { name: string; loyaltyPoints: number; expiryDate: Date; postingDate: Date; }[]; const totalLoyaltyPoints = data.reduce((total, entry) => { if (entry.expiryDate > entry.postingDate) { return total + entry.loyaltyPoints; } return total; }, 0); return totalLoyaltyPoints; } async _getTotalOutstandingAmount( schemaName: 'SalesInvoice' | 'PurchaseInvoice' ) { const outstandingAmounts = await this.fyo.db.getAllRaw(schemaName, { fields: ['outstandingAmount'], filters: { submitted: true, cancelled: false, party: this.name as string, }, }); return outstandingAmounts .map(({ outstandingAmount }) => this.fyo.pesa(outstandingAmount as number) ) .reduce((a, b) => a.add(b), this.fyo.pesa(0)); } formulas: FormulaMap = { defaultAccount: { formula: async () => { const role = this.role as PartyRole; if (role === 'Both') { return ''; } let accountName = 'Debtors'; if (role === 'Supplier') { accountName = 'Creditors'; } const accountExists = await this.fyo.db.exists('Account', accountName); return accountExists ? accountName : ''; }, dependsOn: ['role'], }, currency: { formula: () => { if (!this.currency) { return this.fyo.singles.SystemSettings!.currency as string; } }, }, }; validations: ValidationMap = { email: validateEmail, phone: validatePhoneNumber, }; static filters: FiltersMap = { defaultAccount: (doc: Doc) => { const role = doc.role as PartyRole; if (role === 'Both') { return { isGroup: false, accountType: ['in', ['Payable', 'Receivable']], }; } return { isGroup: false, accountType: role === 'Customer' ? 'Receivable' : 'Payable', }; }, }; static getListViewSettings(): ListViewSettings { return { columns: ['name', 'email', 'phone', 'outstandingAmount'], }; } async afterDelete() { await super.afterDelete(); if (!this.fromLead) { return; } const leadData = await this.fyo.doc.getDoc(ModelNameEnum.Lead, this.name); await leadData.setAndSync('status', 'Interested'); } async afterSync() { await super.afterSync(); if (!this.fromLead) { return; } const leadData = await this.fyo.doc.getDoc(ModelNameEnum.Lead, this.name); await leadData.setAndSync('status', 'Converted'); } static getActions(fyo: Fyo): Action[] { return [ { label: fyo.t`Create Purchase`, condition: (doc: Doc) => !doc.notInserted && (doc.role as PartyRole) !== 'Customer', action: async (partyDoc, router) => { const doc = fyo.doc.getNewDoc('PurchaseInvoice', { party: partyDoc.name, account: partyDoc.defaultAccount as string, }); await router.push({ path: `/edit/PurchaseInvoice/${doc.name!}`, query: { schemaName: 'PurchaseInvoice', values: { // @ts-ignore party: partyDoc.name!, }, }, }); }, }, { label: fyo.t`View Purchases`, condition: (doc: Doc) => !doc.notInserted && (doc.role as PartyRole) !== 'Customer', action: async (partyDoc, router) => { await router.push({ path: '/list/PurchaseInvoice', query: { filters: JSON.stringify({ party: partyDoc.name }) }, }); }, }, { label: fyo.t`Create Sale`, condition: (doc: Doc) => !doc.notInserted && (doc.role as PartyRole) !== 'Supplier', action: async (partyDoc, router) => { const doc = fyo.doc.getNewDoc('SalesInvoice', { party: partyDoc.name, account: partyDoc.defaultAccount as string, }); await router.push({ path: `/edit/SalesInvoice/${doc.name!}`, query: { schemaName: 'SalesInvoice', values: { // @ts-ignore party: partyDoc.name!, }, }, }); }, }, { label: fyo.t`View Sales`, condition: (doc: Doc) => !doc.notInserted && (doc.role as PartyRole) !== 'Supplier', action: async (partyDoc, router) => { await router.push({ path: '/list/SalesInvoice', query: { filters: JSON.stringify({ party: partyDoc.name }) }, }); }, }, ]; } }
2302_79757062/books
models/baseModels/Party/Party.ts
TypeScript
agpl-3.0
6,734
export type PartyRole = 'Both' | 'Supplier' | 'Customer'; export enum PartyRoleEnum { 'Both' = 'Both', 'Supplier' = 'Supplier', 'Customer' = 'Customer', }
2302_79757062/books
models/baseModels/Party/types.ts
TypeScript
agpl-3.0
161
import { Fyo, t } from 'fyo'; import { DocValue } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { Action, ChangeArg, DefaultMap, FiltersMap, FormulaMap, HiddenMap, ListViewSettings, RequiredMap, ValidationMap, } from 'fyo/model/types'; import { NotFoundError, ValidationError } from 'fyo/utils/errors'; import { getDocStatusListColumn, getLedgerLinkAction, getNumberSeries, } from 'models/helpers'; import { LedgerPosting } from 'models/Transactional/LedgerPosting'; import { Transactional } from 'models/Transactional/Transactional'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { QueryFilter } from 'utils/db/types'; import { AccountTypeEnum } from '../Account/types'; import { Invoice } from '../Invoice/Invoice'; import { Party } from '../Party/Party'; import { PaymentFor } from '../PaymentFor/PaymentFor'; import { PaymentMethod, PaymentType } from './types'; import { TaxSummary } from '../TaxSummary/TaxSummary'; type AccountTypeMap = Record<AccountTypeEnum, string[] | undefined>; export class Payment extends Transactional { taxes?: TaxSummary[]; party?: string; amount?: Money; writeoff?: Money; paymentType?: PaymentType; referenceType?: ModelNameEnum.SalesInvoice | ModelNameEnum.PurchaseInvoice; for?: PaymentFor[]; _accountsMap?: AccountTypeMap; async change({ changed }: ChangeArg) { if (changed === 'for') { this.updateAmountOnReferenceUpdate(); await this.updateDetailsOnReferenceUpdate(); } if (changed === 'amount') { this.updateReferenceOnAmountUpdate(); } } async updateDetailsOnReferenceUpdate() { const forReferences = (this.for ?? []) as Doc[]; const { referenceType, referenceName } = forReferences[0] ?? {}; if ( forReferences.length !== 1 || this.party || this.paymentType || !referenceName || !referenceType ) { return; } const schemaName = referenceType as string; const doc = (await this.fyo.doc.getDoc( schemaName, referenceName as string )) as Invoice; let paymentType: PaymentType; if (doc.isSales) { paymentType = 'Receive'; } else { paymentType = 'Pay'; } this.party = doc.party as string; this.paymentType = paymentType; } updateAmountOnReferenceUpdate() { this.amount = this.fyo.pesa(0); for (const paymentReference of (this.for ?? []) as Doc[]) { this.amount = this.amount.add(paymentReference.amount as Money); } } updateReferenceOnAmountUpdate() { const forReferences = (this.for ?? []) as Doc[]; if (forReferences.length !== 1) { return; } forReferences[0].amount = this.amount; } async validate() { await super.validate(); if (this.submitted) { return; } await this.validateFor(); this.validateAccounts(); this.validateTotalReferenceAmount(); await this.validateReferences(); } async validateFor() { for (const childDoc of this.for ?? []) { const referenceName = childDoc.referenceName; const referenceType = childDoc.referenceType; const refDoc = (await this.fyo.doc.getDoc( childDoc.referenceType!, childDoc.referenceName )) as Invoice; if (referenceName && referenceType && !refDoc) { throw new ValidationError( t`${referenceType} of type ${ this.fyo.schemaMap?.[referenceType]?.label ?? referenceType } does not exist` ); } if (!refDoc) { continue; } if (refDoc?.party !== this.party) { throw new ValidationError( t`${refDoc.name!} party ${refDoc.party!} is different from ${this .party!}` ); } } } validateAccounts() { if (this.paymentAccount !== this.account || !this.account) { return; } throw new this.fyo.errors.ValidationError( t`To Account and From Account can't be the same: ${ this.account as string }` ); } validateTotalReferenceAmount() { const forReferences = (this.for ?? []) as Doc[]; if (forReferences.length === 0) { return; } const referenceAmountTotal = forReferences .map(({ amount }) => amount as Money) .reduce((a, b) => a.add(b), this.fyo.pesa(0)); if ( (this.amount as Money) .add((this.writeoff as Money) ?? 0) .gte(referenceAmountTotal) ) { return; } const writeoff = this.fyo.format(this.writeoff!, 'Currency'); const payment = this.fyo.format(this.amount!, 'Currency'); const refAmount = this.fyo.format(referenceAmountTotal, 'Currency'); if ((this.writeoff as Money).gt(0)) { throw new ValidationError( this.fyo.t`Amount: ${payment} and writeoff: ${writeoff} is less than the total amount allocated to references: ${refAmount}.` ); } throw new ValidationError( this.fyo.t`Amount: ${payment} is less than the total amount allocated to references: ${refAmount}.` ); } async validateWriteOffAccount() { if ((this.writeoff as Money).isZero()) { return; } const writeOffAccount = this.fyo.singles.AccountingSettings! .writeOffAccount as string | null | undefined; if (!writeOffAccount) { throw new NotFoundError( t`Write Off Account not set. Please set Write Off Account in General Settings`, false ); } const exists = await this.fyo.db.exists( ModelNameEnum.Account, writeOffAccount ); if (exists) { return; } throw new NotFoundError( t`Write Off Account ${writeOffAccount} does not exist. Please set Write Off Account in General Settings`, false ); } async getTaxSummary() { const taxes: Record< string, Record< string, { account: string; from_account: string; rate: number; amount: Money; } > > = {}; for (const childDoc of this.for ?? []) { const referenceName = childDoc.referenceName; const referenceType = childDoc.referenceType; const refDoc = (await this.fyo.doc.getDoc( childDoc.referenceType!, childDoc.referenceName )) as Invoice; if (referenceName && referenceType && !refDoc) { throw new ValidationError( t`${referenceType} of type ${ this.fyo.schemaMap?.[referenceType]?.label ?? referenceType } does not exist` ); } if (!refDoc) { continue; } for (const { details, taxAmount, exchangeRate, } of await refDoc.getTaxItems()) { const { account, payment_account } = details; if (!payment_account) { continue; } taxes[payment_account] ??= {}; taxes[payment_account][account] ??= { account: payment_account, from_account: account, rate: details.rate, amount: this.fyo.pesa(0), }; taxes[payment_account][account].amount = taxes[payment_account][ account ].amount.add(taxAmount.mul(exchangeRate ?? 1)); } } type Summary = typeof taxes[string][string] & { idx: number }; const taxArr: Summary[] = []; let idx = 0; for (const payment_account in taxes) { for (const account in taxes[payment_account]) { const tax = taxes[payment_account][account]; if (tax.amount.isZero()) { continue; } taxArr.push({ ...tax, idx, }); idx += 1; } } return taxArr; } async getPosting() { /** * account : From Account * paymentAccount : To Account * * if Receive * - account : Debtors, etc * - paymentAccount : Cash, Bank, etc * * if Pay * - account : Cash, Bank, etc * - paymentAccount : Creditors, etc */ await this.validateWriteOffAccount(); const posting: LedgerPosting = new LedgerPosting(this, this.fyo); const paymentAccount = this.paymentAccount as string; const account = this.account as string; const amount = this.amount as Money; await posting.debit(paymentAccount, amount); await posting.credit(account, amount); if (this.taxes) { if (this.paymentType === 'Receive') { for (const tax of this.taxes) { await posting.debit(tax.from_account!, tax.amount!); await posting.credit(tax.account!, tax.amount!); } } else if (this.paymentType === 'Pay') { for (const tax of this.taxes) { await posting.credit(tax.from_account!, tax.amount!); await posting.debit(tax.account!, tax.amount!); } } } await this.applyWriteOffPosting(posting); return posting; } async applyWriteOffPosting(posting: LedgerPosting) { const writeoff = this.writeoff as Money; if (writeoff.isZero()) { return posting; } const account = this.account as string; const paymentAccount = this.paymentAccount as string; const writeOffAccount = this.fyo.singles.AccountingSettings! .writeOffAccount as string; if (this.paymentType === 'Pay') { await posting.credit(paymentAccount, writeoff); await posting.debit(writeOffAccount, writeoff); } else { await posting.debit(account, writeoff); await posting.credit(writeOffAccount, writeoff); } } async validateReferences() { const forReferences = this.for ?? []; if (forReferences.length === 0) { return; } for (const row of forReferences) { this.validateReferenceType(row); } await this.validateReferenceOutstanding(); } validateReferenceType(row: PaymentFor) { const referenceType = row.referenceType; if ( ![ModelNameEnum.SalesInvoice, ModelNameEnum.PurchaseInvoice].includes( referenceType! ) ) { throw new ValidationError(t`Please select a valid reference type.`); } } async validateReferenceOutstanding() { let outstandingAmount = this.fyo.pesa(0); for (const row of this.for ?? []) { const referenceDoc = (await this.fyo.doc.getDoc( row.referenceType as string, row.referenceName as string )) as Invoice; outstandingAmount = outstandingAmount.add( referenceDoc.outstandingAmount?.abs() ?? 0 ); } const amount = this.amount as Money; if (amount.gt(0) && amount.lte(outstandingAmount)) { return; } let message = this.fyo.t`Payment amount: ${this.fyo.format( this.amount!, 'Currency' )} should be less than Outstanding amount: ${this.fyo.format( outstandingAmount, 'Currency' )}.`; if (amount.lte(0)) { const amt = this.fyo.format(this.amount!, 'Currency'); message = this.fyo.t`Payment amount: ${amt} should be greater than 0.`; } throw new ValidationError(message); } async afterSubmit() { await super.afterSubmit(); await this.updateReferenceDocOutstanding(); await this.updatePartyOutstanding(); } async updateReferenceDocOutstanding() { for (const row of this.for ?? []) { const referenceDoc = await this.fyo.doc.getDoc( row.referenceType!, row.referenceName ); const previousOutstandingAmount = referenceDoc.outstandingAmount as Money; const outstandingAmount = previousOutstandingAmount.sub(row.amount!); await referenceDoc.setAndSync({ outstandingAmount }); } } async afterCancel() { await super.afterCancel(); await this.revertOutstandingAmount(); } async revertOutstandingAmount() { await this._revertReferenceOutstanding(); await this.updatePartyOutstanding(); } async _revertReferenceOutstanding() { for (const ref of this.for ?? []) { const refDoc = await this.fyo.doc.getDoc( ref.referenceType!, ref.referenceName ); const outstandingAmount = (refDoc.outstandingAmount as Money).add( ref.amount! ); await refDoc.setAndSync({ outstandingAmount }); } } async updatePartyOutstanding() { const partyDoc = (await this.fyo.doc.getDoc( ModelNameEnum.Party, this.party )) as Party; await partyDoc.updateOutstandingAmount(); } static defaults: DefaultMap = { numberSeries: (doc) => getNumberSeries(doc.schemaName, doc.fyo), date: () => new Date(), }; async _getAccountsMap(): Promise<AccountTypeMap> { if (this._accountsMap) { return this._accountsMap; } const accounts = (await this.fyo.db.getAll(ModelNameEnum.Account, { fields: ['name', 'accountType'], filters: { accountType: [ 'in', [ AccountTypeEnum.Bank, AccountTypeEnum.Cash, AccountTypeEnum.Payable, AccountTypeEnum.Receivable, ], ], }, })) as { name: string; accountType: AccountTypeEnum }[]; return (this._accountsMap = accounts.reduce((acc, ac) => { acc[ac.accountType] ??= []; acc[ac.accountType]!.push(ac.name); return acc; }, {} as AccountTypeMap)); } async _getReferenceAccount() { const account = await this._getAccountFromParty(); if (!account) { return await this._getAccountFromFor(); } return account; } async _getAccountFromParty() { const party = (await this.loadAndGetLink('party')) as Party | null; if (!party || party.role === 'Both') { return null; } return party.defaultAccount ?? null; } async _getAccountFromFor() { const reference = this?.for?.[0]; if (!reference) { return null; } const refDoc = (await reference.loadAndGetLink( 'referenceName' )) as Invoice | null; if ( refDoc && refDoc.schema.name === ModelNameEnum.SalesInvoice && refDoc.isReturned ) { const accountsMap = await this._getAccountsMap(); return accountsMap[AccountTypeEnum.Cash]?.[0]; } return refDoc?.account ?? null; } formulas: FormulaMap = { account: { formula: async () => { const accountsMap = await this._getAccountsMap(); if (this.paymentType === 'Receive') { return ( (await this._getReferenceAccount()) ?? accountsMap[AccountTypeEnum.Receivable]?.[0] ?? null ); } if (this.paymentMethod === 'Cash') { return accountsMap[AccountTypeEnum.Cash]?.[0] ?? null; } if (this.paymentMethod !== 'Cash') { return accountsMap[AccountTypeEnum.Bank]?.[0] ?? null; } return null; }, dependsOn: ['paymentMethod', 'paymentType', 'party'], }, paymentAccount: { formula: async () => { const accountsMap = await this._getAccountsMap(); if (this.paymentType === 'Pay') { return ( (await this._getReferenceAccount()) ?? accountsMap[AccountTypeEnum.Payable]?.[0] ?? null ); } if (this.paymentMethod === 'Cash') { return accountsMap[AccountTypeEnum.Cash]?.[0] ?? null; } if (this.paymentMethod !== 'Cash') { return accountsMap[AccountTypeEnum.Bank]?.[0] ?? null; } return null; }, dependsOn: ['paymentMethod', 'paymentType', 'party'], }, paymentType: { formula: async () => { if (!this.party) { return; } const partyDoc = (await this.loadAndGetLink('party')) as Party; const outstanding = partyDoc.outstandingAmount as Money; if (outstanding.isNegative()) { if (this.referenceType === ModelNameEnum.PurchaseInvoice) { return 'Pay'; } return 'Receive'; } if (partyDoc.role === 'Supplier') { return 'Pay'; } else if (partyDoc.role === 'Customer') { return 'Receive'; } if (outstanding?.isZero() ?? true) { return this.paymentType; } if (outstanding?.isPositive()) { return 'Receive'; } return 'Pay'; }, }, amount: { formula: () => this.getSum('for', 'amount', false), dependsOn: ['for'], }, amountPaid: { formula: () => this.amount!.sub(this.writeoff!), dependsOn: ['amount', 'writeoff', 'for'], }, referenceType: { formula: () => { if (this.referenceType) { return; } return this.for![0].referenceType; }, }, taxes: { formula: async () => await this.getTaxSummary() }, }; validations: ValidationMap = { amount: (value: DocValue) => { if ((value as Money).isNegative()) { throw new ValidationError( this.fyo.t`Payment amount cannot be less than zero.` ); } if (((this.for ?? []) as Doc[]).length === 0) { return; } const amount = (this.getSum('for', 'amount', false) as Money).abs(); if ((value as Money).gt(amount)) { throw new ValidationError( this.fyo.t`Payment amount cannot exceed ${this.fyo.format(amount, 'Currency')}.` ); } else if ((value as Money).isZero()) { throw new ValidationError( this.fyo.t`Payment amount cannot be ${this.fyo.format(value, 'Currency')}.` ); } }, }; required: RequiredMap = { referenceId: () => this.paymentMethod !== 'Cash', clearanceDate: () => this.paymentMethod !== 'Cash', }; hidden: HiddenMap = { referenceId: () => this.paymentMethod === 'Cash', clearanceDate: () => this.paymentMethod === 'Cash', amountPaid: () => this.writeoff?.isZero() ?? true, attachment: () => !(this.attachment || !(this.isSubmitted || this.isCancelled)), for: () => !!((this.isSubmitted || this.isCancelled) && !this.for?.length), taxes: () => !this.taxes?.length, }; static filters: FiltersMap = { party: (doc: Doc) => { const paymentType = (doc as Payment).paymentType; if (paymentType === 'Pay') { return { role: ['in', ['Supplier', 'Both']] } as QueryFilter; } if (paymentType === 'Receive') { return { role: ['in', ['Customer', 'Both']] } as QueryFilter; } return {}; }, numberSeries: () => { return { referenceType: 'Payment' }; }, account: (doc: Doc) => { const paymentType = doc.paymentType as PaymentType; const paymentMethod = doc.paymentMethod as PaymentMethod; if (paymentType === 'Receive') { return { accountType: 'Receivable', isGroup: false }; } if (paymentMethod === 'Cash') { return { accountType: 'Cash', isGroup: false }; } else { return { accountType: ['in', ['Bank', 'Cash']], isGroup: false }; } }, paymentAccount: (doc: Doc) => { const paymentType = doc.paymentType as PaymentType; const paymentMethod = doc.paymentMethod as PaymentMethod; if (paymentType === 'Pay') { return { accountType: 'Payable', isGroup: false }; } if (paymentMethod === 'Cash') { return { accountType: 'Cash', isGroup: false }; } else { return { accountType: ['in', ['Bank', 'Cash']], isGroup: false }; } }, }; static getActions(fyo: Fyo): Action[] { return [getLedgerLinkAction(fyo)]; } static getListViewSettings(): ListViewSettings { return { columns: ['name', getDocStatusListColumn(), 'party', 'date', 'amount'], }; } }
2302_79757062/books
models/baseModels/Payment/Payment.ts
TypeScript
agpl-3.0
19,793
export type PaymentType = 'Receive' | 'Pay'; export type PaymentMethod = 'Cash' | 'Cheque' | 'Transfer'; export enum PaymentTypeEnum{ Receive = 'Receive', Pay = 'Pay' } export enum AccountFieldEnum{ Account = 'account', PaymentAccount = 'paymentAccount' }
2302_79757062/books
models/baseModels/Payment/types.ts
TypeScript
agpl-3.0
275
import { t } from 'fyo'; import { DocValue } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { FiltersMap, FormulaMap, ValidationMap } from 'fyo/model/types'; import { NotFoundError } from 'fyo/utils/errors'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { PartyRoleEnum } from '../Party/types'; import { Payment } from '../Payment/Payment'; export class PaymentFor extends Doc { parentdoc?: Payment | undefined; referenceType?: ModelNameEnum.SalesInvoice | ModelNameEnum.PurchaseInvoice; referenceName?: string; amount?: Money; formulas: FormulaMap = { referenceType: { formula: async () => { if (this.referenceType) { return; } const party = await this.parentdoc?.loadAndGetLink('party'); if (!party) { return ModelNameEnum.SalesInvoice; } if (party.role === PartyRoleEnum.Supplier) { return ModelNameEnum.PurchaseInvoice; } return ModelNameEnum.SalesInvoice; }, }, referenceName: { formula: async () => { if (!this.referenceName || !this.referenceType) { return this.referenceName; } const exists = await this.fyo.db.exists( this.referenceType, this.referenceName ); if (!exists) { return null; } return this.referenceName; }, dependsOn: ['referenceType'], }, amount: { formula: async () => { if (!this.referenceName) { return this.fyo.pesa(0); } const outstandingAmount = (await this.fyo.getValue( this.referenceType as string, this.referenceName, 'outstandingAmount' )) as Money; if (outstandingAmount) { return outstandingAmount; } return this.fyo.pesa(0); }, dependsOn: ['referenceName'], }, }; static filters: FiltersMap = { referenceName: (doc) => { const zero = '0.' + '0'.repeat(doc.fyo.singles.SystemSettings?.internalPrecision ?? 11); const baseFilters = { outstandingAmount: ['!=', zero], submitted: true, cancelled: false, }; const party = doc?.parentdoc?.party as undefined | string; if (!party) { return baseFilters; } return { ...baseFilters, party }; }, }; validations: ValidationMap = { referenceName: async (value: DocValue) => { const exists = await this.fyo.db.exists( this.referenceType!, value as string ); if (exists) { return; } const referenceType = this.referenceType ?? ModelNameEnum.SalesInvoice; const label = this.fyo.schemaMap[referenceType]?.label ?? referenceType; throw new NotFoundError( t`${label} ${value as string} does not exist`, false ); }, }; }
2302_79757062/books
models/baseModels/PaymentFor/PaymentFor.ts
TypeScript
agpl-3.0
2,946
import { Doc } from 'fyo/model/doc'; import { ListViewSettings } from 'fyo/model/types'; import { PriceListItem } from './PriceListItem'; import { getIsDocEnabledColumn, getPriceListStatusColumn, } from 'models/helpers'; export class PriceList extends Doc { isEnabled?: boolean; isSales?: boolean; isPurchase?: boolean; priceListItem?: PriceListItem[]; static getListViewSettings(): ListViewSettings { return { columns: ['name', getIsDocEnabledColumn(), getPriceListStatusColumn()], }; } }
2302_79757062/books
models/baseModels/PriceList/PriceList.ts
TypeScript
agpl-3.0
522
import { Doc } from 'fyo/model/doc'; import type { FormulaMap } from 'fyo/model/types'; import { ModelNameEnum } from 'models/types'; import type { Money } from 'pesa'; import type { PriceList } from './PriceList'; export class PriceListItem extends Doc { item?: string; unit?: string; rate?: Money; parentdoc?: PriceList; formulas: FormulaMap = { unit: { formula: async () => { if (!this.item) { return; } return await this.fyo.getValue(ModelNameEnum.Item, this.item, 'unit'); }, dependsOn: ['item'], }, }; }
2302_79757062/books
models/baseModels/PriceList/PriceListItem.ts
TypeScript
agpl-3.0
585
import { Doc } from 'fyo/model/doc'; import { Money } from 'pesa'; import { PricingRuleItem } from '../PricingRuleItem/PricingRuleItem'; import { getIsDocEnabledColumn } from 'models/helpers'; import { HiddenMap, ListViewSettings, RequiredMap, ValidationMap, } from 'fyo/model/types'; import { DocValue } from 'fyo/core/types'; import { ValidationError } from 'fyo/utils/errors'; import { t } from 'fyo'; export class PricingRule extends Doc { isEnabled?: boolean; title?: string; appliedItems?: PricingRuleItem[]; discountType?: 'Price Discount' | 'Product Discount'; priceDiscountType?: 'rate' | 'percentage' | 'amount'; discountRate?: Money; discountPercentage?: number; discountAmount?: Money; forPriceList?: string; freeItem?: string; freeItemQuantity?: number; freeItemUnit?: string; freeItemRate?: Money; roundFreeItemQty?: number; roundingMethod?: string; isRecursive?: boolean; recurseEvery?: number; recurseOver?: number; minQuantity?: number; maxQuantity?: number; minAmount?: Money; maxAmount?: Money; validFrom?: Date; validTo?: Date; thresholdForSuggestion?: number; priority?: number; get isDiscountTypeIsPriceDiscount() { return this.discountType === 'Price Discount'; } validations: ValidationMap = { minQuantity: (value: DocValue) => { if (!value || !this.maxQuantity) { return; } if ((value as number) > this.maxQuantity) { throw new ValidationError( t`Minimum Quantity should be less than the Maximum Quantity.` ); } }, maxQuantity: (value: DocValue) => { if (!this.minQuantity || !value) { return; } if ((value as number) < this.minQuantity) { throw new ValidationError( t`Maximum Quantity should be greater than the Minimum Quantity.` ); } }, minAmount: (value: DocValue) => { if (!value || !this.maxAmount) { return; } if ((value as Money).isZero() && this.maxAmount.isZero()) { return; } if ((value as Money).gte(this.maxAmount)) { throw new ValidationError( t`Minimum Amount should be less than the Maximum Amount.` ); } }, maxAmount: (value: DocValue) => { if (!this.minAmount || !value) { return; } if (this.minAmount.isZero() && (value as Money).isZero()) { return; } if ((value as Money).lte(this.minAmount)) { throw new ValidationError( t`Maximum Amount should be greater than the Minimum Amount.` ); } }, validFrom: (value: DocValue) => { if (!value || !this.validTo) { return; } if ((value as Date).toISOString() > this.validTo.toISOString()) { throw new ValidationError( t`Valid From Date should be less than Valid To Date.` ); } }, validTo: (value: DocValue) => { if (!this.validFrom || !value) { return; } if ((value as Date).toISOString() < this.validFrom.toISOString()) { throw new ValidationError( t`Valid To Date should be greater than Valid From Date.` ); } }, }; required: RequiredMap = { priceDiscountType: () => this.isDiscountTypeIsPriceDiscount, }; static getListViewSettings(): ListViewSettings { return { columns: ['name', 'title', getIsDocEnabledColumn(), 'discountType'], }; } hidden: HiddenMap = { location: () => !this.fyo.singles.AccountingSettings?.enableInventory, priceDiscountType: () => !this.isDiscountTypeIsPriceDiscount, discountRate: () => !this.isDiscountTypeIsPriceDiscount || this.priceDiscountType !== 'rate', discountPercentage: () => !this.isDiscountTypeIsPriceDiscount || this.priceDiscountType !== 'percentage', discountAmount: () => !this.isDiscountTypeIsPriceDiscount || this.priceDiscountType !== 'amount', forPriceList: () => !this.isDiscountTypeIsPriceDiscount || this.priceDiscountType === 'rate', freeItem: () => this.isDiscountTypeIsPriceDiscount, freeItemQuantity: () => this.isDiscountTypeIsPriceDiscount, freeItemUnit: () => this.isDiscountTypeIsPriceDiscount, freeItemRate: () => this.isDiscountTypeIsPriceDiscount, roundFreeItemQty: () => this.isDiscountTypeIsPriceDiscount, roundingMethod: () => this.isDiscountTypeIsPriceDiscount || !this.roundFreeItemQty, isRecursive: () => this.isDiscountTypeIsPriceDiscount, recurseEvery: () => this.isDiscountTypeIsPriceDiscount || !this.isRecursive, recurseOver: () => this.isDiscountTypeIsPriceDiscount || !this.isRecursive, }; }
2302_79757062/books
models/baseModels/PricingRule/PricingRule.ts
TypeScript
agpl-3.0
4,716
import { Doc } from 'fyo/model/doc'; export class PricingRuleDetail extends Doc { referenceName?: string; referenceItem?: string; }
2302_79757062/books
models/baseModels/PricingRuleDetail/PricingRuleDetail.ts
TypeScript
agpl-3.0
137
import { Doc } from 'fyo/model/doc'; import { FormulaMap } from 'fyo/model/types'; import { ModelNameEnum } from 'models/types'; export class PricingRuleItem extends Doc { item?: string; unit?: string; formulas: FormulaMap = { unit: { formula: () => { if (!this.item) { return; } return this.fyo.getValue(ModelNameEnum.Item, this.item, 'unit'); }, }, }; }
2302_79757062/books
models/baseModels/PricingRuleItem/PricingRuleItem.ts
TypeScript
agpl-3.0
420
import { Attachment } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { HiddenMap } from 'fyo/model/types'; export class PrintSettings extends Doc { logo?: Attachment; email?: string; phone?: string; address?: string; companyName?: string; color?: string; font?: string; displayLogo?: boolean; override hidden: HiddenMap = {}; }
2302_79757062/books
models/baseModels/PrintSettings/PrintSettings.ts
TypeScript
agpl-3.0
367
import { Doc } from 'fyo/model/doc'; import { SchemaMap } from 'schemas/types'; import { ListsMap, ListViewSettings, ReadOnlyMap } from 'fyo/model/types'; import { ModelNameEnum } from 'models/types'; import { Fyo } from 'fyo'; export class PrintTemplate extends Doc { name?: string; type?: string; width?: number; height?: number; template?: string; isCustom?: boolean; override get canDelete(): boolean { if (this.isCustom === false) { return false; } return super.canDelete; } static getListViewSettings(fyo: Fyo): ListViewSettings { return { formRoute: (name) => `/template-builder/${name}`, columns: [ 'name', { label: fyo.t`Type`, fieldtype: 'AutoComplete', fieldname: 'type', display(value) { return fyo.schemaMap[value as string]?.label ?? ''; }, }, 'isCustom', ], }; } readOnly: ReadOnlyMap = { name: () => !this.isCustom, type: () => !this.isCustom, template: () => !this.isCustom, }; static lists: ListsMap = { type(doc?: Doc) { let enableInventory = false; let schemaMap: SchemaMap = {}; if (doc) { enableInventory = !!doc.fyo.singles.AccountingSettings?.enableInventory; schemaMap = doc.fyo.schemaMap; } const models = [ ModelNameEnum.SalesInvoice, ModelNameEnum.SalesQuote, ModelNameEnum.PurchaseInvoice, ModelNameEnum.JournalEntry, ModelNameEnum.Payment, ]; if (enableInventory) { models.push( ModelNameEnum.Shipment, ModelNameEnum.PurchaseReceipt, ModelNameEnum.StockMovement ); } return models.map((value) => ({ value, label: schemaMap[value]?.label ?? value, })); }, }; override duplicate(): Doc { const doc = super.duplicate() as PrintTemplate; doc.isCustom = true; return doc; } }
2302_79757062/books
models/baseModels/PrintTemplate.ts
TypeScript
agpl-3.0
1,991
import { Fyo } from 'fyo'; import { Action, ListViewSettings } from 'fyo/model/types'; import { LedgerPosting } from 'models/Transactional/LedgerPosting'; import { ModelNameEnum } from 'models/types'; import { getInvoiceActions, getTransactionStatusColumn } from '../../helpers'; import { Invoice } from '../Invoice/Invoice'; import { PurchaseInvoiceItem } from '../PurchaseInvoiceItem/PurchaseInvoiceItem'; export class PurchaseInvoice extends Invoice { items?: PurchaseInvoiceItem[]; async getPosting() { const exchangeRate = this.exchangeRate ?? 1; const posting: LedgerPosting = new LedgerPosting(this, this.fyo); if (this.isReturn) { await posting.debit(this.account!, this.baseGrandTotal!); } else { await posting.credit(this.account!, this.baseGrandTotal!); } for (const item of this.items!) { if (this.isReturn) { await posting.credit(item.account!, item.amount!.mul(exchangeRate)); continue; } await posting.debit(item.account!, item.amount!.mul(exchangeRate)); } if (this.taxes) { for (const tax of this.taxes) { if (this.isReturn) { await posting.credit(tax.account!, tax.amount!.mul(exchangeRate)); continue; } await posting.debit(tax.account!, tax.amount!.mul(exchangeRate)); } } const discountAmount = this.getTotalDiscount(); const discountAccount = this.fyo.singles.AccountingSettings ?.discountAccount as string | undefined; if (discountAccount && discountAmount.isPositive()) { if (this.isReturn) { await posting.debit(discountAccount, discountAmount.mul(exchangeRate)); } else { await posting.credit(discountAccount, discountAmount.mul(exchangeRate)); } } await posting.makeRoundOffEntry(); return posting; } static getListViewSettings(): ListViewSettings { return { columns: [ 'name', getTransactionStatusColumn(), 'party', 'date', 'baseGrandTotal', 'outstandingAmount', ], }; } static getActions(fyo: Fyo): Action[] { return getInvoiceActions(fyo, ModelNameEnum.PurchaseInvoice); } }
2302_79757062/books
models/baseModels/PurchaseInvoice/PurchaseInvoice.ts
TypeScript
agpl-3.0
2,201
import { InvoiceItem } from '../InvoiceItem/InvoiceItem'; export class PurchaseInvoiceItem extends InvoiceItem {}
2302_79757062/books
models/baseModels/PurchaseInvoiceItem/PurchaseInvoiceItem.ts
TypeScript
agpl-3.0
115
import { Fyo, t } from 'fyo'; import { Action, ListViewSettings, ValidationMap } from 'fyo/model/types'; import { LedgerPosting } from 'models/Transactional/LedgerPosting'; import { ModelNameEnum } from 'models/types'; import { getAddedLPWithGrandTotal, getInvoiceActions, getTransactionStatusColumn, } from '../../helpers'; import { Invoice } from '../Invoice/Invoice'; import { SalesInvoiceItem } from '../SalesInvoiceItem/SalesInvoiceItem'; import { LoyaltyProgram } from '../LoyaltyProgram/LoyaltyProgram'; import { DocValue } from 'fyo/core/types'; import { Party } from '../Party/Party'; import { ValidationError } from 'fyo/utils/errors'; export class SalesInvoice extends Invoice { items?: SalesInvoiceItem[]; async getPosting() { const exchangeRate = this.exchangeRate ?? 1; const posting: LedgerPosting = new LedgerPosting(this, this.fyo); if (this.isReturn) { await posting.credit(this.account!, this.baseGrandTotal!); } else { await posting.debit(this.account!, this.baseGrandTotal!); } for (const item of this.items!) { if (this.isReturn) { await posting.debit(item.account!, item.amount!.mul(exchangeRate)); continue; } await posting.credit(item.account!, item.amount!.mul(exchangeRate)); } if (this.redeemLoyaltyPoints) { const loyaltyProgramDoc = (await this.fyo.doc.getDoc( ModelNameEnum.LoyaltyProgram, this.loyaltyProgram )) as LoyaltyProgram; const totalAmount = await getAddedLPWithGrandTotal( this.fyo, this.loyaltyProgram as string, this.loyaltyPoints as number ); await posting.debit( loyaltyProgramDoc.expenseAccount as string, totalAmount ); await posting.credit(this.account!, totalAmount); } if (this.taxes) { for (const tax of this.taxes) { if (this.isReturn) { await posting.debit(tax.account!, tax.amount!.mul(exchangeRate)); continue; } await posting.credit(tax.account!, tax.amount!.mul(exchangeRate)); } } const discountAmount = this.getTotalDiscount(); const discountAccount = this.fyo.singles.AccountingSettings ?.discountAccount as string | undefined; if (discountAccount && discountAmount.isPositive()) { if (this.isReturn) { await posting.credit(discountAccount, discountAmount.mul(exchangeRate)); } else { await posting.debit(discountAccount, discountAmount.mul(exchangeRate)); } } await posting.makeRoundOffEntry(); return posting; } validations: ValidationMap = { loyaltyPoints: async (value: DocValue) => { if (!this.redeemLoyaltyPoints) { return; } const partyDoc = (await this.fyo.doc.getDoc( ModelNameEnum.Party, this.party )) as Party; if ((value as number) <= 0) { throw new ValidationError(t`Points must be greather than 0`); } if ((value as number) > (partyDoc?.loyaltyPoints || 0)) { throw new ValidationError( t`${this.party as string} only has ${ partyDoc.loyaltyPoints as number } points` ); } const loyaltyProgramDoc = (await this.fyo.doc.getDoc( ModelNameEnum.LoyaltyProgram, this.loyaltyProgram )) as LoyaltyProgram; if (!this?.grandTotal) { return; } const loyaltyPoint = ((value as number) || 0) * ((loyaltyProgramDoc?.conversionFactor as number) || 0); if (this.grandTotal?.lt(loyaltyPoint)) { throw new ValidationError( t`no need ${value as number} points to purchase this item` ); } }, }; static getListViewSettings(): ListViewSettings { return { columns: [ 'name', getTransactionStatusColumn(), 'party', 'date', 'baseGrandTotal', 'outstandingAmount', ], }; } static getActions(fyo: Fyo): Action[] { return getInvoiceActions(fyo, ModelNameEnum.SalesInvoice); } }
2302_79757062/books
models/baseModels/SalesInvoice/SalesInvoice.ts
TypeScript
agpl-3.0
4,093
import { InvoiceItem } from '../InvoiceItem/InvoiceItem'; export class SalesInvoiceItem extends InvoiceItem {}
2302_79757062/books
models/baseModels/SalesInvoiceItem/SalesInvoiceItem.ts
TypeScript
agpl-3.0
112
import { Fyo } from 'fyo'; import { DocValueMap } from 'fyo/core/types'; import { Action, FiltersMap, ListViewSettings } from 'fyo/model/types'; import { ModelNameEnum } from 'models/types'; import { getQuoteActions, getTransactionStatusColumn } from '../../helpers'; import { Invoice } from '../Invoice/Invoice'; import { SalesQuoteItem } from '../SalesQuoteItem/SalesQuoteItem'; import { Defaults } from '../Defaults/Defaults'; import { Doc } from 'fyo/model/doc'; import { Party } from '../Party/Party'; export class SalesQuote extends Invoice { items?: SalesQuoteItem[]; party?: string; name?: string; referenceType?: | ModelNameEnum.SalesInvoice | ModelNameEnum.PurchaseInvoice | ModelNameEnum.Lead; // This is an inherited method and it must keep the async from the parent // class // eslint-disable-next-line @typescript-eslint/require-await async getPosting() { return null; } async getInvoice(): Promise<Invoice | null> { if (!this.isSubmitted) { return null; } const schemaName = ModelNameEnum.SalesInvoice; const defaults = (this.fyo.singles.Defaults as Defaults) ?? {}; const terms = defaults.salesInvoiceTerms ?? ''; const numberSeries = defaults.salesInvoiceNumberSeries ?? undefined; const data: DocValueMap = { ...this.getValidDict(false, true), date: new Date().toISOString(), terms, numberSeries, quote: this.name, items: [], submitted: false, }; const invoice = this.fyo.doc.getNewDoc(schemaName, data) as Invoice; for (const row of this.items ?? []) { await invoice.append('items', row.getValidDict(false, true)); } if (!invoice.items?.length) { return null; } return invoice; } static filters: FiltersMap = { numberSeries: (doc: Doc) => ({ referenceType: doc.schemaName }), }; async afterSubmit(): Promise<void> { await super.afterSubmit(); if (this.referenceType == ModelNameEnum.Lead) { const partyDoc = (await this.loadAndGetLink('party')) as Party; await partyDoc.setAndSync('status', 'Quotation'); } } static getListViewSettings(): ListViewSettings { return { columns: [ 'name', getTransactionStatusColumn(), 'party', 'date', 'baseGrandTotal', 'outstandingAmount', ], }; } static getActions(fyo: Fyo): Action[] { return getQuoteActions(fyo, ModelNameEnum.SalesQuote); } }
2302_79757062/books
models/baseModels/SalesQuote/SalesQuote.ts
TypeScript
agpl-3.0
2,482
import { InvoiceItem } from '../InvoiceItem/InvoiceItem'; export class SalesQuoteItem extends InvoiceItem {}
2302_79757062/books
models/baseModels/SalesQuoteItem/SalesQuoteItem.ts
TypeScript
agpl-3.0
110