2
0
mirror of https://github.com/frappe/books.git synced 2024-12-24 11:55:46 +00:00
books/fyo/model/naming.ts

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

106 lines
2.3 KiB
TypeScript
Raw Normal View History

import { Fyo } from 'fyo';
import NumberSeries from 'fyo/models/NumberSeries';
import { DEFAULT_SERIES_START } from 'fyo/utils/consts';
import { BaseError } from 'fyo/utils/errors';
import { getRandomString } from 'utils';
import { Doc } from './doc';
export function isNameAutoSet(schemaName: string, fyo: Fyo): boolean {
const schema = fyo.schemaMap[schemaName]!;
if (schema.naming === 'manual') {
return false;
}
if (schema.naming === 'autoincrement') {
return true;
}
if (schema.naming === 'random') {
return true;
}
const numberSeries = fyo.getField(schema.name, 'numberSeries');
if (numberSeries) {
return true;
}
2022-03-08 08:12:08 +00:00
return false;
}
2018-03-05 16:45:21 +00:00
export async function setName(doc: Doc, fyo: Fyo) {
if (doc.schema.naming === 'manual') {
return;
}
if (doc.schema.naming === 'autoincrement') {
return (doc.name = await getNextId(doc.schemaName, fyo));
}
2022-03-08 08:12:08 +00:00
if (doc.numberSeries !== undefined) {
return (doc.name = await getSeriesNext(
doc.numberSeries as string,
doc.schemaName,
fyo
));
}
2022-05-01 04:45:47 +00:00
// name === schemaName for Single
if (doc.schema.isSingle) {
return (doc.name = doc.schemaName);
}
// Assign a random name by default
if (!doc.name) {
doc.name = getRandomString();
}
return doc.name;
}
export async function getNextId(schemaName: string, fyo: Fyo): Promise<string> {
const lastInserted = await fyo.db.getLastInserted(schemaName);
return String(lastInserted + 1).padStart(9, '0');
}
export async function getSeriesNext(
prefix: string,
schemaName: string,
fyo: Fyo
) {
let series: NumberSeries;
try {
series = (await fyo.doc.getDoc('NumberSeries', prefix)) as NumberSeries;
} catch (e) {
const { statusCode } = e as BaseError;
if (!statusCode || statusCode !== 404) {
throw e;
}
2022-03-08 08:12:08 +00:00
await createNumberSeries(prefix, schemaName, DEFAULT_SERIES_START, fyo);
series = (await fyo.doc.getDoc('NumberSeries', prefix)) as NumberSeries;
}
2018-03-27 13:55:26 +00:00
return await series.next(schemaName);
}
export async function createNumberSeries(
prefix: string,
referenceType: string,
start: number,
fyo: Fyo
) {
const exists = await fyo.db.exists('NumberSeries', prefix);
if (exists) {
return;
}
2022-03-08 08:12:08 +00:00
const series = fyo.doc.getNewDoc('NumberSeries', {
name: prefix,
start,
referenceType,
});
2022-03-08 08:12:08 +00:00
await series.sync();
}