2022-04-24 06:48:44 +00:00
|
|
|
import { Doc } from 'fyo/model/doc';
|
2023-04-03 05:04:59 +00:00
|
|
|
import { ReadOnlyMap } from 'fyo/model/types';
|
2022-04-07 09:27:01 +00:00
|
|
|
|
2022-04-11 07:15:35 +00:00
|
|
|
function getPaddedName(prefix: string, next: number, padZeros: number): string {
|
|
|
|
return prefix + next.toString().padStart(padZeros ?? 4, '0');
|
|
|
|
}
|
|
|
|
|
2022-04-07 09:27:01 +00:00
|
|
|
export default class NumberSeries extends Doc {
|
2022-05-02 10:15:16 +00:00
|
|
|
setCurrent() {
|
|
|
|
let current = this.get('current') as number | null;
|
2022-07-07 11:28:58 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Increment current if it isn't the first entry. This
|
|
|
|
* is to prevent reassignment of NumberSeries document ids.
|
|
|
|
*/
|
|
|
|
|
2022-05-02 10:15:16 +00:00
|
|
|
if (!current) {
|
|
|
|
current = this.get('start') as number;
|
2022-07-07 11:28:58 +00:00
|
|
|
} else {
|
|
|
|
current = current + 1;
|
2022-04-07 09:27:01 +00:00
|
|
|
}
|
2022-05-02 10:15:16 +00:00
|
|
|
|
|
|
|
this.current = current;
|
2022-04-07 09:27:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async next(schemaName: string) {
|
2022-05-02 10:15:16 +00:00
|
|
|
this.setCurrent();
|
2022-04-07 09:27:01 +00:00
|
|
|
const exists = await this.checkIfCurrentExists(schemaName);
|
2022-07-07 11:28:58 +00:00
|
|
|
|
|
|
|
if (exists) {
|
|
|
|
this.current = (this.current as number) + 1;
|
2022-04-07 09:27:01 +00:00
|
|
|
}
|
|
|
|
|
2022-04-24 06:48:44 +00:00
|
|
|
await this.sync();
|
2022-04-07 09:27:01 +00:00
|
|
|
return this.getPaddedName(this.current as number);
|
|
|
|
}
|
|
|
|
|
|
|
|
async checkIfCurrentExists(schemaName: string) {
|
|
|
|
if (!schemaName) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
const name = this.getPaddedName(this.current as number);
|
2022-04-19 05:59:36 +00:00
|
|
|
return await this.fyo.db.exists(schemaName, name);
|
2022-04-07 09:27:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
getPaddedName(next: number): string {
|
2022-04-11 07:15:35 +00:00
|
|
|
return getPaddedName(this.name as string, next, this.padZeros as number);
|
2022-04-07 09:27:01 +00:00
|
|
|
}
|
2023-04-03 05:04:59 +00:00
|
|
|
|
|
|
|
readOnly: ReadOnlyMap = {
|
|
|
|
referenceType: () => this.inserted,
|
|
|
|
padZeros: () => this.inserted,
|
|
|
|
start: () => this.inserted,
|
|
|
|
};
|
2022-04-07 09:27:01 +00:00
|
|
|
}
|