Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,15 @@ jobs:
shell: bash
working-directory: InventoryManagementSystem

- name: Integration Test
- name: Integration Test - Api
run: |
cp InventoryManagementSystem/InventoryAlert.IntegrationTests/appsettings.test.json appsettings.test.json
dotnet test InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj --no-restore --no-build --configuration Release --verbosity normal
dotnet test InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj --no-restore --no-build --configuration Release --verbosity normal --filter Category=Api

- name: Integration Test - Jobs
run: |
cp InventoryManagementSystem/InventoryAlert.IntegrationTests/appsettings.test.json appsettings.test.json
dotnet test InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj --no-restore --no-build --configuration Release --verbosity normal --filter Category=Jobs

- name: Run E2E Tests
run: dotnet test InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj --no-restore --configuration Release --verbosity normal
Expand Down
9 changes: 9 additions & 0 deletions InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ SignalR provides an instant push architecture:

---

## Traceability & Observability

Every alert flow is traceable via a unique **CorrelationId**:

1. **API Initiated**: The `X-Correlation-Id` from the HTTP request is propagated to the SQS `EventEnvelope`.
2. **Worker Context**: The `IntegrationMessageRouter` extracts the `CorrelationId` from the envelope and pushes it to the Serilog `LogContext`.
3. **Cross-Project Trace**: Logs in Seq from both the API and Worker are grouped by this ID, allowing deterministic verification in integration tests using `SeqLogReader`.
4. **Message Metadata**: Each log entry also includes `MessageId` and `EventType` for granular debugging.

## Notification Schema

Notifications are now categorized for better UX:
Expand Down
41 changes: 41 additions & 0 deletions InventoryAlert.Wiki/docs/04-execution-flows/earnings-sync-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Earnings Surprise Synchronization Flow

> Orchestration pipeline for fetching historical earnings performance and surprise metrics.

## Sequence

```mermaid
sequenceDiagram
participant HF as Hangfire Scheduler
participant Job as SyncEarningsJob
participant Finnhub as Finnhub API
participant DB as PostgreSQL

HF->>Job: Trigger (Scheduled)
Job->>DB: SELECT TickerSymbols FROM StockListing

loop For each symbol
Job->>Finnhub: GET /stock/earnings?symbol={s}
Finnhub-->>Job: List<EarningsSurprise>
Job->>DB: UpsertRangeAsync(Earnings)
end

Job->>DB: SaveChangesAsync()
```

## Data Points

| Field | Description |
|---|---|
| **Actual EPS** | The actual Earnings Per Share reported by the company. |
| **Estimate EPS** | The consensus analyst estimate for EPS. |
| **Surprise %** | The percentage difference between actual and estimate. |
| **Period** | The fiscal quarter/year for the reported data. |

## Implementation Details

| Feature | Detail |
|---|---|
| **Upsert Logic** | Uses `UpsertRangeAsync` to handle updates to existing periods or additions of new reports. |
| **PostgreSQL Store** | Unlike news, earnings data is stored in PostgreSQL for relational analysis and reporting. |
| **Sequential Processing** | Currently processed sequentially per symbol to respect API rate limits for non-premium tiers. |
70 changes: 70 additions & 0 deletions InventoryAlert.Wiki/docs/04-execution-flows/error-handling-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Error Handling & Standardized Response Flow

> Global pipeline for intercepting failures, mapping them to business-friendly status codes, and ensuring diagnostic traceability.

## Sequence

```mermaid
sequenceDiagram
participant User as User / Client
participant MW as GlobalExceptionMiddleware
participant Controller as ApiController
participant Service as Business Service
participant DB as PostgreSQL

User->>MW: HTTP Request (CorrelationId: CID-123)
MW->>Controller: Invoke next()
Controller->>Service: Call Action

alt Logic failure (e.g., Symbol not found)
Service->>MW: Throw KeyNotFoundException
else Unexpected crash
Service->>MW: Throw SystemException
end

Note over MW: Catch(Exception ex)
MW->>MW: Map Exception Type to HttpStatusCode
MW->>MW: Resolve ErrorRespondCode (e.g. NOT_FOUND)
MW->>MW: Log Error with CorrelationId
MW-->>User: JSON ErrorResponse (500/404/400)
```

## Error Mapping Strategy

The system uses a centralized mapping logic to ensure consistency across all endpoints:

| Exception Type | HTTP Status | Business Error Code |
|---|---|---|
| `UserFriendlyException` | *Dynamic (Mapped)* | *Dynamic (Mapped)* |
| `KeyNotFoundException` | 404 Not Found | `IA.NOT_FOUND` |
| `ValidationException` | 400 Bad Request | `IA.BAD_REQUEST` |
| `UnauthorizedAccessException` | 401 Unauthorized | `IA.UNAUTHORIZED` |
| `System.Exception` | 500 Internal Error | `IA.GENERAL_ERROR` |

