All files / account-summary/domain account-summary-event-handler-with-cancel.ts

76.81% Statements 53/69
56.25% Branches 18/32
100% Functions 6/6
76.47% Lines 52/68

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                      1x   5x 5x 5x 5x               5x     5x                             5x   5x       5x 5x   5x 1x     1x               4x           4x       4x 1x     1x               3x         3x 3x 3x       3x       3x         3x 1x               2x         2x     2x   2x                                       2x 2x   2x         2x           2x   2x 1x 1x       1x       1x             1x 1x     1x       1x                                   2x 2x 2x 2x                                               2x   2x   2x                                                    
import { inject, injectable } from "tsyringe";
import type { Logger } from "pino";
import { tokens } from "../../registry/tokens.js";
import { AccountSummaryEventHandlerClean } from "./account-summary-event-handler-clean.js";
import { TransactionLogService } from "./transaction-log.service.js";
import { AccountSummaryEventV2 } from "./account-summary-event.js";
import { AccountSummaryEntity } from "../entity/account.summary.entity.js";
import { Result } from "../../tr8-script/domain/utils/types.js";
import { CostBasisRecalculationService } from "./cost-basis-recalculation.service.js";
 
@injectable()
class AccountSummaryEventHandlerWithCancel {
  constructor(
    @inject(tokens.Logger) private readonly logger: Logger,
    private readonly baseHandler: AccountSummaryEventHandlerClean,
    private readonly transactionLogService: TransactionLogService,
    private readonly costBasisRecalculationService: CostBasisRecalculationService,
  ) {}
 
  async handle(
    event: AccountSummaryEventV2,
    partition: number,
    offset: string,
  ): Promise<Result<AccountSummaryEntity[], Error>> {
    try {
      // This handler is only called for cancel events now
      // Normal events are handled directly by AccountSummaryEventHandlerClean
      return await this.handleCancelEvent(event, partition, offset);
    } catch (error) {
      this.logger.error(
        { err: error },
        "[AccountSummaryHandlerWithCancel] Failed to handle cancel event",
      );
      return { ok: false, error: error as Error };
    }
  }
 
