52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
import type { OperationInterval } from './operations/domain/operations-sync-plan';
|
|
|
|
const JANUARY_INDEX = 0;
|
|
const FIRST_DAY_OF_MONTH = 1;
|
|
const EXCLUSIVE_END_OFFSET_MS = 1;
|
|
const NO_END_OFFSET_MS = 0;
|
|
|
|
type Account = { accountId: string; openedOn: null | string };
|
|
|
|
export function accountHistory(
|
|
accounts: Account[],
|
|
now: Date,
|
|
): OperationInterval[] {
|
|
return accounts.flatMap((account) => {
|
|
const from = new Date(
|
|
account.openedOn
|
|
? `${account.openedOn}T00:00:00Z`
|
|
: '1970-01-01T00:00:00Z',
|
|
);
|
|
return from < now ? [{ accountId: account.accountId, from, to: now }] : [];
|
|
});
|
|
}
|
|
|
|
export function ledgerRange(
|
|
fromValue: string | undefined,
|
|
toValue: string | undefined,
|
|
instrumentUid: string | undefined,
|
|
accounts: Account[],
|
|
now: Date,
|
|
) {
|
|
const opening = accounts.every((account) => account.openedOn)
|
|
// eslint-disable-next-line sonarjs/no-alphabetical-sort -- Code-unit ordering is intentional for canonical keys and ISO dates; locale collation would change persisted bindings.
|
|
? accounts.map((account) => account.openedOn ?? '').sort()[0]
|
|
: undefined;
|
|
const from = fromValue
|
|
? new Date(fromValue)
|
|
: instrumentUid
|
|
? new Date(opening ? `${opening}T00:00:00Z` : '1970-01-01T00:00:00Z')
|
|
: new Date(Date.UTC(now.getUTCFullYear(), JANUARY_INDEX, FIRST_DAY_OF_MONTH));
|
|
const end = toValue
|
|
? new Date(
|
|
/^\d{4}-\d{2}-\d{2}$/.test(toValue)
|
|
? `${toValue}T23:59:59.999Z`
|
|
: toValue,
|
|
)
|
|
: now;
|
|
return {
|
|
from,
|
|
to: new Date(Math.min(end.valueOf() + (toValue ? EXCLUSIVE_END_OFFSET_MS : NO_END_OFFSET_MS), now.valueOf())),
|
|
};
|
|
}
|