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
import { t } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { FormulaMap, ListsMap, ValidationMap } from 'fyo/model/types'; import { validateEmail } from 'fyo/model/validationFunction'; import { DateTime } from 'luxon'; import { getCountryInfo, getFiscalYear } from 'utils/misc'; function getCurrencyList(): { countryCode: string; name: string }[] { const result: { countryCode: string; name: string }[] = []; const countryInfo = getCountryInfo(); for (const info of Object.values(countryInfo)) { const { currency, code } = info ?? {}; if (typeof currency !== 'string' || typeof code !== 'string') { continue; } result.push({ name: currency, countryCode: code }); } return result; } export function getCOAList() { return [ { name: t`Standard Chart of Accounts`, countryCode: '' }, { countryCode: 'ae', name: 'U.A.E - Chart of Accounts' }, { countryCode: 'ca', name: 'Canada - Plan comptable pour les provinces francophones', }, { countryCode: 'gt', name: 'Guatemala - Cuentas' }, { countryCode: 'hu', name: 'Hungary - Chart of Accounts' }, { countryCode: 'id', name: 'Indonesia - Chart of Accounts' }, { countryCode: 'in', name: 'India - Chart of Accounts' }, { countryCode: 'mx', name: 'Mexico - Plan de Cuentas' }, { countryCode: 'ni', name: 'Nicaragua - Catalogo de Cuentas' }, { countryCode: 'nl', name: 'Netherlands - Grootboekschema' }, { countryCode: 'sg', name: 'Singapore - Chart of Accounts' }, { countryCode: 'fr', name: 'France - Plan Comptable General' }, /* { countryCode: 'th', name: 'Thailand - Chart of Accounts' }, { countryCode: 'us', name: 'United States - Chart of Accounts' }, { countryCode: 've', name: 'Venezuela - Plan de Cuentas' }, { countryCode: 'za', name: 'South Africa - Chart of Accounts' }, { countryCode: 'de', name: 'Germany - Kontenplan' }, { countryCode: 'it', name: 'Italy - Piano dei Conti' }, { countryCode: 'es', name: 'Spain - Plan de Cuentas' }, { countryCode: 'pt', name: 'Portugal - Plan de Contas' }, { countryCode: 'pl', name: 'Poland - Rejestr Kont' }, { countryCode: 'ro', name: 'Romania - Contabilitate' }, { countryCode: 'ru', name: 'Russia - Chart of Accounts' }, { countryCode: 'se', name: 'Sweden - Kontoplan' }, { countryCode: 'ch', name: 'Switzerland - Kontenplan' }, { countryCode: 'tr', name: 'Turkey - Chart of Accounts' },*/ ]; } export class SetupWizard extends Doc { fiscalYearEnd?: Date; fiscalYearStart?: Date; formulas: FormulaMap = { fiscalYearStart: { formula: (fieldname?: string) => { if ( fieldname === 'fiscalYearEnd' && this.fiscalYearEnd && !this.fiscalYearStart ) { return DateTime.fromJSDate(this.fiscalYearEnd) .minus({ years: 1 }) .plus({ days: 1 }) .toJSDate(); } if (!this.country) { return; } const countryInfo = getCountryInfo(); const fyStart = countryInfo[this.country as string]?.fiscal_year_start ?? ''; return getFiscalYear(fyStart, true); }, dependsOn: ['country', 'fiscalYearEnd'], }, fiscalYearEnd: { formula: (fieldname?: string) => { if ( fieldname === 'fiscalYearStart' && this.fiscalYearStart && !this.fiscalYearEnd ) { return DateTime.fromJSDate(this.fiscalYearStart) .plus({ years: 1 }) .minus({ days: 1 }) .toJSDate(); } if (!this.country) { return; } const countryInfo = getCountryInfo(); const fyEnd = countryInfo[this.country as string]?.fiscal_year_end ?? ''; return getFiscalYear(fyEnd, false); }, dependsOn: ['country', 'fiscalYearStart'], }, currency: { formula: () => { const country = this.get('country'); if (typeof country !== 'string') { return; } const countryInfo = getCountryInfo(); const { code } = countryInfo[country] ?? {}; if (!code) { return; } const currencyList = getCurrencyList(); const currency = currencyList.find( ({ countryCode }) => countryCode === code ); if (currency === undefined) { return currencyList[0].name; } return currency.name; }, dependsOn: ['country'], }, chartOfAccounts: { formula: () => { const country = this.get('country') as string | undefined; if (country === undefined) { return; } const countryInfo = getCountryInfo(); const code = countryInfo[country]?.code; if (!code) { return; } const coaList = getCOAList(); const coa = coaList.find(({ countryCode }) => countryCode === code); return coa?.name ?? coaList[0].name; }, dependsOn: ['country'], }, }; validations: ValidationMap = { email: validateEmail, }; static lists: ListsMap = { country: () => Object.keys(getCountryInfo()), currency: () => getCurrencyList().map(({ name }) => name), chartOfAccounts: () => getCOAList().map(({ name }) => name), }; }
2302_79757062/books
models/baseModels/SetupWizard/SetupWizard.ts
TypeScript
agpl-3.0
5,343
import { Doc } from 'fyo/model/doc'; import { ListViewSettings } from 'fyo/model/types'; export class Tax extends Doc { static getListViewSettings(): ListViewSettings { return { columns: ['name'] }; } }
2302_79757062/books
models/baseModels/Tax/Tax.ts
TypeScript
agpl-3.0
212
import { Fyo } from 'fyo'; import { DocValueMap } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { CurrenciesMap } from 'fyo/model/types'; import { DEFAULT_CURRENCY } from 'fyo/utils/consts'; import { Money } from 'pesa'; import { FieldTypeEnum, Schema } from 'schemas/types'; import { Invoice } from '../Invoice/Invoice'; export class TaxSummary extends Doc { account?: string; from_account?: string; rate?: number; amount?: Money; parentdoc?: Invoice; get exchangeRate() { return this.parentdoc?.exchangeRate ?? 1; } get currency() { return this.parentdoc?.currency ?? DEFAULT_CURRENCY; } constructor(schema: Schema, data: DocValueMap, fyo: Fyo) { super(schema, data, fyo); this._setGetCurrencies(); } 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 ); const getCurrency = this._getCurrency.bind(this); for (const { fieldname } of currencyFields) { this.getCurrencies[fieldname] ??= getCurrency; } } }
2302_79757062/books
models/baseModels/TaxSummary/TaxSummary.ts
TypeScript
agpl-3.0
1,289
import { Fyo, t } from 'fyo'; import { Doc } from 'fyo/model/doc'; import { Action, ColumnConfig, DocStatus, LeadStatus, RenderData, } from 'fyo/model/types'; import { DateTime } from 'luxon'; import { Money } from 'pesa'; import { safeParseFloat } from 'utils/index'; import { Router } from 'vue-router'; import { AccountRootType, AccountRootTypeEnum, } from './baseModels/Account/types'; import { numberSeriesDefaultsMap } from './baseModels/Defaults/Defaults'; import { Invoice } from './baseModels/Invoice/Invoice'; import { SalesQuote } from './baseModels/SalesQuote/SalesQuote'; import { StockMovement } from './inventory/StockMovement'; import { StockTransfer } from './inventory/StockTransfer'; import { InvoiceStatus, ModelNameEnum } from './types'; import { Lead } from './baseModels/Lead/Lead'; import { PricingRule } from './baseModels/PricingRule/PricingRule'; import { ApplicablePricingRules } from './baseModels/Invoice/types'; import { LoyaltyProgram } from './baseModels/LoyaltyProgram/LoyaltyProgram'; import { CollectionRulesItems } from './baseModels/CollectionRulesItems/CollectionRulesItems'; import { isPesa } from 'fyo/utils'; import { Party } from './baseModels/Party/Party'; export function getQuoteActions( fyo: Fyo, schemaName: ModelNameEnum.SalesQuote ): Action[] { return [getMakeInvoiceAction(fyo, schemaName)]; } export function getLeadActions(fyo: Fyo): Action[] { return [getCreateCustomerAction(fyo), getSalesQuoteAction(fyo)]; } export function getInvoiceActions( fyo: Fyo, schemaName: ModelNameEnum.SalesInvoice | ModelNameEnum.PurchaseInvoice ): Action[] { return [ getMakePaymentAction(fyo), getMakeStockTransferAction(fyo, schemaName), getLedgerLinkAction(fyo), getMakeReturnDocAction(fyo), ]; } export function getStockTransferActions( fyo: Fyo, schemaName: ModelNameEnum.Shipment | ModelNameEnum.PurchaseReceipt ): Action[] { return [ getMakeInvoiceAction(fyo, schemaName), getLedgerLinkAction(fyo, false), getLedgerLinkAction(fyo, true), getMakeReturnDocAction(fyo), ]; } export function getMakeStockTransferAction( fyo: Fyo, schemaName: ModelNameEnum.SalesInvoice | ModelNameEnum.PurchaseInvoice ): Action { let label = fyo.t`Shipment`; if (schemaName === ModelNameEnum.PurchaseInvoice) { label = fyo.t`Purchase Receipt`; } return { label, group: fyo.t`Create`, condition: (doc: Doc) => doc.isSubmitted && !!doc.stockNotTransferred, action: async (doc: Doc) => { const transfer = await (doc as Invoice).getStockTransfer(); if (!transfer || !transfer.name) { return; } const { routeTo } = await import('src/utils/ui'); const path = `/edit/${transfer.schemaName}/${transfer.name}`; await routeTo(path); }, }; } export function getMakeInvoiceAction( fyo: Fyo, schemaName: | ModelNameEnum.Shipment | ModelNameEnum.PurchaseReceipt | ModelNameEnum.SalesQuote ): Action { let label = fyo.t`Sales Invoice`; if (schemaName === ModelNameEnum.PurchaseReceipt) { label = fyo.t`Purchase Invoice`; } return { label, group: fyo.t`Create`, condition: (doc: Doc) => { if (schemaName === ModelNameEnum.SalesQuote) { return doc.isSubmitted; } else { return doc.isSubmitted && !doc.backReference; } }, action: async (doc: Doc) => { const invoice = await (doc as SalesQuote | StockTransfer).getInvoice(); if (!invoice || !invoice.name) { return; } const { routeTo } = await import('src/utils/ui'); const path = `/edit/${invoice.schemaName}/${invoice.name}`; await routeTo(path); }, }; } export function getCreateCustomerAction(fyo: Fyo): Action { return { group: fyo.t`Create`, label: fyo.t`Customer`, condition: (doc: Doc) => !doc.notInserted, action: async (doc: Doc, router) => { const customerData = (doc as Lead).createCustomer(); if (!customerData.name) { return; } await router.push(`/edit/Party/${customerData.name}`); }, }; } export function getSalesQuoteAction(fyo: Fyo): Action { return { group: fyo.t`Create`, label: fyo.t`Sales Quote`, condition: (doc: Doc) => !doc.notInserted, action: async (doc, router) => { const salesQuoteData = (doc as Lead).createSalesQuote(); if (!salesQuoteData.name) { return; } await router.push(`/edit/SalesQuote/${salesQuoteData.name}`); }, }; } export function getMakePaymentAction(fyo: Fyo): Action { return { label: fyo.t`Payment`, group: fyo.t`Create`, condition: (doc: Doc) => doc.isSubmitted && !(doc.outstandingAmount as Money).isZero(), action: async (doc, router) => { const schemaName = doc.schema.name; const payment = (doc as Invoice).getPayment(); if (!payment) { return; } await payment?.set('referenceType', schemaName); const currentRoute = router.currentRoute.value.fullPath; payment.once('afterSync', async () => { await payment.submit(); await doc.load(); await router.push(currentRoute); }); const hideFields = ['party', 'for']; if (!fyo.singles.AccountingSettings?.enableInvoiceReturns) { hideFields.push('paymentType'); } if (doc.schemaName === ModelNameEnum.SalesInvoice) { hideFields.push('account'); } else { hideFields.push('paymentAccount'); } await payment.runFormulas(); const { openQuickEdit } = await import('src/utils/ui'); await openQuickEdit({ doc: payment, hideFields, }); }, }; } export function getLedgerLinkAction(fyo: Fyo, isStock = false): Action { let label = fyo.t`Accounting Entries`; let reportClassName: 'GeneralLedger' | 'StockLedger' = 'GeneralLedger'; if (isStock) { label = fyo.t`Stock Entries`; reportClassName = 'StockLedger'; } return { label, group: fyo.t`View`, condition: (doc: Doc) => doc.isSubmitted, action: async (doc: Doc, router: Router) => { const route = getLedgerLink(doc, reportClassName); await router.push(route); }, }; } export function getLedgerLink( doc: Doc, reportClassName: 'GeneralLedger' | 'StockLedger' ) { return { name: 'Report', params: { reportClassName, defaultFilters: JSON.stringify({ referenceType: doc.schemaName, referenceName: doc.name, }), }, }; } export function getMakeReturnDocAction(fyo: Fyo): Action { return { label: fyo.t`Return`, group: fyo.t`Create`, condition: (doc: Doc) => (!!fyo.singles.AccountingSettings?.enableInvoiceReturns || !!fyo.singles.InventorySettings?.enableStockReturns) && doc.isSubmitted && !doc.isReturn, action: async (doc: Doc) => { let returnDoc: Invoice | StockTransfer | undefined; if (doc instanceof Invoice || doc instanceof StockTransfer) { returnDoc = await doc.getReturnDoc(); } if (!returnDoc || !returnDoc.name) { return; } const { routeTo } = await import('src/utils/ui'); const path = `/edit/${doc.schemaName}/${returnDoc.name}`; await routeTo(path); }, }; } export function getTransactionStatusColumn(): ColumnConfig { return { label: t`Status`, fieldname: 'status', fieldtype: 'Select', render(doc) { const status = getDocStatus(doc) as InvoiceStatus; const color = statusColor[status] ?? 'gray'; const label = getStatusText(status); return { template: `<Badge class="text-xs" color="${color}">${label}</Badge>`, }; }, }; } export function getLeadStatusColumn(): ColumnConfig { return { label: t`Status`, fieldname: 'status', fieldtype: 'Select', render(doc) { const status = getLeadStatus(doc) as LeadStatus; const color = statusColor[status] ?? 'gray'; const label = getStatusTextOfLead(status); return { template: `<Badge class="text-xs" color="${color}">${label}</Badge>`, }; }, }; } export const statusColor: Record< DocStatus | InvoiceStatus | LeadStatus, string | undefined > = { '': 'gray', Draft: 'gray', Open: 'gray', Replied: 'yellow', Opportunity: 'yellow', Unpaid: 'orange', Paid: 'green', Interested: 'yellow', Converted: 'green', Quotation: 'green', Saved: 'gray', NotSaved: 'gray', Submitted: 'green', Cancelled: 'red', DonotContact: 'red', Return: 'green', ReturnIssued: 'green', }; export function getStatusText(status: DocStatus | InvoiceStatus): string { switch (status) { case 'Draft': return t`Draft`; case 'Saved': return t`Saved`; case 'NotSaved': return t`Not Saved`; case 'Submitted': return t`Submitted`; case 'Cancelled': return t`Cancelled`; case 'Paid': return t`Paid`; case 'Unpaid': return t`Unpaid`; case 'Return': return t`Return`; case 'ReturnIssued': return t`Return Issued`; default: return ''; } } export function getStatusTextOfLead(status: LeadStatus): string { switch (status) { case 'Open': return t`Open`; case 'Replied': return t`Replied`; case 'Opportunity': return t`Opportunity`; case 'Interested': return t`Interested`; case 'Converted': return t`Converted`; case 'Quotation': return t`Quotation`; case 'DonotContact': return t`Do not Contact`; default: return ''; } } export function getLeadStatus( doc?: Lead | Doc | RenderData ): LeadStatus | DocStatus { if (!doc) { return ''; } return doc.status as LeadStatus; } export function getDocStatus( doc?: RenderData | Doc ): DocStatus | InvoiceStatus { if (!doc) { return ''; } if (doc.notInserted) { return 'Draft'; } if (doc.dirty) { return 'NotSaved'; } if (!doc.schema?.isSubmittable) { return 'Saved'; } return getSubmittableDocStatus(doc); } function getSubmittableDocStatus(doc: RenderData | Doc) { if ( [ModelNameEnum.SalesInvoice, ModelNameEnum.PurchaseInvoice].includes( doc.schema.name as ModelNameEnum ) ) { return getInvoiceStatus(doc); } if ( [ModelNameEnum.Shipment, ModelNameEnum.PurchaseReceipt].includes( doc.schema.name as ModelNameEnum ) ) { if (!!doc.returnAgainst && doc.submitted && !doc.cancelled) { return 'Return'; } if (doc.isReturned && doc.submitted && !doc.cancelled) { return 'ReturnIssued'; } } if (!!doc.submitted && !doc.cancelled) { return 'Submitted'; } if (!!doc.submitted && !!doc.cancelled) { return 'Cancelled'; } return 'Saved'; } export function getInvoiceStatus(doc: RenderData | Doc): InvoiceStatus { if (doc.submitted && !doc.cancelled && doc.returnAgainst) { return 'Return'; } if (doc.submitted && !doc.cancelled && doc.isReturned) { return 'ReturnIssued'; } if ( doc.submitted && !doc.cancelled && (doc.outstandingAmount as Money).isZero() ) { return 'Paid'; } if ( doc.submitted && !doc.cancelled && (doc.outstandingAmount as Money).isPositive() ) { return 'Unpaid'; } if (doc.cancelled) { return 'Cancelled'; } return 'Saved'; } export function getSerialNumberStatusColumn(): ColumnConfig { return { label: t`Status`, fieldname: 'status', fieldtype: 'Select', render(doc) { let status = doc.status; if (typeof status !== 'string') { status = 'Inactive'; } const color = serialNumberStatusColor[status] ?? 'gray'; const label = getSerialNumberStatusText(status); return { template: `<Badge class="text-xs" color="${color}">${label}</Badge>`, }; }, }; } export const serialNumberStatusColor: Record<string, string | undefined> = { Inactive: 'gray', Active: 'green', Delivered: 'blue', }; export function getSerialNumberStatusText(status: string): string { switch (status) { case 'Inactive': return t`Inactive`; case 'Active': return t`Active`; case 'Delivered': return t`Delivered`; default: return t`Inactive`; } } export function getPriceListStatusColumn(): ColumnConfig { return { label: t`Enabled For`, fieldname: 'enabledFor', fieldtype: 'Select', render({ isSales, isPurchase }) { let status = t`None`; if (isSales && isPurchase) { status = t`Sales and Purchase`; } else if (isSales) { status = t`Sales`; } else if (isPurchase) { status = t`Purchase`; } return { template: `<Badge class="text-xs" color="gray">${status}</Badge>`, }; }, }; } export function getIsDocEnabledColumn(): ColumnConfig { return { label: t`Enabled`, fieldname: 'enabled', fieldtype: 'Data', render(doc) { let status = t`Disabled`; let color = 'orange'; if (doc.isEnabled) { status = t`Enabled`; color = 'green'; } return { template: `<Badge class="text-xs" color="${color}">${status}</Badge>`, }; }, }; } export async function getExchangeRate({ fromCurrency, toCurrency, date, }: { fromCurrency: string; toCurrency: string; date?: string; }) { if (!fetch) { return 1; } if (!date) { date = DateTime.local().toISODate(); } const cacheKey = `currencyExchangeRate:${date}:${fromCurrency}:${toCurrency}`; let exchangeRate = 0; if (localStorage) { exchangeRate = safeParseFloat(localStorage.getItem(cacheKey) as string); } if (exchangeRate && exchangeRate !== 1) { return exchangeRate; } try { const res = await fetch( `https://api.vatcomply.com/rates?date=${date}&base=${fromCurrency}&symbols=${toCurrency}` ); const data = (await res.json()) as { base: string; data: string; rates: Record<string, number>; }; exchangeRate = data.rates[toCurrency]; } catch (error) { // eslint-disable-next-line no-console console.error(error); exchangeRate ??= 1; } if (localStorage) { localStorage.setItem(cacheKey, String(exchangeRate)); } return exchangeRate; } export function isCredit(rootType: AccountRootType) { switch (rootType) { case AccountRootTypeEnum.Asset: return false; case AccountRootTypeEnum.Liability: return true; case AccountRootTypeEnum.Equity: return true; case AccountRootTypeEnum.Expense: return false; case AccountRootTypeEnum.Income: return true; default: return true; } } export function getNumberSeries(schemaName: string, fyo: Fyo) { const numberSeriesKey = numberSeriesDefaultsMap[schemaName]; if (!numberSeriesKey) { return undefined; } const defaults = fyo.singles.Defaults; const field = fyo.getField(schemaName, 'numberSeries'); const value = defaults?.[numberSeriesKey] as string | undefined; return value ?? (field?.default as string | undefined); } export function getDocStatusListColumn(): ColumnConfig { return { 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>`, }; }, }; } type ModelsWithItems = Invoice | StockTransfer | StockMovement; export async function addItem<M extends ModelsWithItems>(name: string, doc: M) { if (!doc.canEdit) { return; } const items = (doc.items ?? []) as NonNullable<M['items']>[number][]; let item = items.find((i) => i.item === name); if (item) { const q = item.quantity ?? 0; await item.set('quantity', q + 1); return; } await doc.append('items'); item = doc.items?.at(-1); if (!item) { return; } await item.set('item', name); } export async function createLoyaltyPointEntry(doc: Invoice) { const loyaltyProgramDoc = (await doc.fyo.doc.getDoc( ModelNameEnum.LoyaltyProgram, doc?.loyaltyProgram )) as LoyaltyProgram; if (!loyaltyProgramDoc.isEnabled) { return; } const expiryDate = new Date(Date.now()); expiryDate.setDate( expiryDate.getDate() + (loyaltyProgramDoc.expiryDuration || 0) ); let loyaltyProgramTier; let loyaltyPoint: number; if (doc.redeemLoyaltyPoints) { loyaltyPoint = -(doc.loyaltyPoints || 0); } else { loyaltyProgramTier = getLoyaltyProgramTier( loyaltyProgramDoc, doc?.grandTotal as Money ) as CollectionRulesItems; if (!loyaltyProgramTier) { return; } const collectionFactor = loyaltyProgramTier.collectionFactor as number; loyaltyPoint = Math.round(doc?.grandTotal?.float || 0) * collectionFactor; } const newLoyaltyPointEntry = doc.fyo.doc.getNewDoc( ModelNameEnum.LoyaltyPointEntry, { loyaltyProgram: doc.loyaltyProgram, customer: doc.party, invoice: doc.name, postingDate: doc.date, purchaseAmount: doc.grandTotal, expiryDate: expiryDate, loyaltyProgramTier: loyaltyProgramTier?.tierName, loyaltyPoints: loyaltyPoint, } ); return await newLoyaltyPointEntry.sync(); } export async function getAddedLPWithGrandTotal( fyo: Fyo, loyaltyProgram: string, loyaltyPoints: number ) { const loyaltyProgramDoc = (await fyo.doc.getDoc( ModelNameEnum.LoyaltyProgram, loyaltyProgram )) as LoyaltyProgram; const conversionFactor = loyaltyProgramDoc.conversionFactor as number; return fyo.pesa((loyaltyPoints || 0) * conversionFactor); } export function getLoyaltyProgramTier( loyaltyProgramData: LoyaltyProgram, grandTotal: Money ): CollectionRulesItems | undefined { if (!loyaltyProgramData.collectionRules) { return; } let loyaltyProgramTier: CollectionRulesItems | undefined; for (const row of loyaltyProgramData.collectionRules) { if (isPesa(row.minimumTotalSpent)) { const minimumSpent = row.minimumTotalSpent; if (!minimumSpent.lte(grandTotal)) { continue; } if ( !loyaltyProgramTier || minimumSpent.gt(loyaltyProgramTier.minimumTotalSpent as Money) ) { loyaltyProgramTier = row; } } } return loyaltyProgramTier; } export async function removeLoyaltyPoint(doc: Doc) { const data = (await doc.fyo.db.getAll(ModelNameEnum.LoyaltyPointEntry, { fields: ['name', 'loyaltyPoints', 'expiryDate'], filters: { loyaltyProgram: doc.loyaltyProgram as string, invoice: doc.isReturn ? (doc.returnAgainst as string) : (doc.name as string), }, })) as { name: string; loyaltyPoints: number; expiryDate: Date }[]; if (!data.length) { return; } const loyalityPointEntryDoc = await doc.fyo.doc.getDoc( ModelNameEnum.LoyaltyPointEntry, data[0].name ); const party = (await doc.fyo.doc.getDoc( ModelNameEnum.Party, doc.party as string )) as Party; await loyalityPointEntryDoc.delete(); await party.updateLoyaltyPoints(); } export async function getPricingRule( doc: Invoice ): Promise<ApplicablePricingRules[] | undefined> { if ( !doc.fyo.singles.AccountingSettings?.enablePricingRule || !doc.isSales || !doc.items ) { return; } const pricingRules: ApplicablePricingRules[] = []; for (const item of doc.items) { if (item.isFreeItem) { continue; } const pricingRuleDocNames = ( await doc.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 doc.fyo.db.getAll( ModelNameEnum.PricingRule, { fields: ['*'], filters: { name: ['in', pricingRuleDocNames], isEnabled: true, }, orderBy: 'priority', order: 'desc', } )) as PricingRule[]; const filtered = filterPricingRules( pricingRuleDocsForItem, doc.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; } export function filterPricingRules( pricingRuleDocsForItem: PricingRule[], sinvDate: Date, quantity: number, amount: Money ): PricingRule[] | [] { const filteredPricingRules: PricingRule[] | undefined = []; for (const pricingRuleDoc of pricingRuleDocsForItem) { if (canApplyPricingRule(pricingRuleDoc, sinvDate, quantity, amount)) { filteredPricingRules.push(pricingRuleDoc); } } return filteredPricingRules; } export function canApplyPricingRule( pricingRuleDoc: PricingRule, sinvDate: Date, quantity: number, amount: Money ): boolean { // Filter by Quantity if ( (pricingRuleDoc.minQuantity as number) > 0 && quantity < (pricingRuleDoc.minQuantity as number) ) { return false; } if ( (pricingRuleDoc.maxQuantity as number) > 0 && quantity > (pricingRuleDoc.maxQuantity as number) ) { return false; } // Filter by Amount if ( !pricingRuleDoc.minAmount?.isZero() && amount.lte(pricingRuleDoc.minAmount as Money) ) { return false; } if ( !pricingRuleDoc.maxAmount?.isZero() && amount.gte(pricingRuleDoc.maxAmount as Money) ) { return false; } // Filter by Validity if ( pricingRuleDoc.validFrom && new Date(sinvDate.setHours(0, 0, 0, 0)).toISOString() < pricingRuleDoc.validFrom.toISOString() ) { return false; } if ( pricingRuleDoc.validTo && new Date(sinvDate.setHours(0, 0, 0, 0)).toISOString() > pricingRuleDoc.validTo.toISOString() ) { return false; } return true; } export function getPricingRulesConflicts( pricingRules: PricingRule[] ): undefined | boolean { const pricingRuleDocs = Array.from(pricingRules); const firstPricingRule = pricingRuleDocs.shift(); if (!firstPricingRule) { return; } const conflictingPricingRuleNames: string[] = []; for (const pricingRuleDoc of pricingRuleDocs.slice(0)) { if (pricingRuleDoc.priority !== firstPricingRule?.priority) { continue; } conflictingPricingRuleNames.push(pricingRuleDoc.name as string); } if (!conflictingPricingRuleNames.length) { return; } return true; } export function roundFreeItemQty( quantity: number, roundingMethod: 'round' | 'floor' | 'ceil' ): number { return Math[roundingMethod](quantity); }
2302_79757062/books
models/helpers.ts
TypeScript
agpl-3.0
23,014
import { ModelMap } from 'fyo/model/types'; import { Account } from './baseModels/Account/Account'; import { AccountingLedgerEntry } from './baseModels/AccountingLedgerEntry/AccountingLedgerEntry'; import { AccountingSettings } from './baseModels/AccountingSettings/AccountingSettings'; import { Address } from './baseModels/Address/Address'; import { Defaults } from './baseModels/Defaults/Defaults'; import { Item } from './baseModels/Item/Item'; import { JournalEntry } from './baseModels/JournalEntry/JournalEntry'; import { JournalEntryAccount } from './baseModels/JournalEntryAccount/JournalEntryAccount'; import { Misc } from './baseModels/Misc'; import { Party } from './baseModels/Party/Party'; import { LoyaltyProgram } from './baseModels/LoyaltyProgram/LoyaltyProgram'; import { LoyaltyPointEntry } from './baseModels/LoyaltyPointEntry/LoyaltyPointEntry'; import { CollectionRulesItems } from './baseModels/CollectionRulesItems/CollectionRulesItems'; import { Lead } from './baseModels/Lead/Lead'; import { Payment } from './baseModels/Payment/Payment'; import { PaymentFor } from './baseModels/PaymentFor/PaymentFor'; import { PriceList } from './baseModels/PriceList/PriceList'; import { PriceListItem } from './baseModels/PriceList/PriceListItem'; import { PricingRule } from './baseModels/PricingRule/PricingRule'; import { PricingRuleItem } from './baseModels/PricingRuleItem/PricingRuleItem'; import { PrintSettings } from './baseModels/PrintSettings/PrintSettings'; import { PrintTemplate } from './baseModels/PrintTemplate'; import { PurchaseInvoice } from './baseModels/PurchaseInvoice/PurchaseInvoice'; import { PurchaseInvoiceItem } from './baseModels/PurchaseInvoiceItem/PurchaseInvoiceItem'; import { SalesInvoice } from './baseModels/SalesInvoice/SalesInvoice'; import { SalesInvoiceItem } from './baseModels/SalesInvoiceItem/SalesInvoiceItem'; import { SalesQuote } from './baseModels/SalesQuote/SalesQuote'; import { SalesQuoteItem } from './baseModels/SalesQuoteItem/SalesQuoteItem'; import { SetupWizard } from './baseModels/SetupWizard/SetupWizard'; import { Tax } from './baseModels/Tax/Tax'; import { TaxSummary } from './baseModels/TaxSummary/TaxSummary'; import { Batch } from './inventory/Batch'; import { InventorySettings } from './inventory/InventorySettings'; import { Location } from './inventory/Location'; import { PurchaseReceipt } from './inventory/PurchaseReceipt'; import { PurchaseReceiptItem } from './inventory/PurchaseReceiptItem'; import { SerialNumber } from './inventory/SerialNumber'; import { Shipment } from './inventory/Shipment'; import { ShipmentItem } from './inventory/ShipmentItem'; import { StockLedgerEntry } from './inventory/StockLedgerEntry'; import { StockMovement } from './inventory/StockMovement'; import { StockMovementItem } from './inventory/StockMovementItem'; import { ClosingAmounts } from './inventory/Point of Sale/ClosingAmounts'; import { ClosingCash } from './inventory/Point of Sale/ClosingCash'; import { OpeningAmounts } from './inventory/Point of Sale/OpeningAmounts'; import { OpeningCash } from './inventory/Point of Sale/OpeningCash'; import { POSSettings } from './inventory/Point of Sale/POSSettings'; import { POSShift } from './inventory/Point of Sale/POSShift'; export const models = { Account, AccountingLedgerEntry, AccountingSettings, Address, Batch, Defaults, Item, JournalEntry, JournalEntryAccount, Misc, Lead, Party, LoyaltyProgram, LoyaltyPointEntry, CollectionRulesItems, Payment, PaymentFor, PrintSettings, PriceList, PriceListItem, PricingRule, PricingRuleItem, PurchaseInvoice, PurchaseInvoiceItem, SalesInvoice, SalesInvoiceItem, SalesQuote, SalesQuoteItem, SerialNumber, SetupWizard, PrintTemplate, Tax, TaxSummary, // Inventory Models InventorySettings, StockMovement, StockMovementItem, StockLedgerEntry, Location, Shipment, ShipmentItem, PurchaseReceipt, PurchaseReceiptItem, // POS Models ClosingAmounts, ClosingCash, OpeningAmounts, OpeningCash, POSSettings, POSShift, } as ModelMap; export async function getRegionalModels( countryCode: string ): Promise<ModelMap> { if (countryCode !== 'in') { return {}; } const { Address } = await import('./regionalModels/in/Address'); const { Party } = await import('./regionalModels/in/Party'); return { Address, Party }; }
2302_79757062/books
models/index.ts
TypeScript
agpl-3.0
4,396
import { Doc } from 'fyo/model/doc'; import { ListViewSettings } from 'fyo/model/types'; export class Batch extends Doc { static getListViewSettings(): ListViewSettings { return { columns: ['name', 'expiryDate', 'manufactureDate'], }; } }
2302_79757062/books
models/inventory/Batch.ts
TypeScript
agpl-3.0
258
import { Doc } from 'fyo/model/doc'; import { FiltersMap, ReadOnlyMap } from 'fyo/model/types'; import { AccountTypeEnum } from 'models/baseModels/Account/types'; export class InventorySettings extends Doc { defaultLocation?: string; stockInHand?: string; stockReceivedButNotBilled?: string; costOfGoodsSold?: string; enableBarcodes?: boolean; enableBatches?: boolean; enableSerialNumber?: boolean; enableUomConversions?: boolean; enableStockReturns?: boolean; enablePointOfSale?: boolean; static filters: FiltersMap = { stockInHand: () => ({ isGroup: false, accountType: AccountTypeEnum.Stock, }), stockReceivedButNotBilled: () => ({ isGroup: false, accountType: AccountTypeEnum['Stock Received But Not Billed'], }), costOfGoodsSold: () => ({ isGroup: false, accountType: AccountTypeEnum['Cost of Goods Sold'], }), }; readOnly: ReadOnlyMap = { enableBarcodes: () => { return !!this.enableBarcodes; }, enableBatches: () => { return !!this.enableBatches; }, enableSerialNumber: () => { return !!this.enableSerialNumber; }, enableUomConversions: () => { return !!this.enableUomConversions; }, enableStockReturns: () => { return !!this.enableStockReturns; }, enablePointOfSale: () => { return !!this.fyo.singles.POSShift?.isShiftOpen; }, }; }
2302_79757062/books
models/inventory/InventorySettings.ts
TypeScript
agpl-3.0
1,415
import { Doc } from 'fyo/model/doc'; export class Location extends Doc { item?: string; }
2302_79757062/books
models/inventory/Location.ts
TypeScript
agpl-3.0
93
import { Doc } from 'fyo/model/doc'; import { Money } from 'pesa'; export abstract class CashDenominations extends Doc { denomination?: Money; }
2302_79757062/books
models/inventory/Point of Sale/CashDenominations.ts
TypeScript
agpl-3.0
148
import { Doc } from 'fyo/model/doc'; import { FormulaMap } from 'fyo/model/types'; import { Money } from 'pesa'; export class ClosingAmounts extends Doc { closingAmount?: Money; differenceAmount?: Money; expectedAmount?: Money; openingAmount?: Money; paymentMethod?: string; formulas: FormulaMap = { differenceAmount: { formula: () => { if (!this.closingAmount) { return this.fyo.pesa(0); } if (!this.expectedAmount) { return this.fyo.pesa(0); } return this.closingAmount.sub(this.expectedAmount); }, }, }; }
2302_79757062/books
models/inventory/Point of Sale/ClosingAmounts.ts
TypeScript
agpl-3.0
607
import { CashDenominations } from './CashDenominations'; export class ClosingCash extends CashDenominations { count?: number; }
2302_79757062/books
models/inventory/Point of Sale/ClosingCash.ts
TypeScript
agpl-3.0
131
import { CashDenominations } from './CashDenominations'; export class DefaultCashDenominations extends CashDenominations {}
2302_79757062/books
models/inventory/Point of Sale/DefaultCashDenominations.ts
TypeScript
agpl-3.0
125
import { Doc } from 'fyo/model/doc'; import { Money } from 'pesa'; export class OpeningAmounts extends Doc { amount?: Money; paymentMethod?: 'Cash' | 'Transfer'; get openingCashAmount() { return this.parentdoc?.openingCashAmount as Money; } }
2302_79757062/books
models/inventory/Point of Sale/OpeningAmounts.ts
TypeScript
agpl-3.0
257
import { CashDenominations } from './CashDenominations'; export class OpeningCash extends CashDenominations { count?: number; }
2302_79757062/books
models/inventory/Point of Sale/OpeningCash.ts
TypeScript
agpl-3.0
131
import { Doc } from 'fyo/model/doc'; import { FiltersMap } from 'fyo/model/types'; import { AccountRootTypeEnum, AccountTypeEnum, } from 'models/baseModels/Account/types'; export class POSSettings extends Doc { inventory?: string; cashAccount?: string; writeOffAccount?: string; static filters: FiltersMap = { cashAccount: () => ({ rootType: AccountRootTypeEnum.Asset, accountType: AccountTypeEnum.Cash, isGroup: false, }), }; }
2302_79757062/books
models/inventory/Point of Sale/POSSettings.ts
TypeScript
agpl-3.0
471
import { ClosingAmounts } from './ClosingAmounts'; import { ClosingCash } from './ClosingCash'; import { Doc } from 'fyo/model/doc'; import { OpeningAmounts } from './OpeningAmounts'; import { OpeningCash } from './OpeningCash'; export class POSShift extends Doc { closingAmounts?: ClosingAmounts[]; closingCash?: ClosingCash[]; closingDate?: Date; isShiftOpen?: boolean; openingAmounts?: OpeningAmounts[]; openingCash?: OpeningCash[]; openingDate?: Date; get openingCashAmount() { if (!this.openingCash) { return this.fyo.pesa(0); } let openingAmount = this.fyo.pesa(0); this.openingCash.map((row: OpeningCash) => { const denomination = row.denomination ?? this.fyo.pesa(0); const count = row.count ?? 0; const amount = denomination.mul(count); openingAmount = openingAmount.add(amount); }); return openingAmount; } get closingCashAmount() { if (!this.closingCash) { return this.fyo.pesa(0); } let closingAmount = this.fyo.pesa(0); this.closingCash.map((row: ClosingCash) => { const denomination = row.denomination ?? this.fyo.pesa(0); const count = row.count ?? 0; const amount = denomination.mul(count); closingAmount = closingAmount.add(amount); }); return closingAmount; } get openingTransferAmount() { if (!this.openingAmounts) { return this.fyo.pesa(0); } const transferAmountRow = this.openingAmounts.filter( (row) => row.paymentMethod === 'Transfer' )[0]; return transferAmountRow.amount ?? this.fyo.pesa(0); } }
2302_79757062/books
models/inventory/Point of Sale/POSShift.ts
TypeScript
agpl-3.0
1,600
import { Action, ListViewSettings } from 'fyo/model/types'; import { getStockTransferActions, getTransactionStatusColumn, } from 'models/helpers'; import { PurchaseReceiptItem } from './PurchaseReceiptItem'; import { StockTransfer } from './StockTransfer'; import { Fyo } from 'fyo'; import { ModelNameEnum } from 'models/types'; export class PurchaseReceipt extends StockTransfer { items?: PurchaseReceiptItem[]; static getListViewSettings(): ListViewSettings { return { columns: [ 'name', getTransactionStatusColumn(), 'party', 'date', 'grandTotal', ], }; } static getActions(fyo: Fyo): Action[] { return getStockTransferActions(fyo, ModelNameEnum.PurchaseReceipt); } }
2302_79757062/books
models/inventory/PurchaseReceipt.ts
TypeScript
agpl-3.0
753
import { StockTransferItem } from './StockTransferItem'; export class PurchaseReceiptItem extends StockTransferItem {}
2302_79757062/books
models/inventory/PurchaseReceiptItem.ts
TypeScript
agpl-3.0
120
import { Doc } from 'fyo/model/doc'; import { ListViewSettings } from 'fyo/model/types'; import { getSerialNumberStatusColumn } from 'models/helpers'; import { SerialNumberStatus } from './types'; export class SerialNumber extends Doc { name?: string; item?: string; description?: string; status?: SerialNumberStatus; static getListViewSettings(): ListViewSettings { return { columns: [ 'name', getSerialNumberStatusColumn(), 'item', 'description', 'party', ], }; } }
2302_79757062/books
models/inventory/SerialNumber.ts
TypeScript
agpl-3.0
542
import { Fyo } from 'fyo'; import { Action, ListViewSettings } from 'fyo/model/types'; import { getStockTransferActions, getTransactionStatusColumn, } from 'models/helpers'; import { ModelNameEnum } from 'models/types'; import { ShipmentItem } from './ShipmentItem'; import { StockTransfer } from './StockTransfer'; export class Shipment extends StockTransfer { items?: ShipmentItem[]; static getListViewSettings(): ListViewSettings { return { columns: [ 'name', getTransactionStatusColumn(), 'party', 'date', 'grandTotal', ], }; } static getActions(fyo: Fyo): Action[] { return getStockTransferActions(fyo, ModelNameEnum.Shipment); } }
2302_79757062/books
models/inventory/Shipment.ts
TypeScript
agpl-3.0
718
import { StockTransferItem } from './StockTransferItem'; export class ShipmentItem extends StockTransferItem {}
2302_79757062/books
models/inventory/ShipmentItem.ts
TypeScript
agpl-3.0
113
import { Doc } from 'fyo/model/doc'; import { ListViewSettings } from 'fyo/model/types'; import { Money } from 'pesa'; export class StockLedgerEntry extends Doc { date?: Date; item?: string; rate?: Money; quantity?: number; location?: string; referenceName?: string; referenceType?: string; batch?: string; serialNumber?: string; static override getListViewSettings(): ListViewSettings { return { columns: [ 'date', 'item', 'location', 'rate', 'quantity', 'referenceName', ], }; } }
2302_79757062/books
models/inventory/StockLedgerEntry.ts
TypeScript
agpl-3.0
575
import { Fyo, t } from 'fyo'; import { ValidationError } from 'fyo/utils/errors'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { StockLedgerEntry } from './StockLedgerEntry'; import { SMDetails, SMIDetails, SMTransferDetails } from './types'; import { getSerialNumbers } from './helpers'; export class StockManager { /** * The Stock Manager manages a group of Stock Manager Items * all of which would belong to a single transaction such as a * single Stock Movement entry. */ items: StockManagerItem[]; details: SMDetails; isCancelled: boolean; fyo: Fyo; constructor(details: SMDetails, isCancelled: boolean, fyo: Fyo) { this.items = []; this.details = details; this.isCancelled = isCancelled; this.fyo = fyo; } async validateTransfers(transferDetails: SMTransferDetails[]) { const detailsList = transferDetails.map((d) => this.#getSMIDetails(d)); for (const details of detailsList) { await this.#validate(details); } } async createTransfers(transferDetails: SMTransferDetails[]) { const detailsList = transferDetails.map((d) => this.#getSMIDetails(d)); for (const details of detailsList) { await this.#validate(details); } for (const details of detailsList) { this.#createTransfer(details); } await this.#sync(); } async cancelTransfers() { const { referenceName, referenceType } = this.details; await this.fyo.db.deleteAll(ModelNameEnum.StockLedgerEntry, { referenceType, referenceName, }); } async validateCancel(transferDetails: SMTransferDetails[]) { const reverseTransferDetails = transferDetails.map( ({ item, rate, quantity, fromLocation, toLocation, isReturn }) => ({ item, rate, quantity, fromLocation: toLocation, toLocation: fromLocation, isReturn, }) ); await this.validateTransfers(reverseTransferDetails); } async #sync() { for (const item of this.items) { await item.sync(); } } #createTransfer(details: SMIDetails) { const item = new StockManagerItem(details, this.fyo); item.transferStock(); this.items.push(item); } #getSMIDetails(transferDetails: SMTransferDetails): SMIDetails { return Object.assign({}, this.details, transferDetails); } async #validate(details: SMIDetails) { this.#validateRate(details); this.#validateQuantity(details); this.#validateLocation(details); await this.#validateStockAvailability(details); } #validateQuantity(details: SMIDetails) { if (!details.quantity) { throw new ValidationError(t`Quantity needs to be set`); } if (!details.isReturn && details.quantity <= 0) { throw new ValidationError( t`Quantity (${details.quantity}) has to be greater than zero` ); } } #validateRate(details: SMIDetails) { if (!details.rate) { throw new ValidationError(t`Rate needs to be set`); } if (details.rate.lt(0)) { throw new ValidationError( t`Rate (${details.rate.float}) has to be greater than zero` ); } } #validateLocation(details: SMIDetails) { if (details.fromLocation) { return; } if (details.toLocation) { return; } throw new ValidationError(t`Both From and To Location cannot be undefined`); } async #validateStockAvailability(details: SMIDetails) { if (!details.fromLocation) { return; } const date = details.date.toISOString(); const formattedDate = this.fyo.format(details.date, 'Datetime'); const batch = details.batch || undefined; const serialNumbers = getSerialNumbers(details.serialNumber ?? ''); let quantityBefore = (await this.fyo.db.getStockQuantity( details.item, details.fromLocation, undefined, date, batch, serialNumbers )) ?? 0; if (this.isCancelled) { quantityBefore += details.quantity; } const batchMessage = !!batch ? t` in Batch ${batch}` : ''; if (!details.isReturn && quantityBefore < details.quantity) { throw new ValidationError( [ t`Insufficient Quantity.`, t`Additional quantity (${ details.quantity - quantityBefore }) required${batchMessage} to make outward transfer of item ${ details.item } from ${details.fromLocation} on ${formattedDate}`, ].join('\n') ); } const quantityAfter = await this.fyo.db.getStockQuantity( details.item, details.fromLocation, details.date.toISOString(), undefined, batch, serialNumbers ); if (quantityAfter === null) { // No future transactions return; } const quantityRemaining = quantityBefore - details.quantity; const futureQuantity = quantityRemaining + quantityAfter; if (futureQuantity < 0) { throw new ValidationError( [ t`Insufficient Quantity.`, t`Transfer will cause future entries to have negative stock.`, t`Additional quantity (${-futureQuantity}) required${batchMessage} to make outward transfer of item ${ details.item } from ${details.fromLocation} on ${formattedDate}`, ].join('\n') ); } } } class StockManagerItem { /** * The Stock Manager Item is used to move stock to and from a location. It * updates the Stock Queue and creates Stock Ledger Entries. * * 1. Get existing stock Queue * 5. Create Stock Ledger Entry * 7. Insert Stock Ledger Entry */ date: Date; item: string; rate: Money; quantity: number; referenceName: string; referenceType: string; fromLocation?: string; toLocation?: string; batch?: string; serialNumber?: string; stockLedgerEntries?: StockLedgerEntry[]; fyo: Fyo; constructor(details: SMIDetails, fyo: Fyo) { this.date = details.date; this.item = details.item; this.rate = details.rate; this.quantity = details.quantity; this.fromLocation = details.fromLocation; this.toLocation = details.toLocation; this.referenceName = details.referenceName; this.referenceType = details.referenceType; this.batch = details.batch; this.serialNumber = details.serialNumber; this.fyo = fyo; } transferStock() { this.#clear(); this.#moveStockForBothLocations(); } async sync() { const sles = [ this.stockLedgerEntries?.filter((s) => s.quantity! <= 0), this.stockLedgerEntries?.filter((s) => s.quantity! > 0), ] .flat() .filter(Boolean); for (const sle of sles) { await sle!.sync(); } } #moveStockForBothLocations() { if (this.fromLocation) { this.#moveStockForSingleLocation(this.fromLocation, true); } if (this.toLocation) { this.#moveStockForSingleLocation(this.toLocation, false); } } #moveStockForSingleLocation(location: string, isOutward: boolean) { let quantity: number = this.quantity; if (quantity === 0) { return; } const serialNumbers = getSerialNumbers(this.serialNumber ?? ''); if (serialNumbers.length) { const snStockLedgerEntries = this.#getSerialNumberedStockLedgerEntries( location, isOutward, serialNumbers ); this.stockLedgerEntries?.push(...snStockLedgerEntries); return; } if (isOutward) { quantity = -quantity; } const stockLedgerEntry = this.#getStockLedgerEntry(location, quantity); this.stockLedgerEntries?.push(stockLedgerEntry); } #getSerialNumberedStockLedgerEntries( location: string, isOutward: boolean, serialNumbers: string[] ): StockLedgerEntry[] { let quantity = 1; if (isOutward) { quantity = -1; } return serialNumbers.map((sn) => this.#getStockLedgerEntry(location, quantity, sn) ); } #getStockLedgerEntry( location: string, quantity: number, serialNumber?: string ): StockLedgerEntry { return this.fyo.doc.getNewDoc(ModelNameEnum.StockLedgerEntry, { date: this.date, item: this.item, rate: this.rate, batch: this.batch || null, serialNumber: serialNumber || null, quantity, location, referenceName: this.referenceName, referenceType: this.referenceType, }) as StockLedgerEntry; } #clear() { this.stockLedgerEntries = []; } }
2302_79757062/books
models/inventory/StockManager.ts
TypeScript
agpl-3.0
8,487
import { Fyo, t } from 'fyo'; import { Action, DefaultMap, FiltersMap, FormulaMap, ListViewSettings, } from 'fyo/model/types'; import { ValidationError } from 'fyo/utils/errors'; import { LedgerPosting } from 'models/Transactional/LedgerPosting'; import { addItem, getDocStatusListColumn, getLedgerLinkAction, } from 'models/helpers'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { SerialNumber } from './SerialNumber'; import { StockMovementItem } from './StockMovementItem'; import { Transfer } from './Transfer'; import { canValidateSerialNumber, getSerialNumberFromDoc, updateSerialNumbers, validateBatch, validateSerialNumber, } from './helpers'; import { MovementType, MovementTypeEnum } from './types'; export class StockMovement extends Transfer { name?: string; date?: Date; numberSeries?: string; movementType?: MovementType; items?: StockMovementItem[]; amount?: Money; override get isTransactional(): boolean { return false; } // eslint-disable-next-line @typescript-eslint/require-await override async getPosting(): Promise<LedgerPosting | null> { return null; } formulas: FormulaMap = { amount: { formula: () => { return this.items?.reduce( (acc, item) => acc.add(item.amount ?? 0), this.fyo.pesa(0) ); }, dependsOn: ['items'], }, }; async validate() { await super.validate(); this.validateManufacture(); await validateBatch(this); await validateSerialNumber(this); await validateSerialNumberStatus(this); } async afterSubmit(): Promise<void> { await super.afterSubmit(); await updateSerialNumbers(this, false); } async afterCancel(): Promise<void> { await super.afterCancel(); await updateSerialNumbers(this, true); } validateManufacture() { if (this.movementType !== MovementTypeEnum.Manufacture) { return; } const hasFrom = this.items?.findIndex((f) => f.fromLocation) !== -1; const hasTo = this.items?.findIndex((f) => f.toLocation) !== -1; if (!hasFrom) { throw new ValidationError(this.fyo.t`Item with From location not found`); } if (!hasTo) { throw new ValidationError(this.fyo.t`Item with To location not found`); } } static filters: FiltersMap = { numberSeries: () => ({ referenceType: ModelNameEnum.StockMovement }), }; static defaults: DefaultMap = { date: () => new Date(), }; static getListViewSettings(fyo: Fyo): ListViewSettings { const movementTypeMap = { [MovementTypeEnum.MaterialIssue]: fyo.t`Material Issue`, [MovementTypeEnum.MaterialReceipt]: fyo.t`Material Receipt`, [MovementTypeEnum.MaterialTransfer]: fyo.t`Material Transfer`, [MovementTypeEnum.Manufacture]: fyo.t`Manufacture`, }; return { columns: [ 'name', getDocStatusListColumn(), 'date', { label: fyo.t`Movement Type`, fieldname: 'movementType', fieldtype: 'Select', display(value): string { return movementTypeMap[value as MovementTypeEnum] ?? ''; }, }, ], }; } _getTransferDetails() { return (this.items ?? []).map((row) => ({ item: row.item!, rate: row.rate!, quantity: row.quantity!, batch: row.batch!, serialNumber: row.serialNumber!, fromLocation: row.fromLocation, toLocation: row.toLocation, })); } static getActions(fyo: Fyo): Action[] { return [getLedgerLinkAction(fyo, true)]; } async addItem(name: string) { return await addItem(name, this); } } async function validateSerialNumberStatus(doc: StockMovement) { if (doc.isCancelled) { return; } for (const { serialNumber, item } of getSerialNumberFromDoc(doc)) { const cannotValidate = !(await canValidateSerialNumber(item, serialNumber)); if (cannotValidate) { continue; } const snDoc = await doc.fyo.doc.getDoc( ModelNameEnum.SerialNumber, serialNumber ); if (!(snDoc instanceof SerialNumber)) { continue; } const status = snDoc.status ?? 'Inactive'; if (doc.movementType === 'MaterialReceipt' && status !== 'Inactive') { throw new ValidationError( t`Non Inactive Serial Number ${serialNumber} cannot be used for Material Receipt` ); } if (doc.movementType === 'MaterialIssue' && status !== 'Active') { throw new ValidationError( t`Non Active Serial Number ${serialNumber} cannot be used for Material Issue` ); } if (doc.movementType === 'MaterialTransfer' && status !== 'Active') { throw new ValidationError( t`Non Active Serial Number ${serialNumber} cannot be used for Material Transfer` ); } if (item.fromLocation && status !== 'Active') { throw new ValidationError( t`Non Active Serial Number ${serialNumber} cannot be used as Manufacture raw material` ); } } }
2302_79757062/books
models/inventory/StockMovement.ts
TypeScript
agpl-3.0
5,039
import { t } from 'fyo'; import { DocValue } from 'fyo/core/types'; import { FiltersMap, FormulaMap, HiddenMap, ReadOnlyMap, RequiredMap, ValidationMap, } from 'fyo/model/types'; import { ValidationError } from 'fyo/utils/errors'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { safeParseFloat } from 'utils/index'; import { StockMovement } from './StockMovement'; import { TransferItem } from './TransferItem'; import { MovementTypeEnum } from './types'; export class StockMovementItem extends TransferItem { name?: string; item?: string; fromLocation?: string; toLocation?: string; unit?: string; transferUnit?: string; quantity?: number; transferQuantity?: number; unitConversionFactor?: number; rate?: Money; amount?: Money; batch?: string; serialNumber?: string; parentdoc?: StockMovement; get isIssue() { return this.parentdoc?.movementType === MovementTypeEnum.MaterialIssue; } get isReceipt() { return this.parentdoc?.movementType === MovementTypeEnum.MaterialReceipt; } get isTransfer() { return this.parentdoc?.movementType === MovementTypeEnum.MaterialTransfer; } get isManufacture() { return this.parentdoc?.movementType === MovementTypeEnum.Manufacture; } static filters: FiltersMap = { item: () => ({ trackItem: true }), }; formulas: FormulaMap = { rate: { formula: async () => { if (!this.item) { return this.rate; } return await this.fyo.getValue(ModelNameEnum.Item, this.item, 'rate'); }, dependsOn: ['item'], }, amount: { formula: () => this.rate!.mul(this.quantity!), dependsOn: ['item', 'rate', 'quantity'], }, fromLocation: { formula: () => { if (this.isReceipt || this.isTransfer || this.isManufacture) { return null; } const defaultLocation = this.fyo.singles.InventorySettings?.defaultLocation; if (defaultLocation && !this.fromLocation && this.isIssue) { return defaultLocation; } return this.toLocation; }, dependsOn: ['movementType'], }, toLocation: { formula: () => { if (this.isIssue || this.isTransfer || this.isManufacture) { return null; } const defaultLocation = this.fyo.singles.InventorySettings?.defaultLocation; if (defaultLocation && !this.toLocation && this.isReceipt) { return defaultLocation; } return this.toLocation; }, dependsOn: ['movementType'], }, 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 (fieldname === 'transferQuantity') { quantity = this.transferQuantity! * this.unitConversionFactor!; } if (unitDoc?.isWhole) { return Math.round(quantity); } return safeParseFloat(quantity); }, dependsOn: [ 'quantity', 'transferQuantity', 'transferUnit', 'unitConversionFactor', ], }, 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'], }, }; validations: ValidationMap = { fromLocation: (value) => { if (!this.isManufacture) { return; } if (value && this.toLocation) { throw new ValidationError( this.fyo.t`Only From or To can be set for Manufacture` ); } }, toLocation: (value) => { if (!this.isManufacture) { return; } if (value && this.fromLocation) { throw new ValidationError( this.fyo.t`Only From or To can be set for Manufacture` ); } }, 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 }` ); }, }; required: RequiredMap = { fromLocation: () => this.isIssue || this.isTransfer, toLocation: () => this.isReceipt || this.isTransfer, }; readOnly: ReadOnlyMap = { fromLocation: () => this.isReceipt, toLocation: () => this.isIssue, }; override hidden: HiddenMap = { batch: () => !this.fyo.singles.InventorySettings?.enableBatches, serialNumber: () => !this.fyo.singles.InventorySettings?.enableSerialNumber, transferUnit: () => !this.fyo.singles.InventorySettings?.enableUomConversions, transferQuantity: () => !this.fyo.singles.InventorySettings?.enableUomConversions, unitConversionFactor: () => !this.fyo.singles.InventorySettings?.enableUomConversions, }; static createFilters: FiltersMap = { item: () => ({ trackItem: true, itemType: 'Product' }), }; }
2302_79757062/books
models/inventory/StockMovementItem.ts
TypeScript
agpl-3.0
6,505
import { t } from 'fyo'; import { Attachment, DocValueMap } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { ChangeArg, DefaultMap, FiltersMap, FormulaMap, HiddenMap, } from 'fyo/model/types'; import { ValidationError } from 'fyo/utils/errors'; import { LedgerPosting } from 'models/Transactional/LedgerPosting'; import { Defaults } from 'models/baseModels/Defaults/Defaults'; import { Invoice } from 'models/baseModels/Invoice/Invoice'; import { addItem, getNumberSeries } from 'models/helpers'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { TargetField } from 'schemas/types'; import { SerialNumber } from './SerialNumber'; import { StockTransferItem } from './StockTransferItem'; import { Transfer } from './Transfer'; import { canValidateSerialNumber, getSerialNumberFromDoc, updateSerialNumbers, validateBatch, validateSerialNumber, } from './helpers'; import { ReturnDocItem } from './types'; import { getShipmentCOGSAmountFromSLEs } from 'reports/inventory/helpers'; export abstract class StockTransfer extends Transfer { name?: string; date?: Date; party?: string; terms?: string; attachment?: Attachment; grandTotal?: Money; backReference?: string; items?: StockTransferItem[]; isReturned?: boolean; returnAgainst?: string; get isSales() { return this.schemaName === ModelNameEnum.Shipment; } get isReturn(): boolean { return !!this.returnAgainst; } get invoiceSchemaName() { if (this.isSales) { return ModelNameEnum.SalesInvoice; } return ModelNameEnum.PurchaseInvoice; } formulas: FormulaMap = { grandTotal: { formula: () => this.getSum('items', 'amount', false), dependsOn: ['items'], }, }; hidden: HiddenMap = { backReference: () => !(this.backReference || !(this.isSubmitted || this.isCancelled)), terms: () => !(this.terms || !(this.isSubmitted || this.isCancelled)), attachment: () => !(this.attachment || !(this.isSubmitted || this.isCancelled)), returnAgainst: () => (this.isSubmitted || this.isCancelled) && !this.returnAgainst, }; static defaults: DefaultMap = { numberSeries: (doc) => getNumberSeries(doc.schemaName, doc.fyo), terms: (doc) => { const defaults = doc.fyo.singles.Defaults; if (doc.schemaName === ModelNameEnum.Shipment) { return defaults?.shipmentTerms ?? ''; } return defaults?.purchaseReceiptTerms ?? ''; }, date: () => new Date(), }; static filters: FiltersMap = { party: (doc: Doc) => ({ role: ['in', [doc.isSales ? 'Customer' : 'Supplier', 'Both']], }), numberSeries: (doc: Doc) => ({ referenceType: doc.schemaName }), backReference: () => ({ stockNotTransferred: ['!=', 0], submitted: true, cancelled: false, }), }; override _getTransferDetails() { return (this.items ?? []).map((row) => { let fromLocation = undefined; let toLocation = undefined; if (this.isSales) { fromLocation = row.location; } else { toLocation = row.location; } return { item: row.item!, rate: row.rate!, quantity: row.quantity!, batch: row.batch!, serialNumber: row.serialNumber!, isReturn: row.isReturn, fromLocation, toLocation, }; }); } override async getPosting(): Promise<LedgerPosting | null> { await this.validateAccounts(); const stockInHand = (await this.fyo.getValue( ModelNameEnum.InventorySettings, 'stockInHand' )) as string; const amount = await this.getPostingAmount(); const posting = new LedgerPosting(this, this.fyo); if (this.isSales) { const costOfGoodsSold = (await this.fyo.getValue( ModelNameEnum.InventorySettings, 'costOfGoodsSold' )) as string; if (this.isReturn) { await posting.debit(stockInHand, amount); await posting.credit(costOfGoodsSold, amount); } else { await posting.debit(costOfGoodsSold, amount); await posting.credit(stockInHand, amount); } } else { const stockReceivedButNotBilled = (await this.fyo.getValue( ModelNameEnum.InventorySettings, 'stockReceivedButNotBilled' )) as string; if (this.isReturn) { await posting.debit(stockReceivedButNotBilled, amount); await posting.credit(stockInHand, amount); } else { await posting.debit(stockInHand, amount); await posting.credit(stockReceivedButNotBilled, amount); } } await posting.makeRoundOffEntry(); return posting; } async getPostingAmount(): Promise<Money> { if (!this.isSales) { return this.grandTotal ?? this.fyo.pesa(0); } return await getShipmentCOGSAmountFromSLEs(this); } async validateAccounts() { const settings: string[] = ['stockInHand']; if (this.isSales) { settings.push('costOfGoodsSold'); } else { settings.push('stockReceivedButNotBilled'); } const messages: string[] = []; for (const setting of settings) { const value = this.fyo.singles.InventorySettings?.[setting] as | string | undefined; const field = this.fyo.getField(ModelNameEnum.InventorySettings, setting); if (!value) { messages.push(t`${field.label} account not set in Inventory Settings.`); continue; } const exists = await this.fyo.db.exists(ModelNameEnum.Account, value); if (!exists) { messages.push(t`Account ${value} does not exist.`); } } if (messages.length) { throw new ValidationError(messages.join(' ')); } } override async validate(): Promise<void> { await super.validate(); await validateBatch(this); await validateSerialNumber(this); await validateSerialNumberStatus(this); await this._validateHasReturnDocs(); } async afterSubmit() { await super.afterSubmit(); await updateSerialNumbers(this, false, this.isReturn); await this._updateBackReference(); await this._updateItemsReturned(); } async afterCancel(): Promise<void> { await super.afterCancel(); await updateSerialNumbers(this, true, this.isReturn); await this._updateBackReference(); await this._updateItemsReturned(); } async _updateBackReference() { if (!this.isCancelled && !this.isSubmitted) { return; } if (!this.backReference) { return; } const schemaName = this.isSales ? ModelNameEnum.SalesInvoice : ModelNameEnum.PurchaseInvoice; const invoice = (await this.fyo.doc.getDoc( schemaName, this.backReference )) as Invoice; const transferMap = this._getTransferMap(); for (const row of invoice.items ?? []) { const item = row.item!; const quantity = row.quantity!; const notTransferred = (row.stockNotTransferred as number) ?? 0; const transferred = transferMap[item]; if ( typeof transferred !== 'number' || typeof notTransferred !== 'number' ) { continue; } if (this.isCancelled) { await row.set( 'stockNotTransferred', Math.min(notTransferred + transferred, quantity) ); transferMap[item] = Math.max( transferred + notTransferred - quantity, 0 ); } else { await row.set( 'stockNotTransferred', Math.max(notTransferred - transferred, 0) ); transferMap[item] = Math.max(transferred - notTransferred, 0); } } const notTransferred = invoice.getStockNotTransferred(); await invoice.setAndSync('stockNotTransferred', notTransferred); } async _updateItemsReturned() { if (!this.returnAgainst) { return; } const linkedReference = await this.loadAndGetLink('returnAgainst'); if (!linkedReference) { return; } const referenceDoc = await this.fyo.doc.getDoc( this.schemaName, linkedReference.name ); const isReturned = this.isSubmitted; await referenceDoc.setAndSync({ isReturned }); } async _validateHasReturnDocs() { if (!this.name || !this.isCancelled) { return; } const returnDocs = await this.fyo.db.getAll(this.schemaName, { filters: { returnAgainst: this.name }, }); const hasReturnDocs = !!returnDocs.length; if (!hasReturnDocs) { return; } const returnDocNames = returnDocs.map((doc) => doc.name).join(', '); const label = this.fyo.schemaMap[this.schemaName]?.label ?? this.schemaName; throw new ValidationError( t`Cannot cancel ${this.schema.label} ${this.name} because of the following ${label}: ${returnDocNames}` ); } _getTransferMap() { return (this.items ?? []).reduce((acc, item) => { if (!item.item) { return acc; } if (!item.quantity) { return acc; } acc[item.item] ??= 0; acc[item.item] += item.quantity; return acc; }, {} as Record<string, number>); } override duplicate(): Doc { const doc = super.duplicate() as StockTransfer; doc.backReference = undefined; return doc; } static createFilters: FiltersMap = { party: (doc: Doc) => ({ role: doc.isSales ? 'Customer' : 'Supplier', }), }; async addItem(name: string) { return await addItem(name, this); } override async change({ doc, changed }: ChangeArg): Promise<void> { if (doc.name === this.name && changed === 'backReference') { await this.setFieldsFromBackReference(); } } async setFieldsFromBackReference() { const backReference = this.backReference; const { target } = this.fyo.getField( this.schemaName, 'backReference' ) as TargetField; if (!backReference || !target) { return; } const brDoc = await this.fyo.doc.getDoc(target, backReference); if (!(brDoc instanceof Invoice)) { return; } const stDoc = await brDoc.getStockTransfer(); if (!stDoc) { return; } await this.set('party', stDoc.party); await this.set('terms', stDoc.terms); await this.set('date', stDoc.date); await this.set('items', stDoc.items); } async getInvoice(): Promise<Invoice | null> { if (!this.isSubmitted || this.backReference) { return null; } const schemaName = this.invoiceSchemaName; const defaults = (this.fyo.singles.Defaults as Defaults) ?? {}; let terms; let numberSeries; if (this.isSales) { terms = defaults.salesInvoiceTerms ?? ''; numberSeries = defaults.salesInvoiceNumberSeries ?? undefined; } else { terms = defaults.purchaseInvoiceTerms ?? ''; numberSeries = defaults.purchaseInvoiceNumberSeries ?? undefined; } const data = { party: this.party, date: new Date().toISOString(), terms, numberSeries, backReference: this.name, }; const invoice = this.fyo.doc.getNewDoc(schemaName, data) as Invoice; for (const row of this.items ?? []) { if (!row.item) { continue; } const item = row.item; const unit = row.unit; const quantity = row.quantity; const batch = row.batch || null; const rate = row.rate ?? this.fyo.pesa(0); const description = row.description; const hsnCode = row.hsnCode; if (!quantity) { continue; } await invoice.append('items', { item, quantity, unit, rate, batch, hsnCode, description, }); } if (!invoice.items?.length) { return null; } return invoice; } async getReturnDoc(): Promise<StockTransfer | 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 StockTransfer; await newReturnDoc.runFormulas(); return newReturnDoc; } } async function validateSerialNumberStatus(doc: StockTransfer) { if (doc.isCancelled) { return; } for (const { serialNumber, item } of getSerialNumberFromDoc(doc)) { const cannotValidate = !(await canValidateSerialNumber(item, serialNumber)); if (cannotValidate) { continue; } const snDoc = await doc.fyo.doc.getDoc( ModelNameEnum.SerialNumber, serialNumber ); if (!(snDoc instanceof SerialNumber)) { continue; } const status = snDoc.status ?? 'Inactive'; const isSubmitted = !!doc.isSubmitted; const isReturn = !!doc.returnAgainst; if (isSubmitted || isReturn) { return; } if ( doc.schemaName === ModelNameEnum.PurchaseReceipt && status !== 'Inactive' ) { throw new ValidationError( t`Serial Number ${serialNumber} is not Inactive` ); } if (doc.schemaName === ModelNameEnum.Shipment && status !== 'Active') { throw new ValidationError( t`Serial Number ${serialNumber} is not Active.` ); } } }
2302_79757062/books
models/inventory/StockTransfer.ts
TypeScript
agpl-3.0
14,878
import { DocValue } from 'fyo/core/types'; import { Doc } from 'fyo/model/doc'; import { FiltersMap, FormulaMap, HiddenMap, ValidationMap, } from 'fyo/model/types'; import { ValidationError } from 'fyo/utils/errors'; import { ModelNameEnum } from 'models/types'; import { Money } from 'pesa'; import { safeParseFloat } from 'utils/index'; import { StockTransfer } from './StockTransfer'; import { TransferItem } from './TransferItem'; export class StockTransferItem extends TransferItem { item?: string; location?: string; unit?: string; transferUnit?: string; quantity?: number; transferQuantity?: number; unitConversionFactor?: number; rate?: Money; amount?: Money; description?: string; hsnCode?: number; batch?: string; serialNumber?: string; parentdoc?: StockTransfer; get isSales() { return this.schemaName === ModelNameEnum.ShipmentItem; } get isReturn(): boolean { return !!this.parentdoc?.isReturn; } formulas: FormulaMap = { description: { formula: async () => (await this.fyo.getValue( 'Item', this.item as string, 'description' )) as string, dependsOn: ['item'], }, 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', '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'], }, hsnCode: { formula: async () => (await this.fyo.getValue( 'Item', this.item as string, 'hsnCode' )) as string, dependsOn: ['item'], }, amount: { formula: () => { return this.rate?.mul(this.quantity ?? 0) ?? this.fyo.pesa(0); }, dependsOn: ['rate', 'quantity'], }, rate: { formula: async () => { const rate = (await this.fyo.getValue( 'Item', this.item as string, 'rate' )) as undefined | Money; if (!rate?.float && this.rate?.float) { return this.rate; } return rate ?? this.fyo.pesa(0); }, dependsOn: ['item'], }, account: { formula: () => { let accountType = 'expenseAccount'; if (this.isSales) { accountType = 'incomeAccount'; } return this.fyo.getValue('Item', this.item as string, accountType); }, dependsOn: ['item'], }, location: { formula: () => { if (this.location) { return; } const defaultLocation = this.fyo.singles.InventorySettings?.defaultLocation; if (defaultLocation && !this.location) { return defaultLocation; } }, }, }; validations: ValidationMap = { 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( this.fyo.t`Transfer Unit ${ value as string } is not applicable for Item ${this.item}` ); }, }; static filters: FiltersMap = { item: (doc: Doc) => { let itemNotFor = 'Sales'; if (doc.isSales) { itemNotFor = 'Purchases'; } return { for: ['not in', [itemNotFor]], trackItem: true }; }, }; override hidden: HiddenMap = { batch: () => !this.fyo.singles.InventorySettings?.enableBatches, serialNumber: () => !this.fyo.singles.InventorySettings?.enableSerialNumber, transferUnit: () => !this.fyo.singles.InventorySettings?.enableUomConversions, transferQuantity: () => !this.fyo.singles.InventorySettings?.enableUomConversions, unitConversionFactor: () => !this.fyo.singles.InventorySettings?.enableUomConversions, }; }
2302_79757062/books
models/inventory/StockTransferItem.ts
TypeScript
agpl-3.0
5,962
import { Transactional } from 'models/Transactional/Transactional'; import { StockManager } from './StockManager'; import type { SMTransferDetails } from './types'; import type { TransferItem } from './TransferItem'; import { createSerialNumbers } from './helpers'; export abstract class Transfer extends Transactional { date?: Date; items?: TransferItem[]; async beforeSubmit(): Promise<void> { await super.beforeSubmit(); const transferDetails = this._getTransferDetails(); await this._getStockManager().validateTransfers(transferDetails); } async afterSubmit(): Promise<void> { await super.afterSubmit(); await createSerialNumbers(this); const transferDetails = this._getTransferDetails(); await this._getStockManager().createTransfers(transferDetails); } async beforeCancel(): Promise<void> { await super.beforeCancel(); const transferDetails = this._getTransferDetails(); const stockManager = this._getStockManager(); stockManager.isCancelled = true; await stockManager.validateCancel(transferDetails); } async afterCancel(): Promise<void> { await super.afterCancel(); await this._getStockManager().cancelTransfers(); } _getStockManager(): StockManager { let date = this.date!; if (typeof date === 'string') { date = new Date(date); } return new StockManager( { date, referenceName: this.name!, referenceType: this.schemaName, }, this.isCancelled, this.fyo ); } abstract _getTransferDetails(): SMTransferDetails[]; }
2302_79757062/books
models/inventory/Transfer.ts
TypeScript
agpl-3.0
1,586
import { Doc } from 'fyo/model/doc'; import type { Transfer } from './Transfer'; import type { Money } from 'pesa'; export class TransferItem extends Doc { item?: string; unit?: string; transferUnit?: string; quantity?: number; transferQuantity?: number; unitConversionFactor?: number; rate?: Money; amount?: Money; batch?: string; serialNumber?: string; parentdoc?: Transfer; }
2302_79757062/books
models/inventory/TransferItem.ts
TypeScript
agpl-3.0
406
import { Fyo, t } from 'fyo'; import { ValidationError } from 'fyo/utils/errors'; import type { Invoice } from 'models/baseModels/Invoice/Invoice'; import type { InvoiceItem } from 'models/baseModels/InvoiceItem/InvoiceItem'; import { ModelNameEnum } from 'models/types'; import { SerialNumber } from './SerialNumber'; import type { StockMovement } from './StockMovement'; import type { StockMovementItem } from './StockMovementItem'; import type { StockTransfer } from './StockTransfer'; import type { StockTransferItem } from './StockTransferItem'; import { Transfer } from './Transfer'; import { TransferItem } from './TransferItem'; import type { SerialNumberStatus } from './types'; export async function validateBatch( doc: StockMovement | StockTransfer | Invoice ) { for (const row of doc.items ?? []) { await validateItemRowBatch(row); } } async function validateItemRowBatch( doc: StockMovementItem | StockTransferItem | InvoiceItem ) { const idx = doc.idx ?? 0; const item = doc.item; const batch = doc.batch; if (!item) { return; } const hasBatch = await doc.fyo.getValue(ModelNameEnum.Item, item, 'hasBatch'); if (!hasBatch && batch) { throw new ValidationError( [ doc.fyo.t`Batch set for row ${idx + 1}.`, doc.fyo.t`Item ${item} is not a batched item`, ].join(' ') ); } if (hasBatch && !batch) { throw new ValidationError( [ doc.fyo.t`Batch not set for row ${idx + 1}.`, doc.fyo.t`Item ${item} is a batched item`, ].join(' ') ); } } export async function validateSerialNumber(doc: StockMovement | StockTransfer) { if (doc.isCancelled) { return; } for (const row of doc.items ?? []) { await validateItemRowSerialNumber(row); } } async function validateItemRowSerialNumber( row: StockMovementItem | StockTransferItem ) { const idx = row.idx ?? 0; const item = row.item; if (!item) { return; } const hasSerialNumber = await row.fyo.getValue( ModelNameEnum.Item, item, 'hasSerialNumber' ); if (hasSerialNumber && !row.serialNumber) { throw new ValidationError( [ row.fyo.t`Serial Number not set for row ${idx + 1}.`, row.fyo.t`Serial Number is enabled for Item ${item}`, ].join(' ') ); } if (!hasSerialNumber && row.serialNumber) { throw new ValidationError( [ row.fyo.t`Serial Number set for row ${idx + 1}.`, row.fyo.t`Serial Number is not enabled for Item ${item}`, ].join(' ') ); } const serialNumber = row.serialNumber; if (!hasSerialNumber || typeof serialNumber !== 'string') { return; } const serialNumbers = getSerialNumbers(serialNumber); const quantity = Math.abs(row.quantity ?? 0); if (serialNumbers.length !== quantity) { throw new ValidationError( t`Additional ${ quantity - serialNumbers.length } Serial Numbers required for ${quantity} quantity of ${item}.` ); } const nonExistingIncomingSerialNumbers: string[] = []; for (const serialNumber of serialNumbers) { if (await row.fyo.db.exists(ModelNameEnum.SerialNumber, serialNumber)) { continue; } if (isSerialNumberIncoming(row)) { nonExistingIncomingSerialNumbers.push(serialNumber); continue; } throw new ValidationError(t`Serial Number ${serialNumber} does not exist.`); } for (const serialNumber of serialNumbers) { if (nonExistingIncomingSerialNumbers.includes(serialNumber)) { continue; } const snDoc = await row.fyo.doc.getDoc( ModelNameEnum.SerialNumber, serialNumber ); if (!(snDoc instanceof SerialNumber)) { continue; } if (snDoc.item !== item) { throw new ValidationError( t`Serial Number ${serialNumber} does not belong to the item ${item}.` ); } const status = snDoc.status ?? 'Inactive'; const schemaName = row.parentSchemaName; const isReturn = !!row.parentdoc?.returnAgainst; const isSubmitted = !!row.parentdoc?.submitted; if ( schemaName === 'PurchaseReceipt' && status !== 'Inactive' && !isSubmitted && !isReturn ) { throw new ValidationError( t`Serial Number ${serialNumber} is not Inactive` ); } if ( schemaName === 'Shipment' && status !== 'Active' && !isSubmitted && !isReturn ) { throw new ValidationError( t`Serial Number ${serialNumber} is not Active.` ); } } } export function getSerialNumbers(serialNumber: string): string[] { if (!serialNumber) { return []; } return serialNumber .split('\n') .map((s) => s.trim()) .filter(Boolean); } export function getSerialNumberFromDoc(doc: StockTransfer | StockMovement) { if (!doc.items?.length) { return []; } return doc.items .map((item) => getSerialNumbers(item.serialNumber ?? '').map((serialNumber) => ({ serialNumber, item, })) ) .flat() .filter(Boolean); } export async function createSerialNumbers(doc: Transfer) { const items = doc.items ?? []; const serialNumberCreateList = items .map((item) => { const serialNumbers = getSerialNumbers(item.serialNumber ?? ''); return serialNumbers.map((serialNumber) => ({ item: item.item ?? '', serialNumber, isIncoming: isSerialNumberIncoming(item), })); }) .flat() .filter(({ item, isIncoming }) => isIncoming && item); for (const { item, serialNumber } of serialNumberCreateList) { if (await doc.fyo.db.exists(ModelNameEnum.SerialNumber, serialNumber)) { continue; } const snDoc = doc.fyo.doc.getNewDoc(ModelNameEnum.SerialNumber, { name: serialNumber, item, }); const status: SerialNumberStatus = 'Active'; await snDoc.set('status', status); await snDoc.sync(); } } function isSerialNumberIncoming(item: TransferItem) { if (item.parentdoc?.schemaName === ModelNameEnum.Shipment) { return false; } if (item.parentdoc?.schemaName === ModelNameEnum.PurchaseReceipt) { return true; } return !!item.toLocation && !item.fromLocation; } export async function canValidateSerialNumber( item: StockTransferItem | StockMovementItem, serialNumber: string ) { if (!isSerialNumberIncoming(item)) { return true; } return await item.fyo.db.exists(ModelNameEnum.SerialNumber, serialNumber); } export async function updateSerialNumbers( doc: StockTransfer | StockMovement, isCancel: boolean, isReturn = false ) { for (const row of doc.items ?? []) { if (!row.serialNumber) { continue; } const status = getSerialNumberStatus(doc, row, isCancel, isReturn); await updateSerialNumberStatus(status, row.serialNumber, doc.fyo); } } async function updateSerialNumberStatus( status: SerialNumberStatus, serialNumber: string, fyo: Fyo ) { for (const name of getSerialNumbers(serialNumber)) { const doc = await fyo.doc.getDoc(ModelNameEnum.SerialNumber, name); await doc.setAndSync('status', status); } } function getSerialNumberStatus( doc: StockTransfer | StockMovement, item: StockTransferItem | StockMovementItem, isCancel: boolean, isReturn: boolean ): SerialNumberStatus { if (doc.schemaName === ModelNameEnum.Shipment) { if (isReturn) { return isCancel ? 'Delivered' : 'Active'; } return isCancel ? 'Active' : 'Delivered'; } if (doc.schemaName === ModelNameEnum.PurchaseReceipt) { if (isReturn) { return isCancel ? 'Active' : 'Delivered'; } return isCancel ? 'Inactive' : 'Active'; } return getSerialNumberStatusForStockMovement( doc as StockMovement, item, isCancel ); } function getSerialNumberStatusForStockMovement( doc: StockMovement, item: StockTransferItem | StockMovementItem, isCancel: boolean ): SerialNumberStatus { if (doc.movementType === 'MaterialIssue') { return isCancel ? 'Active' : 'Delivered'; } if (doc.movementType === 'MaterialReceipt') { return isCancel ? 'Inactive' : 'Active'; } if (doc.movementType === 'MaterialTransfer') { return 'Active'; } // MovementType is Manufacture if (item.fromLocation) { return isCancel ? 'Active' : 'Delivered'; } return isCancel ? 'Inactive' : 'Active'; }
2302_79757062/books
models/inventory/helpers.ts
TypeScript
agpl-3.0
8,350
export class StockQueue { quantity: number; value: number; queue: { rate: number; quantity: number }[]; movingAverage: number; constructor() { this.value = 0; this.quantity = 0; this.movingAverage = 0; this.queue = []; } get fifo() { /** * Stock value maintained is based on the stock queue * ∴ FIFO by default. This returns FIFO valuation rate. */ const valuation = this.value / this.quantity; if (Number.isNaN(valuation)) { return 0; } return valuation; } inward(rate: number, quantity: number): null | number { if (quantity <= 0 || rate < 0) { return null; } const inwardValue = rate * quantity; /** * Update Moving Average valuation */ this.movingAverage = (this.movingAverage * this.quantity + inwardValue) / (this.quantity + quantity); this.quantity += quantity; this.value += inwardValue; const last = this.queue.at(-1); if (last?.rate !== rate) { this.queue.push({ rate, quantity }); } else { last.quantity += quantity; } return rate; } outward(quantity: number): null | number { if (this.quantity < quantity || quantity <= 0) { return null; } let incomingRate = 0; this.quantity -= quantity; let remaining = quantity; while (remaining > 0) { const last = this.queue.shift(); if (last === undefined) { return null; } const storedQuantity = last.quantity; let quantityRemoved = remaining; const quantityLeft = storedQuantity - remaining; remaining = remaining - storedQuantity; if (remaining > 0) { quantityRemoved = storedQuantity; } if (quantityLeft > 0) { this.queue.unshift({ rate: last.rate, quantity: quantityLeft }); } this.value -= last.rate * quantityRemoved; incomingRate += quantityRemoved * last.rate; } return incomingRate / quantity; } }
2302_79757062/books
models/inventory/stockQueue.ts
TypeScript
agpl-3.0
1,987
import { Fyo } from 'fyo'; import { Batch } from 'models/inventory/Batch'; import { ModelNameEnum } from 'models/types'; import { StockMovement } from '../StockMovement'; import { StockTransfer } from '../StockTransfer'; import { MovementTypeEnum } from '../types'; type ALE = { date: string; account: string; party: string; debit: string; credit: string; reverted: number; }; type SLE = { date: string; name: string; item: string; location: string; rate: string; quantity: string; }; type Transfer = { item: string; from?: string; to?: string; batch?: string; serialNumber?: string; quantity: number; rate: number; }; interface TransferTwo extends Omit<Transfer, 'from' | 'to'> { location: string; } export function getItem( name: string, rate: number, hasBatch = false, hasSerialNumber = false ) { return { name, rate, trackItem: true, hasBatch, hasSerialNumber }; } export function getBatch( schemaName: ModelNameEnum.Batch, batch: string, expiryDate: Date, manufactureDate: Date, fyo: Fyo ): Batch { const doc = fyo.doc.getNewDoc(schemaName, { batch, expiryDate, manufactureDate, }) as Batch; return doc; } export async function getStockTransfer( schemaName: ModelNameEnum.PurchaseReceipt | ModelNameEnum.Shipment, party: string, date: Date, transfers: TransferTwo[], fyo: Fyo ): Promise<StockTransfer> { const doc = fyo.doc.getNewDoc(schemaName, { party, date }) as StockTransfer; for (const { item, location, quantity, rate } of transfers) { await doc.append('items', { item, location, quantity, rate }); } return doc; } export async function getStockMovement( movementType: MovementTypeEnum, date: Date, transfers: Transfer[], fyo: Fyo ): Promise<StockMovement> { const doc = fyo.doc.getNewDoc(ModelNameEnum.StockMovement, { movementType, date, }) as StockMovement; for (const { item, from: fromLocation, to: toLocation, batch, serialNumber, quantity, rate, } of transfers) { await doc.append('items', { item, fromLocation, toLocation, batch, serialNumber, rate, quantity, }); } return doc; } export async function getSLEs( referenceName: string, referenceType: string, fyo: Fyo ) { return (await fyo.db.getAllRaw(ModelNameEnum.StockLedgerEntry, { filters: { referenceName, referenceType }, fields: ['date', 'name', 'item', 'location', 'rate', 'quantity'], })) as SLE[]; } export async function getALEs( referenceName: string, referenceType: string, fyo: Fyo ) { return (await fyo.db.getAllRaw(ModelNameEnum.AccountingLedgerEntry, { filters: { referenceName, referenceType }, fields: ['date', 'account', 'party', 'debit', 'credit', 'reverted'], })) as ALE[]; }
2302_79757062/books
models/inventory/tests/helpers.ts
TypeScript
agpl-3.0
2,821
import { Money } from 'pesa'; export enum ValuationMethod { 'FIFO' = 'FIFO', 'MovingAverage' = 'MovingAverage', } export enum MovementTypeEnum { 'MaterialIssue' = 'MaterialIssue', 'MaterialReceipt' = 'MaterialReceipt', 'MaterialTransfer' = 'MaterialTransfer', 'Manufacture' = 'Manufacture', } export type MovementType = | 'MaterialIssue' | 'MaterialReceipt' | 'MaterialTransfer' | 'Manufacture'; export type SerialNumberStatus = | 'Inactive' | 'Active' | 'Delivered'; export interface SMDetails { date: Date; referenceName: string; referenceType: string; } export interface SMTransferDetails { item: string; rate: Money; quantity: number; batch?: string; serialNumber?: string; fromLocation?: string; toLocation?: string; isReturn?: boolean; } export interface ReturnBalanceItemQty { item?: string; quantity: number; batch?: string | undefined; serialNumber?: string; } export interface DocItem { item: string; quantity: number; batch?: string | undefined; serialNumber?: string; } export interface ReturnDocItem { quantity: number; batches?: Record<string, { quantity: number, serialNumbers?: string[] }> | undefined; serialNumbers?: string[] | undefined; } export interface SMIDetails extends SMDetails, SMTransferDetails {}
2302_79757062/books
models/inventory/types.ts
TypeScript
agpl-3.0
1,307
import { FormulaMap, ListsMap } from 'fyo/model/types'; import { Address as BaseAddress } from 'models/baseModels/Address/Address'; import { codeStateMap } from 'regional/in'; export class Address extends BaseAddress { 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', ], }, pos: { formula: () => { const stateList = Object.values(codeStateMap).sort(); const state = this.state as string; if (stateList.includes(state)) { return state; } return ''; }, dependsOn: ['state'], }, }; static lists: ListsMap = { ...BaseAddress.lists, pos: () => { return Object.values(codeStateMap).sort(); }, }; }
2302_79757062/books
models/regionalModels/in/Address.ts
TypeScript
agpl-3.0
1,107
import { HiddenMap } from 'fyo/model/types'; import { Party as BaseParty } from 'models/baseModels/Party/Party'; import { GSTType } from './types'; import { PartyRole } from 'models/baseModels/Party/types'; export class Party extends BaseParty { gstin?: string; role?: PartyRole; gstType?: GSTType; loyaltyProgram?: string; // eslint-disable-next-line @typescript-eslint/require-await async beforeSync() { const gstin = this.get('gstin') as string | undefined; const gstType = this.get('gstType') as GSTType; if (gstin && gstType !== 'Registered Regular') { this.gstin = ''; } } hidden: HiddenMap = { gstin: () => (this.gstType as GSTType) !== 'Registered Regular', loyaltyProgram: () => { if (!this.fyo.singles.AccountingSettings?.enableLoyaltyProgram) { return true; } return this.role === 'Supplier'; }, loyaltyPoints: () => !this.loyaltyProgram || this.role === 'Supplier', }; }
2302_79757062/books
models/regionalModels/in/Party.ts
TypeScript
agpl-3.0
969
export type GSTType = 'Unregistered' | 'Registered Regular' | 'Consumer';
2302_79757062/books
models/regionalModels/in/types.ts
TypeScript
agpl-3.0
74
export type InvoiceStatus = 'Draft' | 'Saved' | 'Unpaid' | 'Cancelled' | 'Paid' | 'Return' | 'ReturnIssued'; export enum ModelNameEnum { Account = 'Account', AccountingLedgerEntry = 'AccountingLedgerEntry', AccountingSettings = 'AccountingSettings', Address = 'Address', Batch= 'Batch', Color = 'Color', Currency = 'Currency', GetStarted = 'GetStarted', Defaults = 'Defaults', Item = 'Item', ItemPrice = 'ItemPrice', UOM = 'UOM', UOMConversionItem = 'UOMConversionItem', JournalEntry = 'JournalEntry', JournalEntryAccount = 'JournalEntryAccount', Misc = 'Misc', NumberSeries = 'NumberSeries', Lead = 'Lead', Party = 'Party', LoyaltyProgram = 'LoyaltyProgram', LoyaltyPointEntry = 'LoyaltyPointEntry', CollectionRulesItems = 'CollectionRulesItems', Payment = 'Payment', PaymentFor = 'PaymentFor', PriceList = 'PriceList', PricingRule = 'PricingRule', PricingRuleItem = 'PricingRuleItem', PricingRuleDetail = 'PricingRuleDetail', PrintSettings = 'PrintSettings', PrintTemplate = 'PrintTemplate', PurchaseInvoice = 'PurchaseInvoice', PurchaseInvoiceItem = 'PurchaseInvoiceItem', SalesInvoice = 'SalesInvoice', SalesInvoiceItem = 'SalesInvoiceItem', SalesQuote = 'SalesQuote', SalesQuoteItem = 'SalesQuoteItem', SerialNumber = 'SerialNumber', SetupWizard = 'SetupWizard', Tax = 'Tax', TaxDetail = 'TaxDetail', TaxSummary = 'TaxSummary', PatchRun = 'PatchRun', SingleValue = 'SingleValue', InventorySettings = 'InventorySettings', SystemSettings = 'SystemSettings', StockMovement = 'StockMovement', StockMovementItem = 'StockMovementItem', StockLedgerEntry = 'StockLedgerEntry', Shipment = 'Shipment', ShipmentItem = 'ShipmentItem', PurchaseReceipt = 'PurchaseReceipt', PurchaseReceiptItem = 'PurchaseReceiptItem', Location = 'Location', CustomForm = 'CustomForm', CustomField = 'CustomField', POSSettings = 'POSSettings', POSShift = 'POSShift' } export type ModelName = keyof typeof ModelNameEnum;
2302_79757062/books
models/types.ts
TypeScript
agpl-3.0
2,009
module.exports = { plugins: [require('tailwindcss'), require('autoprefixer')], };
2302_79757062/books
postcss.config.js
JavaScript
agpl-3.0
84
export const codeStateMap = { '01': 'Jammu and Kashmir', '02': 'Himachal Pradesh', '03': 'Punjab', '04': 'Chandigarh', '05': 'Uttarakhand', '06': 'Haryana', '07': 'Delhi', '08': 'Rajasthan', '09': 'Uttar Pradesh', '10': 'Bihar', '11': 'Sikkim', '12': 'Arunachal Pradesh', '13': 'Nagaland', '14': 'Manipur', '15': 'Mizoram', '16': 'Tripura', '17': 'Meghalaya', '18': 'Assam', '19': 'West Bengal', '20': 'Jharkhand', '21': 'Odisha', '22': 'Chattisgarh', '23': 'Madhya Pradesh', '24': 'Gujarat', '26': 'Dadra and Nagar Haveli and Daman and Diu', '27': 'Maharashtra', '29': 'Karnataka', '30': 'Goa', '31': 'Lakshadweep', '32': 'Kerala', '33': 'Tamil Nadu', '34': 'Puducherry', '35': 'Andaman and Nicobar Islands', '36': 'Telangana', '37': 'Andhra Pradesh', '38': 'Ladakh', } as Record<string, string>;
2302_79757062/books
regional/in.ts
TypeScript
agpl-3.0
870
import { Fyo, t } from 'fyo'; import { cloneDeep } from 'lodash'; import { DateTime } from 'luxon'; import { AccountRootType } from 'models/baseModels/Account/types'; import { isCredit } from 'models/helpers'; import { ModelNameEnum } from 'models/types'; import { LedgerReport } from 'reports/LedgerReport'; import { Account, AccountList, AccountListNode, AccountNameValueMapMap, AccountTree, AccountTreeNode, BasedOn, ColumnField, DateRange, GroupedMap, LedgerEntry, Periodicity, ReportCell, ReportData, ReportRow, Tree, TreeNode, ValueMap, } from 'reports/types'; import { Field } from 'schemas/types'; import { getMapFromList } from 'utils'; import { QueryFilter } from 'utils/db/types'; export const ACC_NAME_WIDTH = 2; export const ACC_BAL_WIDTH = 1.25; export abstract class AccountReport extends LedgerReport { toDate?: string; count = 3; fromYear?: number; toYear?: number; consolidateColumns = false; hideGroupAmounts = false; periodicity: Periodicity = 'Monthly'; basedOn: BasedOn = 'Until Date'; _rawData: LedgerEntry[] = []; _dateRanges?: DateRange[]; accountMap?: Record<string, Account>; async setDefaultFilters(): Promise<void> { if (this.basedOn === 'Until Date' && !this.toDate) { this.toDate = DateTime.now().plus({ days: 1 }).toISODate(); } if (this.basedOn === 'Fiscal Year' && !this.toYear) { this.fromYear = DateTime.now().year; this.toYear = this.fromYear + 1; } await this._setDateRanges(); } async _setDateRanges() { this._dateRanges = await this._getDateRanges(); } getRootNodes( rootType: AccountRootType, accountTree: AccountTree ): AccountTreeNode[] | undefined { const rootNodeList = Object.values(accountTree); return rootNodeList.filter((n) => n.rootType === rootType); } getEmptyRow(): ReportRow { const columns = this.getColumns(); return { isEmpty: true, cells: columns.map( (c) => ({ value: '', rawValue: '', width: c.width, align: 'left', } as ReportCell) ), }; } getTotalNode(rootNodes: AccountTreeNode[], name: string): AccountListNode { const accountTree: Tree = {}; for (const rootNode of rootNodes) { accountTree[rootNode.name] = rootNode; } const leafNodes = getListOfLeafNodes(accountTree) as AccountTreeNode[]; const totalMap = leafNodes.reduce((acc, node) => { for (const key of this._dateRanges!) { const bal = acc.get(key)?.balance ?? 0; const val = node.valueMap?.get(key)?.balance ?? 0; acc.set(key, { balance: bal + val }); } return acc; }, new Map() as ValueMap); return { name, valueMap: totalMap, level: 0 } as AccountListNode; } getReportRowsFromAccountList(accountList: AccountList): ReportData { return accountList.map((al) => { return this.getRowFromAccountListNode(al); }); } getRowFromAccountListNode(al: AccountListNode) { const nameCell = { value: al.name, rawValue: al.name, align: 'left', width: ACC_NAME_WIDTH, bold: !al.level, indent: al.level ?? 0, } as ReportCell; const balanceCells = this._dateRanges!.map((k) => { const rawValue = al.valueMap?.get(k)?.balance ?? 0; let value = this.fyo.format(rawValue, 'Currency'); if (this.hideGroupAmounts && al.isGroup) { value = ''; } return { rawValue, value, align: 'right', width: ACC_BAL_WIDTH, } as ReportCell; }); return { cells: [nameCell, balanceCells].flat(), level: al.level, isGroup: !!al.isGroup, folded: false, foldedBelow: false, } as ReportRow; } async _getGroupedByDateRanges( map: GroupedMap ): Promise<AccountNameValueMapMap> { const accountValueMap: AccountNameValueMapMap = new Map(); if (!this.accountMap) { await this._setAndReturnAccountMap(); } for (const account of map.keys()) { const valueMap: ValueMap = new Map(); /** * Set Balance for every DateRange key */ for (const entry of map.get(account)!) { const key = this._getRangeMapKey(entry); if (key === null) { continue; } if (!this.accountMap?.[entry.account]) { await this._setAndReturnAccountMap(true); } const totalBalance = valueMap.get(key)?.balance ?? 0; const balance = (entry.debit ?? 0) - (entry.credit ?? 0); const rootType = this.accountMap![entry.account]?.rootType; if (isCredit(rootType)) { valueMap.set(key, { balance: totalBalance - balance }); } else { valueMap.set(key, { balance: totalBalance + balance }); } } accountValueMap.set(account, valueMap); } return accountValueMap; } async _getAccountTree(rangeGroupedMap: AccountNameValueMapMap) { const accountTree = cloneDeep( await this._setAndReturnAccountMap() ) as AccountTree; setPruneFlagOnAccountTreeNodes(accountTree); setValueMapOnAccountTreeNodes(accountTree, rangeGroupedMap); setChildrenOnAccountTreeNodes(accountTree); deleteNonRootAccountTreeNodes(accountTree); pruneAccountTree(accountTree); return accountTree; } async _setAndReturnAccountMap(force = false) { if (this.accountMap && !force) { return this.accountMap; } const accountList: Account[] = ( await this.fyo.db.getAllRaw('Account', { fields: ['name', 'rootType', 'isGroup', 'parentAccount'], }) ).map((rv) => ({ name: rv.name as string, rootType: rv.rootType as AccountRootType, isGroup: Boolean(rv.isGroup), parentAccount: rv.parentAccount as string | null, })); this.accountMap = getMapFromList(accountList, 'name'); return this.accountMap; } _getRangeMapKey(entry: LedgerEntry): DateRange | null { const entryDate = DateTime.fromISO( entry.date!.toISOString().split('T')[0] ).toMillis(); for (const dr of this._dateRanges!) { const toDate = dr.toDate.toMillis(); const fromDate = dr.fromDate.toMillis(); if (entryDate >= fromDate && entryDate < toDate) { return dr; } } return null; } // Fix arythmetic on dates when adding or substracting months. If the // reference date was the last day in month, ensure that the resulting date is // also the last day. _fixMonthsJump(refDate: DateTime, date: DateTime): DateTime { if (refDate.day == refDate.daysInMonth && date.day != date.daysInMonth) { return date.set({ day: date.daysInMonth }); } else { return date; } } async _getDateRanges(): Promise<DateRange[]> { const endpoints = await this._getFromAndToDates(); const fromDate = DateTime.fromISO(endpoints.fromDate); const toDate = DateTime.fromISO(endpoints.toDate); if (this.consolidateColumns) { return [ { toDate, fromDate, }, ]; } const months: number = monthsMap[this.periodicity]; const dateRanges: DateRange[] = [ { toDate, fromDate: this._fixMonthsJump(toDate, toDate.minus({ months })), }, ]; let count = this.count ?? 1; if (this.basedOn === 'Fiscal Year') { count = Math.ceil(((this.toYear! - this.fromYear!) * 12) / months); } for (let i = 1; i < count; i++) { const lastRange = dateRanges.at(-1)!; dateRanges.push({ toDate: lastRange.fromDate, fromDate: this._fixMonthsJump( toDate, lastRange.fromDate.minus({ months }) ), }); } return dateRanges.sort((b, a) => b.toDate.toMillis() - a.toDate.toMillis()); } async _getFromAndToDates() { let toDate: string; let fromDate: string; if (this.basedOn === 'Until Date') { toDate = DateTime.fromISO(this.toDate!).plus({ days: 1 }).toISODate(); const months = monthsMap[this.periodicity] * Math.max(this.count ?? 1, 1); fromDate = DateTime.fromISO(this.toDate!).minus({ months }).toISODate(); } else { const fy = await getFiscalEndpoints( this.toYear!, this.fromYear!, this.fyo ); toDate = DateTime.fromISO(fy.toDate).plus({ days: 1 }).toISODate(); fromDate = fy.fromDate; } return { fromDate, toDate }; } async _getQueryFilters(): Promise<QueryFilter> { const filters: QueryFilter = {}; const { fromDate, toDate } = await this._getFromAndToDates(); const dateFilter: string[] = []; dateFilter.push('<', toDate); dateFilter.push('>=', fromDate); filters.date = dateFilter; filters.reverted = false; return filters; } getFilters(): Field[] { const periodNameMap: Record<Periodicity, string> = { Monthly: t`Months`, Quarterly: t`Quarters`, 'Half Yearly': t`Half Years`, Yearly: t`Years`, }; const filters = [ { fieldtype: 'Select', options: [ { label: t`Fiscal Year`, value: 'Fiscal Year' }, { label: t`Until Date`, value: 'Until Date' }, ], label: t`Based On`, fieldname: 'basedOn', }, { fieldtype: 'Select', options: [ { label: t`Monthly`, value: 'Monthly' }, { label: t`Quarterly`, value: 'Quarterly' }, { label: t`Half Yearly`, value: 'Half Yearly' }, { label: t`Yearly`, value: 'Yearly' }, ], label: t`Periodicity`, fieldname: 'periodicity', }, , ] as Field[]; let dateFilters = [ { fieldtype: 'Int', fieldname: 'fromYear', placeholder: t`From Year`, label: t`From Year`, minvalue: 2000, required: true, }, { fieldtype: 'Int', fieldname: 'toYear', placeholder: t`To Year`, label: t`To Year`, minvalue: 2000, required: true, }, ] as Field[]; if (this.basedOn === 'Until Date') { dateFilters = [ { fieldtype: 'Date', fieldname: 'toDate', placeholder: t`To Date`, label: t`To Date`, required: true, }, { fieldtype: 'Int', fieldname: 'count', minvalue: 1, placeholder: t`Number of ${periodNameMap[this.periodicity]}`, label: t`Number of ${periodNameMap[this.periodicity]}`, required: true, }, ] as Field[]; } return [ filters, dateFilters, { fieldtype: 'Check', label: t`Consolidate Columns`, fieldname: 'consolidateColumns', } as Field, { fieldtype: 'Check', label: t`Hide Group Amounts`, fieldname: 'hideGroupAmounts', } as Field, ].flat(); } getColumns(): ColumnField[] { const columns = [ { label: t`Account`, fieldtype: 'Link', fieldname: 'account', align: 'left', width: ACC_NAME_WIDTH, }, ] as ColumnField[]; const dateColumns = this._dateRanges!.sort( (a, b) => b.toDate.toMillis() - a.toDate.toMillis() ).map((d) => { const toDate = d.toDate.minus({ days: 1 }); const label = this.fyo.format(toDate.toJSDate(), 'Date'); return { label, fieldtype: 'Data', fieldname: 'toDate', align: 'right', width: ACC_BAL_WIDTH, } as ColumnField; }); return [columns, dateColumns].flat(); } metaFilters: string[] = ['basedOn']; } export async function getFiscalEndpoints( toYear: number, fromYear: number, fyo: Fyo ) { const fys = (await fyo.getValue( ModelNameEnum.AccountingSettings, 'fiscalYearStart' )) as Date; const fye = (await fyo.getValue( ModelNameEnum.AccountingSettings, 'fiscalYearEnd' )) as Date; /** * Get the month and the day, and * prepend with the passed year. */ const fromDate = [ fromYear, (fys.getMonth() + 1).toString().padStart(2, '0'), fys.getDate().toString().padStart(2, '0'), ].join('-'); const toDate = [ toYear, (fye.getMonth() + 1).toString().padStart(2, '0'), fye.getDate().toString().padStart(2, '0'), ].join('-'); return { fromDate, toDate }; } const monthsMap: Record<Periodicity, number> = { Monthly: 1, Quarterly: 3, 'Half Yearly': 6, Yearly: 12, }; function setPruneFlagOnAccountTreeNodes(accountTree: AccountTree) { for (const account of Object.values(accountTree)) { account.prune = true; } } function setValueMapOnAccountTreeNodes( accountTree: AccountTree, rangeGroupedMap: AccountNameValueMapMap ) { for (const name of rangeGroupedMap.keys()) { if (!accountTree[name]) { continue; } const valueMap = rangeGroupedMap.get(name)!; accountTree[name].valueMap = valueMap; accountTree[name].prune = false; /** * Set the update the parent account values recursively * also prevent pruning of the parent accounts. */ let parentAccountName: string | null = accountTree[name].parentAccount; while (parentAccountName !== null) { parentAccountName = updateParentAccountWithChildValues( accountTree, parentAccountName, valueMap ); } } } function updateParentAccountWithChildValues( accountTree: AccountTree, parentAccountName: string, valueMap: ValueMap ): string { const parentAccount = accountTree[parentAccountName]; parentAccount.prune = false; parentAccount.valueMap ??= new Map(); for (const key of valueMap.keys()) { const value = parentAccount.valueMap.get(key); const childValue = valueMap.get(key); const map: Record<string, number> = {}; for (const key of Object.keys(childValue!)) { map[key] = (value?.[key] ?? 0) + (childValue?.[key] ?? 0); } parentAccount.valueMap.set(key, map); } return parentAccount.parentAccount!; } function setChildrenOnAccountTreeNodes(accountTree: AccountTree) { const parentNodes: Set<string> = new Set(); for (const name of Object.keys(accountTree)) { const ac = accountTree[name]; if (!ac.parentAccount) { continue; } accountTree[ac.parentAccount].children ??= []; accountTree[ac.parentAccount].children!.push(ac); parentNodes.add(ac.parentAccount); } } function deleteNonRootAccountTreeNodes(accountTree: AccountTree) { for (const name of Object.keys(accountTree)) { const ac = accountTree[name]; if (!ac.parentAccount) { continue; } delete accountTree[name]; } } function pruneAccountTree(accountTree: AccountTree) { for (const root of Object.keys(accountTree)) { if (accountTree[root].prune) { delete accountTree[root]; } } for (const root of Object.keys(accountTree)) { accountTree[root].children = getPrunedChildren( accountTree[root].children ?? [] ); } } function getPrunedChildren(children: AccountTreeNode[]): AccountTreeNode[] { return children.filter((child) => { if (child.children?.length) { child.children = getPrunedChildren(child.children); } return !child.prune; }); } export function convertAccountRootNodesToAccountList( rootNodes: AccountTreeNode[] ): AccountList { if (!rootNodes || rootNodes.length == 0) { return []; } const accountList: AccountList = []; for (const rootNode of rootNodes) { pushToAccountList(rootNode, accountList, 0); } return accountList; } function pushToAccountList( accountTreeNode: AccountTreeNode, accountList: AccountList, level: number ) { accountList.push({ name: accountTreeNode.name, rootType: accountTreeNode.rootType, isGroup: accountTreeNode.isGroup, parentAccount: accountTreeNode.parentAccount, valueMap: accountTreeNode.valueMap, level, }); const children = accountTreeNode.children ?? []; const childLevel = level + 1; for (const childNode of children) { pushToAccountList(childNode, accountList, childLevel); } } function getListOfLeafNodes(tree: Tree): TreeNode[] { const nonGroupChildren: TreeNode[] = []; for (const node of Object.values(tree)) { if (!node) { continue; } const groupChildren = node.children ?? []; while (groupChildren.length) { const child = groupChildren.shift()!; if (!child?.children?.length) { nonGroupChildren.push(child); continue; } groupChildren.unshift(...(child.children ?? [])); } } return nonGroupChildren; }
2302_79757062/books
reports/AccountReport.ts
TypeScript
agpl-3.0
16,677
import { t } from 'fyo'; import { AccountRootType, AccountRootTypeEnum, } from 'models/baseModels/Account/types'; import { AccountReport, convertAccountRootNodesToAccountList, } from 'reports/AccountReport'; import { ReportData, RootTypeRow } from 'reports/types'; import { getMapFromList } from 'utils'; export class BalanceSheet extends AccountReport { static title = t`Balance Sheet`; static reportName = 'balance-sheet'; loading = false; get rootTypes(): AccountRootType[] { return [ AccountRootTypeEnum.Asset, AccountRootTypeEnum.Liability, AccountRootTypeEnum.Equity, ]; } async setReportData(filter?: string, force?: boolean) { this.loading = true; if (force || filter !== 'hideGroupAmounts') { await this._setRawData(); } const map = this._getGroupedMap(true, 'account'); const rangeGroupedMap = await this._getGroupedByDateRanges(map); const accountTree = await this._getAccountTree(rangeGroupedMap); for (const name of Object.keys(accountTree)) { const { rootType } = accountTree[name]; if (this.rootTypes.includes(rootType)) { continue; } delete accountTree[name]; } const rootTypeRows: RootTypeRow[] = this.rootTypes .map((rootType) => { const rootNodes = this.getRootNodes(rootType, accountTree)!; const rootList = convertAccountRootNodesToAccountList(rootNodes); return { rootType, rootNodes, rows: this.getReportRowsFromAccountList(rootList), }; }) .filter((row) => !!row.rootNodes.length); this.reportData = this.getReportDataFromRows( getMapFromList(rootTypeRows, 'rootType') ); this.loading = false; } getReportDataFromRows( rootTypeRows: Record<AccountRootType, RootTypeRow | undefined> ): ReportData { const typeNameList = [ { rootType: AccountRootTypeEnum.Asset, totalName: t`Total Asset (Debit)`, }, { rootType: AccountRootTypeEnum.Liability, totalName: t`Total Liability (Credit)`, }, { rootType: AccountRootTypeEnum.Equity, totalName: t`Total Equity (Credit)`, }, ]; const reportData: ReportData = []; const emptyRow = this.getEmptyRow(); for (const { rootType, totalName } of typeNameList) { const row = rootTypeRows[rootType]; if (!row) { continue; } reportData.push(...row.rows); if (row.rootNodes.length) { const totalNode = this.getTotalNode(row.rootNodes, totalName); const totalRow = this.getRowFromAccountListNode(totalNode); reportData.push(totalRow); } reportData.push(emptyRow); } if (reportData.at(-1)?.isEmpty) { reportData.pop(); } return reportData; } }
2302_79757062/books
reports/BalanceSheet/BalanceSheet.ts
TypeScript
agpl-3.0
2,838
import { Fyo, t } from 'fyo'; import { DateTime } from 'luxon'; import { ModelNameEnum } from 'models/types'; import { LedgerReport } from 'reports/LedgerReport'; import { ColumnField, GroupedMap, LedgerEntry, ReportData, ReportRow, } from 'reports/types'; import { Field, FieldTypeEnum } from 'schemas/types'; import { QueryFilter } from 'utils/db/types'; type ReferenceType = | ModelNameEnum.SalesInvoice | ModelNameEnum.PurchaseInvoice | ModelNameEnum.Payment | ModelNameEnum.JournalEntry | ModelNameEnum.Shipment | ModelNameEnum.PurchaseReceipt | 'All'; export class GeneralLedger extends LedgerReport { static title = t`General Ledger`; static reportName = 'general-ledger'; usePagination = true; loading = false; ascending = false; reverted = false; referenceType: ReferenceType = 'All'; groupBy: 'none' | 'party' | 'account' | 'referenceName' = 'none'; _rawData: LedgerEntry[] = []; constructor(fyo: Fyo) { super(fyo); } setDefaultFilters() { if (!this.toDate) { this.toDate = DateTime.now().plus({ days: 1 }).toISODate(); this.fromDate = DateTime.now().minus({ years: 1 }).toISODate(); } } async setReportData(filter?: string, force?: boolean) { this.loading = true; let sort = true; if (force || filter !== 'grouped' || this._rawData.length === 0) { await this._setRawData(); sort = false; } const map = this._getGroupedMap(sort); this._setIndexOnEntries(map); const { totalDebit, totalCredit } = this._getTotalsAndSetBalance(map); const consolidated = this._consolidateEntries(map); /** * Push a blank row if last row isn't blank */ if (consolidated.at(-1)?.name !== -3) { this._pushBlankEntry(consolidated); } /** * Set the closing row */ consolidated.push({ name: -2, // Bold account: t`Closing`, date: null, debit: totalDebit, credit: totalCredit, balance: totalDebit - totalCredit, referenceType: '', referenceName: '', party: '', reverted: false, reverts: '', }); this.reportData = this._convertEntriesToReportData(consolidated); this.loading = false; } _setIndexOnEntries(map: GroupedMap) { let i = 1; for (const key of map.keys()) { for (const entry of map.get(key)!) { entry.index = String(i); i = i + 1; } } } _convertEntriesToReportData(entries: LedgerEntry[]): ReportData { const reportData = []; for (const entry of entries) { const row = this._getRowFromEntry(entry, this.columns); reportData.push(row); } return reportData; } _getRowFromEntry(entry: LedgerEntry, columns: ColumnField[]): ReportRow { if (entry.name === -3) { return { isEmpty: true, cells: columns.map((c) => ({ rawValue: '', value: '', width: c.width ?? 1, })), }; } const row: ReportRow = { cells: [] }; for (const col of columns) { const align = col.align ?? 'left'; const width = col.width ?? 1; const fieldname = col.fieldname; let value = entry[fieldname as keyof LedgerEntry]; const rawValue = value; if (value === null || value === undefined) { value = ''; } if (value instanceof Date) { value = this.fyo.format(value, FieldTypeEnum.Date); } if (typeof value === 'number' && fieldname !== 'index') { value = this.fyo.format(value, FieldTypeEnum.Currency); } if (typeof value === 'boolean' && fieldname === 'reverted') { value = value ? t`Reverted` : ''; } else { value = String(value); } if (fieldname === 'referenceType') { value = this.fyo.schemaMap[value]?.label ?? value; } row.cells.push({ italics: entry.name === -1, bold: entry.name === -2, value, rawValue, align, width, }); } return row; } _consolidateEntries(map: GroupedMap) { const entries: LedgerEntry[] = []; for (const key of map.keys()) { entries.push(...map.get(key)!); /** * Add blank row for spacing if groupBy */ if (this.groupBy !== 'none') { this._pushBlankEntry(entries); } } return entries; } _pushBlankEntry(entries: LedgerEntry[]) { entries.push({ name: -3, // Empty account: '', date: null, debit: null, credit: null, balance: null, referenceType: '', referenceName: '', party: '', reverted: false, reverts: '', }); } _getTotalsAndSetBalance(map: GroupedMap) { let totalDebit = 0; let totalCredit = 0; for (const key of map.keys()) { let balance = 0; let debit = 0; let credit = 0; for (const entry of map.get(key)!) { debit += entry.debit!; credit += entry.credit!; const diff = entry.debit! - entry.credit!; balance += diff; entry.balance = balance; } /** * Total row incase groupBy is used */ if (this.groupBy !== 'none') { map.get(key)?.push({ name: -1, // Italics account: t`Total`, date: null, debit, credit, balance: debit - credit, referenceType: '', referenceName: '', party: '', reverted: false, reverts: '', }); } /** * Total debit and credit for the final row */ totalDebit += debit; totalCredit += credit; } return { totalDebit, totalCredit }; } _getQueryFilters(): QueryFilter { const filters: QueryFilter = {}; const stringFilters = ['account', 'party', 'referenceName']; for (const sf of stringFilters) { const value = this[sf]; if (value === undefined) { continue; } filters[sf] = value as string; } if (this.referenceType !== 'All') { filters.referenceType = this.referenceType as string; } if (this.toDate) { filters.date ??= []; (filters.date as string[]).push('<=', this.toDate as string); } if (this.fromDate) { filters.date ??= []; (filters.date as string[]).push('>=', this.fromDate as string); } if (!this.reverted) { filters.reverted = false; } return filters; } getFilters() { const refTypeOptions = [ { label: t`All`, value: 'All' }, { label: t`Sales Invoices`, value: 'SalesInvoice' }, { label: t`Purchase Invoices`, value: 'PurchaseInvoice' }, { label: t`Payments`, value: 'Payment' }, { label: t`Journal Entries`, value: 'JournalEntry' }, ]; if (!this.fyo.singles.AccountingSettings?.enableInventory) { refTypeOptions.push( { label: t`Shipment`, value: 'Shipment' }, { label: t`Purchase Receipt`, value: 'PurchaseReceipt' } ); } return [ { fieldtype: 'Select', options: refTypeOptions, label: t`Ref Type`, fieldname: 'referenceType', placeholder: t`Ref Type`, }, { fieldtype: 'DynamicLink', label: t`Ref. Name`, references: 'referenceType', placeholder: t`Ref Name`, emptyMessage: t`Change Ref Type`, fieldname: 'referenceName', }, { fieldtype: 'Link', target: 'Account', placeholder: t`Account`, label: t`Account`, fieldname: 'account', }, { fieldtype: 'Link', target: 'Party', label: t`Party`, placeholder: t`Party`, fieldname: 'party', }, { fieldtype: 'Date', placeholder: t`From Date`, label: t`From Date`, fieldname: 'fromDate', }, { fieldtype: 'Date', placeholder: t`To Date`, label: t`To Date`, fieldname: 'toDate', }, { fieldtype: 'Select', label: t`Group By`, fieldname: 'groupBy', options: [ { label: t`None`, value: 'none' }, { label: t`Party`, value: 'party' }, { label: t`Account`, value: 'account' }, { label: t`Reference`, value: 'referenceName' }, ], }, { fieldtype: 'Check', label: t`Include Cancelled`, fieldname: 'reverted', }, { fieldtype: 'Check', label: t`Ascending Order`, fieldname: 'ascending', }, ] as Field[]; } getColumns(): ColumnField[] { let columns = [ { label: '#', fieldtype: 'Int', fieldname: 'index', align: 'right', width: 0.5, }, { label: t`Account`, fieldtype: 'Link', fieldname: 'account', width: 1.5, }, { label: t`Date`, fieldtype: 'Date', fieldname: 'date', }, { label: t`Debit`, fieldtype: 'Currency', fieldname: 'debit', align: 'right', width: 1.25, }, { label: t`Credit`, fieldtype: 'Currency', fieldname: 'credit', align: 'right', width: 1.25, }, { label: t`Balance`, fieldtype: 'Currency', fieldname: 'balance', align: 'right', width: 1.25, }, { label: t`Party`, fieldtype: 'Link', fieldname: 'party', }, { label: t`Ref Name`, fieldtype: 'Data', fieldname: 'referenceName', }, { label: t`Ref Type`, fieldtype: 'Data', fieldname: 'referenceType', }, { label: t`Reverted`, fieldtype: 'Check', fieldname: 'reverted', }, ] as ColumnField[]; if (!this.reverted) { columns = columns.filter((f) => f.fieldname !== 'reverted'); } return columns; } }
2302_79757062/books
reports/GeneralLedger/GeneralLedger.ts
TypeScript
agpl-3.0
10,031
import { t } from 'fyo'; import { Action } from 'fyo/model/types'; import { DateTime } from 'luxon'; import { Invoice } from 'models/baseModels/Invoice/Invoice'; import { Party } from 'models/regionalModels/in/Party'; import { ModelNameEnum } from 'models/types'; import { codeStateMap } from 'regional/in'; import { Report } from 'reports/Report'; import { ColumnField, ReportData, ReportRow } from 'reports/types'; import { Field, OptionField } from 'schemas/types'; import { isNumeric } from 'src/utils'; import getGSTRExportActions from './gstExporter'; import { GSTRRow, GSTRType, TransferType, TransferTypeEnum } from './types'; export abstract class BaseGSTR extends Report { place?: string; toDate?: string; fromDate?: string; transferType?: TransferType; usePagination = true; gstrRows?: GSTRRow[]; loading = false; abstract gstrType: GSTRType; get transferTypeMap(): Record<string, string> { if (this.gstrType === 'GSTR-2') { return { B2B: 'B2B', }; } return { B2B: 'B2B', B2CL: 'B2C-Large', B2CS: 'B2C-Small', NR: 'Nil Rated, Exempted and Non GST supplies', }; } get schemaName() { if (this.gstrType === 'GSTR-1') { return ModelNameEnum.SalesInvoice; } return ModelNameEnum.PurchaseInvoice; } async setReportData(): Promise<void> { this.loading = true; const gstrRows = await this.getGstrRows(); const filteredRows = this.filterGstrRows(gstrRows); this.gstrRows = filteredRows; this.reportData = this.getReportDataFromGSTRRows(filteredRows); this.loading = false; } getReportDataFromGSTRRows(gstrRows: GSTRRow[]): ReportData { const reportData: ReportData = []; for (const row of gstrRows) { const reportRow: ReportRow = { cells: [] }; for (const { fieldname, fieldtype, width } of this.columns) { const align = isNumeric(fieldtype) ? 'right' : 'left'; const rawValue = row[fieldname as keyof GSTRRow]; let value = ''; if (rawValue !== undefined) { value = this.fyo.format(rawValue, fieldtype); } reportRow.cells.push({ align, rawValue, value, width: width ?? 1, }); } reportData.push(reportRow); } return reportData; } filterGstrRows(gstrRows: GSTRRow[]) { return gstrRows.filter((row) => { let allow = true; if (this.place) { allow &&= codeStateMap[this.place] === row.place; } this.place; return (allow &&= this.transferFilterFunction(row)); }); } get transferFilterFunction(): (row: GSTRRow) => boolean { if (this.transferType === 'B2B') { return (row) => !!row.gstin; } if (this.transferType === 'B2CL') { return (row) => !row.gstin && !row.inState && row.invAmt >= 250000; } if (this.transferType === 'B2CS') { return (row) => !row.gstin && (row.inState || row.invAmt < 250000); } if (this.transferType === 'NR') { return (row) => row.rate === 0; // this takes care of both nil rated, exempted goods } return () => true; } async getEntries() { const date: string[] = []; if (this.toDate) { date.push('<=', this.toDate); } if (this.fromDate) { date.push('>=', this.fromDate); } return (await this.fyo.db.getAllRaw(this.schemaName, { filters: { date, submitted: true, cancelled: false }, })) as { name: string }[]; } async getGstrRows(): Promise<GSTRRow[]> { const entries = await this.getEntries(); const gstrRows: GSTRRow[] = []; for (const entry of entries) { const gstrRow = await this.getGstrRow(entry.name); gstrRows.push(gstrRow); } return gstrRows; } async getGstrRow(entryName: string): Promise<GSTRRow> { const entry = (await this.fyo.doc.getDoc( this.schemaName, entryName )) as Invoice; const gstin = (await this.fyo.getValue( ModelNameEnum.AccountingSettings, 'gstin' )) as string | null; const party = (await this.fyo.doc.getDoc('Party', entry.party)) as Party; let place = ''; if (party.address) { const pos = (await this.fyo.getValue( ModelNameEnum.Address, party.address as string, 'pos' )) as string | undefined; place = pos ?? ''; } else if (party.gstin) { const code = party.gstin.slice(0, 2); place = codeStateMap[code] ?? ''; } let inState = false; if (gstin) { inState = codeStateMap[gstin.slice(0, 2)] === place; } const gstrRow: GSTRRow = { gstin: party.gstin ?? '', partyName: entry.party!, invNo: entry.name!, invDate: entry.date!, rate: 0, reverseCharge: !party.gstin ? 'Y' : 'N', inState, place, invAmt: entry.grandTotal?.float ?? 0, taxVal: entry.netTotal?.float ?? 0, }; for (const tax of entry.taxes ?? []) { gstrRow.rate += tax.rate ?? 0; } this.setTaxValuesOnGSTRRow(entry, gstrRow); return gstrRow; } setTaxValuesOnGSTRRow(entry: Invoice, gstrRow: GSTRRow) { for (const tax of entry.taxes ?? []) { const rate = tax.rate ?? 0; gstrRow.rate += rate; const taxAmt = entry.netTotal!.percent(rate).float; switch (tax.account) { case 'IGST': { gstrRow.igstAmt = taxAmt; gstrRow.inState = false; } case 'CGST': gstrRow.cgstAmt = taxAmt; case 'SGST': gstrRow.sgstAmt = taxAmt; case 'Nil Rated': gstrRow.nilRated = true; case 'Exempt': gstrRow.exempt = true; case 'Non GST': gstrRow.nonGST = true; } } } setDefaultFilters() { if (!this.toDate) { this.toDate = DateTime.local().toISODate(); } if (!this.fromDate) { this.fromDate = DateTime.local().minus({ months: 3 }).toISODate(); } if (!this.transferType) { this.transferType = 'B2B'; } } getFilters(): Field[] { const transferTypeMap = this.transferTypeMap; const options = Object.keys(transferTypeMap).map((k) => ({ value: k, label: transferTypeMap[k], })); return [ { fieldtype: 'Select', label: t`Transfer Type`, placeholder: t`Transfer Type`, fieldname: 'transferType', options, } as OptionField, { fieldtype: 'AutoComplete', label: t`Place`, placeholder: t`Place`, fieldname: 'place', options: Object.keys(codeStateMap).map((code) => { return { value: code, label: codeStateMap[code], }; }), } as OptionField, { fieldtype: 'Date', label: t`From Date`, placeholder: t`From Date`, fieldname: 'fromDate', }, { fieldtype: 'Date', label: t`To Date`, placeholder: t`To Date`, fieldname: 'toDate', }, ]; } getColumns(): ColumnField[] | Promise<ColumnField[]> { const columns = [ { label: t`Party`, fieldtype: 'Data', fieldname: 'partyName', width: 1.5, }, { label: t`Invoice No.`, fieldname: 'invNo', fieldtype: 'Data', }, { label: t`Invoice Value`, fieldname: 'invAmt', fieldtype: 'Currency', }, { label: t`Invoice Date`, fieldname: 'invDate', fieldtype: 'Date', }, { label: t`Place of supply`, fieldname: 'place', fieldtype: 'Data', }, { label: t`Rate`, fieldname: 'rate', width: 0.5, }, { label: t`Taxable Value`, fieldname: 'taxVal', fieldtype: 'Currency', }, { label: t`Reverse Chrg.`, fieldname: 'reverseCharge', fieldtype: 'Data', }, { label: t`Intergrated Tax`, fieldname: 'igstAmt', fieldtype: 'Currency', }, { label: t`Central Tax`, fieldname: 'cgstAmt', fieldtype: 'Currency', }, { label: t`State Tax`, fieldname: 'sgstAmt', fieldtype: 'Currency', }, ] as ColumnField[]; const transferType = this.transferType ?? TransferTypeEnum.B2B; if (transferType === TransferTypeEnum.B2B) { columns.unshift({ label: t`GSTIN No.`, fieldname: 'gstin', fieldtype: 'Data', width: 1.5, }); } return columns; } getActions(): Action[] { return getGSTRExportActions(this); } }
2302_79757062/books
reports/GoodsAndServiceTax/BaseGSTR.ts
TypeScript
agpl-3.0
8,686
import { BaseGSTR } from './BaseGSTR'; import { GSTRType } from './types'; export class GSTR1 extends BaseGSTR { static title = 'GSTR1'; static reportName = 'gstr-1'; gstrType: GSTRType = 'GSTR-1'; }
2302_79757062/books
reports/GoodsAndServiceTax/GSTR1.ts
TypeScript
agpl-3.0
208
import { BaseGSTR } from './BaseGSTR'; import { GSTRType } from './types'; export class GSTR2 extends BaseGSTR { static title = 'GSTR2'; static reportName = 'gstr-2'; gstrType: GSTRType = 'GSTR-2'; }
2302_79757062/books
reports/GoodsAndServiceTax/GSTR2.ts
TypeScript
agpl-3.0
208
import { Action } from 'fyo/model/types'; import { Verb } from 'fyo/telemetry/types'; import { DateTime } from 'luxon'; import { ModelNameEnum } from 'models/types'; import { codeStateMap } from 'regional/in'; import { ExportExtention } from 'reports/types'; import { showDialog } from 'src/utils/interactive'; import { invertMap } from 'utils'; import { getCsvData, saveExportData } from '../commonExporter'; import { BaseGSTR } from './BaseGSTR'; import { TransferTypeEnum } from './types'; import { getSavePath } from 'src/utils/ui'; const GST = { 'GST-0': 0, 'GST-0.25': 0.25, 'GST-3': 3, 'GST-5': 5, 'GST-6': 6, 'GST-12': 12, 'GST-18': 18, 'GST-28': 28, 'IGST-0': 0, 'IGST-0.25': 0.25, 'IGST-3': 3, 'IGST-5': 5, 'IGST-6': 6, 'IGST-12': 12, 'IGST-18': 18, 'IGST-28': 28, } as Record<string, number>; const CSGST = { 'GST-0': 0, 'GST-0.25': 0.125, 'GST-3': 1.5, 'GST-5': 2.5, 'GST-6': 3, 'GST-12': 6, 'GST-18': 9, 'GST-28': 14, } as Record<string, number>; const IGST = { 'IGST-0.25': 0.25, 'IGST-3': 3, 'IGST-5': 5, 'IGST-6': 6, 'IGST-12': 12, 'IGST-18': 18, 'IGST-28': 28, } as Record<string, number>; interface GSTData { version: string; hash: string; gstin: string; fp: string; b2b?: B2BCustomer[]; b2cl?: B2CLStateInvoiceRecord[]; b2cs?: B2CSInvRecord[]; } interface B2BCustomer { ctin: string; inv: B2BInvRecord[]; } interface B2BInvRecord { inum: string; idt: string; val: number; pos: string; rchrg: 'Y' | 'N'; inv_typ: string; itms: B2BItmRecord[]; } interface B2BItmRecord { num: number; itm_det: { txval: number; rt: number; csamt: number; camt: number; samt: number; iamt: number; }; } interface B2CLInvRecord { inum: string; idt: string; val: number; itms: B2CLItmRecord[]; } interface B2CLItmRecord { num: number; itm_det: { txval: number; rt: number; csamt: 0; iamt: number; }; } interface B2CLStateInvoiceRecord { pos: string; inv: B2CLInvRecord[]; } interface B2CSInvRecord { sply_ty: 'INTRA' | 'INTER'; pos: string; typ: 'OE'; // "OE" - Errors and omissions excepted. txval: number; rt: number; iamt: number; camt: number; samt: number; csamt: number; } export default function getGSTRExportActions(report: BaseGSTR): Action[] { const exportExtention = ['csv', 'json'] as ExportExtention[]; return exportExtention.map((ext) => ({ group: `Export`, label: ext.toUpperCase(), type: 'primary', action: async () => { await exportReport(ext, report); }, })); } async function exportReport(extention: ExportExtention, report: BaseGSTR) { const canExport = await getCanExport(report); if (!canExport) { return; } const { filePath, canceled } = await getSavePath( report.reportName, extention ); if (canceled || !filePath) { return; } let data = ''; if (extention === 'csv') { data = getCsvData(report); } else if (extention === 'json') { data = await getGstrJsonData(report); } if (!data.length) { return; } await saveExportData(data, filePath); report.fyo.telemetry.log(Verb.Exported, report.reportName, { extention }); } async function getCanExport(report: BaseGSTR) { const gstin = await report.fyo.getValue( ModelNameEnum.AccountingSettings, 'gstin' ); if (gstin) { return true; } await showDialog({ title: report.fyo.t`Cannot Export`, detail: report.fyo.t`Please set GSTIN in General Settings.`, type: 'error', }); return false; } export async function getGstrJsonData(report: BaseGSTR): Promise<string> { const toDate = report.toDate!; const transferType = report.transferType!; const gstin = await report.fyo.getValue( ModelNameEnum.AccountingSettings, 'gstin' ); const gstData: GSTData = { version: 'GST3.0.4', hash: 'hash', gstin: gstin as string, fp: DateTime.fromISO(toDate).toFormat('MMyyyy'), }; if (transferType === TransferTypeEnum.B2B) { gstData.b2b = await generateB2bData(report); } else if (transferType === TransferTypeEnum.B2CL) { gstData.b2cl = await generateB2clData(report); } else if (transferType === TransferTypeEnum.B2CS) { gstData.b2cs = generateB2csData(report); } return JSON.stringify(gstData); } async function generateB2bData(report: BaseGSTR): Promise<B2BCustomer[]> { const fyo = report.fyo; const b2b: B2BCustomer[] = []; const schemaName = report.gstrType === 'GSTR-1' ? ModelNameEnum.SalesInvoiceItem : ModelNameEnum.PurchaseInvoiceItem; const parentSchemaName = report.gstrType === 'GSTR-1' ? ModelNameEnum.SalesInvoice : ModelNameEnum.PurchaseInvoice; for (const row of report.gstrRows ?? []) { const invRecord: B2BInvRecord = { inum: row.invNo, idt: DateTime.fromJSDate(row.invDate).toFormat('dd-MM-yyyy'), val: row.invAmt, pos: row.gstin && row.gstin.substring(0, 2), rchrg: row.reverseCharge, inv_typ: 'R', itms: [], }; const exchangeRate = ( await fyo.db.getAllRaw(parentSchemaName, { fields: ['exchangeRate'], filters: { name: invRecord.inum }, }) )[0].exchangeRate as number; const items = await fyo.db.getAllRaw(schemaName, { fields: ['amount', 'tax', 'hsnCode'], filters: { parent: invRecord.inum }, }); items.forEach((item) => { const hsnCode = item.hsnCode as number; const tax = item.tax as string; const baseAmount = fyo .pesa((item.amount as string) ?? 0) .mul(exchangeRate); const itemRecord: B2BItmRecord = { num: hsnCode, itm_det: { txval: baseAmount.float, rt: GST[tax], csamt: 0, camt: fyo .pesa(CSGST[tax] ?? 0) .mul(baseAmount) .div(100).float, samt: fyo .pesa(CSGST[tax] ?? 0) .mul(baseAmount) .div(100).float, iamt: fyo .pesa(IGST[tax] ?? 0) .mul(baseAmount) .div(100).float, }, }; invRecord.itms.push(itemRecord); }); const customerRecord = b2b.find((b) => b.ctin === row.gstin); const customer = { ctin: row.gstin, inv: [], } as B2BCustomer; if (customerRecord) { customerRecord.inv.push(invRecord); } else { customer.inv.push(invRecord); b2b.push(customer); } } return b2b; } async function generateB2clData( report: BaseGSTR ): Promise<B2CLStateInvoiceRecord[]> { const fyo = report.fyo; const b2cl: B2CLStateInvoiceRecord[] = []; const stateCodeMap = invertMap(codeStateMap); const schemaName = report.gstrType === 'GSTR-1' ? ModelNameEnum.SalesInvoiceItem : ModelNameEnum.PurchaseInvoiceItem; const parentSchemaName = report.gstrType === 'GSTR-1' ? ModelNameEnum.SalesInvoice : ModelNameEnum.PurchaseInvoice; for (const row of report.gstrRows ?? []) { const invRecord: B2CLInvRecord = { inum: row.invNo, idt: DateTime.fromJSDate(row.invDate).toFormat('dd-MM-yyyy'), val: row.invAmt, itms: [], }; const exchangeRate = ( await fyo.db.getAllRaw(parentSchemaName, { fields: ['exchangeRate'], filters: { name: invRecord.inum }, }) )[0].exchangeRate as number; const items = await fyo.db.getAllRaw(schemaName, { fields: ['amount', 'tax', 'hsnCode'], filters: { parent: invRecord.inum }, }); items.forEach((item) => { const hsnCode = item.hsnCode as number; const tax = item.tax as string; const baseAmount = fyo .pesa((item.amount as string) ?? 0) .mul(exchangeRate); const itemRecord: B2CLItmRecord = { num: hsnCode, itm_det: { txval: baseAmount.float, rt: GST[tax] ?? 0, csamt: 0, iamt: fyo .pesa(row.rate ?? 0) .mul(baseAmount) .div(100).float, }, }; invRecord.itms.push(itemRecord); }); const stateRecord = b2cl.find((b) => b.pos === stateCodeMap[row.place]); const stateInvoiceRecord: B2CLStateInvoiceRecord = { pos: stateCodeMap[row.place], inv: [], }; if (stateRecord) { stateRecord.inv.push(invRecord); } else { stateInvoiceRecord.inv.push(invRecord); b2cl.push(stateInvoiceRecord); } } return b2cl; } function generateB2csData(report: BaseGSTR): B2CSInvRecord[] { const stateCodeMap = invertMap(codeStateMap); const b2cs: B2CSInvRecord[] = []; for (const row of report.gstrRows ?? []) { const invRecord: B2CSInvRecord = { sply_ty: row.inState ? 'INTRA' : 'INTER', pos: stateCodeMap[row.place], typ: 'OE', txval: row.taxVal, rt: row.rate, iamt: !row.inState ? (row.taxVal * row.rate) / 100 : 0, camt: row.inState ? row.cgstAmt ?? 0 : 0, samt: row.inState ? row.sgstAmt ?? 0 : 0, csamt: 0, }; b2cs.push(invRecord); } return b2cs; }
2302_79757062/books
reports/GoodsAndServiceTax/gstExporter.ts
TypeScript
agpl-3.0
9,119
export enum TransferTypeEnum { 'B2B' = 'B2B', 'B2CL' = 'B2CL', 'B2CS' = 'B2CS', 'NR' = 'NR', } export type TransferType = keyof typeof TransferTypeEnum; export type GSTRType = 'GSTR-1' | 'GSTR-2'; export interface GSTRRow { gstin: string; partyName: string; invNo: string; invDate: Date; rate: number; reverseCharge: 'Y' | 'N'; inState: boolean; place: string; invAmt: number; taxVal: number; igstAmt?: number; cgstAmt?: number; sgstAmt?: number; exempt?: boolean; nonGST?: boolean; nilRated?: boolean; }
2302_79757062/books
reports/GoodsAndServiceTax/types.ts
TypeScript
agpl-3.0
546
import { Fyo, t } from 'fyo'; import { Action } from 'fyo/model/types'; import { ModelNameEnum } from 'models/types'; import { Report } from 'reports/Report'; import { GroupedMap, LedgerEntry, RawLedgerEntry } from 'reports/types'; import { QueryFilter } from 'utils/db/types'; import { safeParseFloat, safeParseInt } from 'utils/index'; import getCommonExportActions from './commonExporter'; type GroupByKey = 'account' | 'party' | 'referenceName'; export abstract class LedgerReport extends Report { static title = t`General Ledger`; static reportName = 'general-ledger'; _rawData: LedgerEntry[] = []; shouldRefresh = false; constructor(fyo: Fyo) { super(fyo); this._setObservers(); } _setObservers() { const listener = () => (this.shouldRefresh = true); this.fyo.doc.observer.on( `sync:${ModelNameEnum.AccountingLedgerEntry}`, listener ); this.fyo.doc.observer.on( `delete:${ModelNameEnum.AccountingLedgerEntry}`, listener ); } _getGroupByKey() { let groupBy: GroupByKey = 'referenceName'; if (this.groupBy && this.groupBy !== 'none') { groupBy = this.groupBy as GroupByKey; } return groupBy; } _getGroupedMap(sort: boolean, groupBy?: GroupByKey): GroupedMap { groupBy ??= this._getGroupByKey(); /** * Sort rows by ascending or descending */ if (sort) { this._rawData.sort((a, b) => { if (this.ascending) { return +a.date! - +b.date!; } return +b.date! - +a.date!; }); } /** * Map remembers the order of insertion * ∴ presorting maintains grouping order */ const map: GroupedMap = new Map(); for (const entry of this._rawData) { const groupingKey = entry[groupBy]; if (!map.has(groupingKey)) { map.set(groupingKey, []); } map.get(groupingKey)!.push(entry); } return map; } async _setRawData() { const fields = [ 'name', 'account', 'date', 'debit', 'credit', 'referenceType', 'referenceName', 'party', 'reverted', 'reverts', ]; const filters = await this._getQueryFilters(); const entries = (await this.fyo.db.getAllRaw( ModelNameEnum.AccountingLedgerEntry, { fields, filters, orderBy: ['date', 'created'], order: this.ascending ? 'asc' : 'desc', } )) as RawLedgerEntry[]; this._rawData = entries.map((entry) => { return { name: safeParseInt(entry.name), account: entry.account, date: new Date(entry.date), debit: Math.abs(safeParseFloat(entry.debit)), credit: Math.abs(safeParseFloat(entry.credit)), balance: 0, referenceType: entry.referenceType, referenceName: entry.referenceName, party: entry.party, reverted: Boolean(entry.reverted), reverts: entry.reverts, } as LedgerEntry; }); } abstract _getQueryFilters(): QueryFilter | Promise<QueryFilter>; getActions(): Action[] { return getCommonExportActions(this); } }
2302_79757062/books
reports/LedgerReport.ts
TypeScript
agpl-3.0
3,130
import { t } from 'fyo'; import { AccountRootType, AccountRootTypeEnum, } from 'models/baseModels/Account/types'; import { AccountReport, convertAccountRootNodesToAccountList, } from 'reports/AccountReport'; import { AccountListNode, AccountTreeNode, ReportData, ValueMap, } from 'reports/types'; export class ProfitAndLoss extends AccountReport { static title = t`Profit And Loss`; static reportName = 'profit-and-loss'; loading = false; get rootTypes(): AccountRootType[] { return [AccountRootTypeEnum.Income, AccountRootTypeEnum.Expense]; } async setReportData(filter?: string, force?: boolean) { this.loading = true; if (force || filter !== 'hideGroupAmounts') { await this._setRawData(); } const map = this._getGroupedMap(true, 'account'); const rangeGroupedMap = await this._getGroupedByDateRanges(map); const accountTree = await this._getAccountTree(rangeGroupedMap); for (const name of Object.keys(accountTree)) { const { rootType } = accountTree[name]; if (this.rootTypes.includes(rootType)) { continue; } delete accountTree[name]; } /** * Income Rows */ const incomeRoots = this.getRootNodes( AccountRootTypeEnum.Income, accountTree )!; const incomeList = convertAccountRootNodesToAccountList(incomeRoots); const incomeRows = this.getReportRowsFromAccountList(incomeList); /** * Expense Rows */ const expenseRoots = this.getRootNodes( AccountRootTypeEnum.Expense, accountTree )!; const expenseList = convertAccountRootNodesToAccountList(expenseRoots); const expenseRows = this.getReportRowsFromAccountList(expenseList); this.reportData = this.getReportDataFromRows( incomeRows, expenseRows, incomeRoots, expenseRoots ); this.loading = false; } getReportDataFromRows( incomeRows: ReportData, expenseRows: ReportData, incomeRoots: AccountTreeNode[] | undefined, expenseRoots: AccountTreeNode[] | undefined ): ReportData { if ( incomeRoots && incomeRoots.length && !expenseRoots && !expenseRoots.length ) { return this.getIncomeOrExpenseRows( incomeRoots, incomeRows, t`Total Income (Credit)` ); } if ( expenseRoots && expenseRoots.length && (!incomeRoots || !incomeRoots.length) ) { return this.getIncomeOrExpenseRows( expenseRoots, expenseRows, t`Total Income (Credit)` ); } if ( !incomeRoots || !incomeRoots.length || !expenseRoots || !expenseRoots.length ) { return []; } return this.getIncomeAndExpenseRows( incomeRows, expenseRows, incomeRoots, expenseRoots ); } getIncomeOrExpenseRows( roots: AccountTreeNode[], rows: ReportData, totalRowName: string ): ReportData { const total = this.getTotalNode(roots, totalRowName); const totalRow = this.getRowFromAccountListNode(total); return [rows, totalRow].flat(); } getIncomeAndExpenseRows( incomeRows: ReportData, expenseRows: ReportData, incomeRoots: AccountTreeNode[], expenseRoots: AccountTreeNode[] ) { const totalIncome = this.getTotalNode( incomeRoots, t`Total Income (Credit)` ); const totalIncomeRow = this.getRowFromAccountListNode(totalIncome); const totalExpense = this.getTotalNode( expenseRoots, t`Total Expense (Debit)` ); const totalExpenseRow = this.getRowFromAccountListNode(totalExpense); const totalValueMap: ValueMap = new Map(); for (const key of totalIncome.valueMap!.keys()) { const income = totalIncome.valueMap!.get(key)?.balance ?? 0; const expense = totalExpense.valueMap!.get(key)?.balance ?? 0; totalValueMap.set(key, { balance: income - expense }); } const totalProfit = { name: t`Total Profit`, valueMap: totalValueMap, level: 0, } as AccountListNode; const totalProfitRow = this.getRowFromAccountListNode(totalProfit); totalProfitRow.cells.forEach((c) => { c.bold = true; if (typeof c.rawValue !== 'number') { return; } if (c.rawValue > 0) { c.color = 'green'; } else if (c.rawValue < 0) { c.color = 'red'; } }); const emptyRow = this.getEmptyRow(); return [ incomeRows, totalIncomeRow, emptyRow, expenseRows, totalExpenseRow, emptyRow, totalProfitRow, ].flat() as ReportData; } }
2302_79757062/books
reports/ProfitAndLoss/ProfitAndLoss.ts
TypeScript
agpl-3.0
4,636
import { Fyo } from 'fyo'; import { Converter } from 'fyo/core/converter'; import { DocValue } from 'fyo/core/types'; import { Action } from 'fyo/model/types'; import Observable from 'fyo/utils/observable'; import { Field, RawValue } from 'schemas/types'; import { getIsNullOrUndef } from 'utils'; import { ColumnField, ReportData } from './types'; export abstract class Report extends Observable<RawValue> { static title: string; static reportName: string; static isInventory = false; fyo: Fyo; columns: ColumnField[] = []; filters: Field[] = []; reportData: ReportData; usePagination = false; shouldRefresh = false; abstract loading: boolean; constructor(fyo: Fyo) { super(); this.fyo = fyo; this.reportData = []; } get title(): string { return (this.constructor as typeof Report).title; } get reportName(): string { return (this.constructor as typeof Report).reportName; } async initialize() { /** * Not in constructor cause possibly async. */ await this.setDefaultFilters(); this.filters = await this.getFilters(); this.columns = await this.getColumns(); await this.setReportData(); } get filterMap() { const filterMap: Record<string, RawValue> = {}; for (const { fieldname } of this.filters) { const value = this.get(fieldname); if (getIsNullOrUndef(value)) { continue; } filterMap[fieldname] = value; } return filterMap; } async set(key: string, value: DocValue, callPostSet = true) { const field = this.filters.find((f) => f.fieldname === key); if (field === undefined) { return; } value = Converter.toRawValue(value, field, this.fyo); const prevValue = this[key]; if (prevValue === value) { return; } if (getIsNullOrUndef(value)) { delete this[key]; } else { this[key] = value; } if (callPostSet) { await this.updateData(key); } } async updateData(key?: string, force?: boolean) { await this.setDefaultFilters(); this.filters = await this.getFilters(); this.columns = await this.getColumns(); await this.setReportData(key, force); } /** * Should first check if filter value is set * and update only if it is not set. */ abstract setDefaultFilters(): void | Promise<void>; abstract getActions(): Action[]; abstract getFilters(): Field[] | Promise<Field[]>; abstract getColumns(): ColumnField[] | Promise<ColumnField[]>; abstract setReportData(filter?: string, force?: boolean): Promise<void>; }
2302_79757062/books
reports/Report.ts
TypeScript
agpl-3.0
2,579
import { t } from 'fyo'; import { ValueError } from 'fyo/utils/errors'; import { DateTime } from 'luxon'; import { AccountRootType, AccountRootTypeEnum, } from 'models/baseModels/Account/types'; import { AccountReport, ACC_BAL_WIDTH, ACC_NAME_WIDTH, convertAccountRootNodesToAccountList, getFiscalEndpoints, } from 'reports/AccountReport'; import { Account, AccountListNode, AccountNameValueMapMap, ColumnField, DateRange, GroupedMap, LedgerEntry, ReportCell, ReportData, ReportRow, RootTypeRow, ValueMap, } from 'reports/types'; import { Field } from 'schemas/types'; import { QueryFilter } from 'utils/db/types'; export class TrialBalance extends AccountReport { static title = t`Trial Balance`; static reportName = 'trial-balance'; fromDate?: string; toDate?: string; hideGroupAmounts = false; loading = false; _rawData: LedgerEntry[] = []; _dateRanges?: DateRange[]; accountMap?: Record<string, Account>; get rootTypes(): AccountRootType[] { return [ AccountRootTypeEnum.Asset, AccountRootTypeEnum.Liability, AccountRootTypeEnum.Income, AccountRootTypeEnum.Expense, AccountRootTypeEnum.Equity, ]; } async setReportData(filter?: string, force?: boolean) { this.loading = true; if (force || filter !== 'hideGroupAmounts') { await this._setRawData(); } const map = this._getGroupedMap(true, 'account'); const rangeGroupedMap = await this._getGroupedByDateRanges(map); const accountTree = await this._getAccountTree(rangeGroupedMap); const rootTypeRows: RootTypeRow[] = this.rootTypes .map((rootType) => { const rootNodes = this.getRootNodes(rootType, accountTree)!; const rootList = convertAccountRootNodesToAccountList(rootNodes); return { rootType, rootNodes, rows: this.getReportRowsFromAccountList(rootList), }; }) .filter((row) => !!(row.rootNodes && row.rootNodes.length)); this.reportData = await this.getReportDataFromRows(rootTypeRows); this.loading = false; } // eslint-disable-next-line @typescript-eslint/require-await async getReportDataFromRows( rootTypeRows: RootTypeRow[] ): Promise<ReportData> { const reportData = rootTypeRows.reduce((reportData, r) => { reportData.push(...r.rows); reportData.push(this.getEmptyRow()); return reportData; }, [] as ReportData); reportData.pop(); return reportData; } // eslint-disable-next-line @typescript-eslint/require-await async _getGroupedByDateRanges( map: GroupedMap ): Promise<AccountNameValueMapMap> { const accountValueMap: AccountNameValueMapMap = new Map(); for (const account of map.keys()) { const valueMap: ValueMap = new Map(); /** * Set Balance for every DateRange key */ for (const entry of map.get(account)!) { const key = this._getRangeMapKey(entry); if (key === null) { throw new ValueError( `invalid entry in trial balance ${entry.date?.toISOString() ?? ''}` ); } const map = valueMap.get(key); const totalCredit = map?.credit ?? 0; const totalDebit = map?.debit ?? 0; valueMap.set(key, { credit: totalCredit + (entry.credit ?? 0), debit: totalDebit + (entry.debit ?? 0), }); } accountValueMap.set(account, valueMap); } return accountValueMap; } async _getDateRanges(): Promise<DateRange[]> { if (!this.toDate || !this.fromDate) { await this.setDefaultFilters(); } const toDate = DateTime.fromISO(this.toDate!); const fromDate = DateTime.fromISO(this.fromDate!); return [ { fromDate: DateTime.fromISO('0001-01-01'), toDate: fromDate, }, { fromDate, toDate }, { fromDate: toDate, toDate: DateTime.fromISO('9999-12-31'), }, ]; } getRowFromAccountListNode(al: AccountListNode) { const nameCell = { value: al.name, rawValue: al.name, align: 'left', width: ACC_NAME_WIDTH, bold: !al.level, indent: al.level ?? 0, } as ReportCell; const balanceCells = this._dateRanges!.map((k) => { const map = al.valueMap?.get(k); const hide = this.hideGroupAmounts && al.isGroup; return [ { rawValue: map?.debit ?? 0, value: hide ? '' : this.fyo.format(map?.debit ?? 0, 'Currency'), align: 'right', width: ACC_BAL_WIDTH, }, { rawValue: map?.credit ?? 0, value: hide ? '' : this.fyo.format(map?.credit ?? 0, 'Currency'), align: 'right', width: ACC_BAL_WIDTH, } as ReportCell, ]; }); return { cells: [nameCell, balanceCells].flat(2), level: al.level, isGroup: !!al.isGroup, folded: false, foldedBelow: false, } as ReportRow; } // eslint-disable-next-line @typescript-eslint/require-await async _getQueryFilters(): Promise<QueryFilter> { const filters: QueryFilter = {}; filters.reverted = false; return filters; } async setDefaultFilters(): Promise<void> { if (!this.toDate || !this.fromDate) { const { year } = DateTime.now(); const endpoints = await getFiscalEndpoints(year + 1, year, this.fyo); this.fromDate = endpoints.fromDate; this.toDate = DateTime.fromISO(endpoints.toDate) .minus({ days: 1 }) .toISODate(); } await this._setDateRanges(); } getFilters(): Field[] { return [ { fieldtype: 'Date', fieldname: 'fromDate', placeholder: t`From Date`, label: t`From Date`, required: true, }, { fieldtype: 'Date', fieldname: 'toDate', placeholder: t`To Date`, label: t`To Date`, required: true, }, { fieldtype: 'Check', label: t`Hide Group Amounts`, fieldname: 'hideGroupAmounts', } as Field, ] as Field[]; } getColumns(): ColumnField[] { return [ { label: t`Account`, fieldtype: 'Link', fieldname: 'account', align: 'left', width: ACC_NAME_WIDTH, }, { label: t`Opening (Dr)`, fieldtype: 'Data', fieldname: 'openingDebit', align: 'right', width: ACC_BAL_WIDTH, }, { label: t`Opening (Cr)`, fieldtype: 'Data', fieldname: 'openingCredit', align: 'right', width: ACC_BAL_WIDTH, }, { label: t`Debit`, fieldtype: 'Data', fieldname: 'debit', align: 'right', width: ACC_BAL_WIDTH, }, { label: t`Credit`, fieldtype: 'Data', fieldname: 'credit', align: 'right', width: ACC_BAL_WIDTH, }, { label: t`Closing (Dr)`, fieldtype: 'Data', fieldname: 'closingDebit', align: 'right', width: ACC_BAL_WIDTH, }, { label: t`Closing (Cr)`, fieldtype: 'Data', fieldname: 'closingCredit', align: 'right', width: ACC_BAL_WIDTH, }, ] as ColumnField[]; } }
2302_79757062/books
reports/TrialBalance/TrialBalance.ts
TypeScript
agpl-3.0
7,301
import { t } from 'fyo'; import { Action } from 'fyo/model/types'; import { Verb } from 'fyo/telemetry/types'; import { getSavePath, showExportInFolder } from 'src/utils/ui'; import { getIsNullOrUndef } from 'utils'; import { generateCSV } from 'utils/csvParser'; import { Report } from './Report'; import { ExportExtention, ReportCell } from './types'; interface JSONExport { columns: { fieldname: string; label: string }[]; rows: Record<string, unknown>[]; filters: Record<string, string>; timestamp: string; reportName: string; softwareName: string; softwareVersion: string; } export default function getCommonExportActions(report: Report): Action[] { const exportExtention = ['csv', 'json'] as ExportExtention[]; return exportExtention.map((ext) => ({ group: t`Export`, label: ext.toUpperCase(), type: 'primary', action: async () => { await exportReport(ext, report); }, })); } async function exportReport(extention: ExportExtention, report: Report) { const { filePath, canceled } = await getSavePath( report.reportName, extention ); if (canceled || !filePath) { return; } let data = ''; if (extention === 'csv') { data = getCsvData(report); } else if (extention === 'json') { data = getJsonData(report); } if (!data.length) { return; } await saveExportData(data, filePath); report.fyo.telemetry.log(Verb.Exported, report.reportName, { extention }); } function getJsonData(report: Report): string { const exportObject: JSONExport = { columns: [], rows: [], filters: {}, timestamp: '', reportName: '', softwareName: '', softwareVersion: '', }; const columns = report.columns; const displayPrecision = (report.fyo.singles.SystemSettings?.displayPrecision as number) ?? 2; /** * Set columns as list of fieldname, label */ exportObject.columns = columns.map(({ fieldname, label }) => ({ fieldname, label, })); /** * Set rows as fieldname: value map */ for (const row of report.reportData) { if (row.isEmpty) { continue; } const rowObj: Record<string, unknown> = {}; for (let c = 0; c < row.cells.length; c++) { const { label } = columns[c]; const cell = getValueFromCell(row.cells[c], displayPrecision); rowObj[label] = cell; } exportObject.rows.push(rowObj); } /** * Set filter map */ for (const { fieldname } of report.filters) { const value = report.get(fieldname); if (getIsNullOrUndef(value)) { continue; } exportObject.filters[fieldname] = String(value); } /** * Metadata */ exportObject.timestamp = new Date().toISOString(); exportObject.reportName = report.reportName; exportObject.softwareName = 'Frappe Books'; exportObject.softwareVersion = report.fyo.store.appVersion; return JSON.stringify(exportObject); } export function getCsvData(report: Report): string { const csvMatrix = convertReportToCSVMatrix(report); return generateCSV(csvMatrix); } function convertReportToCSVMatrix(report: Report): unknown[][] { const displayPrecision = (report.fyo.singles.SystemSettings?.displayPrecision as number) ?? 2; const reportData = report.reportData; const columns = report.columns; const csvdata: unknown[][] = []; csvdata.push(columns.map((c) => c.label)); for (const row of reportData) { if (row.isEmpty) { csvdata.push(Array(row.cells.length).fill('')); continue; } const csvrow: unknown[] = []; for (let c = 0; c < row.cells.length; c++) { const cell = getValueFromCell(row.cells[c], displayPrecision); csvrow.push(cell); } csvdata.push(csvrow); } return csvdata; } function getValueFromCell(cell: ReportCell, displayPrecision: number) { const rawValue = cell.rawValue; if (rawValue instanceof Date) { return rawValue.toISOString(); } if (typeof rawValue === 'number') { const value = rawValue.toFixed(displayPrecision); /** * remove insignificant zeroes */ if (value.endsWith('0'.repeat(displayPrecision))) { return value.slice(0, -displayPrecision - 1); } return value; } if (getIsNullOrUndef(cell)) { return ''; } return rawValue; } export async function saveExportData( data: string, filePath: string, message?: string ) { await ipc.saveData(data, filePath); message ??= t`Export Successful`; showExportInFolder(message, filePath); }
2302_79757062/books
reports/commonExporter.ts
TypeScript
agpl-3.0
4,491
import { BalanceSheet } from './BalanceSheet/BalanceSheet'; import { GeneralLedger } from './GeneralLedger/GeneralLedger'; import { GSTR1 } from './GoodsAndServiceTax/GSTR1'; import { GSTR2 } from './GoodsAndServiceTax/GSTR2'; import { ProfitAndLoss } from './ProfitAndLoss/ProfitAndLoss'; import { TrialBalance } from './TrialBalance/TrialBalance'; import { StockBalance } from './inventory/StockBalance'; import { StockLedger } from './inventory/StockLedger'; export const reports = { GeneralLedger, ProfitAndLoss, BalanceSheet, TrialBalance, GSTR1, GSTR2, StockLedger, StockBalance, } as const;
2302_79757062/books
reports/index.ts
TypeScript
agpl-3.0
615
import { t } from 'fyo'; import { RawValueMap } from 'fyo/core/types'; import { Action } from 'fyo/model/types'; import getCommonExportActions from 'reports/commonExporter'; import { ColumnField, ReportData } from 'reports/types'; import { Field } from 'schemas/types'; import { getStockBalanceEntries } from './helpers'; import { StockLedger } from './StockLedger'; import { ReferenceType } from './types'; export class StockBalance extends StockLedger { static title = t`Stock Balance`; static reportName = 'stock-balance'; static isInventory = true; override ascending = true; override referenceType: ReferenceType = 'All'; override referenceName = ''; override async _getReportData(force?: boolean): Promise<ReportData> { if (this.shouldRefresh || force || !this._rawData?.length) { await this._setRawData(); } const filters = { item: this.item, location: this.location, batch: this.batch, fromDate: this.fromDate, toDate: this.toDate, }; const rawData = getStockBalanceEntries(this._rawData ?? [], filters); return rawData.map((sbe, i) => { const row = { ...sbe, name: i + 1 } as RawValueMap; return this._convertRawDataRowToReportRow(row, { incomingQuantity: 'green', outgoingQuantity: 'red', balanceQuantity: null, }); }); } getFilters(): Field[] { const filters = [ { fieldtype: 'Link', target: 'Item', placeholder: t`Item`, label: t`Item`, fieldname: 'item', }, { fieldtype: 'Link', target: 'Location', placeholder: t`Location`, label: t`Location`, fieldname: 'location', }, ...(this.hasBatches ? [ { fieldtype: 'Link', target: 'Batch', placeholder: t`Batch`, label: t`Batch`, fieldname: 'batch', }, ] : []), { fieldtype: 'Date', placeholder: t`From Date`, label: t`From Date`, fieldname: 'fromDate', }, { fieldtype: 'Date', placeholder: t`To Date`, label: t`To Date`, fieldname: 'toDate', }, ] as Field[]; return filters; } getColumns(): ColumnField[] { return [ { fieldname: 'name', label: '#', fieldtype: 'Int', width: 0.5, }, { fieldname: 'item', label: 'Item', fieldtype: 'Link', }, { fieldname: 'location', label: 'Location', fieldtype: 'Link', }, ...(this.hasBatches ? ([ { fieldname: 'batch', label: 'Batch', fieldtype: 'Link' }, ] as ColumnField[]) : []), { fieldname: 'balanceQuantity', label: 'Balance Qty.', fieldtype: 'Float', }, { fieldname: 'balanceValue', label: 'Balance Value', fieldtype: 'Float', }, { fieldname: 'openingQuantity', label: 'Opening Qty.', fieldtype: 'Float', }, { fieldname: 'openingValue', label: 'Opening Value', fieldtype: 'Float', }, { fieldname: 'incomingQuantity', label: 'In Qty.', fieldtype: 'Float', }, { fieldname: 'incomingValue', label: 'In Value', fieldtype: 'Currency', }, { fieldname: 'outgoingQuantity', label: 'Out Qty.', fieldtype: 'Float', }, { fieldname: 'outgoingValue', label: 'Out Value', fieldtype: 'Currency', }, { fieldname: 'valuationRate', label: 'Valuation rate', fieldtype: 'Currency', }, ]; } getActions(): Action[] { return getCommonExportActions(this); } }
2302_79757062/books
reports/inventory/StockBalance.ts
TypeScript
agpl-3.0
3,904
import { Fyo, t } from 'fyo'; import { RawValueMap } from 'fyo/core/types'; import { Action } from 'fyo/model/types'; import { cloneDeep } from 'lodash'; import { DateTime } from 'luxon'; import { InventorySettings } from 'models/inventory/InventorySettings'; import { ValuationMethod } from 'models/inventory/types'; import { ModelNameEnum } from 'models/types'; import getCommonExportActions from 'reports/commonExporter'; import { Report } from 'reports/Report'; import { ColumnField, ReportCell, ReportData, ReportRow } from 'reports/types'; import { Field, RawValue } from 'schemas/types'; import { isNumeric } from 'src/utils'; import { getRawStockLedgerEntries, getStockLedgerEntries } from './helpers'; import { ComputedStockLedgerEntry, ReferenceType } from './types'; export class StockLedger extends Report { static title = t`Stock Ledger`; static reportName = 'stock-ledger'; static isInventory = true; usePagination = true; _rawData?: ComputedStockLedgerEntry[]; loading = false; shouldRefresh = false; item?: string; location?: string; batch?: string; serialNumber?: string; fromDate?: string; toDate?: string; ascending?: boolean; referenceType?: ReferenceType = 'All'; referenceName?: string; groupBy: 'none' | 'item' | 'location' = 'none'; get hasBatches(): boolean { return !!(this.fyo.singles.InventorySettings as InventorySettings) .enableBatches; } get hasSerialNumbers(): boolean { return !!(this.fyo.singles.InventorySettings as InventorySettings) .enableSerialNumber; } constructor(fyo: Fyo) { super(fyo); this._setObservers(); } setDefaultFilters() { if (!this.toDate) { this.toDate = DateTime.now().plus({ days: 1 }).toISODate(); this.fromDate = DateTime.now().minus({ years: 1 }).toISODate(); } } async setReportData( filter?: string | undefined, force?: boolean | undefined ): Promise<void> { this.loading = true; this.reportData = await this._getReportData(force); this.loading = false; } async _getReportData(force?: boolean): Promise<ReportData> { if (this.shouldRefresh || force || !this._rawData?.length) { await this._setRawData(); } const rawData = cloneDeep(this._rawData); if (!rawData) { return []; } const filtered = this._getFilteredRawData(rawData); const grouped = this._getGroupedRawData(filtered); return grouped.map((row) => this._convertRawDataRowToReportRow(row as RawValueMap, { quantity: null, valueChange: null, }) ); } async _setRawData() { const valuationMethod = ValuationMethod.FIFO; const rawSLEs = await getRawStockLedgerEntries(this.fyo); this._rawData = getStockLedgerEntries(rawSLEs, valuationMethod); } _getFilteredRawData(rawData: ComputedStockLedgerEntry[]) { const filteredRawData: ComputedStockLedgerEntry[] = []; if (!rawData.length) { return []; } const fromDate = this.fromDate ? Date.parse(this.fromDate) : null; const toDate = this.toDate ? Date.parse(this.toDate) : null; if (!this.ascending) { rawData.reverse(); } let i = 0; for (let idx = 0; idx < rawData.length; idx++) { const row = rawData[idx]; if (this.item && row.item !== this.item) { continue; } if (this.location && row.location !== this.location) { continue; } if (this.batch && row.batch !== this.batch) { continue; } const date = row.date.valueOf(); if (toDate && date > toDate) { continue; } if (fromDate && date < fromDate) { continue; } if ( this.referenceType !== 'All' && row.referenceType !== this.referenceType ) { continue; } if (this.referenceName && row.referenceName !== this.referenceName) { continue; } row.name = ++i; filteredRawData.push(row); } return filteredRawData; } _getGroupedRawData(rawData: ComputedStockLedgerEntry[]) { const groupBy = this.groupBy; if (groupBy === 'none') { return rawData; } const groups: Map<string, ComputedStockLedgerEntry[]> = new Map(); for (const row of rawData) { const key = row[groupBy]; if (!groups.has(key)) { groups.set(key, []); } groups.get(key)?.push(row); } const groupedRawData: (ComputedStockLedgerEntry | { name: null })[] = []; let i = 0; for (const key of groups.keys()) { for (const row of groups.get(key) ?? []) { row.name = ++i; groupedRawData.push(row); } groupedRawData.push({ name: null }); } if (groupedRawData.at(-1)?.name === null) { groupedRawData.pop(); } return groupedRawData; } _convertRawDataRowToReportRow( row: RawValueMap, colouredMap: Record<string, 'red' | 'green' | null> ): ReportRow { const cells: ReportCell[] = []; const columns = this.getColumns(); if (row.name === null) { return { isEmpty: true, cells: columns.map((c) => ({ rawValue: '', value: '', width: c.width ?? 1, })), }; } for (const col of columns) { const fieldname = col.fieldname as keyof ComputedStockLedgerEntry; const fieldtype = col.fieldtype; const rawValue = row[fieldname] as RawValue; let value; if (col.fieldname === 'referenceType' && typeof rawValue === 'string') { value = this.fyo.schemaMap[rawValue]?.label ?? rawValue; } else { value = this.fyo.format(rawValue, fieldtype); } const align = isNumeric(fieldtype) ? 'right' : 'left'; const isColoured = fieldname in colouredMap; const isNumber = typeof rawValue === 'number'; let color: 'red' | 'green' | undefined = undefined; if (isColoured && colouredMap[fieldname]) { color = colouredMap[fieldname]!; } else if (isColoured && isNumber && rawValue > 0) { color = 'green'; } else if (isColoured && isNumber && rawValue < 0) { color = 'red'; } cells.push({ rawValue, value, align, color, width: col.width }); } return { cells }; } _setObservers() { const listener = () => (this.shouldRefresh = true); this.fyo.doc.observer.on( `sync:${ModelNameEnum.StockLedgerEntry}`, listener ); this.fyo.doc.observer.on( `delete:${ModelNameEnum.StockLedgerEntry}`, listener ); } getColumns(): ColumnField[] { const batch: Field[] = []; const serialNumber: Field[] = []; if (this.hasBatches) { batch.push({ fieldname: 'batch', label: 'Batch', fieldtype: 'Link', target: 'Batch', }); } if (this.hasSerialNumbers) { serialNumber.push({ fieldname: 'serialNumber', label: 'Serial Number', fieldtype: 'Data', }); } return [ { fieldname: 'name', label: '#', fieldtype: 'Int', width: 0.5, }, { fieldname: 'date', label: 'Date', fieldtype: 'Datetime', width: 1.25, }, { fieldname: 'item', label: 'Item', fieldtype: 'Link', }, { fieldname: 'location', label: 'Location', fieldtype: 'Link', }, ...batch, ...serialNumber, { fieldname: 'quantity', label: 'Quantity', fieldtype: 'Float', }, { fieldname: 'balanceQuantity', label: 'Balance Qty.', fieldtype: 'Float', }, { fieldname: 'incomingRate', label: 'Incoming rate', fieldtype: 'Currency', }, { fieldname: 'valuationRate', label: 'Valuation Rate', fieldtype: 'Currency', }, { fieldname: 'balanceValue', label: 'Balance Value', fieldtype: 'Currency', }, { fieldname: 'valueChange', label: 'Value Change', fieldtype: 'Currency', }, { fieldname: 'referenceName', label: 'Ref. Name', fieldtype: 'DynamicLink', }, { fieldname: 'referenceType', label: 'Ref. Type', fieldtype: 'Data', }, ]; } getFilters(): Field[] { return [ { fieldtype: 'Select', options: [ { label: t`All`, value: 'All' }, { label: t`Stock Movements`, value: 'StockMovement' }, { label: t`Shipment`, value: 'Shipment' }, { label: t`Purchase Receipt`, value: 'PurchaseReceipt' }, ], label: t`Ref Type`, fieldname: 'referenceType', placeholder: t`Ref Type`, }, { fieldtype: 'DynamicLink', label: t`Ref Name`, references: 'referenceType', placeholder: t`Ref Name`, emptyMessage: t`Change Ref Type`, fieldname: 'referenceName', }, { fieldtype: 'Link', target: 'Item', placeholder: t`Item`, label: t`Item`, fieldname: 'item', }, { fieldtype: 'Link', target: 'Location', placeholder: t`Location`, label: t`Location`, fieldname: 'location', }, ...(this.hasBatches ? ([ { fieldtype: 'Link', target: 'Batch', placeholder: t`Batch`, label: t`Batch`, fieldname: 'batch', }, ] as Field[]) : []), { fieldtype: 'Date', placeholder: t`From Date`, label: t`From Date`, fieldname: 'fromDate', }, { fieldtype: 'Date', placeholder: t`To Date`, label: t`To Date`, fieldname: 'toDate', }, { fieldtype: 'Select', label: t`Group By`, fieldname: 'groupBy', options: [ { label: t`None`, value: 'none' }, { label: t`Item`, value: 'item' }, { label: t`Location`, value: 'location' }, { label: t`Reference`, value: 'referenceName' }, ], }, { fieldtype: 'Check', label: t`Ascending Order`, fieldname: 'ascending', }, ] as Field[]; } getActions(): Action[] { return getCommonExportActions(this); } }
2302_79757062/books
reports/inventory/StockLedger.ts
TypeScript
agpl-3.0
10,461
import { Fyo } from 'fyo'; import { StockQueue } from 'models/inventory/stockQueue'; import { ValuationMethod } from 'models/inventory/types'; import { ModelNameEnum } from 'models/types'; import { safeParseFloat, safeParseInt } from 'utils/index'; import type { ComputedStockLedgerEntry, RawStockLedgerEntry, StockBalanceEntry, } from './types'; import type { QueryFilter } from 'utils/db/types'; import type { StockTransfer } from 'models/inventory/StockTransfer'; type Item = string; type Location = string; type Batch = string; export async function getRawStockLedgerEntries( fyo: Fyo, filters: QueryFilter = {} ) { const fieldnames = [ 'name', 'date', 'item', 'batch', 'serialNumber', 'rate', 'quantity', 'location', 'referenceName', 'referenceType', ]; return (await fyo.db.getAllRaw(ModelNameEnum.StockLedgerEntry, { fields: fieldnames, filters, orderBy: ['date', 'created', 'name'], order: 'asc', })) as RawStockLedgerEntry[]; } export async function getShipmentCOGSAmountFromSLEs( stockTransfer: StockTransfer ) { const fyo = stockTransfer.fyo; const date = stockTransfer.date ?? new Date(); const items = (stockTransfer.items ?? []).filter((i) => i.item); const itemNames = Array.from(new Set(items.map((i) => i.item))) as string[]; type Item = string; type Batch = string; type Location = string; type Queues = Record<Item, Record<Location, Record<Batch, StockQueue>>>; const rawSles = await getRawStockLedgerEntries(fyo, { item: ['in', itemNames], date: ['<=', date.toISOString()], }); const q: Queues = {}; for (const sle of rawSles) { const i = sle.item; const l = sle.location; const b = sle.batch ?? '-'; q[i] ??= {}; q[i][l] ??= {}; q[i][l][b] ??= new StockQueue(); const sq = q[i][l][b]; if (sle.quantity > 0) { const rate = fyo.pesa(sle.rate); sq.inward(rate.float, sle.quantity); } else { sq.outward(-sle.quantity); } } let total = fyo.pesa(0); for (const item of items) { const i = item.item ?? '-'; const l = item.location ?? '-'; const b = item.batch ?? '-'; const sq = q[i][l][b]; const stAmount = item.amount ?? 0; if (!sq) { total = total.add(stAmount); } const stRate = item.rate?.float ?? 0; const stQuantity = item.quantity ?? 0; const rate = sq.outward(stQuantity) ?? stRate; const amount = rate * stQuantity; total = total.add(amount); } return total; } export function getStockLedgerEntries( rawSLEs: RawStockLedgerEntry[], valuationMethod: ValuationMethod ): ComputedStockLedgerEntry[] { const computedSLEs: ComputedStockLedgerEntry[] = []; const stockQueues: Record< Item, Record<Location, Record<Batch, StockQueue>> > = {}; for (const sle of rawSLEs) { const name = safeParseInt(sle.name); const date = new Date(sle.date); const rate = safeParseFloat(sle.rate); const { item, location, quantity, referenceName, referenceType } = sle; const batch = sle.batch ?? ''; const serialNumber = sle.serialNumber ?? ''; if (quantity === 0) { continue; } stockQueues[item] ??= {}; stockQueues[item][location] ??= {}; stockQueues[item][location][batch] ??= new StockQueue(); const q = stockQueues[item][location][batch]; const initialValue = q.value; let incomingRate: number | null; if (quantity > 0) { incomingRate = q.inward(rate, quantity); } else { incomingRate = q.outward(-quantity); } if (incomingRate === null) { continue; } const balanceQuantity = q.quantity; let valuationRate = q.fifo; if (valuationMethod === ValuationMethod.MovingAverage) { valuationRate = q.movingAverage; } const balanceValue = q.value; const valueChange = balanceValue - initialValue; const csle: ComputedStockLedgerEntry = { name, date, item, location, batch, serialNumber, quantity, balanceQuantity, incomingRate, valuationRate, balanceValue, valueChange, referenceName, referenceType, }; computedSLEs.push(csle); } return computedSLEs; } export function getStockBalanceEntries( computedSLEs: ComputedStockLedgerEntry[], filters: { item?: string; location?: string; fromDate?: string; toDate?: string; batch?: string; } ): StockBalanceEntry[] { const sbeMap: Record< Item, Record<Location, Record<Batch, StockBalanceEntry>> > = {}; const fromDate = filters.fromDate ? Date.parse(filters.fromDate) : null; const toDate = filters.toDate ? Date.parse(filters.toDate) : null; for (const sle of computedSLEs) { if (filters.item && sle.item !== filters.item) { continue; } if (filters.location && sle.location !== filters.location) { continue; } if (filters.batch && sle.batch !== filters.batch) { continue; } const batch = sle.batch || ''; sbeMap[sle.item] ??= {}; sbeMap[sle.item][sle.location] ??= {}; sbeMap[sle.item][sle.location][batch] ??= getSBE( sle.item, sle.location, batch ); const date = sle.date.valueOf(); if (fromDate && date < fromDate) { const sbe = sbeMap[sle.item][sle.location][batch]; updateOpeningBalances(sbe, sle); continue; } if (toDate && date > toDate) { continue; } const sbe = sbeMap[sle.item][sle.location][batch]; updateCurrentBalances(sbe, sle); } return Object.values(sbeMap) .map((sbeBatched) => Object.values(sbeBatched).map((sbes) => Object.values(sbes)) ) .flat(2); } function getSBE( item: string, location: string, batch: string ): StockBalanceEntry { return { name: 0, item, location, batch, balanceQuantity: 0, balanceValue: 0, openingQuantity: 0, openingValue: 0, incomingQuantity: 0, incomingValue: 0, outgoingQuantity: 0, outgoingValue: 0, valuationRate: 0, }; } function updateOpeningBalances( sbe: StockBalanceEntry, sle: ComputedStockLedgerEntry ) { sbe.openingQuantity += sle.quantity; sbe.openingValue += sle.valueChange; sbe.balanceQuantity += sle.quantity; sbe.balanceValue += sle.valueChange; } function updateCurrentBalances( sbe: StockBalanceEntry, sle: ComputedStockLedgerEntry ) { sbe.balanceQuantity += sle.quantity; sbe.balanceValue += sle.valueChange; if (sle.quantity > 0) { sbe.incomingQuantity += sle.quantity; sbe.incomingValue += sle.valueChange; } else { sbe.outgoingQuantity -= sle.quantity; sbe.outgoingValue -= sle.valueChange; } sbe.valuationRate = sle.valuationRate; }
2302_79757062/books
reports/inventory/helpers.ts
TypeScript
agpl-3.0
6,782
import { ModelNameEnum } from "models/types"; export interface RawStockLedgerEntry { name: string; date: string; item: string; rate: string; batch: string | null; serialNumber: string | null; quantity: number; location: string; referenceName: string; referenceType: string; [key: string]: unknown; } export interface ComputedStockLedgerEntry{ name: number; date: Date; item: string; location:string; batch: string; serialNumber: string; quantity: number; balanceQuantity: number; incomingRate: number; valuationRate:number; balanceValue:number; valueChange:number; referenceName: string; referenceType: string; } export interface StockBalanceEntry{ name: number; item: string; location:string; batch: string; balanceQuantity: number; balanceValue: number; openingQuantity: number; openingValue:number; incomingQuantity:number; incomingValue:number; outgoingQuantity:number; outgoingValue:number; valuationRate:number; } export type ReferenceType = | ModelNameEnum.StockMovement | ModelNameEnum.Shipment | ModelNameEnum.PurchaseReceipt | 'All';
2302_79757062/books
reports/inventory/types.ts
TypeScript
agpl-3.0
1,153
import { DateTime } from 'luxon'; import { AccountRootType } from 'models/baseModels/Account/types'; import { BaseField, FieldType, RawValue } from 'schemas/types'; export type ExportExtention = 'csv' | 'json'; export interface ReportCell { bold?: boolean; italics?: boolean; align?: 'left' | 'right' | 'center'; width?: number; value: string; rawValue: RawValue | undefined | Date; indent?: number; color?: 'red' | 'green'; } export interface ReportRow { cells: ReportCell[]; level?: number; isGroup?: boolean; isEmpty?: boolean; folded?: boolean; foldedBelow?: boolean; } export type ReportData = ReportRow[]; export interface ColumnField extends Omit<BaseField, 'fieldtype'> { fieldtype: FieldType; align?: 'left' | 'right' | 'center'; width?: number; } export type BalanceType = 'Credit' | 'Debit'; export type Periodicity = 'Monthly' | 'Quarterly' | 'Half Yearly' | 'Yearly'; export interface FinancialStatementOptions { rootType: AccountRootType; fromDate: string; toDate: string; balanceMustBe?: BalanceType; periodicity?: Periodicity; accumulateValues?: boolean; } export interface RawLedgerEntry { name: string; account: string; date: string; debit: string; credit: string; referenceType: string; referenceName: string; party: string; reverted: number; reverts: string; [key: string]: RawValue; } export interface LedgerEntry { index?: string; name: number; account: string; date: Date | null; debit: number | null; credit: number | null; balance: number | null; referenceType: string; referenceName: string; party: string; reverted: boolean; reverts: string; } export type GroupedMap = Map<string, LedgerEntry[]>; export type DateRange = { fromDate: DateTime; toDate: DateTime }; export type ValueMap = Map<DateRange, Record<string, number>>; export interface Account { name: string; rootType: AccountRootType; isGroup: boolean; parentAccount: string | null; } export type AccountTree = Record<string, AccountTreeNode>; export interface AccountTreeNode extends Account { children?: AccountTreeNode[]; valueMap?: ValueMap; prune?: boolean; } export type AccountList = AccountListNode[]; export interface AccountListNode extends Account { valueMap?: ValueMap; level?: number; } export type AccountNameValueMapMap = Map<string, ValueMap>; export type BasedOn = 'Fiscal Year' | 'Until Date'; export interface TreeNode { name: string; children?: TreeNode[]; } export type Tree = Record<string, TreeNode>; export type RootTypeRow = { rootType: AccountRootType; rootNodes: AccountTreeNode[]; rows: ReportData; };
2302_79757062/books
reports/types.ts
TypeScript
agpl-3.0
2,650
import { RawCustomField } from 'backend/database/types'; import { cloneDeep } from 'lodash'; import { getListFromMap, getMapFromList } from 'utils'; import regionalSchemas from './regional'; import { appSchemas, coreSchemas, metaSchemas } from './schemas'; import type { DynamicLinkField, Field, OptionField, Schema, SchemaMap, SchemaStub, SchemaStubMap, SelectOption, TargetField, } from './types'; const NAME_FIELD = { fieldname: 'name', label: `ID`, fieldtype: 'Data', required: true, readOnly: true, }; export function getSchemas( countryCode = '-', rawCustomFields: RawCustomField[] ): Readonly<SchemaMap> { const builtCoreSchemas = getCoreSchemas(); const builtAppSchemas = getAppSchemas(countryCode); let schemaMap = Object.assign({}, builtAppSchemas, builtCoreSchemas); schemaMap = addMetaFields(schemaMap); schemaMap = removeFields(schemaMap); schemaMap = setSchemaNameOnFields(schemaMap); addCustomFields(schemaMap, rawCustomFields); deepFreeze(schemaMap); return schemaMap; } export function setSchemaNameOnFields(schemaMap: SchemaMap): SchemaMap { for (const schemaName in schemaMap) { const schema = schemaMap[schemaName]!; schema.fields = schema.fields.map((f) => ({ ...f, schemaName })); } return schemaMap; } function removeFields(schemaMap: SchemaMap): SchemaMap { for (const schemaName in schemaMap) { const schema = schemaMap[schemaName]!; if (schema.removeFields === undefined) { continue; } for (const fieldname of schema.removeFields) { schema.fields = schema.fields.filter((f) => f.fieldname !== fieldname); schema.tableFields = schema.tableFields?.filter((fn) => fn !== fieldname); schema.quickEditFields = schema.quickEditFields?.filter( (fn) => fn !== fieldname ); schema.keywordFields = schema.keywordFields?.filter( (fn) => fn !== fieldname ); if (schema.linkDisplayField === fieldname) { delete schema.linkDisplayField; } } delete schema.removeFields; } return schemaMap; } function deepFreeze(schemaMap: SchemaMap) { Object.freeze(schemaMap); for (const schemaName in schemaMap) { Object.freeze(schemaMap[schemaName]); for (const key in schemaMap[schemaName]) { // @ts-ignore Object.freeze(schemaMap[schemaName][key]); } for (const field of schemaMap[schemaName]?.fields ?? []) { Object.freeze(field); } } } export function addMetaFields(schemaMap: SchemaMap): SchemaMap { const metaSchemaMap = getMapFromList(cloneDeep(metaSchemas), 'name'); const base = metaSchemaMap.base; const tree = getCombined(metaSchemaMap.tree, base); const child = metaSchemaMap.child; const submittable = getCombined(metaSchemaMap.submittable, base); const submittableTree = getCombined(tree, metaSchemaMap.submittable); for (const name in schemaMap) { const schema = schemaMap[name] as Schema; if (schema.isSingle) { continue; } if (schema.isTree && schema.isSubmittable) { schema.fields = [...schema.fields, ...submittableTree.fields!]; } else if (schema.isTree) { schema.fields = [...schema.fields, ...tree.fields!]; } else if (schema.isSubmittable) { schema.fields = [...schema.fields, ...submittable.fields!]; } else if (schema.isChild) { schema.fields = [...schema.fields, ...child.fields!]; } else { schema.fields = [...schema.fields, ...base.fields!]; } } addNameField(schemaMap); addTitleField(schemaMap); return schemaMap; } function addTitleField(schemaMap: SchemaMap) { for (const schemaName in schemaMap) { schemaMap[schemaName]!.titleField ??= 'name'; } } function addNameField(schemaMap: SchemaMap) { for (const name in schemaMap) { const schema = schemaMap[name] as Schema; if (schema.isSingle) { continue; } const pkField = schema.fields.find((f) => f.fieldname === 'name'); if (pkField !== undefined) { continue; } schema.fields.unshift(NAME_FIELD as Field); } } function getCoreSchemas(): SchemaMap { const rawSchemaMap = getMapFromList(cloneDeep(coreSchemas), 'name'); const coreSchemaMap = getAbstractCombinedSchemas(rawSchemaMap); return cleanSchemas(coreSchemaMap); } function getAppSchemas(countryCode: string): SchemaMap { const appSchemaMap = getMapFromList(cloneDeep(appSchemas), 'name'); const regionalSchemaMap = getRegionalSchemaMap(countryCode); const combinedSchemas = getRegionalCombinedSchemas( appSchemaMap, regionalSchemaMap ); const schemaMap = getAbstractCombinedSchemas(combinedSchemas); return cleanSchemas(schemaMap); } export function cleanSchemas(schemaMap: SchemaMap): SchemaMap { for (const name in schemaMap) { const schema = schemaMap[name] as Schema; if (schema.isAbstract && !schema.extends) { delete schemaMap[name]; continue; } delete schema.extends; delete schema.isAbstract; } return schemaMap; } function getCombined( extendingSchema: SchemaStub, abstractSchema: SchemaStub ): SchemaStub { abstractSchema = cloneDeep(abstractSchema); extendingSchema = cloneDeep(extendingSchema); const abstractFields = getMapFromList( abstractSchema.fields ?? [], 'fieldname' ); const extendingFields = getMapFromList( extendingSchema.fields ?? [], 'fieldname' ); const combined = Object.assign(abstractSchema, extendingSchema); for (const fieldname in extendingFields) { abstractFields[fieldname] = extendingFields[fieldname]; } combined.fields = getListFromMap(abstractFields); return combined; } export function getAbstractCombinedSchemas(schemas: SchemaStubMap): SchemaMap { const abstractSchemaNames: string[] = Object.keys(schemas).filter( (n) => schemas[n].isAbstract ); const extendingSchemaNames: string[] = Object.keys(schemas).filter((n) => abstractSchemaNames.includes(schemas[n].extends ?? '') ); const completeSchemas: Schema[] = Object.keys(schemas) .filter( (n) => !abstractSchemaNames.includes(n) && !extendingSchemaNames.includes(n) ) .map((n) => schemas[n] as Schema); const schemaMap = getMapFromList(completeSchemas, 'name') as SchemaMap; for (const name of extendingSchemaNames) { const extendingSchema = schemas[name] as Schema; const abstractSchema = schemas[extendingSchema.extends!]; schemaMap[name] = getCombined(extendingSchema, abstractSchema) as Schema; } abstractSchemaNames.forEach((name) => { delete schemaMap[name]; }); return schemaMap; } export function getRegionalCombinedSchemas( appSchemaMap: SchemaStubMap, regionalSchemaMap: SchemaStubMap ): SchemaStubMap { const combined = { ...appSchemaMap }; for (const name in regionalSchemaMap) { const regionalSchema = regionalSchemaMap[name]; if (!combined.hasOwnProperty(name)) { combined[name] = regionalSchema; continue; } combined[name] = getCombined(regionalSchema, combined[name]); } return combined; } function getRegionalSchemaMap(countryCode: string): SchemaStubMap { const countrySchemas = cloneDeep(regionalSchemas[countryCode]) as | SchemaStub[] | undefined; if (countrySchemas === undefined) { return {}; } return getMapFromList(countrySchemas, 'name'); } function addCustomFields( schemaMap: SchemaMap, rawCustomFields: RawCustomField[] ): void { const fieldMap = getFieldMapFromRawCustomFields(rawCustomFields, schemaMap); for (const schemaName in fieldMap) { const fields = fieldMap[schemaName]; schemaMap[schemaName]?.fields.push(...fields); } } function getFieldMapFromRawCustomFields( rawCustomFields: RawCustomField[], schemaMap: SchemaMap ) { const schemaFieldMap: Record<string, Record<string, Field>> = {}; return rawCustomFields.reduce( ( map, { parent, label, fieldname, fieldtype, isRequired, section, tab, options: rawOptions, default: defaultValue, target, references, } ) => { schemaFieldMap[parent] ??= getMapFromList( schemaMap[parent]?.fields ?? [], 'fieldname' ); if (!schemaFieldMap[parent] || schemaFieldMap[parent][fieldname]) { return map; } map[parent] ??= []; const options = rawOptions ?.split('\n') .map((o) => { const value = o.trim(); return { value, label: value } as SelectOption; }) .filter((o) => o.label && o.value); const field = { label, fieldname, fieldtype, section, tab, isCustom: true, } as Field; if (options?.length) { (field as OptionField).options = options; } if (typeof isRequired === 'number' || typeof isRequired === 'boolean') { field.required = Boolean(isRequired); } if (typeof target === 'string') { (field as TargetField).target = target; } if (typeof references === 'string') { (field as DynamicLinkField).references = references; } if (field.required && defaultValue != null) { field.default = defaultValue; } if (field.required && field.default == null) { field.required = false; } map[parent].push(field); return map; }, {} as Record<string, Field[]> ); }
2302_79757062/books
schemas/index.ts
TypeScript
agpl-3.0
9,472
import { SchemaStub } from '../../types'; import AccountingSettings from './AccountingSettings.json'; export default [AccountingSettings] as SchemaStub[];
2302_79757062/books
schemas/regional/ch/index.ts
TypeScript
agpl-3.0
156
import { SchemaStub } from '../../types'; import AccountingSettings from './AccountingSettings.json'; import Address from './Address.json'; import Party from './Party.json'; export default [AccountingSettings, Address, Party] as SchemaStub[];
2302_79757062/books
schemas/regional/in/index.ts
TypeScript
agpl-3.0
244
import { SchemaStub } from 'schemas/types'; import IndianSchemas from './in'; import SwissSchemas from './ch'; /** * Regional Schemas are exported by country code. */ export default { in: IndianSchemas, ch: SwissSchemas } as Record< string, SchemaStub[] >;
2302_79757062/books
schemas/regional/index.ts
TypeScript
agpl-3.0
264
import Account from './app/Account.json'; import AccountingLedgerEntry from './app/AccountingLedgerEntry.json'; import AccountingSettings from './app/AccountingSettings.json'; import Address from './app/Address.json'; import Batch from './app/Batch.json'; import Color from './app/Color.json'; import Currency from './app/Currency.json'; import Defaults from './app/Defaults.json'; import GetStarted from './app/GetStarted.json'; import Invoice from './app/Invoice.json'; import InvoiceItem from './app/InvoiceItem.json'; import Item from './app/Item.json'; import JournalEntry from './app/JournalEntry.json'; import JournalEntryAccount from './app/JournalEntryAccount.json'; import Misc from './app/Misc.json'; import NumberSeries from './app/NumberSeries.json'; import Party from './app/Party.json'; import Lead from './app/Lead.json'; import LoyaltyProgram from './app/LoyaltyProgram.json'; import LoyaltyPointEntry from './app/LoyaltyPointEntry.json'; import CollectionRulesItems from './app/CollectionRulesItems.json'; import Payment from './app/Payment.json'; import PaymentFor from './app/PaymentFor.json'; import PriceList from './app/PriceList.json'; import PriceListItem from './app/PriceListItem.json'; import PricingRule from './app/PricingRule.json'; import PricingRuleItem from './app/PricingRuleItem.json'; import PricingRuleDetail from './app/PricingRuleDetail.json'; import PrintSettings from './app/PrintSettings.json'; import PrintTemplate from './app/PrintTemplate.json'; import PurchaseInvoice from './app/PurchaseInvoice.json'; import PurchaseInvoiceItem from './app/PurchaseInvoiceItem.json'; import SalesInvoice from './app/SalesInvoice.json'; import SalesInvoiceItem from './app/SalesInvoiceItem.json'; import SalesQuote from './app/SalesQuote.json'; import SalesQuoteItem from './app/SalesQuoteItem.json'; import SetupWizard from './app/SetupWizard.json'; import Tax from './app/Tax.json'; import TaxDetail from './app/TaxDetail.json'; import TaxSummary from './app/TaxSummary.json'; import UOM from './app/UOM.json'; import InventorySettings from './app/inventory/InventorySettings.json'; import Location from './app/inventory/Location.json'; import PurchaseReceipt from './app/inventory/PurchaseReceipt.json'; import PurchaseReceiptItem from './app/inventory/PurchaseReceiptItem.json'; import SerialNumber from './app/inventory/SerialNumber.json'; import Shipment from './app/inventory/Shipment.json'; import ShipmentItem from './app/inventory/ShipmentItem.json'; import StockLedgerEntry from './app/inventory/StockLedgerEntry.json'; import StockMovement from './app/inventory/StockMovement.json'; import StockMovementItem from './app/inventory/StockMovementItem.json'; import StockTransfer from './app/inventory/StockTransfer.json'; import StockTransferItem from './app/inventory/StockTransferItem.json'; import UOMConversionItem from './app/inventory/UOMConversionItem.json'; import CustomField from './core/CustomField.json'; import CustomForm from './core/CustomForm.json'; import PatchRun from './core/PatchRun.json'; import SingleValue from './core/SingleValue.json'; import SystemSettings from './core/SystemSettings.json'; import base from './meta/base.json'; import child from './meta/child.json'; import submittable from './meta/submittable.json'; import tree from './meta/tree.json'; import CashDenominations from './app/inventory/Point of Sale/CashDenominations.json'; import ClosingAmounts from './app/inventory/Point of Sale/ClosingAmounts.json'; import ClosingCash from './app/inventory/Point of Sale/ClosingCash.json'; import DefaultCashDenominations from './app/inventory/Point of Sale/DefaultCashDenominations.json'; import OpeningAmounts from './app/inventory/Point of Sale/OpeningAmounts.json'; import OpeningCash from './app/inventory/Point of Sale/OpeningCash.json'; import POSSettings from './app/inventory/Point of Sale/POSSettings.json'; import POSShift from './app/inventory/Point of Sale/POSShift.json'; import POSShiftAmounts from './app/inventory/Point of Sale/POSShiftAmounts.json'; import { Schema, SchemaStub } from './types'; export const coreSchemas: Schema[] = [ PatchRun as Schema, SingleValue as Schema, SystemSettings as Schema, ]; export const metaSchemas: SchemaStub[] = [ base as SchemaStub, child as SchemaStub, submittable as SchemaStub, tree as SchemaStub, ]; export const appSchemas: Schema[] | SchemaStub[] = [ Misc as Schema, SetupWizard as Schema, GetStarted as Schema, PrintTemplate as Schema, Color as Schema, Currency as Schema, Defaults as Schema, NumberSeries as Schema, PrintSettings as Schema, Account as Schema, AccountingSettings as Schema, AccountingLedgerEntry as Schema, Party as Schema, Lead as Schema, Address as Schema, Item as Schema, UOM as Schema, UOMConversionItem as Schema, LoyaltyProgram as Schema, LoyaltyPointEntry as Schema, CollectionRulesItems as Schema, Payment as Schema, PaymentFor as Schema, JournalEntry as Schema, JournalEntryAccount as Schema, Invoice as Schema, SalesInvoice as Schema, PurchaseInvoice as Schema, SalesQuote as Schema, InvoiceItem as Schema, SalesInvoiceItem as SchemaStub, PurchaseInvoiceItem as SchemaStub, SalesQuoteItem as SchemaStub, PriceList as Schema, PriceListItem as SchemaStub, PricingRule as Schema, PricingRuleItem as SchemaStub, PricingRuleDetail as SchemaStub, Tax as Schema, TaxDetail as Schema, TaxSummary as Schema, InventorySettings as Schema, Location as Schema, StockLedgerEntry as Schema, StockMovement as Schema, StockMovementItem as Schema, StockTransfer as Schema, StockTransferItem as Schema, Shipment as Schema, ShipmentItem as Schema, PurchaseReceipt as Schema, PurchaseReceiptItem as Schema, Batch as Schema, SerialNumber as Schema, CustomForm as Schema, CustomField as Schema, CashDenominations as Schema, ClosingAmounts as Schema, ClosingCash as Schema, DefaultCashDenominations as Schema, OpeningAmounts as Schema, OpeningCash as Schema, POSSettings as Schema, POSShift as Schema, POSShiftAmounts as Schema, ];
2302_79757062/books
schemas/schemas.ts
TypeScript
agpl-3.0
6,134
import { cloneDeep } from 'lodash'; import Account from '../app/Account.json'; import JournalEntry from '../app/JournalEntry.json'; import JournalEntryAccount from '../app/JournalEntryAccount.json'; import PartyRegional from '../regional/in/Party.json'; import { Schema, SchemaStub, SchemaStubMap } from '../types'; import Customer from './Customer.json'; import Party from './Party.json'; interface AppSchemaMap extends SchemaStubMap { Account: SchemaStub; JournalEntry: SchemaStub; JournalEntryAccount: SchemaStub; Party: SchemaStub; Customer: SchemaStub; } interface RegionalSchemaMap extends SchemaStubMap { Party: SchemaStub; } export function getTestSchemaMap(): { appSchemaMap: AppSchemaMap; regionalSchemaMap: RegionalSchemaMap; } { const appSchemaMap = { Account, JournalEntry, JournalEntryAccount, Party, Customer, } as AppSchemaMap; const regionalSchemaMap = { Party: PartyRegional } as RegionalSchemaMap; return cloneDeep({ appSchemaMap, regionalSchemaMap, }); } export function everyFieldExists(fieldList: string[], schema: Schema): boolean { return fieldsExist(fieldList, schema, 'every'); } export function someFieldExists(fieldList: string[], schema: Schema): boolean { return fieldsExist(fieldList, schema, 'some'); } function fieldsExist( fieldList: string[], schema: Schema, type: 'every' | 'some' ): boolean { const schemaFieldNames = schema.fields.map((f) => f.fieldname); return fieldList.map((f) => schemaFieldNames.includes(f))[type](Boolean); } export function subtract( targetList: string[], ...removalLists: string[][] ): string[] { const removalList = removalLists.flat(); return targetList.filter((f) => !removalList.includes(f)); }
2302_79757062/books
schemas/tests/helpers.ts
TypeScript
agpl-3.0
1,746
import { PropertyEnum } from "utils/types"; export type FieldType = | 'Data' | 'Select' | 'Link' | 'Date' | 'Datetime' | 'Table' | 'AutoComplete' | 'Check' | 'AttachImage' | 'DynamicLink' | 'Int' | 'Float' | 'Currency' | 'Text' | 'Color' | 'Attachment'; export const FieldTypeEnum: PropertyEnum<Record<FieldType, FieldType>> = { Data: 'Data', Select: 'Select', Link: 'Link', Date: 'Date', Datetime: 'Datetime', Table: 'Table', AutoComplete: 'AutoComplete', Check: 'Check', AttachImage: 'AttachImage', DynamicLink: 'DynamicLink', Int: 'Int', Float: 'Float', Currency: 'Currency', Text: 'Text', Color: 'Color', Attachment: 'Attachment', }; type OptionFieldType = 'Select' | 'AutoComplete' | 'Color'; type TargetFieldType = 'Table' | 'Link'; type NumberFieldType = 'Int' | 'Float'; type DynamicLinkFieldType = 'DynamicLink'; type BaseFieldType = Exclude< FieldType, TargetFieldType | DynamicLinkFieldType | OptionFieldType | NumberFieldType >; export type RawValue = string | number | boolean | null; export interface BaseField { fieldname: string; // Column name in the db fieldtype: BaseFieldType; // UI Descriptive field types that map to column types label: string; // Translateable UI facing name schemaName?: string; // Convenient access to schemaName incase just the field is passed required?: boolean; // Implies Not Null hidden?: boolean; // UI Facing config, whether field is shown in a form readOnly?: boolean; // UI Facing config, whether field is editable description?: string; // UI Facing, translateable, used for inline documentation default?: RawValue; // Default value of a field, should match the db type placeholder?: string; // UI Facing config, form field placeholder groupBy?: string; // UI Facing used in dropdowns fields meta?: boolean; // Field is a meta field, i.e. only for the db, not UI filter?: boolean; // UI Facing config, whether to be used to filter the List. computed?: boolean; // Computed values are not stored in the database. section?: string; // UI Facing config, for grouping by sections tab?: string; // UI Facing config, for grouping by tabs abstract?: string; // Used to mark the location of a field in an Abstract schema isCustom?: boolean; // Whether the field is a custom field } export type SelectOption = { value: string; label: string }; export interface OptionField extends Omit<BaseField, 'fieldtype'> { fieldtype: OptionFieldType; options: SelectOption[]; allowCustom?: boolean; } export interface TargetField extends Omit<BaseField, 'fieldtype'> { fieldtype: TargetFieldType; target: string; // Name of the table or group of tables to fetch values create?: boolean; // Whether to show Create in the dropdown edit?: boolean; // Whether the Table has quick editable columns } export interface DynamicLinkField extends Omit<BaseField, 'fieldtype'> { fieldtype: DynamicLinkFieldType; references: string; // Reference to an option field that links to schema } export interface NumberField extends Omit<BaseField, 'fieldtype'> { fieldtype: NumberFieldType; minvalue?: number; // UI Facing used to restrict lower bound maxvalue?: number; // UI Facing used to restrict upper bound } export type Field = | BaseField | OptionField | TargetField | DynamicLinkField | NumberField; export type Naming = 'autoincrement' | 'random' | 'numberSeries' | 'manual'; export interface Schema { name: string; // Table name label: string; // Translateable UI facing name fields: Field[]; // Maps to database columns isTree?: boolean; // Used for nested set, eg for Chart of Accounts extends?: string; // Value points to an Abstract schema. Indicates Subclass schema isChild?: boolean; // Indicates a child table, i.e table with "parent" FK column isSingle?: boolean; // Fields will be values in SingleValue, i.e. an Entity Attr. Value isAbstract?: boolean; // Not entered into db, used to extend a Subclass schema tableFields?: string[] // Used for displaying childTableFields isSubmittable?: boolean; // For transactional types, values considered only after submit keywordFields?: string[]; // Used to get fields that are to be used for search. quickEditFields?: string[]; // Used to get fields for the quickEditForm linkDisplayField?:string; // Display field if inline editable create?: boolean // Whether the user can create an entry from the ListView naming?: Naming; // Used for assigning name, default is 'random' else 'numberSeries' if present titleField?: string; // Main display field removeFields?: string[]; // Used by the builder to remove fields. } export interface SchemaStub extends Partial<Schema> { name: string; } export type SchemaMap = Record<string, Schema | undefined>; export type SchemaStubMap = Record<string, SchemaStub>;
2302_79757062/books
schemas/types.ts
TypeScript
agpl-3.0
5,330
import fs from 'fs/promises'; import path from 'path'; import { UnknownMap } from 'utils/types'; import { generateCSV, parseCSV } from '../utils/csvParser'; import { getIndexFormat, getWhitespaceSanitized, schemaTranslateables, } from '../utils/translationHelpers'; /* eslint-disable no-console, @typescript-eslint/no-floating-promises */ const translationsFolder = path.resolve(__dirname, '..', 'translations'); const PATTERN = /(?<!\w)t`([^`]+)`/g; type Content = { fileName: string; content: string }; function shouldIgnore(p: string, ignoreList: string[]): boolean { const name = p.split(path.sep).at(-1) ?? ''; return ignoreList.includes(name); } async function getFileList( root: string, ignoreList: string[], extPattern = /\.(js|ts|vue)$/ ): Promise<string[]> { const contents: string[] = await fs.readdir(root); const files: string[] = []; const promises: Promise<void>[] = []; for (const c of contents) { const absPath = path.resolve(root, c); const isDir = (await fs.stat(absPath)).isDirectory(); if (isDir && !shouldIgnore(absPath, ignoreList)) { const pr = getFileList(absPath, ignoreList, extPattern).then((fl) => { files.push(...fl); }); promises.push(pr); } else if (absPath.match(extPattern) !== null) { files.push(absPath); } } await Promise.all(promises); return files; } async function getFileContents(fileList: string[]): Promise<Content[]> { const contents: Content[] = []; const promises: Promise<void>[] = []; for (const fileName of fileList) { const pr = fs.readFile(fileName, { encoding: 'utf-8' }).then((content) => { contents.push({ fileName, content }); }); promises.push(pr); } await Promise.all(promises); return contents; } async function getAllTStringsMap( contents: Content[] ): Promise<Map<string, string[]>> { const strings: Map<string, string[]> = new Map(); const promises: Promise<void>[] = []; contents.forEach(({ fileName, content }) => { const pr = getTStrings(content).then((ts) => { if (ts.length === 0) { return; } strings.set(fileName, ts); }); promises.push(pr); }); await Promise.all(promises); return strings; } function getTStrings(content: string): Promise<string[]> { return new Promise((resolve) => { const tStrings = tStringFinder(content); resolve(tStrings); }); } function tStringFinder(content: string): string[] { return [...content.matchAll(PATTERN)].map(([, t]) => { t = getIndexFormat(t); return getWhitespaceSanitized(t); }); } function tStringsToArray( tMap: Map<string, string[]>, tStrings: string[] ): string[] { const tSet: Set<string> = new Set(); for (const k of tMap.keys()) { tMap.get(k)!.forEach((s) => tSet.add(s)); } for (const ts of tStrings) { tSet.add(ts); } return Array.from(tSet).sort(); } function printHelp() { const shouldPrint = process.argv.findIndex((i) => i === '-h') !== -1; if (shouldPrint) { console.log( `Usage: ` + `\tyarn script:translate\n` + `\tyarn script:translate -h\n` + `\tyarn script:translate -l [language_code]\n` + `\n` + `Example: $ yarn script:translate -l de\n` + `\n` + `Description:\n` + `\tPassing a language code will create a '.csv' file in\n` + `\tthe 'translations' subdirectory. Translated strings are to\n` + `\tbe added to this file.\n\n` + `\tCalling the script without args will update the translation csv\n` + `\tfile with new strings if any. Existing translations won't\n` + `\tbe removed.\n` + `\n` + `Parameters:\n` + `\tlanguage_code : An ISO 693-1 code or a locale identifier.\n` + `\n` + `Reference:\n` + `\tISO 693-1 codes: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes\n` + `\tLocale identifier: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation` ); } return shouldPrint; } function getLanguageCode() { const i = process.argv.findIndex((i) => i === '-l'); if (i === -1) { return ''; } return process.argv[i + 1] ?? ''; } function getTranslationFilePath(languageCode: string) { return path.resolve(translationsFolder, `${languageCode}.csv`); } async function regenerateTranslation(tArray: string[], path: string) { // Removes old strings, adds new strings const storedCSV = await fs.readFile(path, { encoding: 'utf-8' }); const storedMatrix = parseCSV(storedCSV); const map: Map<string, string[]> = new Map(); for (const row of storedMatrix) { const tstring = row[0]; map.set(tstring, row.slice(1)); } const matrix = tArray.map((source) => { const stored = map.get(source) ?? []; const translation = stored[0] ?? ''; const context = stored[1] ?? ''; return [source, translation, context]; }); const csv = generateCSV(matrix); await fs.writeFile(path, csv, { encoding: 'utf-8' }); console.log(`\tregenerated: ${path}`); } async function regenerateTranslations(languageCode: string, tArray: string[]) { // regenerate one file if (languageCode.length !== 0) { const path = getTranslationFilePath(languageCode); regenerateTranslation(tArray, path); return; } // regenerate all translation files console.log(`Language code not passed, regenerating all translations.`); for (const filePath of await fs.readdir(translationsFolder)) { if (!filePath.endsWith('.csv')) { continue; } regenerateTranslation(tArray, path.resolve(translationsFolder, filePath)); } } async function writeTranslations(languageCode: string, tArray: string[]) { const path = getTranslationFilePath(languageCode); try { const stat = await fs.stat(path); if (!stat.isFile()) { throw new Error(`${path} is not a translation file`); } console.log( `Existing file found for '${languageCode}': ${path}\n` + `regenerating it's translations.` ); regenerateTranslations(languageCode, tArray); } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') { throw err; } const matrix = tArray.map((s) => [s, '', '']); const csv = generateCSV(matrix); await fs.writeFile(path, csv, { encoding: 'utf-8' }); console.log(`Generated translation file for '${languageCode}': ${path}`); } } async function getTStringsFromJsonFileList( fileList: string[] ): Promise<string[]> { const promises: Promise<void>[] = []; const schemaTStrings: string[][] = []; for (const filePath of fileList) { const promise = fs .readFile(filePath, { encoding: 'utf8' }) .then((content) => { const schema = JSON.parse(content) as Record<string, unknown>; const tStrings: string[] = []; pushTStringsFromSchema(schema, tStrings, schemaTranslateables); return tStrings; }) .then((ts) => { schemaTStrings.push(ts); }); promises.push(promise); } await Promise.all(promises); return schemaTStrings.flat(); } function pushTStringsFromSchema( map: UnknownMap | UnknownMap[], array: string[], translateables: string[] ) { if (Array.isArray(map)) { for (const item of map) { pushTStringsFromSchema(item, array, translateables); } return; } if (typeof map !== 'object') { return; } for (const key of Object.keys(map)) { const value = map[key]; if (translateables.includes(key) && typeof value === 'string') { array.push(value); } if (typeof value !== 'object') { continue; } pushTStringsFromSchema( value as UnknownMap | UnknownMap[], array, translateables ); } } async function getSchemaTStrings() { const root = path.resolve(__dirname, '../schemas'); const fileList = await getFileList(root, ['tests', 'regional'], /\.json$/); return await getTStringsFromJsonFileList(fileList); } async function run() { if (printHelp()) { return; } const root = path.resolve(__dirname, '..'); const ignoreList = ['node_modules', 'dist_electron', 'scripts']; const languageCode = getLanguageCode(); console.log(); const fileList: string[] = await getFileList(root, ignoreList); const contents: Content[] = await getFileContents(fileList); const tMap: Map<string, string[]> = await getAllTStringsMap(contents); const schemaTStrings: string[] = await getSchemaTStrings(); const tArray: string[] = tStringsToArray(tMap, schemaTStrings); try { await fs.stat(translationsFolder); } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') { throw err; } await fs.mkdir(translationsFolder); } if (languageCode === '') { regenerateTranslations('', tArray); return; } writeTranslations(languageCode, tArray); } run();
2302_79757062/books
scripts/generateTranslations.ts
TypeScript
agpl-3.0
8,929
#! /usr/bin/env zsh # https://nodejs.org/en/docs/guides/simple-profiling/ export TS_NODE_COMPILER_OPTIONS='{"module":"commonjs"}' rm ./isolate-*-v8.log 2> /dev/null rm ./profiler-output.log 2> /dev/null export ELECTRON_RUN_AS_NODE=true alias electron_node=./node_modules/.bin/electron echo "running profile.ts" electron_node --require ts-node/register --require tsconfig-paths/register --prof ./scripts/profile.ts echo "processing tick file" electron_node --prof-process ./isolate-*-v8.log > ./profiler-output.log && echo "generated profiler-output.log" rm ./isolate-*-v8.log
2302_79757062/books
scripts/profile.sh
Shell
agpl-3.0
581
import { DatabaseManager } from 'backend/database/manager'; import { setupDummyInstance } from 'dummy'; import { unlink } from 'fs/promises'; import { Fyo } from 'fyo'; import { DummyAuthDemux } from 'fyo/tests/helpers'; import { getTestDbPath } from 'tests/helpers'; async function run() { const fyo = new Fyo({ DatabaseDemux: DatabaseManager, AuthDemux: DummyAuthDemux, isTest: true, isElectron: false, }); const dbPath = getTestDbPath(); await setupDummyInstance(dbPath, fyo, 1, 100); await fyo.close(); await unlink(dbPath); } // eslint-disable-next-line @typescript-eslint/no-floating-promises run();
2302_79757062/books
scripts/profile.ts
TypeScript
agpl-3.0
637
# #! /bin/zsh set -e # Check node and yarn versions YARN_VERSION=$(yarn --version) if [ "$YARN_VERSION" != "1.22.18" ]; then echo "Incorrect yarn version: $YARN_VERSION" exit 1 fi # Source secrets source .env.publish # Create folder for the publish build cd ../ rm -rf build_publish mkdir build_publish cd build_publish # Clone and cd into books git clone https://github.com/frappe/books --depth 1 cd books # Copy creds to log_creds.txt echo $ERR_LOG_KEY > log_creds.txt echo $ERR_LOG_SECRET >> log_creds.txt echo $ERR_LOG_URL >> log_creds.txt echo $TELEMETRY_URL >> log_creds.txt # Install Dependencies yarn install # Set .env and build export GH_TOKEN=$GH_TOKEN && export CSC_IDENTITY_AUTO_DISCOVERY=true && export APPLE_ID=$APPLE_ID && export APPLE_TEAM_ID=$APPLE_TEAM_ID && export APPLE_APP_SPECIFIC_PASSWORD=$APPLE_APP_SPECIFIC_PASSWORD && yarn build --mac --publish=always cd ../books
2302_79757062/books
scripts/publish-mac-arm.sh
Shell
agpl-3.0
910
#! /usr/bin/env zsh # basically uses electron's node to prevent # mismatch in NODE_MODULE_VERSION when running # better-sqlite3 export TS_NODE_COMPILER_OPTIONS='{"module":"commonjs"}' export ELECTRON_RUN_AS_NODE=true alias electron_node="./node_modules/.bin/electron --require ts-node/register --require tsconfig-paths/register" electron_node $@
2302_79757062/books
scripts/runner.sh
Shell
agpl-3.0
347
TEST_PATH=$@ if [ $# -eq 0 ] then TEST_PATH=./**/tests/**/*.spec.ts fi export IS_TEST=true ./scripts/runner.sh ./node_modules/.bin/tape $TEST_PATH | ./node_modules/.bin/tap-spec
2302_79757062/books
scripts/test.sh
Shell
agpl-3.0
185
<template> <div id="app" class=" dark:bg-gray-900 h-screen flex flex-col font-sans overflow-hidden antialiased " :dir="languageDirection" :language="language" > <WindowsTitleBar v-if="platform === 'Windows'" :db-path="dbPath" :company-name="companyName" /> <!-- Main Contents --> <Desk v-if="activeScreen === 'Desk'" class="flex-1" :darkMode="darkMode" @change-db-file="showDbSelector" /> <DatabaseSelector v-if="activeScreen === 'DatabaseSelector'" ref="databaseSelector" @new-database="newDatabase" @file-selected="fileSelected" /> <SetupWizard v-if="activeScreen === 'SetupWizard'" @setup-complete="setupComplete" @setup-canceled="showDbSelector" /> <!-- Render target for toasts --> <div id="toast-container" class="absolute bottom-0 flex flex-col items-end mb-3 pe-6" style="width: 100%; pointer-events: none" ></div> </div> </template> <script lang="ts"> import { RTL_LANGUAGES } from 'fyo/utils/consts'; import { ModelNameEnum } from 'models/types'; import { systemLanguageRef } from 'src/utils/refs'; import { defineComponent, provide, ref, Ref } from 'vue'; import WindowsTitleBar from './components/WindowsTitleBar.vue'; import { handleErrorWithDialog } from './errorHandling'; import { fyo } from './initFyo'; import DatabaseSelector from './pages/DatabaseSelector.vue'; import Desk from './pages/Desk.vue'; import SetupWizard from './pages/SetupWizard/SetupWizard.vue'; import setupInstance from './setup/setupInstance'; import { SetupWizardOptions } from './setup/types'; import './styles/index.css'; import { connectToDatabase, dbErrorActionSymbols } from './utils/db'; import { initializeInstance } from './utils/initialization'; import * as injectionKeys from './utils/injectionKeys'; import { showDialog } from './utils/interactive'; import { setLanguageMap } from './utils/language'; import { updateConfigFiles } from './utils/misc'; import { updatePrintTemplates } from './utils/printTemplates'; import { Search } from './utils/search'; import { Shortcuts } from './utils/shortcuts'; import { routeTo } from './utils/ui'; import { useKeys } from './utils/vueUtils'; import { setDarkMode } from 'src/utils/theme'; enum Screen { Desk = 'Desk', DatabaseSelector = 'DatabaseSelector', SetupWizard = 'SetupWizard', } export default defineComponent({ name: 'App', components: { Desk, SetupWizard, DatabaseSelector, WindowsTitleBar, }, setup() { const keys = useKeys(); const searcher: Ref<null | Search> = ref(null); const shortcuts = new Shortcuts(keys); const languageDirection = ref( getLanguageDirection(systemLanguageRef.value) ); provide(injectionKeys.keysKey, keys); provide(injectionKeys.searcherKey, searcher); provide(injectionKeys.shortcutsKey, shortcuts); provide(injectionKeys.languageDirectionKey, languageDirection); const databaseSelector = ref<InstanceType<typeof DatabaseSelector> | null>( null ); return { keys, searcher, shortcuts, languageDirection, databaseSelector, }; }, data() { return { activeScreen: null, dbPath: '', companyName: '', darkMode: false, } as { activeScreen: null | Screen; dbPath: string; companyName: string; darkMode: boolean | undefined; }; }, computed: { language(): string { return systemLanguageRef.value; }, }, watch: { language(value: string) { this.languageDirection = getLanguageDirection(value); }, }, async mounted() { await this.setInitialScreen(); const { darkMode } = await fyo.doc.getDoc('SystemSettings'); setDarkMode(!!darkMode); this.darkMode = !!darkMode; }, methods: { async setInitialScreen(): Promise<void> { const lastSelectedFilePath = fyo.config.get('lastSelectedFilePath', null); if ( typeof lastSelectedFilePath !== 'string' || !lastSelectedFilePath.length ) { this.activeScreen = Screen.DatabaseSelector; return; } await this.fileSelected(lastSelectedFilePath); }, async setSearcher(): Promise<void> { this.searcher = new Search(fyo); await this.searcher.initializeKeywords(); }, async setDesk(filePath: string): Promise<void> { await setLanguageMap(); this.activeScreen = Screen.Desk; await this.setDeskRoute(); await fyo.telemetry.start(true); await ipc.checkForUpdates(); this.dbPath = filePath; this.companyName = (await fyo.getValue( ModelNameEnum.AccountingSettings, 'companyName' )) as string; await this.setSearcher(); updateConfigFiles(fyo); }, newDatabase() { this.activeScreen = Screen.SetupWizard; }, async fileSelected(filePath: string): Promise<void> { fyo.config.set('lastSelectedFilePath', filePath); if (filePath !== ':memory:' && !(await ipc.checkDbAccess(filePath))) { await showDialog({ title: this.t`Cannot open file`, type: 'error', detail: this .t`Frappe Books does not have access to the selected file: ${filePath}`, }); fyo.config.set('lastSelectedFilePath', null); return; } try { await this.showSetupWizardOrDesk(filePath); } catch (error) { await handleErrorWithDialog(error, undefined, true, true); await this.showDbSelector(); } }, async setupComplete(setupWizardOptions: SetupWizardOptions): Promise<void> { const companyName = setupWizardOptions.companyName; const filePath = await ipc.getDbDefaultPath(companyName); await setupInstance(filePath, setupWizardOptions, fyo); fyo.config.set('lastSelectedFilePath', filePath); await this.setDesk(filePath); }, async showSetupWizardOrDesk(filePath: string): Promise<void> { const { countryCode, error, actionSymbol } = await connectToDatabase( this.fyo, filePath ); if (!countryCode && error && actionSymbol) { return await this.handleConnectionFailed(error, actionSymbol); } const setupComplete = await fyo.getValue( ModelNameEnum.AccountingSettings, 'setupComplete' ); if (!setupComplete) { this.activeScreen = Screen.SetupWizard; return; } await initializeInstance(filePath, false, countryCode, fyo); await updatePrintTemplates(fyo); await this.setDesk(filePath); }, async handleConnectionFailed(error: Error, actionSymbol: symbol) { await this.showDbSelector(); if (actionSymbol === dbErrorActionSymbols.CancelSelection) { return; } if (actionSymbol === dbErrorActionSymbols.SelectFile) { await this.databaseSelector?.existingDatabase(); return; } throw error; }, async setDeskRoute(): Promise<void> { const { onboardingComplete } = await fyo.doc.getDoc('GetStarted'); const { hideGetStarted } = await fyo.doc.getDoc('SystemSettings'); let route = '/get-started'; if (hideGetStarted || onboardingComplete) { route = localStorage.getItem('lastRoute') || '/'; } await routeTo(route); }, async showDbSelector(): Promise<void> { localStorage.clear(); fyo.config.set('lastSelectedFilePath', null); fyo.telemetry.stop(); await fyo.purgeCache(); this.activeScreen = Screen.DatabaseSelector; this.dbPath = ''; this.searcher = null; this.companyName = ''; }, }, }); function getLanguageDirection(language: string): 'rtl' | 'ltr' { return RTL_LANGUAGES.includes(language) ? 'rtl' : 'ltr'; } </script>
2302_79757062/books
src/App.vue
Vue
agpl-3.0
7,914
<template> <div class="rounded-full overflow-hidden" :class="sizeClasses"> <img v-if="imageURL" :src="imageURL" class="object-cover" :class="sizeClasses" /> <div v-else class=" bg-gray-500 flex h-full items-center justify-center text-white dark:text-gray-900 w-full text-base uppercase " > {{ label && label[0] }} </div> </div> </template> <script> export default { name: 'Avatar', props: { imageURL: String, label: String, size: { default: 'md', }, }, computed: { sizeClasses() { return { sm: 'w-5 h-5', md: 'w-7 h-7', lg: 'w-9 h-9', }[this.size]; }, }, }; </script>
2302_79757062/books
src/components/Avatar.vue
Vue
agpl-3.0
797
<template> <div class="inline-block rounded-md px-2 py-1 truncate select-none" :class="colorClass" > <slot></slot> </div> </template> <script> import { getBgTextColorClass } from 'src/utils/colors'; export default { name: 'Badge', props: { color: { default: 'gray', }, }, computed: { colorClass() { return getBgTextColorClass(this.color); }, }, }; </script>
2302_79757062/books
src/components/Badge.vue
Vue
agpl-3.0
416
<template> <button class="rounded-md flex justify-center items-center text-sm" :disabled="disabled" :class="_class" v-bind="$attrs" > <slot></slot> </button> </template> <script lang="ts"> import { defineComponent } from 'vue'; export default defineComponent({ name: 'Button', props: { type: { type: String, default: 'secondary', }, icon: { type: Boolean, default: false, }, disabled: { type: Boolean, default: false, }, padding: { type: Boolean, default: true, }, background: { type: Boolean, default: true, }, }, computed: { _class() { return { 'opacity-50 cursor-not-allowed pointer-events-none': this.disabled, 'text-white dark:text-black': this.type === 'primary', 'bg-black dark:bg-gray-300 dark:font-semibold': this.type === 'primary' && this.background, 'text-gray-700 dark:text-gray-200': this.type !== 'primary', 'bg-gray-200 dark:bg-gray-900': this.type !== 'primary' && this.background, 'h-8': this.background, 'px-3': this.padding && this.icon, 'px-6': this.padding && !this.icon, }; }, }, }); </script> <style scoped> button:focus { filter: brightness(0.95); } </style>
2302_79757062/books
src/components/Button.vue
Vue
agpl-3.0
1,327
<template> <div> <svg ref="chartSvg" :viewBox="`0 0 ${viewBoxWidth} ${viewBoxHeight}`" xmlns="http://www.w3.org/2000/svg" > <!-- x Grid Lines --> <path v-if="drawXGrid" :d="xGrid" :stroke="gridColor" :stroke-width="gridThickness" stroke-linecap="round" fill="transparent" /> <!-- zero line --> <path v-if="drawZeroLine" :d="zLine" :stroke="zeroLineColor" :stroke-width="gridThickness" stroke-linecap="round" fill="transparent" /> <!-- Axis --> <path v-if="drawAxis" :d="axis" :stroke-width="axisThickness" :stroke="axisColor" fill="transparent" /> <!-- x Labels --> <template v-if="xLabels.length > 0"> <text v-for="(i, j) in count" :key="j + '-xlabels'" :style="fontStyle" :y=" viewBoxHeight - axisPadding + yLabelOffset + fontStyle.fontSize / 2 - bottom " :x="xs[i - 1]" text-anchor="middle" > {{ j % skipXLabel === 0 ? formatX(xLabels[i - 1] || '') : '' }} </text> </template> <!-- y Labels --> <template v-if="yLabelDivisions > 0"> <text v-for="(i, j) in yLabelDivisions + 1" :key="j + '-ylabels'" :style="fontStyle" :y="yScalerLocation(i - 1)" :x="axisPadding - xLabelOffset + left" text-anchor="end" > {{ yScalerValue(i - 1) }} </text> </template> <defs> <clipPath id="positive-rect-clip"> <rect x="0" y="0" :width="viewBoxWidth" :height="z" /> </clipPath> <clipPath id="negative-rect-clip"> <rect x="0" :y="z" :width="viewBoxWidth" :height="viewBoxHeight - z" /> </clipPath> </defs> <rect v-for="(rec, i) in positiveRects" :key="i + 'prec'" :rx="radius" :ry="radius" :x="rec.x" :y="rec.y" :width="width" :height="rec.height" :fill="rec.color" clip-path="url(#positive-rect-clip)" @mouseenter="() => create(rec.xi, rec.yi)" @mousemove="update" @mouseleave="destroy" /> <rect v-for="(rec, i) in negativeRects" :key="i + 'nrec'" :rx="radius" :ry="radius" :x="rec.x" :y="rec.y" :width="width" :height="rec.height" :fill="rec.color" clip-path="url(#negative-rect-clip)" @mouseenter="() => create(rec.xi, rec.yi)" @mousemove="update" @mouseleave="destroy" /> </svg> <Tooltip ref="tooltip" :offset="15" placement="top" class=" text-sm shadow-md px-2 py-1 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-200 border-s-4 " :style="{ borderColor: activeColor }" > <div class="flex flex-col justify-center items-center"> <p> {{ xi > -1 ? formatX(xLabels[xi]) : '' }} </p> <p class="font-semibold"> {{ yi > -1 ? format(points[yi][xi]) : '' }} </p> </div> </Tooltip> </div> </template> <script> import { prefixFormat } from 'src/utils/chart'; import Tooltip from '../Tooltip.vue'; export default { components: { Tooltip }, props: { skipXLabel: { type: Number, default: 2 }, colors: { type: Array, default: () => [] }, xLabels: { type: Array, default: () => [] }, yLabelDivisions: { type: Number, default: 4 }, points: { type: Array, default: () => [[]] }, drawAxis: { type: Boolean, default: false }, drawXGrid: { type: Boolean, default: true }, viewBoxHeight: { type: Number, default: 500 }, aspectRatio: { type: Number, default: 2.1 }, axisPadding: { type: Number, default: 30 }, pointsPadding: { type: Number, default: 40 }, xLabelOffset: { type: Number, default: 20 }, yLabelOffset: { type: Number, default: 0 }, gridColor: { type: String, default: 'rgba(0, 0, 0, 0.2)' }, zeroLineColor: { type: String, default: 'rgba(0, 0, 0, 0.2)' }, axisColor: { type: String, default: 'rgba(0, 0, 0, 0.5)' }, axisThickness: { type: Number, default: 1 }, gridThickness: { type: Number, default: 0.5 }, yMin: { type: Number, default: null }, yMax: { type: Number, default: null }, format: { type: Function, default: (n) => n.toFixed(1) }, formatY: { type: Function, default: prefixFormat }, formatX: { type: Function, default: (v) => v }, fontSize: { type: Number, default: 22 }, fontColor: { type: String, default: '#415668' }, bottom: { type: Number, default: 0 }, width: { type: Number, default: 28 }, left: { type: Number, default: 65 }, radius: { type: Number, default: 17 }, extendGridX: { type: Number, default: -20 }, tooltipDispDistThreshold: { type: Number, default: 20 }, drawZeroLine: { type: Boolean, default: true }, }, data() { return { xi: -1, yi: -1, activeColor: 'rgba(0, 0, 0, 0.2)' }; }, computed: { fontStyle() { return { fontSize: this.fontSize, fill: this.fontColor }; }, viewBoxWidth() { return this.aspectRatio * this.viewBoxHeight; }, num() { return this.points.length; }, count() { return Math.max(...this.points.map((p) => p.length)); }, xs() { return Array(this.count) .fill() .map( (_, i) => this.padding + this.left + (i * (this.viewBoxWidth - this.left - 2 * this.padding)) / (this.count - 1 || 1) // The "or" one (1) prevents accidentally dividing by 0 ); }, z() { return this.getViewBoxY(0); }, ys() { return this.points.map((pp) => pp.map(this.getViewBoxY)); }, xy() { return this.xs.map((x, i) => [x, this.ys.map((y) => y[i])]); }, min() { return Math.min(...this.points.flat()); }, max() { return Math.max(...this.points.flat()); }, axis() { return `M ${this.axisPadding + this.left} ${this.axisPadding} V ${ this.viewBoxHeight - this.axisPadding - this.bottom } H ${this.viewBoxWidth - this.axisPadding}`; }, padding() { return this.axisPadding + this.pointsPadding; }, xGrid() { const { l, r } = this.xLims; const lo = l + this.extendGridX; const ro = r - this.extendGridX; const ys = Array(this.yLabelDivisions + 1) .fill() .map((_, i) => this.yScalerLocation(i)); return ys.map((y) => `M ${lo} ${y} H ${ro}`).join(' '); }, yGrid() { return []; }, zLine() { const { l, r } = this.xLims; const lo = l + this.extendGridX; const ro = r - this.extendGridX; return `M ${lo} ${this.z} H ${ro}`; }, xLims() { const l = this.padding + this.left; const r = this.viewBoxWidth - this.padding; return { l, r }; }, positiveRects() { return this.rects.flat().filter(({ isPositive }) => isPositive); }, negativeRects() { return this.rects.flat().filter(({ isPositive }) => !isPositive); }, rects() { return this.xy.map(([x, ys], i) => ys.map((y, j) => this.getRect(x, y, i, j)) ); }, hMin() { return Math.min(this.yMin ?? this.min, 0); }, hMax() { let hMax = Math.max(this.yMax ?? this.max, 0); if (hMax === this.hMin) { return hMax + 1000; } return hMax; }, }, methods: { gradY(i) { return Math.min(...this.ys[i]).toFixed(); }, getViewBoxY(value) { const min = this.hMin; const max = this.hMax; let percent = 1 - (value - min) / (max - min); if (percent === -Infinity) { percent = 0; } return ( this.padding + percent * (this.viewBoxHeight - 2 * this.padding - this.bottom) ); }, getRect(px, py, i, j) { const isPositive = py <= this.z; const x = px - (this.width * this.num) / 2 + j * this.width; const y = isPositive ? py : this.z - this.radius; const h = Math.abs(py - this.z); const height = h + this.radius; const color = this.getColor(j, isPositive); return { x, y, height, color, isPositive, xi: i, yi: j }; }, getColor(j, isPositive) { if (this.colors.length > 0) { const c = this.colors[j]; return typeof c === 'string' ? c : c[isPositive ? 'positive' : 'negative']; } return this.getRandomColor(); }, yScalerLocation(i) { return ( ((this.yLabelDivisions - i) * (this.viewBoxHeight - this.padding * 2 - this.bottom)) / this.yLabelDivisions + this.padding ); }, yScalerValue(i) { const min = this.hMin; const max = this.hMax; return this.formatY((i * (max - min)) / this.yLabelDivisions + min); }, getLine(i) { const [x, y] = this.xy[0]; let d = `M ${x} ${y[i]} `; this.xy.slice(1).forEach(([x, y]) => { d += `L ${x} ${y[i]} `; }); return d; }, getGradLine(i) { let bo = this.viewBoxHeight - this.padding - this.bottom; let d = `M ${this.padding + this.left} ${bo}`; this.xy.forEach(([x, y]) => { d += `L ${x} ${y[i]} `; }); return d + ` V ${bo} Z`; }, getRandomColor() { const rgb = Array(3) .fill() .map(() => parseInt(Math.random() * 255)) .join(','); return `rgb(${rgb})`; }, create(xi, yi) { this.xi = xi; this.yi = yi; this.activeColor = this.getColor(yi, this.points[yi][xi] > 0); this.$refs.tooltip.create(); }, update(event) { this.$refs.tooltip.update(event); }, destroy() { this.xi = -1; this.yi = -1; this.$refs.tooltip.destroy(); }, }, }; </script> <style scoped> rect:hover { filter: brightness(105%); } </style>
2302_79757062/books
src/components/Charts/BarChart.vue
Vue
agpl-3.0
10,260
<template> <div> <svg version="1.1" viewBox="0 0 100 100" @mouseleave="$emit('change', null)" > <defs> <clipPath id="donut-hole"> <circle :cx="cx" :cy="cy" :r="radius + thickness / 2" fill="black" stroke-width="0" /> </clipPath> </defs> <circle v-if="thetasAndStarts.length === 1 || thetasAndStarts.length === 0" clip-path="url(#donut-hole)" :cx="cx" :cy="cy" :r="radius" :stroke-width=" thickness + (hasNonZeroValues && active === thetasAndStarts[0][0] ? 4 : 0) " :stroke=" hasNonZeroValues ? sectors[thetasAndStarts[0][0]].color : '#f4f4f6' " :class="hasNonZeroValues ? 'sector' : ''" :style="{ transformOrigin: `${cx}px ${cy}px` }" fill="transparent" @mouseover=" $emit( 'change', thetasAndStarts.length === 1 ? thetasAndStarts[0][0] : null ) " /> <template v-if="thetasAndStarts.length > 1"> <path v-for="[i, theta, start_] in thetasAndStarts" :key="i" clip-path="url(#donut-hole)" :d="getArcPath(cx, cy, radius, start_, theta)" :stroke="getSectorColor(i)" :stroke-width="thickness + (active === i ? 4 : 0)" :style="{ transformOrigin: `${cx}px ${cy}px` }" class="sector" fill="transparent" @mouseover="$emit('change', i)" /> </template> <text :x="cx" :y="cy" text-anchor="middle" :style="{ fontSize: '6px', fontWeight: 'bold', fill: darkMode ? '#FFFFFF' : '#415668', }" > {{ valueFormatter( active !== null && sectors.length !== 0 ? sectors[active].value : totalValue, 'Currency' ) }} </text> <text :x="cx" :y="cy + 8" text-anchor="middle" style="font-size: 5px; fill: #a1abb4" > {{ active !== null && sectors.length !== 0 ? sectors[active].label : totalLabel }} </text> </svg> </div> </template> <script> export default { props: { sectors: { default: () => [], type: Array, }, totalLabel: { default: 'Total', type: String }, radius: { default: 36, type: Number }, startAngle: { default: Math.PI, type: Number }, thickness: { default: 10, type: Number }, active: { default: null, type: Number }, valueFormatter: { default: (v) => v.toString(), Function }, offsetX: { default: 0, type: Number }, offsetY: { default: 0, type: Number }, textOffsetX: { default: 0, type: Number }, textOffsetY: { default: 0, type: Number }, darkMode: { type: Boolean, default: false }, }, emits: ['change'], computed: { cx() { return 50 + this.offsetX; }, cy() { return 50 + this.offsetY; }, totalValue() { return this.sectors.map(({ value }) => value).reduce((a, b) => a + b, 0); }, thetasAndStarts() { const thetas = this.sectors .map(({ value }, i) => ({ value: (2 * Math.PI * value) / this.totalValue, filterOut: value !== 0, i, })) .filter(({ filterOut }) => filterOut); const starts = [...thetas.map(({ value }) => value)]; starts.forEach(({ value }, i) => { starts[i] += starts[i - 1] ?? 0; }); starts.unshift(0); starts.pop(); return thetas.map((t, i) => [t.i, t.value, starts[i]]); }, hasNonZeroValues() { return this.thetasAndStarts.some((t) => this.sectors[t[0]].value !== 0); }, }, methods: { getArcPath(...args) { let [cx, cy, r, start, theta] = args.map(parseFloat); start += parseFloat(this.startAngle); const startX = cx + r * Math.cos(start); const startY = cy + r * Math.sin(start); const endX = cx + r * Math.cos(start + theta); const endY = cy + r * Math.sin(start + theta); const largeArcFlag = theta > Math.PI ? 1 : 0; const sweepFlag = 1; return `M ${startX} ${startY} A ${r} ${r} 0 ${largeArcFlag} ${sweepFlag} ${endX} ${endY}`; }, getSectorColor(index) { if (this.darkMode) { return this.sectors[index].color.darkColor; } else { return this.sectors[index].color.color; } }, }, }; </script> <style scoped> .sector { transition: 100ms stroke-width ease-out; } </style>
2302_79757062/books
src/components/Charts/DonutChart.vue
Vue
agpl-3.0
4,678
<template> <div> <svg ref="chartSvg" :viewBox="`0 0 ${viewBoxWidth} ${viewBoxHeight}`" xmlns="http://www.w3.org/2000/svg" @mousemove="update" > <!-- x Grid Lines --> <path v-if="drawXGrid" :d="xGrid" :stroke="gridColor" :stroke-width="gridThickness" stroke-linecap="round" fill="transparent" /> <!-- Axis --> <path v-if="drawAxis" :d="axis" :stroke-width="axisThickness" :stroke="axisColor" fill="transparent" /> <!-- x Labels --> <template v-if="drawLabels && xLabels.length > 0"> <text v-for="(i, j) in count" :key="j + '-xlabels'" :style="fontStyle" :y=" viewBoxHeight - axisPadding + yLabelOffset + fontStyle.fontSize / 2 - bottom " :x="xs[i - 1]" text-anchor="middle" > {{ formatX(xLabels[i - 1] || '') }} </text> </template> <!-- y Labels --> <template v-if="drawLabels && yLabelDivisions > 0"> <text v-for="(i, j) in yLabelDivisions + 1" :key="j + '-ylabels'" :style="fontStyle" :y="yScalerLocation(i - 1)" :x="axisPadding - xLabelOffset + left" text-anchor="end" > {{ yScalerValue(i - 1) }} </text> </template> <!-- Gradient Mask --> <defs> <linearGradient id="grad" x1="0" y1="0" x2="0" y2="85%"> <stop offset="0%" stop-color="rgba(255, 255, 255, 0.5)" /> <stop offset="40%" stop-color="rgba(255, 255, 255, 0.1)" /> <stop offset="70%" stop-color="rgba(255, 255, 255, 0)" /> </linearGradient> <mask v-for="(i, j) in num" :id="'rect-mask-' + i" :key="j + '-mask'"> <rect x="0" :y="gradY(j)" :height="viewBoxHeight - gradY(j)" width="100%" fill="url('#grad')" /> </mask> </defs> <g v-for="(i, j) in num" :key="j + '-gpath'"> <!-- Gradient Paths --> <path stroke-linejoin="round" :d="getGradLine(i - 1)" :stroke-width="thickness" stroke-linecap="round" :fill="colors[i - 1] || getRandomColor()" :mask="`url('#rect-mask-${i}')`" /> <!-- Lines --> <path stroke-linejoin="round" :d="getLine(i - 1)" :stroke="colors[i - 1] || getRandomColor()" :stroke-width="thickness" stroke-linecap="round" fill="transparent" /> </g> <!-- Tooltip Reference --> <circle v-if="xi > -1 && yi > -1" r="12" :cx="cx" :cy="cy" :fill="colors[yi]" style=" filter: brightness(115%) drop-shadow(0px 2px 3px rgba(0, 0, 0, 0.25)); " /> </svg> <Tooltip v-if="showTooltip" ref="tooltip" :offset="15" placement="top" class=" text-sm shadow-md px-2 py-1 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-200 border-s-4 " :style="{ borderColor: colors[yi] }" > <div class="flex flex-col justify-center items-center"> <p> {{ xi > -1 ? formatX(xLabels[xi]) : '' }} </p> <p class="font-semibold"> {{ yi > -1 ? format(points[yi][xi]) : '' }} </p> </div> </Tooltip> </div> </template> <script> import { euclideanDistance, prefixFormat } from 'src/utils/chart'; import Tooltip from '../Tooltip.vue'; export default { components: { Tooltip }, props: { colors: { type: Array, default: () => [] }, xLabels: { type: Array, default: () => [] }, yLabelDivisions: { type: Number, default: 4 }, points: { type: Array, default: () => [[]] }, drawAxis: { type: Boolean, default: false }, drawXGrid: { type: Boolean, default: true }, drawLabels: { type: Boolean, default: true }, viewBoxHeight: { type: Number, default: 500 }, aspectRatio: { type: Number, default: 4 }, axisPadding: { type: Number, default: 30 }, pointsPadding: { type: Number, default: 24 }, xLabelOffset: { type: Number, default: 20 }, yLabelOffset: { type: Number, default: 5 }, gridColor: { type: String, default: 'rgba(0, 0, 0, 0.2)' }, axisColor: { type: String, default: 'rgba(0, 0, 0, 0.5)' }, thickness: { type: Number, default: 5 }, axisThickness: { type: Number, default: 1 }, gridThickness: { type: Number, default: 0.5 }, yMin: { type: Number, default: null }, yMax: { type: Number, default: null }, format: { type: Function, default: (n) => n.toFixed(1) }, formatY: { type: Function, default: prefixFormat }, formatX: { type: Function, default: (v) => v }, fontSize: { type: Number, default: 20 }, fontColor: { type: String, default: '#415668' }, bottom: { type: Number, default: 0 }, left: { type: Number, default: 55 }, extendGridX: { type: Number, default: -20 }, tooltipDispDistThreshold: { type: Number, default: 40 }, showTooltip: { type: Boolean, default: true }, }, data() { return { cx: -1, cy: -1, xi: -1, yi: -1 }; }, computed: { fontStyle() { return { fontSize: this.fontSize, fill: this.fontColor }; }, viewBoxWidth() { return this.aspectRatio * this.viewBoxHeight; }, num() { return this.points.length; }, count() { return Math.max(...this.points.map((p) => p.length)); }, xs() { return Array(this.count) .fill() .map( (_, i) => this.padding + this.left + (i * (this.viewBoxWidth - this.left - 2 * this.padding)) / (this.count - 1 || 1) // The "or" one (1) prevents accidentally dividing by 0 ); }, ys() { const min = this.hMin; const max = this.hMax; return this.points.map((pp) => pp.map( (p) => this.padding + (1 - (p - min) / (max - min)) * (this.viewBoxHeight - 2 * this.padding - this.bottom) ) ); }, xy() { return this.xs.map((x, i) => [x, this.ys.map((y) => y[i])]); }, min() { return Math.min(...this.points.flat()); }, max() { return Math.max(...this.points.flat()); }, axis() { return `M ${this.axisPadding + this.left} ${this.axisPadding} V ${ this.viewBoxHeight - this.axisPadding - this.bottom } H ${this.viewBoxWidth - this.axisPadding}`; }, padding() { return this.axisPadding + this.pointsPadding; }, xGrid() { const { l, r } = this.xLims; const lo = l + this.extendGridX; const ro = r - this.extendGridX; const ys = Array(this.yLabelDivisions + 1) .fill() .map((_, i) => this.yScalerLocation(i)); return ys.map((y) => `M ${lo} ${y} H ${ro}`).join(' '); }, yGrid() { return []; }, xLims() { const l = this.padding + this.left; const r = this.viewBoxWidth - this.padding; return { l, r }; }, hMin() { return Math.min(this.yMin ?? this.min, 0); }, hMax() { let hMax = Math.max(this.yMax ?? this.max, 0); if (hMax === this.hMin) { return hMax + 1000; } return hMax; }, }, methods: { gradY(i) { return Math.min(...this.ys[i]).toFixed(); }, yScalerLocation(i) { return ( ((this.yLabelDivisions - i) * (this.viewBoxHeight - this.padding * 2 - this.bottom)) / this.yLabelDivisions + this.padding ); }, yScalerValue(i) { const min = this.hMin; const max = this.hMax; return this.formatY((i * (max - min)) / this.yLabelDivisions + min); }, getLine(i) { const [x, y] = this.xy[0]; let d = `M ${x} ${y[i]} `; this.xy.slice(1).forEach(([x, y]) => { d += `L ${x} ${y[i]} `; }); return d; }, getGradLine(i) { let bo = this.viewBoxHeight - this.padding - this.bottom; let d = `M ${this.padding + this.left} ${bo}`; this.xy.forEach(([x, y]) => { d += `L ${x} ${y[i]} `; }); return d + ` V ${bo} Z`; }, getRandomColor() { const rgb = Array(3) .fill() .map(() => parseInt(Math.random() * 255)) .join(','); return `rgb(${rgb})`; }, update(event) { if (!this.showTooltip) { return; } const { x, y } = this.getSvgXY(event); const { xi, yi, cx, cy, d } = this.getPointIndexAndCoords(x, y); if (d > this.tooltipDispDistThreshold) { this.xi = -1; this.yi = -1; this.cx = -1; this.cy = -1; this.$refs.tooltip.destroy(); return; } this.$refs.tooltip.create(); this.xi = xi; this.yi = yi; this.cx = cx; this.cy = cy; this.$refs.tooltip.update(event); }, getSvgXY({ clientX, clientY }) { const inv = this.$refs.chartSvg.getScreenCTM().inverse(); const point = new DOMPoint(clientX, clientY); const { x, y } = point.matrixTransform(inv); return { x, y }; }, getPointIndexAndCoords(x, y) { const { l, r } = this.xLims; const xi = Math.round((x - l) / ((r - l) / (this.count - 1))); if (xi < 0 || xi > this.count - 1) { return { d: this.tooltipDispDistThreshold + 1 }; } const px = this.xs[xi]; const pys = this.ys.map((yarr) => yarr[xi]); const dists = pys.map((py) => euclideanDistance(x, y, px, py)); const minDist = Math.min(...dists); const yi = dists .map((j, i) => [j - minDist, i]) .filter(([j, _]) => j === 0) .at(-1)[1]; return { xi, yi, cx: px, cy: pys[yi], d: minDist }; }, }, }; </script>
2302_79757062/books
src/components/Charts/LineChart.vue
Vue
agpl-3.0
10,048
<template> <div class=" relative bg-white dark:bg-gray-900 border dark:border-gray-800 flex-center overflow-hidden group " :class="{ rounded: size === 'form', 'w-20 h-20 rounded-full': size !== 'small' && size !== 'form', 'w-12 h-12 rounded-full': size === 'small', }" :title="df?.label" :style="imageSizeStyle" > <img v-if="value" :src="value" /> <div v-else :class="[!isReadOnly ? 'group-hover:opacity-90' : '']"> <div v-if="letterPlaceholder" class=" flex h-full items-center justify-center text-gray-400 dark:text-gray-600 font-semibold w-full text-4xl select-none " > {{ letterPlaceholder }} </div> <svg v-else class="w-6 h-6 text-gray-300 dark:text-gray-600" viewBox="0 0 24 21" xmlns="http://www.w3.org/2000/svg" > <path d="M21 3h-4l-2-3H9L7 3H3a3 3 0 00-3 3v12a3 3 0 003 3h18a3 3 0 003-3V6a3 3 0 00-3-3zm-9 14a5 5 0 110-10 5 5 0 010 10z" fill="currentColor" fill-rule="nonzero" /> </svg> </div> <div class="hidden w-full h-full absolute justify-center items-end" :class="[!isReadOnly ? 'group-hover:flex' : '']" style="background: rgba(0, 0, 0, 0.2); backdrop-filter: blur(2px)" > <button class="bg-gray-100 dark:bg-gray-800 p-0.5 rounded mb-1" @click="handleClick" > <FeatherIcon :name="shouldClear ? 'x' : 'upload'" class="w-4 h-4 text-gray-600 dark:text-gray-400" /> </button> </div> </div> </template> <script lang="ts"> import { Field } from 'schemas/types'; import { fyo } from 'src/initFyo'; import { getDataURL } from 'src/utils/misc'; import { defineComponent, PropType } from 'vue'; import FeatherIcon from '../FeatherIcon.vue'; import Base from './Base.vue'; const mime_types: Record<string, string> = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', svg: 'image/svg+xml', }; export default defineComponent({ name: 'AttachImage', components: { FeatherIcon }, extends: Base, props: { letterPlaceholder: { type: String, default: '' }, value: { type: String, default: '' }, df: { type: Object as PropType<Field> }, }, computed: { imageSizeStyle() { if (this.size === 'form') { return { width: '135px', height: '135px' }; } return {}; }, shouldClear() { return !!this.value; }, }, methods: { async handleClick() { if (this.value) { return await this.clearImage(); } return await this.selectImage(); }, async clearImage() { // @ts-ignore this.triggerChange(null); }, async selectImage() { if (this.isReadOnly) { return; } const options = { title: fyo.t`Select Image`, filters: [{ name: 'Image', extensions: Object.keys(mime_types) }], }; const { name, success, data } = await ipc.selectFile(options); if (!success) { return; } const extension = name.split('.').at(-1); const type = mime_types[extension]; const dataURL = await getDataURL(type, data); // @ts-ignore this.triggerChange(dataURL); }, }, }); </script>
2302_79757062/books
src/components/Controls/AttachImage.vue
Vue
agpl-3.0
3,471
<template> <div> <div v-if="showLabel && df" :class="labelClasses"> {{ df.label }} </div> <div :class="containerClasses" class="flex gap-2 items-center"> <label for="attachment" class="block whitespace-nowrap overflow-auto no-scrollbar" :class="[ inputClasses, !value ? 'text-gray-600 dark:text-gray-400' : 'cursor-default', ]" >{{ label }}</label > <input id="attachment" ref="fileInput" type="file" accept="image/*,.pdf" class="hidden" :disabled="!!value" @input="selectFile" /> <!-- Buttons --> <div class="me-2 flex gap-1"> <!-- Upload Button --> <button v-if="!value" class="p-0.5 rounded" @click="upload"> <FeatherIcon name="upload" class="h-4 w-4 text-gray-600 dark:text-gray-400" /> </button> <!-- Download Button --> <button v-if="value" class="p-0.5 rounded" @click="download"> <FeatherIcon name="download" class="h-4 w-4 text-gray-600 dark:text-gray-400" /> </button> <!-- Clear Button --> <button v-if="value && !isReadOnly" class="p-0.5 rounded" @click="clear" > <FeatherIcon name="x" class="h-4 w-4 text-gray-600 dark:text-gray-400" /> </button> </div> </div> </div> </template> <script lang="ts"> import { t } from 'fyo'; import { Attachment } from 'fyo/core/types'; import { Field } from 'schemas/types'; import { convertFileToDataURL } from 'src/utils/misc'; import { defineComponent, PropType } from 'vue'; import FeatherIcon from '../FeatherIcon.vue'; import Base from './Base.vue'; export default defineComponent({ components: { FeatherIcon }, extends: Base, props: { df: Object as PropType<Field>, value: { type: Object as PropType<Attachment | null>, default: null }, border: { type: Boolean, default: false }, size: String, }, computed: { label() { if (this.value) { return this.value.name; } return this.df?.placeholder ?? this.df?.label ?? t`Attachment`; }, inputReadOnlyClasses() { if (!this.value) { return 'text-gray-600'; } else if (this.isReadOnly) { return 'text-gray-800 cursor-default'; } return 'text-gray-900'; }, containerReadOnlyClasses() { return ''; }, }, methods: { upload() { (this.$refs.fileInput as HTMLInputElement).click(); }, clear() { (this.$refs.fileInput as HTMLInputElement).value = ''; // @ts-ignore this.triggerChange(null); }, download() { if (!this.value) { return; } const { name, data } = this.value; if (!name || !data) { return; } const a = document.createElement('a'); a.style.display = 'none'; a.href = data; a.target = '_self'; a.download = name; document.body.appendChild(a); a.click(); document.body.removeChild(a); }, async selectFile(e: Event) { const target = e.target as HTMLInputElement; const file = target.files?.[0]; if (!file) { return; } const attachment = await this.getAttachment(file); // @ts-ignore this.triggerChange(attachment); }, async getAttachment(file: File | null) { if (!file) { return null; } const name = file.name; const type = file.type; const data = await convertFileToDataURL(file, type); return { name, type, data }; }, }, }); </script>
2302_79757062/books
src/components/Controls/Attachment.vue
Vue
agpl-3.0
3,748
<template> <Dropdown :items="suggestions" :is-loading="isLoading" :df="df" :doc="doc"> <template #default="{ toggleDropdown, highlightItemUp, highlightItemDown, selectHighlightedItem, }" > <div v-if="showLabel" :class="labelClasses"> {{ df.label }} </div> <div class="flex items-center justify-between pe-2 rounded" :style="containerStyles" :class="containerClasses" > <input ref="input" spellcheck="false" :class="inputClasses" class="bg-transparent" type="text" :value="linkValue" :placeholder="inputPlaceholder" :readonly="isReadOnly" :tabindex="isReadOnly ? '-1' : '0'" @focus="(e) => !isReadOnly && onFocus(e, toggleDropdown)" @click="(e) => !isReadOnly && onFocus(e, toggleDropdown)" @blur="(e) => !isReadOnly && onBlur(e.target.value)" @input="onInput" @keydown.up="highlightItemUp" @keydown.down="highlightItemDown" @keydown.enter="selectHighlightedItem" @keydown.tab="toggleDropdown(false)" @keydown.esc="toggleDropdown(false)" /> <svg v-if="!isReadOnly && !canLink" class="w-3 h-3" style="background: inherit; margin-right: -3px" viewBox="0 0 5 10" xmlns="http://www.w3.org/2000/svg" @click="(e) => !isReadOnly && onFocus(e, toggleDropdown)" > <path d="M1 2.636L2.636 1l1.637 1.636M1 7.364L2.636 9l1.637-1.636" class="stroke-current" :class=" showMandatory ? 'text-red-400 dark:text-red-600' : 'text-gray-400' " fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round" /> </svg> <button v-if="canLink" class="p-0.5 rounded -me1 bg-transparent" @mouseenter="showQuickView = true" @mouseleave="showQuickView = false" @click="routeToLinkedDoc" > <Popover :show-popup="showQuickView" :entry-delay="300" placement="bottom" > <template #target> <feather-icon name="chevron-right" class="w-4 h-4 text-gray-600 dark:text-gray-400" /> </template> <template #content> <QuickView :schema-name="linkSchemaName" :name="value" /> </template> </Popover> </button> </div> </template> </Dropdown> </template> <script> import { getOptionList } from 'fyo/utils'; import { FieldTypeEnum } from 'schemas/types'; import Dropdown from 'src/components/Dropdown.vue'; import { fuzzyMatch } from 'src/utils'; import { getFormRoute, routeTo } from 'src/utils/ui'; import Popover from '../Popover.vue'; import Base from './Base.vue'; import QuickView from '../QuickView.vue'; export default { name: 'AutoComplete', components: { Dropdown, Popover, QuickView, }, extends: Base, emits: ['focus'], data() { return { showQuickView: false, linkValue: '', isLoading: false, suggestions: [], highlightedIndex: -1, }; }, computed: { linkSchemaName() { let schemaName = this.df?.target; if (!schemaName) { const references = this.df?.references ?? ''; schemaName = this.doc?.[references]; } return schemaName; }, options() { if (!this.df) { return []; } return getOptionList(this.df, this.doc); }, canLink() { if (!this.value || !this.df) { return false; } const fieldtype = this.df?.fieldtype; const isLink = fieldtype === FieldTypeEnum.Link; const isDynamicLink = fieldtype === FieldTypeEnum.DynamicLink; if (!isLink && !isDynamicLink) { return false; } if (isLink && this.df.target) { return true; } const references = this.df.references; if (!references) { return false; } if (!this.doc?.[references]) { return false; } return true; }, }, watch: { value: { immediate: true, handler(newValue) { this.setLinkValue(this.getLinkValue(newValue)); }, }, }, mounted() { const value = this.linkValue || this.value; this.setLinkValue(this.getLinkValue(value)); }, unmounted() { this.showQuickView = false; }, deactivated() { this.showQuickView = false; }, methods: { async routeToLinkedDoc() { const name = this.value; if (!this.linkSchemaName || !name) { return; } const route = getFormRoute(this.linkSchemaName, name); await routeTo(route); }, setLinkValue(value) { this.linkValue = value; }, getLinkValue(value) { const oldValue = this.linkValue; let option = this.options.find((o) => o.value === value); if (option === undefined) { option = this.options.find((o) => o.label === value); } if (!value && option === undefined) { return null; } return option?.label ?? oldValue; }, async updateSuggestions(keyword) { if (typeof keyword === 'string') { this.setLinkValue(keyword, true); } this.isLoading = true; const suggestions = await this.getSuggestions(keyword); this.suggestions = this.setSetSuggestionAction(suggestions); this.isLoading = false; }, setSetSuggestionAction(suggestions) { for (const option of suggestions) { if (option.action) { continue; } option.action = () => { this.setSuggestion(option); }; } return suggestions; }, async getSuggestions(keyword = '') { keyword = keyword.toLowerCase(); if (!keyword) { return this.options; } return this.options .map((item) => ({ ...fuzzyMatch(keyword, item.label), item })) .filter(({ isMatch }) => isMatch) .sort((a, b) => a.distance - b.distance) .map(({ item }) => item); }, setSuggestion(suggestion) { if (suggestion?.actionOnly) { this.setLinkValue(this.value); return; } if (suggestion) { this.setLinkValue(suggestion.label); this.triggerChange(suggestion.value); } this.toggleDropdown(false); }, onFocus(e, toggleDropdown) { this.toggleDropdown = toggleDropdown; this.toggleDropdown(true); this.updateSuggestions(); this.$emit('focus', e); }, async onBlur(label) { if (!label) { this.triggerChange(''); return; } if (this.suggestions.length === 0) { this.triggerChange(label); return; } const suggestion = this.suggestions.find((s) => s.label === label); if (suggestion) { this.setSuggestion(suggestion); } else { const suggestions = await this.getSuggestions(label); this.setSuggestion(suggestions[0]); } }, onInput(e) { if (this.isReadOnly) { return; } this.toggleDropdown(true); this.updateSuggestions(e.target.value); }, }, }; </script>
2302_79757062/books
src/components/Controls/AutoComplete.vue
Vue
agpl-3.0
7,456
<template> <div class=" flex items-center border w-36 rounded px-2 bg-gray-50 dark:bg-gray-890 focus-within:bg-gray-100 dark:focus-within:bg-gray-900 " > <input ref="scanner" type="text" class="text-base placeholder-gray-600 w-full bg-transparent outline-none" :placeholder="t`Enter barcode`" @change="handleChange" /> <feather-icon name="maximize" class="w-3 h-3 text-gray-600 dark:text-gray-400 cursor-text" @click="() => ($refs.scanner as HTMLInputElement).focus()" /> </div> </template> <script lang="ts"> import { showToast } from 'src/utils/interactive'; import { defineComponent } from 'vue'; export default defineComponent({ emits: ['item-selected'], data() { return { timerId: null, barcode: '', cooldown: '', } as { timerId: null | ReturnType<typeof setTimeout>; barcode: string; cooldown: string; }; }, mounted() { document.addEventListener('keydown', this.scanListener); }, unmounted() { document.removeEventListener('keydown', this.scanListener); }, activated() { document.addEventListener('keydown', this.scanListener); }, deactivated() { document.removeEventListener('keydown', this.scanListener); }, methods: { handleChange(e: Event) { const elem = e.target as HTMLInputElement; this.selectItem(elem.value); elem.value = ''; }, async selectItem(code: string) { const barcode = code.trim(); if (!/\d{12,}/.test(barcode)) { return this.error(this.t`Invalid barcode value ${barcode}.`); } /** * Between two entries of the same item, this adds * a cooldown period of 100ms. This is to prevent * double entry. */ if (this.cooldown === barcode) { return; } this.cooldown = barcode; setTimeout(() => (this.cooldown = ''), 100); const items = (await this.fyo.db.getAll('Item', { filters: { barcode }, fields: ['name'], })) as { name: string }[]; const name = items?.[0]?.name; if (!name) { return this.error(this.t`Item with barcode ${barcode} not found.`); } this.success(this.t`${name} quantity 1 added.`); this.$emit('item-selected', name); }, async scanListener({ key, code }: KeyboardEvent) { /** * Based under the assumption that * - Barcode scanners trigger keydown events * - Keydown events are triggered quicker than human can * i.e. at max 20ms between events * - Keydown events are triggered for barcode digits * - The sequence of digits might be punctuated by a return */ const keyCode = Number(key); const isEnter = code === 'Enter'; if (Number.isNaN(keyCode) && !isEnter) { return; } if (isEnter) { return await this.setItemFromBarcode(); } this.clearInterval(); this.barcode += key; this.timerId = setTimeout(async () => { await this.setItemFromBarcode(); this.barcode = ''; }, 20); }, async setItemFromBarcode() { if (this.barcode.length < 12) { return; } await this.selectItem(this.barcode); this.barcode = ''; this.clearInterval(); }, clearInterval() { if (this.timerId === null) { return; } clearInterval(this.timerId); this.timerId = null; }, error(message: string) { showToast({ type: 'error', message }); }, success(message: string) { showToast({ type: 'success', message }); }, }, }); </script>
2302_79757062/books
src/components/Controls/Barcode.vue
Vue
agpl-3.0
3,730
<template> <div :title="df.label"> <div v-if="showLabel" :class="labelClasses"> {{ df.label }} </div> <div :class="showMandatory ? 'show-mandatory' : ''"> <input ref="input" spellcheck="false" class="bg-transparent" :class="[inputClasses, containerClasses]" :type="inputType" :value="value" :placeholder="inputPlaceholder" :readonly="isReadOnly" :step="step" :max="isNumeric(df) ? df.maxvalue : undefined" :min="isNumeric(df) ? df.minvalue : undefined" :style="containerStyles" :tabindex="isReadOnly ? '-1' : '0'" @blur="onBlur" @focus="(e) => !isReadOnly && $emit('focus', e)" @input="(e) => !isReadOnly && $emit('input', e)" /> </div> </div> </template> <script lang="ts"> import { Doc } from 'fyo/model/doc'; import { Field } from 'schemas/types'; import { isNumeric } from 'src/utils'; import { evaluateReadOnly, evaluateRequired } from 'src/utils/doc'; import { getIsNullOrUndef } from 'utils/index'; import { defineComponent, PropType } from 'vue'; export default defineComponent({ name: 'Base', inject: { injectedDoc: { from: 'doc', default: undefined, }, }, props: { df: { type: Object as PropType<Field>, required: true }, step: { type: Number, default: 1 }, value: [String, Number, Boolean, Object], inputClass: [String, Array] as PropType<string | string[]>, border: { type: Boolean, default: false }, size: { type: String, default: 'large' }, placeholder: String, showLabel: { type: Boolean, default: false }, containerStyles: { type: Object, default: () => ({}) }, textRight: { type: [null, Boolean] as PropType<boolean | null>, default: null, }, readOnly: { type: [null, Boolean] as PropType<boolean | null>, default: null, }, required: { type: [null, Boolean] as PropType<boolean | null>, default: null, }, }, emits: ['focus', 'input', 'change'], computed: { doc(): Doc | undefined { // @ts-ignore const doc = this.injectedDoc; if (doc instanceof Doc) { return doc; } return undefined; }, inputType(): string { return 'text'; }, labelClasses(): string { return 'text-gray-600 dark:text-gray-500 text-sm mb-1'; }, inputClasses(): string[] { /** * These classes will be used by components that extend Base */ const classes: string[] = []; classes.push(...this.baseInputClasses); if (this.textRight ?? isNumeric(this.df)) { classes.push('text-end'); } classes.push(this.sizeClasses); classes.push(this.inputReadOnlyClasses); return this.getInputClassesFromProp(classes).filter(Boolean); }, baseInputClasses(): string[] { return [ 'text-base', 'focus:outline-none', 'w-full', 'placeholder-gray-500', ]; }, sizeClasses(): string { if (this.size === 'small') { return 'px-2 py-1'; } return 'px-3 py-2'; }, inputReadOnlyClasses(): string { if (this.isReadOnly) { return 'text-gray-800 dark:text-gray-300 cursor-default'; } return 'text-gray-900 dark:text-gray-100'; }, containerClasses(): string[] { /** * Used to accomodate extending compoents where the input is contained in * a div eg AutoComplete */ const classes: string[] = []; classes.push(...this.baseContainerClasses); classes.push(this.containerReadOnlyClasses); classes.push(this.borderClasses); return classes.filter(Boolean); }, baseContainerClasses(): string[] { return ['rounded']; }, containerReadOnlyClasses(): string { if (!this.isReadOnly) { return 'focus-within:bg-gray-100 dark:focus-within:bg-gray-850'; } return ''; }, borderClasses(): string { if (!this.border) { return ''; } const border = 'border border-gray-200 dark:border-gray-800'; let background = 'bg-gray-25 dark:bg-gray-875'; if (this.isReadOnly) { background = 'bg-gray-50 dark:bg-gray-850'; } return border + ' ' + background; }, inputPlaceholder(): string { return this.placeholder || this.df.placeholder || this.df.label; }, showMandatory(): boolean { return this.isEmpty && this.isRequired; }, isEmpty(): boolean { if (Array.isArray(this.value) && !this.value.length) { return true; } if (typeof this.value === 'string' && !this.value) { return true; } if (getIsNullOrUndef(this.value)) { return true; } return false; }, isReadOnly(): boolean { if (typeof this.readOnly === 'boolean') { return this.readOnly; } return evaluateReadOnly(this.df, this.doc); }, isRequired(): boolean { if (typeof this.required === 'boolean') { return this.required; } return evaluateRequired(this.df, this.doc); }, }, methods: { onBlur(e: FocusEvent) { const target = e.target; if (!(target instanceof HTMLInputElement)) { return; } if (this.isReadOnly) { return; } this.triggerChange(target.value); }, getInputClassesFromProp(classes: string[]) { if (!this.inputClass) { return classes; } let inputClass = this.inputClass; if (typeof inputClass === 'string') { inputClass = [inputClass]; } inputClass = inputClass.filter((i) => typeof i === 'string'); return [classes, inputClass].flat(); }, focus(): void { const el = this.$refs.input; if (el instanceof HTMLInputElement) { el.focus(); } }, triggerChange(value: unknown): void { value = this.parse(value); if (value === '') { value = null; } this.$emit('change', value); }, parse(value: unknown): unknown { return value; }, isNumeric, }, }); </script>
2302_79757062/books
src/components/Controls/Base.vue
Vue
agpl-3.0
6,197
<template> <div :class="[inputClasses, containerClasses]"> <label class="flex items-center" :class="spaceBetween ? 'justify-between' : ''" > <div v-if="showLabel && !labelRight" class="me-3" :class="labelClasses"> {{ df.label }} </div> <div style="width: 14px; height: 14px; overflow: hidden" :class="isReadOnly ? 'cursor-default' : 'cursor-pointer'" > <svg v-if="value" width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" > <mask id="path-1-inside-1_107_160" fill="white"> <path fill-rule="evenodd" clip-rule="evenodd" d="M3 0C1.34315 0 0 1.34315 0 3V11C0 12.6569 1.34315 14 3 14H11C12.6569 14 14 12.6569 14 11V3C14 1.34315 12.6569 0 11 0H3ZM5.49955 10.8938L11.687 3.58135L10.313 2.41865L4.75726 8.98447L2.6364 6.8636L1.3636 8.1364L4.1761 10.9489L4.86774 11.6405L5.49955 10.8938Z" /> </mask> <path fill-rule="evenodd" clip-rule="evenodd" d="M3 0C1.34315 0 0 1.34315 0 3V11C0 12.6569 1.34315 14 3 14H11C12.6569 14 14 12.6569 14 11V3C14 1.34315 12.6569 0 11 0H3ZM5.49955 10.8938L11.687 3.58135L10.313 2.41865L4.75726 8.98447L2.6364 6.8636L1.3636 8.1364L4.1761 10.9489L4.86774 11.6405L5.49955 10.8938Z" :fill="color" /> <path d="M11.687 3.58135L12.4504 4.22729L13.0964 3.4639L12.333 2.81796L11.687 3.58135ZM5.49955 10.8938L6.26293 11.5398L6.26293 11.5398L5.49955 10.8938ZM10.313 2.41865L10.9589 1.65527L10.1955 1.00932L9.54957 1.77271L10.313 2.41865ZM4.75726 8.98447L4.05015 9.69158L4.81864 10.4601L5.52065 9.63041L4.75726 8.98447ZM2.6364 6.8636L3.3435 6.1565L2.6364 5.44939L1.92929 6.1565L2.6364 6.8636ZM1.3636 8.1364L0.656497 7.42929L-0.0506096 8.1364L0.656497 8.8435L1.3636 8.1364ZM4.1761 10.9489L3.469 11.656L3.469 11.656L4.1761 10.9489ZM4.86774 11.6405L4.16063 12.3476L4.92912 13.1161L5.63112 12.2865L4.86774 11.6405ZM1 3C1 1.89543 1.89543 1 3 1V-1C0.790861 -1 -1 0.790861 -1 3H1ZM1 11V3H-1V11H1ZM3 13C1.89543 13 1 12.1046 1 11H-1C-1 13.2091 0.790862 15 3 15V13ZM11 13H3V15H11V13ZM13 11C13 12.1046 12.1046 13 11 13V15C13.2091 15 15 13.2091 15 11H13ZM13 3V11H15V3H13ZM11 1C12.1046 1 13 1.89543 13 3H15C15 0.790861 13.2091 -1 11 -1V1ZM3 1H11V-1H3V1ZM10.9237 2.93541L4.73616 10.2479L6.26293 11.5398L12.4504 4.22729L10.9237 2.93541ZM9.66701 3.18204L11.0411 4.34473L12.333 2.81796L10.9589 1.65527L9.66701 3.18204ZM5.52065 9.63041L11.0763 3.06459L9.54957 1.77271L3.99387 8.33853L5.52065 9.63041ZM1.92929 7.57071L4.05015 9.69158L5.46437 8.27736L3.3435 6.1565L1.92929 7.57071ZM2.07071 8.8435L3.3435 7.57071L1.92929 6.1565L0.656497 7.42929L2.07071 8.8435ZM4.88321 10.2418L2.07071 7.42929L0.656497 8.8435L3.469 11.656L4.88321 10.2418ZM5.57485 10.9334L4.88321 10.2418L3.469 11.656L4.16063 12.3476L5.57485 10.9334ZM4.73616 10.2479L4.10435 10.9946L5.63112 12.2865L6.26293 11.5398L4.73616 10.2479Z" :fill="color" mask="url(#path-1-inside-1_107_160)" /> </svg> <svg v-else width="14" height="14" viewBox="0 0 14 14" :fill="offColor" xmlns="http://www.w3.org/2000/svg" > <rect x="0.5" y="0.5" width="13" height="13" rx="3" :stroke="color" stroke-width="1.5" /> </svg> <input ref="input" type="checkbox" :checked="getChecked(value)" :readonly="isReadOnly" :tabindex="isReadOnly ? '-1' : '0'" @change="onChange" @focus="(e) => $emit('focus', e)" /> </div> <div v-if="showLabel && labelRight" class="ms-3" :class="labelClasses"> {{ df.label }} </div> </label> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; import Base from './Base.vue'; export default defineComponent({ name: 'Check', extends: Base, props: { spaceBetween: { default: false, type: Boolean, }, labelRight: { default: true, type: Boolean, }, labelClass: String, }, emits: ['focus'], data() { return { offColor: '#0000', color: '#A1ABB4', }; }, computed: { labelClasses() { if (this.labelClass) { return this.labelClass; } return 'text-gray-600 text-base'; }, }, methods: { getChecked(value: unknown) { return Boolean(value); }, onChange(e: Event) { if (this.isReadOnly) { return; } const target = e.target; if (!(target instanceof HTMLInputElement)) { return; } this.triggerChange(target.checked); }, }, }); </script> <style scoped> input[type='checkbox'] { height: 14px; width: 14px; transform: translateY(-14px); display: none; } </style>
2302_79757062/books
src/components/Controls/Check.vue
Vue
agpl-3.0
5,037
<template> <div> <div v-if="showLabel" :class="labelClasses"> {{ df.label }} </div> <Popover placement="bottom-end"> <template #target="{ togglePopover }"> <div tabindex="0" :class="[inputClasses, containerClasses]" @click="!isReadOnly && togglePopover()" > <div class="flex items-center"> <div v-if="value" class="w-3 h-3 rounded me-1" :style="{ backgroundColor: value }" ></div> <span v-if="value"> {{ selectedColorLabel }} </span> <span v-else class="text-gray-400 dark:text-gray-600"> {{ inputPlaceholder }} </span> </div> </div> </template> <template #content> <div class="text-sm p-2 text-center"> <div> <Row :column-count="5" gap="0.5rem"> <div v-for="color in colors" :key="color.value" class="w-4 h-4 rounded cursor-pointer" :style="{ backgroundColor: color.value }" @click="setColorValue(color.value)" ></div> </Row> </div> <div class="mt-3 w-28"> <input type="color" :placeholder="t`Custom Hex`" :class="[inputClasses, containerClasses]" :value="value" style="padding: 0" @change="(e) => setColorValue(e.target.value)" /> </div> </div> </template> </Popover> </div> </template> <script> import Popover from 'src/components/Popover.vue'; import Row from 'src/components/Row.vue'; import Base from './Base.vue'; export default { name: 'Color', components: { Popover, Row, }, extends: Base, computed: { colors() { return this.df.options; }, selectedColorLabel() { if (!this.colors) return this.value; const color = this.colors.find((c) => this.value === c.value); return color ? color.label : this.value; }, }, methods: { setColorValue(value) { if (!value.startsWith('#')) { value = '#' + value; } if (/^#[0-9A-F]{6}$/i.test(value)) { this.triggerChange(value); } }, }, }; </script>
2302_79757062/books
src/components/Controls/Color.vue
Vue
agpl-3.0
2,367
<template> <div> <div v-if="showLabel" :class="labelClasses"> {{ df.label }} </div> <input v-show="showInput" ref="input" class="text-end" :class="[inputClasses, containerClasses]" :type="inputType" :value="round(value)" :placeholder="inputPlaceholder" :readonly="isReadOnly" :tabindex="isReadOnly ? '-1' : '0'" @blur="onBlur" @focus="onFocus" @input="(e) => $emit('input', e)" /> <div v-show="!showInput" class="whitespace-nowrap overflow-x-auto no-scrollbar" :class="[inputClasses, containerClasses]" tabindex="0" @click="activateInput" @focus="activateInput" > {{ formattedValue }} </div> </div> </template> <script lang="ts"> import { isPesa } from 'fyo/utils'; import { Money } from 'pesa'; import { fyo } from 'src/initFyo'; import { safeParsePesa } from 'utils/index'; import { defineComponent, nextTick } from 'vue'; import Float from './Float.vue'; export default defineComponent({ name: 'Currency', extends: Float, emits: ['input', 'focus'], data() { return { showInput: false, currencySymbol: '', }; }, computed: { formattedValue() { const value = this.parse(this.value); return fyo.format(value, this.df, this.doc); }, }, methods: { onFocus(e: FocusEvent) { const target = e.target; if (!(target instanceof HTMLInputElement)) { return; } target.select(); this.showInput = true; this.$emit('focus', e); }, round(v: unknown) { if (!isPesa(v)) { v = this.parse(v); } if (isPesa(v)) { return v.round(); } return fyo.pesa(0).round(); }, parse(value: unknown): Money { return safeParsePesa(value, this.fyo); }, onBlur(e: FocusEvent) { const target = e.target; if (!(target instanceof HTMLInputElement)) { return; } this.showInput = false; this.triggerChange(target.value); }, activateInput() { if (this.isReadOnly) { return; } this.showInput = true; nextTick(() => { this.focus(); }); }, }, }); </script>
2302_79757062/books
src/components/Controls/Currency.vue
Vue
agpl-3.0
2,247
<script lang="ts"> import Base from './Base.vue'; import { defineComponent } from 'vue'; export default defineComponent({ name: 'Data', extends: Base, computed: { inputType() { return 'text'; }, }, }); </script>
2302_79757062/books
src/components/Controls/Data.vue
Vue
agpl-3.0
235
<template> <div> <div v-if="showLabel" :class="labelClasses"> {{ df.label }} </div> <input v-show="showInput" ref="input" :class="[inputClasses, containerClasses]" :type="inputType" :value="inputValue" :placeholder="inputPlaceholder" :readonly="isReadOnly" :tabindex="isReadOnly ? '-1' : '0'" @blur="onBlur" @focus="onFocus" @input="(e) => $emit('input', e)" /> <div v-show="!showInput" class="flex" :class="[containerClasses, sizeClasses]" tabindex="0" @click="activateInput" @focus="activateInput" > <p v-if="!isEmpty" :class="[baseInputClasses]" class="overflow-auto no-scrollbar whitespace-nowrap dark:text-gray-100" > {{ formattedValue }} </p> <p v-else-if="inputPlaceholder" class="text-base text-gray-500 w-full"> {{ inputPlaceholder }} </p> <button v-if="!isReadOnly" class="-me-0.5 ms-1"> <FeatherIcon name="calendar" class="w-4 h-4" :class=" showMandatory ? 'text-red-600' : 'text-gray-600 dark:text-gray-400' " /> </button> </div> </div> </template> <script lang="ts"> import { DateTime } from 'luxon'; import { fyo } from 'src/initFyo'; import { defineComponent, nextTick } from 'vue'; import Base from './Base.vue'; export default defineComponent({ extends: Base, emits: ['input', 'focus'], data() { return { showInput: false, }; }, computed: { inputValue(): string { let value = this.value; if (typeof value === 'string') { value = new Date(value); } if (value instanceof Date && !Number.isNaN(value.valueOf())) { return DateTime.fromJSDate(value).toISODate(); } return ''; }, inputType() { return 'date'; }, formattedValue() { const value = this.parse(this.value); return fyo.format(value, this.df, this.doc); }, borderClasses(): string { if (!this.border) { return ''; } const border = 'border border-gray-200 dark:border-gray-800'; let background = 'bg-gray-25 dark:bg-gray-875'; if (this.isReadOnly) { background = 'bg-gray-50 dark:bg-gray-850'; } if (this.showInput) { return background; } return border + ' ' + background; }, }, methods: { onFocus(e: FocusEvent) { const target = e.target; if (!(target instanceof HTMLInputElement)) { return; } target.select(); this.showInput = true; this.$emit('focus', e); }, onBlur(e: FocusEvent) { const target = e.target; if (!(target instanceof HTMLInputElement)) { return; } this.showInput = false; let value: Date | null = DateTime.fromISO(target.value).toJSDate(); if (Number.isNaN(value.valueOf())) { value = null; } this.triggerChange(value); }, activateInput() { if (this.isReadOnly) { return; } this.showInput = true; nextTick(() => { this.focus(); // @ts-ignore this.$refs.input.showPicker(); }); }, }, }); </script>
2302_79757062/books
src/components/Controls/Date.vue
Vue
agpl-3.0
3,291
<script lang="ts"> import { defineComponent } from 'vue'; import DateVue from './Date.vue'; import { DateTime } from 'luxon'; export default defineComponent({ extends: DateVue, computed: { inputType() { return 'datetime-local'; }, inputValue(): string { let value = this.value; if (typeof value === 'string') { value = new Date(value); } if (value instanceof Date && !Number.isNaN(value.valueOf())) { return DateTime.fromJSDate(value).toISO().split('.')[0]; } return ''; }, }, }); </script>
2302_79757062/books
src/components/Controls/Datetime.vue
Vue
agpl-3.0
574
<template> <div> <!-- Datetime header --> <div class="flex justify-between items-center text-sm px-4 pt-4"> <div v-if="viewMonth !== month || viewYear !== year" class="text-gray-900" > {{ `${months[viewMonth]}, ${viewYear}` }} </div> <div v-else class="text-blue-500"> {{ datetimeString }} </div> <!-- Next and Previous Month Buttons --> <div class="flex items-center"> <button class="font-mono text-gray-600 cursor-pointer" @click="prevClicked" > <FeatherIcon name="chevron-left" class="w-4 h-4" /> </button> <button class=" font-mono cursor-pointer w-2 h-2 rounded-full border-gray-400 border-2 " @click="selectToday" /> <button class="font-mono text-gray-600 cursor-pointer" @click="nextClicked" > <FeatherIcon name="chevron-right" class="w-4 h-4" /> </button> </div> </div> <!-- Date Input --> <div class="flex"> <!-- Weekday Titles --> <div class="px-3 pt-4" :class="selectTime ? 'pb-4' : ''"> <div class="grid grid-cols-7 gap-1"> <div v-for="day of weekdays" :key="day" class=" w-7 h-7 flex items-center justify-center text-xs text-gray-600 " > {{ day }} </div> </div> <!-- Weekday Grid --> <div class="grid grid-cols-7 gap-1"> <div v-for="item of weekdayList" :key="`${item.year}-${item.month}-${item.day}`" class=" w-7 h-7 flex items-center justify-center text-xs rounded-full cursor-pointer hover:bg-gray-100 " :class="getDayClass(item)" @click="select(item)" > {{ item.day }} </div> </div> </div> <!-- Month and Year Selectors --> <div v-if="selectMonthYear" class="border-s flex flex-col justify-between" > <!-- Month Selector --> <div class="flex flex-col gap-2 overflow-auto m-4" style="height: calc(248px - 79.5px - 1px - 2rem)" > <div v-for="(m, i) of months" :key="m" ref="monthDivs" class="text-xs cursor-pointer" :class="getMonthClass(i)" @click="change(i, 'month')" > {{ m }} </div> </div> <!-- Year Selector --> <div class="border-t w-full px-4 pt-4" :class="selectTime ? 'pb-4' : ''" > <label class="date-selector-label">Year</label> <input class="date-selector-input" type="number" min="1000" max="9999" :value="year" @change="(e) => change(e, 'year')" /> </div> </div> </div> <!-- Time Selector --> <div v-if="selectTime" class="px-4 pt-4 grid gap-4 border-t" style="grid-template-columns: repeat(3, minmax(0, 1fr))" > <div> <label class="date-selector-label">Hours</label> <input class="date-selector-input" type="number" min="0" max="23" :value="hours" @change="(e) => change(e, 'hours')" /> </div> <div> <label class="date-selector-label">Minutes</label> <input class="date-selector-input" type="number" min="0" max="59" :value="minutes" @change="(e) => change(e, 'minutes')" /> </div> <div> <label class="date-selector-label">Seconds</label> <input class="date-selector-input" type="number" min="0" max="59" :value="seconds" @change="(e) => change(e, 'seconds')" /> </div> </div> <!-- Footer --> <div class="flex p-4 w-full justify-between"> <button class="text-xs text-gray-600 hover:text-gray-600" @click="selectMonthYear = !selectMonthYear" > {{ selectMonthYear ? t`Hide Month/Year` : t`Show Month/Year` }} </button> <button v-if="showClear" class="text-xs text-gray-600 hover:text-gray-600 ms-auto" @click="clearClicked" > {{ t`Clear` }} </button> </div> </div> </template> <script lang="ts"> import { defineComponent, nextTick, PropType } from 'vue'; import FeatherIcon from '../FeatherIcon.vue'; type WeekListItem = { year: number; month: number; day: number; weekday: number; }; type DatetimeValues = { year: number; month: number; day: number; hours: number; minutes: number; seconds: number; ms: number; }; export default defineComponent({ components: { FeatherIcon }, props: { modelValue: { type: Date }, selectTime: { type: Boolean, default: true }, showClear: { type: Boolean, default: true }, formatValue: { type: Function as PropType<(value: Date | null) => string> }, }, emits: ['update:modelValue'], data() { return { selectedMonth: 0, selectedYear: 1000, viewMonth: 0, viewYear: 1000, selectMonthYear: false, } as { selectedMonth: number; selectedYear: number; selectMonthYear: boolean; viewMonth: number; viewYear: number; }; }, computed: { today() { return new Date(); }, internalValue(): Date { if (this.modelValue == null) { return this.today; } return this.modelValue; }, year() { // 1000 to 9999 return this.internalValue?.getFullYear() ?? 1000; }, month() { // 0 to 11 return this.internalValue?.getMonth() ?? 0; }, day() { // 1 to 31 return this.internalValue?.getDate() ?? 1; }, hours() { // 0 to 23 return this.internalValue?.getHours() ?? 0; }, minutes() { // 0 to 59 return this.internalValue?.getMinutes() ?? 0; }, seconds() { // 0 to 59 return this.internalValue?.getSeconds() ?? 0; }, ms() { // 0 to 999 return this.internalValue?.getMilliseconds() ?? 0; }, weekdayList() { return getWeekdayList(this.viewYear, this.viewMonth); }, datetimeString() { if (this.formatValue) { return this.formatValue(this.internalValue); } const dateString = this.internalValue .toDateString() .split(' ') .slice(1) .join(' '); if (!this.selectTime) { return dateString; } const timeString = this.internalValue?.toTimeString().split(' ')[0] ?? ''; return `${dateString} ${timeString}]`; }, months() { return [ this.t`January`, this.t`February`, this.t`March`, this.t`April`, this.t`May`, this.t`June`, this.t`July`, this.t`August`, this.t`September`, this.t`October`, this.t`November`, this.t`December`, ]; }, weekdays() { return [ this.t`Su`, this.t`Mo`, this.t`Tu`, this.t`We`, this.t`Th`, this.t`Fr`, this.t`Sa`, ]; }, }, watch: { async selectMonthYear(value) { if (!value) { return; } await nextTick(); const monthDivs = this.$refs.monthDivs as HTMLDivElement[]; if (!monthDivs?.length) { return; } monthDivs[this.month]?.scrollIntoView({ block: 'center', inline: 'center', }); }, }, mounted() { this.viewMonth = this.month; this.viewYear = this.year; }, methods: { getDayClass(item: WeekListItem) { let dclass = []; const today = this.today; const todayDay = today.getDate(); const todayMonth = today.getMonth(); const isToday = item.day === todayDay && item.month === todayMonth; const isSelected = item.day === this.day && item.month === this.month; if (item.month !== this.viewMonth && !isToday) { dclass.push('text-gray-600'); } if (isSelected) { dclass.push('font-semibold'); } if (isSelected && this.modelValue != null) { dclass.push('bg-gray-100', 'text-blue-500'); } else if (isToday && !isSelected) { dclass.push('text-blue-500'); } return dclass; }, getMonthClass(item: number) { let dclass = []; if (item === this.month) { dclass.push('font-semibold'); } if (this.modelValue != null && item === this.month) { dclass.push('text-blue-500'); } return dclass; }, change(e: number | Event, name: keyof DatetimeValues) { let value: number; if (typeof e === 'number' && name === 'month') { value = e; } else if (typeof e !== 'number') { value = Number((e.target as HTMLInputElement).value); } else { return; } if (Number.isNaN(value)) { return; } if (name === 'year' && value >= 1000 && value <= 9999) { return this.select({ year: value }); } if (name === 'month' && value >= 0 && value <= 11) { return this.select({ month: value }); } if (name === 'day' && value >= 1 && value <= 31) { return this.select({ day: value }); } if (name === 'hours' && value >= 0 && value <= 23) { return this.select({ hours: value }); } if (name === 'minutes' && value >= 0 && value <= 59) { return this.select({ minutes: value }); } if (name === 'seconds' && value >= 0 && value <= 59) { return this.select({ seconds: value }); } if (name === 'ms' && value >= 0 && value <= 999) { return this.select({ ms: value }); } }, select(values: Partial<DatetimeValues>) { values.year ??= this.year; values.month ??= this.month; values.day ??= this.day; values.hours ??= this.hours; values.minutes ??= this.minutes; values.seconds ??= this.seconds; values.ms ??= this.ms; const date = new Date( values.year, values.month, values.day, values.hours, values.minutes, values.seconds, values.ms ); this.viewMonth = values.month; this.viewYear = values.year; this.emitChange(date); }, selectToday() { return this.emitChange(new Date()); }, clearClicked() { this.emitChange(null); }, emitChange(value: null | Date) { if (value == null) { this.viewMonth = this.today.getMonth(); this.viewYear = this.today.getFullYear(); } else { this.viewMonth = value.getMonth(); this.viewYear = value.getFullYear(); } this.$emit('update:modelValue', value); }, nextClicked() { const d = new Date(this.viewYear, this.viewMonth + 1, 1); this.viewYear = d.getFullYear(); this.viewMonth = d.getMonth(); }, prevClicked() { const d = new Date(this.viewYear, this.viewMonth - 1, 1); this.viewYear = d.getFullYear(); this.viewMonth = d.getMonth(); }, }, }); function getWeekdayList(startYear: number, startMonth: number): WeekListItem[] { /** * Weekday: * * S M T W T F S * 0 1 2 3 4 5 6 * * 0: Sunday * 6: Saturday */ let year = startYear; let month = startMonth; let day = 1; const weekdayList: WeekListItem[] = []; /** * Push days of the current month into weeklist */ while (month === startMonth) { const date = new Date(year, month, day); if (date.getMonth() !== month) { break; } weekdayList.push({ year, month, day, weekday: date.getDay() }); year = date.getFullYear(); month = date.getMonth(); day += 1; } /** * Unshift days of the previous month into weeklist * until the first day is Sunday */ while (weekdayList[0]?.weekday !== 0) { const { year, month, day } = weekdayList[0] ?? {}; if (year === undefined || month === undefined || day === undefined) { break; } const date = new Date(year, month, day - 1); weekdayList.unshift({ year: date.getFullYear(), month: date.getMonth(), day: date.getDate(), weekday: date.getDay(), }); } /** * Push days of the next month into weeklist * until the last day is Saturday */ while (weekdayList.length !== 42) { const { year, month, day } = weekdayList.at(-1) ?? {}; if (year === undefined || month === undefined || day === undefined) { break; } const date = new Date(year, month, day + 1); weekdayList.push({ year: date.getFullYear(), month: date.getMonth(), day: date.getDate(), weekday: date.getDay(), }); } return weekdayList; } </script> <style scoped> .date-selector-label { @apply text-xs text-gray-600 block mb-0.5; } .date-selector-input { @apply text-sm text-gray-900 p-1 border rounded w-full; } input[type='number']::-webkit-inner-spin-button { appearance: auto; } </style>
2302_79757062/books
src/components/Controls/DatetimePicker.vue
Vue
agpl-3.0
13,589
<template> <Popover> <!-- Datetime Selected Display --> <template #target="{ togglePopover }"> <div v-if="showLabel" :class="labelClasses"> {{ df?.label }} </div> <div :class="[containerClasses, sizeClasses]" class="flex" @click="() => !isReadOnly && togglePopover()" > <p v-if="!isEmpty" :class="[baseInputClasses]" class="overflow-auto no-scrollbar whitespace-nowrap" > {{ formattedValue }} </p> <p v-else-if="inputPlaceholder" class="text-base text-gray-500 w-full"> {{ inputPlaceholder }} </p> <button v-if="!isReadOnly" class="p-0.5 rounded -me-1 ms-1"> <FeatherIcon name="calendar" class="w-4 h-4" :class="showMandatory ? 'text-red-600' : 'text-gray-600'" /> </button> </div> </template> <!-- Datetime Input Popover --> <template #content> <DatetimePicker :show-clear="!isRequired" :select-time="selectTime" :model-value="internalValue" :format-value="formatValue" @update:model-value="(value) => triggerChange(value)" /> </template> </Popover> </template> <script lang="ts"> /** * This is a Datetime/Date component that builds * uses a custom DatetimePicker. It is not being used * for now because users are more familiar with their * system's date and datetime picker. * * That provides better UX. * * This component can be used once the underlying * DatetimePicker's UX issues are solved. */ import { Field } from 'schemas/types'; import { defineComponent, PropType } from 'vue'; import DatetimePicker from './DatetimePicker.vue'; import FeatherIcon from '../FeatherIcon.vue'; import Popover from '../Popover.vue'; import Base from './Base.vue'; export default defineComponent({ components: { Popover, FeatherIcon, DatetimePicker }, extends: Base, props: { value: [Date, String], df: Object as PropType<Field> }, data() { return { selectTime: true }; }, computed: { internalValue() { if (this.value == null) { return undefined; } if (typeof this.value === 'string') { return new Date(this.value); } return this.value; }, formattedValue() { return this.formatValue(this.internalValue); }, }, methods: { triggerChange(value: Date | null) { this.$emit('change', value); }, formatValue(value?: Date | null) { if (value == null) { return ''; } return this.fyo.format( value, this.df ?? (this.selectTime ? 'Datetime' : 'Date') ); }, }, }); </script>
2302_79757062/books
src/components/Controls/Datetime_old.vue
Vue
agpl-3.0
2,735
<script> import { fyo } from 'src/initFyo'; import Link from './Link.vue'; export default { name: 'DynamicLink', extends: Link, inject: { report: { default: null }, }, props: ['target'], created() { const watchKey = `doc.${this.df.references}`; this.targetWatcher = this.$watch(watchKey, function (newTarget, oldTarget) { if (oldTarget && newTarget !== oldTarget) { this.triggerChange(''); } }); }, unmounted() { this.targetWatcher(); }, methods: { getTargetSchemaName() { const references = this.df.references; if (!references) { return null; } let schemaName = this.doc?.[references]; if (!schemaName) { schemaName = this.report?.[references]; } if (!schemaName) { return null; } if (!fyo.schemaMap[schemaName]) { return null; } return schemaName; }, async getOptions() { this.results = []; const schemaName = this.getTargetSchemaName(); if (!schemaName) { return []; } if (this.results?.length) { return this.results; } const schema = fyo.schemaMap[schemaName]; const filters = await this.getFilters(); const fields = [ ...new Set(['name', schema.titleField, this.df.groupBy]), ].filter(Boolean); const results = await fyo.db.getAll(schemaName, { filters, fields, }); return (this.results = results .map((r) => { const option = { label: r[schema.titleField], value: r.name }; if (this.df.groupBy) { option.group = r[this.df.groupBy]; } return option; }) .filter(Boolean)); }, async openNewDoc() { const schemaName = this.getTargetSchemaName(); if (!schemaName) { return; } const name = this.linkValue || fyo.doc.getTemporaryName(fyo.schemaMap[schemaName]); const filters = await this.getCreateFilters(); const { openQuickEdit } = await import('src/utils/ui'); const doc = fyo.doc.getNewDoc(schemaName, { name, ...filters }); openQuickEdit({ doc }); doc.once('afterSync', () => { this.$router.back(); this.results = []; this.triggerChange(doc.name); }); }, }, }; </script>
2302_79757062/books
src/components/Controls/DynamicLink.vue
Vue
agpl-3.0
2,363
<template> <div class=" flex items-center bg-gray-50 dark:bg-gray-890 rounded-md text-sm p-1 border " > <div class="rate-container" :class=" disabled ? 'bg-gray-100 dark:bg-gray-850' : 'bg-gray-25 dark:bg-gray-890' " > <input v-model="fromValue" type="number" :disabled="disabled" min="0" /> <p>{{ left }}</p> </div> <p class="mx-1 text-gray-600 dark:text-gray-400">=</p> <div class="rate-container" :class=" disabled ? 'bg-gray-100 dark:bg-gray-850' : 'bg-gray-25 dark:bg-gray-890' " > <input type="number" :value="isSwapped ? fromValue / exchangeRate : exchangeRate * fromValue" :disabled="disabled" min="0" @change="rightChange" /> <p>{{ right }}</p> </div> <button v-if="!disabled" class=" bg-green-100 dark:bg-green-600 px-2 ms-1 -me-0.5 h-full border-s dark:border-gray-800 " @click="swap" > <feather-icon name="refresh-cw" class="w-3 h-3 text-gray-600 dark:text-gray-400" /> </button> </div> </template> <script lang="ts"> import { safeParseFloat } from 'utils/index'; import { defineComponent } from 'vue'; export default defineComponent({ props: { disabled: { type: Boolean, default: false }, fromCurrency: { type: String, default: 'USD' }, toCurrency: { type: String, default: 'INR' }, exchangeRate: { type: Number, default: 75 }, }, emits: ['change'], data() { return { fromValue: 1, isSwapped: false }; }, computed: { left(): string { if (this.isSwapped) { return this.toCurrency; } return this.fromCurrency; }, right(): string { if (this.isSwapped) { return this.fromCurrency; } return this.toCurrency; }, }, methods: { swap() { this.isSwapped = !this.isSwapped; }, rightChange(e: Event) { let value: string | number = 1; if (e.target instanceof HTMLInputElement) { value = e.target.value; } value = safeParseFloat(value); let exchangeRate = value / this.fromValue; if (this.isSwapped) { exchangeRate = this.fromValue / value; } this.$emit('change', exchangeRate); }, }, }); </script> <style scoped> input[type='number'] { @apply w-12 bg-transparent p-0.5; } .rate-container { @apply flex items-center rounded-md border-gray-100 text-gray-900 text-sm px-1 focus-within:border-gray-200 bg-transparent; } .rate-container > p { @apply text-xs text-gray-600; } </style>
2302_79757062/books
src/components/Controls/ExchangeRate.vue
Vue
agpl-3.0
2,771
<script lang="ts"> import { safeParseFloat } from 'utils/index'; import { defineComponent } from 'vue'; import Int from './Int.vue'; export default defineComponent({ name: 'Float', extends: Int, computed: { inputType() { return 'number'; }, }, methods: { parse(value: unknown): number { return safeParseFloat(value); }, }, }); </script>
2302_79757062/books
src/components/Controls/Float.vue
Vue
agpl-3.0
378
<script> import { h } from 'vue'; import AttachImage from './AttachImage.vue'; import Attachment from './Attachment.vue'; import AutoComplete from './AutoComplete.vue'; import Check from './Check.vue'; import Color from './Color.vue'; import Currency from './Currency.vue'; import Data from './Data.vue'; import Date from './Date.vue'; import Datetime from './Datetime.vue'; import DynamicLink from './DynamicLink.vue'; import Float from './Float.vue'; import Int from './Int.vue'; import Link from './Link.vue'; import Select from './Select.vue'; import Text from './Text.vue'; const components = { AttachImage, Data, Check, Color, Select, Link, Date, Datetime, AutoComplete, DynamicLink, Int, Float, Attachment, Currency, Text, }; export default { name: 'FormControl', methods: { clear() { const input = this.$refs.control.$refs.input; if (input instanceof HTMLInputElement) { input.value = ''; } }, select() { this.$refs.control.$refs?.input?.select(); }, focus() { this.$refs.control.focus(); }, getInput() { return this.$refs.control.$refs.input; }, }, render() { const fieldtype = this.$attrs.df.fieldtype; const component = components[fieldtype] ?? Data; return h(component, { ...this.$attrs, ref: 'control', }); }, }; </script>
2302_79757062/books
src/components/Controls/FormControl.vue
Vue
agpl-3.0
1,383
<script lang="ts"> import Data from './Data.vue'; import { defineComponent } from 'vue'; import { safeParseInt } from 'utils/index'; export default defineComponent({ name: 'Int', extends: Data, computed: { inputType() { return 'number'; }, }, methods: { parse(value: unknown): number { return safeParseInt(value); }, }, }); </script>
2302_79757062/books
src/components/Controls/Int.vue
Vue
agpl-3.0
375
<template> <AutoComplete :df="languageDf" :value="value" :border="true" input-class="rounded py-1.5" @change="onChange" /> </template> <script lang="ts"> import { DEFAULT_LANGUAGE } from 'fyo/utils/consts'; import { OptionField } from 'schemas/types'; import { fyo } from 'src/initFyo'; import { languageCodeMap, setLanguageMap } from 'src/utils/language'; import { defineComponent } from 'vue'; import AutoComplete from './AutoComplete.vue'; export default defineComponent({ components: { AutoComplete }, props: { dontReload: { type: Boolean, default: false, }, }, computed: { value() { return fyo.config.get('language') ?? DEFAULT_LANGUAGE; }, languageDf(): OptionField { const preset = fyo.config.get('language'); let language = DEFAULT_LANGUAGE; if (typeof preset === 'string') { language = preset; } return { fieldname: 'language', label: this.t`Language`, fieldtype: 'AutoComplete', options: Object.keys(languageCodeMap).map((value) => ({ label: value, value, })), default: language, description: this.t`Set the display language.`, }; }, }, methods: { onChange(value: unknown) { if (typeof value !== 'string') { return; } if (languageCodeMap[value] === undefined) { return; } setLanguageMap(value, this.dontReload); }, }, }); </script>
2302_79757062/books
src/components/Controls/LanguageSelector.vue
Vue
agpl-3.0
1,500
<script> import { t } from 'fyo'; import Badge from 'src/components/Badge.vue'; import { fyo } from 'src/initFyo'; import { fuzzyMatch } from 'src/utils'; import { getCreateFiltersFromListViewFilters } from 'src/utils/misc'; import { markRaw } from 'vue'; import AutoComplete from './AutoComplete.vue'; export default { name: 'Link', extends: AutoComplete, data() { return { results: [] }; }, watch: { value: { immediate: true, handler(newValue) { this.setLinkValue(newValue); }, }, }, mounted() { if (this.value) { this.setLinkValue(); } }, methods: { async setLinkValue(newValue, isInput) { if (isInput) { return (this.linkValue = newValue || ''); } const value = newValue ?? this.value; const { fieldname, target } = this.df ?? {}; const linkDisplayField = fyo.schemaMap[target ?? '']?.linkDisplayField; if (!linkDisplayField) { return (this.linkValue = value); } const linkDoc = await this.doc?.loadAndGetLink(fieldname); this.linkValue = linkDoc?.get(linkDisplayField) ?? ''; }, getTargetSchemaName() { return this.df.target; }, async getOptions() { const schemaName = this.getTargetSchemaName(); if (!schemaName) { return []; } if (this.results?.length) { return this.results; } const schema = fyo.schemaMap[schemaName]; const filters = await this.getFilters(); const fields = [ ...new Set(['name', schema.titleField, this.df.groupBy]), ].filter(Boolean); const results = await fyo.db.getAll(schemaName, { filters, fields, }); return (this.results = results .map((r) => { const option = { label: r[schema.titleField], value: r.name }; if (this.df.groupBy) { option.group = r[this.df.groupBy]; } return option; }) .filter(Boolean)); }, async getSuggestions(keyword = '') { let options = await this.getOptions(); if (keyword) { options = options .map((item) => ({ ...fuzzyMatch(keyword, item.label), item })) .filter(({ isMatch }) => isMatch) .sort((a, b) => a.distance - b.distance) .map(({ item }) => item); } if (this.doc && this.df.create) { options = options.concat(this.getCreateNewOption()); } if (options.length === 0 && !this.df.emptyMessage) { return [ { component: markRaw({ template: '<span class="text-gray-600 dark:text-gray-400">{{ t`No results found` }}</span>', }), action: () => {}, actionOnly: true, }, ]; } return options; }, getCreateNewOption() { return { label: t`Create`, action: () => this.openNewDoc(), actionOnly: true, component: markRaw({ template: '<div class="flex items-center font-semibold">{{ t`Create` }}' + '<Badge color="blue" class="ms-2" v-if="isNewValue">{{ linkValue }}</Badge>' + '</div>', computed: { value: () => this.value, linkValue: () => this.linkValue, isNewValue: () => { const values = this.suggestions.map((d) => d.label); return this.linkValue && !values.includes(this.linkValue); }, }, components: { Badge }, }), }; }, async openNewDoc() { const schemaName = this.df.target; const name = this.linkValue || fyo.doc.getTemporaryName(fyo.schemaMap[schemaName]); const filters = await this.getCreateFilters(); const { openQuickEdit } = await import('src/utils/ui'); const doc = fyo.doc.getNewDoc(schemaName, { name, ...filters }); openQuickEdit({ doc }); doc.once('afterSync', () => { this.$router.back(); this.results = []; this.triggerChange(doc.name); }); }, async getCreateFilters() { const { schemaName, fieldname } = this.df; const getCreateFilters = fyo.models[schemaName]?.createFilters?.[fieldname]; let createFilters = await getCreateFilters?.(this.doc); if (createFilters !== undefined) { return createFilters; } const filters = await this.getFilters(); return getCreateFiltersFromListViewFilters(filters); }, async getFilters() { const { schemaName, fieldname } = this.df; const getFilters = fyo.models[schemaName]?.filters?.[fieldname]; if (getFilters === undefined) { return {}; } if (this.doc) { return (await getFilters(this.doc)) ?? {}; } try { return (await getFilters()) ?? {}; } catch { return {}; } }, }, }; </script>
2302_79757062/books
src/components/Controls/Link.vue
Vue
agpl-3.0
4,958
<template> <div> <div v-if="showLabel" :class="labelClasses"> {{ df.label }} </div> <div class="flex items-center justify-between" :class="[inputClasses, containerClasses]" > <select class=" appearance-none bg-transparent focus:outline-none w-11/12 cursor-pointer custom-scroll custom-scroll-thumb2 " :class="{ 'pointer-events-none': isReadOnly, 'text-gray-500': !value, }" :value="value" @change="onChange" @focus="(e) => $emit('focus', e)" > <option v-if="inputPlaceholder && !showLabel" value="" disabled selected class="text-black dark:text-gray-200 dark:bg-gray-850" > {{ inputPlaceholder }} </option> <option v-for="option in options" :key="option.value" :value="option.value" class="text-black dark:text-gray-200 dark:bg-gray-850" > {{ option.label }} </option> </select> <svg v-if="!isReadOnly" class="w-3 h-3" style="background: inherit; margin-right: -3px" viewBox="0 0 5 10" xmlns="http://www.w3.org/2000/svg" > <path d="M1 2.636L2.636 1l1.637 1.636M1 7.364L2.636 9l1.637-1.636" class="stroke-current" :class=" showMandatory ? 'text-red-400 dark:text-red-600' : 'text-gray-400 dark:text-gray-600' " fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round" /> </svg> </div> </div> </template> <script lang="ts"> import Base from './Base.vue'; import { defineComponent } from 'vue'; import { SelectOption } from 'schemas/types'; export default defineComponent({ name: 'Select', extends: Base, emits: ['focus'], computed: { options(): SelectOption[] { if (this.df.fieldtype !== 'Select') { return []; } return this.df.options; }, }, methods: { onChange(e: Event) { const target = e.target; if ( !(target instanceof HTMLSelectElement) && !(target instanceof HTMLInputElement) ) { return; } this.triggerChange(target.value); }, }, }); </script>
2302_79757062/books
src/components/Controls/Select.vue
Vue
agpl-3.0
2,435
<template> <div v-if="tableFields?.length"> <div v-if="showLabel" class="text-gray-600 dark:text-gray-400 text-sm mb-1"> {{ df.label }} </div> <div :class="border ? 'border dark:border-gray-800 rounded-md' : ''"> <!-- Title Row --> <Row :ratio="ratio" class=" border-b dark:border-gray-800 px-2 text-gray-600 dark:text-gray-400 w-full flex items-center " > <div class="flex items-center ps-2">#</div> <div v-for="df in tableFields" :key="df.fieldname" class="items-center flex px-2 h-row-mid" :class="{ 'ms-auto': isNumeric(df), }" :style="{ height: ``, }" > {{ df.label }} </div> </Row> <!-- Data Rows --> <div v-if="value" class="overflow-auto custom-scroll custom-scroll-thumb1" :style="{ 'max-height': maxHeight }" > <TableRow v-for="(row, idx) of value" ref="table-row" :key="row.name" :class="idx < value.length - 1 ? 'border-b dark:border-gray-800' : ''" v-bind="{ row, tableFields, size, ratio, isNumeric }" :read-only="isReadOnly" :can-edit-row="canEditRow" @remove="removeRow(row)" @change="(field, value) => $emit('row-change', field, value, df)" /> </div> <!-- Add Row and Row Count --> <Row v-if="!isReadOnly" :ratio="ratio" class=" text-gray-500 cursor-pointer px-2 w-full h-row-mid flex items-center " :class="value.length > 0 ? 'border-t dark:border-gray-800' : ''" @click="addRow" > <div class="flex items-center ps-1"> <feather-icon name="plus" class="w-4 h-4 text-gray-500" /> </div> <div class="flex justify-between px-2" :style="`grid-column: 2 / ${ratio.length + 1}`" > <p> {{ t`Add Row` }} </p> <p v-if=" value && maxRowsBeforeOverflow && value.length > maxRowsBeforeOverflow " class="text-end px-2" > {{ t`${value.length} rows` }} </p> </div> </Row> </div> </div> </template> <script> import Row from 'src/components/Row.vue'; import { fyo } from 'src/initFyo'; import { nextTick } from 'vue'; import Base from './Base.vue'; import TableRow from './TableRow.vue'; export default { name: 'Table', components: { Row, TableRow, }, extends: Base, props: { value: { type: Array, default: () => [] }, showHeader: { type: Boolean, default: true, }, maxRowsBeforeOverflow: { type: Number, default: 3, }, border: { type: Boolean, default: false, }, }, emits: ['editrow', 'row-change'], data() { return { maxHeight: '' }; }, computed: { height() { if (this.size === 'small') { } return 2; }, canEditRow() { return this.df.edit; }, ratio() { const ratio = [0.3].concat(this.tableFields.map(() => 1)); if (this.canEditRow) { return ratio.concat(0.3); } return ratio; }, tableFields() { const fields = fyo.schemaMap[this.df.target].tableFields ?? []; return fields.map((fieldname) => fyo.getField(this.df.target, fieldname)); }, }, watch: { value() { this.setMaxHeight(); }, }, mounted() { if (fyo.store.isDevelopment) { window.tab = this; } }, methods: { focus() {}, async addRow() { await this.doc.append(this.df.fieldname); await nextTick(); this.scrollToRow(this.value.length - 1); this.triggerChange(this.value); }, removeRow(row) { this.doc.remove(this.df.fieldname, row.idx).then((s) => { if (!s) { return; } this.triggerChange(this.value); }); }, scrollToRow(index) { const row = this.$refs['table-row'][index]; row && row.$el.scrollIntoView({ block: 'nearest' }); }, setMaxHeight() { if (this.maxRowsBeforeOverflow === 0) { return (this.maxHeight = ''); } const size = this?.value?.length ?? 0; if (size === 0) { return (this.maxHeight = ''); } const rowHeight = this.$refs?.['table-row']?.[0]?.$el.offsetHeight; if (rowHeight === undefined) { return (this.maxHeight = ''); } const maxHeight = rowHeight * Math.min(this.maxRowsBeforeOverflow, size); return (this.maxHeight = `${maxHeight}px`); }, }, }; </script>
2302_79757062/books
src/components/Controls/Table.vue
Vue
agpl-3.0
4,892