---

## Response Structure

All errors follow the same JSON schema to allow the frontend to display uniform error alerts:

```json
{
"error": {
"code": "InventoryAlert.NOT_FOUND",
"message": "Symbol 'XYZ' is not recognized."
},
"correlationId": "CID-123",
"timestamp": "2026-05-04T12:00:00Z"
}
```

---

## Logic Highlights

| Feature | Detail |
|---|---|
| **Diagnostic Trace** | Every error response includes the `correlationId`, allowing users to provide a reference for support logs. |
| **User Friendly Messages** | `UserFriendlyException` allows services to pass safe, translated messages to the UI while keeping technical details in logs. |
| **Validation Integration** | Automatically captures and formats `FluentValidation` failures into the standard error schema. |
| **Transaction Rollback** | Since the middleware catches exceptions at the top level, incomplete DB transactions are naturally rolled back by the Unit of Work. |
48 changes: 48 additions & 0 deletions InventoryAlert.Wiki/docs/04-execution-flows/news-sync-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# News Synchronization Flow

> Orchestration pipeline for fetching global market news and symbol-specific company news, persisting to DynamoDB with TTL.

## Sequence

```mermaid
sequenceDiagram
participant HF as Hangfire Scheduler
participant Job as NewsSyncJob
participant Finnhub as Finnhub API
participant DDB as DynamoDB (Market/Company News)
participant DB as PostgreSQL

HF->>Job: Trigger (Scheduled / Manual)

Note over Job,Finnhub: Part 1: Global Market News
loop For each category (general, forex, crypto, merger)
Job->>Finnhub: GET /news?category={category}
Finnhub-->>Job: List<MarketNews>
Job->>DDB: BatchSaveAsync (MarketNewsRepo)
end

Note over Job,DB: Part 2: Symbol-Specific Company News
Job->>DB: SELECT TickerSymbols FROM StockListing
loop Parallel.ForEachAsync
Job->>Finnhub: GET /company-news?symbol={s}&from={d}&to={d}
Finnhub-->>Job: List<CompanyNews>
Job->>DDB: BatchSaveAsync (CompanyNewsRepo)
end
```

## Data Persistence Strategy

| Entity | Store | Key Schema (Partition / Sort) | TTL |
|---|---|---|---|
| **Market News** | DynamoDB | `PK: CATEGORY#{CAT}` / `SK: TS#{UNIX}#ID#{ID}` | 7 Days |
| **Company News** | DynamoDB | `PK: SYMBOL#{SYM}` / `SK: TS#{UNIX}#ID#{ID}` | 7 Days |

## Logic Highlights

| Feature | Detail |
|---|---|
| **Multi-Category** | Fetches general, forex, crypto, and merger news in a single job run. |
| **Deduplication** | Uses `DistinctBy(a => a.Id)` to prevent redundant processing of the same article. |
| **Throughput Optimization** | Uses `Parallel.ForEachAsync` with `WorkerSettings.MaxDegreeOfParallelism` for company-specific news. |
| **DynamoDB Batching** | Implements `BatchSaveAsync` to reduce write I/O costs and latency. |
| **Auto-Cleanup** | TTL attribute ensures stale news is automatically removed by DynamoDB. |
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Portfolio Management Flow

> Orchestration for user-specific portfolios, trade history, and real-time performance tracking.

## Overview

The Portfolio flow manages the lifecycle of a user's financial positions. It tracks **Trades** (Buys/Sells), computes **Cost Basis**, and aggregates real-time **Market Value** and **Total Return** using live price data.

---

## Position Lifecycle (Sequence)

```mermaid
sequenceDiagram
participant User as User / Frontend
participant API as PortfolioController
participant Service as PortfolioService
participant DB as PostgreSQL
participant SDS as StockDataService

Note over User,SDS: Part 1: Opening a Position
User->>API: POST /api/v1/portfolio/positions
API->>Service: OpenPositionAsync(request, userId)
Service->>DB: BEGIN Transaction
Service->>DB: INSERT INTO WatchlistItems (Ensure tracked)
Service->>DB: INSERT INTO Trades (Type=Buy, Qty, Price)
Service->>DB: COMMIT Transaction

Note over User,SDS: Part 2: Recording subsequent Trades
User->>API: POST /api/v1/portfolio/{symbol}/trades
API->>Service: RecordTradeAsync(symbol, tradeRequest, userId)
Service->>DB: SELECT SUM(Qty) FROM Trades (Net Holdings)
alt Type = Sell AND NetHoldings < request.Qty
Service-->>API: Throw InsufficientHoldingsException
end
Service->>DB: INSERT INTO Trade
Service->>DB: SaveChangesAsync()

Note over User,SDS: Part 3: Performance Calculation
Service->>SDS: GetQuoteAsync(symbol)
Service->>Service: Compute AvgPrice, MarketValue, TotalReturn
Service-->>API: PortfolioPositionResponse
API-->>User: 201 Created / 200 OK
```

