Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 | 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 4x 5x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 1x 1x 1x 4x 4x 5x 1x 1x 1x 5x 11x 11x 11x 11x 11x 11x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 1x 1x 1x 5x | import { inject, injectable } from "tsyringe";
import type { Logger } from "pino";
import { tokens } from "../../registry/tokens.js";
import { AppDataSourceService } from "./data-source.js";
import { TransactionLogService } from "./transaction-log.service.js";
import { AccountSummaryEntity } from "../entity/account.summary.entity.js";
import { AccountSummaryRedisStore } from "../store/summary-redis.store.js";
import { CostBasisTransactionLogEntity } from "../entity/cost-basis-transaction-log.entity.js";
import { Result } from "../../tr8-script/domain/utils/types.js";
import { Amount } from "../../tr8-script/domain/value.js";
import { AmountMapper } from "../../commons/mappers/amount.mapper.js";
import {
plus,
minus,
times,
divide,
} from "../../tr8-script/domain/utils/math.js";
import { LessThan, MoreThanOrEqual } from "typeorm";
interface RecalculatedSnapshot {
date: Date;
cost_basis: Amount;
qty: Amount;
avg: Amount;
}
@injectable()
class CostBasisRecalculationService {
constructor(
@inject(tokens.Logger) private readonly logger: Logger,
private readonly appDataSourceService: AppDataSourceService,
private readonly transactionLogService: TransactionLogService,
private readonly accountSummaryRedisStore: AccountSummaryRedisStore,
) {}
async recalculateFromDate(
bookId: string,
accountId: string,
fromDate: Date,
): Promise<Result<AccountSummaryEntity[], Error>> {
try {
this.logger.info(
{
bookId,
accountId,
fromDate: fromDate.toISOString(),
},
`[RecalculationService] Starting recalculation`,
);
// STEP 1: Get initial state (snapshot before fromDate)
const snapshotBefore = await this.getSnapshotBefore(
bookId,
accountId,
fromDate,
);
let cost: Amount = snapshotBefore?.cost_basis || {
amount: 0n,
scale: 0n,
};
let qty: Amount = snapshotBefore?.qty || { amount: 0n, scale: 0n };
this.logger.info(
`[RecalculationService] Initial state: cost=${
AmountMapper.toDTO(cost).amount
}, qty=${AmountMapper.toDTO(qty).amount}`,
);
// STEP 2: Get all ACTIVE transactions from fromDate to max(now, fromDate + 1 year)
// This handles cases where transaction_time is in the future (e.g., scheduled events)
const now = new Date();
const oneYearFromDate = new Date(fromDate);
oneYearFromDate.setFullYear(oneYearFromDate.getFullYear() + 1);
const toDate = now > oneYearFromDate ? now : oneYearFromDate;
const transactionsResult =
await this.transactionLogService.getActiveTransactions(
bookId,
accountId,
fromDate,
toDate,
);
Iif (!transactionsResult.ok) {
return { ok: false, error: transactionsResult.error };
}
const transactions = transactionsResult.value;
this.logger.info(
{
count: transactions.length,
transactions: transactions.map((t) => ({
event_id: t.event_id,
operation: t.operation,
qty: t.qty,
price: t.price,
status: t.status,
transaction_time: t.transaction_time,
})),
},
`[RecalculationService] Found ${transactions.length} active transactions to replay`,
);
// STEP 3: Group transactions by date
const groupedByDate = this.groupByDate(transactions);
// STEP 4: Replay transactions date by date
const recalculatedSnapshots: RecalculatedSnapshot[] = [];
for (const [dateStr, txsOnDate] of Object.entries(groupedByDate)) {
const date = new Date(dateStr);
this.logger.info(
`[RecalculationService] Processing ${txsOnDate.length} transactions for ${dateStr}`,
);
for (const tx of txsOnDate) {
// Check if this is a non-trade event
// Simple check: if alpaca_non_trade_event_id exists, it's a non-trade event
const isNonTradeEvent = !!tx.alpaca_non_trade_event_id;
Iif (isNonTradeEvent) {
// For non-trade events:
// - ADD: receive shares, cost basis = shares * price (from metadata)
// - SUB: return/remove shares, cost basis reduced by shares * average
const shareQtyStr =
tx.metadata?.share_quantity?.toString() || tx.qty || "0";
const shareQty = AmountMapper.fromDTO({
amount: this.parseDecimalToInteger(shareQtyStr),
scale: "0",
});
const eventLabel =
tx.metadata?.event_type ||
tx.metadata?.event_sub_type ||
"NON-TRADE";
if (tx.operation === "ADD") {
// Non-trade ADD: receive shares
// cost += share_quantity * price (from metadata or tx.price)
const priceStr =
tx.metadata?.price?.toString() || tx.price || "0";
const txPrice = AmountMapper.fromDTO({
amount: this.parseDecimalToInteger(priceStr),
scale: "0",
});
const addCost = times(shareQty, txPrice) as Amount;
cost = plus(cost, addCost) as Amount;
qty = plus(qty, shareQty) as Amount;
this.logger.info(
`[RecalculationService] ${eventLabel} ADD ${
tx.event_id
}: share_qty=${shareQtyStr}, price=${priceStr}, new_cost=${
AmountMapper.toDTO(cost).amount
}, new_qty=${AmountMapper.toDTO(qty).amount}`,
);
} else if (tx.operation === "SUB") {
// Non-trade SUB: return/remove shares
// cost -= share_quantity * average
if (qty.amount > 0n) {
const avg = divide(cost, qty) as Amount;
const subCost = times(shareQty, avg) as Amount;
cost = minus(cost, subCost) as Amount;
qty = minus(qty, shareQty) as Amount;
this.logger.info(
`[RecalculationService] ${eventLabel} SUB ${
tx.event_id
}: share_qty=${shareQtyStr}, avg=${
AmountMapper.toDTO(avg).amount
}, new_cost=${AmountMapper.toDTO(cost).amount}, new_qty=${
AmountMapper.toDTO(qty).amount
}`,
);
} else {
this.logger.warn(
`[RecalculationService] Skipping ${eventLabel} SUB ${tx.event_id}: qty is 0`,
);
}
}
continue;
}
// For trade events: get share_quantity from metadata
// Fallback to tx.qty for legacy transactions
const shareQtyStr =
tx.metadata?.share_quantity?.toString() || tx.qty || "0";
const shareQty = AmountMapper.fromDTO({
amount: this.parseDecimalToInteger(shareQtyStr),
scale: "0",
});
if (tx.operation === "ADD") {
// Trade ADD: cost += share_quantity * price
const txPrice = AmountMapper.fromDTO({
amount: this.parseDecimalToInteger(tx.price),
scale: "0",
});
const addCost = times(shareQty, txPrice) as Amount;
cost = plus(cost, addCost) as Amount;
qty = plus(qty, shareQty) as Amount;
this.logger.info(
`[RecalculationService] TRADE ADD ${
tx.event_id
}: share_qty=${shareQtyStr}, price=${tx.price}, new_cost=${
AmountMapper.toDTO(cost).amount
}, new_qty=${AmountMapper.toDTO(qty).amount}`,
);
E} else if (tx.operation === "SUB") {
// Trade SUB: cost -= share_quantity * avg
if (qty.amount > 0n) {
const avg = divide(cost, qty) as Amount;
const subCost = times(shareQty, avg) as Amount;
cost = minus(cost, subCost) as Amount;
qty = minus(qty, shareQty) as Amount;
this.logger.info(
`[RecalculationService] TRADE SUB ${
tx.event_id
}: share_qty=${shareQtyStr}, avg=${
AmountMapper.toDTO(avg).amount
}, new_cost=${AmountMapper.toDTO(cost).amount}, new_qty=${
AmountMapper.toDTO(qty).amount
}`,
);
} else E{
this.logger.warn(
`[RecalculationService] Skipping TRADE SUB ${tx.event_id}: qty is 0`,
);
}
}
}
// Save snapshot for this date
const avg =
qty.amount > 0n
? (divide(cost, qty) as Amount)
: { amount: 0n, scale: 0n };
recalculatedSnapshots.push({
date,
cost_basis: cost,
qty,
avg,
});
this.logger.info(
`[RecalculationService] Snapshot for ${dateStr}: cost=${
AmountMapper.toDTO(cost).amount
}, qty=${AmountMapper.toDTO(qty).amount}, avg=${
AmountMapper.toDTO(avg).amount
}`,
);
}
// STEP 5: Get ALL AccountSummaryEntity from fromDate onwards
// We need to update entities even if they don't have transactions on that day
// because the cost_basis/qty values need to carry forward
const allEntitiesFromDate = await this.getAllEntitiesFromDate(
bookId,
accountId,
fromDate,
);
// STEP 6: Build snapshots for ALL dates (including days without transactions)
// by carrying forward the last calculated values
// We pass the INITIAL cost/qty (from snapshot before fromDate) to start the carry-forward
const initialCost: Amount = snapshotBefore?.cost_basis || {
amount: 0n,
scale: 0n,
};
const initialQty: Amount = snapshotBefore?.qty || {
amount: 0n,
scale: 0n,
};
const allSnapshots = this.buildAllSnapshots(
recalculatedSnapshots,
allEntitiesFromDate,
initialCost,
initialQty,
);
// STEP 7: Update AccountSummaryEntity for each affected date
const updatedEntities = await this.updateAccountSummaryEntities(
bookId,
accountId,
allSnapshots,
);
this.logger.info(
`[RecalculationService] Recalculation completed. Updated ${updatedEntities.length} snapshots`,
);
return { ok: true, value: updatedEntities };
} catch (error) {
this.logger.error(
{ err: error },
"[RecalculationService] Recalculation failed",
);
return { ok: false, error: error as Error };
}
}
/**
* Get snapshot before the given date
* IMPORTANT: Check Redis first, then DB, because summaries may not be flushed to DB yet
*/
private async getSnapshotBefore(
bookId: string,
accountId: string,
beforeDate: Date,
): Promise<{ cost_basis: Amount; qty: Amount } | null> {
try {
let snapshot: AccountSummaryEntity | null = null;
// STEP 1: Check Redis first (summaries may not be flushed to DB yet)
const redisResult = await this.accountSummaryRedisStore.get(bookId);
if (redisResult.ok && redisResult.value && redisResult.value.length > 0) {
// Find the latest snapshot before beforeDate in Redis
let latestBeforeDate: AccountSummaryEntity | null = null;
let latestTime: Date | null = null;
for (const entity of redisResult.value) {
Iif (!entity.transaction_time) continue;
const txTime =
entity.transaction_time instanceof Date
? entity.transaction_time
: new Date(entity.transaction_time);
Iif (txTime < beforeDate) {
if (!latestTime || txTime > latestTime) {
latestTime = txTime;
latestBeforeDate = entity;
}
}
}
Iif (latestBeforeDate) {
snapshot = latestBeforeDate;
this.logger.info(
{
bookId,
beforeDate: beforeDate.toISOString(),
foundAt: latestTime?.toISOString(),
},
`[RecalculationService] Found snapshot before date in Redis`,
);
}
}
// STEP 2: If not found in Redis, check DB
Eif (!snapshot) {
const repository =
this.appDataSourceService.AppDataSource.getRepository(
AccountSummaryEntity,
);
snapshot = await repository.findOne({
where: {
book_id: bookId,
transaction_time: LessThan(beforeDate),
},
order: {
transaction_time: "DESC",
},
});
if (snapshot) {
this.logger.info(
{
bookId,
beforeDate: beforeDate.toISOString(),
foundAt: snapshot.transaction_time?.toISOString(),
},
`[RecalculationService] Found snapshot before date in DB`,
);
}
}
if (!snapshot || !snapshot.metrics) {
return null;
}
// Find the COST-BASIS metric - try both directions for flexible matching
// This handles format differences like:
// - "S-OWN-BRK.B-COST-BASIS" vs "gti-staging-S-OWN-BRK.B-COST-BASIS"
const costBasisMetric = snapshot.metrics.find(
(m) =>
m.account_id.includes(accountId) ||
accountId.includes(m.account_id) ||
this.extractTickerFromAccountId(m.account_id) ===
this.extractTickerFromAccountId(accountId),
);
Iif (!costBasisMetric) {
this.logger.warn(
{
accountId,
availableMetrics: snapshot.metrics.map((m) => m.account_id),
},
"[RecalculationService] COST-BASIS metric not found in snapshot",
);
return null;
}
const cost_basis = AmountMapper.fromDTO({
amount: costBasisMetric.amount,
scale: costBasisMetric.scale,
});
// Find corresponding qty from summary (S-OWN-XXX account)
// Extract ticker from accountId (e.g., "S-OWN-BRK.B-COST-BASIS" -> "BRK.B")
const ticker = this.extractTickerFromAccountId(accountId);
const qtyAccountPattern = `S-OWN-${ticker}`;
let qty: Amount = { amount: 0n, scale: 0n };
Eif (snapshot.summary) {
for (const summaryItem of snapshot.summary) {
Eif (summaryItem.account_id.includes(qtyAccountPattern)) {
qty = AmountMapper.fromDTO({
amount: summaryItem.value,
scale: summaryItem.scale,
});
break;
}
}
}
return { cost_basis, qty };
} catch (error) {
this.logger.error(
{ err: error },
"[RecalculationService] Failed to get snapshot before",
);
return null;
}
}
private groupByDate(
transactions: CostBasisTransactionLogEntity[],
): Record<string, CostBasisTransactionLogEntity[]> {
const grouped: Record<string, CostBasisTransactionLogEntity[]> = {};
for (const tx of transactions) {
const dateStr = tx.transaction_time.toISOString().split("T")[0] || "";
Eif (!grouped[dateStr]) {
grouped[dateStr] = [];
}
grouped[dateStr]?.push(tx);
}
return grouped;
}
private async updateAccountSummaryEntities(
bookId: string,
accountId: string,
snapshots: RecalculatedSnapshot[],
): Promise<AccountSummaryEntity[]> {
const repository =
this.appDataSourceService.AppDataSource.getRepository(
AccountSummaryEntity,
);
const updatedEntities: AccountSummaryEntity[] = [];
this.logger.info(
{
bookId,
accountId,
snapshotCount: snapshots.length,
snapshots: snapshots.map((s) => ({
date: s.date.toISOString(),
cost_basis: AmountMapper.toDTO(s.cost_basis).amount,
qty: AmountMapper.toDTO(s.qty).amount,
})),
},
`[RecalculationService] Updating ${snapshots.length} snapshot(s)`,
);
// STEP 1: Get ALL summaries from Redis first (may not be flushed to DB)
const redisResult = await this.accountSummaryRedisStore.get(bookId);
const redisSummaries: AccountSummaryEntity[] =
redisResult.ok && redisResult.value ? redisResult.value : [];
this.logger.info(
{
bookId,
redisSummariesCount: redisSummaries.length,
},
`[RecalculationService] Found ${redisSummaries.length} summaries in Redis for update`,
);
// STEP 2: Get ALL entities from DB
const dbEntities = await repository.find({
where: {
book_id: bookId,
},
order: {
transaction_time: "DESC",
},
});
this.logger.info(
{
bookId,
dbEntitiesCount: dbEntities.length,
},
`[RecalculationService] Found ${dbEntities.length} entities in DB for update`,
);
// Track which Redis entries were updated
let redisUpdated = false;
for (const snapshot of snapshots) {
// Find existing AccountSummaryEntity for this date
const dateOnly = new Date(snapshot.date);
dateOnly.setHours(0, 0, 0, 0);
// STEP 3: Try to find entity in Redis first
let entity: AccountSummaryEntity | undefined;
let foundInRedis = false;
let redisIndex = -1;
for (let i = 0; i < redisSummaries.length; i++) {
const e = redisSummaries[i];
Iif (!e?.transaction_time) continue;
const entityDate = new Date(e.transaction_time);
entityDate.setHours(0, 0, 0, 0);
Eif (entityDate.getTime() === dateOnly.getTime()) {
entity = e;
foundInRedis = true;
redisIndex = i;
break;
}
}
// STEP 4: If not in Redis, find in DB
if (!entity) {
entity = dbEntities.find((e) => {
Iif (!e.transaction_time) return false;
const entityDate = new Date(e.transaction_time);
entityDate.setHours(0, 0, 0, 0);
return entityDate.getTime() === dateOnly.getTime();
});
}
Iif (!entity) {
this.logger.warn(
{
bookId,
accountId,
dateOnly: dateOnly.toISOString(),
},
`[RecalculationService] No entity found for date (checked Redis and DB)`,
);
continue;
}
this.logger.info(
{
bookId,
dateOnly: dateOnly.toISOString(),
foundInRedis,
},
`[RecalculationService] Found entity for date in ${
foundInRedis ? "Redis" : "DB"
}`,
);
Iif (!entity.metrics) {
this.logger.warn(
{
bookId,
accountId,
dateOnly: dateOnly.toISOString(),
},
`[RecalculationService] Entity has no metrics`,
);
continue;
}
// Update the COST-BASIS metric - try both exact match and includes
let metricIndex = entity.metrics.findIndex(
(m) => m.account_id === accountId,
);
// Fallback: try includes match (both directions)
Iif (metricIndex < 0) {
metricIndex = entity.metrics.findIndex(
(m) =>
m.account_id.includes(accountId) ||
accountId.includes(m.account_id),
);
}
this.logger.info(
{
accountId,
metricIndex,
availableMetrics: entity.metrics.map((m) => m.account_id),
},
`[RecalculationService] Looking for metric`,
);
if (metricIndex >= 0) {
const metric = entity.metrics[metricIndex];
Eif (metric) {
const oldAmount = metric.amount;
metric.amount = AmountMapper.toDTO(snapshot.cost_basis).amount;
metric.scale = AmountMapper.toDTO(snapshot.cost_basis).scale;
this.logger.info(
{
date: snapshot.date.toISOString(),
accountId: metric.account_id,
oldAmount,
newAmount: metric.amount,
},
`[RecalculationService] Updated cost_basis metric`,
);
}
} else E{
this.logger.warn(
{
accountId,
availableMetrics: entity.metrics.map((m) => m.account_id),
},
`[RecalculationService] Metric not found in entity`,
);
}
// Also update the summary (stock quantity) - S-OWN-XXX account
// Now qty is correctly tracked as share_quantity from metadata
if (entity.summary) {
const ticker = this.extractTickerFromAccountId(accountId);
const qtyAccountPattern = `S-OWN-${ticker}`;
const summaryIndex = entity.summary.findIndex(
(s) =>
s.account_id === qtyAccountPattern ||
s.account_id.includes(qtyAccountPattern) ||
(s.account_id.includes("S-OWN-") &&
s.account_id.includes(ticker) &&
!s.account_id.includes("COST-BASIS")),
);
if (summaryIndex >= 0) {
const summaryItem = entity.summary[summaryIndex];
Eif (summaryItem) {
const oldQty = summaryItem.value;
summaryItem.value = AmountMapper.toDTO(snapshot.qty).amount;
summaryItem.scale = AmountMapper.toDTO(snapshot.qty).scale;
this.logger.info(
{
date: snapshot.date.toISOString(),
accountId: summaryItem.account_id,
oldQty,
newQty: summaryItem.value,
},
`[RecalculationService] Updated summary qty`,
);
}
} else E{
this.logger.warn(
{
qtyAccountPattern,
availableSummary: entity.summary.map((s) => s.account_id),
},
`[RecalculationService] Summary account not found for qty update`,
);
}
}
// STEP 5: Save entity to appropriate store
if (foundInRedis && redisIndex >= 0) {
// Update the entity in Redis array
redisSummaries[redisIndex] = entity;
redisUpdated = true;
updatedEntities.push(entity);
} else {
// Save to DB
const saved = await repository.save(entity);
updatedEntities.push(saved);
}
}
// STEP 6: Save updated Redis summaries back to Redis
if (redisUpdated && redisSummaries.length > 0) {
const saveResult = await this.accountSummaryRedisStore.set(
bookId,
redisSummaries,
);
if (saveResult.ok) {
this.logger.info(
{
bookId,
count: redisSummaries.length,
},
`[RecalculationService] Saved updated summaries back to Redis`,
);
} else E{
this.logger.error(
{
bookId,
error: saveResult.error?.message,
},
`[RecalculationService] Failed to save updated summaries to Redis`,
);
}
}
return updatedEntities;
}
private extractTickerFromAccountId(accountId: string): string {
// Extract ticker from account ID
// Format: "S-OWN-BRK.B-COST-BASIS" -> "BRK.B"
// Format: "gti-staging-S-OWN-BRK.B-COST-BASIS" -> "BRK.B"
const parts = accountId.split("-");
const ownIndex = parts.indexOf("OWN");
Eif (ownIndex >= 0 && ownIndex + 1 < parts.length) {
// Find COST-BASIS index
const costIndex = parts.indexOf("COST");
Eif (costIndex > ownIndex) {
// Return everything between OWN and COST
return parts.slice(ownIndex + 1, costIndex).join("-");
}
}
return "";
}
private parseDecimalToInteger(value: string | null): string {
// Handle decimal strings like "4000.00000000" from DECIMAL(20, 8) columns
// AmountMapper.fromDTO expects integer strings, not decimal strings
Iif (!value) return "0";
const intPart = value.split(".")[0];
return intPart || "0";
}
/**
* Get all AccountSummaryEntity records from fromDate onwards for the given bookId
* These need to be updated even if they don't have transactions on that day
*
* IMPORTANT: Check Redis first, then DB, because summaries may not be flushed to DB yet
*/
private async getAllEntitiesFromDate(
bookId: string,
accountId: string,
fromDate: Date,
): Promise<Date[]> {
try {
const ticker = this.extractTickerFromAccountId(accountId);
const dates: Date[] = [];
// STEP 1: Check Redis first (summaries may not be flushed to DB yet)
// Use fromDate - 1 day to ensure we capture summaries at fromDate
const dayBeforeFromDate = new Date(fromDate);
dayBeforeFromDate.setDate(dayBeforeFromDate.getDate() - 1);
const redisSummaries =
await this.accountSummaryRedisStore.getAccountSummariesAfterRedis(
bookId,
dayBeforeFromDate,
);
this.logger.info(
{
bookId,
fromDate: fromDate.toISOString(),
redisSummariesCount: redisSummaries.length,
},
`[RecalculationService] Found ${redisSummaries.length} summaries in Redis`,
);
for (const entity of redisSummaries) {
Iif (!entity.transaction_time) continue;
// Check if this entity has the relevant COST-BASIS metric
const hasRelevantMetric = entity.metrics?.some(
(m) =>
m.account_id.includes(accountId) ||
accountId.includes(m.account_id) ||
(m.account_id.includes("COST-BASIS") &&
m.account_id.includes(ticker)),
);
Eif (hasRelevantMetric) {
const txTime =
entity.transaction_time instanceof Date
? entity.transaction_time
: new Date(entity.transaction_time);
const dateStr = txTime.toISOString().split("T")[0] || "";
const dateOnly = new Date(dateStr + "T00:00:00Z");
// Only include dates >= fromDate
Eif (dateOnly >= fromDate) {
Eif (!dates.some((d) => d.getTime() === dateOnly.getTime())) {
dates.push(dateOnly);
}
}
}
}
// STEP 2: Also check DB (for older summaries that have been flushed)
const repository =
this.appDataSourceService.AppDataSource.getRepository(
AccountSummaryEntity,
);
const dbEntities = await repository.find({
where: {
book_id: bookId,
transaction_time: MoreThanOrEqual(fromDate),
},
order: {
transaction_time: "ASC",
},
});
this.logger.info(
{
bookId,
fromDate: fromDate.toISOString(),
dbEntitiesCount: dbEntities.length,
},
`[RecalculationService] Found ${dbEntities.length} entities in DB`,
);
for (const entity of dbEntities) {
Iif (!entity.transaction_time) continue;
// Check if this entity has the relevant COST-BASIS metric
const hasRelevantMetric = entity.metrics?.some(
(m) =>
m.account_id.includes(accountId) ||
accountId.includes(m.account_id) ||
(m.account_id.includes("COST-BASIS") &&
m.account_id.includes(ticker)),
);
Eif (hasRelevantMetric) {
const dateStr =
entity.transaction_time.toISOString().split("T")[0] || "";
const dateOnly = new Date(dateStr + "T00:00:00Z");
// Avoid duplicates (may already be in Redis)
Eif (!dates.some((d) => d.getTime() === dateOnly.getTime())) {
dates.push(dateOnly);
}
}
}
// Sort dates chronologically
dates.sort((a, b) => a.getTime() - b.getTime());
this.logger.info(
{
bookId,
accountId,
fromDate: fromDate.toISOString(),
datesFound: dates.length,
dates: dates.map((d) => d.toISOString()),
},
`[RecalculationService] Found ${dates.length} dates with entities from fromDate onwards (Redis + DB)`,
);
return dates;
} catch (error) {
this.logger.error(
{ err: error },
"[RecalculationService] Failed to get all entities from date",
);
return [];
}
}
/**
* Build snapshots for ALL dates (including days without transactions)
* by using calculated values for transaction days and carrying forward for other days
*
* @param transactionSnapshots - Snapshots calculated from ACTIVE transactions
* @param allDates - All dates that have AccountSummaryEntity records
* @param initialCost - Cost basis from snapshot BEFORE fromDate (starting point)
* @param initialQty - Stock qty from snapshot BEFORE fromDate (starting point)
*/
private buildAllSnapshots(
transactionSnapshots: RecalculatedSnapshot[],
allDates: Date[],
initialCost: Amount,
initialQty: Amount,
): RecalculatedSnapshot[] {
// Create a map of date -> snapshot for quick lookup
const snapshotMap = new Map<string, RecalculatedSnapshot>();
for (const snapshot of transactionSnapshots) {
const dateStr = snapshot.date.toISOString().split("T")[0] || "";
snapshotMap.set(dateStr, snapshot);
}
// Sort all dates chronologically
const sortedDates = [...allDates].sort((a, b) => a.getTime() - b.getTime());
const allSnapshots: RecalculatedSnapshot[] = [];
// Start from initial state (snapshot before fromDate)
let lastCost = initialCost;
let lastQty = initialQty;
// For each date, use the transaction snapshot if available, otherwise carry forward
for (const date of sortedDates) {
const dateStr = date.toISOString().split("T")[0] || "";
const existingSnapshot = snapshotMap.get(dateStr);
if (existingSnapshot) {
// Use the calculated snapshot from transactions
allSnapshots.push(existingSnapshot);
lastCost = existingSnapshot.cost_basis;
lastQty = existingSnapshot.qty;
} else {
// No transactions on this day, carry forward the last values
const avg =
lastQty.amount > 0n
? (divide(lastCost, lastQty) as Amount)
: { amount: 0n, scale: 0n };
allSnapshots.push({
date,
cost_basis: lastCost,
qty: lastQty,
avg,
});
this.logger.info(
`[RecalculationService] Carry forward for ${dateStr}: cost=${
AmountMapper.toDTO(lastCost).amount
}, qty=${AmountMapper.toDTO(lastQty).amount}`,
);
}
}
return allSnapshots;
}
}
export { CostBasisRecalculationService };
export type { RecalculatedSnapshot };
|