  private async handleCancelEvent(
    event: AccountSummaryEventV2,
    _partition: number,
    _offset: string,
  ): Promise<Result<AccountSummaryEntity[], Error>> {
    try {
      const metadata =
        typeof event.metadata === "string"
          ? JSON.parse(event.metadata)
          : event.metadata;
 
      const alpacaEventIdToCancel = metadata.alpaca_non_trade_event_id;
      const cancelEventId = event.id;
 
      if (!alpacaEventIdToCancel) {
        this.logger.error(
          `[CancelEvent] Missing alpaca_non_trade_event_id in cancel event ${cancelEventId}`,
        );
        return {
          ok: false,
          error: new Error(
            `Missing alpaca_non_trade_event_id in cancel event ${cancelEventId}`,
          ),
        };
      }
 
      this.logger.info(
        `[CancelEvent] Processing cancel event ${cancelEventId} for alpaca_event_id ${alpacaEventIdToCancel}`,
      );
 
      // STEP 1: Find ALL original transactions by alpaca_non_trade_event_id
      const originalTransactions =
        await this.transactionLogService.findAllByAlpacaNonTradeEventId(
          alpacaEventIdToCancel,
        );
 
      if (!originalTransactions || originalTransactions.length === 0) {
        this.logger.error(
          `[CancelEvent] Original transactions not found for alpaca_event_id ${alpacaEventIdToCancel}`,
        );
        return {
          ok: false,
          error: new Error(
            `Original transactions not found for alpaca_event_id ${alpacaEventIdToCancel}`,
          ),
        };
      }
 
      this.logger.info(
        `[CancelEvent] Found ${originalTransactions.length} original transaction(s) for alpaca_event_id ${alpacaEventIdToCancel}`,
      );
 
      // Get the earliest transaction time for propagation
      const earliestTxTime = originalTransactions.reduce((earliest, tx) => {
        const txTime = new Date(tx.transaction_time);
        return txTime < earliest ? txTime : earliest;
      }, new Date(originalTransactions[0]!.transaction_time));
 
      // Get bookId from first transaction
      const bookId = originalTransactions[0]!.book_id;
 
      // STEP 2: Mark ALL originals as SUPERSEDED
      const markResult =
        await this.transactionLogService.markAllAsSupersededByAlpacaNonTradeEventId(
          alpacaEventIdToCancel,
          cancelEventId,
        );
 
      if (!markResult.ok) {
        return {
          ok: false,
          error: new Error(
            `Failed to mark event ${alpacaEventIdToCancel} as superseded: ${markResult.error.message}`,
          ),
        };
      }
 
      this.logger.info(
        `[CancelEvent] Marked ${markResult.value} transaction(s) as SUPERSEDED`,
      );
 
      // STEP 3: Save cancel event to transaction log
      await this.saveToTransactionLog(event);
 
      // STEP 4: Extract COST-BASIS account ID for recalculation
      const accountId = this.extractCostBasisAccountId(event, bookId);
 
      Iif (!accountId) {
        this.logger.warn(
          `[CancelEvent] Could not extract COST-BASIS account ID from event`,
        );
        return {
          ok: false,
          error: new Error(
            `Could not extract COST-BASIS account ID from cancel event`,
          ),
        };
      }
 
      // STEP 5: Full replay from cancel date (NOT nextDay)
      // This handles cases where there are multiple transactions on the same day
      // e.g., Day 17: ADD 30@13 (canceled) + SUB 40 (should be recalculated with new avg)
      //
      // By replaying from cancel date:
      // 1. Get snapshot BEFORE cancel date (e.g., Day 16)
      // 2. Replay ALL ACTIVE transactions from cancel date onwards
      // 3. The canceled transaction is already marked SUPERSEDED, so it will be skipped
      const cancelDate = new Date(earliestTxTime);
      cancelDate.setHours(0, 0, 0, 0);
 
      this.logger.info(
        `[CancelEvent] Starting full replay from cancel date ${cancelDate.toISOString()} for account ${accountId}`,
      );
 
      const recalcResult =
        await this.costBasisRecalculationService.recalculateFromDate(
          bookId,
          accountId,
          cancelDate,
        );
 
      let allUpdatedSummaries: AccountSummaryEntity[] = [];
 
      if (recalcResult.ok) {
        allUpdatedSummaries = recalcResult.value;
        this.logger.info(
          `[CancelEvent] Full replay completed. Recalculated ${recalcResult.value.length} snapshots`,
        );
      } else {
        this.logger.error(
          { err: recalcResult.error },
          `[CancelEvent] Full replay failed`,
        );
        return {
          ok: false,
          error: new Error(`Full replay failed: ${recalcResult.error.message}`),
        };
      }
 
      // STEP 9: Send to GTI
      Eif (allUpdatedSummaries.length > 0) {
        await this.baseHandler.sendToGtiEvent(allUpdatedSummaries);
      }
 
      this.logger.info(
        `[CancelEvent] Cancel event processing completed. Total updated: ${allUpdatedSummaries.length} snapshots`,
      );
 
      return { ok: true, value: allUpdatedSummaries };
    } catch (error) {
      this.logger.error(
        { err: error },
        "[CancelEvent] Failed to handle cancel event",
      );
      return { ok: false, error: error as Error };
    }
  }
 
  /**
   * Extract COST-BASIS account ID from event metrics
   */
  private extractCostBasisAccountId(
    event: AccountSummaryEventV2,
    bookId: string,
  ): string | null {
    // Try to get from metrics first
    Eif (event.metrics && event.metrics.length > 0) {
      for (const metric of event.metrics) {
        Eif (metric.account.includes("COST-BASIS")) {
          return metric.account;
        }
      }
    }
 
    // Try to get from metadata ticker
    const metadata =
      typeof event.metadata === "string"
        ? JSON.parse(event.metadata)
        : event.metadata;
 
    if (metadata?.ticker) {
      // Construct account ID from ticker
      // Format: gti-staging-S-OWN-BRK.B-COST-BASIS
      const prefix = bookId.split(":")[1] || "gti-staging";
      return `${prefix}-S-OWN-${metadata.ticker}-COST-BASIS`;
    }
 
    return null;
  }
 
  private async saveToTransactionLog(
    event: AccountSummaryEventV2,
  ): Promise<void> {
    try {
      const transactionDetails =
        this.transactionLogService.extractTransactionDetails(event);
 
      for (const details of transactionDetails) {
        const result = await this.transactionLogService.saveTransaction(
          details,
        );
 
        if (result.ok) {
          this.logger.info(
            `[TransactionLog] Saved transaction for event ${details.eventId}, operation=${details.operation}`,
          );
        } else {
          this.logger.error(
            { err: result.error },
            `[TransactionLog] Failed to save transaction for event ${details.eventId}`,
          );
        }
      }
    } catch (error) {
      this.logger.error(
        { err: error },
        "[TransactionLog] Failed to save to transaction log",
      );
    }
  }
}
 
export { AccountSummaryEventHandlerWithCancel };