---

## Performance Calculation Logic

The system computes performance metrics on-the-fly to ensure accuracy:

1. **Net Holdings**: `SUM(BuyQuantity) - SUM(SellQuantity)`
2. **Total Buy Cost**: `SUM(BuyQuantity * BuyPrice)`
3. **Average Price (Cost Basis)**: `TotalBuyCost / TotalBuyQuantity`
4. **Market Value**: `NetHoldings * CurrentMarketPrice`
5. **Total Cost**: `NetHoldings * AveragePrice`
6. **Total Return**: `MarketValue - TotalCost`
7. **Total Return %**: `(TotalReturn / TotalCost) * 100`

---

## Removal Constraints

To maintain data integrity, a position can only be removed if:
- It has **no active Alert Rules**.
- The removal operation deletes the `WatchlistItem` and **all associated `Trade` records** in a single transaction.

---

## Logic Highlights

| Feature | Detail |
|---|---|
| **Transaction Safety** | Uses `ExecuteTransactionAsync` to ensure trades and watchlist entries are in sync. |
| **Validation** | Prevents "Short Selling" by validating net holdings before a `Sell` trade is recorded. |
| **Bulk Import** | Supports importing multiple positions via `BulkImportPositionsAsync` for easy migration. |
| **Real-Time Enrichment** | Integrates with `IStockDataService` to provide live P&L (Profit and Loss) metrics. |
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Watchlist Management Flow

> Orchestration for user-specific stock watchlists, including DB-first resolution and Finnhub fallback.

## Overview

The Watchlist flow allows users to track stock symbols without having a financial position. It leverages a **DB-first resolution strategy** to minimize API costs, with a fallback to Finnhub for unknown symbols.

---

## Addition Flow (Sequence)

```mermaid
sequenceDiagram
participant User as User / Frontend
participant API as WatchlistController
participant Service as WatchlistService
participant SDS as StockDataService
participant DB as PostgreSQL
participant Finnhub as Finnhub API

User->>API: POST /api/v1/watchlist/{symbol}
API->>Service: AddToWatchlistAsync(symbol, userId)

Service->>DB: SELECT * FROM StockListings WHERE TickerSymbol = {symbol}

alt Symbol found in DB
DB-->>Service: StockListing
else Symbol NOT in DB (Fallback)
Service->>SDS: GetProfileAsync(symbol)
SDS->>Finnhub: GET /stock/profile2?symbol={symbol}
Finnhub-->>SDS: ProfileData
SDS->>DB: INSERT INTO StockListings (Persist Profile)
DB-->>Service: New StockListing
end

Service->>DB: INSERT INTO WatchlistItems (userId, symbol)
Service->>DB: SaveChangesAsync()

Note over Service,Finnhub: Part 2: Enrich with Live Data
Service->>SDS: GetQuoteAsync(symbol)
SDS->>Finnhub: GET /quote?symbol={symbol}
Finnhub-->>Service: { CurrentPrice, Change, ... }

Service-->>API: PortfolioPositionResponse (Holdings=0)
API-->>User: 201 Created
```

---

## Retrieval Flow

When a user views their watchlist, the system:
1. Fetches all `WatchlistItems` for the `userId`.
2. For each item, builds a `PortfolioPositionResponse`.
3. Sets `HoldingsCount`, `MarketValue`, and `TotalReturn` to **0** (since it is a watchlist-only item).
4. Fetches the latest price via `IStockDataService` (which uses internal Redis caching).

---

## Removal Flow

1. The system verifies the item exists for the user.
2. Removes the `WatchlistItem` record.
3. **Note**: This does *not* delete the `StockListing` record, as other users might be watching it.

---

## Logic Highlights

| Feature | Detail |
|---|---|
| **DB-First Resolution** | Always checks `StockListings` before calling Finnhub to save credits. |
| **Auto-Discovery** | Unknown symbols are automatically discovered, persisted, and shared system-wide. |
| **Unified Response** | Uses `PortfolioPositionResponse` for both Watchlist and Portfolio for frontend consistency. |
| **Traceability** | Every addition/removal is logged with the `UserId` for auditability. |
Loading
Loading