Files
backend/src/modules/investments/investment-sync-plan.ts
T
ksv741 af92ac980e
Backend verify / commits (pull_request) Successful in 32s
Backend verify / security (pull_request) Successful in 10s
Backend verify / verify (pull_request) Canceled after 3m55s
fix: scope income and ledger sync to requested intervals (WealthLedger/backend#57)
2026-10-28 20:55:38 +03:00

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())),
};
}