2
0
mirror of https://github.com/frappe/books.git synced 2024-12-23 11:29:03 +00:00
books/models/helpers.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

324 lines
7.1 KiB
TypeScript
Raw Normal View History

import { Fyo, t } from 'fyo';
import { Doc } from 'fyo/model/doc';
2022-06-14 09:10:46 +00:00
import { Action, ColumnConfig, DocStatus, RenderData } from 'fyo/model/types';
import { DateTime } from 'luxon';
2022-05-23 05:30:54 +00:00
import { Money } from 'pesa';
import { safeParseFloat } from 'utils/index';
import { Router } from 'vue-router';
import {
AccountRootType,
AccountRootTypeEnum,
} from './baseModels/Account/types';
2022-10-12 09:29:43 +00:00
import {
Defaults,
numberSeriesDefaultsMap,
2022-10-12 09:29:43 +00:00
} from './baseModels/Defaults/Defaults';
2022-11-22 09:12:49 +00:00
import { Invoice } from './baseModels/Invoice/Invoice';
import { InvoiceStatus, ModelNameEnum } from './types';
2022-12-01 08:31:23 +00:00
export function getInvoiceActions(
fyo: Fyo,
schemaName: ModelNameEnum.SalesInvoice | ModelNameEnum.PurchaseInvoice
): Action[] {
2022-04-14 08:01:33 +00:00
return [
2022-11-22 09:12:49 +00:00
getMakePaymentAction(fyo),
2022-12-01 08:31:23 +00:00
getMakeStockTransferAction(fyo, schemaName),
2022-11-22 09:12:49 +00:00
getLedgerLinkAction(fyo),
];
}
2022-12-01 08:31:23 +00:00
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`;
}
2022-11-22 09:12:49 +00:00
return {
2022-12-01 08:31:23 +00:00
label,
2022-11-30 06:59:52 +00:00
group: fyo.t`Create`,
2022-11-22 09:12:49 +00:00
condition: (doc: Doc) => doc.isSubmitted && !!doc.stockNotTransferred,
action: async (doc: Doc) => {
const transfer = await (doc as Invoice).getStockTransfer();
if (!transfer) {
return;
}
2022-04-14 08:01:33 +00:00
2022-11-22 09:12:49 +00:00
const { routeTo } = await import('src/utils/ui');
const path = `/edit/${transfer.schemaName}/${transfer.name}`;
await routeTo(path);
2022-04-14 08:01:33 +00:00
},
2022-11-22 09:12:49 +00:00
};
}
export function getMakePaymentAction(fyo: Fyo): Action {
return {
2022-11-30 06:59:52 +00:00
label: fyo.t`Payment`,
group: fyo.t`Create`,
2022-11-22 09:12:49 +00:00
condition: (doc: Doc) =>
doc.isSubmitted && !(doc.outstandingAmount as Money).isZero(),
action: async (doc: Doc) => {
const payment = (doc as Invoice).getPayment();
if (!payment) {
return;
}
payment.once('afterSync', async () => {
await payment.submit();
});
const { openQuickEdit } = await import('src/utils/ui');
await openQuickEdit({
doc: payment,
hideFields: ['party', 'paymentType', 'for'],
});
},
};
2022-04-14 08:01:33 +00:00
}
export function getLedgerLinkAction(
fyo: Fyo,
isStock: boolean = false
): Action {
2022-12-01 08:31:23 +00:00
let label = fyo.t`Accounting Entries`;
let reportClassName = 'GeneralLedger';
if (isStock) {
label = fyo.t`Stock Entries`;
reportClassName = 'StockLedger';
}
return {
label,
2022-11-30 06:59:52 +00:00
group: fyo.t`View`,
condition: (doc: Doc) => doc.isSubmitted,
action: async (doc: Doc, router: Router) => {
router.push({
name: 'Report',
params: {
reportClassName,
2022-05-27 07:15:07 +00:00
defaultFilters: JSON.stringify({
referenceType: doc.schemaName,
referenceName: doc.name,
2022-05-27 07:15:07 +00:00
}),
},
});
},
};
}
export function getTransactionStatusColumn(): ColumnConfig {
2022-04-14 08:01:33 +00:00
return {
label: t`Status`,
2022-04-14 08:01:33 +00:00
fieldname: 'status',
fieldtype: 'Select',
2022-06-14 09:10:46 +00:00
render(doc) {
const status = getDocStatus(doc) as InvoiceStatus;
2022-04-14 08:01:33 +00:00
const color = statusColor[status];
const label = getStatusText(status);
2022-06-14 09:10:46 +00:00
2022-04-14 08:01:33 +00:00
return {
template: `<Badge class="text-xs" color="${color}">${label}</Badge>`,
};
},
};
}
2022-06-14 09:10:46 +00:00
export const statusColor: Record<
DocStatus | InvoiceStatus,
string | undefined
> = {
'': 'gray',
2022-04-14 08:01:33 +00:00
Draft: 'gray',
Unpaid: 'orange',
Paid: 'green',
2022-06-14 09:10:46 +00:00
Saved: 'gray',
NotSaved: 'gray',
Submitted: 'green',
2022-04-14 08:01:33 +00:00
Cancelled: 'red',
};
export function getStatusText(status: DocStatus | InvoiceStatus): string {
switch (status) {
case 'Draft':
return t`Draft`;
case 'Saved':
return t`Saved`;
case 'NotSaved':
return t`NotSaved`;
case 'Submitted':
return t`Submitted`;
case 'Cancelled':
return t`Cancelled`;
case 'Paid':
return t`Paid`;
case 'Unpaid':
return t`Unpaid`;
default:
return '';
}
2022-06-14 09:10:46 +00:00
}
export function getDocStatus(
doc?: RenderData | Doc
): DocStatus | InvoiceStatus {
if (!doc) {
return '';
}
if (doc.notInserted) {
return 'Draft';
2022-04-14 08:01:33 +00:00
}
2022-06-14 09:10:46 +00:00
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 (!!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.outstandingAmount as Money).isZero()
) {
return 'Paid';
}
if (
doc.submitted &&
!doc.cancelled &&
(doc.outstandingAmount as Money).isPositive()
) {
return 'Unpaid';
2022-04-14 08:01:33 +00:00
}
if (doc.cancelled) {
2022-06-14 09:10:46 +00:00
return 'Cancelled';
2022-04-14 08:01:33 +00:00
}
2022-06-14 09:10:46 +00:00
return 'Saved';
2022-04-14 08:01:33 +00:00
}
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) 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();
exchangeRate = data.rates[toCurrency];
} catch (error) {
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;
}
}
2022-10-12 09:29:43 +00:00
export function getNumberSeries(schemaName: string, fyo: Fyo) {
const numberSeriesKey = numberSeriesDefaultsMap[schemaName];
if (!numberSeriesKey) {
return undefined;
}
const defaults = fyo.singles.Defaults as Defaults | undefined;
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',
size: 'small',
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>`,
};
},
};
}