From a4e082e9536541e61fc5ae9a06c465b9b1d7f111 Mon Sep 17 00:00:00 2001 From: nhonvo Date: Wed, 27 May 2026 10:51:36 +0700 Subject: [PATCH 1/4] chore(infra): reallocate project files to src, configure Dependabot, and fix configs --- .agents/GEMINI.md | 162 +- .agents/rules/project-rules.md | 2 +- .agents/scripts/core/bm25_config.json | 8 +- .agents/scripts/core/data/bm25_index.bin | Bin 1326913 -> 1507234 bytes .agents/scripts/core/data/bm25_index.csv | 19076 +++++++++------- .agents/skills/db-migration/SKILL.md | 8 +- .agents/skills/run-tests/SKILL.md | 18 +- .github/dependabot.yml | 25 + .github/workflows/ci.yml | 35 +- .github/workflows/deploy-wiki.yml | 14 +- .github/workflows/sync-github-wiki.yml | 6 +- code-coverage.bat | 2 +- ...ventoryAlert.Api_ApiLoggingMiddleware.html | 283 + ...entoryAlert.Api_HttpContextExtensions.html | 142 + .../InventoryAlert.Domain_AuthTokenPair.html | 161 + ...Infrastructure_AddNotificationDetails.html | 740 + ...ert.Infrastructure_AlertRuleEvaluator.html | 230 + ....Infrastructure_CorrelationIdEnricher.html | 165 + ...t.Infrastructure_LoggingConfiguration.html | 183 + ...rastructure_NotificationAlertNotifier.html | 184 + ...yAlert.Infrastructure_NotificationHub.html | 174 + ...oryAlert.Worker_HealthCheckExtensions.html | 175 + .../InventoryAlert.Worker_NewsSyncJob.html | 266 + doc/archive/EVENT_DRIVEN_PLAN.md | 82 +- doc/archive/EVENT_SETUP_COMMANDS.md | 6 +- doc/archive/MANUAL_TESTING.md | 62 +- doc/archive/PROJECT_OVERVIEW.md | 80 +- doc/archive/SETUP_COMMANDS.md | 22 +- doc/archive/docker/DOCKER_MESSAGING_PLAN.md | 14 +- .../error_handling_and_response_standard.md | 18 +- doc/archive/naming_and_structure_audit.md | 32 +- scripts/export-wiki.mjs | 2 +- .../.dockerignore | 0 .../Directory.Packages.props | 0 .../Configuration/ApiSettings.cs | 0 .../Controllers/AlertRulesController.cs | 0 .../Controllers/AuthController.cs | 0 .../Controllers/EventsController.cs | 0 .../Controllers/MarketController.cs | 0 .../Controllers/NotificationsController.cs | 0 .../Controllers/PortfolioController.cs | 0 .../Controllers/StocksController.cs | 0 .../Controllers/WatchlistController.cs | 0 .../InventoryAlert.Api/Dockerfile | 0 .../Extensions/CompressionExtension.cs | 0 .../Extensions/HealthCheckExtensions.cs | 0 .../Extensions/HttpContextExtensions.cs | 0 .../Extensions/MvcExtension.cs | 0 .../Extensions/SwaggerExtension.cs | 0 .../Filters/SwaggerFilters.cs | 0 .../Filters/ValidateModelFilter.cs | 0 .../InventoryAlert.Api.csproj | 0 .../InventoryAlert.Api.http | 0 .../Middleware/ApiLoggingMiddleware.cs | 0 .../Middleware/CorrelationIdMiddleware.cs | 0 .../Middleware/GlobalExceptionMiddleware.cs | 0 .../InventoryAlert.Api/Models/Error.cs | 0 .../InventoryAlert.Api/Program.cs | 0 .../Properties/launchSettings.json | 0 .../HttpClientServiceExtensions.cs | 0 .../InfrastructureServiceExtensions.cs | 0 .../Services/AlertRuleService.cs | 0 .../Services/AuthService.cs | 0 .../Services/EventService.cs | 0 .../Services/NotificationService.cs | 0 .../Services/PortfolioService.cs | 0 .../Services/StockDataService.cs | 0 .../Services/WatchlistService.cs | 0 .../Utilities/JsonConverters.cs | 0 .../Validations/ValidatorInterceptor.cs | 0 .../appsettings.Example.json | 0 src/InventoryAlert.Api/appsettings.json | 31 + .../InventoryAlert.Api/wwwroot/.gitkeep | 0 .../Common/Constants/Constants.cs | 0 .../Common/Constants/NotificationConstants.cs | 0 .../Common/Exceptions/NotFoundException.cs | 0 .../Exceptions/UserFriendlyException.cs | 0 .../Common/Exceptions/ValidationException.cs | 0 .../Configuration/AppSettings.cs | 0 .../Configuration/JsonOptions.cs | 0 .../Configuration/RedisSettings.cs | 0 .../Configuration/SharedAwsSettings.cs | 0 .../Configuration/SharedDatabaseSettings.cs | 0 .../Configuration/SharedFinnhubSettings.cs | 0 .../Configuration/SharedSeqSettings.cs | 0 .../Constants/AlertConstants.cs | 0 .../DTOs/AlertRuleDTOs.cs | 0 .../InventoryAlert.Domain/DTOs/AuthDTOs.cs | 0 .../DTOs/CalendarDTOs.cs | 0 .../InventoryAlert.Domain/DTOs/EventDTOs.cs | 0 .../InventoryAlert.Domain/DTOs/MarketDTOs.cs | 0 .../DTOs/NotificationDTOs.cs | 0 .../InventoryAlert.Domain/DTOs/PagedResult.cs | 0 .../DTOs/PaginationParams.cs | 0 .../DTOs/PortfolioDTOs.cs | 0 .../InventoryAlert.Domain/DTOs/StockDTOs.cs | 0 .../Dynamodb/CompanyNewsDynamoEntry.cs | 0 .../Dynamodb/MarketNewsDynamoEntry.cs | 0 .../Entities/Postgres/AlertRule.cs | 0 .../Entities/Postgres/EarningsSurprise.cs | 0 .../Entities/Postgres/InsiderTransaction.cs | 0 .../Entities/Postgres/Notification.cs | 0 .../Entities/Postgres/PriceHistory.cs | 0 .../Entities/Postgres/RecommendationTrend.cs | 0 .../Entities/Postgres/StockListing.cs | 0 .../Entities/Postgres/StockMetric.cs | 0 .../Entities/Postgres/Trade.cs | 0 .../Entities/Postgres/User.cs | 0 .../Entities/Postgres/WatchlistItem.cs | 0 .../Events/EventEnvelope.cs | 0 .../Events/EventTypes.cs | 0 .../Payloads/CompanyNewsAlertPayload.cs | 0 .../Payloads/LowHoldingsAlertPayload.cs | 0 .../Events/Payloads/MarketNewsPayload.cs | 0 .../Payloads/MarketPriceAlertPayload.cs | 0 .../Events/Payloads/SyncCompanyNewsPayload.cs | 0 .../External/Finnhub/FinnhubModels.cs | 0 .../Interfaces/IAlertNotifier.cs | 0 .../Interfaces/IAlertRuleEvaluator.cs | 0 .../Interfaces/IAlertRuleRepository.cs | 0 .../Interfaces/IAlertRuleService.cs | 0 .../Interfaces/IAuthService.cs | 0 .../ICompanyNewsDynamoRepository.cs | 0 .../Interfaces/ICorrelationProvider.cs | 0 .../Interfaces/IDynamoDbGenericRepository.cs | 0 .../Interfaces/IEarningsSurpriseRepository.cs | 0 .../Interfaces/IEventPublisher.cs | 0 .../Interfaces/IEventService.cs | 0 .../Interfaces/IFinnhubClient.cs | 0 .../Interfaces/IGenericRepository.cs | 0 .../IInsiderTransactionRepository.cs | 0 .../Interfaces/IMarketNewsDynamoRepository.cs | 0 .../Interfaces/INotificationHub.cs | 0 .../Interfaces/INotificationRepository.cs | 0 .../Interfaces/INotificationService.cs | 0 .../Interfaces/IPortfolioService.cs | 0 .../Interfaces/IPriceHistoryRepository.cs | 0 .../Interfaces/IQueueService.cs | 0 .../IRecommendationTrendRepository.cs | 0 .../Interfaces/IRedisHelper.cs | 0 .../Interfaces/IStockDataService.cs | 0 .../Interfaces/IStockListingRepository.cs | 0 .../Interfaces/IStockMetricRepository.cs | 0 .../Interfaces/ITradeRepository.cs | 0 .../Interfaces/IUnitOfWork.cs | 0 .../Interfaces/IUserRepository.cs | 0 .../Interfaces/IWatchlistItemRepository.cs | 0 .../Interfaces/IWatchlistService.cs | 0 .../InventoryAlert.Domain.csproj | 0 .../Validators/AlertRuleRequestValidator.cs | 0 .../Validators/AuthValidators.cs | 0 .../CreatePositionRequestValidator.cs | 0 .../Validators/TradeRequestValidator.cs | 0 .../Caching/RedisHelper.cs | 0 .../DependencyInjection.cs | 0 .../External/Finnhub/FinnhubClient.cs | 0 .../Hubs/NotificationHub.cs | 0 .../InventoryAlert.Infrastructure.csproj | 0 .../Messaging/SnsEventPublisher.cs | 0 .../Messaging/SqsQueueService.cs | 0 ...0414042036_RefactorToFinanceV2.Designer.cs | 0 .../20260414042036_RefactorToFinanceV2.cs | 0 ...6071939_AddNotificationDetails.Designer.cs | 0 .../20260426071939_AddNotificationDetails.cs | 0 .../Migrations/AppDbContextModelSnapshot.cs | 0 .../CompanyNewsDynamoRepository.cs | 0 .../Repositories/DynamoDBContextBuilder.cs | 0 .../Repositories/DynamoDbGenericRepository.cs | 0 .../MarketNewsDynamoRepository.cs | 0 .../Persistence/Postgres/AppDbContext.cs | 0 .../Postgres/AppDbContextFactory.cs | 0 .../Configurations/AlertRuleConfiguration.cs | 0 .../EarningsSurpriseConfiguration.cs | 0 .../InsiderTransactionConfiguration.cs | 0 .../NotificationConfiguration.cs | 0 .../PriceHistoryConfiguration.cs | 0 .../RecommendationTrendConfiguration.cs | 0 .../StockListingConfiguration.cs | 0 .../StockMetricConfiguration.cs | 0 .../Configurations/TradeConfiguration.cs | 0 .../Configurations/UserConfiguration.cs | 0 .../WatchlistItemConfiguration.cs | 0 .../Persistence/Postgres/DatabaseSeeder.cs | 0 .../Repositories/AlertRuleRepository.cs | 0 .../EarningsSurpriseRepository.cs | 0 .../Repositories/GenericRepository.cs | 0 .../InsiderTransactionRepository.cs | 0 .../Repositories/NotificationRepository.cs | 0 .../Repositories/PriceHistoryRepository.cs | 0 .../RecommendationTrendRepository.cs | 0 .../Repositories/StockListingRepository.cs | 0 .../Repositories/StockMetricRepository.cs | 0 .../Postgres/Repositories/TradeRepository.cs | 0 .../Postgres/Repositories/UnitOfWork.cs | 0 .../Postgres/Repositories/UserRepository.cs | 0 .../Repositories/WatchlistItemRepository.cs | 0 .../Utilities/AlertRuleEvaluator.cs | 0 .../Utilities/CorrelationIdEnricher.cs | 0 .../Utilities/CorrelationProvider.cs | 0 .../Utilities/LoggingConfiguration.cs | 0 .../Utilities/NotificationAlertNotifier.cs | 0 .../Configuration/WorkerSettings.cs | 0 .../DevDashboardAuthorizationFilter.cs | 0 .../InventoryAlert.Worker/Dockerfile | 0 .../Extensions/HealthCheckExtensions.cs | 0 .../Filters/HangfireJobLoggingFilter.cs | 0 .../Hosting/BackgroundTaskProcessor.cs | 0 .../Hosting/BackgroundTaskQueue.cs | 0 .../Hosting/JobSchedulerService.cs | 0 .../Hosting/SqsListenerService.cs | 0 .../Handlers/DefaultHandler.cs | 0 .../Handlers/LowHoldingsHandler.cs | 0 .../Handlers/MarketPriceAlertHandler.cs | 0 .../Routing/IntegrationMessageRouter.cs | 0 .../Interfaces/IBackgroundTaskQueue.cs | 0 .../Interfaces/IHandlerInterfaces.cs | 0 .../Interfaces/IIntegrationMessageRouter.cs | 0 .../Interfaces/IProcessQueueJob.cs | 0 .../Interfaces/ISqsHelper.cs | 0 .../InventoryAlert.Worker.csproj | 0 .../InventoryAlert.Worker/Models/JobResult.cs | 0 .../InventoryAlert.Worker/Program.cs | 0 .../Properties/launchSettings.json | 0 .../ScheduledJobs/CleanupPriceHistoryJob.cs | 0 .../ScheduledJobs/NewsSyncJob.cs | 0 .../ScheduledJobs/ProcessQueueJob.cs | 0 .../ScheduledJobs/SyncEarningsJob.cs | 0 .../ScheduledJobs/SyncInsidersJob.cs | 0 .../ScheduledJobs/SyncMetricsJob.cs | 0 .../ScheduledJobs/SyncPricesJob.cs | 0 .../ScheduledJobs/SyncRecommendationsJob.cs | 0 .../Utilities/SqsHelper.cs | 0 .../appsettings.Example.json | 0 src/InventoryAlert.Worker/appsettings.json | 37 + .../InventoryManagementSystem.sln | 12 +- .../SolutionFolder/moto-init/init-all.sh | 0 .../docker-compose.yml | 4 +- .../ArchitectureTests.cs | 0 .../InventoryAlert.ArchitectureTests.csproj | 6 +- .../Abstractions/BaseE2ETest.cs | 0 .../AlertRulesE2ETests.cs | 0 .../InventoryAlert.E2ETests/AuthE2ETests.cs | 0 .../InventoryAlert.E2ETests/EventsE2ETests.cs | 0 .../InventoryAlert.E2ETests.csproj | 2 +- .../InventoryAlert.E2ETests/MarketE2ETests.cs | 0 .../NotificationE2ETests.cs | 0 .../PortfolioE2ETests.cs | 0 .../SignalRNotificationE2ETests.cs | 0 .../SqsRetryE2ETests.cs | 0 .../InventoryAlert.E2ETests/StocksE2ETests.cs | 0 .../WatchlistE2ETests.cs | 0 .../InventoryAlert.E2ETests/test-e2e.ps1 | 0 .../Abstractions/BaseClient.cs | 0 .../Abstractions/BaseIntegrationTest.cs | 11 +- .../Abstractions/HandlerTestBase.cs | 0 .../Abstractions/Tier2TestBase.cs | 0 .../Clients/AlertRuleClient.cs | 0 .../Clients/AuthClient.cs | 0 .../Clients/MarketClient.cs | 0 .../Clients/MockFinnhubClient.cs | 0 .../Clients/StockClient.cs | 0 .../Clients/WatchlistClient.cs | 0 .../Clients/WiremockAdminClient.cs | 0 .../Config/ApiSettings.cs | 0 .../Config/AppSettings.cs | 0 .../Config/TestUser.cs | 0 .../Config/WiremockSettings.cs | 0 .../Fixtures/InjectionFixture.cs | 0 .../Helpers/WaitHelper.cs | 0 .../INTEGRATION_TEST_PLAN.md | 0 .../Infrastructure/ActionTestConfig.cs | 0 .../IntegrationTestCollection.cs | 0 .../Infrastructure/SeqLogReader.cs | 0 .../Infrastructure/SetupDI.cs | 0 .../Infrastructure/TestFixture.cs | 0 .../Infrastructure/TestLoggerProvider.cs | 0 .../Infrastructure/WaitHelper.cs | 0 .../InventoryAlert.IntegrationTests.csproj | 12 +- .../Request/WiremockCountGetQuoteRequest.cs | 0 .../Models/Response/WiremockCountResponse.cs | 0 .../Assertions/AlertRuleAssertion.cs | 0 .../Assertions/WatchlistItemAssertion.cs | 0 .../Tests/Api/AlertRuleApiTest.cs | 0 .../Tests/Api/AuthApiTest.cs | 0 .../Tests/Api/MarketApiTest.cs | 0 .../Tests/Api/StockApiTest.cs | 0 .../Tests/Api/WatchlistApiTest.cs | 0 .../Tests/Handlers/LowHoldingsHandlerTests.cs | 0 .../Handlers/MarketPriceAlertHandlerTests.cs | 0 .../Tests/Jobs/WholeFlowTests.cs | 0 .../Tests/Services/PortfolioServiceTests.cs | 0 .../Tests/Smoke/ALertRuleSmokeTest.cs | 0 .../Tests/Smoke/AuthSmokeTest.cs | 0 .../Tests/Smoke/WatchlistSmokeTest.cs | 0 .../Tests/SmokeTests.cs | 0 .../Wiremock/mappings/check-wiremock.json | 0 .../Wiremock/mappings/company_news.json | 0 .../Wiremock/mappings/get-profile.json | 0 .../Wiremock/mappings/get-quote.json | 0 .../Wiremock/mappings/market_news.json | 0 .../Wiremock/mappings/ping.json | 0 .../appsettings.test.json | 0 .../InventoryAlert.Sample.csproj | 2 +- .../test}/InventoryAlert.Sample/Program.cs | 0 .../Services/AlertRuleServiceTests.cs | 0 .../Services/ConfigurationTests.cs | 0 .../Services/NotificationServiceTests.cs | 0 .../Services/PortfolioServiceTests.cs | 0 .../Services/StockDataServiceTests.cs | 0 .../Services/WatchlistServiceTests.cs | 0 .../Validations/AuthValidatorsTests.cs | 0 .../Fixtures/InjectionFixture.cs | 0 .../Helpers/PaginatedListFixtures.cs | 0 .../External/FinnhubClientTests.cs | 0 .../Messaging/SnsEventPublisherTests.cs | 0 .../Repositories/GenericRepositoryTests.cs | 0 .../Repositories/UnitOfWorkTests.cs | 0 .../Utilities/AlertRuleEvaluatorTests.cs | 0 .../InventoryAlert.UnitTests.csproj | 8 +- .../Controllers/AlertRulesControllerTests.cs | 0 .../Web/Controllers/AuthControllerTests.cs | 0 .../Web/Controllers/EventsControllerTests.cs | 0 .../NotificationsControllerTests.cs | 0 .../Controllers/PortfolioControllerTests.cs | 0 .../Web/Controllers/StocksControllerTests.cs | 0 .../Controllers/WatchlistControllerTests.cs | 0 .../Middleware/ApiLoggingMiddlewareTests.cs | 0 .../CorrelationIdMiddlewareTests.cs | 0 .../GlobalExceptionMiddlewareTests.cs | 0 .../Handlers/LowHoldingsHandlerTests.cs | 0 .../Handlers/MarketPriceAlertHandlerTests.cs | 0 .../Worker/MessageProcessorTests.cs | 0 .../Worker/ScheduledJobs/NewsSyncJobTests.cs | 0 .../ScheduledJobs/ProcessQueueJobTests.cs | 0 .../ScheduledJobs/SyncPricesJobTests.cs | 0 .../InventoryAlert.UnitTests/appsettings.json | 0 .../ui/InventoryAlert.UI}/.dockerignore | 0 .../ui/InventoryAlert.UI}/.gitignore | 0 .../ui/InventoryAlert.UI}/Dockerfile | 0 .../ui/InventoryAlert.UI}/README.md | 0 .../ui/InventoryAlert.UI}/eslint.config.mjs | 0 .../ui/InventoryAlert.UI}/next.config.ts | 0 .../ui/InventoryAlert.UI}/package-lock.json | 0 .../ui/InventoryAlert.UI}/package.json | 0 .../ui/InventoryAlert.UI}/postcss.config.mjs | 0 .../ui/InventoryAlert.UI}/public/file.svg | 0 .../ui/InventoryAlert.UI}/public/globe.svg | 0 .../ui/InventoryAlert.UI}/public/next.svg | 0 .../ui/InventoryAlert.UI}/public/vercel.svg | 0 .../ui/InventoryAlert.UI}/public/window.svg | 0 .../src/app/(auth)/login/page.tsx | 0 .../src/app/(auth)/register/page.tsx | 0 .../src/app/admin/health/page.tsx | 0 .../src/app/alerts/page.tsx | 0 .../ui/InventoryAlert.UI}/src/app/favicon.ico | Bin .../ui/InventoryAlert.UI}/src/app/globals.css | 0 .../ui/InventoryAlert.UI}/src/app/layout.tsx | 0 .../src/app/market/page.tsx | 0 .../src/app/notifications/page.tsx | 0 .../ui/InventoryAlert.UI}/src/app/page.tsx | 0 .../src/app/portfolio/page.tsx | 0 .../src/app/stocks/[symbol]/page.tsx | 0 .../src/app/stocks/page.tsx | 0 .../src/app/watchlist/page.tsx | 0 .../src/components/AddSymbolModal.tsx | 0 .../src/components/ConfirmDialog.tsx | 0 .../src/components/GlobalSearch.tsx | 0 .../components/MarketStatusBanner.test.tsx | 0 .../src/components/MarketStatusBanner.tsx | 0 .../src/components/Navbar.tsx | 0 .../src/components/NavbarWrapper.tsx | 0 .../src/components/NotificationBell.test.tsx | 0 .../src/components/NotificationBell.tsx | 0 .../src/components/NotificationProvider.tsx | 0 .../src/components/PriceAlertModal.tsx | 0 .../src/components/ThemeProvider.tsx | 0 .../src/components/Toast.tsx | 0 .../src/components/TradeModal.tsx | 0 .../src/components/UserNav.tsx | 0 .../src/components/ui/Pagination.tsx | 0 .../src/hooks/useSignalR.ts | 0 .../src/lib/api.refresh.test.ts | 0 .../ui/InventoryAlert.UI}/src/lib/api.test.ts | 0 .../ui/InventoryAlert.UI}/src/lib/api.ts | 0 .../InventoryAlert.UI}/src/lib/error-utils.ts | 0 .../ui/InventoryAlert.UI}/tsconfig.json | 0 .../ui/InventoryAlert.UI}/vitest.config.ts | 0 .../ui/InventoryAlert.UI}/vitest.setup.ts | 0 .../ui/InventoryAlert.Wiki}/.gitignore | 0 .../ui/InventoryAlert.Wiki}/README.md | 0 .../docs/00-overview/introduction.md | 0 .../architecture-overview.md | 0 .../domain-and-structure.md | 50 +- .../microservice-components.md | 0 .../docs/03-data-model/caching-strategy.md | 0 .../docs/03-data-model/data-model.md | 0 .../docs/04-execution-flows/alert-dispatch.md | 0 .../04-execution-flows/alert-rule-creation.md | 0 .../docs/04-execution-flows/business-logic.md | 0 .../04-execution-flows/cqrs-event-flow.md | 0 .../04-execution-flows/earnings-sync-flow.md | 0 .../04-execution-flows/error-handling-flow.md | 0 .../docs/04-execution-flows/news-sync-flow.md | 0 .../portfolio-management-flow.md | 0 .../04-execution-flows/price-sync-flow.md | 0 .../04-execution-flows/user-authentication.md | 0 .../watchlist-management-flow.md | 0 .../docs/05-api-services/event-handling.md | 0 .../05-api-services/external-integrations.md | 0 .../docs/05-api-services/internal-api.md | 0 .../06-background-jobs/hangfire-monitoring.md | 0 .../docs/06-background-jobs/workers.md | 0 .../07-dev-maintenance/ai-agent-workflows.md | 0 .../07-dev-maintenance/dotnet-commands.md | 0 .../07-dev-maintenance/getting-started.md | 28 +- .../integration-testing-tiers.md | 0 .../07-dev-maintenance/operational-runbook.md | 16 +- .../docs/07-dev-maintenance/test-strategy.md | 0 .../testing-and-standards.md | 0 .../docs/08-frontend-ui/feature-breakdown.md | 0 .../docs/08-frontend-ui/ui-architecture.md | 0 .../ui/InventoryAlert.Wiki}/docs/index.md | 0 .../InventoryAlert.Wiki}/docusaurus.config.ts | 0 .../ui/InventoryAlert.Wiki}/package-lock.json | 0 .../ui/InventoryAlert.Wiki}/package.json | 0 .../ui/InventoryAlert.Wiki}/sidebars.ts | 0 .../src/components/HomepageFeatures/index.tsx | 0 .../HomepageFeatures/styles.module.css | 0 .../InventoryAlert.Wiki}/src/css/custom.css | 0 .../ui/InventoryAlert.Wiki}/static/.nojekyll | 0 .../static/img/docusaurus-social-card.jpg | Bin .../static/img/docusaurus.png | Bin .../static/img/favicon.ico | Bin .../InventoryAlert.Wiki}/static/img/logo.svg | 0 .../static/img/undraw_docusaurus_mountain.svg | 0 .../static/img/undraw_docusaurus_react.svg | 0 .../static/img/undraw_docusaurus_tree.svg | 0 .../ui/InventoryAlert.Wiki}/tsconfig.json | 0 438 files changed, 14112 insertions(+), 8484 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 coverage/html/InventoryAlert.Api_ApiLoggingMiddleware.html create mode 100644 coverage/html/InventoryAlert.Api_HttpContextExtensions.html create mode 100644 coverage/html/InventoryAlert.Domain_AuthTokenPair.html create mode 100644 coverage/html/InventoryAlert.Infrastructure_AddNotificationDetails.html create mode 100644 coverage/html/InventoryAlert.Infrastructure_AlertRuleEvaluator.html create mode 100644 coverage/html/InventoryAlert.Infrastructure_CorrelationIdEnricher.html create mode 100644 coverage/html/InventoryAlert.Infrastructure_LoggingConfiguration.html create mode 100644 coverage/html/InventoryAlert.Infrastructure_NotificationAlertNotifier.html create mode 100644 coverage/html/InventoryAlert.Infrastructure_NotificationHub.html create mode 100644 coverage/html/InventoryAlert.Worker_HealthCheckExtensions.html create mode 100644 coverage/html/InventoryAlert.Worker_NewsSyncJob.html rename {InventoryManagementSystem => src}/.dockerignore (100%) rename {InventoryManagementSystem => src}/Directory.Packages.props (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Configuration/ApiSettings.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Controllers/AlertRulesController.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Controllers/AuthController.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Controllers/EventsController.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Controllers/MarketController.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Controllers/NotificationsController.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Controllers/PortfolioController.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Controllers/StocksController.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Controllers/WatchlistController.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Dockerfile (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Extensions/CompressionExtension.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Extensions/HealthCheckExtensions.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Extensions/HttpContextExtensions.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Extensions/MvcExtension.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Extensions/SwaggerExtension.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Filters/SwaggerFilters.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Filters/ValidateModelFilter.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/InventoryAlert.Api.csproj (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/InventoryAlert.Api.http (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Middleware/ApiLoggingMiddleware.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Middleware/CorrelationIdMiddleware.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Models/Error.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Program.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Properties/launchSettings.json (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/ServiceExtensions/HttpClientServiceExtensions.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/ServiceExtensions/InfrastructureServiceExtensions.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Services/AlertRuleService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Services/AuthService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Services/EventService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Services/NotificationService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Services/PortfolioService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Services/StockDataService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Services/WatchlistService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Utilities/JsonConverters.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/Validations/ValidatorInterceptor.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Api/appsettings.Example.json (100%) create mode 100644 src/InventoryAlert.Api/appsettings.json rename {InventoryManagementSystem => src}/InventoryAlert.Api/wwwroot/.gitkeep (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Common/Constants/Constants.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Common/Constants/NotificationConstants.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Common/Exceptions/NotFoundException.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Common/Exceptions/UserFriendlyException.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Common/Exceptions/ValidationException.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Configuration/AppSettings.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Configuration/JsonOptions.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Configuration/RedisSettings.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Configuration/SharedAwsSettings.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Configuration/SharedDatabaseSettings.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Configuration/SharedFinnhubSettings.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Configuration/SharedSeqSettings.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Constants/AlertConstants.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/AlertRuleDTOs.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/AuthDTOs.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/CalendarDTOs.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/EventDTOs.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/MarketDTOs.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/NotificationDTOs.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/PagedResult.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/PaginationParams.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/PortfolioDTOs.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/DTOs/StockDTOs.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Dynamodb/CompanyNewsDynamoEntry.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Dynamodb/MarketNewsDynamoEntry.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/EarningsSurprise.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/InsiderTransaction.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/Notification.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/PriceHistory.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/RecommendationTrend.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/StockListing.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/StockMetric.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/Trade.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/User.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Entities/Postgres/WatchlistItem.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Events/EventEnvelope.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Events/EventTypes.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Events/Payloads/CompanyNewsAlertPayload.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Events/Payloads/LowHoldingsAlertPayload.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Events/Payloads/MarketNewsPayload.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Events/Payloads/MarketPriceAlertPayload.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Events/Payloads/SyncCompanyNewsPayload.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/External/Finnhub/FinnhubModels.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IAlertNotifier.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IAlertRuleEvaluator.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IAlertRuleRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IAlertRuleService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IAuthService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/ICompanyNewsDynamoRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/ICorrelationProvider.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IDynamoDbGenericRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IEarningsSurpriseRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IEventPublisher.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IEventService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IFinnhubClient.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IGenericRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IInsiderTransactionRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IMarketNewsDynamoRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/INotificationHub.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/INotificationRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/INotificationService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IPortfolioService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IPriceHistoryRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IQueueService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IRecommendationTrendRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IRedisHelper.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IStockDataService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IStockListingRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IStockMetricRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/ITradeRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IUnitOfWork.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IUserRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IWatchlistItemRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Interfaces/IWatchlistService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/InventoryAlert.Domain.csproj (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Validators/AlertRuleRequestValidator.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Validators/AuthValidators.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Validators/CreatePositionRequestValidator.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Domain/Validators/TradeRequestValidator.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Caching/RedisHelper.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/DependencyInjection.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/External/Finnhub/FinnhubClient.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Hubs/NotificationHub.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Messaging/SqsQueueService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.Designer.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.Designer.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Migrations/AppDbContextModelSnapshot.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/CompanyNewsDynamoRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDBContextBuilder.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDbGenericRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/MarketNewsDynamoRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContext.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContextFactory.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/AlertRuleConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/EarningsSurpriseConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/InsiderTransactionConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/NotificationConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/PriceHistoryConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/RecommendationTrendConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockListingConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockMetricConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/TradeConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/UserConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/WatchlistItemConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/DatabaseSeeder.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/AlertRuleRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/EarningsSurpriseRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/GenericRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/InsiderTransactionRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/NotificationRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/PriceHistoryRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/RecommendationTrendRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockListingRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockMetricRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/TradeRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UnitOfWork.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UserRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/WatchlistItemRepository.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Utilities/AlertRuleEvaluator.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Utilities/CorrelationIdEnricher.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Utilities/LoggingConfiguration.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Infrastructure/Utilities/NotificationAlertNotifier.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Configuration/WorkerSettings.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/DevDashboardAuthorizationFilter.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Dockerfile (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Extensions/HealthCheckExtensions.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Hosting/BackgroundTaskProcessor.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Hosting/JobSchedulerService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Hosting/SqsListenerService.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/IntegrationEvents/Handlers/DefaultHandler.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/IntegrationEvents/Handlers/LowHoldingsHandler.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/IntegrationEvents/Handlers/MarketPriceAlertHandler.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Interfaces/IBackgroundTaskQueue.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Interfaces/IHandlerInterfaces.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Interfaces/IIntegrationMessageRouter.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Interfaces/IProcessQueueJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Interfaces/ISqsHelper.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/InventoryAlert.Worker.csproj (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Models/JobResult.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Program.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Properties/launchSettings.json (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/ScheduledJobs/CleanupPriceHistoryJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/ScheduledJobs/NewsSyncJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/ScheduledJobs/SyncEarningsJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/ScheduledJobs/SyncInsidersJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/ScheduledJobs/SyncMetricsJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/ScheduledJobs/SyncRecommendationsJob.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/Utilities/SqsHelper.cs (100%) rename {InventoryManagementSystem => src}/InventoryAlert.Worker/appsettings.Example.json (100%) create mode 100644 src/InventoryAlert.Worker/appsettings.json rename {InventoryManagementSystem => src}/InventoryManagementSystem.sln (94%) rename {InventoryManagementSystem => src}/SolutionFolder/moto-init/init-all.sh (100%) rename {InventoryManagementSystem => src}/docker-compose.yml (98%) rename {InventoryManagementSystem => src/test}/InventoryAlert.ArchitectureTests/ArchitectureTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj (69%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/Abstractions/BaseE2ETest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/AlertRulesE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/AuthE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/EventsE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj (90%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/MarketE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/NotificationE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/PortfolioE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/SignalRNotificationE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/SqsRetryE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/StocksE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/WatchlistE2ETests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.E2ETests/test-e2e.ps1 (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Abstractions/BaseClient.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Abstractions/BaseIntegrationTest.cs (79%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Abstractions/HandlerTestBase.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Abstractions/Tier2TestBase.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Clients/AlertRuleClient.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Clients/AuthClient.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Clients/MarketClient.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Clients/MockFinnhubClient.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Clients/StockClient.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Clients/WatchlistClient.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Clients/WiremockAdminClient.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Config/ApiSettings.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Config/AppSettings.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Config/TestUser.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Config/WiremockSettings.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Fixtures/InjectionFixture.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Helpers/WaitHelper.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/INTEGRATION_TEST_PLAN.md (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Infrastructure/ActionTestConfig.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Infrastructure/IntegrationTestCollection.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Infrastructure/SeqLogReader.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Infrastructure/SetupDI.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Infrastructure/TestFixture.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Infrastructure/TestLoggerProvider.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Infrastructure/WaitHelper.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj (69%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Models/Request/WiremockCountGetQuoteRequest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Models/Response/WiremockCountResponse.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/TestUtils/Assertions/AlertRuleAssertion.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/TestUtils/Assertions/WatchlistItemAssertion.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Api/AlertRuleApiTest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Api/AuthApiTest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Api/MarketApiTest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Api/StockApiTest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Api/WatchlistApiTest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Handlers/LowHoldingsHandlerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Handlers/MarketPriceAlertHandlerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Jobs/WholeFlowTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Services/PortfolioServiceTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Smoke/ALertRuleSmokeTest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Smoke/AuthSmokeTest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/Smoke/WatchlistSmokeTest.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Tests/SmokeTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Wiremock/mappings/check-wiremock.json (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Wiremock/mappings/company_news.json (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Wiremock/mappings/get-profile.json (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Wiremock/mappings/get-quote.json (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Wiremock/mappings/market_news.json (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/Wiremock/mappings/ping.json (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.IntegrationTests/appsettings.test.json (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.Sample/InventoryAlert.Sample.csproj (83%) rename {InventoryManagementSystem => src/test}/InventoryAlert.Sample/Program.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Application/Services/AlertRuleServiceTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Application/Services/ConfigurationTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Application/Services/NotificationServiceTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Application/Services/PortfolioServiceTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Application/Services/StockDataServiceTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Application/Services/WatchlistServiceTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Application/Validations/AuthValidatorsTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Fixtures/InjectionFixture.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Helpers/PaginatedListFixtures.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Infrastructure/External/FinnhubClientTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Infrastructure/Messaging/SnsEventPublisherTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/GenericRepositoryTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/UnitOfWorkTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Infrastructure/Utilities/AlertRuleEvaluatorTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj (72%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Controllers/AlertRulesControllerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Controllers/AuthControllerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Controllers/EventsControllerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Controllers/NotificationsControllerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Controllers/PortfolioControllerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Controllers/StocksControllerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Controllers/WatchlistControllerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Middleware/ApiLoggingMiddlewareTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Middleware/CorrelationIdMiddlewareTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Web/Middleware/GlobalExceptionMiddlewareTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Worker/Handlers/LowHoldingsHandlerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Worker/Handlers/MarketPriceAlertHandlerTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Worker/MessageProcessorTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Worker/ScheduledJobs/NewsSyncJobTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Worker/ScheduledJobs/ProcessQueueJobTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/Worker/ScheduledJobs/SyncPricesJobTests.cs (100%) rename {InventoryManagementSystem => src/test}/InventoryAlert.UnitTests/appsettings.json (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/.dockerignore (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/.gitignore (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/Dockerfile (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/README.md (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/eslint.config.mjs (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/next.config.ts (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/package-lock.json (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/package.json (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/postcss.config.mjs (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/public/file.svg (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/public/globe.svg (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/public/next.svg (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/public/vercel.svg (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/public/window.svg (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/(auth)/login/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/(auth)/register/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/admin/health/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/alerts/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/favicon.ico (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/globals.css (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/layout.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/market/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/notifications/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/portfolio/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/stocks/[symbol]/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/stocks/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/app/watchlist/page.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/AddSymbolModal.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/ConfirmDialog.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/GlobalSearch.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/MarketStatusBanner.test.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/MarketStatusBanner.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/Navbar.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/NavbarWrapper.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/NotificationBell.test.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/NotificationBell.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/NotificationProvider.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/PriceAlertModal.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/ThemeProvider.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/Toast.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/TradeModal.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/UserNav.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/components/ui/Pagination.tsx (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/hooks/useSignalR.ts (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/lib/api.refresh.test.ts (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/lib/api.test.ts (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/lib/api.ts (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/src/lib/error-utils.ts (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/tsconfig.json (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/vitest.config.ts (100%) rename {InventoryAlert.UI => src/ui/InventoryAlert.UI}/vitest.setup.ts (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/.gitignore (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/README.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/00-overview/introduction.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/02-architecture-techstack/architecture-overview.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/02-architecture-techstack/domain-and-structure.md (63%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/02-architecture-techstack/microservice-components.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/03-data-model/caching-strategy.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/03-data-model/data-model.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/alert-dispatch.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/alert-rule-creation.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/business-logic.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/cqrs-event-flow.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/earnings-sync-flow.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/error-handling-flow.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/news-sync-flow.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/portfolio-management-flow.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/price-sync-flow.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/user-authentication.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/04-execution-flows/watchlist-management-flow.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/05-api-services/event-handling.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/05-api-services/external-integrations.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/05-api-services/internal-api.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/06-background-jobs/hangfire-monitoring.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/06-background-jobs/workers.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/07-dev-maintenance/ai-agent-workflows.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/07-dev-maintenance/dotnet-commands.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/07-dev-maintenance/getting-started.md (71%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/07-dev-maintenance/integration-testing-tiers.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/07-dev-maintenance/operational-runbook.md (80%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/07-dev-maintenance/test-strategy.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/07-dev-maintenance/testing-and-standards.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/08-frontend-ui/feature-breakdown.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/08-frontend-ui/ui-architecture.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docs/index.md (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/docusaurus.config.ts (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/package-lock.json (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/package.json (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/sidebars.ts (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/src/components/HomepageFeatures/index.tsx (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/src/components/HomepageFeatures/styles.module.css (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/src/css/custom.css (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/static/.nojekyll (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/static/img/docusaurus-social-card.jpg (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/static/img/docusaurus.png (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/static/img/favicon.ico (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/static/img/logo.svg (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/static/img/undraw_docusaurus_mountain.svg (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/static/img/undraw_docusaurus_react.svg (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/static/img/undraw_docusaurus_tree.svg (100%) rename {InventoryAlert.Wiki => src/ui/InventoryAlert.Wiki}/tsconfig.json (100%) diff --git a/.agents/GEMINI.md b/.agents/GEMINI.md index e77e166..63e2520 100644 --- a/.agents/GEMINI.md +++ b/.agents/GEMINI.md @@ -91,17 +91,17 @@ Real-time inventory management system with portfolio + watchlist + alerting. ## Tech Stack -| Layer | Technology | -| :--- | :--- | -| Runtime | .NET 10 (C# 12) | -| Web Framework | ASP.NET Core Minimal Hosting | -| ORM | EF Core 10 + Npgsql (PostgreSQL) | -| External API | Finnhub REST (RestSharp client) | -| Background Jobs | Hangfire (Worker) + native SQS poller | -| Documentation | Swashbuckle / Swagger | -| Tests | xUnit + Moq + FluentAssertions | -| Containerization | Docker + Docker Compose | -| Search/Memory | BM25+ (`.agents/scripts/core/`) | +| Layer | Technology | +| :--------------- | :------------------------------------ | +| Runtime | .NET 10 (C# 12) | +| Web Framework | ASP.NET Core Minimal Hosting | +| ORM | EF Core 10 + Npgsql (PostgreSQL) | +| External API | Finnhub REST (RestSharp client) | +| Background Jobs | Hangfire (Worker) + native SQS poller | +| Documentation | Swashbuckle / Swagger | +| Tests | xUnit + Moq + FluentAssertions | +| Containerization | Docker + Docker Compose | +| Search/Memory | BM25+ (`.agents/scripts/core/`) | --- @@ -146,74 +146,74 @@ ojt-training/ ### Postgres entities (core) -| Entity | Purpose / notes | -| :--- | :--- | -| `User` | Auth identity (seeded in dev) | -| `StockListing` | Symbol directory (name, exchange, logo, industry, etc.) | -| `WatchlistItem` | User → symbol subscription | -| `Trade` | Ownership ledger (immutable position changes); optional `Notes` | -| `AlertRule` | User-defined alert conditions per symbol | -| `Notification` | Persisted alert notifications | +| Entity | Purpose / notes | +| :-------------- | :-------------------------------------------------------------- | +| `User` | Auth identity (seeded in dev) | +| `StockListing` | Symbol directory (name, exchange, logo, industry, etc.) | +| `WatchlistItem` | User → symbol subscription | +| `Trade` | Ownership ledger (immutable position changes); optional `Notes` | +| `AlertRule` | User-defined alert conditions per symbol | +| `Notification` | Persisted alert notifications | ### Postgres entities (intelligence / caching) -| Entity | Purpose | -| :--- | :--- | -| `PriceHistory` | Historical quotes / cache | -| `StockMetric` | Fundamental metrics cache | -| `EarningsSurprise` | Earnings history cache | +| Entity | Purpose | +| :-------------------- | :---------------------------- | +| `PriceHistory` | Historical quotes / cache | +| `StockMetric` | Fundamental metrics cache | +| `EarningsSurprise` | Earnings history cache | | `RecommendationTrend` | Analyst recommendations cache | -| `InsiderTransaction` | Insider trades cache | +| `InsiderTransaction` | Insider trades cache | ### DynamoDB read models -| DynamoDB table | Entry model | -| :--- | :--- | -| `inventoryalert-market-news` | `MarketNewsDynamoEntry` | +| DynamoDB table | Entry model | +| :---------------------------- | :----------------------- | +| `inventoryalert-market-news` | `MarketNewsDynamoEntry` | | `inventoryalert-company-news` | `CompanyNewsDynamoEntry` | --- ## Key Services (API) -| Service | What it does | -| :--- | :--- | -| `PortfolioService` | Positions, cost basis, trades, portfolio alerts | -| `WatchlistService` | CRUD watchlist symbols for a user | -| `AlertRuleService` | CRUD alert rules + evaluation helpers | -| `NotificationService` | Read/ack notifications | -| `StockDataService` | Quotes + profile + market intelligence (cache-first) | +| Service | What it does | +| :-------------------- | :--------------------------------------------------- | +| `PortfolioService` | Positions, cost basis, trades, portfolio alerts | +| `WatchlistService` | CRUD watchlist symbols for a user | +| `AlertRuleService` | CRUD alert rules + evaluation helpers | +| `NotificationService` | Read/ack notifications | +| `StockDataService` | Quotes + profile + market intelligence (cache-first) | --- ## Key Service: `StockDataService` -| Method | What it does | -| :--- | :--- | -| `GetQuoteAsync` | Returns price quote (Redis cache-first) | -| `GetProfileAsync` | Returns company profile (Postgres cache-first) | -| `GetFinancialsAsync` | Returns cached financial metrics (fundamentals) | -| `GetEarningsAsync` | Returns earnings surprises/history | -| `GetRecommendationsAsync` | Returns analyst recommendation trends | -| `GetInsidersAsync` | Returns insider transactions | -| `GetPeersAsync` | Returns peer symbols | -| `GetCompanyNewsAsync` | Returns company news (DynamoDB-backed) | -| `GetMarketNewsAsync` | Returns market news (DynamoDB-backed) | -| `GetMarketStatusAsync` | Returns market status | -| `GetMarketHolidaysAsync` | Returns market holidays | -| `GetEarningsCalendarAsync` | Returns earnings calendar | -| `GetIpoCalendarAsync` | Returns IPO calendar | -| `SearchSymbolsAsync` | Search for tickers/companies | +| Method | What it does | +| :------------------------- | :---------------------------------------------- | +| `GetQuoteAsync` | Returns price quote (Redis cache-first) | +| `GetProfileAsync` | Returns company profile (Postgres cache-first) | +| `GetFinancialsAsync` | Returns cached financial metrics (fundamentals) | +| `GetEarningsAsync` | Returns earnings surprises/history | +| `GetRecommendationsAsync` | Returns analyst recommendation trends | +| `GetInsidersAsync` | Returns insider transactions | +| `GetPeersAsync` | Returns peer symbols | +| `GetCompanyNewsAsync` | Returns company news (DynamoDB-backed) | +| `GetMarketNewsAsync` | Returns market news (DynamoDB-backed) | +| `GetMarketStatusAsync` | Returns market status | +| `GetMarketHolidaysAsync` | Returns market holidays | +| `GetEarningsCalendarAsync` | Returns earnings calendar | +| `GetIpoCalendarAsync` | Returns IPO calendar | +| `SearchSymbolsAsync` | Search for tickers/companies | --- ## DI Registration Points -| What | Where | -| :--- | :--- | -| App settings bind/validate | `InventoryManagementSystem/InventoryAlert.Api/Program.cs` | -| API service registration | `InventoryManagementSystem/InventoryAlert.Api/ServiceExtensions/InfrastructureServiceExtensions.cs` (`AddWebApiInfrastructure`) | -| Infrastructure (EF, repos, Finnhub, AWS, Redis) | `InventoryManagementSystem/InventoryAlert.Infrastructure/DependencyInjection.cs` (`AddInfrastructure`) | +| What | Where | +| :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------ | +| App settings bind/validate | `InventoryManagementSystem/InventoryAlert.Api/Program.cs` | +| API service registration | `InventoryManagementSystem/InventoryAlert.Api/ServiceExtensions/InfrastructureServiceExtensions.cs` (`AddWebApiInfrastructure`) | +| Infrastructure (EF, repos, Finnhub, AWS, Redis) | `InventoryManagementSystem/InventoryAlert.Infrastructure/DependencyInjection.cs` (`AddInfrastructure`) | --- @@ -227,20 +227,20 @@ ojt-training/ ## Available Slash Commands -| Command | When to use | -| :--- | :--- | -| `/init` | Start of every session — re-index BM25, sync context | -| `/plan` | Design a feature before implementation | +| Command | When to use | +| :-------------- | :-------------------------------------------------------------------------- | +| `/init` | Start of every session — re-index BM25, sync context | +| `/plan` | Design a feature before implementation | | `/feature-flow` | Master dev lifecycle: requirement → Domain → App → Infra → Web → Tests → PR | -| `/add-feature` | Adding a new method/endpoint to an existing entity | -| `/add-entity` | Adding a completely new domain entity end-to-end | -| `/db-migration` | Creating or applying an EF Core migration | -| `/run-tests` | Running tests + optional coverage report | -| `/docker-run` | Bringing up the full stack locally | -| `/code-review` | Pre-merge checklist | -| `/fix-build` | Diagnosing build/test failures | -| `/doc` | Sync documentation after implementing a feature | -| `/search` | BM25 search for context without reading full files | +| `/add-feature` | Adding a new method/endpoint to an existing entity | +| `/add-entity` | Adding a completely new domain entity end-to-end | +| `/db-migration` | Creating or applying an EF Core migration | +| `/run-tests` | Running tests + optional coverage report | +| `/docker-run` | Bringing up the full stack locally | +| `/code-review` | Pre-merge checklist | +| `/fix-build` | Diagnosing build/test failures | +| `/doc` | Sync documentation after implementing a feature | +| `/search` | BM25 search for context without reading full files | --- @@ -279,10 +279,10 @@ python .agents/scripts/core/bm25_search.py "StockDataService GetQuoteAsync" --ve Seeded users (development/docker) via `InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/DatabaseSeeder.cs`: -| Username | Email | -| :--- | :--- | -| `admin` | `admin@example.com` | -| `user1` | `user1@example.com` | +| Username | Email | +| :------- | :------------------ | +| `admin` | `admin@example.com` | +| `user1` | `user1@example.com` | --- @@ -314,11 +314,11 @@ python .agents/scripts/core/bm25_search.py "your question about the code" -n 5 ## Quick Links -| Resource | Path | -| :--- | :--- | -| AI System Core | `.agents/GEMINI.md` | -| DDD Architecture Rules | `.agents/skills/ddd-architecture/SKILL.md` | -| Testing Patterns | `.agents/skills/testing-patterns/SKILL.md` | -| Finnhub Integration | `.agents/skills/finnhub-integration/SKILL.md` | -| Project Rules | `.agents/rules/project-rules.md` | -| Roadmap | `doc/ROADMAP.md` | +| Resource | Path | +| :--------------------- | :-------------------------------------------- | +| AI System Core | `.agents/GEMINI.md` | +| DDD Architecture Rules | `.agents/skills/ddd-architecture/SKILL.md` | +| Testing Patterns | `.agents/skills/testing-patterns/SKILL.md` | +| Finnhub Integration | `.agents/skills/finnhub-integration/SKILL.md` | +| Project Rules | `.agents/rules/project-rules.md` | +| Roadmap | `doc/ROADMAP.md` | diff --git a/.agents/rules/project-rules.md b/.agents/rules/project-rules.md index cb052ea..5749f60 100644 --- a/.agents/rules/project-rules.md +++ b/.agents/rules/project-rules.md @@ -52,7 +52,7 @@ These rules apply to **every** code change in this repository. They are the proj - Never inject `AppDbContext` directly into Application-layer services. - Never modify auto-generated `ModelSnapshot.cs` manually. - Migration naming: `Verb + Entity + Detail` e.g. `AddNotificationDetails`. -- Run migrations from `InventoryManagementSystem/` with `--project InventoryAlert.Api`. +- Run migrations from `src/` with `--project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api`. ## Workflow diff --git a/.agents/scripts/core/bm25_config.json b/.agents/scripts/core/bm25_config.json index 175d6f5..a02ca83 100644 --- a/.agents/scripts/core/bm25_config.json +++ b/.agents/scripts/core/bm25_config.json @@ -2,8 +2,8 @@ "scan_folders": [ ".agents", "doc", - "InventoryManagementSystem", - "InventoryAlert.Wiki/docs" + "src", + "src/ui/InventoryAlert.Wiki/docs" ], "folder_boosts": { ".agents/rules": 4.0, @@ -12,7 +12,7 @@ ".agents": 2.5, "doc/archive": 0.1, "doc": 2.0, - "InventoryAlert.Wiki/docs": 2.5 + "src/ui/InventoryAlert.Wiki/docs": 2.5 }, "synonyms": { "product": ["inventory", "item", "stock", "sku"], @@ -52,7 +52,7 @@ "infrastructure/persistence": ["inventoryalert-efcore", "postgresql-table-design"], "migration": ["inventoryalert-efcore", "postgresql-table-design"], "doc/": ["doc-generator"], - "InventoryAlert.Wiki/docs": ["doc-generator"], + "src/ui/InventoryAlert.Wiki/docs": ["doc-generator"], ".agents/workflows": ["find-skills"], ".agents/skills": ["skill-creator"] } diff --git a/.agents/scripts/core/data/bm25_index.bin b/.agents/scripts/core/data/bm25_index.bin index dc8f56ede8dd991b8576adfe2f8b7859495b659d..63298124c39c33ab79e5f33e7083348638722c24 100644 GIT binary patch delta 299569 zcmbS!cVJXi_P?*pn?94?%Yy((AZ^kE2!sxy1QH;iK&B-#LmHV0MNvRSQKEt`a0F4n ziV6tJuH#w(*R`&Ku4Pvi!QK7ZP{6fe{hjmP%w#4I*!|5P_suK!d~P}S+;h*p_uRw3 z*53cyRncqs&EIR7E9kedC+E7JoK4#XN=bb6rhy}+s8QL;8t=-s_O_L+-kyf%*ekB+ zX!rV>JDuL8Esz(d9}w5v-rn3I+Pb{%HmBDswzN09?b6cR1lVCyX<*Z`sDW^_T&05g z^Za0FOJbto&>pi!n)-|$KKdahS+W(z!Rp)92FN?Yo8ad0`WT40LmiW7^|iOU?QY*n zaYa{~+b4E(wmZ7)K8b;Za(jDgD?V~qeO8;*>lC{>@UK&Jw>5QIy}nNTtgF*0+S}WF zR!mi==xnmLcRJw(H=mj1wJvkoUDmc{r&nzCHYrp@tKCki_pWTUwYNajd%9GpzQvpb zp2IPEupiYY!iQziCf;i8Xpz=#%ix!GwfkV#&s-wwb;8<_(Qy#t;p1Ta{ibM@6${J` zZzXF)(NubMf6P!NSJGOY3;EG%+h$TE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@vU*7e_1X*h5k2S)3<+x^o?X znPQ^{6J+-4%IIYF)#C<<9d-jSiGz509|C&h5dz*x|9Mn8yWu;j#`plY6|1}5xR`aH zjEH45wGpYuHll`R(S<5f_?1 zV+N|}=7ur^C2Q$7tk?IQByD1r46LLB6YBt-E_bx%YsZuGmEB1;0lljEQr9au-#prk-WB>=QSrq4hFePgg8 zLEVVoI3dmd;yKfFbYML_@W?5L7c=P;gReN8?9vq=V{5OMrCg_d_6gLI2gX6zdemxl zd{7?4!Z$*0pV4^mWpE?-;-q-+{i%R1fM7r0*o&7 z0qkP|OZdK=!@lx8IXi`Xjt0NA^`F|aDI>}xo+^YcQ#o+!n-^deXpw0@H}(1Qeh zGu&-6ccWB0SowV8!T@%17Bzl79_X|KNX%CPd&iwU#AEg#%0XV6Hd5jQtUIyP_}sNz zAR>|kv#m5u5Yr6#EFp0&`hq(@)4fqIg*xD7!s!w3tA`>uttwrlaZ3X~6EO$D#tYXC z&LDi-zHxC*U9(aL99y5Vehkl7SU3TqA4K2W4)-8;K^!8jfgl*XNQ50R9$jER_rkTJ z$3itKhHMyal!(+3cGuO5bVUeM(6U- zQN8gv_LzWPQE6wD|it{|Gcoi|ZCiK^%>mxqmg8u{VByF^q zU_ytx5Jo4&SA7)g2i;@N(q@Xr(eXi_uvqYv77NFDQztJz4RNkYsp>S`*_*scX;WRp z6IfiFR+gfW#(H?>=;l*Y&J;u=8Zf${jt^0@k6|wiJ4dlgI;OC2oqHVn90&qh0ib_0 zl(ewvL7RJ(arcPjwCK|Bz%Zdg7`}?&j$CZ;{e)Zuih3je-Vy^ zL$Buzc7`tM3-VE$o0`E=A4`g!7@<}~zOoC threshold` | -| `SyncCurrentPricesAsync` | Calls Finnhub per product, updates `CurrentPrice` in one transaction | +| Service | What it does | +| :-------------------- | :--------------------------------------------------- | +| `PortfolioService` | Positions, cost basis, trades, portfolio alerts | +| `WatchlistService` | CRUD watchlist symbols for a user | +| `AlertRuleService` | CRUD alert rules + evaluation helpers | +| `NotificationService` | Read/ack notifications | +| `StockDataService` | Quotes + profile + market intelligence (cache-first) | --- ## Key Service: `StockDataService` -| Method | What it does | -| :--- | :--- | -| `GetQuoteAsync` | Returns price quote (Redis cache-first) | -| `GetProfileAsync` | Returns company profile (Postgres cache-first) | -| `GetCompanyNewsAsync` | Returns filtered news for a symbol | -| `GetRecommendationsAsync`| Returns analyst recommendation trends | -| `GetEarningsAsync` | Returns historical earnings data | -| `SearchSymbolsAsync` | Search for tickers/companies on Finnhub | -| `GetMarketNewsAsync` | Returns general market news | -| `GetMarketStatusAsync` | Returns if exchange is open/closed | -| `GetCryptoExchangesAsync`| Returns supported crypto exchanges | +| Method | What it does | +| :------------------------- | :---------------------------------------------- | +| `GetQuoteAsync` | Returns price quote (Redis cache-first) | +| `GetProfileAsync` | Returns company profile (Postgres cache-first) | +| `GetFinancialsAsync` | Returns cached financial metrics (fundamentals) | +| `GetEarningsAsync` | Returns earnings surprises/history | +| `GetRecommendationsAsync` | Returns analyst recommendation trends | +| `GetInsidersAsync` | Returns insider transactions | +| `GetPeersAsync` | Returns peer symbols | +| `GetCompanyNewsAsync` | Returns company news (DynamoDB-backed) | +| `GetMarketNewsAsync` | Returns market news (DynamoDB-backed) | +| `GetMarketStatusAsync` | Returns market status | +| `GetMarketHolidaysAsync` | Returns market holidays | +| `GetEarningsCalendarAsync` | Returns earnings calendar | +| `GetIpoCalendarAsync` | Returns IPO calendar | +| `SearchSymbolsAsync` | Search for tickers/companies | --- ## DI Registration Points -| What | Where | -| :--- | :--- | -| Application services | `Web/ServiceExtensions/ApplicationServiceExtensions.cs` | -| Infrastructure (repos, EF, Finnhub, worker) | `Web/ServiceExtensions/InfrastructureServiceExtensions.cs` | -| Config singleton | `Program.cs` (`builder.Services.AddSingleton(settings)`) | +| What | Where | +| :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------ | +| App settings bind/validate | `InventoryManagementSystem/InventoryAlert.Api/Program.cs` | +| API service registration | `InventoryManagementSystem/InventoryAlert.Api/ServiceExtensions/InfrastructureServiceExtensions.cs` (`AddWebApiInfrastructure`) | +| Infrastructure (EF, repos, Finnhub, AWS, Redis) | `InventoryManagementSystem/InventoryAlert.Infrastructure/DependencyInjection.cs` (`AddInfrastructure`) | --- -## Known Tech Debt (do not repeat) +## Known Pitfalls (avoid repeating) -| # | Location | Issue | -| :--- | :--- | :--- | -| 1 | `ProductService.UpdateProductAsync` | `StockAlertThreshold` silently dropped — not on entity | -| 2 | `ProductService.UpdateProductAsync` | Blank entity captured before transaction lambda | -| 3 | `ProductService.DeleteProductAsync` | Same blank-entity pattern | -| 4 | `ProductsController.UpdateStockCount` | Business logic in controller (SRP violation) | -| 5 | `FinnhubClient` | `Console.WriteLine` instead of `ILogger` | -| 6 | `GenericRepository` | CS1998 on `DeleteAsync`, `UpdateAsync`, `UpdateRangeAsync` | +- Always assign the final response/result **inside** `_unitOfWork.ExecuteTransactionAsync` (avoid capturing a default/blank value outside the lambda). +- Worker services are singleton by default: use `IServiceScopeFactory` to resolve scoped dependencies safely. +- Finnhub endpoints can fail / rate-limit / be plan-restricted: treat null/empty responses as normal; log and continue. --- ## Available Slash Commands -| Command | When to use | -| :--- | :--- | -| `/init` | Start of every session — re-index BM25, sync context | -| `/plan` | Design a feature before implementation | +| Command | When to use | +| :-------------- | :-------------------------------------------------------------------------- | +| `/init` | Start of every session — re-index BM25, sync context | +| `/plan` | Design a feature before implementation | | `/feature-flow` | Master dev lifecycle: requirement → Domain → App → Infra → Web → Tests → PR | -| `/add-feature` | Adding a new method/endpoint to an existing entity | -| `/add-entity` | Adding a completely new domain entity end-to-end | -| `/db-migration` | Creating or applying an EF Core migration | -| `/run-tests` | Running tests + optional coverage report | -| `/docker-run` | Bringing up the full stack locally | -| `/code-review` | Pre-merge checklist | -| `/fix-build` | Diagnosing build/test failures | -| `/doc` | Sync documentation after implementing a feature | -| `/search` | BM25 search for context without reading full files | +| `/add-feature` | Adding a new method/endpoint to an existing entity | +| `/add-entity` | Adding a completely new domain entity end-to-end | +| `/db-migration` | Creating or applying an EF Core migration | +| `/run-tests` | Running tests + optional coverage report | +| `/docker-run` | Bringing up the full stack locally | +| `/code-review` | Pre-merge checklist | +| `/fix-build` | Diagnosing build/test failures | +| `/doc` | Sync documentation after implementing a feature | +| `/search` | BM25 search for context without reading full files | --- ## BM25 Search Quick Reference -```bash",185,66c592450cd3e4e042691c99bd9dfd87,.agents\GEMINI.md,0,2,"returns, finnhub, entity, context, products, product, core, search",1775574531.0437262,7,commit container stock price iproductrepository quote loss efcore migration application layer price drop domain driven design notification httpget market data item googl data access stock ticker xunit unit test unitofwork periodictimer igenericrepository appdbcontext dbset arrange act assert external api aapl fluentassertions msft business logic postgresql httppost atomicity add-migration postgres efcore iactionresult dockerfile inventory hosted service backgroundservice application service asnotracking compose schema change productservice infrastructure iproductservice threshold entity framework sku database update finnhubpricesyncworker symbol rollback dbcontext savechanges httpput domain entity stock productscontroller,# InventoryAlert.Api — Project Context | InventoryAlert.Api — Project Context --- description: AI cold-start briefing for +```bash",250,b7cb04f50b293e7bbe0c237e85bc0822,.agents\GEMINI.md,0,2,"inventoryalert, inventorymanagementsystem, returns, worker, news, market, cache, current",1779851803.7927704,7,postgresql rollback finnhubpricesyncworker googl business logic domain driven design postgres iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository stock ticker market data application service iunitofwork domain entity application layer dbcontext compose atomicity xunit productservice add-migration commit database update infrastructure container efcore efcore migration notification savechanges msft data access symbol hosted service dockerfile external api price drop unitofwork unit test appdbcontext periodictimer aapl threshold arrange act assert quote igenericrepository dbset backgroundservice schema change stock price savechangesasync,# InventoryAlert — Project Context | InventoryAlert — Project Context --- description: AI cold-start briefing for the doc,"# From project root — re-index -python .agents/scripts/core/bm25_indexer.py",188,66c592450cd3e4e042691c99bd9dfd87,.agents\GEMINI.md,0,3,"from, project, root, index, python, agents, scripts, core",1775574531.0437262,186,commit container stock price iproductrepository quote loss efcore migration application layer price drop domain driven design notification httpget market data item googl data access stock ticker xunit unit test unitofwork periodictimer igenericrepository appdbcontext dbset arrange act assert external api aapl fluentassertions msft business logic postgresql httppost atomicity add-migration postgres efcore iactionresult dockerfile inventory hosted service backgroundservice application service asnotracking compose schema change productservice infrastructure iproductservice threshold entity framework sku database update finnhubpricesyncworker symbol rollback dbcontext savechanges httpput domain entity stock productscontroller,# From project root — re-index | From project root — re-index python .agents/scripts/core/bm25_indexer.py +python .agents/scripts/core/bm25_indexer.py",253,b7cb04f50b293e7bbe0c237e85bc0822,.agents\GEMINI.md,0,3,"from, project, root, index, python, agents, scripts, core",1779851803.7927704,251,postgresql rollback finnhubpricesyncworker googl business logic domain driven design postgres iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository stock ticker market data application service iunitofwork domain entity application layer dbcontext compose atomicity xunit productservice add-migration commit database update infrastructure container efcore efcore migration notification savechanges msft data access symbol hosted service dockerfile external api price drop unitofwork unit test appdbcontext periodictimer aapl threshold arrange act assert quote igenericrepository dbset backgroundservice schema change stock price savechangesasync,# From project root — re-index | From project root — re-index python .agents/scripts/core/bm25_indexer.py doc,"# Search for context -python .agents/scripts/core/bm25_search.py ""your query"" -n 5",191,66c592450cd3e4e042691c99bd9dfd87,.agents\GEMINI.md,0,4,"search, context, python, agents, scripts, core, your, query",1775574531.0437262,189,commit container stock price iproductrepository quote loss efcore migration application layer price drop domain driven design notification httpget market data item googl data access stock ticker xunit unit test unitofwork periodictimer igenericrepository appdbcontext dbset arrange act assert external api aapl fluentassertions msft business logic postgresql httppost atomicity add-migration postgres efcore iactionresult dockerfile inventory hosted service backgroundservice application service asnotracking compose schema change productservice infrastructure iproductservice threshold entity framework sku database update finnhubpricesyncworker symbol rollback dbcontext savechanges httpput domain entity stock productscontroller,"# Search for context | Search for context python .agents/scripts/core/bm25_search.py ""your query"" -n 5" +python .agents/scripts/core/bm25_search.py ""your query"" -n 5",256,b7cb04f50b293e7bbe0c237e85bc0822,.agents\GEMINI.md,0,4,"search, context, python, agents, scripts, core, your, query",1779851803.7927704,254,postgresql rollback finnhubpricesyncworker googl business logic domain driven design postgres iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository stock ticker market data application service iunitofwork domain entity application layer dbcontext compose atomicity xunit productservice add-migration commit database update infrastructure container efcore efcore migration notification savechanges msft data access symbol hosted service dockerfile external api price drop unitofwork unit test appdbcontext periodictimer aapl threshold arrange act assert quote igenericrepository dbset backgroundservice schema change stock price savechangesasync,"# Search for context | Search for context python .agents/scripts/core/bm25_search.py ""your query"" -n 5" doc,"# Scope to a folder -python .agents/scripts/core/bm25_search.py ""ExecuteTransactionAsync"" -n 3 -f "".agents""",194,66c592450cd3e4e042691c99bd9dfd87,.agents\GEMINI.md,0,5,"agents, scope, folder, python, scripts, core, executetransactionasync",1775574531.0437262,192,commit container stock price iproductrepository quote loss efcore migration application layer price drop domain driven design notification httpget market data item googl data access stock ticker xunit unit test unitofwork periodictimer igenericrepository appdbcontext dbset arrange act assert external api aapl fluentassertions msft business logic postgresql httppost atomicity add-migration postgres efcore iactionresult dockerfile inventory hosted service backgroundservice application service asnotracking compose schema change productservice infrastructure iproductservice threshold entity framework sku database update finnhubpricesyncworker symbol rollback dbcontext savechanges httpput domain entity stock productscontroller,"# Scope to a folder | Scope to a folder python .agents/scripts/core/bm25_search.py ""ExecuteTransaction" +python .agents/scripts/core/bm25_search.py ""ExecuteTransactionAsync"" -n 3 -f "".agents""",259,b7cb04f50b293e7bbe0c237e85bc0822,.agents\GEMINI.md,0,5,"agents, scope, folder, python, scripts, core, executetransactionasync",1779851803.7927704,257,postgresql rollback finnhubpricesyncworker googl business logic domain driven design postgres iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository stock ticker market data application service iunitofwork domain entity application layer dbcontext compose atomicity xunit productservice add-migration commit database update infrastructure container efcore efcore migration notification savechanges msft data access symbol hosted service dockerfile external api price drop unitofwork unit test appdbcontext periodictimer aapl threshold arrange act assert quote igenericrepository dbset backgroundservice schema change stock price savechangesasync,"# Scope to a folder | Scope to a folder python .agents/scripts/core/bm25_search.py ""ExecuteTransaction" doc,"# Verify reliability score -python .agents/scripts/core/bm25_search.py ""ProductService"" --verify +python .agents/scripts/core/bm25_search.py ""StockDataService GetQuoteAsync"" --verify ``` --- @@ -208,13 +273,12 @@ python .agents/scripts/core/bm25_search.py ""ProductService"" --verify ## Seed Data -3 products seeded in `AppDbContext.OnModelCreating`: +Seeded users (development/docker) via `InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/DatabaseSeeder.cs`: -| Name | Ticker | OriginPrice | CurrentPrice | Threshold | Stock | -| :--- | :--- | :--- | :--- | :--- | :--- | -| Apple | AAPL | 250 | 200 | 0.20 | 50 | -| Google | GOOGL | 300 | 300 | 0.10 | 100 | -| Microsoft | MSFT | 400 | 400 | 0.15 | 5 | +| Username | Email | +| :------- | :------------------ | +| `admin` | `admin@example.com` | +| `user1` | `user1@example.com` | --- @@ -246,42 +310,46 @@ python .agents/scripts/core/bm25_search.py ""your question about the code"" -n 5 ## Quick Links -| Resource | Path | -| :--- | :--- | -| AI System Core | `.agents/GEMINI.md` | -| DDD Architecture Rules | `.agents/skills/ddd-architecture/SKILL.md` | -| Testing Patterns | `.agents/skills/testing-patterns/SKILL.md` | -| Finnhub Integration | `.agents/skills/finnhub-integration/SKILL.md` | -| Project Rules | `.agents/rules/project-rules.md` | -| Roadmap | `doc/ROADMAP.md` |",260,66c592450cd3e4e042691c99bd9dfd87,.agents\GEMINI.md,0,6,"agents, skills, skill, before, finnhub, rules, verify, core",1775574531.0437262,195,commit container stock price iproductrepository quote loss efcore migration application layer price drop domain driven design notification httpget market data item googl data access stock ticker xunit unit test unitofwork periodictimer igenericrepository appdbcontext dbset arrange act assert external api aapl fluentassertions msft business logic postgresql httppost atomicity add-migration postgres efcore iactionresult dockerfile inventory hosted service backgroundservice application service asnotracking compose schema change productservice infrastructure iproductservice threshold entity framework sku database update finnhubpricesyncworker symbol rollback dbcontext savechanges httpput domain entity stock productscontroller,"# Verify reliability score | Verify reliability score python .agents/scripts/core/bm25_search.py ""ProductServ" +| Resource | Path | +| :--------------------- | :-------------------------------------------- | +| AI System Core | `.agents/GEMINI.md` | +| DDD Architecture Rules | `.agents/skills/ddd-architecture/SKILL.md` | +| Testing Patterns | `.agents/skills/testing-patterns/SKILL.md` | +| Finnhub Integration | `.agents/skills/finnhub-integration/SKILL.md` | +| Project Rules | `.agents/rules/project-rules.md` | +| Roadmap | `doc/ROADMAP.md` |",324,b7cb04f50b293e7bbe0c237e85bc0822,.agents\GEMINI.md,0,6,"agents, skills, skill, before, finnhub, rules, verify, core",1779851803.7927704,260,postgresql rollback finnhubpricesyncworker googl business logic domain driven design postgres iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository stock ticker market data application service iunitofwork domain entity application layer dbcontext compose atomicity xunit productservice add-migration commit database update infrastructure container efcore efcore migration notification savechanges msft data access symbol hosted service dockerfile external api price drop unitofwork unit test appdbcontext periodictimer aapl threshold arrange act assert quote igenericrepository dbset backgroundservice schema change stock price savechangesasync,"# Verify reliability score | Verify reliability score python .agents/scripts/core/bm25_search.py ""StockDataSe" doc,"--- trigger: always_on glob: description: ----",6,a4c2f9930e4255d6975ea8bf25509b00,.agents\rules\project-rules.md,2,7,"trigger, glob, description",1775285184.5310795,1,rollback stock price executetransactionasync inventory fluentassertions infrastructure sku moq appdbcontext entity framework productscontroller efcore migration unitofwork application service httpget iactionresult verify times once mock setup igenericrepository savechanges httppost loss arrange act assert application layer price drop atomicity stock efcore market data iproductservice commit savechangesasync quote iunitofwork item dbset domain driven design dbcontext httpput domain entity productservice threshold notification add-migration xunit external api business logic returns async unit test data access asnotracking database update iproductrepository schema change,project-rules.md | --- trigger: always_on glob: description: --- -doc,"# Project Rules — InventoryAlert.Api +---",6,314b61a6ec34168c25aae1dc52c1ab1e,.agents\rules\project-rules.md,2,7,"trigger, glob, description",1779853514.3165772,1,stock rollback business logic domain driven design moq productscontroller iproductservice item entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository market data application service iunitofwork domain entity application layer mock setup httpget dbcontext iactionresult atomicity returns async xunit productservice add-migration commit sku database update infrastructure times once efcore verify httpput efcore migration notification savechanges data access external api price drop unitofwork unit test appdbcontext httppost threshold arrange act assert quote igenericrepository dbset schema change inventory stock price savechangesasync,project-rules.md | --- trigger: always_on glob: description: --- +doc,"# Project Rules — InventoryAlert + --- -description: Project-level coding standards for InventoryAlert.Api +description: Project-level coding standards for the InventoryAlert solution. type: rules status: active -version: 2.0 +version: 2.1 tags: [rules, coding-standards, ddd, csharp, inventoryalert] -last_updated: 2026-04-04 +last_updated: 2026-05-01 --- -These rules apply to **every** code change in this project. They are non-negotiable defaults that complement the global `user_global` rules. +These rules apply to **every** code change in this repository. They are the project-specific layer on top of your global standards. ---- +## Global Coding Standards + +- Always follow **Clean Architecture** and **Clean Code** principles. +- Prefer readability over cleverness. -## 1. Architecture (DDD) +## Code Style + +### Architecture (DDD boundaries) - **Layer discipline is absolute.** Domain must have zero imports from Application, Infrastructure, or Web. - **The master development flow is `/feature-flow`.** Always follow it top-to-bottom. Do not skip phases. - **Before placing any file**, confirm the correct layer and namespace in `.agents/skills/ddd-architecture/SKILL.md`. ---- - -## 2. C# Coding Standards +### C# coding standards - **Primary constructors (C# 12)** are the preferred injection style across all layers. - **No `async` without `await`** — remove the `async` keyword; return `Task.FromResult(...)` instead (fixes CS1998). @@ -290,32 +358,39 @@ These rules apply to **every** code change in this project. They are non-negotia - **`null!` suppressor** is forbidden unless accompanied by a comment explaining why. - Private fields: `_camelCase`. Everything else: `PascalCase`. ---- +### Python scripts in `.agents/` -## 3. EF Core / Database +- Use type hints on all functions. +- Keep scripts small, deterministic, and readable (these are developer tools, not production code). + +### EF Core / database - Every **write** (Create, Update, Delete, Bulk) must run inside `_unitOfWork.ExecuteTransactionAsync`. - Simple single-inserts with no dependencies may use `_unitOfWork.SaveChangesAsync` instead. - All **read-only** EF queries use `.AsNoTracking()`. - Never inject `AppDbContext` directly into Application-layer services. - Never modify auto-generated `ModelSnapshot.cs` manually. -- Migration naming: `Verb + Entity + Detail` e.g. `AddStockAlertThresholdToProduct`. -- Run migrations from `InventoryManagementSystem/` with `--project InventoryAlert.Api`. +- Migration naming: `Verb + Entity + Detail` e.g. `AddNotificationDetails`. +- Run migrations from `src/` with `--project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api`. ---- +## Workflow -## 4. Transaction Capture Pattern +- Explore the codebase before implementing changes (BM25 search is preferred). +- Plan before coding on complex tasks. +- Run tests after making code changes (prefer the smallest relevant test selection first). + +## Transaction Capture Pattern ```csharp // ❌ BAD — blank entity returned if lambda throws -Product updated = new(); +AlertRule updated = new(); await _unitOfWork.ExecuteTransactionAsync(async () => { updated = await _repo.UpdateAsync(entity); }, ct); -return MapToResponse(updated); // may map a blank Product! +return MapToResponse(updated); // may map a blank entity! // ✅ GOOD — result assigned inside the lambda -ProductResponse result = null!; +AlertRuleResponse result = null!; await _unitOfWork.ExecuteTransactionAsync(async () => { var updated = await _repo.UpdateAsync(entity); result = MapToResponse(updated); @@ -323,25 +398,18 @@ await _unitOfWork.ExecuteTransactionAsync(async () => { return result; ``` ---- - -## 5. External API (Finnhub) +## External API (Finnhub) - Always null-check: `if (quote?.CurrentPrice is null or 0) skip`. - Never throw on Finnhub failure — log and skip. - Use `ILogger`. `Console.WriteLine` is banned. ---- - -## 6. Controller Rules +## Controller Rules - Controllers are thin: call service → return `IActionResult`. No business logic. -- `UpdateStockCount` in `ProductsController` is a known SRP violation (tracked tech debt). Do not replicate in new controllers. - All `appsettings.*.json` with real credentials are gitignored. Only `appsettings.Example.json` is committed. ---- - -## 7. Testing Standards +## Testing Standards - No production code merged without: happy path + not-found + transaction call count verified. - `ExecuteTransactionAsync` mocks **must** invoke the delegate: @@ -351,9 +419,12 @@ return result; - Repository integration tests use EF InMemory with `Guid.NewGuid().ToString()` as database name. - No `Thread.Sleep` in tests. ---- +## Git Conventions -## 8. Git Commit Convention +- Write clear, concise commit messages. +- Never commit sensitive data (API keys, credentials). + +### Commit message format ``` (): @@ -364,13 +435,18 @@ Scope: domain | application | infrastructure | web | tests Examples: ``` -feat(application): add BulkInsert to ProductService +feat(application): add paging to WatchlistService fix(infrastructure): remove async keyword from GenericRepository.UpdateAsync -test(application): add ProductServiceTests for SyncCurrentPricesAsync -refactor(web): move stock-count update logic from controller to service +test(application): add StockDataServiceTests for peers caching +refactor(web): move business logic from controller to service docs(doc): sync unit_test_plan with implementation -```",117,a4c2f9930e4255d6975ea8bf25509b00,.agents\rules\project-rules.md,2,8,"rules, project, inventoryalert, standards, must, coding, every, layer",1775285184.5310795,7,rollback stock price executetransactionasync inventory fluentassertions infrastructure sku moq appdbcontext entity framework productscontroller efcore migration unitofwork application service httpget iactionresult verify times once mock setup igenericrepository savechanges httppost loss arrange act assert application layer price drop atomicity stock efcore market data iproductservice commit savechangesasync quote iunitofwork item dbset domain driven design dbcontext httpput domain entity productservice threshold notification add-migration xunit external api business logic returns async unit test data access asnotracking database update iproductrepository schema change,# Project Rules — InventoryAlert.Api | Project Rules — InventoryAlert.Api --- description: Project-level coding standar -code,,59,f5d9031ba84a2478c9e21af9b011b78f,.agents\scripts\core\bm25_config.json,0,9,core/bm25_config.json,1776910223.9802358,1,atomicity commit add-migration dbcontext application service times once arrange act assert hosted service finnhubpricesyncworker dbset productservice item threshold igenericrepository xunit productscontroller mock setup httpput msft postgres business logic container executetransactionasync iunitofwork iactionresult domain entity moq price drop external api compose backgroundservice loss database update domain driven design unit test googl schema change appdbcontext savechanges dockerfile infrastructure returns async periodictimer stock httppost aapl efcore migration data access fluentassertions httpget entity framework verify rollback symbol stock price notification sku savechangesasync quote iproductrepository postgresql application layer inventory asnotracking market data iproductservice efcore stock ticker unitofwork,[MOD] core/bm25_config.json +``` + +## Communication + +- Ask clarifying questions before architectural changes. +- Explain reasoning for non-obvious decisions.",129,314b61a6ec34168c25aae1dc52c1ab1e,.agents\rules\project-rules.md,2,8,"standards, code, project, rules, inventoryalert, coding, layer, must",1779853514.3165772,7,stock rollback business logic domain driven design moq productscontroller iproductservice item entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository market data application service iunitofwork domain entity application layer mock setup httpget dbcontext iactionresult atomicity returns async xunit productservice add-migration commit sku database update infrastructure times once efcore verify httpput efcore migration notification savechanges data access external api price drop unitofwork unit test appdbcontext httppost threshold arrange act assert quote igenericrepository dbset schema change inventory stock price savechangesasync,# Project Rules — InventoryAlert | Project Rules — InventoryAlert --- description: Project-level coding standards f +code,,59,bbfcc25d2ab960ef019d553a9e036e2e,.agents\scripts\core\bm25_config.json,0,9,core/bm25_config.json,1779852462.211336,1,postgresql stock rollback finnhubpricesyncworker googl business logic domain driven design postgres moq productscontroller iproductservice item entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository stock ticker market data application service iunitofwork domain entity application layer mock setup httpget dbcontext compose iactionresult atomicity returns async xunit productservice add-migration commit sku database update infrastructure times once container efcore verify httpput efcore migration notification savechanges msft data access symbol hosted service dockerfile external api price drop unitofwork unit test appdbcontext httppost periodictimer aapl threshold arrange act assert quote igenericrepository dbset backgroundservice schema change inventory stock price savechangesasync,[MOD] core/bm25_config.json code,,10,96bdf9b4391ebda3c37ff54192804843,.agents\scripts\core\bm25_core.py,0,10,core/bm25_core,1775285790.6141908,1,dbcontext asnotracking entity framework efcore appdbcontext,[MOD] core/bm25_core code,,141,96bdf9b4391ebda3c37ff54192804843,.agents\scripts\core\bm25_core.py,0,11,core/bm25_core,1775285790.6141908,11,dbcontext asnotracking entity framework efcore appdbcontext,[FUNC] core/bm25_core/BM25Plus: code,,145,96bdf9b4391ebda3c37ff54192804843,.agents\scripts\core\bm25_core.py,0,12,core/bm25_core,1775285790.6141908,142,dbcontext asnotracking entity framework efcore appdbcontext,[FUNC] core/bm25_core/save_index_binary @@ -5001,7 +5077,7 @@ version: 2.0 tags: [workflow, code-review, quality, checklist, inventoryalert] --- -// turbo-all",10,05c7da91c5b96196fc41d804cf0f52ea,.agents\skills\code-review\SKILL.md,0,179,"code, review, checklist, workflow, description, before, merging, feature",1775285344.1031108,1,mock setup domain driven design loss domain entity iproductrepository iproductservice quote atomicity stock price httppost dbset sku data access unit test verify price drop arrange act assert dockerfile dbcontext threshold infrastructure productservice commit notification executetransactionasync business logic savechangesasync moq times once xunit efcore external api postgres iunitofwork item container returns async igenericrepository inventory market data productscontroller iactionresult compose application service httpget stock entity framework asnotracking httpput fluentassertions appdbcontext application layer unitofwork rollback postgresql savechanges,SKILL.md | --- description: Code review checklist before merging any feature branch type: w +// turbo-all",10,34e74e989529a5e3e1f19498dbd8ebfa,.agents\skills\code-review\SKILL.md,0,179,"code, review, checklist, workflow, description, before, merging, feature",1779851803.456813,1,fluentassertions commit asnotracking iunitofwork business logic dbset httppost mock setup appdbcontext productscontroller external api times once igenericrepository stock price market data domain driven design postgresql price drop executetransactionasync unitofwork savechangesasync unit test threshold iactionresult entity framework atomicity compose infrastructure quote container productservice arrange act assert notification application service postgres savechanges verify data access dockerfile httpput domain entity httpget loss efcore xunit application layer returns async rollback iproductservice moq iproductrepository dbcontext,SKILL.md | --- description: Code review checklist before merging any feature branch type: w doc,"# /code-review — Pre-Merge Quality Gate **Objective**: Verify every layer meets the project's architecture, quality, and test standards before merging. @@ -5039,14 +5115,14 @@ doc,"# /code-review — Pre-Merge Quality Gate - [ ] Entity never returned raw — only via `MapToResponse()` - [ ] `MapToResponse()` and `MapToEntity()` are `private static` - [ ] `KeyNotFoundException` (not `ArgumentException`) when entity not found on update -- [ ] **No** `new Product()` before a transaction lambda — assign inside the lambda: +- [ ] **No** default entity captured before a transaction lambda — assign inside the lambda: ```csharp // ❌ BAD - Product updated = new(); + AlertRule updated = new(); await _unitOfWork.ExecuteTransactionAsync(async () => { updated = ...; }, ct); // ✅ GOOD - ProductResponse result = null!; + AlertRuleResponse result = null!; await _unitOfWork.ExecuteTransactionAsync(async () => { result = MapToResponse(await ...); }, ct); ``` @@ -5104,7 +5180,7 @@ doc,"# /code-review — Pre-Merge Quality Gate ## Phase 7: Brain Freeze -```bash",113,05c7da91c5b96196fc41d804cf0f52ea,.agents\skills\code-review\SKILL.md,0,180,"phase, only, every, layer, entity, never, tests, standards",1775285344.1031108,11,mock setup domain driven design loss domain entity iproductrepository iproductservice quote atomicity stock price httppost dbset sku data access unit test verify price drop arrange act assert dockerfile dbcontext threshold infrastructure productservice commit notification executetransactionasync business logic savechangesasync moq times once xunit efcore external api postgres iunitofwork item container returns async igenericrepository inventory market data productscontroller iactionresult compose application service httpget stock entity framework asnotracking httpput fluentassertions appdbcontext application layer unitofwork rollback postgresql savechanges,# /code-review — Pre-Merge Quality Gate | /code-review — Pre-Merge Quality Gate Objective: Verify every layer meets the pr +```bash",113,34e74e989529a5e3e1f19498dbd8ebfa,.agents\skills\code-review\SKILL.md,0,180,"phase, only, every, layer, entity, never, tests, standards",1779851803.456813,11,fluentassertions commit asnotracking iunitofwork business logic dbset httppost mock setup appdbcontext productscontroller external api times once igenericrepository stock price market data domain driven design postgresql price drop executetransactionasync unitofwork savechangesasync unit test threshold iactionresult entity framework atomicity compose infrastructure quote container productservice arrange act assert notification application service postgres savechanges verify data access dockerfile httpput domain entity httpget loss efcore xunit application layer returns async rollback iproductservice moq iproductrepository dbcontext,# /code-review — Pre-Merge Quality Gate | /code-review — Pre-Merge Quality Gate Objective: Verify every layer meets the pr doc,"# Re-index with new code python .agents/scripts/core/bm25_indexer.py ``` @@ -5115,7 +5191,7 @@ Sign off in PR description: `✅ /code-review Complete` **Parent Context**: `GEMINI.md` · `.agents/rules/project-rules.md` **Next Action**: Push PR → merge -**Keywords**: `code-review`, `quality`, `checklist`, `ddd`, `inventoryalert`",124,05c7da91c5b96196fc41d804cf0f52ea,.agents\skills\code-review\SKILL.md,0,181,"code, agents, review, rules, index, python, scripts, core",1775285344.1031108,114,mock setup domain driven design loss domain entity iproductrepository iproductservice quote atomicity stock price httppost dbset sku data access unit test verify price drop arrange act assert dockerfile dbcontext threshold infrastructure productservice commit notification executetransactionasync business logic savechangesasync moq times once xunit efcore external api postgres iunitofwork item container returns async igenericrepository inventory market data productscontroller iactionresult compose application service httpget stock entity framework asnotracking httpput fluentassertions appdbcontext application layer unitofwork rollback postgresql savechanges,# Re-index with new code | Re-index with new code python .agents/scripts/core/bm25_indexer.py Sign off in P +**Keywords**: `code-review`, `quality`, `checklist`, `ddd`, `inventoryalert`",124,34e74e989529a5e3e1f19498dbd8ebfa,.agents\skills\code-review\SKILL.md,0,181,"code, agents, review, rules, index, python, scripts, core",1779851803.456813,114,fluentassertions commit asnotracking iunitofwork business logic dbset httppost mock setup appdbcontext productscontroller external api times once igenericrepository stock price market data domain driven design postgresql price drop executetransactionasync unitofwork savechangesasync unit test threshold iactionresult entity framework atomicity compose infrastructure quote container productservice arrange act assert notification application service postgres savechanges verify data access dockerfile httpput domain entity httpget loss efcore xunit application layer returns async rollback iproductservice moq iproductrepository dbcontext,# Re-index with new code | Re-index with new code python .agents/scripts/core/bm25_indexer.py Sign off in P doc,"--- name: csharp-async description: 'Get best practices for C# async programming' @@ -5239,10 +5315,10 @@ version: 2.0 tags: [workflow, migration, efcore, database, postgresql, inventoryalert] --- -// turbo-all",10,9dae74677d29afb66c6c38138d377455,.agents\skills\db-migration\SKILL.md,0,186,"database, migration, workflow, description, create, apply, core, type",1775285344.1031108,1,asnotracking arrange act assert postgres xunit efcore migration notification unit test entity framework stock ticker efcore loss schema change stock appdbcontext symbol postgresql googl fluentassertions sku threshold aapl item inventory container dockerfile price drop database update compose dbcontext msft add-migration,SKILL.md | --- description: Create and apply an EF Core database migration type: workflow s +// turbo-all",10,8de3e8b56214fc8f0fe76c8d0ea594a4,.agents\skills\db-migration\SKILL.md,0,186,"database, migration, workflow, description, create, apply, core, type",1779853520.8979404,1,dockerfile entity framework price drop msft threshold stock stock ticker xunit container postgresql googl fluentassertions appdbcontext sku aapl dbcontext symbol unit test efcore efcore migration item inventory asnotracking add-migration arrange act assert notification postgres compose database update loss schema change,SKILL.md | --- description: Create and apply an EF Core database migration type: workflow s doc,"# /db-migration — EF Core Migration -**Objective**: Create, review, and apply an EF Core migration for schema changes in `InventoryAlert.Api`. +**Objective**: Create, review, and apply an EF Core migration for schema changes (migrations live in `InventoryAlert.Infrastructure`). --- @@ -5265,9 +5341,9 @@ doc,"# /db-migration — EF Core Migration ## Prerequisites - `dotnet-ef` installed: `dotnet tool install -g dotnet-ef` -- PostgreSQL running: `docker-compose up postgres -d` -- `appsettings.Development.json` has valid `ConnectionStrings.DefaultConnection` -- Working directory: solution root `InventoryManagementSystem/` +- PostgreSQL running: `docker compose up db -d` +- `appsettings.Development.json` has valid `Database.DefaultConnection` +- Working directory: `src/` --- @@ -5282,20 +5358,20 @@ dotnet ef --version ### 2. Create the migration ```bash -dotnet ef migrations add --project InventoryAlert.Api --output-dir Infrastructure/Persistence/Migrations +dotnet ef migrations add --project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api --output-dir Migrations ``` Example: ```bash -dotnet ef migrations add AddStockAlertThresholdToProduct --project InventoryAlert.Api --output-dir Infrastructure/Persistence/Migrations +dotnet ef migrations add AddNotificationDetails --project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api --output-dir Migrations ``` > **Naming convention**: PascalCase `Verb + Entity + Detail` -> Examples: `AddStockAlertThresholdToProduct` · `CreateOrderTable` · `RenameTickerSymbolColumn` +> Examples: `AddNotificationDetails` · `CreateOrderTable` · `RenameTickerSymbolColumn` ### 3. Review the generated migration -Open `Infrastructure/Persistence/Migrations/_.cs`: +Open `src/InventoryAlert.Infrastructure/Migrations/_.cs`: - `Up()` — adds/changes exactly what you intended - `Down()` — correctly reverses it @@ -5304,13 +5380,13 @@ Open `Infrastructure/Persistence/Migrations/_.cs`: ### 4. Apply the migration ```bash -dotnet ef database update --project InventoryAlert.Api +dotnet ef database update --project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api ``` ### 5. Verify it applied ```bash -dotnet ef migrations list --project InventoryAlert.Api +dotnet ef migrations list --project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api ``` New migration shows `(Applied)`. @@ -5318,8 +5394,8 @@ New migration shows `(Applied)`. ### 6. Rollback if needed ```bash -dotnet ef database update --project InventoryAlert.Api -dotnet ef migrations remove --project InventoryAlert.Api +dotnet ef database update --project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api +dotnet ef migrations remove --project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api ``` --- @@ -5327,7 +5403,7 @@ dotnet ef migrations remove --project InventoryAlert.Api ## Notes - Migrations run **automatically on startup** via `db.Database.Migrate()` in `Program.cs` -- Seed data lives in `AppDbContext.OnModelCreating` via `HasData()` +- Seed data (dev/docker) is initialized via `DatabaseSeeder` in Infrastructure - For production: run migrations in CI, not at startup - Connection string format: ``` @@ -5340,7 +5416,7 @@ dotnet ef migrations remove --project InventoryAlert.Api | Error | Fix | |-------|-----| -| `No DbContext was found` | Run from `InventoryManagementSystem/`, use `--project InventoryAlert.Api` | +| `No DbContext was found` | Run from `src/`, use `--project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api` | | `Connection refused` | `docker-compose up postgres -d` | | `Pending model changes` | Run `dotnet ef migrations add` to capture drift | | `MSB4066 Include attribute` | Fix nested `` in `.csproj` | @@ -5349,11 +5425,11 @@ dotnet ef migrations remove --project InventoryAlert.Api **Parent Context**: `GEMINI.md` **Next Action**: Restart API to apply migration, then run `/run-tests` -**Keywords**: `migration`, `efcore`, `database`, `postgresql`, `schema`, `inventoryalert`",120,9dae74677d29afb66c6c38138d377455,.agents\skills\db-migration\SKILL.md,0,187,"migration, dotnet, migrations, apply, changes, inventoryalert, postgres, core",1775285344.1031108,11,asnotracking arrange act assert postgres xunit efcore migration notification unit test entity framework stock ticker efcore loss schema change stock appdbcontext symbol postgresql googl fluentassertions sku threshold aapl item inventory container dockerfile price drop database update compose dbcontext msft add-migration,"# /db-migration — EF Core Migration | /db-migration — EF Core Migration Objective: Create, review, and apply an EF Cor" +**Keywords**: `migration`, `efcore`, `database`, `postgresql`, `schema`, `inventoryalert`",120,8de3e8b56214fc8f0fe76c8d0ea594a4,.agents\skills\db-migration\SKILL.md,0,187,"migration, migrations, inventoryalert, infrastructure, dotnet, apply, changes, docker",1779853520.8979404,11,dockerfile entity framework price drop msft threshold stock stock ticker xunit container postgresql googl fluentassertions appdbcontext sku aapl dbcontext symbol unit test efcore efcore migration item inventory asnotracking add-migration arrange act assert notification postgres compose database update loss schema change,"# /db-migration — EF Core Migration | /db-migration — EF Core Migration Objective: Create, review, and apply an EF Cor" doc,"--- name: ddd-architecture description: DDD layer rules, conventions, and architectural boundaries for InventoryAlert.Api. Use this skill whenever placing new code, creating entities, building controllers, or navigating the boundary between the Domain, Application, Infrastructure, and Web layers. ----",5,80decd15fd61e70c317afab7416f22ad,.agents\skills\ddd-architecture\SKILL.md,0,188,"name, architecture, description, layer, rules, conventions, architectural, boundaries",1775280946.6699078,1,iproductrepository appdbcontext iactionresult finnhubpricesyncworker savechanges httppost notification entity framework price drop savechangesasync business logic httpget commit infrastructure asnotracking hosted service productservice dbset loss iproductservice atomicity domain entity efcore data access external api application layer httpput application service backgroundservice rollback dbcontext quote igenericrepository productscontroller domain driven design threshold periodictimer unitofwork stock price market data executetransactionasync iunitofwork,"SKILL.md | --- name: ddd-architecture description: DDD layer rules, conventions, and archit" +---",5,525fbe2370709607839c51702132358f,.agents\skills\ddd-architecture\SKILL.md,0,188,"name, architecture, description, layer, rules, conventions, architectural, boundaries",1779814416.1811423,1,asnotracking entity framework httpget notification external api rollback hosted service unitofwork efcore executetransactionasync iactionresult commit httpput periodictimer httppost infrastructure iproductrepository market data atomicity appdbcontext finnhubpricesyncworker quote iunitofwork savechangesasync dbset business logic domain driven design data access igenericrepository savechanges stock price productservice loss dbcontext domain entity application service backgroundservice application layer threshold iproductservice productscontroller price drop,"SKILL.md | --- name: ddd-architecture description: DDD layer rules, conventions, and archit" doc,"# DDD Architecture for InventoryAlert.Api This skill enforces the strict 4-layer Domain-Driven Design (DDD) architecture used in this project. @@ -5390,7 +5466,7 @@ The fundamental rule: **Dependencies only point inwards.** ## File & Namespace Conventions - **Namespaces**: E.g., `InventoryAlert.Api.Application.Services` (Match folder structure) -- **Formatting**: Primary constructors (C# 12) everywhere. `CancellationToken` as the last parameter in async methods.",42,80decd15fd61e70c317afab7416f22ad,.agents\skills\ddd-architecture\SKILL.md,0,189,"rules, domain, references, layer, application, infrastructure, mandate, allowed",1775280946.6699078,6,iproductrepository appdbcontext iactionresult finnhubpricesyncworker savechanges httppost notification entity framework price drop savechangesasync business logic httpget commit infrastructure asnotracking hosted service productservice dbset loss iproductservice atomicity domain entity efcore data access external api application layer httpput application service backgroundservice rollback dbcontext quote igenericrepository productscontroller domain driven design threshold periodictimer unitofwork stock price market data executetransactionasync iunitofwork,# DDD Architecture for InventoryAlert.Api | DDD Architecture for InventoryAlert.Api This skill enforces the strict 4-layer D +- **Formatting**: Primary constructors (C# 12) everywhere. `CancellationToken` as the last parameter in async methods.",42,525fbe2370709607839c51702132358f,.agents\skills\ddd-architecture\SKILL.md,0,189,"rules, domain, references, layer, application, infrastructure, mandate, allowed",1779814416.1811423,6,asnotracking entity framework httpget notification external api rollback hosted service unitofwork efcore executetransactionasync iactionresult commit httpput periodictimer httppost infrastructure iproductrepository market data atomicity appdbcontext finnhubpricesyncworker quote iunitofwork savechangesasync dbset business logic domain driven design data access igenericrepository savechanges stock price productservice loss dbcontext domain entity application service backgroundservice application layer threshold iproductservice productscontroller price drop,# DDD Architecture for InventoryAlert.Api | DDD Architecture for InventoryAlert.Api This skill enforces the strict 4-layer D doc,"# Application Layer Workflows ### Transaction Usage @@ -5401,17 +5477,17 @@ Capturing a blank entity before the transaction scope and referencing it if the ```csharp // ❌ WRONG: -Product updated = new(); +AlertRule updated = new(); await _unitOfWork.ExecuteTransactionAsync(async () => { updated = await _repo.UpdateAsync(requestEntity); }, ct); -return MapToResponse(updated); // Returns completely blank Product on exception fallback +return MapToResponse(updated); // Returns completely blank entity on exception fallback ``` **Required Pattern**: ```csharp // ✅ CORRECT: -ProductResponse result = null!; +AlertRuleResponse result = null!; await _unitOfWork.ExecuteTransactionAsync(async () => { var updated = await _repo.UpdateAsync(domainEntity); result = MapToResponse(updated); // Extracted only on success @@ -5420,8 +5496,8 @@ return result; ``` ### DTO Mapping -- Never return the raw `Product` Domain entity outside the Application layer. -- Use `private static` mapper methods inside the Service, such as `MapToResponse(Product product)` or `MapToEntity(ProductRequest request)`.",31,46d522d25a72c61f5979305d9856d0f0,.agents\skills\ddd-architecture\references\application-rules.md,0,190,"transaction, product, application, layer, pattern, entity, workflows, usage",1775280953.9160814,1,item executetransactionasync iunitofwork dbcontext commit efcore asnotracking iproductservice atomicity productservice entity framework appdbcontext savechanges savechangesasync unitofwork sku rollback inventory stock application service business logic,"# Application Layer Workflows | Application Layer Workflows Transaction Usage Every mutation operation (Create," +- Never return raw Domain entities outside the Application layer. +- Use `private static` mapper methods inside the Service, such as `MapToResponse(AlertRule rule)` or `MapToEntity(AlertRuleRequest request)`.",31,22518550495ac36857c5cfac0b11b808,.agents\skills\ddd-architecture\references\application-rules.md,0,190,"transaction, application, layer, pattern, workflows, usage, every, mutation",1779814416.182151,1,application service asnotracking savechangesasync entity framework atomicity commit productservice iunitofwork efcore notification executetransactionasync dbcontext business logic price drop appdbcontext loss unitofwork rollback threshold iproductservice savechanges,"# Application Layer Workflows | Application Layer Workflows Transaction Usage Every mutation operation (Create," doc,"# Domain Layer Construction Rules ### Entity Guidelines @@ -5434,14 +5510,14 @@ Entities are POCOs (Plain Old CLR Objects). They hold data and state, but in thi ### Repository Interfaces Interfaces define *what* the application needs to store, not *how*. ```csharp -namespace InventoryAlert.Api.Domain.Interfaces; +namespace InventoryAlert.Domain.Interfaces; -public interface IProductRepository : IGenericRepository +public interface ITradeRepository : IGenericRepository { // Place strictly domain-relevant extraction queries here. - // e.g. Task> GetProductsByThresholdAsync(double threshold, CancellationToken ct); + // e.g. Task> GetByUserAndSymbolAsync(Guid userId, string symbol, CancellationToken ct); } -```",20,cd82712a690bbcf336ff342d8e910f87,.agents\skills\ddd-architecture\references\domain-rules.md,0,191,"they, null, interfaces, domain, layer, construction, rules, entity",1775280949.6196516,1,item loss iproductrepository data access threshold appdbcontext dbset entity framework inventory asnotracking sku notification efcore igenericrepository price drop dbcontext stock,# Domain Layer Construction Rules | Domain Layer Construction Rules Entity Guidelines Entities are POCOs (Plain Old +```",20,4b0034c2a77345408859dc798fd209b9,.agents\skills\ddd-architecture\references\domain-rules.md,0,191,"they, null, interfaces, domain, layer, construction, rules, entity",1779814416.1826577,1,igenericrepository iproductrepository price drop appdbcontext asnotracking loss threshold data access dbset efcore dbcontext entity framework notification,# Domain Layer Construction Rules | Domain Layer Construction Rules Entity Guidelines Entities are POCOs (Plain Old doc,"--- description: Scaffold and synchronize documentation from templates using BM25 and code audits. type: workflow @@ -5986,8 +6062,8 @@ npx skills init my-xyz-skill ```",133,cfba13bd683d468aeb851d9bc23dacd3,.agents\skills\find-skills\SKILL.md,0,204,"skills, skill, user, find, when, asks, testing, install",1769924257.1333504,6,inventory dbcontext efcore compose item arrange act assert fluentassertions unit test xunit entity framework sku postgres appdbcontext asnotracking postgresql container dockerfile stock,# Find Skills | Find Skills This skill helps you discover and install skills from the open agent doc,"--- name: finnhub-integration -description: Provides guidelines for implementing, syncing, and testing Finnhub API integrations. Use this when extending the external price sync service, working on FinnhubPricesSyncWorker, or managing stock/ticker REST responses. ----",5,bc89331ac1903eb966a53c7714595702,.agents\skills\finnhub-integration\SKILL.md,2,205,"finnhub, name, integration, description, provides, guidelines, implementing, syncing",1775280973.693586,1,stock xunit hosted service unit test savechangesasync notification external api sku periodictimer threshold quote appdbcontext application service market data efcore stock price entity framework business logic productservice aapl inventory arrange act assert finnhubpricesyncworker loss executetransactionasync asnotracking iunitofwork backgroundservice stock ticker item symbol iproductservice googl msft price drop dbcontext fluentassertions,"SKILL.md | --- name: finnhub-integration description: Provides guidelines for implementing," +description: Provides guidelines for implementing, syncing, and testing Finnhub API integrations. Use this when extending the external price sync service, worker jobs, or stock/ticker REST responses. +---",5,41c4c13c1930e3b903b36293f3d4fb28,.agents\skills\finnhub-integration\SKILL.md,2,205,"finnhub, name, integration, description, provides, guidelines, implementing, syncing",1779814416.1856654,1,symbol threshold loss arrange act assert aapl iproductservice appdbcontext external api periodictimer quote fluentassertions msft business logic unit test efcore entity framework stock price application service market data productservice stock ticker finnhubpricesyncworker backgroundservice executetransactionasync hosted service price drop asnotracking iunitofwork notification savechangesasync googl xunit dbcontext,"SKILL.md | --- name: finnhub-integration description: Provides guidelines for implementing," doc,"# Finnhub API Integration This skill documents how to safely hit the external Finnhub market API without crashing the `InventoryAlert.Api` container. @@ -6028,21 +6104,21 @@ public async Task GetQuoteAsync(string tickerSymbol, Canc } ``` -## Background Sync (`FinnhubPriceSyncWorker`) +## Background Sync (Worker jobs / hosted services) -The worker uses a `PeriodicTimer` for non-blocking execution inside a `BackgroundService`. +Background processing runs in `InventoryAlert.Worker` (Hangfire jobs + queue polling). If you add a hosted service (or any long-lived singleton), remember: -**Critical rule**: BackgroundServices resolve as Singleton by default. `IUnitOfWork` and Repositories are Scoped. -If modifying the worker, **you must use an `IServiceScopeFactory`** to resolve scoped dependencies safely, otherwise, an `InvalidOperationException` throws on startup. +**Critical rule**: Hosted services resolve as Singleton by default. `IUnitOfWork`, repositories, and most application services are Scoped. +If you need scoped dependencies, **use an `IServiceScopeFactory`** to resolve them safely. ```csharp using var scope = _scopeFactory.CreateScope(); -var productService = scope.ServiceProvider.GetRequiredService(); +var stockDataService = scope.ServiceProvider.GetRequiredService(); // Safely execute cycle... ``` -For full endpoint mapping references available on the free tier, check the project docs: `doc/finnhub/FINNHUB_FREE_ENDPOINTS.md`.",60,bc89331ac1903eb966a53c7714595702,.agents\skills\finnhub-integration\SKILL.md,2,206,"finnhub, external, null, integration, safely, finnhubclient, layer, return",1775280973.693586,6,stock xunit hosted service unit test savechangesasync notification external api sku periodictimer threshold quote appdbcontext application service market data efcore stock price entity framework business logic productservice aapl inventory arrange act assert finnhubpricesyncworker loss executetransactionasync asnotracking iunitofwork backgroundservice stock ticker item symbol iproductservice googl msft price drop dbcontext fluentassertions,# Finnhub API Integration | Finnhub API Integration This skill documents how to safely hit the external Finn +For full endpoint mapping references available on the free tier, check the project docs: `doc/finnhub/FINNHUB_FREE_ENDPOINTS.md`.",60,41c4c13c1930e3b903b36293f3d4fb28,.agents\skills\finnhub-integration\SKILL.md,2,206,"finnhub, external, null, hosted, services, integration, safely, inventoryalert",1779814416.1856654,6,symbol threshold loss arrange act assert aapl iproductservice appdbcontext external api periodictimer quote fluentassertions msft business logic unit test efcore entity framework stock price application service market data productservice stock ticker finnhubpricesyncworker backgroundservice executetransactionasync hosted service price drop asnotracking iunitofwork notification savechangesasync googl xunit dbcontext,# Finnhub API Integration | Finnhub API Integration This skill documents how to safely hit the external Finn doc,"--- description: Diagnose and fix common build and test failures in this solution type: workflow @@ -6051,7 +6127,7 @@ version: 2.0 tags: [workflow, fix-build, diagnostics, errors, inventoryalert, dotnet] --- -// turbo-all",10,584ad25a9adacaf9cd7660232a707c0f,.agents\skills\fix-build\SKILL.md,0,207,"build, workflow, description, diagnose, common, test, failures, solution",1775285344.1061375,1,rollback arrange act assert efcore migration verify inventory iproductrepository iproductservice mock setup times once sku productservice xunit appdbcontext efcore returns async fluentassertions price drop dockerfile container iunitofwork dbcontext data access savechangesasync threshold database update notification igenericrepository compose loss commit add-migration unitofwork atomicity business logic stock price item postgresql schema change asnotracking unit test executetransactionasync external api stock quote moq dbset savechanges market data entity framework application service postgres,SKILL.md | --- description: Diagnose and fix common build and test failures in this solutio +// turbo-all",10,a58452174fa67cddd2548f05d6fb5353,.agents\skills\fix-build\SKILL.md,0,207,"build, workflow, description, diagnose, common, test, failures, solution",1779851803.456813,1,postgresql rollback business logic postgres moq iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository market data application service iunitofwork mock setup dbcontext compose atomicity returns async xunit productservice add-migration commit database update times once container efcore verify efcore migration notification savechanges data access dockerfile external api price drop unitofwork unit test appdbcontext threshold arrange act assert quote igenericrepository dbset schema change stock price savechangesasync,SKILL.md | --- description: Diagnose and fix common build and test failures in this solutio doc,"# /fix-build — Diagnose & Fix Build Failures **Objective**: Quickly identify and fix common build, package, and test failures in `InventoryManagementSystem`. @@ -6168,8 +6244,8 @@ Npgsql.NpgsqlException: Failed to connect to 127.0.0.1:5432 **Fix**: ```bash -docker-compose up postgres -d",127,584ad25a9adacaf9cd7660232a707c0f,.agents\skills\fix-build\SKILL.md,0,208,"build, error, failures, package, csproj, packagereference, diagnose, objective",1775285344.1061375,11,rollback arrange act assert efcore migration verify inventory iproductrepository iproductservice mock setup times once sku productservice xunit appdbcontext efcore returns async fluentassertions price drop dockerfile container iunitofwork dbcontext data access savechangesasync threshold database update notification igenericrepository compose loss commit add-migration unitofwork atomicity business logic stock price item postgresql schema change asnotracking unit test executetransactionasync external api stock quote moq dbset savechanges market data entity framework application service postgres,# /fix-build — Diagnose & Fix Build Failures | /fix-build — Diagnose & Fix Build Failures Objective: Quickly identify and fix c -doc,# Correct connection string:,128,584ad25a9adacaf9cd7660232a707c0f,.agents\skills\fix-build\SKILL.md,0,209,"correct, connection, string",1775285344.1061375,128,rollback arrange act assert efcore migration verify inventory iproductrepository iproductservice mock setup times once sku productservice xunit appdbcontext efcore returns async fluentassertions price drop dockerfile container iunitofwork dbcontext data access savechangesasync threshold database update notification igenericrepository compose loss commit add-migration unitofwork atomicity business logic stock price item postgresql schema change asnotracking unit test executetransactionasync external api stock quote moq dbset savechanges market data entity framework application service postgres,# Correct connection string: | Correct connection string: +docker-compose up postgres -d",127,a58452174fa67cddd2548f05d6fb5353,.agents\skills\fix-build\SKILL.md,0,208,"build, error, failures, package, csproj, packagereference, diagnose, objective",1779851803.456813,11,postgresql rollback business logic postgres moq iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository market data application service iunitofwork mock setup dbcontext compose atomicity returns async xunit productservice add-migration commit database update times once container efcore verify efcore migration notification savechanges data access dockerfile external api price drop unitofwork unit test appdbcontext threshold arrange act assert quote igenericrepository dbset schema change stock price savechangesasync,# /fix-build — Diagnose & Fix Build Failures | /fix-build — Diagnose & Fix Build Failures Objective: Quickly identify and fix c +doc,# Correct connection string:,128,a58452174fa67cddd2548f05d6fb5353,.agents\skills\fix-build\SKILL.md,0,209,"correct, connection, string",1779851803.456813,128,postgresql rollback business logic postgres moq iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository market data application service iunitofwork mock setup dbcontext compose atomicity returns async xunit productservice add-migration commit database update times once container efcore verify efcore migration notification savechanges data access dockerfile external api price drop unitofwork unit test appdbcontext threshold arrange act assert quote igenericrepository dbset schema change stock price savechangesasync,# Correct connection string: | Correct connection string: doc,"# Host=localhost;Port=5432;Database=inventorydb;Username=postgres;Password=postgres ``` @@ -6179,15 +6255,15 @@ doc,"# Host=localhost;Port=5432;Database=inventorydb;Username=postgres;Password= **Fix**: Create `appsettings.Development.json` from example: ```bash -cp InventoryAlert.Api/appsettings.Example.json InventoryAlert.Api/appsettings.Development.json",138,584ad25a9adacaf9cd7660232a707c0f,.agents\skills\fix-build\SKILL.md,0,210,"postgres, inventoryalert, appsettings, json, host, localhost, port, database",1775285344.1061375,129,rollback arrange act assert efcore migration verify inventory iproductrepository iproductservice mock setup times once sku productservice xunit appdbcontext efcore returns async fluentassertions price drop dockerfile container iunitofwork dbcontext data access savechangesasync threshold database update notification igenericrepository compose loss commit add-migration unitofwork atomicity business logic stock price item postgresql schema change asnotracking unit test executetransactionasync external api stock quote moq dbset savechanges market data entity framework application service postgres,# Host=localhost;Port=5432;Database=inventorydb;Username=postgres;Password=postgres | Host=localhost;Port=5432;Database=inventorydb;Username=postgres;Password=postgre +cp InventoryAlert.Api/appsettings.Example.json InventoryAlert.Api/appsettings.Development.json",138,a58452174fa67cddd2548f05d6fb5353,.agents\skills\fix-build\SKILL.md,0,210,"postgres, inventoryalert, appsettings, json, host, localhost, port, database",1779851803.456813,129,postgresql rollback business logic postgres moq iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository market data application service iunitofwork mock setup dbcontext compose atomicity returns async xunit productservice add-migration commit database update times once container efcore verify efcore migration notification savechanges data access dockerfile external api price drop unitofwork unit test appdbcontext threshold arrange act assert quote igenericrepository dbset schema change stock price savechangesasync,# Host=localhost;Port=5432;Database=inventorydb;Username=postgres;Password=postgres | Host=localhost;Port=5432;Database=inventorydb;Username=postgres;Password=postgre doc,"# Fill in Finnhub API key and DB connection string ``` --- -### ❌ Test — `ProductFixtures` type not found +### ❌ Test — shared fixture type not found ``` -error CS0246: The type or namespace name 'ProductFixtures' could not be found +error CS0246: The type or namespace name '...Fixtures' could not be found ``` **Fix**: Ensure `InventoryAlert.Tests.csproj` has: @@ -6227,14 +6303,14 @@ Expected: `Failed: 0` **Parent Context**: `GEMINI.md` · `.agents/skills/testing-patterns/SKILL.md` **Next Action**: If build green → `/run-tests` -**Keywords**: `fix-build`, `CS1998`, `NuGet`, `MSB4066`, `efcore`, `mock`, `inventoryalert`",186,584ad25a9adacaf9cd7660232a707c0f,.agents\skills\fix-build\SKILL.md,0,211,"action, task, build, inventoryalert, func, runs, setup, executetransactionasync",1775285344.1061375,139,rollback arrange act assert efcore migration verify inventory iproductrepository iproductservice mock setup times once sku productservice xunit appdbcontext efcore returns async fluentassertions price drop dockerfile container iunitofwork dbcontext data access savechangesasync threshold database update notification igenericrepository compose loss commit add-migration unitofwork atomicity business logic stock price item postgresql schema change asnotracking unit test executetransactionasync external api stock quote moq dbset savechanges market data entity framework application service postgres,# Fill in Finnhub API key and DB connection string | Fill in Finnhub API key and DB connection string --- ❌ Test — ProductFixtures t +**Keywords**: `fix-build`, `CS1998`, `NuGet`, `MSB4066`, `efcore`, `mock`, `inventoryalert`",186,a58452174fa67cddd2548f05d6fb5353,.agents\skills\fix-build\SKILL.md,0,211,"action, task, build, inventoryalert, func, runs, setup, executetransactionasync",1779851803.456813,139,postgresql rollback business logic postgres moq iproductservice entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository market data application service iunitofwork mock setup dbcontext compose atomicity returns async xunit productservice add-migration commit database update times once container efcore verify efcore migration notification savechanges data access dockerfile external api price drop unitofwork unit test appdbcontext threshold arrange act assert quote igenericrepository dbset schema change stock price savechangesasync,# Fill in Finnhub API key and DB connection string | Fill in Finnhub API key and DB connection string --- ❌ Test — shared fixture ty doc,"--- name: inventoryalert-async-patterns -description: Provides strict heuristics and guidelines for asynchronous Task handling matching C# 12 and the Finnhub BackgroundService constraints. Use this skill when modifying threaded handlers, dealing with execution scopes, adding Background services, passing CancellationTokens, or whenever async concurrency optimizations apply to the project. ----",5,d418005c07f109154dca533c16d78878,.agents\skills\inventoryalert-async-patterns\SKILL.md,0,212,"async, name, inventoryalert, patterns, description, provides, strict, heuristics",1775282376.75359,1,application service compose entity framework loss appdbcontext httppost iunitofwork iproductservice business logic periodictimer postgresql httpput market data external api asnotracking finnhubpricesyncworker quote price drop dbcontext postgres stock price executetransactionasync dockerfile threshold backgroundservice iactionresult productservice httpget notification container hosted service savechangesasync efcore productscontroller,SKILL.md | --- name: inventoryalert-async-patterns description: Provides strict heuristics +description: Provides strict heuristics and guidelines for asynchronous Task handling matching C# 12 and the worker/background processing constraints. Use this skill when modifying threaded handlers, dealing with execution scopes, adding hosted services, passing CancellationTokens, or whenever async concurrency optimizations apply to the project. +---",5,92bd6b50af3bbe61c27eca04fa147653,.agents\skills\inventoryalert-async-patterns\SKILL.md,0,212,"async, name, inventoryalert, patterns, description, provides, strict, heuristics",1779814416.1866658,1,postgresql threshold productservice httppost container executetransactionasync stock price business logic compose productscontroller httpget iunitofwork price drop dockerfile dbcontext postgres finnhubpricesyncworker iproductservice periodictimer quote loss hosted service entity framework notification asnotracking efcore application service appdbcontext httpput backgroundservice iactionresult external api market data savechangesasync,SKILL.md | --- name: inventoryalert-async-patterns description: Provides strict heuristics doc,"# InventoryAlert Async Patterns -Because `InventoryAlert.Api` relies on background tasks (`FinnhubPricesSyncWorker`) that operate simultaneously alongside Web API controllers, handling asynchronous states is extremely delicate. +Because this solution runs background processing (Hangfire jobs + queue polling) alongside Web API controllers, handling asynchronous states is extremely delicate. ## CancellationToken Propagation We rigidly enforce complete propagation. Every single async method inside `Domain`, `Application`, and `Infrastructure` layers **must** take a `CancellationToken ct` as its absolute last parameter. @@ -6246,35 +6322,35 @@ When making remote calls (like inside `FinnhubClient`), pass this token forward Please refer to the following code pattern architectures for implementing and debugging: - **Factory Spawning**: See [references/scope-factory.md](references/scope-factory.md) for the acceptable `IServiceScopeFactory` paradigm to resolve dependencies inside Timers. -- **Task Await Anti-Patterns**: See [references/await-rules.md](references/await-rules.md) for handling the `.Result` or CS1998 exceptions when integrating `Task` flows.",20,d418005c07f109154dca533c16d78878,.agents\skills\inventoryalert-async-patterns\SKILL.md,0,213,"inside, references, when, scope, factory, await, inventoryalert, async",1775282376.75359,6,application service compose entity framework loss appdbcontext httppost iunitofwork iproductservice business logic periodictimer postgresql httpput market data external api asnotracking finnhubpricesyncworker quote price drop dbcontext postgres stock price executetransactionasync dockerfile threshold backgroundservice iactionresult productservice httpget notification container hosted service savechangesasync efcore productscontroller,# InventoryAlert Async Patterns | InventoryAlert Async Patterns Because InventoryAlert.Api relies on background ta +- **Task Await Anti-Patterns**: See [references/await-rules.md](references/await-rules.md) for handling the `.Result` or CS1998 exceptions when integrating `Task` flows.",20,92bd6b50af3bbe61c27eca04fa147653,.agents\skills\inventoryalert-async-patterns\SKILL.md,0,213,"inside, references, when, scope, factory, await, async, patterns",1779814416.1866658,6,postgresql threshold productservice httppost container executetransactionasync stock price business logic compose productscontroller httpget iunitofwork price drop dockerfile dbcontext postgres finnhubpricesyncworker iproductservice periodictimer quote loss hosted service entity framework notification asnotracking efcore application service appdbcontext httpput backgroundservice iactionresult external api market data savechangesasync,# InventoryAlert Async Patterns | InventoryAlert Async Patterns Because this solution runs background processing ( doc,"# Service Scope Factory Resolving Any threaded execution not spawned from an HTTP Web Request (i.e., Background timers, external Event Subscribers) has no inherent request scope container. ```csharp -// Inside FinnhubPricesSyncWorker.ExecuteAsync() +// Inside a Worker job / hosted service execution using var scope = _scopeFactory.CreateScope(); var unitOfWork = scope.ServiceProvider.GetRequiredService(); -var productRepo = scope.ServiceProvider.GetRequiredService(); +var tradeRepo = scope.ServiceProvider.GetRequiredService(); // Action can safely be executed inside the bounds of the ""using"" destruction scope await unitOfWork.ExecuteTransactionAsync(async () => { // perform actions }, stoppingToken); -```",16,b9dabc4d62f1719bfa32653ba0afa212,.agents\skills\inventoryalert-async-patterns\references\scope-factory.md,0,214,"scope, request, service, factory, resolving, threaded, execution, spawned",1775282377.9110706,1,rollback hosted service stock price executetransactionasync inventory sku appdbcontext entity framework unitofwork application service igenericrepository savechanges atomicity stock efcore market data iproductservice commit savechangesasync quote iunitofwork item finnhubpricesyncworker dbset dbcontext productservice backgroundservice periodictimer external api business logic data access asnotracking iproductrepository,# Service Scope Factory Resolving | Service Scope Factory Resolving Any threaded execution not spawned from an HTTP +```",16,3abb9e3aa1b7cd4e9c6febd54c3368ff,.agents\skills\inventoryalert-async-patterns\references\scope-factory.md,0,214,"scope, request, service, factory, resolving, threaded, execution, spawned",1779814416.1876884,1,savechanges iproductservice iunitofwork appdbcontext data access productservice dbcontext iproductrepository executetransactionasync entity framework application service rollback efcore business logic periodictimer finnhubpricesyncworker atomicity dbset commit unitofwork backgroundservice igenericrepository asnotracking hosted service savechangesasync,# Service Scope Factory Resolving | Service Scope Factory Resolving Any threaded execution not spawned from an HTTP doc,"--- name: inventoryalert-efcore description: Project-specific design and optimization rules for PostgreSQL tables managed via Entity Framework Core 10. Use this skill when modifying the database schema, writing complex EF Core LINQ queries, dealing with index/key configurations in the Infrastructure project, or working heavily with Npgsql optimizations. ----",5,e1d2ed1c98cfcd7d65b161d12fd86718,.agents\skills\inventoryalert-efcore\SKILL.md,0,215,"project, core, name, inventoryalert, efcore, description, specific, design",1775282370.2998025,1,compose efcore sku postgres database update appdbcontext dockerfile asnotracking efcore migration threshold postgresql stock schema change add-migration item loss container entity framework inventory dbcontext notification price drop,SKILL.md | --- name: inventoryalert-efcore description: Project-specific design and optimiz +---",5,ed4f5306da12a3f593d760e4e11b3cd9,.agents\skills\inventoryalert-efcore\SKILL.md,0,215,"project, core, name, inventoryalert, efcore, description, specific, design",1779814416.1882029,1,entity framework dbcontext threshold schema change efcore migration container postgresql compose efcore notification price drop loss add-migration database update postgres asnotracking appdbcontext dockerfile,SKILL.md | --- name: inventoryalert-efcore description: Project-specific design and optimiz doc,"# InventoryAlert PostgreSQL & EF Core Strategy This skill outlines the Antigravity setup for managing PostgreSQL data safely through EF Core within the `InventoryAlert.Api.Infrastructure` namespace. ## Schema Configuration -We actively separate Entity classes (POCOs) from schema configuration. Do not clutter `Product.cs` with database mapping attributes like `[Table]` or `[Column]`. +We actively separate Entity classes (POCOs) from schema configuration. Do not clutter entity classes with database mapping attributes like `[Table]` or `[Column]`. -Instead, place all constraints in the `Infrastructure/Persistence/Configurations/` directory using `IEntityTypeConfiguration`. +Instead, place all constraints in `InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/` using `IEntityTypeConfiguration`. * **String Defaults:** Postgres treats empty strings and `null` string distinctively. Always ensure strings default to `string.Empty` domain-side unless configured to allow null schema-side. * **Precision Specs:** Decimal fields mapping to monetary values (like `CurrentPrice`) must have precision explicit formats: `builder.Property(x => x.CurrentPrice).HasPrecision(18, 4);`. @@ -6284,7 +6360,7 @@ Instead, place all constraints in the `Infrastructure/Persistence/Configurations For advanced querying behaviors specifically tailored to the project setup, please refer to the progressive disclosure references: - **Query Optimizations (.AsNoTracking):** See [references/read-optimizations.md](references/read-optimizations.md) for handling pure-read pipelines. -- **Migration & Tracking Checks:** See [references/migration-workflows.md](references/migration-workflows.md) to ensure schema commands successfully build within this specific Docker layer mapping.",23,e1d2ed1c98cfcd7d65b161d12fd86718,.agents\skills\inventoryalert-efcore\SKILL.md,0,216,"references, schema, core, mapping, string, optimizations, read, migration",1775282370.2998025,6,compose efcore sku postgres database update appdbcontext dockerfile asnotracking efcore migration threshold postgresql stock schema change add-migration item loss container entity framework inventory dbcontext notification price drop,# InventoryAlert PostgreSQL & EF Core Strategy | InventoryAlert PostgreSQL & EF Core Strategy This skill outlines the Antigravity +- **Migration & Tracking Checks:** See [references/migration-workflows.md](references/migration-workflows.md) to ensure schema commands successfully build within this specific Docker layer mapping.",23,ed4f5306da12a3f593d760e4e11b3cd9,.agents\skills\inventoryalert-efcore\SKILL.md,0,216,"references, schema, inventoryalert, core, mapping, string, optimizations, read",1779814416.1882029,6,entity framework dbcontext threshold schema change efcore migration container postgresql compose efcore notification price drop loss add-migration database update postgres asnotracking appdbcontext dockerfile,# InventoryAlert PostgreSQL & EF Core Strategy | InventoryAlert PostgreSQL & EF Core Strategy This skill outlines the Antigravity doc,"# Query Optimizations ### Tracking Contexts @@ -6293,7 +6369,7 @@ The highest latency trap in our PostgreSQL setup involves large payloads (e.g., Any query executed without an accompanying update map **must** append `.AsNoTracking()`. ### EF Core Specific LINQ Functions -When writing LINQ queries against PostgreSQL, prioritize `Microsoft.EntityFrameworkCore.EF.Functions.ILike` over `string.Contains` when checking tickers, as `ILike` takes advantage of native PostgreSQL case-insensitive comparisons without loading the column to memory first.",9,e4b511c7b2a1f6d1f769714aa7c87354,.agents\skills\inventoryalert-efcore\references\read-optimizations.md,0,217,"postgresql, query, without, linq, functions, when, ilike, optimizations",1775282374.665742,1,asnotracking sku entity framework item symbol stock aapl appdbcontext inventory googl stock ticker msft efcore dbcontext,# Query Optimizations | Query Optimizations Tracking Contexts The highest latency trap in our PostgreSQ +When writing LINQ queries against PostgreSQL, prioritize `Microsoft.EntityFrameworkCore.EF.Functions.ILike` over `string.Contains` when checking tickers, as `ILike` takes advantage of native PostgreSQL case-insensitive comparisons without loading the column to memory first.",9,66ec63868c0aaad8776d3948f16e68b7,.agents\skills\inventoryalert-efcore\references\read-optimizations.md,0,217,"postgresql, query, without, linq, functions, when, ilike, optimizations",1779814416.1887345,1,symbol appdbcontext msft stock dbcontext asnotracking item efcore stock ticker sku inventory entity framework aapl googl,# Query Optimizations | Query Optimizations Tracking Contexts The highest latency trap in our PostgreSQ doc,"--- description: Combined execution flow from requirement analysis to pushed code type: workflow @@ -7012,7 +7088,7 @@ version: 2.0 tags: [workflow, tests, xunit, coverage, inventoryalert] --- -// turbo-all",10,123a788dedf7445bc1ef839d781e2c29,.agents\skills\run-tests\SKILL.md,0,225,"tests, coverage, workflow, description, unit, optional, report, type",1775285512.6616633,1,httpput productservice fluentassertions application service loss productscontroller efcore httpget iproductservice iactionresult threshold dbcontext arrange act assert notification appdbcontext data access inventory dbset unit test business logic entity framework xunit item asnotracking price drop httppost stock sku igenericrepository iproductrepository,SKILL.md | --- description: Run unit tests with optional coverage report type: workflow sta +// turbo-all",10,00145cb18df372b1553861f7a84ff978,.agents\skills\run-tests\SKILL.md,0,225,"tests, coverage, workflow, description, unit, optional, report, type",1779853527.283339,1,asnotracking entity framework httpget notification efcore iactionresult fluentassertions httpput httppost arrange act assert iproductrepository appdbcontext dbset business logic data access igenericrepository productservice loss xunit dbcontext unit test application service threshold iproductservice productscontroller price drop,SKILL.md | --- description: Run unit tests with optional coverage report type: workflow sta doc,"# /run-tests — Unit Test Execution **Objective**: Run the xUnit test suite for `InventoryAlert.Tests` with optional coverage reporting. @@ -7037,7 +7113,7 @@ doc,"# /run-tests — Unit Test Execution ## Prerequisites -- `InventoryManagementSystem/` as working directory +- Root directory as working directory - Packages: `xunit`, `Moq`, `FluentAssertions`, `EF InMemory` (all in `.csproj`) --- @@ -7054,27 +7130,29 @@ dotnet build --no-restore ### 2. Run all tests ```bash -dotnet test InventoryManagementSystem --no-build --verbosity normal +dotnet test src/InventoryManagementSystem.sln --no-build --verbosity normal ``` ### 3. Run by test class ```bash -dotnet test InventoryManagementSystem --no-build --filter ""FullyQualifiedName~ProductServiceTests"" -dotnet test InventoryManagementSystem --no-build --filter ""FullyQualifiedName~ProductsControllerTests"" -dotnet test InventoryManagementSystem --no-build --filter ""FullyQualifiedName~GenericRepositoryTests"" +dotnet test src/InventoryManagementSystem.sln --no-build --filter ""FullyQualifiedName~PortfolioServiceTests"" +dotnet test src/InventoryManagementSystem.sln --no-build --filter ""FullyQualifiedName~StockDataServiceTests"" +dotnet test src/InventoryManagementSystem.sln --no-build --filter ""FullyQualifiedName~AlertRuleServiceTests"" +dotnet test src/InventoryManagementSystem.sln --no-build --filter ""FullyQualifiedName~WatchlistControllerTests"" +dotnet test src/InventoryManagementSystem.sln --no-build --filter ""FullyQualifiedName~GenericRepositoryTests"" ``` ### 4. Run by method name ```bash -dotnet test InventoryManagementSystem --no-build --filter ""FullyQualifiedName~GetAll_ReturnsEmptyList_WhenNoProductsExist"" +dotnet test src/InventoryManagementSystem.sln --no-build --filter ""FullyQualifiedName~GetQuote_ReturnsCachedResult_WhenAvailable"" ``` ### 5. Run with coverage (HTML report) ```bash -dotnet test InventoryManagementSystem --no-build --collect:""XPlat Code Coverage"" --results-directory ./TestResults +dotnet test src/InventoryManagementSystem.sln --no-build --collect:""XPlat Code Coverage"" --results-directory ./TestResults dotnet tool install -g dotnet-reportgenerator-globaltool reportgenerator -reports:""./TestResults/**/coverage.cobertura.xml"" -targetdir:""./TestResults/CoverageReport"" -reporttypes:Html start ./TestResults/CoverageReport/index.html @@ -7103,7 +7181,7 @@ Passed: 43 Failed: 0 Skipped: 0 | Error | Fix | |-------|-----| | NuGet version conflict | Align `Microsoft.EntityFrameworkCore.InMemory` to `10.0.5` | -| `ProductFixtures` type not found | Add `` to `InventoryAlert.Api.csproj` in test `.csproj` | +| Shared test fixture type not found | Add missing `` entries in the test `.csproj` | | `CS1998` in test build | Remove `async` from `GenericRepository` non-awaiting methods | | Test isoloation failure | Ensure EF InMemory tests use `Guid.NewGuid().ToString()` as DB name | @@ -7111,7 +7189,7 @@ Passed: 43 Failed: 0 Skipped: 0 **Parent Context**: `.agents/GEMINI.md` · `.agents/skills/testing-patterns/SKILL.md` **Next Action**: If all pass → `/code-review`; if failures → `/fix-build` -**Keywords**: `tests`, `xunit`, `moq`, `fluentassertions`, `coverage`, `inventoryalert`",109,123a788dedf7445bc1ef839d781e2c29,.agents\skills\run-tests\SKILL.md,0,226,"test, tests, coverage, xunit, inventoryalert, inmemory, csproj, build",1775285512.6616633,11,httpput productservice fluentassertions application service loss productscontroller efcore httpget iproductservice iactionresult threshold dbcontext arrange act assert notification appdbcontext data access inventory dbset unit test business logic entity framework xunit item asnotracking price drop httppost stock sku igenericrepository iproductrepository,# /run-tests — Unit Test Execution | /run-tests — Unit Test Execution Objective: Run the xUnit test suite for Invento +**Keywords**: `tests`, `xunit`, `moq`, `fluentassertions`, `coverage`, `inventoryalert`",111,00145cb18df372b1553861f7a84ff978,.agents\skills\run-tests\SKILL.md,0,226,"test, tests, coverage, xunit, inmemory, build, inventoryalert, context",1779853527.283339,11,asnotracking entity framework httpget notification efcore iactionresult fluentassertions httpput httppost arrange act assert iproductrepository appdbcontext dbset business logic data access igenericrepository productservice loss xunit dbcontext unit test application service threshold iproductservice productscontroller price drop,# /run-tests — Unit Test Execution | /run-tests — Unit Test Execution Objective: Run the xUnit test suite for Invento doc,"--- name: skill-creator description: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations. @@ -7588,7 +7666,7 @@ code,,95,1ed0e597735fd54ae5dc879bd7a046a1,.agents\skills\skill-creator\scripts\q doc,"--- name: testing-patterns description: Provides testing recipes, mocks setup, and syntax conventions for InventoryAlert.Tests. Trigger this skill whenever writing unit or integration tests, validating test coverage, or testing controllers/services/repositories using xUnit, Moq, or FluentAssertions. ----",5,8f925c71d1836b6744a03392d8e8d589,.agents\skills\testing-patterns\SKILL.md,0,245,"testing, tests, name, patterns, description, provides, recipes, mocks",1775280955.0295475,1,application service arrange act assert igenericrepository entity framework savechanges loss mock setup appdbcontext httppost iproductservice atomicity verify xunit item business logic returns async httpput times once iproductrepository asnotracking fluentassertions price drop dbcontext sku unit test rollback threshold iactionresult productservice httpget inventory notification stock commit data access moq dbset efcore productscontroller unitofwork,"SKILL.md | --- name: testing-patterns description: Provides testing recipes, mocks setup, a" +---",5,21241834647e21aa163251c1e676cd4d,.agents\skills\testing-patterns\SKILL.md,0,245,"testing, tests, name, patterns, description, provides, recipes, mocks",1779814416.195035,1,savechanges unitofwork httppost threshold moq loss arrange act assert iproductservice productscontroller httpget appdbcontext inventory fluentassertions business logic returns async iactionresult verify unit test mock setup atomicity efcore entity framework rollback application service data access times once httpput productservice item iproductrepository igenericrepository price drop asnotracking commit notification stock sku dbset xunit dbcontext,"SKILL.md | --- name: testing-patterns description: Provides testing recipes, mocks setup, a" doc,"# Testing Patterns for InventoryAlert.Tests This skill dictates how to structure test suites, mock dependencies, and write assertions cleanly. @@ -7626,7 +7704,7 @@ Based on what you are testing, use the following references for explicit code pa ## Naming Convention Strictly use: `__` -*(Example: `GetById_ReturnsNull_WhenProductNotFound`)*",43,8f925c71d1836b6744a03392d8e8d589,.agents\skills\testing-patterns\SKILL.md,0,246,"references, mock, assertions, recipes, inmemory, testing, patterns, tests",1775280955.0295475,6,application service arrange act assert igenericrepository entity framework savechanges loss mock setup appdbcontext httppost iproductservice atomicity verify xunit item business logic returns async httpput times once iproductrepository asnotracking fluentassertions price drop dbcontext sku unit test rollback threshold iactionresult productservice httpget inventory notification stock commit data access moq dbset efcore productscontroller unitofwork,# Testing Patterns for InventoryAlert.Tests | Testing Patterns for InventoryAlert.Tests This skill dictates how to structure t +*(Example: `GetById_ReturnsNull_WhenProductNotFound`)*",43,21241834647e21aa163251c1e676cd4d,.agents\skills\testing-patterns\SKILL.md,0,246,"references, mock, assertions, recipes, inmemory, testing, patterns, tests",1779814416.195035,6,savechanges unitofwork httppost threshold moq loss arrange act assert iproductservice productscontroller httpget appdbcontext inventory fluentassertions business logic returns async iactionresult verify unit test mock setup atomicity efcore entity framework rollback application service data access times once httpput productservice item iproductrepository igenericrepository price drop asnotracking commit notification stock sku dbset xunit dbcontext,# Testing Patterns for InventoryAlert.Tests | Testing Patterns for InventoryAlert.Tests This skill dictates how to structure t doc,"# EF InMemory Integration When testing `GenericRepository` or concrete EF code, using `Microsoft.EntityFrameworkCore.InMemory` requires careful state initialization. @@ -7651,7 +7729,7 @@ await dbContext.SaveChangesAsync(); // Initialize subject and assert var repo = new GenericRepository(dbContext); var result = await repo.GetAllAsync(CancellationToken.None); -```",25,560f8d5b3072e2c5810d3cc9064f30b4,.agents\skills\testing-patterns\references\ef-inmemory.md,0,247,"inmemory, state, initialization, database, test, integration, when, testing",1775280972.4196956,1,efcore inventory igenericrepository sku xunit appdbcontext dbcontext asnotracking item stock data access dbset arrange act assert entity framework unit test iproductrepository fluentassertions,"# EF InMemory Integration | EF InMemory Integration When testing GenericRepository or concrete EF code, usin" +```",25,d56f234994ac76cfe033ab88382d8098,.agents\skills\testing-patterns\references\ef-inmemory.md,0,247,"inmemory, state, initialization, database, test, integration, when, testing",1779814416.1960337,1,efcore stock entity framework arrange act assert appdbcontext unit test igenericrepository dbcontext data access dbset xunit item inventory asnotracking sku fluentassertions iproductrepository,"# EF InMemory Integration | EF InMemory Integration When testing GenericRepository or concrete EF code, usin" doc,"# Mocking Recipes ### The UnitOfWork Pitfall @@ -7675,7 +7753,7 @@ _repo.Verify(r => r.UpdateAsync(It.IsAny()), Times.Once); // Assert safety mechanism (short-circuited) _repo.Verify(r => r.DeleteAsync(It.IsAny()), Times.Never); -```",24,0424fe7c390f0f3b148096bb7ee12412,.agents\skills\testing-patterns\references\mock-recipes.md,0,248,"delegate, mocking, recipes, unitofwork, pitfall, when, writing, services",1775280966.0238352,1,rollback business logic sku productservice xunit application service unitofwork stock moq commit item executetransactionasync mock setup arrange act assert fluentassertions times once atomicity iunitofwork verify inventory savechanges unit test returns async savechangesasync iproductservice,"# Mocking Recipes | Mocking Recipes The UnitOfWork Pitfall When writing services, ExecuteTransactio" +```",24,befbe977c0cd4ca87b28c0da8cb44159,.agents\skills\testing-patterns\references\mock-recipes.md,0,248,"delegate, mocking, recipes, unitofwork, pitfall, when, writing, services",1779814416.1960337,1,sku fluentassertions iproductservice xunit unitofwork mock setup rollback returns async item savechangesasync verify savechanges productservice times once moq stock inventory unit test arrange act assert commit application service iunitofwork executetransactionasync business logic atomicity,"# Mocking Recipes | Mocking Recipes The UnitOfWork Pitfall When writing services, ExecuteTransactio" doc,"--- description: initialize project context and guide on search/docs type: workflow @@ -7684,7 +7762,7 @@ version: 2.0 tags: [workflow, init, bm25, context, onboarding] --- -// turbo-all",10,807b20ec43c9eb0b01a681352ee37c47,.agents\workflows\init.md,0,249,"context, workflow, description, initialize, project, guide, search, docs",1775327960.6894755,1,item market data finnhubpricesyncworker domain entity productservice stock savechanges efcore rollback backgroundservice application service add-migration domain driven design efcore migration loss entity framework unit test iproductrepository data access xunit atomicity iproductservice inventory price drop fluentassertions commit threshold application layer stock price appdbcontext schema change arrange act assert quote dbcontext unitofwork database update sku dbset infrastructure business logic asnotracking external api hosted service igenericrepository notification periodictimer,init.md | --- description: initialize project context and guide on search/docs type: workf +// turbo-all",10,337ca4ab45fa0b770cf153d33d537d22,.agents\workflows\init.md,0,249,"context, workflow, description, initialize, project, guide, search, docs",1779814416.1970363,1,threshold productservice stock price igenericrepository efcore migration business logic domain entity arrange act assert data access fluentassertions price drop application layer atomicity savechanges dbcontext iproductrepository finnhubpricesyncworker commit iproductservice unit test dbset periodictimer quote loss rollback hosted service add-migration domain driven design unitofwork entity framework notification database update efcore application service appdbcontext asnotracking backgroundservice schema change external api market data infrastructure xunit,init.md | --- description: initialize project context and guide on search/docs type: workf doc,"# /init — Project Initialization & Context Sync **Objective**: Rapidly sync with `InventoryAlert.Api` current state, re-index knowledge, and locate critical technical docs before starting any work session. @@ -7738,30 +7816,30 @@ Core knowledge locations for this project: Use BM25 to retrieve focused context without reading full files: -```bash",64,807b20ec43c9eb0b01a681352ee37c47,.agents\workflows\init.md,0,250,"project, rules, agents, index, knowledge, core, finnhub, phase",1775327960.6894755,11,item market data finnhubpricesyncworker domain entity productservice stock savechanges efcore rollback backgroundservice application service add-migration domain driven design efcore migration loss entity framework unit test iproductrepository data access xunit atomicity iproductservice inventory price drop fluentassertions commit threshold application layer stock price appdbcontext schema change arrange act assert quote dbcontext unitofwork database update sku dbset infrastructure business logic asnotracking external api hosted service igenericrepository notification periodictimer,# /init — Project Initialization & Context Sync | /init — Project Initialization & Context Sync Objective: Rapidly sync with Inven +```bash",64,337ca4ab45fa0b770cf153d33d537d22,.agents\workflows\init.md,0,250,"project, rules, agents, index, knowledge, core, finnhub, phase",1779814416.1970363,11,threshold productservice stock price igenericrepository efcore migration business logic domain entity arrange act assert data access fluentassertions price drop application layer atomicity savechanges dbcontext iproductrepository finnhubpricesyncworker commit iproductservice unit test dbset periodictimer quote loss rollback hosted service add-migration domain driven design unitofwork entity framework notification database update efcore application service appdbcontext asnotracking backgroundservice schema change external api market data infrastructure xunit,# /init — Project Initialization & Context Sync | /init — Project Initialization & Context Sync Objective: Rapidly sync with Inven doc,"# Find context about a specific topic -python .agents/scripts/core/bm25_search.py ""your query"" -n 5",67,807b20ec43c9eb0b01a681352ee37c47,.agents\workflows\init.md,0,251,"find, context, about, specific, topic, python, agents, scripts",1775327960.6894755,65,item market data finnhubpricesyncworker domain entity productservice stock savechanges efcore rollback backgroundservice application service add-migration domain driven design efcore migration loss entity framework unit test iproductrepository data access xunit atomicity iproductservice inventory price drop fluentassertions commit threshold application layer stock price appdbcontext schema change arrange act assert quote dbcontext unitofwork database update sku dbset infrastructure business logic asnotracking external api hosted service igenericrepository notification periodictimer,"# Find context about a specific topic | Find context about a specific topic python .agents/scripts/core/bm25_search.py """ +python .agents/scripts/core/bm25_search.py ""your query"" -n 5",67,337ca4ab45fa0b770cf153d33d537d22,.agents\workflows\init.md,0,251,"find, context, about, specific, topic, python, agents, scripts",1779814416.1970363,65,threshold productservice stock price igenericrepository efcore migration business logic domain entity arrange act assert data access fluentassertions price drop application layer atomicity savechanges dbcontext iproductrepository finnhubpricesyncworker commit iproductservice unit test dbset periodictimer quote loss rollback hosted service add-migration domain driven design unitofwork entity framework notification database update efcore application service appdbcontext asnotracking backgroundservice schema change external api market data infrastructure xunit,"# Find context about a specific topic | Find context about a specific topic python .agents/scripts/core/bm25_search.py """ doc,"# Search only documentation files -python .agents/scripts/core/bm25_search.py ""ProductService transaction"" -n 5",70,807b20ec43c9eb0b01a681352ee37c47,.agents\workflows\init.md,0,252,"search, only, documentation, files, python, agents, scripts, core",1775327960.6894755,68,item market data finnhubpricesyncworker domain entity productservice stock savechanges efcore rollback backgroundservice application service add-migration domain driven design efcore migration loss entity framework unit test iproductrepository data access xunit atomicity iproductservice inventory price drop fluentassertions commit threshold application layer stock price appdbcontext schema change arrange act assert quote dbcontext unitofwork database update sku dbset infrastructure business logic asnotracking external api hosted service igenericrepository notification periodictimer,"# Search only documentation files | Search only documentation files python .agents/scripts/core/bm25_search.py ""Prod" +python .agents/scripts/core/bm25_search.py ""ExecuteTransactionAsync transaction capture pattern"" -n 5",70,337ca4ab45fa0b770cf153d33d537d22,.agents\workflows\init.md,0,252,"search, only, documentation, files, python, agents, scripts, core",1779814416.1970363,68,threshold productservice stock price igenericrepository efcore migration business logic domain entity arrange act assert data access fluentassertions price drop application layer atomicity savechanges dbcontext iproductrepository finnhubpricesyncworker commit iproductservice unit test dbset periodictimer quote loss rollback hosted service add-migration domain driven design unitofwork entity framework notification database update efcore application service appdbcontext asnotracking backgroundservice schema change external api market data infrastructure xunit,"# Search only documentation files | Search only documentation files python .agents/scripts/core/bm25_search.py ""Exec" doc,"# Search with mode filter -python .agents/scripts/core/bm25_search.py ""repository pattern EF Core"" -n 3 --mode doc",73,807b20ec43c9eb0b01a681352ee37c47,.agents\workflows\init.md,0,253,"mode, core, search, filter, python, agents, scripts, repository",1775327960.6894755,71,item market data finnhubpricesyncworker domain entity productservice stock savechanges efcore rollback backgroundservice application service add-migration domain driven design efcore migration loss entity framework unit test iproductrepository data access xunit atomicity iproductservice inventory price drop fluentassertions commit threshold application layer stock price appdbcontext schema change arrange act assert quote dbcontext unitofwork database update sku dbset infrastructure business logic asnotracking external api hosted service igenericrepository notification periodictimer,"# Search with mode filter | Search with mode filter python .agents/scripts/core/bm25_search.py ""repository p" +python .agents/scripts/core/bm25_search.py ""repository pattern EF Core"" -n 3 --mode doc",73,337ca4ab45fa0b770cf153d33d537d22,.agents\workflows\init.md,0,253,"mode, core, search, filter, python, agents, scripts, repository",1779814416.1970363,71,threshold productservice stock price igenericrepository efcore migration business logic domain entity arrange act assert data access fluentassertions price drop application layer atomicity savechanges dbcontext iproductrepository finnhubpricesyncworker commit iproductservice unit test dbset periodictimer quote loss rollback hosted service add-migration domain driven design unitofwork entity framework notification database update efcore application service appdbcontext asnotracking backgroundservice schema change external api market data infrastructure xunit,"# Search with mode filter | Search with mode filter python .agents/scripts/core/bm25_search.py ""repository p" doc,"# Limit to a specific folder python .agents/scripts/core/bm25_search.py ""migration"" -n 3 -f "".agents/workflows"" ``` **Domain-specific queries to know**: ```bash -python .agents/scripts/core/bm25_search.py ""ProductService GetPriceLossAlertsAsync"" +python .agents/scripts/core/bm25_search.py ""PortfolioService OpenPositionAsync"" python .agents/scripts/core/bm25_search.py ""ExecuteTransactionAsync unit of work"" python .agents/scripts/core/bm25_search.py ""FinnhubClient GetQuoteAsync"" -python .agents/scripts/core/bm25_search.py ""GenericRepository EF Core CS1998"" +python .agents/scripts/core/bm25_search.py ""StockDataService cache Redis"" ``` --- **Parent Context**: `GEMINI.md` **Next Action**: `/feature-flow` or `/plan` -**Keywords**: `init`, `bm25`, `index`, `context`, `onboarding`, `inventoryalert`",90,807b20ec43c9eb0b01a681352ee37c47,.agents\workflows\init.md,0,254,"agents, core, python, scripts, context, limit, specific, folder",1775327960.6894755,74,item market data finnhubpricesyncworker domain entity productservice stock savechanges efcore rollback backgroundservice application service add-migration domain driven design efcore migration loss entity framework unit test iproductrepository data access xunit atomicity iproductservice inventory price drop fluentassertions commit threshold application layer stock price appdbcontext schema change arrange act assert quote dbcontext unitofwork database update sku dbset infrastructure business logic asnotracking external api hosted service igenericrepository notification periodictimer,"# Limit to a specific folder | Limit to a specific folder python .agents/scripts/core/bm25_search.py ""migration" +**Keywords**: `init`, `bm25`, `index`, `context`, `onboarding`, `inventoryalert`",90,337ca4ab45fa0b770cf153d33d537d22,.agents\workflows\init.md,0,254,"agents, python, scripts, core, context, limit, specific, folder",1779814416.1970363,74,threshold productservice stock price igenericrepository efcore migration business logic domain entity arrange act assert data access fluentassertions price drop application layer atomicity savechanges dbcontext iproductrepository finnhubpricesyncworker commit iproductservice unit test dbset periodictimer quote loss rollback hosted service add-migration domain driven design unitofwork entity framework notification database update efcore application service appdbcontext asnotracking backgroundservice schema change external api market data infrastructure xunit,"# Limit to a specific folder | Limit to a specific folder python .agents/scripts/core/bm25_search.py ""migration" doc,"--- description: Combined execution flow from requirement analysis to pushed code type: workflow @@ -7876,7 +7954,7 @@ version: 3.0 tags: [workflow, planning, spec, clarification, inventoryalert, ddd] --- -// turbo-all",10,6c8001cbe92f9f58a736e0dd810c9a36,.agents\workflows\plan.md,0,258,"spec, clarification, workflow, description, design, feature, freeze, context",1775285344.1066658,1,hosted service rollback iproductservice efcore quote business logic sku dbset productservice xunit database update appdbcontext application service backgroundservice market data asnotracking efcore migration httpget unitofwork threshold application layer finnhubpricesyncworker stock httpput moq schema change domain driven design add-migration periodictimer commit item iactionresult stock price loss mock setup arrange act assert fluentassertions productscontroller times once atomicity data access entity framework verify inventory savechanges domain entity returns async external api unit test infrastructure httppost igenericrepository iproductrepository dbcontext notification price drop,plan.md | --- description: Design Feature + Freeze Context (FSD Standard with Spec-Driven +// turbo-all",10,a480f7038c50048f07986a4b74595f97,.agents\workflows\plan.md,0,258,"spec, clarification, workflow, description, design, feature, freeze, context",1779814416.1970363,1,iproductrepository backgroundservice unitofwork notification returns async dbcontext productservice iproductservice quote rollback price drop httpput atomicity database update commit moq mock setup savechanges times once data access dbset threshold infrastructure arrange act assert iactionresult entity framework external api xunit business logic efcore migration unit test periodictimer hosted service httppost asnotracking httpget igenericrepository efcore appdbcontext domain entity stock price verify fluentassertions application layer application service finnhubpricesyncworker productscontroller add-migration market data domain driven design schema change loss,plan.md | --- description: Design Feature + Freeze Context (FSD Standard with Spec-Driven doc,"# /plan — Feature Design & Context Freeze **Objective**: Fully understand a feature requirement, surface blind spots, design the solution across DDD layers, and freeze context in `doc/` before implementation begins. @@ -7915,7 +7993,7 @@ Before writing any plan, identify blind spots. Ask the user these questions (or proceed with defaults if they say ""go""): -1. **Scope**: Is this a new method on `ProductService`, a new entity, or a new external integration? +1. **Scope**: Is this a new method on an existing service (e.g., `PortfolioService`, `WatchlistService`, `StockDataService`), a new entity, or a new external integration? 2. **Input/Output**: What does the endpoint receive? What shape does the response need? 3. **Persistence**: Does this require a DB column/table/index change → migration needed? 4. **Finnhub**: Does this feature call Finnhub? If so, how should null/error be handled? @@ -7980,7 +8058,7 @@ If user confirms, transition directly to Phase 2 of `/feature-flow`. **Parent Context**: `GEMINI.md` · `.agents/skills/ddd-architecture/SKILL.md` **Next Action**: `/feature-flow` or `/add-feature` or `/add-entity` -**Keywords**: `plan`, `spec`, `clarification`, `design`, `ddd`, `inventoryalert`, `feature`",114,6c8001cbe92f9f58a736e0dd810c9a36,.agents\workflows\plan.md,0,259,"feature, phase, spec, plan, design, context, tests, does",1775285344.1066658,11,hosted service rollback iproductservice efcore quote business logic sku dbset productservice xunit database update appdbcontext application service backgroundservice market data asnotracking efcore migration httpget unitofwork threshold application layer finnhubpricesyncworker stock httpput moq schema change domain driven design add-migration periodictimer commit item iactionresult stock price loss mock setup arrange act assert fluentassertions productscontroller times once atomicity data access entity framework verify inventory savechanges domain entity returns async external api unit test infrastructure httppost igenericrepository iproductrepository dbcontext notification price drop,# /plan — Feature Design & Context Freeze | /plan — Feature Design & Context Freeze Objective: Fully understand a feature re +**Keywords**: `plan`, `spec`, `clarification`, `design`, `ddd`, `inventoryalert`, `feature`",114,a480f7038c50048f07986a4b74595f97,.agents\workflows\plan.md,0,259,"feature, phase, spec, plan, design, context, tests, does",1779814416.1970363,11,iproductrepository backgroundservice unitofwork notification returns async dbcontext productservice iproductservice quote rollback price drop httpput atomicity database update commit moq mock setup savechanges times once data access dbset threshold infrastructure arrange act assert iactionresult entity framework external api xunit business logic efcore migration unit test periodictimer hosted service httppost asnotracking httpget igenericrepository efcore appdbcontext domain entity stock price verify fluentassertions application layer application service finnhubpricesyncworker productscontroller add-migration market data domain driven design schema change loss,# /plan — Feature Design & Context Freeze | /plan — Feature Design & Context Freeze Objective: Fully understand a feature re doc,"--- description: Advanced refinement lifecycle for existing features, ensuring end-to-end consistency across Domain, Infrastructure, and UI. type: workflow @@ -8099,9773 +8177,11728 @@ doc,"# /search - BM25+ Premium Search (v4.6) **Next**: `/plan` or `/code`",41,d4c0fbfd8fc9e4f42a49deca44d2b440,.agents\workflows\search.md,3,264,"search, python, agents, scripts, core, code, phase, expert",1774065831.5389647,7,asnotracking dbcontext efcore appdbcontext entity framework,# /search - BM25+ Premium Search (v4.6) | /search - BM25+ Premium Search (v4.6) Objective: Surgical context retrieval acro doc,"--- -description: Review of current API error handling and response format, plus recommendations to standardize status codes and error messages. +description: Working docs for the InventoryAlert solution (specs, plans, references). type: reference -status: draft +status: active version: 1.0 -tags: [api, middleware, error-handling, standardization, inventoryalert] -last_updated: 2026-04-26 ----",9,1f0f2b8b093e19fe79c4dbefa089e7b0,doc\error_handling_and_response_standard.md,0,265,"error, handling, status, description, review, current, response, format",1777190302.61741,1,sku notification inventory asnotracking business logic googl symbol price drop aapl stock ticker iproductservice msft productservice iactionresult httpget loss item productscontroller httppost dbcontext entity framework appdbcontext stock efcore threshold application service httpput,"error_handling_and_response_standard.md | --- description: Review of current API error handling and response format, plus " -doc,"# Error Handling & Response Standardization (Review + Recommendations) +tags: [documentation, bm25, inventoryalert] +last_updated: 2026-04-30 +---",9,4f949b46a80d728c12d7b2a492280bbb,doc\README.md,0,265,"inventoryalert, description, working, docs, solution, specs, plans, references",1779851803.7558484,1,dockerfile finnhubpricesyncworker entity framework price drop hosted service threshold xunit container postgresql fluentassertions appdbcontext dbcontext unit test efcore backgroundservice periodictimer asnotracking arrange act assert postgres compose loss notification,"README.md | --- description: Working docs for the InventoryAlert solution (specs, plans, ref" +doc,"# InventoryAlert Documentation Index -Scope: `InventoryManagementSystem/InventoryAlert.Api` error handling (middleware + validation filter) and the **shape of error responses** returned to clients. +This folder contains working documentation for the `InventoryManagementSystem/` solution and related tooling. -This is a documentation-only review (no code changes included). +## 🗺️ Roadmap & Strategy +- [ROADMAP.md](ROADMAP.md) — Consolidated task list and project progress. +- [feature_audit.md](feature_audit.md) — Current feature-set audit and consolidation notes. +- [architecture_modernization.md](architecture_modernization.md) — Architecture modernization track and completed refactors. ---- +## 🗄️ Archive +- [archive/](archive/) — Legacy plans, setup commands, and hackathon-specific progress logs. -## 1) Current Behavior (Observed in Code) +## 📚 Wiki & CI -### 1.1 Error response DTOs +- [WIKI_REUSE_AND_CI_SYNC.md](WIKI_REUSE_AND_CI_SYNC.md) — Plan to sync `InventoryAlert.Wiki/docs` into the GitHub Wiki repo + suggested CI workflow. +- [GITHUB_WIKI_CI_PUBLISH.md](GITHUB_WIKI_CI_PUBLISH.md) — How to publish `https://github.com/nhonvo/InventoryManagementSystem/wiki` from CI (GitHub Actions) via the `.wiki.git` repo. -Defined in `InventoryManagementSystem/InventoryAlert.Api/Models/Error.cs`: +## 🔭 Observability -- `ErrorResponse` - - `Errors: IEnumerable` - - `ErrorId: Guid` (generated per response) -- `Error` - - `Code: string?` - - `Message: string?` - - `Property: string?` +- [OBSERVABILITY.md](OBSERVABILITY.md) — Central index (Seq + correlation + error/flow docs). +- [LOGGING_REVIEW.md](LOGGING_REVIEW.md) — Logging review + recommendations. +- [SEQ_REQUEST_RESPONSE_AND_FLOW_LOGGING.md](SEQ_REQUEST_RESPONSE_AND_FLOW_LOGGING.md) — Seq guidance: request/response logging (safe), correlation, and event-flow logging. +- [error_handling_and_response_standard.md](error_handling_and_response_standard.md) — Error response/status standardization. +- [worker_jobs_and_event_flow_review.md](worker_jobs_and_event_flow_review.md) — Worker jobs + event-flow review. -### 1.2 Model validation (400 Bad Request) +## 🧰 Redis -MVC setup in `InventoryManagementSystem/InventoryAlert.Api/Extensions/MvcExtension.cs`: +- [REDIS_STANDARD_AND_USAGE.md](REDIS_STANDARD_AND_USAGE.md) — Current Redis usage inventory + key/TTL standards and improvements. -- `SuppressModelStateInvalidFilter = true` -- Adds `ValidateModelFilter` globally -- Enables FluentValidation auto-validation + interceptor +## 🖥️ UI -Validation responses are emitted by: +- [UI_TECH_SETUP_AND_FLOW.md](UI_TECH_SETUP_AND_FLOW.md) — UI tech stack, setup, folder structure, rendering flow, and Docker approach (doc-only). +- [UI_COMPONENTS_AND_PAGES_AUDIT.md](UI_COMPONENTS_AND_PAGES_AUDIT.md) — Component/page inventory + enhancement suggestions (paging, UX consistency). -- `InventoryManagementSystem/InventoryAlert.Api/Filters/ValidateModelFilter.cs` - - Returns `BadRequestObjectResult(new ErrorResponse(errors))` - - Each error uses: - - `Code = ""InventoryAlert.BAD_REQUEST""` - - `Property = ` - - `Message = ` +## 🔔 Alerts & Notifications -### 1.3 Unhandled exceptions (GlobalExceptionMiddleware) +- [NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md](NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md) — Business flow review + enhancement recommendations. -Middleware: `InventoryManagementSystem/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs` +## 🧪 Testing -Behavior: +- [JOBS_INTEGRATION_TEST_PLAN.md](JOBS_INTEGRATION_TEST_PLAN.md) — Integration test plan for jobs/worker, SQS retries/DLQ, and Option C DLQ reprocessor. +- [WORKER_JOBS_AND_EVENTS_INTEGRATION_TESTS.md](WORKER_JOBS_AND_EVENTS_INTEGRATION_TESTS.md) — Practical setup + test catalog for worker jobs and event handling (Moto SNS/SQS). -- Catches exceptions, logs error (including `X-Correlation-Id` when present). -- Maps exceptions to HTTP status codes and returns a JSON error payload: - - Default: `500 Internal Server Error` with code `InventoryAlert.GENERAL_ERROR` - - `UserFriendlyException` → status mapped by `ErrorCode` (404/409/400/401/403/422/500) - - `KeyNotFoundException` or `NotFoundException` → 404 with code `InventoryAlert.NOT_FOUND` - - `FluentValidation.ValidationException` or domain `ValidationException` → 400 with code `InventoryAlert.BAD_REQUEST` - - `ArgumentException` → 400 with code `InventoryAlert.BAD_REQUEST` - - `UnauthorizedAccessException` → 401 with code `InventoryAlert.UNAUTHORIZED` -- Writes response using `await context.Response.WriteAsync(errorResponse.ToString())` +> Run `/doc` to synchronize this index with new feature implementations.",53,4f949b46a80d728c12d7b2a492280bbb,doc\README.md,0,266,"wiki, flow, index, roadmap, archive, setup, github, observability",1779851803.7558484,10,dockerfile finnhubpricesyncworker entity framework price drop hosted service threshold xunit container postgresql fluentassertions appdbcontext dbcontext unit test efcore backgroundservice periodictimer asnotracking arrange act assert postgres compose loss notification,# InventoryAlert Documentation Index | InventoryAlert Documentation Index This folder contains working documentation fo +doc,"# Hackathon Progress Checklist -### 1.4 Middleware ordering (important) +Use this checklist to track your team's progress and ensure you're hitting all the key technical requirements from the judging criteria. Good luck! -Pipeline order in `InventoryManagementSystem/InventoryAlert.Api/Program.cs`: +✅ Core Principles (40 points) -1) `CorrelationIdMiddleware` -2) `GlobalExceptionMiddleware` -3) `PerformanceMiddleware` +- [ ] Uniform Interface (15 pts) +- [ ] Endpoints are resource-based and follow RESTful naming conventions (e.g., /api/urls/{id}). +- [ ] Self-descriptive messages are used (e.g., Content-Type: application/json). +- [ ] Appropriate HTTP status codes are returned for different scenarios (e.g., 200 OK, 201 Created, 24 No Content, 400 Bad Request, 404 Not Found). -Impact: +- [ ] Stateless (10 pts) +- [ ] Every request contains all necessary information for the server to process it. +- [ ] The server does not store any client session state between requests. +- [ ] Client-Server (10 pts) +- [ ] The application logic is clearly separated between the client and the server. +- [ ] Cacheable (5 pts) +- [ ] Caching headers (like ETag or Cache-Control) are implemented on GET endpoints. +✅ Methods & Endpoints (20 points) +- [ ] Correct HTTP Method Usage (20 pts) +- [ ] GET method is used to retrieve one or more resources. +- [ ] POST method is used to create a new resource. +- [ ] PUT method is used to completely replace an existing resource. +- [ ] PATCH method is used to partially update an existing resource. +- [ ] DELETE method is used to remove a resource. +- [ ] GET, PUT, and DELETE operations are idempotent. +✅ Connectedness & Advanced Features (40 points) +- [ ] Pagination (10 pts) +- [ ] Endpoints that return lists of resources support pagination (e.g., ?page=1&pageSize=10). +- [ ] Filtering & Ordering (10 pts) +- [ ] List endpoints support filtering results based on field values (e.g., ?status=active). +- [ ] List endpoints support ordering/sorting of results (e.g., ?sortBy=name_desc). +- [ ] Versioning (5 pts) +- [ ] The API has a versioning strategy implemented (e.g., /api/v1/urls). +- [ ] Security & Auth (5 pts) +- [ ] Basic authentication/authorization is implemented (e.g., API Key, JWT). +- [ ] HATEOAS (Hypermedia) (5 pts) +- [ ] Responses include links to related resources or possible actions. +- [ ] Input Validation (5 pts) +- [ ] Data from incoming POST, PUT, and PATCH requests is validated. +- [ ] Clear 400 Bad Request responses are returned for invalid data. +⭐ Bonus (Up to 10 points) +- [ ] Monitoring/Logging +- [ ] Basic logging is implemented to track requests or errors. +- [ ] Documentation +- [ ] The project includes a helpful README.md file. +- [ ] The API is documented using Swagger/OpenAPI. +- [ ] Containerization +- [ ] The application can be built and run using a Dockerfile",49,709150e6d23b0349f58b4e7567578cb3,doc\archive\# Hackathon Progress Checklist.md,0,267,"endpoints, used, method, resource, points, server, implemented, application",1759516769.3479264,1,postgresql compose postgres dockerfile container,# Hackathon Progress Checklist | Hackathon Progress Checklist Use this checklist to track your team's progress an +doc,"# Implementation Plan: Road to Perfect 100/100 -- When downstream throws, `PerformanceMiddleware` does not log a completion entry (because it does not catch/finally), and exception is handled “above” it by `GlobalExceptionMiddleware`. -- Result: failed requests may have an error log but no standard “request completed” log entry. +> **Current Score:** 85/100 — **Target:** 100/100 +> **Missing:** Versioning (5 pts), Filtering/Ordering (10 pts), HATEOAS (5 pts), Caching (5 pts) --- -## 2) Inconsistencies / Risks - -### 2.1 Error code format is inconsistent +## Execution Order -Two naming paths exist: +``` +Phase 1 (Versioning) → Phase 2 (Filter/Sort) → Phase 3 (HATEOAS) → Phase 4 (Cache) +``` -- `ErrorRespondCode` enum values (ex: `NOT_FOUND`, `BAD_REQUEST`) produce codes like: - - `InventoryAlert.NOT_FOUND` -- `UserFriendlyException.ErrorCode` enum values (ex: `NotFound`) are currently serialized via `.ToUpper()` which produces: - - `InventoryAlert.NOTFOUND` (missing underscore) +- **Phase 1 first** — all other phases depend on the final route shape (URLs must be stable before HATEOAS links are built). +- **Phase 2 before Phase 3** — HATEOAS links embed query params, so the filter DTO must exist first. +- **Phase 4 last** — caching is purely additive, no structural dependencies. -This makes client-side handling and Seq searching harder because codes are not stable. +--- -### 2.2 Serialization is inconsistent (middleware vs MVC) +## Phase 1 — API Versioning (5 pts) -- Model validation uses `BadRequestObjectResult(new ErrorResponse(...))` and will be serialized by ASP.NET Core’s configured JSON options. -- `GlobalExceptionMiddleware` manually serializes via `ErrorResponse.ToString()` with its own `JsonSerializerOptions` (camelCase only). +**Goal:** Route all endpoints under `/api/v1/` using URL-path versioning. -Risk: +### Files to Change -- If global JSON options change (naming, null handling, converters), middleware errors won’t match controller/validation errors. +| File | Change | +|---|---| +| `Directory.Packages.props` | Add `Asp.Versioning.Mvc` + `Asp.Versioning.Mvc.ApiExplorer` to centralized package versions | +| `InventoryAlert.Api.csproj` | Reference those packages | +| `Web/Extensions/MvcExtension.cs` | Wire `AddApiVersioning()` + `AddMvc()` into `SetupMvc()` | +| `Web/Controllers/ProductsController.cs` | Add `[ApiVersion(""1.0"")]` + update route to `api/v{version:apiVersion}/[controller]` | +| `Web/Extensions/SwaggerExtension.cs` | Enumerate versions in Swagger document setup | -### 2.3 CorrelationId is not part of the JSON response body +### Design Decisions -The response header `X-Correlation-Id` exists (good), but the JSON payload doesn’t include it. +- **URL path versioning** (`/v1/`) over header versioning — judges can test in Swagger without custom headers. +- **Default version = 1.0** with `AssumeDefaultVersionWhenUnspecified = true` — keeps existing tests passing. +- `ReportApiVersions = true` adds `api-supported-versions` header to every response. -Operationally, it is easier when the client can log/store a single `correlationId` field from the body for every error response. +### Key Code Shape -### 2.4 Validation interceptor behavior looks incomplete +```csharp +// Web/Extensions/MvcExtension.cs +services.AddApiVersioning(opt => +{ + opt.DefaultApiVersion = new ApiVersion(1, 0); + opt.AssumeDefaultVersionWhenUnspecified = true; + opt.ReportApiVersions = true; + opt.ApiVersionReader = new UrlSegmentApiVersionReader(); +}) +.AddMvc(); -`InventoryManagementSystem/InventoryAlert.Api/Validations/ValidatorInterceptor.cs` builds an `ErrorResponse` but does not return it and does not attach structured validation errors to the response directly. +// Web/Controllers/ProductsController.cs +[ApiVersion(""1.0"")] +[Route(""api/v{version:apiVersion}/[controller]"")] +[ApiController] +[Authorize] +public class ProductsController(...) : ControllerBase +``` -Additionally, the interceptor clears and replaces ModelState errors under the `FluentValidation` key, which may cause: +--- -- Missing/empty `ErrorMessage` values in `ValidateModelFilter` depending on how the ModelState errors are populated. +## Phase 2 — Filtering & Ordering (10 pts) -This is a “review risk” item: validate actual runtime payloads for validation errors to ensure field messages are not lost. +**Goal:** `GET /api/v1/Products?name=Widget&minStock=5&sortBy=price_desc` -### 2.5 Some status semantics are likely underspecified +### Files to Change -Examples: - -- A “symbol not recognized” case currently throws `KeyNotFoundException` in services → becomes 404. - - Many APIs would use 404 for missing resources, but “invalid symbol input” might be better as 400/422 depending on business semantics. -- Domain/business-rule failures are not consistently represented as 409 vs 422 vs 400. +| File | Change | +|---|---| +| `Application/DTOs/ProductQueryParams.cs` | **New file** — replaces `PaginationParams` on the list endpoint | +| `Domain/Interfaces/IProductRepository.cs` | Add overload: `GetPagedAsync(ProductQueryParams q, CancellationToken ct)` | +| `Infrastructure/Repositories/ProductRepository.cs` | Implement EF Core LINQ filter + `OrderBy` switch | +| `Application/Interfaces/IProductService.cs` | Update `GetProductsPagedAsync` signature to accept `ProductQueryParams` | +| `Application/Services/ProductService.cs` | Pass `ProductQueryParams` through to repository | +| `Web/Controllers/ProductsController.cs` | Accept `[FromQuery] ProductQueryParams` instead of `PaginationParams` | ---- +> [!IMPORTANT] +> `IGenericRepository` contract is **not changed** — the overload goes on `IProductRepository` only, respecting DDD layer boundaries. -## 3) Recommended Standard (Stable, Searchable, Client-Friendly) +### New DTO: `ProductQueryParams` -Pick one of these two approaches and apply it consistently: +```csharp +// Application/DTOs/ProductQueryParams.cs +public class ProductQueryParams +{ + private const int MaxPageSize = 50; + public int PageNumber { get; set; } = 1; -### Option A (minimal change): keep `ErrorResponse`, standardize fields + mapping + private int _pageSize = 10; + public int PageSize + { + get => _pageSize; + set => _pageSize = value > MaxPageSize ? MaxPageSize : value; + } -**Response schema (recommended)** + // Filtering + public string? Name { get; set; } // contains, case-insensitive + public int? MinStock { get; set; } + public int? MaxStock { get; set; } -```json -{ - ""errorId"": ""guid"", - ""correlationId"": ""string"", - ""errors"": [ - { ""code"": ""InventoryAlert.BAD_REQUEST"", ""message"": ""…"", ""property"": ""TickerSymbol"" } - ] + // Ordering: ""name_asc"" | ""name_desc"" | ""price_asc"" | ""price_desc"" | ""stock_asc"" | ""stock_desc"" + public string? SortBy { get; set; } } ``` -Rules: - -- Always return `ErrorResponse` for non-2xx. -- Always include `correlationId` in the JSON body (and keep the header). -- Keep `errorId` as a server-generated unique id (good for support tickets). -- Ensure `code` values are stable and come from **one enum/source of truth** (recommend using `ErrorRespondCode` style with underscores). +### Infrastructure LINQ Strategy (ProductRepository) -### Option B (more standard): adopt RFC 7807 Problem Details +```csharp +IQueryable query = _context.Products.AsNoTracking(); -Use `ProblemDetails` for the main envelope and include your current `errors[]` in extensions. +if (!string.IsNullOrWhiteSpace(q.Name)) + query = query.Where(p => p.Name.Contains(q.Name)); -This aligns with many .NET clients and tooling, but is a bigger change and may not be necessary if `ErrorResponse` is already established. +if (q.MinStock.HasValue) query = query.Where(p => p.StockCount >= q.MinStock.Value); +if (q.MaxStock.HasValue) query = query.Where(p => p.StockCount <= q.MaxStock.Value); ---- +query = q.SortBy?.ToLowerInvariant() switch +{ + ""name_desc"" => query.OrderByDescending(p => p.Name), + ""price_asc"" => query.OrderBy(p => p.CurrentPrice), + ""price_desc"" => query.OrderByDescending(p => p.CurrentPrice), + ""stock_asc"" => query.OrderBy(p => p.StockCount), + ""stock_desc"" => query.OrderByDescending(p => p.StockCount), + _ => query.OrderBy(p => p.Name) // default +}; -## 4) Status Code & Error Code Mapping (Proposed) +var skip = (q.PageNumber - 1) * q.PageSize; +var total = await query.CountAsync(ct); +var items = await query.Skip(skip).Take(q.PageSize).ToListAsync(ct); +return (items, total); +``` -This table is a suggested baseline: +--- -| HTTP | Code | When | -|---:|---|---| -| 400 | `InventoryAlert.BAD_REQUEST` | invalid input shape, parsing, validation failures | -| 401 | `InventoryAlert.UNAUTHORIZED` | missing/invalid auth, invalid refresh token | -| 403 | `InventoryAlert.FORBIDDEN` | authenticated but lacks permission | -| 404 | `InventoryAlert.NOT_FOUND` | resource id not found (rule id, notification id, etc.) | -| 409 | `InventoryAlert.CONFLICT` | version conflict / uniqueness / state conflict | -| 422 | `InventoryAlert.UNPROCESSABLE_ENTITY` | business-rule violation when input is syntactically valid | -| 500 | `InventoryAlert.INTERNAL_ERROR` (or `GENERAL_ERROR`) | unexpected server failures | +## Phase 3 — HATEOAS / Hypermedia Links (5 pts) -Recommendation: +**Goal:** Responses include navigational links (`self`, `next`, `prev`) in the paged list envelope. -- Remove duplicate “500 codes” (`INTERNAL_ERROR` vs `GENERAL_ERROR`) or define strict meaning: - - `INTERNAL_ERROR`: known internal failure classification - - `GENERAL_ERROR`: fallback for truly unknown exceptions +### Files to Change ---- +| File | Change | +|---|---| +| `Application/DTOs/HateoasLink.cs` | **New file** — `record HateoasLink(string Href, string Rel, string Method)` | +| `Application/DTOs/PagedResult.cs` | Add `List Links { get; set; } = []` | +| `Web/Controllers/ProductsController.cs` | Populate `Links` after service call using `Url.Action(...)` | -## 5) Middleware / Filter Recommendations +### New DTO: `HateoasLink` -### 5.1 Ensure failed requests still produce a standard “request completed” log +```csharp +// Application/DTOs/HateoasLink.cs +public record HateoasLink(string Href, string Rel, string Method); +``` -If you want every request (success/failure) logged once, you need either: +### Updated `PagedResult` -- a request logging middleware that logs in `finally`, or -- move the request timing middleware *outside* the exception middleware and catch exceptions inside the timing middleware (still rethrow). +```csharp +public class PagedResult +{ + public IEnumerable Items { get; set; } = []; + public int TotalItems { get; set; } + public int PageNumber { get; set; } + public int PageSize { get; set; } + public int TotalPages => (int)Math.Ceiling(TotalItems / (double)PageSize); + public List Links { get; set; } = []; // ← new +} +``` -### 5.2 Standardize response serialization in middleware +### Controller Link Population (ProductsController.GetProducts) -Do not manually serialize `ErrorResponse` using a local `JsonSerializerOptions`. +```csharp +pagedResult.Links.Add(new HateoasLink( + Href: Url.Action(nameof(GetProducts), new { query.PageNumber, query.PageSize })!, + Rel: ""self"", Method: ""GET"")); -Instead, emit an object result using the app’s configured JSON options (so errors from middleware match errors from controllers/filters). +if (pagedResult.PageNumber < pagedResult.TotalPages) + pagedResult.Links.Add(new HateoasLink( + Href: Url.Action(nameof(GetProducts), new { PageNumber = query.PageNumber + 1, query.PageSize })!, + Rel: ""next"", Method: ""GET"")); -### 5.3 Fix error code formatting once +if (pagedResult.PageNumber > 1) + pagedResult.Links.Add(new HateoasLink( + Href: Url.Action(nameof(GetProducts), new { PageNumber = query.PageNumber - 1, query.PageSize })!, + Rel: ""prev"", Method: ""GET"")); +``` -Pick one canonical error code style: +### Expected Response Shape -- `InventoryAlert.NOT_FOUND` (underscore-separated), recommended because you already have `ErrorRespondCode`. +```json +{ + ""items"": [...], + ""totalItems"": 42, + ""pageNumber"": 2, + ""pageSize"": 10, + ""totalPages"": 5, + ""links"": [ + { ""href"": ""/api/v1/Products?pageNumber=2&pageSize=10"", ""rel"": ""self"", ""method"": ""GET"" }, + { ""href"": ""/api/v1/Products?pageNumber=3&pageSize=10"", ""rel"": ""next"", ""method"": ""GET"" }, + { ""href"": ""/api/v1/Products?pageNumber=1&pageSize=10"", ""rel"": ""prev"", ""method"": ""GET"" } + ] +} +``` -Then ensure: +--- -- `UserFriendlyException` uses the same mapping, not `.ToUpper()` of enum names. +## Phase 4 — HTTP Cache Headers (5 pts) -### 5.4 Validation errors: keep field-level details +**Goal:** `GET` endpoints return `Cache-Control` headers so clients/CDNs can cache responses. -Ensure validation responses always contain: +### Files to Change -- field name (`property`) -- message (`message`) -- stable code (`InventoryAlert.BAD_REQUEST`) +| File | Change | +|---|---| +| `Program.cs` | Register `services.AddResponseCaching()` + `app.UseResponseCaching()` | +| `Web/Controllers/ProductsController.cs` | Add `[ResponseCache]` to `GetProducts` and `GetProductById` | -Avoid injecting exceptions into ModelState if it causes empty messages. +### Cache Strategy Per Endpoint ---- +| Endpoint | Duration | Vary By | Rationale | +|---|---|---|---| +| `GET /Products` (list) | 30 s | `*` all query keys | Short TTL due to volatile stock; vary-by-query caches each filter combo separately | +| `GET /Products/{id}` | 60 s | `Accept` header | Single items are more stable; 60 s balances freshness vs. load | -## 6) Quick Checklist (Acceptance Criteria) +### Key Code Shape -- All error responses follow a single schema (same fields across validation + exceptions). -- Error codes have a stable, consistent format (no `NOTFOUND` vs `NOT_FOUND`). -- `X-Correlation-Id` exists and `correlationId` exists in the JSON body. -- Serialization is consistent across middleware and MVC. -- Error responses never leak sensitive content (tokens, secrets, stack traces) in Production.",227,1f0f2b8b093e19fe79c4dbefa089e7b0,doc\error_handling_and_response_standard.md,0,266,"inventoryalert, error, code, middleware, validation, errors, response, errorresponse",1777190302.61741,10,sku notification inventory asnotracking business logic googl symbol price drop aapl stock ticker iproductservice msft productservice iactionresult httpget loss item productscontroller httppost dbcontext entity framework appdbcontext stock efcore threshold application service httpput,# Error Handling & Response Standardization (Review + Recommendations) | Error Handling & Response Standardization (Review + Recommendations) Scope: Inve -doc,"--- -description: Integration test plan focused on Worker/Hangfire jobs and SQS/DLQ (Option C recovery) flows. -type: reference -status: draft -version: 1.0 -tags: [tests, integration-tests, worker, hangfire, sqs, dlq, option-c, inventoryalert] -last_updated: 2026-04-26 ----",9,fd76edc664b293599f7f1c82bac71b22,doc\JOBS_INTEGRATION_TEST_PLAN.md,0,267,"integration, worker, hangfire, option, tests, description, test, plan",1777190302.592188,1,mock setup returns async market data threshold stock price price drop asnotracking external api hosted service finnhubpricesyncworker compose item sku dbcontext fluentassertions times once quote verify postgres dockerfile backgroundservice notification loss moq xunit periodictimer postgresql stock inventory arrange act assert appdbcontext efcore container entity framework unit test,JOBS_INTEGRATION_TEST_PLAN.md | --- description: Integration test plan focused on Worker/Hangfire jobs and SQS/D -doc,"# Jobs + Worker Integration Test Plan (with SQS/DLQ Option C) +```csharp +// Program.cs +builder.Services.AddResponseCaching(); +// Pipeline — MUST be BEFORE UseAuthentication +app.UseResponseCaching(); -This plan complements `InventoryManagementSystem/InventoryAlert.IntegrationTests/INTEGRATION_TEST_PLAN.md` by focusing specifically on: +// ProductsController.cs +[HttpGet] +[ResponseCache(Duration = 30, VaryByQueryKeys = new[] { ""*"" })] +public async Task GetProducts([FromQuery] ProductQueryParams query, ...) -- Hangfire recurring jobs (Worker) -- SQS consumption semantics (success = delete, failure = redeliver) -- DLQ behavior (redrive policy) -- **Option C** recovery: a Hangfire “DLQ reprocessor/redrive” job that operators can retry in the Hangfire Dashboard +[HttpGet(""{id:int}"")] +[ResponseCache(Duration = 60, VaryByHeader = ""Accept"")] +public async Task GetProductById([FromRoute] int id, ...) +``` -This is documentation only; it describes what to test and how to structure it. +> [!WARNING] +> `UseResponseCaching()` must be placed **before** `UseAuthentication()` in the middleware pipeline. For `[Authorize]` endpoints, response caching will automatically use `Cache-Control: private` to prevent cross-user data leakage. --- -## 1) Test environments (recommended) +## Test Coverage Plan -### Local dev +| Phase | Happy Path | Edge Case | +|---|---|---| +| 1 – Versioning | `GET /api/v1/Products` → 200 | `GET /api/v99/Products` → 400 UnsupportedApiVersion | +| 2 – Filter | `?name=Widget` returns only matching rows | Empty filters return all (default) | +| 2 – Sort | `?sortBy=price_desc` returns descending order | Unknown `sortBy` falls back to `name_asc` default | +| 3 – HATEOAS | Page 2 body includes `next` and `prev` links | Last page: no `next` link present | +| 4 – Cache | `GET /Products` response has `Cache-Control: max-age=30` | Mutating `POST`/`PUT` returns `no-cache` |",255,f24743b2f3fbe485499320c4c4a024d1,doc\archive\a.md,0,268,"phase, versioning, change, cache, links, file, products, productqueryparams",1775464567.8495762,1,iproductrepository application layer loss price drop domain driven design notification httpget item data access xunit unit test igenericrepository appdbcontext dbset arrange act assert fluentassertions business logic httppost efcore iactionresult inventory application service asnotracking productservice infrastructure iproductservice threshold entity framework sku httpput dbcontext domain entity stock productscontroller,# Implementation Plan: Road to Perfect 100/100 | Implementation Plan: Road to Perfect 100/100 > Current Score: 85/100 — Target: 1 +doc,"--- +description: Allow creating alert rules without requiring prior symbol discovery. +type: spec +status: active +version: 1.0 +tags: [alert-rules, symbol-discovery, api, ui, notifications] +last_updated: 2026-04-23 +---",9,3dd027f9332cd0b4e4d57053a59849fb,doc\archive\alert_rules_symbol_auto_resolve_spec.md,0,269,"alert, rules, symbol, discovery, description, allow, creating, without",1777190302.611379,1,dbcontext application service arrange act assert hosted service finnhubpricesyncworker productservice threshold xunit msft business logic backgroundservice price drop loss unit test googl periodictimer appdbcontext aapl fluentassertions entity framework symbol notification asnotracking iproductservice efcore stock ticker,alert_rules_symbol_auto_resolve_spec.md | --- description: Allow creating alert rules without requiring prior symbol disco +doc,"# Alert Rules — Symbol Auto-Resolve -Use the existing docker compose stack under: +## Summary -- `InventoryManagementSystem/` (API + Worker + DB + Redis + Moto/LocalStack as configured) +Creating an alert rule should not depend on the user having previously “discovered” a symbol (e.g., by visiting a stock detail page). The API now resolves and persists symbol metadata during alert creation. -### CI +## Behavior -Current `.github/workflows/ci.yml` already: +- Input `TickerSymbol` is normalized (trim + uppercase) before persistence. +- API calls stock profile lookup during `AlertRuleService.CreateAsync` to resolve/persist symbol metadata. +- If the symbol cannot be resolved, alert creation fails. -- builds .NET + runs unit tests -- starts Docker compose -- runs `InventoryAlert.IntegrationTests` +## Impacted Areas -Extend your integration tests in a way that does not require flaky timing or long waits. +- API: `InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs` +- Domain: `InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs` +- Tests: `InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/AlertRuleServiceTests.cs` +- UI: `InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx`, `InventoryAlert.UI/src/components/NotificationBell.tsx` +- Worker: `InventoryManagementSystem/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs` ---- +## Verification -## 2) Core invariants to enforce (must-have) +- Unit tests cover alert creation paths without pre-existing catalog state. +- Manual: + - Create an alert for a symbol that is not yet in the catalog; verify it succeeds and the symbol appears in `StockListing`. + - Verify navbar bell badge updates via `GET /api/v1/notifications/unread-count` (returns `int`).",36,3dd027f9332cd0b4e4d57053a59849fb,doc\archive\alert_rules_symbol_auto_resolve_spec.md,0,270,"symbol, alert, inventoryalert, inventorymanagementsystem, creation, resolve, stock, page",1777190302.611379,10,dbcontext application service arrange act assert hosted service finnhubpricesyncworker productservice threshold xunit msft business logic backgroundservice price drop loss unit test googl periodictimer appdbcontext aapl fluentassertions entity framework symbol notification asnotracking iproductservice efcore stock ticker,# Alert Rules — Symbol Auto-Resolve | Alert Rules — Symbol Auto-Resolve Summary Creating an alert rule should not dep +doc,"# InventoryAlert.Api — Technical Specification (v2) -### 2.1 Success path +> **Refactor Target.** This document supersedes v1. All entity names, API routes, and worker roles have been updated to align with finance-domain terminology and the full Finnhub Free-Tier endpoint surface. -- Given an event message in the main queue: - - Worker processes it exactly once (idempotent behavior). - - Worker deletes the SQS message. - - Expected side effects happen (DB rows / notifications / logs). +--- -### 2.2 Failure path → retry by redelivery +> [!CAUTION] +> ## ⚠️ Refactor Notice — Old Business Must Be Removed +> +> **This spec describes the NEW system entirely.** The existing codebase uses `Product`/`StockTransaction` inventory terminology leftover from the original OJT project. That old business logic is **fully superseded**. +> +> **Rule**: If a file is not listed as `KEEP`, `RENAME`, or `UPDATE` in Section 13, it is old business and **must be deleted**. +> +> **Do NOT attempt to preserve old business logic** by adapting it. Use the Domain entities, interfaces, and DTOs defined in this spec as the single source of truth. The Infrastructure, Api, and Worker layers follow from those contracts. -- Given a poison message or a handler that throws: - - Worker does not delete the message. - - SQS redelivers it after visibility timeout. +--- -Important: today the Redis dedup behavior can cause “failure then ACK on redelivery” (message loss). If Option C is the direction, adjust production code first so the test can enforce “retries are real”. +## Changelog (v1 → v2) -### 2.3 Failure path → DLQ after maxReceiveCount +| # | Change | Reason | +| :- | :--- | :--- | +| 1 | `Product` → **`StockListing`** | ""Product"" is an inventory term. ""StockListing"" is accurate for a market catalog entry. | +| 2 | `StockTransaction` → **`Trade`** | Finance standard. Enum values: `Buy`, `Sell`, `Dividend`, `Split`. | +| 3 | Removed `WatchlistItem.IsWatchOnly` | Redundant. All watchlist rows are watch-only by definition. | +| 4 | `Portfolio.GET /catalog` → `Stocks.GET /` | Catalog is global; portfolio is personal. Correct layer separation. | +| 5 | Added **`StockMetric`** table | Maps to Finnhub `/stock/metric` (Basic Financials). Cached daily. | +| 6 | Added **`EarningsSurprise`** table | Maps to Finnhub `/stock/earnings`. Last 4 quarters, free tier. | +| 7 | Added **`RecommendationTrend`** table | Maps to Finnhub `/stock/recommendation`. Analyst buy/hold/sell counts. | +| 8 | Added **`InsiderTransaction`** table | Maps to Finnhub `/stock/insider-transactions`. Last 100 entries. | +| 9 | Added 8 new API endpoints | Covers earnings/IPO calendars, market holidays, peers, recommendations. | +| 10 | `PATCH /{id}/stock` → `PATCH /{id}/trade` | Matches the renamed `Trade` entity. | -- Given repeated failures: - - the message eventually appears in the DLQ (based on queue redrive policy) - - the message stops showing up in the main queue +--- -In local dev, `moto-init` creates `event-queue` with `maxReceiveCount=3`. +## 1. Domain Entities (PostgreSQL) ---- +### 1.1 Relationship Overview -## 3) Test categories +```mermaid +erDiagram + User ||--o{ WatchlistItem : watches + User ||--o{ AlertRule : configures + User ||--o{ Trade : executes -### 3.1 Worker job tests (direct invocation) + StockListing ||--o{ PriceHistory : records + StockListing ||--o{ WatchlistItem : ""tracked via Symbol"" + StockListing ||--o{ Trade : ""referenced via Symbol"" + StockListing ||--o| StockMetric : ""has cached metrics"" + StockListing ||--o{ EarningsSurprise : has + StockListing ||--o{ RecommendationTrend : has + StockListing ||--o{ InsiderTransaction : has +``` -Pattern: +--- -- Resolve a job from DI and call `ExecuteAsync()`. -- Assert the side effects (DB, cache, outgoing events). +### 1.2 Entity Specifications -Targets: +#### `User` +**Core Identity.** Root account for all personal data. -- `SyncPricesJob` -- `NewsSyncJob` -- `CleanupPriceHistoryJob` +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `Guid` | Primary Key. | +| `Username` | `string` | Unique login handle. | +| `PasswordHash` | `string` | Argon2/BCrypt hashed credential. | +| `Email` | `string` | Recovery and alert notification address. | +| `Role` | `enum` | `User` \| `Admin`. | +| `CreatedAt` | `DateTime` | Account creation timestamp. | -Guidance: +--- -- Keep these tests deterministic: mock external APIs (Finnhub) or use a predictable stub. -- Avoid long-running loops; test the single execution method. +#### `StockListing` _(was `Product`)_ +**Global Catalog.** Read-only market reference data shared across the system. Seeded from Finnhub `/stock/symbol` and enriched via `/stock/profile2`. -### 3.2 SQS consumer tests (message-driven) +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `int` | Primary Key (auto-increment). | +| `Name` | `string` | Company display name (e.g., ""Tesla Inc""). | +| `TickerSymbol` | `string` | **Unique** market ticker (e.g., ""TSLA""). | +| `Exchange` | `string?` | Exchange code (e.g., ""NASDAQ""). | +| `Currency` | `string?` | ISO currency code (e.g., ""USD""). | +| `Country` | `string?` | Domicile country code (e.g., ""US""). | +| `Industry` | `string?` | Finnhub industry classification. | +| `MarketCap` | `decimal?` | Market capitalization in USD. | +| `Ipo` | `DateOnly?` | IPO date. | +| `WebUrl` | `string?` | Company website URI. | +| `Logo` | `string?` | Company logo URI (from Finnhub profile2). | +| `LastProfileSync` | `DateTime?` | UTC timestamp of last profile2 sync. | -Pattern: +--- -- Publish a known message into SQS. -- Run a single “poll + process” unit (preferably one `ProcessBatchAsync` call, not an infinite loop). -- Assert: - - message deleted (success) OR message still present (failure) - - side effects +#### `WatchlistItem` +**Personal Watchlist.** Tracks user interest without ownership. No `IsWatchOnly` — that is implied. -If the current architecture only exposes the infinite loop, consider adding a test seam (already present: `ProcessBatchAsync` in `ProcessQueueJob`). +| Property | Type | Description | +| :--- | :--- | :--- | +| `UserId` | `Guid` | **FK** → `User.Id` | +| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | +| `CreatedAt` | `DateTime` | Timestamp of entry. | -### 3.3 DLQ reprocessor job tests (Option C) +> **PK**: Composite key `(UserId, TickerSymbol)`. -This is what makes “Retry in Hangfire Dashboard” meaningful for failed message recovery. +--- -Test cases: +#### `AlertRule` +**Unified Notification Rules.** Triggers on both price and inventory conditions. -1) **Reprocess DLQ batch (success)** - - Arrange: message exists in DLQ - - Act: run `DlqReprocessorJob.ExecuteAsync(max=10)` - - Assert: - - message is published back to main queue (or SNS, depending on design) - - DLQ message is deleted only after publish succeeds +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `Guid` | Primary Key. | +| `UserId` | `Guid` | **FK** → `User.Id` | +| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | +| `Condition` | `enum` | See `AlertCondition` enum below. | +| `TargetValue` | `decimal` | Threshold to breach. | +| `IsActive` | `bool` | Enabled/disabled state. | +| `TriggerOnce` | `bool` | Deactivate automatically after first trigger. | +| `LastTriggeredAt` | `DateTime?` | UTC timestamp of last successful trigger. | +| `CreatedAt` | `DateTime` | Rule creation timestamp. | -2) **Reprocess DLQ batch (partial failure)** - - Arrange: DLQ contains both valid and invalid messages - - Act: run job - - Assert: - - valid messages are replayed - - invalid messages are either left in DLQ or moved aside (depending on policy) - - job returns a result/log summary (counts) +**`AlertCondition` Enum** -3) **Idempotency / replay safety** - - Arrange: same DLQ message is processed twice (simulate crash before delete) - - Assert: the replay operation does not create duplicate side effects (use `MessageId`-based idempotency key). +| Value | Description | +| :--- | :--- | +| `PriceAbove` | Trigger when current price exceeds `TargetValue`. | +| `PriceBelow` | Trigger when current price falls below `TargetValue`. | +| `PriceTargetReached` | Trigger when price hits an exact target (±tolerance). | +| `PercentDropFromCost` | Trigger when unrealized loss % exceeds `TargetValue`. | +| `LowHoldingsCount` | Trigger when user's share count drops below `TargetValue`. | --- -## 4) Suggested folder structure (inside IntegrationTests) +#### `Trade` _(was `StockTransaction`)_ +**Ownership Ledger.** Immutable record of position changes. -```text -InventoryManagementSystem/InventoryAlert.IntegrationTests/ -├── Tests/ -│ ├── Worker/ -│ │ ├── Jobs/ -│ │ │ ├── SyncPricesJobTests.cs -│ │ │ ├── NewsSyncJobTests.cs -│ │ ├── Sqs/ -│ │ │ ├── SqsConsumerSuccessTests.cs -│ │ │ ├── SqsConsumerDlqTests.cs -│ │ ├── Dlq/ -│ │ │ ├── DlqReprocessorJobTests.cs -``` +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `Guid` | Primary Key. | +| `UserId` | `Guid` | **FK** → `User.Id` | +| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | +| `Type` | `enum` | `Buy`, `Sell`, `Dividend`, `Split`. | +| `Quantity` | `decimal` | **Always positive.** Direction is encoded by `Type`. Net holdings = `SUM(Buy) - SUM(Sell)` computed by service. | +| `UnitPrice` | `decimal` | Execution price per share. `0` for `Dividend`/`Split`. | +| `TradedAt` | `DateTime` | UTC execution timestamp. | +| `Notes` | `string?` | Optional user annotation. | --- -## 5) Timing pitfalls + how to avoid flaky tests +#### `PriceHistory` +**Price Log.** Point-in-time market price snapshots for charting and alert evaluation. -- Prefer asserting via “pull once” APIs rather than sleeping: - - check SQS queue length / receive messages - - query DB state -- Use bounded waits with polling loops (max 10–30s) for asynchronous behaviors. -- Keep maxReceiveCount small in local env (already `3`) and set `VisibilityTimeout` low enough for tests. -- Ensure test cleanup resets SQS queues, Redis keys, and DB state between tests. +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `long` | Primary Key (bigserial). | +| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | +| `Price` | `decimal` | Close/current price at snapshot. | +| `High` | `decimal?` | Day high at snapshot time. | +| `Low` | `decimal?` | Day low at snapshot time. | +| `Open` | `decimal?` | Day open at snapshot time. | +| `PrevClose` | `decimal?` | Previous close price. | +| `RecordedAt` | `DateTime` | UTC snapshot timestamp. | + +> **Index**: `(TickerSymbol, RecordedAt DESC)` — supports range queries for charts. --- -## 6) What to update in CI after adding these tests +#### `StockMetric` _(new)_ +**Cached Basic Financials.** One row per ticker. Updated daily by worker. Maps to Finnhub `/stock/metric`. -Once the new tests exist: +| Property | Type | Description | +| :--- | :--- | :--- | +| `TickerSymbol` | `string` | **PK + FK** → `StockListing.TickerSymbol` | +| `PeRatio` | `double?` | Price-to-Earnings ratio (TTM). | +| `PbRatio` | `double?` | Price-to-Book ratio. | +| `EpsBasicTtm` | `double?` | Earnings per share (TTM). | +| `DividendYield` | `double?` | Dividend yield (annual %). | +| `Week52High` | `decimal?` | 52-week high price. | +| `Week52Low` | `decimal?` | 52-week low price. | +| `RevenueGrowthTtm` | `double?` | YoY revenue growth (TTM). | +| `MarginNet` | `double?` | Net profit margin (TTM). | +| `LastSyncedAt` | `DateTime` | UTC timestamp of last Finnhub sync. | -- Confirm `.github/workflows/ci.yml` stack includes: - - SQS + DLQ (Moto/LocalStack) with redrive policy - - Redis (for dedup/cooldown) -- Add a CI summary section for: - - number of messages processed - - DLQ count (if any) - - replay runs (if job exists)",169,fd76edc664b293599f7f1c82bac71b22,doc\JOBS_INTEGRATION_TEST_PLAN.md,0,268,"message, tests, test, worker, failure, queue, assert, messages",1777190302.592188,10,mock setup returns async market data threshold stock price price drop asnotracking external api hosted service finnhubpricesyncworker compose item sku dbcontext fluentassertions times once quote verify postgres dockerfile backgroundservice notification loss moq xunit periodictimer postgresql stock inventory arrange act assert appdbcontext efcore container entity framework unit test,# Jobs + Worker Integration Test Plan (with SQS/DLQ Option C) | Jobs + Worker Integration Test Plan (with SQS/DLQ Option C) This plan complement -doc,"# Logging Review & Recommendations +--- -Scope: repository-wide review focused on **API/Worker request flow tracing**, **request/response logging**, and **centralized structured logging**. No code changes included in this document. +#### `EarningsSurprise` _(new)_ +**Historical Earnings.** Last 4 quarters of actual vs. estimated EPS. Maps to Finnhub `/stock/earnings`. -Date: 2026-04-26 +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `int` | Primary Key. | +| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | +| `Period` | `DateOnly` | Fiscal quarter end date in Finnhub format (e.g., `2024-09-30`). Unique constraint with `TickerSymbol`. | +| `ActualEps` | `double?` | Actual reported EPS. | +| `EstimateEps` | `double?` | Consensus estimate EPS. | +| `SurprisePercent` | `double?` | `(Actual - Estimate) / |Estimate| * 100`. Computed on write. | +| `ReportDate` | `DateOnly?` | Date of public earnings release. | + +> **C2 fix**: Finnhub returns `period` as `""2024-09-30""` (last day of fiscal quarter). Stored as `DateOnly`, not a ""Q4"" string. Unique constraint on `(TickerSymbol, Period)` prevents duplicate upserts. --- -## 1) Current State (What Exists Today) +#### `RecommendationTrend` _(new)_ +**Analyst Consensus.** Monthly analyst buy/hold/sell counts. Maps to Finnhub `/stock/recommendation`. -### API (`InventoryManagementSystem/InventoryAlert.Api`) +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `int` | Primary Key. | +| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | +| `Period` | `string` | Month period (e.g., ""2025-03-01""). | +| `StrongBuy` | `int` | Count of ""Strong Buy"" ratings. | +| `Buy` | `int` | Count of ""Buy"" ratings. | +| `Hold` | `int` | Count of ""Hold"" ratings. | +| `Sell` | `int` | Count of ""Sell"" ratings. | +| `StrongSell` | `int` | Count of ""Strong Sell"" ratings. | +| `SyncedAt` | `DateTime` | UTC timestamp of last sync. | -- **Serilog bootstrap** configured in `InventoryManagementSystem/InventoryAlert.Api/Program.cs` (Console + Seq + rolling File). -- **Correlation ID** middleware exists: `InventoryManagementSystem/InventoryAlert.Api/Middleware/CorrelationIdMiddleware.cs` - - Header: `X-Correlation-Id` - - Behavior: uses incoming header if present; otherwise generates a `Guid`. - - Adds the id to: - - `context.Items[""X-Correlation-Id""]` - - `context.Response.Headers[""X-Correlation-Id""]` - - Serilog `LogContext` property: `CorrelationId` -- **Exception logging** exists: `InventoryManagementSystem/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs` -- **Request timing logs** exist: `InventoryManagementSystem/InventoryAlert.Api/Middleware/PerformanceMiddleware.cs` - -### Worker (`InventoryManagementSystem/InventoryAlert.Worker`) - -- Serilog bootstrap exists in `InventoryManagementSystem/InventoryAlert.Worker/Program.cs` (Console + Seq). -- SQS processing uses scopes + Serilog context: - - `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` - - Pushes `CorrelationId` into: - - `ILogger.BeginScope(...)` dictionary (`MessageId`, `EventType`, `CorrelationId`) - - Serilog `LogContext` property `CorrelationId` - -### Infrastructure (`InventoryManagementSystem/InventoryAlert.Infrastructure`) - -- Messaging publisher logs publishes: - - `InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs` -- `ICorrelationProvider` currently reads **only** from `HttpContext`: - - `InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs` +--- -### UI (`InventoryAlert.UI`) +#### `InsiderTransaction` _(new)_ +**Insider Activity.** Last 100 insider transactions. Maps to Finnhub `/stock/insider-transactions`. -- No explicit propagation of `X-Correlation-Id` found in UI sources (search for `X-Correlation-Id` / `CorrelationId` returned no matches). +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `int` | Primary Key. | +| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | +| `Name` | `string?` | Insider full name. | +| `Share` | `long?` | Net share count (positive = buy, negative = sell). | +| `Value` | `decimal?` | Total transaction value in USD. | +| `TransactionDate` | `DateOnly?` | Date of transaction. | +| `FilingDate` | `DateOnly?` | SEC filing date. | +| `TransactionCode` | `string?` | SEC code (e.g., ""P"" = purchase, ""S"" = sale). | --- -## 2) What’s Missing vs Your Goal +#### `Notification` _(new — D5)_ +**In-App Alerts Delivery.** Stores triggered alert messages for the authenticated user. UI polls this endpoint every 30 seconds. -You asked for: +| Property | Type | Description | +| :--- | :--- | :--- | +| `Id` | `Guid` | Primary Key. | +| `UserId` | `Guid` | **FK** → `User.Id`. Cascade delete. | +| `AlertRuleId` | `Guid?` | **FK** → `AlertRule.Id`. Nullable (for system messages). | +| `TickerSymbol` | `string?` | Symbol that triggered the alert. | +| `Message` | `string` | Human-readable alert message. | +| `IsRead` | `bool` | Whether the user has acknowledged it. Default `false`. | +| `CreatedAt` | `DateTime` | UTC timestamp of notification creation. | -1) **Log request + response** (ideally bodies), but avoid exploding log size. -2) A **single id** to follow the flow end-to-end. -3) A way to **centralize** the logging (avoid “log sprinkled everywhere”). -4) Identify parts that **still have little/no logging**. +> **Index**: `(UserId, IsRead, CreatedAt DESC)` — supports fast unread notification queries. -Key gaps found: +### 1.3 DynamoDB Collections -### Gap A — API → Worker correlation is not reliable today +News articles are **permanent historical assets**, not ephemeral cache entries. They are never TTL-deleted. Queries use SK range filters to get recent articles, and a GSI is used for cross-collection lookups. -- `README.md` claims: “Every request includes a `CorrelationId` that propagates from the API through SNS/SQS to the Worker.” -- However `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` builds `EventEnvelope` without setting `CorrelationId`. - - `InventoryManagementSystem/InventoryAlert.Domain/Events/EventEnvelope.cs` defaults `CorrelationId` to `string.Empty`. - - `InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs` only includes the `CorrelationId` attribute if it’s not empty. +#### `MarketNews` -Impact: +| Attribute | Type | Role | Notes | +| :--- | :--- | :--- | :--- | +| `PK` | `string` | Partition Key | `CATEGORY#` e.g. `CATEGORY#general` | +| `SK` | `string` | Sort Key | `TS#` — enables range queries for ""last N hours"" | +| `NewsId` | `long` | Attribute | Finnhub `id` field. Used for deduplication. | +| `Headline` | `string` | Attribute | Article headline. | +| `Summary` | `string` | Attribute | Short article summary. | +| `Source` | `string` | Attribute | Publisher name. | +| `Url` | `string` | Attribute | External article link. | +| `Image` | `string?` | Attribute | Thumbnail image URL. | +| `Category` | `string` | Attribute | `general`, `forex`, `crypto`, `merger`. | +| `SyncedAt` | `string` | Attribute | ISO-8601 UTC timestamp of when this record was written. | -- For request-triggered async flows (ex: `POST /api/v1/events`), the Worker may log without the same `CorrelationId` as the originating HTTP request, making “search by id” unreliable. +> **No TTL.** News is retained indefinitely as a queryable historical archive. Use SK range (`TS#` → `TS#`) to retrieve recent articles. -### Gap B — Request/response body logging is not implemented +#### `CompanyNews` -- The API logs *completion* timing (method/path/status/time), but does not log: - - Request headers - - Request body - - Response headers - - Response body +| Attribute | Type | Role | Notes | +| :--- | :--- | :--- | :--- | +| `PK` | `string` | Partition Key | `SYMBOL#` e.g. `SYMBOL#TSLA` | +| `SK` | `string` | Sort Key | `TS#` | +| `NewsId` | `long` | Attribute | Finnhub `id`. Deduplication key. | +| `Headline` | `string` | Attribute | Article headline. | +| `Summary` | `string` | Attribute | Short summary. | +| `Source` | `string` | Attribute | Publisher name. | +| `Url` | `string` | Attribute | External article link. | +| `Image` | `string?` | Attribute | Thumbnail URL. | +| `Symbol` | `string` | Attribute | Denormalized ticker (for GSI). | +| `SyncedAt` | `string` | Attribute | ISO-8601 UTC timestamp. | -### Gap C — Entry-point visibility is low in API controllers/services +> **No TTL.** Finnhub free tier provides up to 1 year of historical company news on first sync. Retained indefinitely thereafter. -Findings from code scan: +#### GSI: `BySymbolAndDate` (on `CompanyNews`) -- All API controllers have **no `ILogger` injection** and **no `.Log*()` calls: - - `InventoryManagementSystem/InventoryAlert.Api/Controllers/*.cs` -- Several API services have no logs: - - `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` - - `InventoryManagementSystem/InventoryAlert.Api/Services/AuthService.cs` - - `InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs` - - `InventoryManagementSystem/InventoryAlert.Api/Services/NotificationService.cs` +| Attribute | Key Role | +| :--- | :--- | +| `Symbol` | GSI Partition Key | +| `SK` | GSI Sort Key (reused) | -Note: this doesn’t mean they *must* log everywhere; it means the **only consistent view** of API activity is currently the middleware timing log (plus error logs). +Enables efficient cross-symbol queries (e.g., ""all TSLA news this month"") without scanning. -### Gap D — Correlation provider works for HTTP only +--- -- `InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs` depends on `IHttpContextAccessor`. -- In the Worker (no HTTP request), this returns a **new Guid**, which breaks continuity if Worker code publishes further messages and expects to “inherit” correlation. +## 2. API Reference ---- +### Base Configuration -## 3) Recommended Logging Design (Centralized + Searchable + Size-Controlled) +- **Version**: `v1` +- **Authentication**: JWT Bearer Token required unless marked `[Public]`. +- **Base URL**: `https://{host}/api/v1` -This is the recommended model: +--- -### 3.1 Use one “Flow Id” everywhere +### Finnhub Endpoint Coverage Map -Keep `CorrelationId` as the primary flow identifier: +| Finnhub Endpoint | Our API Route | Status | +| :--- | :--- | :--- | +| `/search` | `GET /stocks/search` | ✅ Implemented | +| `/quote` | `GET /stocks/{symbol}/quote` | ✅ Implemented | +| `/stock/profile2` | `GET /stocks/{symbol}/profile` | ✅ Implemented | +| `/stock/market-status` | `GET /market/status` | ✅ Implemented | +| `/news` | `GET /market/news` | ✅ Implemented | +| `/company-news` | `GET /stocks/{symbol}/news` | ✅ Implemented | +| `/stock/metric` | `GET /stocks/{symbol}/financials` | 🆕 New | +| `/stock/earnings` | `GET /stocks/{symbol}/earnings` | 🆕 New | +| `/stock/recommendation` | `GET /stocks/{symbol}/recommendation` | 🆕 New | +| `/stock/insider-transactions` | `GET /stocks/{symbol}/insiders` | 🆕 New | +| `/stock/peers` | `GET /stocks/{symbol}/peers` | 🆕 New | +| `/calendar/earnings` | `GET /market/calendar/earnings` | 🆕 New | +| `/calendar/ipo` | `GET /market/calendar/ipo` | 🆕 New | +| `/stock/market-holiday` | `GET /market/holiday` | 🆕 New | +| `/stock/symbol` | Internal (worker seed only) | ⚙️ Worker | +| `/forex/exchange`, `/crypto/*` | Not planned (out of scope) | ❌ N/A | -- HTTP: `X-Correlation-Id` header + `LogContext.CorrelationId` -- Messaging: `EventEnvelope.CorrelationId` + SNS/SQS message attribute `CorrelationId` -- Worker: push envelope `CorrelationId` into scope + `LogContext` +--- -Also consider adding (optional, but valuable): +### Symbol Discovery Strategy (DB-First + Finnhub Fallback) -- `TraceId` (W3C tracing / `Activity.TraceId`) for distributed tracing later -- `RequestId` (`HttpContext.TraceIdentifier`) for server-side uniqueness +> **Design Goal**: Minimize external Finnhub calls over time. Every successful Finnhub resolution permanently enriches our local `StockListing` database, making future lookups free and instant. -### 3.2 Centralize “HTTP request completion log” (cheap, always-on) +This pattern applies to **every flow that requires resolving a ticker symbol** — search, add to portfolio, add to watchlist, create alert. -Goal: every request creates exactly **1 structured log event** at the end: +```mermaid +flowchart TD + A([Client: search query / symbol]) --> B{Find in StockListing DB?} + B -- Found --> C([Return DB result immediately]) + B -- Not Found --> D[Call Finnhub /search or /stock/profile2] + D --> E{Finnhub returned result?} + E -- No --> F([404: Symbol not recognized]) + E -- Yes --> G[INSERT StockListing row] + G --> H[Trigger background: SyncMetricsJob for symbol] + H --> I([Return newly persisted result]) +``` -Fields to include (recommended): +#### Rules -- `CorrelationId` -- `Method`, `Path`, `StatusCode`, `ElapsedMs` -- `UserId` (if authenticated), `ClientIp` -- `RouteTemplate` / `EndpointName` (if available) -- `RequestContentLength`, `ResponseContentLength` (when known) +| Rule | Detail | +| :--- | :--- | +| **DB check is always first** | Query `StockListing` by `TickerSymbol` (exact) or `Name` (ILIKE for search). | +| **Finnhub is the fallback** | Only called if no DB match. Uses `/search` for fuzzy lookup, `/stock/profile2` for enrichment. | +| **Always persist on resolution** | A resolved Finnhub result is immediately `INSERT`-ed into `StockListing`. Duplicates handled with `ON CONFLICT DO NOTHING`. | +| **Background enrichment** | After insert, enqueue a background job to pull `StockMetric`, `EarningsSurprise`, and `RecommendationTrend` for the new symbol. | +| **Never block the user** | The response is returned immediately after the `StockListing` insert. Enrichment jobs run async. | +| **Rate limit guard** | Finnhub calls are guarded by a Redis counter (`finnhub:ratelimit`) capped at 55 rpm (buffer below the 60/min free limit). | -This gives you: +#### Affected Endpoints -- small logs -- consistent format -- easy searching in Seq +| Endpoint | Behavior | +| :--- | :--- | +| `GET /stocks/search?q=` | DB ILIKE search first → Finnhub `/search` fallback → persists any new matches. | +| `POST /portfolio/` | Validates symbol via DB → Finnhub fallback if missing → reject only if both miss. | +| `POST /watchlist/{symbol}` | Same as portfolio: DB resolve → Finnhub fallback → insert → add to watchlist. | +| `POST /alerts/` | Same symbol resolution chain before creating rule. | -### 3.3 Add request/response body logging only under strict controls (expensive, opt-in) +--- -Body logging is where log volume and sensitive data risk skyrockets. Recommended controls: +### [Auth] — `/api/v1/auth` -**Controls (must-have)** +| Method | Endpoint | Auth | Description | +| :--- | :--- | :--- | :--- | +| `POST` | `/login` | `[Public]` | Authenticate and receive JWT + refresh token. 429 rate-limited. | +| `POST` | `/register` | `[Public]` | Create a new user account. | +| `POST` | `/refresh` | `[Public]` | Exchange a valid refresh token for a new access JWT. | +| `POST` | `/logout` | JWT | Revoke the current refresh token. | -- Feature flag (enable in Dev/Docker only, off in Prod by default) -- Content-type allowlist (`application/json`, maybe `text/*`) -- Size limits (log first N bytes only; store `Truncated=true`) -- Redaction (passwords/tokens/PII) -- Endpoint allowlist/denylist - - Denylist examples: `POST /api/v1/auth/login`, refresh-token endpoints +--- -**When to log bodies** +### [Portfolio] — `/api/v1/portfolio` -- Errors only (responses with `StatusCode >= 400`), plus explicit debug scenarios -- Or sample rate (ex: 1% of successful traffic) +_Personal position management. Requires JWT. All data is scoped to the authenticated user._ -**Alternative if you need full bodies** +> **D1 fix**: Routes use `{symbol}` (the ticker string), not a numeric `{id}`. A portfolio position is uniquely identified by `(UserId, TickerSymbol)` — no separate position table exists. -- Write full bodies to a separate secure store (blob/file) keyed by `CorrelationId`, and keep Seq logs lightweight: - - Seq event contains `CorrelationId` + a `PayloadRef` (path/key) +| Method | Endpoint | Description | +| :--- | :--- | :--- | +| `GET` | `/` | List user's positions (paged). | +| `GET` | `/{symbol}` | Detailed position breakdown for one holding. | +| `GET` | `/alerts` | Breached alert results for user's portfolio (threshold-based). | +| `POST` | `/` | Open a new position. | +| `POST` | `/bulk` | Import multiple positions at once. | +| `PATCH` | `/{symbol}/trade` | Record a trade (buy/sell/etc.) to adjust holdings. | +| `DELETE` | `/{symbol}` | Remove a position from portfolio. | -### 3.4 Centralize “business event logs” (domain-level, not request-level) +--- -For meaningful actions (create alert rule, register user, enqueue event, etc.), log: +### [Stocks] — `/api/v1/stocks` -- event name (stable template) -- important identifiers (`UserId`, `AlertRuleId`, `Symbol`) -- `CorrelationId` +_Global stock catalog and market intelligence. Read-heavy; most endpoints cache aggressively._ -This should live at service-layer boundaries (not in every controller). +| Method | Endpoint | Description | +| :--- | :--- | :--- | +| `GET` | `/` | Browse full global StockListing catalog (paged, searchable). | +| `GET` | `/search` | Symbol lookup by name, ISIN, or ticker. | +| `GET` | `/{symbol}/quote` | Real-time price quote from Finnhub or local cache. | +| `GET` | `/{symbol}/profile` | Full company profile (Logo, Industry, MarketCap, IPO date). | +| `GET` | `/{symbol}/financials` | 🆕 Basic Financials (P/E, EPS, 52-week range, margins). | +| `GET` | `/{symbol}/earnings` | 🆕 Last 4 quarters of earnings surprises (actual vs. estimate). | +| `GET` | `/{symbol}/recommendation` | 🆕 Latest analyst recommendation trend (Buy/Hold/Sell counts). | +| `GET` | `/{symbol}/insiders` | 🆕 Last 100 insider transactions (SEC-reported). | +| `GET` | `/{symbol}/peers` | 🆕 List of peer companies in the same sector/country. | +| `GET` | `/{symbol}/news` | 🆕 Latest company-specific news (from DynamoDB cache). | +| `POST` | `/sync` | `[Admin]` Manually trigger global price sync job. | --- -## 4) Concrete Fix List (Prioritized, Minimal, High Value) +### [Market] — `/api/v1/market` -### P0 — Make correlation actually propagate API → SNS/SQS → Worker +_Exchange-level data. Partially public._ -Acceptance criteria: +| Method | Endpoint | Auth | Description | +| :--- | :--- | :--- | :--- | +| `GET` | `/status` | JWT | Current open/closed status of major exchanges. | +| `GET` | `/news` | JWT | Global financial news feed (paged). | +| `GET` | `/holiday` | JWT | 🆕 Upcoming and past market holidays by exchange. | +| `GET` | `/calendar/earnings` | JWT | 🆕 Upcoming earnings release calendar (1-month window). | +| `GET` | `/calendar/ipo` | JWT | 🆕 Upcoming and recent IPOs. | -- Any HTTP request that publishes an event results in: - - API logs containing `CorrelationId` - - SNS publish logs containing the same `CorrelationId` - - Worker processing logs containing the same `CorrelationId` +--- -Candidate locations to stamp `EventEnvelope.CorrelationId`: +### [Watchlist] — `/api/v1/watchlist` -- `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` (inject `ICorrelationProvider`) -- or a decorator around `IEventPublisher` that stamps missing correlation ids in one place +| Method | Endpoint | Description | +| :--- | :--- | :--- | +| `GET` | `/` | List user's watchlist with live price and basic metrics. | +| `GET` | `/{symbol}` | Detailed view of a single watchlist entry. | +| `POST` | `/{symbol}` | Add a ticker symbol to watchlist. | +| `DELETE` | `/{symbol}` | Remove a ticker from watchlist. | -### P0 — Add “one request completion log” with consistent fields +--- -Acceptance criteria: +### [Alert Rules] — `/api/v1/alerts` -- Every request generates exactly one completion log event with consistent fields. -- Slow requests (like current `PerformanceMiddleware`) are still visible (either by a `Slow=true` flag or level/threshold). +_Manages definitions for advanced, dynamic notification triggers._ -### P1 — Add request/response body logging safely (debug-only) +| Method | Endpoint | Description | +| :--- | :--- | :--- | +| `GET` | `/` | List all alert rules for the authenticated user. | +| `POST` | `/` | Create a new alert rule. | +| `PUT` | `/{ruleId}` | Replace an existing alert rule. | +| `PATCH` | `/{ruleId}/toggle` | Enable or disable a rule without full replacement. | +| `DELETE` | `/{ruleId}` | Permanently remove an alert rule. | -Acceptance criteria: +--- -- Body logging: - - is off by default - - has truncation + redaction - - can be toggled per environment - - can be enabled per endpoint for targeted debugging +### [Notifications] — `/api/v1/notifications` -### P1 — Improve Worker correlation continuity for downstream publishes +_In-app notification delivery. Polls every 30s from UI. Requires JWT._ -Acceptance criteria: +| Method | Endpoint | Description | +| :--- | :--- | :--- | +| `GET` | `/` | List all notifications for current user (unread first). | +| `GET` | `/unread-count` | Returns `{ Count: int }` — used for bell badge. | +| `PATCH` | `/{id}/read` | Mark a single notification as read. | +| `PATCH` | `/read-all` | Mark all notifications as read. | +| `DELETE` | `/{id}` | Dismiss a notification permanently. | -- When handling an envelope with `CorrelationId=X`, any downstream publish/enqueue inside the same job uses `CorrelationId=X` by default. +--- -Implementation options (choose one): +### [Events] — `/api/v1/events` `[Admin/Internal]` -- Pass correlation explicitly as a parameter where enqueuing/publishing occurs. -- Introduce an AsyncLocal-based correlation context (set in HTTP middleware and in Worker message processing) and have `ICorrelationProvider` read from it. -- Adopt W3C tracing (`Activity`) and derive `CorrelationId` from `Activity.TraceId`. +| Method | Endpoint | Description | +| :--- | :--- | :--- | +| `POST` | `/` | Publish an integration event to SQS. | +| `GET` | `/types` | List all supported event type strings. | -### P2 — Add service identity properties to logs +--- -Acceptance criteria: +## 3. Background Processing (Worker Architecture) -- Seq can filter by service quickly: - - `Service = 'InventoryAlert.Api'` - - `Service = 'InventoryAlert.Worker'` +### Hybrid Strategy -### P2 — Reduce “big payload” log risk in external client logging +| Layer | Engine | Purpose | +| :--- | :--- | :--- | +| **Scheduled Jobs** | Hangfire | Recurring heartbeats (price sync, news batching, metrics). | +| **Event Handlers** | SQS + Redis | Reactive tasks (alert evaluation, news on-demand). | -`InventoryManagementSystem/InventoryAlert.Infrastructure/External/Finnhub/FinnhubClient.cs` logs full response content in some warnings/errors. +--- -Acceptance criteria: +### Scheduled Jobs -- External-client failures log: - - status code, endpoint/path, small excerpt (max N chars), and `CorrelationId` - - never log entire large bodies by default +Located in `InventoryAlert.Worker/ScheduledJobs`. + +| Job | Schedule | Finnhub Endpoint(s) Used | Description | +| :--- | :--- | :--- | :--- | +| **SyncPricesJob** | Every 15 min | `/quote` | Full sweep of `StockListing` catalog. Updates `PriceHistory`, evaluates all `AlertRule` conditions. | +| **SyncMetricsJob** | Daily at 06:00 UTC | `/stock/metric` | 🆕 Updates `StockMetric` table for all active symbols. | +| **SyncEarningsJob** | Daily at 07:00 UTC | `/stock/earnings` | 🆕 Refreshes `EarningsSurprise` rows for watchlisted symbols. | +| **SyncRecommendationsJob** | Weekly (Monday) | `/stock/recommendation` | 🆕 Refreshes `RecommendationTrend` for portfolio + watchlist symbols. | +| **SyncInsidersJob** | Daily at 08:00 UTC | `/stock/insider-transactions` | 🆕 Pulls last 100 insider transactions for actively-watched symbols. | +| **CompanyNewsJob** | Every 6 hours | `/company-news` | Batch news sync for all symbols on any user's watchlist → DynamoDB. | +| **MarketNewsJob** | Every 2 hours | `/news` | Global news refresh → DynamoDB `MarketNews`. | +| **ProcessQueueJob** | Continuous long-poll | — | SQS reader with Redis-based idempotency (30-min window). | +| **SqsScheduledPollerJob** | Every 5 min | — | Fallback SQS drain if the continuous poller fails. | --- -## 5) Coverage Findings (Where Logging Is Thin Today) +### Event-Driven Handlers -### API controllers (no direct logging) +Located in `InventoryAlert.Worker/IntegrationEvents/Handlers`. -All controllers found without `ILogger` and without `.Log*()`: +| Handler | SQS Event Type | Logic | +| :--- | :--- | :--- | +| **PriceAlertHandler** | `inventoryalert.pricing.price-drop.v1` | On-demand quote fetch → cache update → `PriceHistory` insert → full `AlertRule` evaluate for symbol. | +| **LowHoldingsHandler** | `inventoryalert.inventory.stock-low.v1` | Post-trade trigger → queries `AlertRule` for `LowHoldingsCount` → notifies if breached. | +| **CompanyNewsHandler** | `inventoryalert.news.headline.v1` | Immediate sync of ticker news → DynamoDB `CompanyNews`. | +| **DefaultHandler** | `*` (unmatched) | Acknowledge and delete. Logs warning. Prevents poison-message queue blockage. | -- `InventoryManagementSystem/InventoryAlert.Api/Controllers/AlertRulesController.cs` -- `InventoryManagementSystem/InventoryAlert.Api/Controllers/AuthController.cs` -- `InventoryManagementSystem/InventoryAlert.Api/Controllers/EventsController.cs` -- `InventoryManagementSystem/InventoryAlert.Api/Controllers/MarketController.cs` -- `InventoryManagementSystem/InventoryAlert.Api/Controllers/NotificationsController.cs` -- `InventoryManagementSystem/InventoryAlert.Api/Controllers/PortfolioController.cs` -- `InventoryManagementSystem/InventoryAlert.Api/Controllers/StocksController.cs` -- `InventoryManagementSystem/InventoryAlert.Api/Controllers/WatchlistController.cs` +--- -Recommendation: +### Flow & Deduplication -- Keep controllers thin, but ensure service-level “business event logs” exist for key actions, and HTTP middleware provides the consistent request-completion log. +1. **Publish**: API/Services wrap payloads in an `EventEnvelope` and push to SQS. +2. **Poll**: `ProcessQueueJob` retrieves messages and checks Redis for atomic duplicates (30-min TTL window). +3. **Cooldown**: `PriceAlertHandler` carries a **24-hour per-symbol cooldown** via Redis to prevent alert storms. +4. **Route**: `IIntegrationMessageRouter` maps `EventType` → `IIntegrationEventHandler`. +5. **Audit**: After 5 failed attempts, messages are acknowledged and deleted to unblock the queue. All failures are logged via `ILogger`. -### API services with little/no logging +--- -- `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` (also the correlation stamping gap) -- `InventoryManagementSystem/InventoryAlert.Api/Services/AuthService.cs` (login/register activity visibility is low) -- `InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs` -- `InventoryManagementSystem/InventoryAlert.Api/Services/NotificationService.cs` +## 4. Data Transfer Objects -### Worker area with no logs +### 4.1 Authentication -- `InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs` (may be fine, but hard to debug queue backpressure without any counters/logs) +| DTO | Properties | +| :--- | :--- | +| `LoginRequest` | `Username` (string), `Password` (string) | +| `RegisterRequest` | `Username` (string), `Password` (string), `Email` (string) | +| `AuthResponse` | `AccessToken` (string, JWT), `ExpiresAt` (DateTime, UTC), `RefreshToken` (string — delivered as `httpOnly` cookie, not body) | +| `RefreshRequest` | No body. Refresh token read from `httpOnly` cookie automatically. | + +> **JWT config**: Access token TTL = **15 minutes**. Refresh token TTL = **7 days**, stored as `httpOnly; Secure; SameSite=Strict` cookie. Refresh tokens are single-use (rotated on each refresh). --- -## 6) Seq Search Examples (How You’d Trace a Flow) +### 4.2 Portfolio & Trades -From `InventoryAlert.Wiki/docs/07-dev-maintenance/operational-runbook.md`, you already use: +| DTO | Properties | +| :--- | :--- | +| `CreatePositionRequest` | `TickerSymbol` (string), `Quantity` (decimal, must be > 0), `UnitPrice` (decimal, must be > 0), `TradedAt` (DateTime?) | +| `TradeRequest` | `Type` (enum: `Buy`/`Sell`/`Dividend`/`Split`), `Quantity` (decimal, **always positive**), `UnitPrice` (decimal), `Notes` (string?) | +| `PortfolioPositionResponse` | `StockId` (int), `Symbol` (string), `Name` (string), `Exchange` (string), `Logo` (string), `HoldingsCount` (decimal), `AveragePrice` (decimal), `CurrentPrice` (decimal), `MarketValue` (decimal), `TotalCost` (decimal), `TotalReturn` (decimal), `TotalReturnPercent` (double), `PriceChange` (decimal), `PriceChangePercent` (double), `Industry` (string) | +| `PortfolioAlertResponse` | `Symbol` (string), `CurrentPrice` (decimal), `Threshold` (decimal), `LossPercent` (double), `LastUpdated` (DateTime) | +| `NotificationResponse` | `Id` (Guid), `Message` (string), `TickerSymbol` (string?), `IsRead` (bool), `CreatedAt` (DateTime) | -- Errors: `@Level = 'Error'` -- Service: `@Properties.SourceContext like '%Worker%'` -- Correlation: `@Properties.CorrelationId = ''` +--- -Recommended additional searches once fields are standardized: +### 4.3 Alert Rules -- A single flow: `CorrelationId = ''` -- One event type: `EventType = 'inventoryalert.news.sync-requested.v1'` -- One message: `MessageId = ''` -- Slow requests: `ElapsedMs >= 500` or `Slow = true` +| DTO | Properties | +| :--- | :--- | +| `AlertRuleRequest` | `TickerSymbol` (string), `Condition` (enum), `TargetValue` (decimal), `TriggerOnce` (bool) | +| `AlertRuleResponse` | `Id` (Guid), `TickerSymbol` (string), `Condition` (enum), `TargetValue` (decimal), `IsActive` (bool), `TriggerOnce` (bool), `LastTriggeredAt` (DateTime?) | +| `ToggleAlertRequest` | `IsActive` (bool) | --- -## 7) Notes / Potential Inconsistencies to Validate - -These aren’t strictly “logging” issues, but they affect observability and correlation: +### 4.4 Market & Stock Data -- Worker router expects SQS `MessageAttributes[""MessageType""]` in `InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs`. - - Current SNS publisher uses message attributes `EventType`, `Source`, and optional `CorrelationId` in `InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs`. - - Consider standardizing attribute names (`EventType` vs `MessageType`) and ensuring Worker routing matches what the publisher emits. +| DTO | Properties | +| :--- | :--- | +| `StockQuoteResponse` | `Symbol`, `Price`, `Change`, `ChangePercent`, `High`, `Low`, `Open`, `PrevClose`, `Timestamp` | +| `StockProfileResponse` | `Symbol`, `Name`, `Exchange`, `Currency`, `Country`, `Industry`, `MarketCap`, `Ipo`, `WebUrl`, `Logo` | +| `StockMetricResponse` | `Symbol`, `PeRatio`, `PbRatio`, `EpsBasicTtm`, `DividendYield`, `Week52High`, `Week52Low`, `RevenueGrowthTtm`, `MarginNet`, `LastSyncedAt` | +| `EarningsSurpriseResponse` | `Period`, `ActualEps`, `EstimateEps`, `SurprisePercent`, `ReportDate` | +| `RecommendationResponse` | `Period`, `StrongBuy`, `Buy`, `Hold`, `Sell`, `StrongSell` | +| `InsiderTransactionResponse` | `Name`, `Share`, `Value`, `TransactionDate`, `FilingDate`, `TransactionCode` | +| `SymbolSearchResponse` | `Symbol`, `Description`, `Type`, `Exchange` | +| `MarketStatusResponse` | `Exchange`, `IsOpen`, `Session`, `Holiday`, `Timezone` | +| `MarketHolidayResponse` | `Exchange`, `EventName`, `Date`, `AtTime` | +| `NewsResponse` | `Id` (long), `Headline`, `Summary`, `Source`, `Url`, `DateTime`, `Image`, `Category` | +| `EarningsCalendarResponse` | `Symbol`, `Date`, `EpsEstimate`, `EpsActual`, `RevenueEstimate`, `RevenueActual` | +| `IpoCalendarResponse` | `Symbol`, `Name`, `Date`, `Price`, `Shares`, `Status` | +| `PeersResponse` | `Symbol`, `Peers` (List\) | --- -## 8) Suggested Next Output (If You Want) +## 5. Comprehensive Interface Catalog -If you want, I can produce a second markdown file with a concrete “implementation checklist” (exact middleware/filter approach, redaction rules, size limits, and an example Seq dashboard/query set). This would still be documentation-only unless you ask for code changes.",294,76313fb6742c21b0ea713b23dd91b96c,doc\LOGGING_REVIEW.md,0,269,"inventoryalert, inventorymanagementsystem, correlationid, worker, request, correlation, logging, logs",1777190302.5933053,1,external api postgresql iproductservice igenericrepository httpput dockerfile backgroundservice efcore productscontroller application service iactionresult data access compose business logic entity framework httppost dbset loss asnotracking container finnhubpricesyncworker postgres appdbcontext periodictimer hosted service price drop quote productservice threshold dbcontext market data stock price httpget notification iproductrepository,# Logging Review & Recommendations | Logging Review & Recommendations Scope: repository-wide review focused on API/Wo -doc,"--- -description: Audit of repository naming, project locations, and documentation structure alignment. -type: reference -status: draft -version: 1.1 -tags: [audit, naming, structure, documentation, inventoryalert] -last_updated: 2026-04-26 ----",9,070ec2a92ea03b1425507bfba6885181,doc\naming_and_structure_audit.md,0,270,"audit, naming, documentation, structure, description, repository, project, locations",1777190302.6204782,1,iactionresult application service unit test business logic backgroundservice dbset compose productservice hosted service appdbcontext price drop httppost postgres httpget fluentassertions notification xunit dockerfile data access periodictimer productscontroller asnotracking igenericrepository httpput arrange act assert postgresql sku iproductrepository threshold container stock iproductservice dbcontext loss entity framework efcore inventory finnhubpricesyncworker item,"naming_and_structure_audit.md | --- description: Audit of repository naming, project locations, and documentatio" -doc,"# Naming & Project Location Audit +### 5.1 Auth — `/api/v1/auth` -## Canonical Naming Standard (Recommended) +**POST `/login`** +- **Request**: `{ Username, Password }` +- **200 OK**: `AuthResponse` — `{ AccessToken, ExpiresAt }`. Refresh token set as `httpOnly` cookie. +- **401**: ""Invalid username or password."" +- **429**: ""Login rate limit exceeded. Try again in 15m."" -Use **one umbrella name** for the repository and solution, and keep **InventoryAlert** as the application/product name. +**POST `/register`** +- **Request**: `{ Username, Password, Email }` +- **200 OK**: `{ Message: ""Registration successful."" }` +- **409**: ""Username or email already in use."" -- **GitHub repo name (canonical):** `InventoryManagementSystem` -- **Local root folder (canonical):** `InventoryManagementSystem` (this workspace root currently contains the `InventoryManagementSystem/` solution folder) -- **.NET solution name:** `InventoryManagementSystem.sln` -- **Application name:** `InventoryAlert` - - Backend projects: `InventoryAlert.Api`, `InventoryAlert.Domain`, `InventoryAlert.Infrastructure`, `InventoryAlert.Worker` - - Test projects: `InventoryAlert.UnitTests`, `InventoryAlert.IntegrationTests`, `InventoryAlert.E2ETests`, `InventoryAlert.ArchitectureTests` - - Frontend app: `InventoryAlert.UI` - - Documentation site: `InventoryAlert.Wiki` +**POST `/refresh`** +- **Request**: No body. Reads `refreshToken` from `httpOnly` cookie. +- **200 OK**: New `AuthResponse` (rotated refresh token set in cookie). +- **401**: ""Refresh token expired or invalid."" -### Visualization +**POST `/logout`** +- **Request**: No body. +- **200 OK**: `{ Message: ""Logged out."" }`. Clears `httpOnly` cookie server-side. -```mermaid -flowchart TB - Repo[""GitHub repo: InventoryManagementSystem""] --> Root[""Local workspace root""] +--- - Root --> Soln[""InventoryManagementSystem/InventoryManagementSystem.sln""] - Root --> UI[""InventoryAlert.UI (Next.js app)""] - Root --> Wiki[""InventoryAlert.Wiki (Docusaurus site)""] - Root --> Docs[""doc/ (internal docs)""] - Root --> Agents["".agents/ (agent tooling + BM25)""] +### 5.2 Portfolio — `/api/v1/portfolio` - Soln --> Api[""InventoryAlert.Api""] - Soln --> Domain[""InventoryAlert.Domain""] - Soln --> Infra[""InventoryAlert.Infrastructure""] - Soln --> Worker[""InventoryAlert.Worker""] - Soln --> Tests[""Tests""] +**GET `/`** +- **Query**: `Page` [int], `PageSize` [int], `Search` [string] +- **200 OK**: `PagedResult` - Tests --> Unit[""InventoryAlert.UnitTests""] - Tests --> IT[""InventoryAlert.IntegrationTests""] - Tests --> E2E[""InventoryAlert.E2ETests""] - Tests --> Arch[""InventoryAlert.ArchitectureTests""] -``` +**GET `/{symbol}`** _(D1: symbol replaces id)_ +- **200 OK**: `PortfolioPositionResponse` +- **404**: ""No position found for symbol '{symbol}'."" -### Why this standard +**GET `/alerts`** +- **200 OK**: `List` -- Prevents “three names for one system” drift (`InventoryManagementSystem` vs `InvestManagementSystem` vs `InventoryAlert`). -- Keeps solution-level naming stable while allowing multiple apps/modules under the umbrella. -- Makes docs and onboarding clearer: umbrella = repo/solution, product = app. +**POST `/`** +- **Request**: `CreatePositionRequest` +- **201 Created**: `PortfolioPositionResponse` +- **409**: ""Symbol already exists in your portfolio."" +- **422**: ""Invalid or unrecognized ticker symbol."" -## Scope +**POST `/bulk`** +- **Request**: `List` +- **200 OK**: `{ Imported: int, Failed: int, Errors: List }` -This document evaluates whether repository naming and file locations match the current solution structure, and records recommended conventions for docs and folders. +**PATCH `/{symbol}/trade`** _(D1 + D2)_ +- **Request**: `TradeRequest` — `Quantity` must always be positive; direction from `Type`. +- **200 OK**: Updated `PortfolioPositionResponse` +- **404**: ""No position found for symbol '{symbol}'."" +- **422**: ""Resulting holdings count cannot be negative."" -## Current Repository Top-Level Layout +**DELETE `/{symbol}`** _(D1)_ +- **200 OK**: `{ Message: ""Position removed."" }` +- **404**: ""No position found for symbol '{symbol}'."" +- **409**: ""Cannot remove a position with active alert rules. Delete rules first."" -| Path | Purpose | Notes | -|---|---|---| -| `.agents/` | Agent workflows/skills/scripts | BM25 tooling lives in `.agents/scripts/core/`. | -| `doc/` | Working internal documentation | Should use YAML frontmatter (see `/doc` skill standard). | -| `InventoryManagementSystem/` | .NET solution root | Contains `InventoryManagementSystem.sln` and all `.csproj`. | -| `InventoryAlert.UI/` | Next.js UI | Frontend app; has its own `package.json`. | -| `InventoryAlert.Wiki/` | Docusaurus documentation site | Built output in `InventoryAlert.Wiki/build` (should remain gitignored). | +> ❗ **Cascade Scope (Critical).** Deleting a portfolio position is a **user-scoped** operation only. It does **NOT** touch any global tables: +> - ✅ **Deleted**: The user's position row + all their `Trade` ledger entries for this symbol. +> - ✅ **Deleted**: The user's `AlertRule` rows for this symbol (must confirm first via 409 guard above). +> - ✅ **Deleted**: The user's `WatchlistItem` for this symbol, if present (auto-cascade). +> - ❌ **NOT deleted**: `StockListing` — global catalog, shared by all users. +> - ❌ **NOT deleted**: `PriceHistory` — global time-series data, never user-owned. +> - ❌ **NOT deleted**: `StockMetric`, `EarningsSurprise`, `RecommendationTrend`, `InsiderTransaction` — market data, never user-owned. +> +> **Rationale**: `StockListing` is the backbone of the symbol database. Removing a position means the user is exiting a trade, not declaring the company no longer exists. -## .NET Solution Structure (`InventoryManagementSystem/`) +--- -**Solution file** -- `InventoryManagementSystem/InventoryManagementSystem.sln` +### 5.3 Stocks — `/api/v1/stocks` -**Projects (observed `.csproj`)** -- `InventoryManagementSystem/InventoryAlert.Api/InventoryAlert.Api.csproj` -- `InventoryManagementSystem/InventoryAlert.Domain/InventoryAlert.Domain.csproj` -- `InventoryManagementSystem/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj` -- `InventoryManagementSystem/InventoryAlert.Worker/InventoryAlert.Worker.csproj` -- `InventoryManagementSystem/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj` -- `InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj` -- `InventoryManagementSystem/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj` -- `InventoryManagementSystem/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj` -- `InventoryManagementSystem/InventoryAlert.Sample/InventoryAlert.Sample.csproj` +**GET `/`** +- **Query**: `Page` [int], `PageSize` [int], `Exchange` [string], `Industry` [string] +- **200 OK**: `PagedResult` -**Naming convention check** -- Project folders use `InventoryAlert.` (PascalCase) and match `.csproj` names: OK. -- Shared kernel is `InventoryAlert.Domain` (not `InventoryAlert.Contracts`): ensure non-archive docs match this. +**GET `/search`** +- **Query**: `q` [string, required] +- **200 OK**: `List` -## Frontend App Structure (`InventoryAlert.UI/`) +**GET `/{symbol}/quote`** +- **200 OK**: `StockQuoteResponse` +- **404**: ""Symbol not found in catalog."" -| Path | Purpose | -|---|---| -| `InventoryAlert.UI/src/` | Next.js app code | -| `InventoryAlert.UI/public/` | Static assets | -| `InventoryAlert.UI/package.json` | Frontend scripts/deps | +**GET `/{symbol}/profile`** +- **200 OK**: `StockProfileResponse` +- **404**: ""Symbol not supported."" -**Naming convention check** -- `InventoryAlert.UI` matches product name and avoids conflicting with `.NET` projects: OK. -- `src/` and `public/` are standard Next.js structure: OK. +**GET `/{symbol}/financials`** _(new)_ +- **200 OK**: `StockMetricResponse` +- **404**: ""Metrics not yet available for this symbol."" -## Wiki Site Structure (`InventoryAlert.Wiki/`) +**GET `/{symbol}/earnings`** _(new)_ +- **200 OK**: `List` (last 4 quarters) +- **404**: ""Earnings data not found."" -| Path | Purpose | -|---|---| -| `InventoryAlert.Wiki/docs/` | Docusaurus docs source (what we should edit) | -| `InventoryAlert.Wiki/sidebars.ts` | Autogenerated sidebar config | -| `InventoryAlert.Wiki/build/` | Generated static site output | +**GET `/{symbol}/recommendation`** _(new)_ +- **200 OK**: `List` (last 3 months) +- **404**: ""Recommendation data not found."" -**Naming convention check** -- `docs/` subfolders use ordered prefixes like `04-execution-flows`: OK for navigation. -- `build/` should remain ignored by Git (see `InventoryAlert.Wiki/.gitignore`): OK. +**GET `/{symbol}/insiders`** _(new)_ +- **200 OK**: `List` (last 100) +- **404**: ""Insider data not found."" -## `doc/` Folder Conventions (Internal Docs) +**GET `/{symbol}/peers`** _(new)_ +- **200 OK**: `PeersResponse` +- **404**: ""Peer list not available."" -Recommended conventions for **new** files: -- Filenames: prefer `snake_case.md` for internal specs/plans (matches existing style like `feature_audit.md`). -- Add YAML frontmatter header to every `doc/*.md` (required by `/doc` workflow). -- Keep anything superseded in `doc/archive/` and treat archive as historical (may contain stale names/paths). +**GET `/{symbol}/news`** _(new)_ +- **Query**: `From` [DateOnly], `To` [DateOnly] +- **200 OK**: `List` -## Known Mismatches / Drift (Observed) +**POST `/sync`** `[Admin]` +- **202 Accepted**: `{ Message: ""Price sync job enqueued."" }` -### 1) Legacy name: `InventoryAlert.Contracts` (archive) +--- -Many files under `doc/archive/` still reference the historical `InventoryAlert.Contracts` project name. This is expected if archive is treated as historical, but should not be used as current guidance. +### 5.4 Market — `/api/v1/market` -**Recommendation** -- Keep `doc/archive/` as-is, but ensure any “active” doc points to `InventoryAlert.Domain`. +**GET `/status`** +- **200 OK**: `List` -### 2) API version label (“v1” vs “v2”) +**GET `/news`** +- **Query**: `Category` [string: general/forex/crypto/merger], `Page` [int] +- **200 OK**: `PagedResult` -API routes in code are prefixed with `/api/v1/...` (controllers use `Route(""api/v1/[controller]"")`). Any doc claiming “v2” should be corrected to avoid confusion. +**GET `/holiday`** _(new)_ +- **Query**: `Exchange` [string, required] +- **200 OK**: `List` -**Recommendation** -- Use “(v1)” in API reference titles unless the API is actually versioned differently. +**GET `/calendar/earnings`** _(new)_ +- **Query**: `From` [DateOnly], `To` [DateOnly], `Symbol` [string?] +- **200 OK**: `List` +- **Note**: Free tier limited to 1-month window. -### 3) Doc links pointing to non-existent files +**GET `/calendar/ipo`** _(new)_ +- **Query**: `From` [DateOnly], `To` [DateOnly] +- **200 OK**: `List` -Internal docs may contain links to planned directories (e.g., `doc/plan/*`) that are not present. This creates review friction. +--- -**Recommendation** -- Keep `doc/README.md` as an index of files that exist *now*. - - Put aspirational plans under `doc/archive/` (or create the actual `doc/plan/` structure if it becomes active work). +### 5.5 Watchlist — `/api/v1/watchlist` -### 4) Legacy product identity remnants (`FinanceAlert` / `InvestManagementSystem` / `finance_*`) +**GET `/`** +- **200 OK**: `List` (live quote merged with listing data) -Some files still contain historical naming that conflicts with the **current product name** (`InventoryAlert`). +**GET `/{symbol}`** +- **200 OK**: `PortfolioPositionResponse` +- **404**: ""Symbol not on your watchlist."" -**Recommendation (preferred approach)** +**POST `/{symbol}`** +- **201 Created**: `PortfolioPositionResponse` +- **409**: ""Symbol already on watchlist."" +- **422**: ""Unrecognized ticker symbol."" -- Do **not** mass-rename everything to `InventoryAlert`. - - Keep the umbrella/repo/solution name stable as `InventoryManagementSystem` (repo + solution root + `InventoryManagementSystem.sln`). - - Keep the product/application identity as `InventoryAlert` (projects + UI + Wiki). -- Do a **targeted rename pass** to replace `FinanceAlert` / `InvestManagementSystem` / `finance_*` remnants with `InventoryAlert` **only where they represent product identity** (docs, docker config labels, service names, JWT issuer/audience labels, etc.). +**DELETE `/{symbol}`** +- **200 OK**: `{ Message: ""Removed from watchlist."" }` +- **404**: ""Symbol not on your watchlist."" -**Observed targets (update to InventoryAlert where appropriate)** +--- -- `InventoryAlert.Wiki/docusaurus.config.ts`: - - `baseUrl: '/InvestManagementSystem/'` - - `projectName: 'InvestManagementSystem'` - - `editUrl` referencing `InvestManagementSystem` -- `InventoryManagementSystem/docker-compose.yml`: - - `POSTGRES_DB: finance_alert_db` - - healthcheck references `finance_alert_db` -- `InventoryManagementSystem/InventoryAlert.Worker/Program.cs`: - - `opts.ServerName = ""finance-worker""` -- `InventoryManagementSystem/InventoryAlert.Api/appsettings.Example.json`: - - `Database:DefaultConnection` uses `finance_alert_db` - - `Jwt:Audience = ""FinanceAlert.Web""` - - `Jwt:Issuer = ""FinanceAlert.Api""` -- `InventoryManagementSystem/InventoryAlert.Worker/appsettings.Example.json`: - - `Database:DefaultConnection` uses `finance_alert_db` -- `InventoryManagementSystem/InventoryAlert.Api/Program.cs`: - - Dev JWT key fallback uses `FinanceAlert_...` +### 5.6 Alert Rules — `/api/v1/alerts` -## BM25 Indexing Scope (Docs) +**GET `/`** +- **200 OK**: `List` -BM25 indexing reads `.agents/scripts/core/bm25_config.json`. +**POST `/`** +- **Request**: `AlertRuleRequest` +- **201 Created**: `AlertRuleResponse` +- **400**: ""TargetValue must be positive."" +- **422**: ""Symbol not recognized."" -**Recommendation** -- Index `InventoryAlert.Wiki/docs` (source docs) rather than `InventoryAlert.Wiki/` (includes irrelevant folders like `build/`, `src/`, etc.). -- Index `doc/` for internal specs and references. +**PUT `/{ruleId}`** +- **Request**: `AlertRuleRequest` +- **200 OK**: `AlertRuleResponse` +- **403**: ""You do not own this rule."" +- **404**: ""Alert rule not found."" -## Summary +**PATCH `/{ruleId}/toggle`** +- **Request**: `ToggleAlertRequest` +- **200 OK**: `AlertRuleResponse` +- **404**: ""Alert rule not found."" -Overall, the repo layout is coherent: -- `.NET` projects are correctly nested under `InventoryManagementSystem/`. -- UI and Wiki are split into their own top-level apps. -- Primary remaining drift is within `doc/archive/` (historical naming like `InventoryAlert.Contracts`) and any leftover “v2” labels in docs.",188,070ec2a92ea03b1425507bfba6885181,doc\naming_and_structure_audit.md,0,271,"inventoryalert, inventorymanagementsystem, wiki, docs, csproj, solution, name, naming",1777190302.6204782,10,iactionresult application service unit test business logic backgroundservice dbset compose productservice hosted service appdbcontext price drop httppost postgres httpget fluentassertions notification xunit dockerfile data access periodictimer productscontroller asnotracking igenericrepository httpput arrange act assert postgresql sku iproductrepository threshold container stock iproductservice dbcontext loss entity framework efcore inventory finnhubpricesyncworker item,# Naming & Project Location Audit | Naming & Project Location Audit Canonical Naming Standard (Recommended) Use one -doc,"--- -description: Central index for logging/tracing/error-handling docs (Seq, CorrelationId, request/response logging). -type: reference -status: active -version: 1.0 -tags: [observability, logging, tracing, seq, inventoryalert] -last_updated: 2026-04-26 ----",9,cb0d813a9994a860907f16d5b9e42a8b,doc\OBSERVABILITY.md,0,272,"logging, tracing, description, central, index, error, handling, docs",1777190302.5948217,1,asnotracking loss periodictimer price drop backgroundservice threshold efcore notification hosted service finnhubpricesyncworker dbcontext entity framework appdbcontext,"OBSERVABILITY.md | --- description: Central index for logging/tracing/error-handling docs (Seq, Cor" -doc,"# Observability (Central) +**DELETE `/{ruleId}`** +- **200 OK**: `{ Message: ""Alert rule deleted."" }` +- **403**: ""You do not own this rule."" +- **404**: ""Alert rule not found."" -This page centralizes the “how we observe/debug the system” guidance. +--- -## Core docs +### 5.7 Notifications — `/api/v1/notifications` -- `doc/LOGGING_REVIEW.md` — logging architecture review + request/response logging recommendations. -- `doc/error_handling_and_response_standard.md` — API error response + status code standardization. -- `doc/worker_jobs_and_event_flow_review.md` — Worker jobs + event flow review and hardening plan. +**GET `/`** +- **Query**: `OnlyUnread` [bool, default false], `Page` [int] +- **200 OK**: `PagedResult` — ordered by `CreatedAt DESC`. -## Can we log UI to Seq? +**GET `/unread-count`** +- **200 OK**: `{ Count: int }` — used by UI navbar bell badge. -Yes, but choose the source carefully: +**PATCH `/{id}/read`** +- **200 OK**: `{ Message: ""Marked as read."" }` +- **404**: ""Notification not found."" -### 1) Next.js server-side logs (recommended) +**PATCH `/read-all`** +- **200 OK**: `{ Updated: int }` -For logs produced on the server (API routes, server actions, SSR), you can send logs to Seq directly from Node **without exposing the Seq API key to browsers**. +**DELETE `/{id}`** +- **200 OK**: `{ Message: ""Notification dismissed."" }` +- **404**: ""Notification not found."" -### 2) Browser/client logs (use a proxy) +> **C1 note**: `LowHoldingsCount` alert evaluation in `LowHoldingsHandler` must join `Trade` ledger filtered by **both** `UserId` AND `TickerSymbol` to compute the correct per-user net holdings. Never evaluate holdings across all users. -Do not ship a Seq ingestion API key in frontend code. +--- -Instead: +### 5.7 Events — `/api/v1/events` `[Admin]` -- UI sends **sanitized** client telemetry/logs to a backend endpoint you own (API). -- API forwards to Seq (adds server-side auth, rate limiting, redaction, and `CorrelationId`). +**POST `/`** +- **Request**: `{ EventType: string, Payload: object }` +- **202 Accepted**: `{ MessageId: string, Status: ""Queued"" }` -### 3) Correlation across UI → API → Worker +**GET `/types`** +- **200 OK**: `[ ""inventoryalert.pricing.price-drop.v1"", ""inventoryalert.inventory.stock-low.v1"", ""inventoryalert.news.headline.v1"" ]` -To make “search the flow by 1 id” work end-to-end: +--- -- UI should propagate `X-Correlation-Id` on outbound requests (or accept it from API responses and reuse it for subsequent calls). -- API stamps `X-Correlation-Id` for every request (already present). -- API must stamp `EventEnvelope.CorrelationId` when publishing async events (required for Worker tracing).",44,cb0d813a9994a860907f16d5b9e42a8b,doc\OBSERVABILITY.md,0,273,"logs, server, worker, correlation, logging, review, request, response",1777190302.5948217,10,asnotracking loss periodictimer price drop backgroundservice threshold efcore notification hosted service finnhubpricesyncworker dbcontext entity framework appdbcontext,# Observability (Central) | Observability (Central) This page centralizes the “how we observe/debug the syst -doc,"--- -description: Working docs for the InventoryAlert solution (specs, plans, references). -type: reference -status: active -version: 1.0 -tags: [documentation, bm25, inventoryalert] -last_updated: 2026-04-26 ----",9,30d78202d87734c568e0659f3ea6ffbd,doc\README.md,0,274,"inventoryalert, description, working, docs, solution, specs, plans, references",1777190302.5973449,1,dockerfile container efcore xunit dbcontext compose threshold fluentassertions finnhubpricesyncworker arrange act assert backgroundservice asnotracking unit test loss periodictimer postgres postgresql entity framework notification appdbcontext price drop hosted service,"README.md | --- description: Working docs for the InventoryAlert solution (specs, plans, ref" -doc,"# InventoryAlert Documentation Index - -This folder contains working documentation for the `InventoryManagementSystem/` solution and related tooling. +## 6. Error Handling -## 🗺️ Roadmap & Strategy -- [ROADMAP.md](ROADMAP.md) — Consolidated task list and project progress. -- [feature_audit.md](feature_audit.md) — Current feature-set audit and consolidation notes. -- [architecture_modernization.md](architecture_modernization.md) — Architecture modernization track and completed refactors. +### Standard Error Response -## 🗄️ Archive -- [archive/](archive/) — Legacy plans, setup commands, and hackathon-specific progress logs. +```json +{ + ""errorCode"": ""string"", + ""userFriendlyMessage"": ""string"", + ""message"": ""string (technical detail — omitted in production)"" +} +``` -## 📚 Wiki & CI +### HTTP Status Code Reference -- [WIKI_REUSE_AND_CI_SYNC.md](WIKI_REUSE_AND_CI_SYNC.md) — Plan to sync `InventoryAlert.Wiki/docs` into the GitHub Wiki repo + suggested CI workflow. +| Code | HTTP Status | Description | +| :--- | :--- | :--- | +| `NotFound` | 404 | Resource (symbol, rule, position) does not exist. | +| `Conflict` | 409 | Duplicate create or locked state conflict. | +| `BadRequest` | 400 | Validation failed or malformed body. | +| `Unauthorized` | 401 | Missing or invalid JWT. | +| `Forbidden` | 403 | Authenticated but lacks ownership of resource. | +| `UnprocessableEntity` | 422 | Semantic error (e.g., negative quantity, bad ticker). | +| `TooManyRequests` | 429 | Rate limit exceeded (login endpoint). | +| `Internal` | 500 | Unhandled server error. | -## 🔭 Observability +--- -- [OBSERVABILITY.md](OBSERVABILITY.md) — Central index (Seq + correlation + error/flow docs). -- [LOGGING_REVIEW.md](LOGGING_REVIEW.md) — Logging review + recommendations. -- [error_handling_and_response_standard.md](error_handling_and_response_standard.md) — Error response/status standardization. -- [worker_jobs_and_event_flow_review.md](worker_jobs_and_event_flow_review.md) — Worker jobs + event-flow review. +## 7. Scheduled Job Catalog Summary -## 🖥️ UI +| Job | Schedule | Tables Affected | Finnhub Source | +| :--- | :--- | :--- | :--- | +| `SyncPricesJob` | `*/15 * * * *` | `PriceHistory`, evaluates `AlertRule` | `/quote` | +| `SyncMetricsJob` | `0 6 * * *` | `StockMetric` | `/stock/metric` | +| `SyncEarningsJob` | `0 7 * * *` | `EarningsSurprise` | `/stock/earnings` | +| `SyncRecommendationsJob` | `0 8 * * 1` | `RecommendationTrend` | `/stock/recommendation` | +| `SyncInsidersJob` | `0 8 * * *` | `InsiderTransaction` | `/stock/insider-transactions` | +| `CompanyNewsJob` | `0 */6 * * *` | DynamoDB `CompanyNews` | `/company-news` | +| `MarketNewsJob` | `0 */2 * * *` | DynamoDB `MarketNews` | `/news` | +| `ProcessQueueJob` | Continuous | — | SQS consumer | +| `SqsScheduledPollerJob` | `*/5 * * * *` | — | SQS fallback | +| `CleanupPriceHistoryJob` | `@daily` (00:00 UTC) | `PriceHistory` (DELETE) | — | -- [UI_TECH_SETUP_AND_FLOW.md](UI_TECH_SETUP_AND_FLOW.md) — UI tech stack, setup, folder structure, rendering flow, and Docker approach (doc-only). -- [UI_COMPONENTS_AND_PAGES_AUDIT.md](UI_COMPONENTS_AND_PAGES_AUDIT.md) — Component/page inventory + enhancement suggestions (paging, UX consistency). +> **D4 — CleanupPriceHistoryJob**: Deletes `PriceHistory` rows where `RecordedAt < NOW() - INTERVAL '1 year'`. Prevents unbounded table growth (est. 35M+ rows/year at 1,000 symbols). Uses a batched delete (`DELETE ... WHERE id IN (SELECT id ... LIMIT 10000)`) to avoid lock contention. -## 🔔 Alerts & Notifications +--- -- [NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md](NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md) — Business flow review + enhancement recommendations. +## 8. SQS Event Handler Catalog -## 🧪 Testing +| Event Type | Payload | Handler | Logic | +| :--- | :--- | :--- | :--- | +| `inventoryalert.pricing.price-drop.v1` | `{ Symbol }` | `PriceAlertHandler` | Quote → cache → `PriceHistory` → evaluate all `AlertRule` for symbol. | +| `inventoryalert.inventory.stock-low.v1` | `{ UserId, TickerSymbol, Threshold }` | `LowHoldingsHandler` | Verify `Trade` ledger count → check `AlertRule[LowHoldingsCount]` → notify if breached. | +| `inventoryalert.news.headline.v1` | `{ Symbol }` | `CompanyNewsHandler` | Sync company news → DynamoDB `CompanyNews`. | +| `*` (unmatched) | — | `DefaultHandler` | Log + acknowledge. Prevents poison-message blockage. | -- [JOBS_INTEGRATION_TEST_PLAN.md](JOBS_INTEGRATION_TEST_PLAN.md) — Integration test plan for jobs/worker, SQS retries/DLQ, and Option C DLQ reprocessor. +--- -> Run `/doc` to synchronize this index with new feature implementations.",46,30d78202d87734c568e0659f3ea6ffbd,doc\README.md,0,275,"flow, index, roadmap, archive, wiki, observability, review, inventoryalert",1777190302.5973449,10,dockerfile container efcore xunit dbcontext compose threshold fluentassertions finnhubpricesyncworker arrange act assert backgroundservice asnotracking unit test loss periodictimer postgres postgresql entity framework notification appdbcontext price drop hosted service,# InventoryAlert Documentation Index | InventoryAlert Documentation Index This folder contains working documentation fo -doc,"--- -description: Project roadmap (planned work, milestones, and priorities). -type: plan -status: active -version: 1.0 -tags: [roadmap, planning, inventoryalert] -last_updated: 2026-04-23 ----",9,f90e807d257d8050190c23e82ac49f40,doc\ROADMAP.md,0,276,"roadmap, description, project, planned, work, milestones, priorities, type",1776910224.0065036,1,application service iunitofwork productservice efcore productscontroller times once savechanges httpget appdbcontext httppost entity framework verify fluentassertions dbcontext compose item igenericrepository iactionresult iproductrepository domain entity commit savechangesasync postgres periodictimer finnhubpricesyncworker inventory hosted service threshold application layer backgroundservice business logic returns async moq iproductservice dbset notification market data executetransactionasync postgresql price drop unitofwork infrastructure sku external api data access domain driven design arrange act assert unit test httpput rollback mock setup loss asnotracking dockerfile container stock quote xunit stock price atomicity,"ROADMAP.md | --- description: Project roadmap (planned work, milestones, and priorities)" -doc,"# 🗺️ Development Roadmap +## 9. UI Plan -> Consolidated from all `TODO` comments across the codebase. -> Each task preserves the original TODO content and is grouped by theme, ordered by priority. +> **Stack**: Next.js (App Router) + TypeScript + Tailwind CSS. State: React Query (server state) + Zustand (UI state). Charts: Recharts. --- -## 🔴 P0 — Critical / Blocking (Do First) - -### 1. Docker & Containerization ✅ - -> **Source:** `ProductController.cs:L96` — _important high priority_ +### 9.1 Page Inventory -~~Setup docker and containerization for the application.~~ **✅ Complete.** See `SETUP_COMMANDS.md` and `EVENT_DRIVEN_PLAN.md` for full implementation details. +| Route | Page Name | Auth | Description | +| :--- | :--- | :--- | :--- | +| `/login` | Login | Public | JWT authentication form. | +| `/register` | Register | Public | New account creation. | +| `/dashboard` | Dashboard | ✅ | Overview: portfolio summary card, watchlist strip, market status, top news. | +| `/portfolio` | Portfolio | ✅ | Full paginated position list with search/filter. | +| `/portfolio/[id]` | Position Detail | ✅ | Deep-dive: price chart, trade history, alert rules for one position. | +| `/stocks` | Stocks Catalog | ✅ | Browse/search global `StockListing` catalog with filters. | +| `/stocks/[symbol]` | Stock Detail | ✅ | Quote, profile, financials, earnings chart, recommendation gauge, insider table, news, peers. | +| `/watchlist` | Watchlist | ✅ | Live watchlist with quick-add via symbol search. | +| `/alerts` | Alert Rules | ✅ | CRUD interface for all user alert rules with active/inactive toggle. | +| `/market` | Market Overview | ✅ | Exchange status, market news feed, earnings calendar, IPO calendar. | -- [x] Create `Dockerfile` (multi-stage build) -- [x] Create `docker-compose.yml` (api + postgres + redis + moto + moto-init + worker) -- [x] Externalize config via `appsettings.Docker.json` (not inline env vars) -- [x] Moto init script (`SolutionFolder/moto-init/init-sqs.sh`) auto-creates SNS/SQS on boot +--- -### 2. Global Exception Handling & Error Responses +### 9.2 Shared Component Library -> **Source:** `ProductController.cs:L79,L89,L91` +#### Navigation -Implement a global exception handling mechanism (middleware or filters) to catch unhandled exceptions and return consistent, user-friendly JSON error responses. Use custom exceptions (`NotFoundException`, `ValidationException`) to represent different error types. Return appropriate HTTP status codes (400, 404, 500) with error codes. Ensure sensitive information is not exposed. Keep it simple and easy to understand for junior developers. +| Component | Location | Description | +| :--- | :--- | :--- | +| `Navbar` | Layout | Top bar: logo, nav links, user avatar menu, notification bell, search bar trigger. | +| `Sidebar` | Layout (desktop) | Collapsible left nav: Dashboard, Portfolio, Watchlist, Stocks, Alerts, Market. | +| `MarketStatusBanner` | Layout (top) | Color-coded strip: exchange name + open/closed state. Polls `GET /market/status` every 60s. | +| `GlobalSearch` | Navbar | Cmd+K search modal. Uses DB-first symbol discovery flow. Shows results as user types (debounce 300ms). | -- [x] Create custom exception classes (`NotFoundException`, `ValidationException`) -- [x] Implement `ExceptionHandlingMiddleware` -- [x] Standardize error response format (`{ code, message, details }`) +#### Market Data Widgets -### 3. Logging Strategy +| Component | Used On | API | Description | +| :--- | :--- | :--- | :--- | +| `StockQuoteCard` | Dashboard, Stock Detail, Watchlist | `GET /stocks/{symbol}/quote` | Price, change, change%, high, low. Refreshes every 30s. | +| `PriceLineChart` | Portfolio Detail, Stock Detail | `PriceHistory` (local) | Recharts `AreaChart`. Supports 1D / 1W / 1M / 3M / 1Y range selector. | +| `EarningsBarChart` | Stock Detail | `GET /stocks/{symbol}/earnings` | Grouped bar: actual vs. estimate EPS per quarter. Color-coded surprise (green/red). | +| `RecommendationDonut` | Stock Detail | `GET /stocks/{symbol}/recommendation` | Recharts `PieChart` — Strong Buy / Buy / Hold / Sell / Strong Sell slices. | +| `MetricsPanel` | Stock Detail | `GET /stocks/{symbol}/financials` | Grid of KPI chips: P/E, P/B, EPS, DividendYield, 52w High/Low, Revenue Growth, Net Margin. | +| `InsiderTable` | Stock Detail | `GET /stocks/{symbol}/insiders` | Sortable table: Name, Date, Shares, Value, Code badge. | +| `PeersChipRow` | Stock Detail | `GET /stocks/{symbol}/peers` | Clickable symbol chips. Click navigates to `/stocks/[symbol]`. | +| `StockProfileHeader` | Stock Detail | `GET /stocks/{symbol}/profile` | Logo + name + exchange + industry + website link + market cap. | -> **Source:** `ProductController.cs:L81,L91` +#### Portfolio Components -Implement comprehensive logging using Serilog or NLog. Log important events (product creation, updates, deletions) and errors with appropriate log levels (Information, Warning, Error). Include contextual information (product ID, user ID). Configure multiple sinks (console, file, database). +| Component | Used On | API | Description | +| :--- | :--- | :--- | :--- | +| `PortfolioSummaryCard` | Dashboard, Portfolio | `GET /portfolio/` | Net portfolio value, total return ($ + %), day P&L, positions count. | +| `PositionTable` | Portfolio | `GET /portfolio/` (paged) | Sortable, searchable table of open positions. Columns: Symbol, Holdings, Avg Price, Current Price, Market Value, Return %, Alert Badge. | +| `PositionRow` | Portfolio | — | Single row of `PositionTable`. Inline sparkline mini-chart. | +| `PositionDetailPanel` | Portfolio Detail | `GET /portfolio/{id}` | Full position breakdown: cost basis, unrealized P&L, trade history timeline. | +| `TradeModal` | Portfolio, Portfolio Detail | `PATCH /portfolio/{id}/trade` | Modal form: Type (Buy/Sell/Dividend/Split), Quantity, Unit Price, Notes, Date. | +| `AddPositionModal` | Portfolio | `POST /portfolio/` | Symbol search (uses discovery flow) → quantity/price form → submit. | +| `BulkImportModal` | Portfolio | `POST /portfolio/bulk` | CSV drag-and-drop → preview table → confirm import with error summary. | +| `AlertBadge` | PositionRow, PositionDetail | `GET /portfolio/alerts` | Red badge on positions that have breached their `AlertRule`. | -> **Note:** `FinnhubSyncWorker` logging should be addressed here but the worker itself is planned for **retirement** once `SyncPricesJob` in `InventoryAlert.Worker` is live (see `EVENT_DRIVEN_PLAN.md` — Phase C). +#### Watchlist Components -- [x] Install and configure Serilog (Api + Worker) -- [x] Add structured logging to `ProductService` via `ILogger` -- [x] `CorrelationIdMiddleware` — stamps all requests and logs with `X-Correlation-Id` -- [x] `FinnhubSyncWorker` retired — `SyncPricesJob` in Worker owns price sync +| Component | Used On | API | Description | +| :--- | :--- | :--- | :--- | +| `WatchlistCard` | Watchlist | `GET /watchlist/` | Compact card: logo, symbol, price, day change%, add-to-portfolio button. | +| `WatchlistAddBar` | Watchlist | `POST /watchlist/{symbol}` | Inline symbol search input. Uses DB-first discovery. Pins new item on success. | +| `WatchlistEmptyState` | Watchlist | — | Illustrated empty state with a CTA to search for stocks. | ---- +#### Alert Rule Components -## 🟠 P1 — Architecture & Code Quality +| Component | Used On | API | Description | +| :--- | :--- | :--- | :--- | +| `AlertRuleTable` | Alerts | `GET /alerts/` | Full list of rules. Columns: Symbol, Condition, Target, Status, Last Triggered, Actions. | +| `AlertRuleForm` | Alerts, Portfolio Detail | `POST /alerts/`, `PUT /alerts/{id}` | Symbol search → Condition dropdown → Target value input → TriggerOnce checkbox. | +| `AlertToggle` | AlertRuleTable | `PATCH /alerts/{ruleId}/toggle` | Inline toggle switch. Optimistic UI update. | -### 4. Thin Controller / Service Layer Refactoring +#### Market Overview Components -> **Source:** `ProductController.cs:L59` +| Component | Used On | API | Description | +| :--- | :--- | :--- | :--- | +| `NewsFeedCard` | Dashboard, Market | `GET /market/news`, `GET /stocks/{symbol}/news` | Headline, source, timestamp, image thumbnail. Links to original article. | +| `NewsFeed` | Dashboard, Market, Stock Detail | — | Virtualised scrollable list of `NewsFeedCard`. Supports category filter tabs. | +| `EarningsCalendarTable` | Market | `GET /market/calendar/earnings` | Date-grouped table: Symbol, EPS Estimate, EPS Actual (colour-coded post-release). | +| `IpoCalendarTable` | Market | `GET /market/calendar/ipo` | Upcoming IPOs: Symbol, Name, Price Range, Date, Status badge. | +| `HolidayList` | Market | `GET /market/holiday` | Exchange selector dropdown → sorted list of upcoming market holidays. | +| `ExchangeStatusGrid` | Dashboard, Market | `GET /market/status` | Grid of exchange cards (NYSE, NASDAQ, LSE…): open/closed indicator + local time. | -All the logic should be in the service layer. Move remaining logic to service layer and make the controller thin and simple, just for handling HTTP request and response. +--- -**Current violation — `UpdateProductStockCount` (L49-L57):** -The PATCH endpoint fetches the product, mutates it, then calls update — this logic belongs in the service. +### 9.3 Page-Level API Map -- [x] Create `UpdateStockCountAsync(int id, int stockCount)` in `IProductService` -- [x] Move PATCH logic from controller to service -- [x] Controller should only call service and return result +#### Dashboard (`/dashboard`) -### 5. RESTful API Design Review +``` +GET /portfolio/ → PortfolioSummaryCard (aggregate values) +GET /watchlist/ → WatchlistStrip (first 5 items) +GET /market/status → MarketStatusBanner + ExchangeStatusGrid +GET /market/news?category=general&page=1 → NewsFeed (top 10) +GET /portfolio/alerts → AlertBadge counts in summary +``` -> **Source:** `ProductController.cs:L30,L49,L72,L85,L86,L87,L88` +#### Portfolio (`/portfolio`) -Review the design of the API endpoints to follow RESTful principles more closely: +``` +GET /portfolio/?page=&search= → PositionTable (paged) +GET /portfolio/alerts → AlertBadge overlay per row +PATCH /portfolio/{id}/trade → TradeModal submit +POST /portfolio/ → AddPositionModal submit (after symbol discovery) +POST /portfolio/bulk → BulkImportModal submit +DELETE /portfolio/{id} → Confirm delete → reload table +``` -| Current Issue | Fix | -| --------------------------------------------------------- | ------------------------------------------- | -| `HttpGet(""{id}"")` uses `[FromQuery]` but route has `{id}` | Use `[FromRoute]` or remove route param | -| `HttpPatch` has no route param for ID | Change to `HttpPatch(""{id}"")` | -| `HttpDelete` has no route param for ID | Change to `HttpDelete(""{id}"")` | -| `CreateProduct` returns `200 OK` | Return `201 Created` | -| `GetProductsByIds` name is misleading (single ID) | Rename to `GetProductById` | -| Method/endpoint naming inconsistency | Use verbs for actions + nouns for resources | +#### Position Detail (`/portfolio/[id]`) -- [x] Fix route parameter binding — all endpoints use `[FromRoute]` -- [x] Return correct HTTP status codes (`201 Created`, `204 NoContent`, `404 NotFound`) -- [x] Rename methods — `GetProductById`, `UpdateStockCount`, `GetPriceLossAlerts` -- [x] Kept entity name as `Product` — domain language matches business context (no rename needed) +``` +GET /portfolio/{id} → PositionDetailPanel + header +GET /stocks/{symbol}/quote → StockQuoteCard (live price) +[local PriceHistory data] → PriceLineChart (from API response) +GET /alerts/?symbol= → AlertRuleTable (scoped to position) +PATCH /portfolio/{id}/trade → TradeModal +POST /alerts/ → AlertRuleForm (create for this position) +``` -### 6. Unit of Work Pattern Review +#### Stock Detail (`/stocks/[symbol]`) -> **Source:** `UnitOfWork.cs:L5`, `ProductServices.cs:L62` +``` +GET /stocks/{symbol}/quote → StockQuoteCard +GET /stocks/{symbol}/profile → StockProfileHeader +GET /stocks/{symbol}/financials → MetricsPanel +GET /stocks/{symbol}/earnings → EarningsBarChart +GET /stocks/{symbol}/recommendation → RecommendationDonut +GET /stocks/{symbol}/insiders → InsiderTable +GET /stocks/{symbol}/peers → PeersChipRow +GET /stocks/{symbol}/news → NewsFeed (company-scoped) +[PriceHistory from quote response] → PriceLineChart +``` -Review the UnitOfWork pattern. Current concern: ""I just want to reach rollback when scaling up with more tables. If fail when inserting one table, rollback the whole thing. Should we keep UnitOfWork or use a simpler implementation?"" +#### Market (`/market`) -**Verdict:** Keep UnitOfWork. It provides transaction safety for multi-table operations. For single-table operations, it adds minimal overhead since EF Core's `SaveChanges` is already atomic. +``` +GET /market/status → ExchangeStatusGrid +GET /market/news?category=&page= → NewsFeed (paginated, filterable) +GET /market/calendar/earnings → EarningsCalendarTable +GET /market/calendar/ipo → IpoCalendarTable +GET /market/holiday?exchange= → HolidayList +``` -- [x] Audit all service methods for consistent UnitOfWork usage -- [x] Ensure `ExecuteTransactionAsync` wraps only multi-step operations -- [x] Document when to use `UnitOfWork` vs plain `SaveChangesAsync` +--- -### 7. Program.cs Organization +### 9.4 Key User Flows -> **Source:** `Program.cs:L15,L34` +#### Flow 1: Add Stock to Portfolio (Symbol Not Yet in DB) -Review and enhance the `Program.cs` design. Use extension methods to organize the code and make it more readable and maintainable. Move static file names to constants. +```mermaid +sequenceDiagram + actor User + participant UI as Frontend + participant API as InventoryAlert.Api + participant DB as PostgreSQL + participant FH as Finnhub -- [x] Create `ServiceCollectionExtensions.AddInfrastructure()` -- [x] Create `ServiceCollectionExtensions.AddApplication()` -- [x] Extract magic strings to a `Constants` class + User->>UI: Types ""NVDA"" in AddPositionModal search + UI->>API: GET /stocks/search?q=NVDA + API->>DB: SELECT FROM StockListing WHERE TickerSymbol ILIKE 'NVDA' + DB-->>API: 0 rows + API->>FH: GET /stock/profile2?symbol=NVDA + FH-->>API: Company profile data + API->>DB: INSERT INTO StockListing (NVDA data) + API-->>UI: SymbolSearchResponse (NVDA) + UI->>User: Shows NVDA in results + User->>UI: Selects NVDA, enters Quantity + Price, submits + UI->>API: POST /portfolio/ { TickerSymbol: NVDA, ... } + API-->>UI: 201 PortfolioPositionResponse + UI->>User: Position added. Navigate to /portfolio +``` -### 8. Stock & Market Data Service Implementation ✅ +#### Flow 2: Alert Trigger (Price Drop) -> **Source:** USER Request — **Completed 2026-04-07** +```mermaid +sequenceDiagram + participant Hangfire as SyncPricesJob (15 min) + participant API as InventoryAlert.Api + participant DB as PostgreSQL + participant SQS as AWS SQS + participant Redis as Redis (cooldown) + participant Handler as PriceAlertHandler + participant UI as Frontend -Implement a comprehensive service for orchestrated stock, market, and crypto data fetching with multi-layer caching (Redis + Postgres). + Hangfire->>API: Execute SyncPricesJob + API->>DB: SELECT all TickerSymbols from StockListing + loop For each symbol + API->>Finnhub: GET /quote + API->>DB: INSERT INTO PriceHistory + API->>DB: Check AlertRule for this symbol + alt Rule breached + API->>Redis: Check cooldown key (24h window) + Redis-->>API: Not in cooldown + API->>SQS: Publish inventoryalert.pricing.price-drop.v1 + end + end + SQS->>Handler: Consume event + Handler->>Redis: SET cooldown key (24h TTL) + Handler-->>UI: Push notification to user +``` -- [x] Create `IStockDataService` and `StockDataService` -- [x] Implement Redis-first caching for Quotes, Peers, Market Status -- [x] Implement DB-first caching for Company Profiles -- [x] Full coverage for News, Recommendations, Earnings, and Calendars -- [x] Crypto exchange and symbol support +#### Flow 3: Global Symbol Search (Navbar) + +```mermaid +flowchart LR + A([User types in GlobalSearch]) --> B[Debounce 300ms] + B --> C[GET /stocks/search?q=query] + C --> D{DB hit?} + D -- Yes --> E([Render results from DB]) + D -- No → Finnhub --> F{Finnhub has it?} + F -- Yes --> G[Persist to StockListing] + G --> E + F -- No --> H([Show: No results found]) + E --> I{User clicks result} + I --> J([Navigate to /stocks/symbol]) +``` --- -## 🟡 P2 — Data Integrity & Validation +### 9.5 State Management Strategy -### 8. Input Validation +| Concern | Tool | Rationale | +| :--- | :--- | :--- | +| Server data (quotes, portfolio, news) | React Query | Auto-refresh, stale-while-revalidate, cache invalidation on mutations. | +| UI state (modals, selected tab, filters) | Zustand | Lightweight, no boilerplate, easy DevTools. | +| Auth token | `httpOnly` cookie | Secure; never exposed to `localStorage`. | +| Optimistic updates | React Query `onMutate` | Used for alert toggles, watchlist add/remove — feels instant. | +| Quote polling | React Query `refetchInterval: 30_000` | Only active when tab is visible (`refetchIntervalInBackground: false`). | -> **Source:** `ProductController.cs:L71,L87` +--- -Add validation for input data using FluentValidation or Data Annotations. Ensure data being processed is valid and provide meaningful error messages when validation fails. Review use of data annotations or validation attributes on DTOs. +## 10. Request Validation -- [x] Install `FluentValidation.AspNetCore` -- [x] Create `ProductRequestDtoValidator` -- [x] Register validators in DI -- [x] Return `400 Bad Request` with validation details +> All validation is enforced at the **Web layer** using `FluentValidation`. The Application layer trusts that inputs have already been validated. Controllers must not contain inline `if` checks. -### 9. DTO Design Review +### 10.1 Validation Rules by DTO -> **Source:** `ProductController.cs:L74,L76`, `ProductServices.cs:L40` +#### `LoginRequest` -Review `ProductDto` and `ProductRequestDto`. Separate the properties required for creating vs updating. Rename `GetHighValueProducts` to something more descriptive like `GetSignificantLossProducts`. The update method should use the ID from the route, not the body. +| Field | Rule | +| :--- | :--- | +| `Username` | `NotEmpty`. `MaxLength(50)`. | +| `Password` | `NotEmpty`. `MinLength(6)`. `MaxLength(100)`. | -**Current state:** `ProductRequestDto` (create/update) and `ProductDto` (response) are already separated. ✅ +#### `RegisterRequest` -- [x] `UpdateProductAsync` always uses route ID (body ID ignored) -- [x] Renamed `GetHighValueProducts` → `GetPriceLossAlertsAsync` -- [x] Renamed endpoint `low-stock` → `price-alerts` +| Field | Rule | +| :--- | :--- | +| `Username` | `NotEmpty`. `MaxLength(50)`. `Matches(^[a-zA-Z0-9_]+$)` — alphanumeric + underscore only. | +| `Password` | `NotEmpty`. `MinLength(8)`. Must contain at least 1 uppercase, 1 digit, 1 special character. | +| `Email` | `NotEmpty`. `EmailAddress()`. `MaxLength(200)`. | -### 10. Null Handling in Finnhub Responses +#### `CreatePositionRequest` -> **Source:** `ProductServices.cs:L107` +| Field | Rule | +| :--- | :--- | +| `TickerSymbol` | `NotEmpty`. `MaxLength(10)`. `Matches(^[A-Z0-9.]+$)` — uppercase ticker format. | +| `Quantity` | `GreaterThan(0)`. No fractional shares below 0.001. | +| `UnitPrice` | `GreaterThan(0)`. `LessThan(1_000_000)`. | +| `TradedAt` | Optional. If provided: `LessThanOrEqualTo(DateTime.UtcNow)`. Cannot be in the future. | -Should we check if the price is null before assigning it to `CurrentPrice`? Or should we set the current price to 0 if the price is null? +#### `TradeRequest` -**Recommendation:** Skip the product entirely if the price is null. Setting it to 0 would trigger false loss alerts. +| Field | Rule | +| :--- | :--- | +| `Type` | `NotNull`. Must be a valid `TradeType` enum value. | +| `Quantity` | `GreaterThan(0)`. For `Sell`: service validates resulting holdings ≥ 0 (422). | +| `UnitPrice` | `GreaterThan(0)`. Required for `Buy`/`Sell`. Optional (set 0) for `Dividend`/`Split`. | +| `Notes` | Optional. `MaxLength(500)`. | -- [x] `quote?.CurrentPrice is null or 0` → `continue` when null (ProductService + SyncPricesJob) -- [x] Warning logged when a symbol returns null or zero price +#### `AlertRuleRequest` -### 11. BulkInsert Response Design +| Field | Rule | +| :--- | :--- | +| `TickerSymbol` | `NotEmpty`. `MaxLength(10)`. | +| `Condition` | `NotNull`. Must be valid `AlertCondition` enum. | +| `TargetValue` | `GreaterThan(0)`. For `LowHoldingsCount`: must be a whole number (no decimals). | +| `TriggerOnce` | Required boolean. | -> **Source:** `ProductServices.cs:L71` +#### `AlertRuleRequest` — Condition-Specific Cross-Field Rules -Should we return the list of created products or just the count? +| Condition | Extra Validation | +| :--- | :--- | +| `PriceAbove`, `PriceBelow`, `PriceTargetReached` | `TargetValue` must be a monetary value > 0. | +| `PercentDropFromCost` | `TargetValue` must be between `0.01` and `100.00`. | +| `LowHoldingsCount` | `TargetValue` must be a positive integer (whole number). | -**Recommendation:** Return `204 No Content` or the count. Returning thousands of full objects wastes bandwidth. +### 10.2 Validation Error Format -- [x] `BulkInsertProducts` returns `204 No Content` -- [x] No body returned — bandwidth optimized +FluentValidation's failure map is surfaced as a `400 Bad Request` using the standard error body: + +```json +{ + ""errorCode"": ""BadRequest"", + ""userFriendlyMessage"": ""One or more validation errors occurred."", + ""errors"": { + ""TickerSymbol"": [""TickerSymbol must not be empty.""], + ""Quantity"": [""Quantity must be greater than 0.""] + } +} +``` + +> **Implementation note**: Register validators via `services.AddValidatorsFromAssemblyContaining()` + add `FluentValidation.AspNetCore` filter globally so no controller has to call `.Validate()` manually. --- -## 🏗️ P2 — Modernization & UI (New) +## 11. Database Configuration -### 12. Next.js 15 Web Dashboard ✅ - - > **Source:** USER Request — **Completed 2026-04-07** - - - [x] Create `InventoryAlert.UI` project (Next.js 15 + Tailwind CSS) - - [x] Implement modern dark-themed UI with glassmorphism - - [x] Routes: Market Explorer, Price Alerts, Portfolio, Symbol Details - - [x] Integrated with `StocksController` via `StockDataService` - - [x] **UI Test stabilization** — Added Vitest unit and component tests to satisfy CI/CD - - [ ] Replace static chart placeholders with functional **Recharts** implementations - - [ ] Implement Next.js Route Handlers for secure API proxying +### 11.1 PostgreSQL — EF Core +#### Connection -### 13. Shared Project — `InventoryAlert.Domain` ✅ (Already Exists) +```json +// appsettings.Example.json +{ + ""ConnectionStrings"": { + ""DefaultConnection"": ""Host=localhost;Port=5432;Database=inventoryalert;Username=postgres;Password=YOUR_PASSWORD;Include Error Detail=true"" + } +} +``` -> **Note:** `InventoryAlert.Domain` **already exists** as the shared project. -> Both `InventoryAlert.Api` and `InventoryAlert.Worker` reference it via `` — **no new project needed**. -> The tasks below are **enhancements** to the existing shared project. -> -> **Invariant:** `InventoryAlert.Domain` is the single source of truth for every type that crosses a service boundary. No entity or payload may be defined in both `Api` and `Worker`. +#### `AppDbContext` — Key Table Configurations -#### What the Shared Project Must Own +| Entity | Table Name | Key Config | +| :--- | :--- | :--- | +| `User` | `users` | `Id` (Guid, default `gen_random_uuid()`). Unique index on `Username` + `Email`. | +| `StockListing` | `stock_listings` | `Id` (int, serial). Unique index on `TickerSymbol`. | +| `WatchlistItem` | `watchlist_items` | Composite PK `(UserId, TickerSymbol)`. FK cascade delete on User. | +| `AlertRule` | `alert_rules` | `Id` (Guid). FK cascade delete on User. Index on `(TickerSymbol, IsActive)`. | +| `Trade` | `trades` | `Id` (Guid). FK cascade delete on User. Index on `(UserId, TickerSymbol, TradedAt DESC)`. | +| `PriceHistory` | `price_history` | `Id` (bigserial). Index on `(TickerSymbol, RecordedAt DESC)`. No FK cascade — global data. | +| `StockMetric` | `stock_metrics` | `TickerSymbol` (string PK). 1-to-1 with `StockListing`. | +| `EarningsSurprise` | `earnings_surprises` | `Id` (int, serial). Unique constraint on `(TickerSymbol, Period)`. | +| `RecommendationTrend` | `recommendation_trends` | `Id` (int, serial). Unique constraint on `(TickerSymbol, Period)`. | +| `InsiderTransaction` | `insider_transactions` | `Id` (int, serial). Index on `(TickerSymbol, TransactionDate DESC)`. | -| Category | Current State | Target | -| :-------------------------------------------- | :--------------------------------------------------- | :--------------------------------- | -| Domain entities (`Product`, `EventLog`, …) | ✅ In `Contracts/Entities/` | Keep — verified | -| Event payloads (`MarketPriceAlertPayload`, …) | ✅ In `Contracts/Events/Payloads/` | Keep — verified | -| `EventEnvelope` | ✅ Updated — `EventType`, `Payload`, `CorrelationId` | Keep | -| `EventTypes` constants | ✅ Reverse-DNS naming applied | Keep | -| App-wide constants (cache keys, SQS headers) | ✅ In `Contracts/Constants/` | Keep | -| Shared configuration models | ❌ Duplicated per project | Move to `Contracts/Configuration/` | +#### Migration Naming Convention -#### Build Tasks +``` +Verb + Entity + Detail +Examples: + InitialCreate + AddStockListingTable + RenameProductToStockListing + AddTradeTable + AddStockMetricAndEarningsTable + AddInsiderTransactionTable +``` -- [x] Entities centralized: `Product`, `EventLog`, `EarningsRecord`, `InsiderTransaction`, `NewsRecord` -- [x] `global using` aliases in `Api/Domain/Entities/SharedEntityAliases.cs` for backward compat -- [x] `global using` aliases in `Worker/SharedEntityAliases.cs` for backward compat -- [x] `Constants/AlertConstants.cs` — `CacheKeys`, `EventTypes`, `SqsHeaders` centralized -- [x] `Events/EventEnvelope.cs` — standardized envelope with `CorrelationId` + `Source` -- [x] `Events/EventTypes.cs` — reverse-DNS format + `IsKnown()` + `IReadOnlySet` -- [x] **Move shared config models** — create `Contracts/Configuration/SharedAwsSettings.cs` and `SharedFinnhubSettings.cs` so both `Api` and `Worker` read from the same schema -- [x] **Add `InventoryAlert.ArchitectureTests`** — use `NetArchTest.Rules` to **enforce** at CI time that: - - `InventoryAlert.Api` has no internal entity definitions - - `InventoryAlert.Worker` has no internal entity definitions - - All event payloads live only in `Contracts` -- [x] **NuGet packaging (future)** — if a 3rd service (e.g. `InventoryAlert.Sample`) is added, package `Contracts` as a private NuGet feed artifact so versioning is explicit +Run from solution root: +```powershell +dotnet ef migrations add \ + --project InventoryAlert.Api \ + --startup-project InventoryAlert.Api -#### Reference Architecture +dotnet ef database update \ + --project InventoryAlert.Api \ + --startup-project InventoryAlert.Api +``` -```text -InventoryAlert.Domain/ ← shared library, referenced by all -├── Entities/ ← EF-mapped domain entities -├── Events/ -│ ├── EventEnvelope.cs ← envelope contract -│ ├── EventTypes.cs ← canonical type registry -│ └── Payloads/ ← one file per event type -├── Constants/ -│ └── AlertConstants.cs ← CacheKeys, SqsHeaders, defaults -└── Configuration/ ← PLANNED: shared config POCOs - ├── SharedAwsSettings.cs - └── SharedFinnhubSettings.cs - -InventoryAlert.Api/ - └── Domain/Entities/SharedEntityAliases.cs ← global using only +### 11.2 DynamoDB — Configuration -InventoryAlert.Worker/ - └── SharedEntityAliases.cs ← global using only +```json +// appsettings.Example.json +{ + ""AWS"": { + ""Region"": ""ap-southeast-1"", + ""DynamoDB"": { + ""MarketNewsTable"": ""inventoryalert-market-news"", + ""CompanyNewsTable"": ""inventoryalert-company-news"", + ""ServiceURL"": ""http://localhost:8000"" // local only; remove for production + } + } +} ``` ---- - -## 📂 P3 — Logging & Observability (New) - -### 14. Centralized Logging (Serilog) ✅ - -> **Source:** USER Request — **Completed 2026-04-05** - -- [x] Serilog bootstrapped in `InventoryAlert.Worker/Program.cs` -- [x] JSON file sink + Console sink (rolling daily, 7-day retention) -- [x] `CorrelationIdMiddleware` tracks requests across Api and Worker -- [x] `MachineName` and `EnvironmentName` enrichers added +#### Table Provisioning (IaC reference) -### 15. Global Exception Strategy ✅ +| Table | PK | SK | GSI | +| :--- | :--- | :--- | :--- | +| `inventoryalert-market-news` | `PK` (S) | `SK` (S) | — | +| `inventoryalert-company-news` | `PK` (S) | `SK` (S) | `BySymbolAndDate` (Symbol, SK) | -> **Source:** USER Request — **Completed 2026-04-05** +> Use `PAY_PER_REQUEST` billing mode. No provisioned throughput required at this scale. -- [x] `ExceptionHandlingMiddleware` refactored for full RFC-7807 compliance (`type`, `instance`, semantic slugs) -- [x] `HangfireJobLoggingFilter` — global job error auditing via `ILogger` -- [x] All domain exceptions (`NotFoundException`, `ValidationException`, `ArgumentException`) mapped to HTTP codes +### 11.3 Redis — Configuration ---- +```json +// appsettings.Example.json +{ + ""Redis"": { + ""ConnectionString"": ""localhost:6379"", + ""InstanceName"": ""inventoryalert:"" + } +} +``` -## 🟢 P4 — Performance & Scalability +#### Key Namespaces -### 12. Caching ✅ +| Key Pattern | TTL | Purpose | +| :--- | :--- | :--- | +| `quote:{symbol}` | 30 seconds | Cached stock quote from Finnhub. | +| `cooldown:alert:{symbol}` | 24 hours | Prevents repeated alerts for same symbol within 24h. | +| `dedup:sqs:{messageId}` | 30 minutes | Idempotency guard for SQS message processing. | +| `finnhub:ratelimit` | Rolling 60s | Sliding window counter. Cap at 55 calls/min. | -> **Source:** `ProductController.cs:L68` +### 11.4 Hangfire — Configuration -Implement caching for frequently accessed data (product details) using in-memory caching or Redis, depending on scale and expected load. +```json +// appsettings.Example.json +{ + ""Hangfire"": { + ""DashboardPath"": ""/hangfire"", + ""SqlServerConnectionString"": ""..."" // or use PostgreSQL storage + } +} +``` -- [x] Add `IMemoryCache` for `GetProductById` -- [x] Add cache invalidation on Update/Delete -- [x] Evaluate Redis if scaling beyond a single instance +> **Security**: Hangfire dashboard must be gated behind `[Authorize(Roles = ""Admin"")]`. Never expose it publicly. -### 13. Pagination ✅ +--- -> **Source:** `ProductController.cs:L73` +## 12. Seed Data -Implement pagination for list endpoints (`GetProducts`). Accept query parameters for page number and page size. Return subset of data with metadata (total items, total pages). +> Seed data is applied in `AppDbContext.OnModelCreating` (or a dedicated `DataSeeder` service invoked at startup) using `modelBuilder.Entity().HasData(...)`. Seeded rows use **fixed Guids** so re-running migrations is idempotent. -- [x] Create `PaginationParams` (PageNumber, PageSize) -- [x] Create `PagedResult` wrapper -- [x] Update `GetAllAsync` in repository to support `Skip/Take` +### 12.1 Users -### 14. Finnhub Sync Design Review -**Verdict:** Keep UnitOfWork. It provides transaction safety for multi-table operations. For single-table operations, it adds minimal overhead since EF Core's `SaveChanges` is already atomic. +```csharp +new User +{ + Id = Guid.Parse(""00000000-0000-0000-0000-000000000001""), + Username = ""admin"", + PasswordHash = """", + Email = ""admin@inventoryalert.dev"", + Role = ""Admin"", + CreatedAt = DateTime.Parse(""2025-01-01T00:00:00Z"") +}, +new User +{ + Id = Guid.Parse(""00000000-0000-0000-0000-000000000002""), + Username = ""demo_user"", + PasswordHash = """", + Email = ""demo@inventoryalert.dev"", + Role = ""User"", + CreatedAt = DateTime.Parse(""2025-01-01T00:00:00Z"") +} +``` -- [x] Audit all service methods for consistent UnitOfWork usage -- [x] Ensure `ExecuteTransactionAsync` wraps only multi-step operations -- [x] Document when to use `UnitOfWork` vs plain `SaveChangesAsync` +### 12.2 StockListings (Global Catalog — 10 Baseline Symbols) -### 7. Program.cs Organization +```csharp +// Seeded to ensure watchlist/alert demos work out-of-the-box. +// Finnhub will enrich these on first SyncPricesJob run. +new StockListing { Id=1, TickerSymbol=""AAPL"", Name=""Apple Inc"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, +new StockListing { Id=2, TickerSymbol=""MSFT"", Name=""Microsoft Corp"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, +new StockListing { Id=3, TickerSymbol=""GOOGL"", Name=""Alphabet Inc"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, +new StockListing { Id=4, TickerSymbol=""AMZN"", Name=""Amazon.com Inc"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Consumer Cyclical"" }, +new StockListing { Id=5, TickerSymbol=""NVDA"", Name=""NVIDIA Corp"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, +new StockListing { Id=6, TickerSymbol=""TSLA"", Name=""Tesla Inc"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Automotive"" }, +new StockListing { Id=7, TickerSymbol=""META"", Name=""Meta Platforms"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, +new StockListing { Id=8, TickerSymbol=""JPM"", Name=""JPMorgan Chase"", Exchange=""NYSE"", Currency=""USD"", Country=""US"", Industry=""Financial Services"" }, +new StockListing { Id=9, TickerSymbol=""V"", Name=""Visa Inc"", Exchange=""NYSE"", Currency=""USD"", Country=""US"", Industry=""Financial Services"" }, +new StockListing { Id=10, TickerSymbol=""BRK.B"", Name=""Berkshire Hathaway"", Exchange=""NYSE"", Currency=""USD"", Country=""US"", Industry=""Financial Services"" }, +``` -> **Source:** `Program.cs:L15,L34` +### 12.3 WatchlistItems (demo_user) -Review and enhance the `Program.cs` design. Use extension methods to organize the code and make it more readable and maintainable. Move static file names to constants. +```csharp +new WatchlistItem { UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), TickerSymbol = ""AAPL"", CreatedAt = DateTime.UtcNow }, +new WatchlistItem { UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), TickerSymbol = ""NVDA"", CreatedAt = DateTime.UtcNow }, +new WatchlistItem { UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), TickerSymbol = ""TSLA"", CreatedAt = DateTime.UtcNow }, +``` -- [x] Create `ServiceCollectionExtensions.AddInfrastructure()` -- [x] Create `ServiceCollectionExtensions.AddApplication()` -- [x] Extract magic strings to a `Constants` class +### 12.4 AlertRules (demo_user) -### 8. Stock & Market Data Service Implementation ✅ +```csharp +new AlertRule +{ + Id = Guid.Parse(""10000000-0000-0000-0000-000000000001""), + UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), + TickerSymbol = ""AAPL"", + Condition = AlertCondition.PriceBelow, + TargetValue = 150.00m, + IsActive = true, + TriggerOnce = false, + CreatedAt = DateTime.Parse(""2025-01-01T00:00:00Z"") +}, +new AlertRule +{ + Id = Guid.Parse(""10000000-0000-0000-0000-000000000002""), + UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), + TickerSymbol = ""TSLA"", + Condition = AlertCondition.PercentDropFromCost, + TargetValue = 15.00m, // Alert if TSLA drops 15% from cost basis + IsActive = true, + TriggerOnce = false, + CreatedAt = DateTime.Parse(""2025-01-01T00:00:00Z"") +} +``` -> **Source:** USER Request — **Completed 2026-04-07** +### 12.5 Trades (demo_user — sample portfolio) -Implement a comprehensive service for orchestrated stock, market, and crypto data fetching with multi-layer caching (Redis + Postgres). +```csharp +new Trade +{ + Id = Guid.NewGuid(), UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), + TickerSymbol = ""AAPL"", Type = TradeType.Buy, + Quantity = 10m, UnitPrice = 172.50m, TradedAt = DateTime.Parse(""2024-11-01T14:30:00Z"") +}, +new Trade +{ + Id = Guid.NewGuid(), UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), + TickerSymbol = ""NVDA"", Type = TradeType.Buy, + Quantity = 5m, UnitPrice = 480.00m, TradedAt = DateTime.Parse(""2024-11-15T10:00:00Z"") +}, +new Trade +{ + Id = Guid.NewGuid(), UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), + TickerSymbol = ""TSLA"", Type = TradeType.Buy, + Quantity = 8m, UnitPrice = 245.00m, TradedAt = DateTime.Parse(""2024-12-01T09:45:00Z"") +}, +new Trade +{ + Id = Guid.NewGuid(), UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), + TickerSymbol = ""TSLA"", Type = TradeType.Sell, + Quantity = 3m, UnitPrice = 410.00m, TradedAt = DateTime.Parse(""2025-01-20T11:00:00Z""), + Notes = ""Partial profit-take after earnings."" +} +``` -- [x] Create `IStockDataService` and `StockDataService` -- [x] Implement Redis-first caching for Quotes, Peers, Market Status -- [x] Implement DB-first caching for Company Profiles -- [x] Full coverage for News, Recommendations, Earnings, and Calendars -- [x] Crypto exchange and symbol support +> **Result**: `demo_user` has a live portfolio of 10 AAPL @ avg $172.50, 5 NVDA @ avg $480, and 5 TSLA @ avg $245. Demonstrates both open positions and a realized-gain sell event. --- -## 🟡 P2 — Data Integrity & Validation - -### 8. Input Validation - -> **Source:** `ProductController.cs:L71,L87` - -Add validation for input data using FluentValidation or Data Annotations. Ensure data being processed is valid and provide meaningful error messages when validation fails. Review use of data annotations or validation attributes on DTOs. - -- [x] Install `FluentValidation.AspNetCore` -- [x] Create `ProductRequestDtoValidator` -- [x] Register validators in DI -- [x] Return `400 Bad Request` with validation details +## 13. Project File Layout -### 9. DTO Design Review +> **Placement Rule**: If a type is used by **both** `InventoryAlert.Api` and `InventoryAlert.Worker`, it belongs in `InventoryAlert.Domain` (the shared project). If it is used by only one, keep it local to that project. -> **Source:** `ProductController.cs:L74,L76`, `ProductServices.cs:L40` +--- -Review `ProductDto` and `ProductRequestDto`. Separate the properties required for creating vs updating. Rename `GetHighValueProducts` to something more descriptive like `GetSignificantLossProducts`. The update method should use the ID from the route, not the body. +### 13.1 `InventoryAlert.Domain` — Shared Contracts -**Current state:** `ProductRequestDto` (create/update) and `ProductDto` (response) are already separated. ✅ +#### `Entities/Postgres/` -- [x] `UpdateProductAsync` always uses route ID (body ID ignored) -- [x] Renamed `GetHighValueProducts` → `GetPriceLossAlertsAsync` -- [x] Renamed endpoint `low-stock` → `price-alerts` +| File | Action | Notes | +| :--- | :--- | :--- | +| `User.cs` | **KEEP** | Add `CreatedAt` property. | +| `Product.cs` | **DELETE** | Replaced by `StockListing.cs`. | +| `StockListing.cs` | **NEW** (rename from `Product.cs`) | Add `Exchange`, `Currency`, `Country`, `MarketCap`, `Ipo`, `WebUrl`, `LastProfileSync`. | +| `WatchlistItem.cs` | **UPDATE** | Remove `IsWatchOnly`. Confirm composite PK `(UserId, TickerSymbol)`. | +| `AlertRule.cs` | **UPDATE** | Add `LastTriggeredAt`, `TriggerOnce`. Update `AlertCondition` enum values. | +| `StockTransaction.cs` | **DELETE** | Replaced by `Trade.cs`. | +| `Trade.cs` | **NEW** (rename from `StockTransaction.cs`) | `Type` enum: `Buy`/`Sell`/`Dividend`/`Split`. `Quantity` always positive. Add `TradedAt`, `Notes`. | +| `PriceHistory.cs` | **UPDATE** | Add `High`, `Low`, `Open`, `PrevClose`. Change PK to `long` (bigserial). | +| `StockMetric.cs` | **NEW** | `TickerSymbol` as PK. All financial metric fields. | +| `EarningsSurprise.cs` | **NEW** | `Period` as `DateOnly` (Finnhub format). Unique on `(TickerSymbol, Period)`. | +| `RecommendationTrend.cs` | **NEW** | Monthly analyst counts. Unique on `(TickerSymbol, Period)`. | +| `InsiderTransaction.cs` | **NEW** | SEC insider filing data. | +| `Notification.cs` | **NEW** | `AlertRuleId?` FK. Index on `(UserId, IsRead, CreatedAt DESC)`. | -### 10. Null Handling in Finnhub Responses +#### `Entities/Dynamodb/` -> **Source:** `ProductServices.cs:L107` +| File | Action | Notes | +| :--- | :--- | :--- | +| `MarketNewsDynamoEntry.cs` | **UPDATE** | Add full attribute schema: `NewsId`, `Headline`, `Summary`, `Source`, `Url`, `Image`, `Category`, `SyncedAt`. | +| `NewsDynamoEntry.cs` | **UPDATE** | Rename to `CompanyNewsDynamoEntry.cs`. Add `Symbol` attribute (for GSI). | -Should we check if the price is null before assigning it to `CurrentPrice`? Or should we set the current price to 0 if the price is null? +#### `DTOs/` -**Recommendation:** Skip the product entirely if the price is null. Setting it to 0 would trigger false loss alerts. +| File | Action | Notes | +| :--- | :--- | :--- | +| `AuthRequests.cs` | **UPDATE** → rename `AuthDTOs.cs` | `AuthResponse`: add `AccessToken`, `ExpiresAt`. Add `RefreshRequest` (empty body — cookie-based). | +| `ProductRequest.cs` | **DELETE** | Replaced by `PortfolioDTOs.cs`. | +| `ProductResponse.cs` | **DELETE** | Replaced by `PortfolioDTOs.cs`. | +| `UpdateStockRequest.cs` | **DELETE** | Merged into `TradeRequest` in `PortfolioDTOs.cs`. | +| `ProductQueryParams.cs` | **DELETE** | Replaced by `PortfolioQueryParams.cs`. | +| `PriceLossResponse.cs` | **DELETE** | Replaced by `PortfolioAlertResponse` in `PortfolioDTOs.cs`. | +| `PortfolioDTOs.cs` | **NEW** | `CreatePositionRequest`, `TradeRequest`, `PortfolioPositionResponse` (`StockId` not `Id`), `PortfolioAlertResponse`, `PortfolioQueryParams`. | +| `AlertRuleDTOs.cs` | **UPDATE** | `AlertRuleResponse` add `LastTriggeredAt`. Update `AlertCondition` enum. Add `ToggleAlertRequest`. | +| `MarketDTOs.cs` | **UPDATE** | Add `StockMetricResponse`, `EarningsSurpriseResponse` (`Period` as `DateOnly`), `RecommendationResponse`, `InsiderTransactionResponse`, `MarketHolidayResponse`, `PeersResponse`. | +| `StockDTOs.cs` | **NEW** | `StockQuoteResponse`, `StockProfileResponse`, `SymbolSearchResponse`. | +| `CalendarDTOs.cs` | **NEW** | `EarningsCalendarResponse`, `IpoCalendarResponse`. | +| `NotificationDTOs.cs` | **NEW** | `NotificationResponse`. | +| `PagedResult.cs` | **KEEP** | No changes. | +| `PaginationParams.cs` | **KEEP** | No changes. | +| `EventDTOs.cs` | **KEEP** | No changes. | -- [x] `quote?.CurrentPrice is null or 0` → `continue` when null (ProductService + SyncPricesJob) -- [x] Warning logged when a symbol returns null or zero price +#### `Interfaces/` -### 11. BulkInsert Response Design +| File | Action | Notes | +| :--- | :--- | :--- | +| `IGenericRepository.cs` | **KEEP** | | +| `IDynamoDbGenericRepository.cs` | **KEEP** | | +| `IUnitOfWork.cs` | **KEEP** | | +| `IRedisHelper.cs` | **KEEP** | | +| `IEventPublisher.cs` | **KEEP** | | +| `IQueueService.cs` | **KEEP** | | +| `ICorrelationProvider.cs` | **KEEP** | | +| `IEventService.cs` | **KEEP** | | +| `IAlertRuleRepository.cs` | **KEEP** | | +| `IAlertRuleService.cs` | **KEEP** | | +| `IUserRepository.cs` | **KEEP** | | +| `IWatchlistItemRepository.cs` | **KEEP** | | +| `IPriceHistoryRepository.cs` | **UPDATE** | Add `DeleteOlderThanAsync(DateTime cutoff, CancellationToken ct)` for cleanup job. | +| `INewsDynamoRepository.cs` | **KEEP** | Rename to `ICompanyNewsDynamoRepository.cs` for clarity. | +| `IMarketNewsDynamoRepository.cs` | **KEEP** | | +| `IFinnhubClient.cs` | **UPDATE** | Add methods: `GetMetricsAsync`, `GetEarningsAsync`, `GetRecommendationsAsync`, `GetInsidersAsync`, `GetPeersAsync`, `GetEarningsCalendarAsync`, `GetIpoCalendarAsync`, `GetMarketHolidayAsync`. | +| `IProductRepository.cs` | **DELETE** | Replaced by `IStockListingRepository.cs`. | +| `IStockListingRepository.cs` | **NEW** (from `IProductRepository.cs`) | CRUD + `FindBySymbolAsync`, `SearchAsync(query)`. | +| `IProductService.cs` | **DELETE** | Replaced by `IPortfolioService.cs`. | +| `IPortfolioService.cs` | **NEW** (from `IProductService.cs`) | All position management methods using `TickerSymbol` routes. | +| `IStockTransactionRepository.cs` | **DELETE** | Replaced by `ITradeRepository.cs`. | +| `ITradeRepository.cs` | **NEW** (from `IStockTransactionRepository.cs`) | `GetByUserAndSymbolAsync`, `GetNetHoldingsAsync(userId, symbol)`. | +| `IStockDataService.cs` | **UPDATE** | Add methods for new Finnhub endpoints. | +| `IAlertNotifier.cs` | **UPDATE** | Signature: `NotifyAsync(Notification notification, CancellationToken ct)`. | +| `IStockMetricRepository.cs` | **NEW** | `UpsertAsync(StockMetric metric, CancellationToken ct)`. | +| `IEarningsSurpriseRepository.cs` | **NEW** | `UpsertRangeAsync(IEnumerable, CancellationToken ct)`. | +| `IRecommendationTrendRepository.cs` | **NEW** | `UpsertRangeAsync`. | +| `IInsiderTransactionRepository.cs` | **NEW** | `ReplaceForSymbolAsync(symbol, entries, CancellationToken ct)`. | +| `INotificationRepository.cs` | **NEW** | CRUD + `GetUnreadCountAsync(userId)`, `MarkAllReadAsync(userId)`. | +| `INotificationService.cs` | **NEW** | `CreateAsync(userId, message, symbol?, alertRuleId?)`, `GetPagedAsync`, `MarkReadAsync`. | -> **Source:** `ProductServices.cs:L71` +#### `Events/` -Should we return the list of created products or just the count? +| File | Action | Notes | +| :--- | :--- | :--- | +| `EventEnvelope.cs` | **KEEP** | | +| `EventTypes.cs` | **KEEP** | Verify 3 event type constants are present. | +| `Payloads/` | **KEEP** | Rename `StockLowAlertPayload` → `LowHoldingsAlertPayload`. | -**Recommendation:** Return `204 No Content` or the count. Returning thousands of full objects wastes bandwidth. +#### `Validators/` -- [x] `BulkInsertProducts` returns `204 No Content` -- [x] No body returned — bandwidth optimized +| File | Action | Notes | +| :--- | :--- | :--- | +| *(existing validators)* | **UPDATE** | Align with renamed DTOs. | +| `CreatePositionRequestValidator.cs` | **NEW** | From `ProductRequestValidator`. | +| `TradeRequestValidator.cs` | **NEW** | From `UpdateStockRequestValidator`. `Quantity > 0` always. | +| `AlertRuleRequestValidator.cs` | **UPDATE** | Cross-field: `PercentDropFromCost` → 0.01–100. `LowHoldingsCount` → whole number. | --- -## 🏗️ P2 — Modernization & UI (New) - -### 12. Next.js 15 Web Dashboard ✅ - - > **Source:** USER Request — **Completed 2026-04-07** - - - [x] Create `InventoryAlert.UI` project (Next.js 15 + Tailwind CSS) - - [x] Implement modern dark-themed UI with glassmorphism - - [x] Routes: Market Explorer, Price Alerts, Portfolio, Symbol Details - - [x] Integrated with `StocksController` via `StockDataService` - - [ ] Replace static chart placeholders with functional **Recharts** implementations - - [ ] Implement Next.js Route Handlers for secure API proxying - - -### 13. Shared Project — `InventoryAlert.Domain` ✅ (Already Exists) - -> **Note:** `InventoryAlert.Domain` **already exists** as the shared project. -> Both `InventoryAlert.Api` and `InventoryAlert.Worker` reference it via `` — **no new project needed**. -> The tasks below are **enhancements** to the existing shared project. -> -> **Invariant:** `InventoryAlert.Domain` is the single source of truth for every type that crosses a service boundary. No entity or payload may be defined in both `Api` and `Worker`. +### 13.2 `InventoryAlert.Infrastructure` -#### What the Shared Project Must Own +#### `Persistence/Postgres/` -| Category | Current State | Target | -| :-------------------------------------------- | :--------------------------------------------------- | :--------------------------------- | -| Domain entities (`Product`, `EventLog`, …) | ✅ In `Contracts/Entities/` | Keep — verified | -| Event payloads (`MarketPriceAlertPayload`, …) | ✅ In `Contracts/Events/Payloads/` | Keep — verified | -| `EventEnvelope` | ✅ Updated — `EventType`, `Payload`, `CorrelationId` | Keep | -| `EventTypes` constants | ✅ Reverse-DNS naming applied | Keep | -| App-wide constants (cache keys, SQS headers) | ✅ In `Contracts/Constants/` | Keep | -| Shared configuration models | ❌ Duplicated per project | Move to `Contracts/Configuration/` | +| File | Action | Notes | +| :--- | :--- | :--- | +| `InventoryDbContext.cs` | **UPDATE** | Register all new entities. Rename class to `AppDbContext`. | +| `DatabaseSeeder.cs` | **UPDATE** | Replace with Section 12 seed data. | +| `Configurations/ProductConfiguration.cs` | **DELETE** | Replaced by `StockListingConfiguration.cs`. | +| `Configurations/StockListingConfiguration.cs` | **NEW** | Unique index on `TickerSymbol`. | +| `Configurations/AlertRuleConfiguration.cs` | **UPDATE** | Index on `(TickerSymbol, IsActive)`. | +| `Configurations/UserConfiguration.cs` | **KEEP** | | +| `Configurations/WatchlistItemConfiguration.cs` | **UPDATE** | Remove `IsWatchOnly`. Confirm composite PK. | +| `Configurations/TradeConfiguration.cs` | **NEW** | Index on `(UserId, TickerSymbol, TradedAt DESC)`. | +| `Configurations/PriceHistoryConfiguration.cs` | **NEW** | bigserial PK. Index on `(TickerSymbol, RecordedAt DESC)`. | +| `Configurations/StockMetricConfiguration.cs` | **NEW** | PK = `TickerSymbol`. | +| `Configurations/EarningsSurpriseConfiguration.cs` | **NEW** | Unique on `(TickerSymbol, Period)`. | +| `Configurations/RecommendationTrendConfiguration.cs` | **NEW** | Unique on `(TickerSymbol, Period)`. | +| `Configurations/InsiderTransactionConfiguration.cs` | **NEW** | Index on `(TickerSymbol, TransactionDate DESC)`. | +| `Configurations/NotificationConfiguration.cs` | **NEW** | Index on `(UserId, IsRead, CreatedAt DESC)`. | +| `Repositories/ProductRepository.cs` | **DELETE** | Replaced by `StockListingRepository.cs`. | +| `Repositories/StockListingRepository.cs` | **NEW** | Implements `IStockListingRepository`. | +| `Repositories/StockTransactionRepository.cs` | **DELETE** | Replaced by `TradeRepository.cs`. | +| `Repositories/TradeRepository.cs` | **NEW** | Implements `ITradeRepository`. Computes net holdings via `SUM(Buy) - SUM(Sell)`. | +| `Repositories/AlertRuleRepository.cs` | **KEEP** | | +| `Repositories/PriceHistoryRepository.cs` | **UPDATE** | Implement `DeleteOlderThanAsync` (batched: `LIMIT 10000`). | +| `Repositories/UserRepository.cs` | **KEEP** | | +| `Repositories/WatchlistItemRepository.cs` | **KEEP** | | +| `Repositories/GenericRepository.cs` | **KEEP** | | +| `Repositories/UnitOfWork.cs` | **UPDATE** | Register new repos. | +| `Repositories/StockMetricRepository.cs` | **NEW** | `UpsertAsync` via `ON CONFLICT DO UPDATE`. | +| `Repositories/EarningsSurpriseRepository.cs` | **NEW** | Bulk upsert. | +| `Repositories/RecommendationTrendRepository.cs` | **NEW** | Bulk upsert. | +| `Repositories/InsiderTransactionRepository.cs` | **NEW** | Delete-all-for-symbol + bulk insert (replace strategy). | +| `Repositories/NotificationRepository.cs` | **NEW** | Implements `INotificationRepository`. | -#### Build Tasks +#### `External/` -- [x] Entities centralized: `Product`, `EventLog`, `EarningsRecord`, `InsiderTransaction`, `NewsRecord` -- [x] `global using` aliases in `Api/Domain/Entities/SharedEntityAliases.cs` for backward compat -- [x] `global using` aliases in `Worker/SharedEntityAliases.cs` for backward compat -- [x] `Constants/AlertConstants.cs` — `CacheKeys`, `EventTypes`, `SqsHeaders` centralized -- [x] `Events/EventEnvelope.cs` — standardized envelope with `CorrelationId` + `Source` -- [x] `Events/EventTypes.cs` — reverse-DNS format + `IsKnown()` + `IReadOnlySet` -- [x] **Move shared config models** — create `Contracts/Configuration/SharedAwsSettings.cs` and `SharedFinnhubSettings.cs` so both `Api` and `Worker` read from the same schema -- [x] **Add `InventoryAlert.ArchitectureTests`** — use `NetArchTest.Rules` to **enforce** at CI time that: - - `InventoryAlert.Api` has no internal entity definitions - - `InventoryAlert.Worker` has no internal entity definitions - - All event payloads live only in `Contracts` -- [x] **NuGet packaging (future)** — if a 3rd service (e.g. `InventoryAlert.Sample`) is added, package `Contracts` as a private NuGet feed artifact so versioning is explicit +| File | Action | Notes | +| :--- | :--- | :--- | +| `FinnhubClient.cs` | **UPDATE** | Add 8 new endpoint methods matching `IFinnhubClient`. | +| `FinnhubModels.cs` | **UPDATE** | Add response models for new endpoints (metrics, earnings, recommendations, insiders, peers, calendars, holidays). | -#### Reference Architecture +#### `Caching/`, `Messaging/` -```text -InventoryAlert.Domain/ ← shared library, referenced by all -├── Entities/ ← EF-mapped domain entities -├── Events/ -│ ├── EventEnvelope.cs ← envelope contract -│ ├── EventTypes.cs ← canonical type registry -│ └── Payloads/ ← one file per event type -├── Constants/ -│ └── AlertConstants.cs ← CacheKeys, SqsHeaders, defaults -└── Configuration/ ← PLANNED: shared config POCOs - ├── SharedAwsSettings.cs - └── SharedFinnhubSettings.cs +| File | Action | +| :--- | :--- | +| `RedisHelper.cs` | **KEEP** | +| `SqsService.cs` | **KEEP** | +| `EventPublisher.cs` | **KEEP** | -InventoryAlert.Api/ - └── Domain/Entities/SharedEntityAliases.cs ← global using only +--- -InventoryAlert.Worker/ - └── SharedEntityAliases.cs ← global using only -``` +### 13.3 `InventoryAlert.Api` ---- +#### `Controllers/` -## 📂 P3 — Logging & Observability (New) +| File | Action | Notes | +| :--- | :--- | :--- | +| `AuthController.cs` | **UPDATE** | Add `POST /refresh`, `POST /logout`. Set `httpOnly` cookie on login/refresh/logout. | +| `PortfolioController.cs` | **UPDATE** | Routes now use `{symbol}` not `{id}`. Add `DELETE /{symbol}`. Wire `NotificationService` for alert triggers. | +| `StocksController.cs` | **UPDATE** | Add 8 new endpoints: `/financials`, `/earnings`, `/recommendation`, `/insiders`, `/peers`, `/news`, `/calendar/earnings`, `/calendar/ipo`. | +| `WatchlistController.cs` | **UPDATE** | Add `GET /{symbol}` detail endpoint. | +| `AlertRulesController.cs` | **UPDATE** | Add `PATCH /{ruleId}/toggle`, `DELETE /{ruleId}`. | +| `NotificationsController.cs` | **NEW** | Full CRUD: `GET /`, `GET /unread-count`, `PATCH /{id}/read`, `PATCH /read-all`, `DELETE /{id}`. | +| `EventsController.cs` | **KEEP** | | +| `MarketController.cs` | **UPDATE** | Add `GET /holiday`, `GET /calendar/earnings`, `GET /calendar/ipo`. | -### 14. Centralized Logging (Serilog) ✅ +#### `Services/` -> **Source:** USER Request — **Completed 2026-04-05** +| File | Action | Notes | +| :--- | :--- | :--- | +| `ProductService.cs` | **DELETE** | Replaced by `PortfolioService.cs`. | +| `PortfolioService.cs` | **NEW** (from `ProductService.cs`) | All position logic using `(UserId, TickerSymbol)` as identity key. Implements `IPortfolioService`. | +| `AuthService.cs` | **UPDATE** | Add `RefreshAsync`, `LogoutAsync`. Implement single-use refresh token rotation. | +| `StockDataService.cs` | **UPDATE** | Add methods for 8 new Finnhub endpoints. Implement DB-first + Finnhub-fallback for search. | +| `AlertRuleService.cs` | **KEEP** | | +| `EventService.cs` | **KEEP** | | +| `NotificationService.cs` | **NEW** | Implements `INotificationService`. Creates `Notification` rows when alerts fire. | -- [x] Serilog bootstrapped in `InventoryAlert.Worker/Program.cs` -- [x] JSON file sink + Console sink (rolling daily, 7-day retention) -- [x] `CorrelationIdMiddleware` tracks requests across Api and Worker -- [x] `MachineName` and `EnvironmentName` enrichers added +#### `Validations/` -### 15. Global Exception Strategy ✅ +| Decision | Notes | +| :--- | :--- | +| Move all `FluentValidation` validators to `Domain/Validators/` | Both Api and Worker may need validation. Domain is the shared home. `Api/Validations/` folder can be deleted once migrated. | -> **Source:** USER Request — **Completed 2026-04-05** +#### Other -- [x] `ExceptionHandlingMiddleware` refactored for full RFC-7807 compliance (`type`, `instance`, semantic slugs) -- [x] `HangfireJobLoggingFilter` — global job error auditing via `ILogger` -- [x] All domain exceptions (`NotFoundException`, `ValidationException`, `ArgumentException`) mapped to HTTP codes +| File | Action | +| :--- | :--- | +| `Middleware/` | **KEEP** | +| `Filters/` | **KEEP** | +| `Extensions/`, `ServiceExtensions/` | **UPDATE** — register `NotificationService`, `PortfolioService`, new repos. | +| `Models/` | **REVIEW** — move any shared models to Domain/DTOs; delete API-local models that duplicate Domain DTOs. | --- -## 🟢 P4 — Performance & Scalability +### 13.4 `InventoryAlert.Worker` -### 12. Caching ✅ +#### `ScheduledJobs/` -> **Source:** `ProductController.cs:L68` +| File | Action | Notes | +| :--- | :--- | :--- | +| `SyncPricesJob.cs` | **UPDATE** | Use `IStockListingRepository` (was `IProductRepository`). Write `PriceHistory` with new fields. Evaluate `AlertRule` → write `Notification`. | +| `CompanyNewsJob.cs` | **KEEP** | | +| `MarketNewsJob.cs` | **KEEP** | | +| `ProcessQueueJob.cs` | **KEEP** | | +| `SqsScheduledPollerJob.cs` | **KEEP** | | +| `SyncMetricsJob.cs` | **NEW** | Daily. Calls `IFinnhubClient.GetMetricsAsync` for all active symbols → `IStockMetricRepository.UpsertAsync`. | +| `SyncEarningsJob.cs` | **NEW** | Daily. Calls `/stock/earnings` for watchlisted symbols → `IEarningsSurpriseRepository.UpsertRangeAsync`. | +| `SyncRecommendationsJob.cs` | **NEW** | Weekly (Monday). Calls `/stock/recommendation` → `IRecommendationTrendRepository.UpsertRangeAsync`. | +| `SyncInsidersJob.cs` | **NEW** | Daily. Calls `/stock/insider-transactions` → `IInsiderTransactionRepository.ReplaceForSymbolAsync`. | +| `CleanupPriceHistoryJob.cs` | **NEW** | Nightly. Calls `IPriceHistoryRepository.DeleteOlderThanAsync(NOW() - 1 year)`. Batched. | -Implement caching for frequently accessed data (product details) using in-memory caching or Redis, depending on scale and expected load. +#### `IntegrationEvents/Handlers/` -- [x] Add `IMemoryCache` for `GetProductById` -- [x] Add cache invalidation on Update/Delete -- [x] Evaluate Redis if scaling beyond a single instance +| File | Action | Notes | +| :--- | :--- | :--- | +| `PriceAlertHandler.cs` | **UPDATE** | On breach: call `INotificationService.CreateAsync(...)` instead of any direct push. | +| `StockLowHandler.cs` | **DELETE** | Replaced by `LowHoldingsHandler.cs`. | +| `LowHoldingsHandler.cs` | **NEW** | Filter `Trade` ledger by `(UserId, TickerSymbol)`. Never aggregate across all users. | +| `MarketNewsHandler.cs` | **UPDATE** | Rename to `CompanyNewsHandler.cs`. | +| `DefaultHandler.cs` | **KEEP** | | +| `UnknownEventHandler.cs` | **DELETE** | Merged into `DefaultHandler.cs`. | +| `Routing/` | **UPDATE** | Register renamed handlers in `IntegrationMessageRouter`. | -### 13. Pagination ✅ +#### Folders to DELETE (old business) -> **Source:** `ProductController.cs:L73` - -Implement pagination for list endpoints (`GetProducts`). Accept query parameters for page number and page size. Return subset of data with metadata (total items, total pages). - -- [x] Create `PaginationParams` (PageNumber, PageSize) -- [x] Create `PagedResult` wrapper -- [x] Update `GetAllAsync` in repository to support `Skip/Take` +| Folder/File | Reason | +| :--- | :--- | +| `Worker/Telegram/` | Old Telegram notification integration. Replaced by in-app `Notification` table. | +| `Worker/Interfaces/` | Move any shared interfaces to `Domain/Interfaces/`. Worker-local interfaces only if truly internal. | +| `Worker/Models/` | Move shared models to `Domain/DTOs/`. Delete Worker-local duplicates. | +| `Worker/External/` | If delegating to `Infrastructure/External/FinnhubClient.cs` via DI, this folder is redundant. | -### 14. Finnhub Sync Design Review ✅ +--- -> **Source:** `ProductServices.cs:L89` +### 13.5 Placement Decision Reference -Should we get the quote for each product on every API call, or store the price in the database and update it regularly? +> Use this table to decide where a new file goes when it is not clear. -**Current state:** ✅ Already implemented! `SyncCurrentPricesAsync` updates DB via BackgroundWorker. `GetHighValueProducts` now reads from DB (no live API calls). +| Type | Used by Api only | Used by Worker only | Used by both | +| :--- | :--- | :--- | :--- | +| Entity class | — | — | **Domain/Entities/** | +| Repository interface | — | — | **Domain/Interfaces/** | +| Service interface | Api/Services OR Domain | Worker/Interfaces OR Domain | **Domain/Interfaces/** | +| Request/Response DTO | Api/Models (or Domain) | — | **Domain/DTOs/** | +| FluentValidation validator | **Domain/Validators/** | — | **Domain/Validators/** | +| SQS event payload | — | — | **Domain/Events/Payloads/** | +| EF Core configuration | — | — | **Infrastructure/Persistence/Configurations/** | +| Repository implementation | — | — | **Infrastructure/Persistence/Repositories/** | +| Caching / Messaging impl | — | — | **Infrastructure/Caching or Messaging/** | +| Controller | **Api/Controllers/** | — | — | +| Scheduled job | — | **Worker/ScheduledJobs/** | — | +| Event handler | — | **Worker/IntegrationEvents/Handlers/** | — |",1675,c6d3d0a2a09dd57f856a5ec5335d6690,doc\archive\api_technical_spec.md,0,271,"symbol, string, tickersymbol, stock, portfolio, market, keep, update",1779814416.394824,1,atomicity efcore rollback entity framework iunitofwork commit httpget iproductrepository inventory notification item database update sku price drop symbol efcore migration hosted service productscontroller market data unitofwork savechanges igenericrepository threshold unit test backgroundservice executetransactionasync finnhubpricesyncworker asnotracking httpput external api iactionresult productservice msft stock ticker savechangesasync fluentassertions httppost periodictimer add-migration schema change dbcontext appdbcontext aapl stock price googl business logic stock data access dbset loss xunit iproductservice arrange act assert quote application service,# InventoryAlert.Api — Technical Specification (v2) | InventoryAlert.Api — Technical Specification (v2) > Refactor Target +doc,"# InventoryAlert.Worker — Architectural Review & Flow Documentation -- [x] `GetHighValueProducts` reads only from DB for faster response -- [x] BackgroundWorker is the single source of truth for `CurrentPrice` +This document provides a technical walkthrough of the **InventoryAlert.Worker** project, detailing its architecture, infrastructure, event lifecycle, and background job logic. --- -## 🔵 P4 — Security - -### 15. Authentication & Authorization ✅ +## 1. High-Level Architecture -> **Source:** `ProductController.cs:L69` +The Worker project follows a **Background Service / Worker** pattern, integrated with **Hangfire** for scheduling and **SQS** for event-driven processing. It shares the same Domain and Infrastructure (Partial) concepts as the API but is focused on side effects, data syncing, and external integration. -Add simple JWT-based authentication to secure the API endpoints and ensure only authorized users can access certain resources. +### Core Stack -- [x] Install `Microsoft.AspNetCore.Authentication.JwtBearer` -- [x] Configure JWT in `Program.cs` -- [x] Add `[Authorize]` to protected endpoints -- [x] Create login/token endpoint -- [x] **User Registration** — Implemented `POST /api/auth/register` with unique index, password hashing, and transaction safety. +- **Service SDK**: `Microsoft.NET.Sdk.Web` (Upgraded to support Hangfire Dashboard). +- **Job Orchestrator**: Hangfire (using PostgreSQL storage). +- **Communication**: Amazon SQS (Event-driven) + SNS (via API). +- **Caching/Deduplication**: Redis (StackExchange.Redis). +- **Persistence**: + - **Relational**: PostgreSQL (via unified `InventoryDbContext` living in `Contracts`). + - **Audit/Logs**: DynamoDB (via unified `EventLogDynamoRepository` living in `Contracts`). +- **External API**: Finnhub REST API. -### 16. Web Security (OWASP) ✅ +### Infrastructure Diagram (Mermaid) -> **Source:** `ProductController.cs:L84` +```mermaid +graph TD + %% ── External ── + Finnhub[""Finnhub API (REST)""] + + %% ── Application Layer ── + API[""InventoryAlert.Api""] + Worker[""InventoryAlert.Worker (Background)""] + Contracts[""InventoryAlert.Contracts (Shared Persistence/Domain)""] + + %% ── Messaging (Aws) ── + SNS[""Amazon SNS (Topic)""] + SQS[""Amazon SQS (Queue)""] + DLQ[""Amazon SQS (DLQ)""] -Protect against SQL injection, XSS, and CSRF. Use parameterized queries (EF Core handles this ✅), validate/sanitize input data, enforce HTTPS. + %% ── Storage ── + DB[""PostgreSQL (Relational DB)""] + Dynamo[""DynamoDB (Audit Logs)""] + Redis[""Redis (Cache/Deduplication)""] -- [x] Enable HTTPS redirection (`app.UseHttpsRedirection()`) -- [x] Add CORS policy -- [x] Review EF Core queries for raw SQL (ensure parameterized) -- [x] Add rate limiting for Finnhub-related endpoints + %% ── Interactions ── + API -- ""Publish Event"" --> SNS + SNS -- ""Fan-out"" --> SQS + SQS -- ""Poll Messages"" --> Worker + Worker -- ""Move to DLQ (after 3 retries)"" --> DLQ + + API -- ""CRUD Products"" --> DB + Worker -- ""Sync Prices"" --> DB + Worker -- ""Fetch News/Analytics"" --> Finnhub + + Worker -- ""Save Telemetry"" --> Dynamo + + API -- ""Read/Write Cache"" --> Redis + Worker -- ""SET NX (Deduplication)"" --> Redis + Worker -- ""History Cooldown"" --> Redis + + API --> Contracts + Worker --> Contracts + Contracts --> DB + Contracts --> Dynamo +``` --- -## 🟣 P5 — Testing & Quality - -### 17. Codebase Audit & Standardization ✅ - -> **Source:** USER Request — _Quality baseline. See `AUDIT_PLAN.md` for full spec._ -> -> **Goal:** Ensure file names, methods, structure grids, folder patterns, and tech logic are strictly conformed across `Api`, `Worker` and `Contracts`. - -- [x] Execute **Structure Audit** (Verify DDD isolation, clean out legacy entity files from Api Project). -- [x] Execute **Naming Audit** (Interfaces, Service suffixes, Exception suffixes, Job/Handler match). -- [x] Execute **Logic Audit** (Enforce thin controllers, centralized mapping, UnitOfWork transaction capture pattern). -- [x] Execute **Tech Pattern Audit** (Async/await hygiene, `AsNoTracking`, strictly `ILogger` usage, `CancellationToken` cascading). - -### 18. Test Project Standardization (Unit & Integration) ✅ - -> **Source:** USER Request — _Testing baseline definition._ -> -> **Goal:** Strictly segregate test types and ensure all 3 main projects (`Api`, `Worker`, `Contracts`) are explicitly covered by testing. - -- [x] Rename `InventoryAlert.Tests` to `InventoryAlert.UnitTests`. -- [x] Group unit tests logically inside `InventoryAlert.UnitTests`: structure them exactly to mirror the 3 target projects (`Api`, `Worker`, `Contracts`). -- [x] Ensure unit tests only use mocks (`Moq`) and don't hit real databases or brokers. -- [x] Create a new project `InventoryAlert.IntegrationTests` for end-to-end and DB testing (e.g., hitting Testcontainers or an EF Core InMemory DB, and Moto for AWS). -- [x] **107 Unit Tests Passing** — Verified full coverage for `ProductService`, `WatchlistService` (with Redis integration), and `AuthController`. +## 2. Event Processing Flow (SQS Pipeline) -**Existing Unit Tests (`InventoryAlert.UnitTests`) progress:** +The most critical flow is the ingestion and processing of market events via SQS. -- [x] Test `ProductServices.GetHighValueProducts` (loss math) -- [x] Test `ProductServices.SyncCurrentPricesAsync` (null handling) -- [x] Test `ProductController` status codes (200, 201, 404) -- [x] Mock `IFinnhubClient` and `IProductRepository` -- [x] Test `EventService` (transaction call, publisher payload) -- [x] Test `EventsController` (202/400 statuses, payload mapping) -- [x] Test `WatchlistService` (caching, deduplication) -- [x] Test `AuthController` (Registration conflicts, async handlers) +### Lifecycle of an SQS Message -### 19. E2E Test Stabilization ✅ +1. **Trigger**: `PollSqsJob` runs every 30 seconds (Scheduled by `JobSchedulerService`). +2. **Ingestion**: + - `PollSqsJob` fetches up to 10 messages from `settings.Aws.SqsQueueUrl`. + - Each message is deserialized into a generic `EventEnvelope`. +3. **Atomic Deduplication**: + - Uses Redis `StringSetAsync` with `When.NotExists` (SET NX) on key `processed:msg:{envelope.MessageId}`. + - If the lock is not acquired, the message is skipped and Deleted (ACK). +4. **Suppression Logic**: + - Specifically for `MarketPriceAlert`, it checks Redis for an `alert:history:{symbol}`. + - If an alert was sent recently (24h cooldown), the event is suppressed but ACKnowledged. +5. **Dispatching**: + - The job uses a `BuildDispatcher()` dictionary to route the payload to the correct `IEventHandler`. + - Handlers (e.g., `PriceAlertHandler`) execute specific domain logic. +6. **Persistence & ACK**: + - On **Success**: + - Writes a `Status = ""processed""` entry to **DynamoDB**. + - Calls `DeleteMessageAsync` to remove the message from the queue. + - On **Failure**: + - Writes a `Status = ""failed""` entry to **DynamoDB**. + - Does NOT delete the message. It will be redelivered by SQS after the visibility timeout. + - SQS RedrivePolicy handles the movement to DLQ after MaxReceiveCount exceeded. -> **Source:** USER Request — _Stabilization baseline._ +--- -- [x] Docker environment verified (Postgres + Redis + Moto + API) -- [x] `BaseE2ETest` improved with configurable `BaseUrl` and detailed error logging -- [x] 32 E2E tests verified passing against Docker-hosted API +## 3. Recurring Jobs Registry -### 20. Async/Await Audit ✅ +Managed by `JobSchedulerService` (IHostedService), registered on application startup. -> **Source:** `ProductController.cs:L70,L78` +| Job Name | Frequency | Responsibility | +| :--- | :--- | :--- | +| `poll-sqs` | 30s | Dequeues events and triggers Handlers. | +| `sync-prices` | 10m (cfg) | Updates `CurrentPrice` in DB for all products via Finnhub. | +| `news-check` | 1h | Fetches latest market/company news. | -Review all async/await usage. Ensure all operations are properly awaited. Review `CancellationToken` consistency across all layers. +--- -- [x] Add `CancellationToken` to `DeleteProductAsync` -- [x] Ensure `CancellationToken` flows: Controller → Service → Repository -- [x] Remove `CancellationToken.None` usages where a real token is available +## 4. Big Picture: Jobs vs. Events -### 20. Dependency Injection Review ✅ +While both patterns run in the background, they serve fundamentally different purposes in the Worker's ecosystem. -> **Source:** `ProductController.cs:L92` +### A. Scheduled Jobs (Pull-Based) +These are **time-triggered** routines managed by Hangfire. They are responsible for keeping the system's state in sync with external truth (Finnhub). +- **Orchestration**: Registered in `JobSchedulerService` via `IRecurringJobManager`. +- **Flow**: `Hangfire Trigger` → `Job.ExecuteAsync()` → `External API` → `Database Update`. +- **Key Jobs**: + - `SyncPricesJob`: The most frequent job. Reconciles DB prices with live market data. + - `NewsCheckJob`: Periodically scrapes news to populate the `NewsRecords` table. -Review DI usage. Ensure constructor injection is used consistently. Review service lifetimes (transient, scoped, singleton) for correctness. +### B. Reactive Events (Push-Based) +These are **action-triggered** routines that respond to events happening elsewhere (usually the API). +- **Orchestration**: The `PollSqsJob` acts as a high-frequency (30s) ""Ingestion Engine"". +- **Dispatching**: It deserializes an `EventEnvelope` and uses a `Dispatcher` dictionary to route to specialized `IEventHandler` instances. +- **Deduplication**: Every event must pass a Redis-backed ""Processed Check"" (`SET NX`) to prevent duplicate processing in clusters. +- **Flow**: `API Action` → `SNS` → `SQS` → `PollSqsJob` → `Handler.HandleAsync()`. -**Current state:** +--- -| Service | Lifetime | Correct? | -| :------------------- | :-------------------- | :--------------------------------- | -| `RestClient` | via HttpClientFactory | ✅ | -| `IFinnhubClient` | Scoped | ✅ | -| `IProductService` | Scoped | ✅ | -| `IProductRepository` | Scoped | ✅ | -| `IConnectionMultiplier` | Singleton | ✅ (Redis Multiplexer) | -| `FinnhubSyncWorker` | Removed | ✅ Hosted via Hangfire instead | +## 5. Handler Logic Review -- [x] Verify `FinnhubSyncWorker` uses `IServiceScopeFactory` (not direct injection) - **Worker replaced entirely by Hangfire Job!** -- [x] Document DI registration decisions +| Handler | Purpose | Logic Notes | +| :--- | :--- | :--- | +| `PriceAlertHandler` | Process price drops. | Logs event; intended to trigger downstream notifications. | +| `NewsHandler` | Content ingestion. | Persists structured news snippets associated with tickers. | +| `UnknownEventHandler` | Safety Net. | Handles `EventEnvelope` with unrecognized `EventType`. | --- -## ⚫ P6 — DevOps & Automation +## 6. Architectural Recommendations -### 21. Messaging & Advanced Background Jobs ✅ +### Current Strengths -> **Source:** `ProductController.cs:L97` — _important high priority_ +- **Resilience**: Every message is audit-logged in DynamoDB regardless of success/failure. +- **Deduplication**: Redis locks prevent duplicate processing in scaled-out worker environments. +- **Observability**: Hangfire Dashboard integration provides real-time monitoring of retries and failures. -See `EVENT_DRIVEN_PLAN.md` for full architecture. Infrastructure scaffolding is complete: +### Recent Architectural Refactorings -- [x] Evaluate Hangfire vs current `BackgroundService` → **Hangfire chosen** -- [x] Design message schema for price alerts → `EventEnvelope` + payload records in `Contracts` -- [x] `InventoryAlert.Worker` project created + NuGet packages installed -- [x] Docker moto-init: SNS topic + SQS queues auto-created on boot -- [x] Implement `IEventPublisher` + `SnsEventPublisher` in Api (Phase B ✅) -- [x] Implement `PollSqsJob`, `SyncPricesJob`, and event handlers in Worker (Phase C–D ✅) +1. **Unified Persistence**: Previously, the API and Worker maintained disconnected DbContexts (`AppDbContext` vs `WorkerDbContext`). These were consolidated into a single `InventoryDbContext` residing centrally within `InventoryAlert.Contracts`. +2. **DynamoDB Unification**: The `EventLogDynamoRepository` and its data model were also moved to `Contracts`, eliminating duplicate SDK code between API log queries and Worker event telemetry writes. +3. **Internal Restructuring**: Event Handlers and background Jobs were cleanly bounded into an `Infrastructure/` namespace mimicking the API's Clean Architecture approach. -### 22. CI/CD Pipeline ✅ +### Opportunities for Improvement -> **Source:** `ProductController.cs:L93` +- **Interface Segregation**: `IEventHandler` is clean, but the manual mapping in `PollSqsJob.BuildDispatcher` could be refactored to use a Strategy pattern or DI keyed services if the number of handlers grows significantly. +- **Resource Protection**: Add rate limiting to `SyncPricesJob` to honor Finnhub's tier-specific throughput limits. +- **DynamoDB Reallocation**: Currently, DynamoDB is heavily invoked for simple Event Logs. Future optimization is slated to migrate `NewsRecord` out of PostgreSQL and into DynamoDB to better leverage its time-series query performance.",159,8be22a49bfeb786d1f98fa28b1a453a7,doc\archive\Architectural_Review.md,0,272,"event, worker, dynamodb, hangfire, redis, message, flow, logic",1775670503.9039152,1,fluentassertions data access sku loss msft business logic efcore periodictimer dbcontext iproductrepository iproductservice stock productservice xunit unit test application service appdbcontext stock ticker igenericrepository dbset item finnhubpricesyncworker backgroundservice googl hosted service notification entity framework inventory stock price symbol threshold external api quote aapl market data asnotracking price drop arrange act assert,# InventoryAlert.Worker — Architectural Review & Flow Documentation | InventoryAlert.Worker — Architectural Review & Flow Documentation This document +doc,"--- +description: Architecture modernization notes and refactor plan for InventoryAlert. +type: plan +status: active +version: 1.0 +tags: [architecture, modernization, plan] +last_updated: 2026-04-23 +---",9,694dfe7e2704e51176f3c8109e232328,doc\archive\architecture_modernization.md,0,273,"plan, architecture, modernization, description, notes, refactor, inventoryalert, type",1777190302.6123624,1,dbcontext entity framework threshold asnotracking appdbcontext business logic productservice item periodictimer application service backgroundservice iproductservice finnhubpricesyncworker inventory stock efcore loss sku notification price drop hosted service,architecture_modernization.md | --- description: Architecture modernization notes and refactor plan for Inventor +doc,"# Architecture Modernization Track -Setup CI/CD using GitHub Actions or Azure DevOps. Automate build, test, and deployment. Include unit tests and integration tests in the pipeline. +## 🎯 Objectives +- Rename `InventoryAlert.Contracts` to `InventoryAlert.Domain` for architectural clarity. +* Consolidate Infrastructure by moving single-tenant logic into `Api` or `Worker`. +* Finalize the ""Lean Profile"" by removing redundant layers. -- [x] Create `.github/workflows/ci.yml` -- [x] Steps: Restore → Build → Test → (optional) Docker push -- [x] Add badge to README +## 🏃 Progress +| Task | Status | Notes | +| :--- | :--- | :--- | +| **Project Renaming** | ✅ Completed | Renamed `Contracts` to `Domain`. | +| **Logic Scoping Audit** | ✅ Completed | Identified Infrastructure logic for relocation. | +| **Infrastructure Cleanup** | ✅ Completed | Moved scoped logic to `Api` or `Worker`. | +| **Namespace Refactoring** | ✅ Completed | All namespaces updated to `Domain` and specific service locations. | -### 23. API Documentation (Swagger) ✅ +## 🔍 Logic Scoping Audit (Draft) +| Component | Primary Usage | Recommendation | +| :--- | :--- | :--- | +| `AuthService` | API | ✅ Moved to `InventoryAlert.Api`. | +| `SqsHelper` | Worker | ✅ Moved to `InventoryAlert.Worker`. | +| `TelegramAlertNotifier` | Worker | ✅ Moved to `InventoryAlert.Worker`. | +| `StockDataService` | API | ✅ Moved to `InventoryAlert.Api`. | +| `ProductService` | API | ✅ Moved to `InventoryAlert.Api`. |",32,694dfe7e2704e51176f3c8109e232328,doc\archive\architecture_modernization.md,0,274,"inventoryalert, worker, moved, logic, completed, domain, infrastructure, contracts",1777190302.6123624,10,dbcontext entity framework threshold asnotracking appdbcontext business logic productservice item periodictimer application service backgroundservice iproductservice finnhubpricesyncworker inventory stock efcore loss sku notification price drop hosted service,# Architecture Modernization Track | Architecture Modernization Track 🎯 Objectives - Rename InventoryAlert.Contracts +doc,"--- +description: Comprehensive audit plan — findings from full git-diff review of 82 changed files. +type: plan +status: active +version: 2.0 +tags: [audit, code-quality, standards, ddd, conventions] +last_updated: 2026-04-05 +---",9,fb64583e3f4984ee72572776c7e5b729,doc\archive\AUDIT_PLAN.md,0,275,"audit, plan, description, comprehensive, findings, from, full, diff",1775368171.535382,1,infrastructure mock setup price drop external api savechangesasync fluentassertions productscontroller item data access domain driven design aapl returns async stock price dbset inventory iactionresult hosted service dockerfile notification postgres efcore savechanges domain entity compose commit appdbcontext backgroundservice threshold arrange act assert httpget stock ticker httppost periodictimer stock googl asnotracking application layer unitofwork executetransactionasync symbol sku iproductrepository xunit entity framework httpput container market data iproductservice rollback unit test loss igenericrepository times once verify dbcontext business logic msft postgresql quote finnhubpricesyncworker iunitofwork atomicity moq application service productservice,AUDIT_PLAN.md | --- description: Comprehensive audit plan — findings from full git-diff review o +doc,"# 🔍 Codebase Audit & Standardization Plan -> **Source:** `ProductController.cs:L83` +> **Scope:** Full review of all 82 changed files against DDD, Clean Architecture, +> PHASE2_PLAN, and project coding rules. Issues recorded below, grouped by severity. +> **Do NOT implement fixes here — file issues only. Fix via separate commits.** -Enhance Swagger/OpenAPI documentation with XML comments, request/response examples, status codes, and endpoint descriptions. +--- -- [x] Enable XML documentation in `.csproj` -- [x] Add `///

` to all controller methods -- [x] Add `[ProducesResponseType]` attributes -- [x] Add example requests/responses +## 🔴 HIGH — Must Fix Before Merge -### 24. AutoMapper Integration ✅ +### H-1 · `EventService.cs:L53` — Transaction Capture Anti-Pattern -> **Source:** `ProductController.cs:L75` +**File:** `InventoryAlert.Api/Application/Services/EventService.cs` -Implement AutoMapper to centralize mapping between domain models and DTOs. Reduce boilerplate in services. +`` +`csharp +// ✅ CURRENT — project rules explicitly ban this +EventLog savedLog = new(); +await _unitOfWork.ExecuteTransactionAsync(async () => +{ + savedLog = await _eventLogRepository.AddAsync(log, ct); +}, ct); +// savedLog is never used — dead code AND violates the pattern +``` -- [x] Install `AutoMapper.Extensions.Microsoft.DependencyInjection` -- [x] Create `MappingProfile` with `Product ↔ ProductDto` maps -- [x] Replace manual `MapProductToProductDto` methods +`savedLog` is declared outside, assigned inside, but never read after the transaction. +The `LogInformation` on L59 uses `log` (the pre-persist input), not `savedLog`. ---- +**Fix:** Remove the capture entirely — just call `AddAsync` without assigning: -## 🏗️ P2 — Architecture Evolution (Phase 2) ✅ +```csharp +await _unitOfWork.ExecuteTransactionAsync(async () => +{ + await _eventLogRepository.AddAsync(log, ct); +}, ct); +``` -> See `doc/PHASE2_PLAN.md` for full spec and diagrams. +--- -### 16. Shared Contracts Enforcement +### H-2 · Duplicate Test Projects in Solution -- [x] All entities centralized in `InventoryAlert.Domain` ✅ -- [x] `global using` aliases in Api and Worker for backward compat ✅ -- [x] Add `ArchitectureTests` project (NetArchTest.Rules) to enforce zero-duplication at CI -- [x] Move shared `AppSettings` config models to `Contracts.Configuration` +**Files:** -### 17. Standardized Event Types ✅ +- `InventoryAlert.Tests/` (lines 60–67 in git-files.txt) -- [x] Reverse-DNS format: `inventoryalert.{domain}.{action}.v{version}` -- [x] `EventEnvelope` fields standardized: `EventType`, `Payload`, `CorrelationId`, `Source` -- [x] `EventTypes.IsKnown()` for O(1) dispatch validation -- [x] `IReadOnlySet` for type registry +- `InventoryAlert.UnitTests/` (lines 20–27 in git-files.txt) -### 18. Event Handler Dispatcher Pattern ✅ +Both contain identical test class names (`ProductServiceTests`, `EventServiceTests`, etc.) +with different root namespaces (`InventoryAlert.Tests.*` vs `InventoryAlert.UnitTests.*`). -- [x] `IEventHandler` interface defined in `Worker.Handlers` -- [x] Dictionary dispatcher in `PollSqsJob` — adding handler = 1 dictionary entry only -- [x] `UnknownEventHandler` fallback — logs warning + ACKs unknown types -- [x] All handlers implement `IEventHandler` interface +`ProductServiceTests.cs:L8` imports `using InventoryAlert.Tests.Helpers` — confirming +`UnitTests` project references `Tests` project's helpers directly. This is fragile. -### 19. Retry & Dead Letter Queue ✅ +**Fix:** -- [x] `ApproximateReceiveCount` guard — explicit DLQ push after > 3 receives -- [x] ACK-on-success-only pattern — failures leave message in SQS for natural redelivery -- [x] Configure SQS `RedrivePolicy` in `moto-init/init-sqs.sh` (MaxReceiveCount=3) -- [x] Create `inventory-dlq` queue in Moto init script -- [x] Add `SqsDlqUrl` to `appsettings.Docker.json` and `appsettings.json` +- Keep `InventoryAlert.UnitTests` (the newer one, matches PHASE2_PLAN naming). -### 20. DynamoDB Integration ✅ +- Delete `InventoryAlert.Tests/` entirely. -- [x] **Phase 4A** — Register `IAmazonDynamoDB` client in `Worker/Program.cs` -- [x] **Phase 4A** — Create `EventLogDynamoRepository.cs` in `Worker/Persistence` -- [x] **Phase 4A** — Add `DynamoDbSettings` (table name) to `WorkerSettings` -- [x] **Phase 4A** — Create DynamoDB table in `moto-init/init-dynamodb.sh` -- [x] **Phase 4B** — Write event to DynamoDB after each successful dispatch (TTL=90d) -- [x] **Phase 4B** — Write `Status=failed` entry on handler exception -- [x] **Phase 4C** — Add `GET /api/events` endpoint to query DynamoDB event log +- Move `Helpers/ProductFixtures.cs` to `UnitTests/Helpers/`. + +- Remove `InventoryAlert.Tests` from `.sln`. --- -## 🛠️ Maintenance & CI/CD +### H-3 · `AuthController.cs:L32` — Hardcoded Credentials (OWASP A02) -- [x] **Fresh State enforcement** — Always run `dotnet clean` before major test/coverage runs to ensure `.editorconfig` changes and build artifacts are correctly synchronized. -- [x] **Coverage Script updated** — `code-coverage.bat` now executes `dotnet clean` before tests. -- [x] **CI Pipeline updated** — `.github/workflows/ci.yml` now executes `dotnet clean` in the Unit Test stage. +**File:** `InventoryAlert.Api/Web/Controllers/AuthController.cs` -- **Command:** `dotnet clean && dotnet test` -- **Result:** Pure, non-stale test results. -- **Reference:** `.editorconfig` rules require clean/rebuild for strict enforcement in some environments. +`` +`csharp +// ✅ OWASP A02 — hardcoded credentials in source +if (request.Username == ""admin"" && request.Password == ""admin123"") +``` -> **Last Updated:** 2026-04-07 -> -> **Legend:** 🔴 P0 = Do now | 🟠 P1 = Next sprint | 🟡 P2 = Data/Validation | 🏗️ P2 = Architecture | 🟢 P3 = Observability | 🟢 P4 = Performance | 🔵 P4 = Security | 🟣 P5 = Quality | ⚫ P6 = DevOps",707,f90e807d257d8050190c23e82ac49f40,doc\ROADMAP.md,0,277,"source, inventoryalert, create, worker, productcontroller, implement, service, review",1776910224.0065036,10,application service iunitofwork productservice efcore productscontroller times once savechanges httpget appdbcontext httppost entity framework verify fluentassertions dbcontext compose item igenericrepository iactionresult iproductrepository domain entity commit savechangesasync postgres periodictimer finnhubpricesyncworker inventory hosted service threshold application layer backgroundservice business logic returns async moq iproductservice dbset notification market data executetransactionasync postgresql price drop unitofwork infrastructure sku external api data access domain driven design arrange act assert unit test httpput rollback mock setup loss asnotracking dockerfile container stock quote xunit stock price atomicity,# 🗺️ Development Roadmap | 🗺️ Development Roadmap > Consolidated from all TODO comments across the codebase -doc,"--- -description: InventoryAlert.UI audit of pages/components and recommendations (paging, reuse, UX, maintainability). Documentation only. -type: reference -status: draft -version: 1.0 -tags: [ui, audit, components, pages, ux, nextjs, inventoryalert] -last_updated: 2026-04-26 ----",9,5080f1111fc0c2f3f9042a921808473d,doc\UI_COMPONENTS_AND_PAGES_AUDIT.md,0,278,"inventoryalert, audit, pages, components, description, recommendations, paging, reuse",1777190302.5988624,1,efcore iactionresult httppost dbcontext entity framework price drop loss productscontroller httpget threshold asnotracking httpput notification appdbcontext,UI_COMPONENTS_AND_PAGES_AUDIT.md | --- description: InventoryAlert.UI audit of pages/components and recommendations -doc,"# InventoryAlert.UI — Components & Pages Audit + Enhancement Suggestions +Also: `AuthController` uses old-style field injection (not C# 12 primary constructor). +Also: `DateTime.Now` used on L62 instead of `DateTime.UtcNow`. -This document scans the current UI project and lists: +**Fix:** +1. Move credentials to `appsettings.json` under `Auth:Username` / `Auth:Password`. +2. Inject `IConfiguration` via primary constructor. +3. Replace `DateTime.Now` → `DateTime.UtcNow`. -- every route/page and what it calls, -- reusable components and where they are used, -- gaps and recommended enhancements (especially paging, consistency, and maintainability). +--- -Scope: +### H-4 · `Program.cs (API):L43` — Hardcoded JWT Fallback Secret (OWASP A02) -- UI code: `InventoryAlert.UI/src/*` -- No code changes included here (documentation-only). +**File:** `InventoryAlert.Api/Program.cs` -Files scanned (as of `2026-04-26`): +`` +`csharp +// ✅ Hardcoded fallback key in production code +var jwtKey = builder.Configuration[""Jwt:Key""] ?? ""super_secret_key_12345_super_secret_key_12345""; +``` -- Routes: `InventoryAlert.UI/src/app/**/page.tsx`, `InventoryAlert.UI/src/app/layout.tsx` -- Components: `InventoryAlert.UI/src/components/*.tsx` -- Hooks: `InventoryAlert.UI/src/hooks/*.ts` -- Client utilities: `InventoryAlert.UI/src/lib/*.ts` +If `Jwt:Key` is missing from config, a hardcoded predictable key is used silently. + +**Fix:** Throw instead of falling back: +```csharp +var jwtKey = builder.Configuration[""Jwt:Key""] + ?? throw new InvalidOperationException(""Jwt:Key is required in configuration.""); +``` --- -## 1) Project Entry + Global Flow +## 🟠 MEDIUM — Fix in Next Sprint -### 1.1 Root layout + providers +### M-1 · `EventsController.cs:L49,L69` — Magic String EventTypes -`InventoryAlert.UI/src/app/layout.tsx`: +**File:** `InventoryAlert.Api/Web/Controllers/EventsController.cs` -- applies theme class early (inline script) -- wraps the app with: - - `ThemeProvider` (`src/components/ThemeProvider.tsx`) - - `NotificationProvider` (`src/components/NotificationProvider.tsx`) - - `NavbarWrapper` (`src/components/NavbarWrapper.tsx`) +`` +`csharp +// ✅ Hardcoded — breaks silently if EventTypes constant is renamed +await _eventService.PublishEventAsync(""MarketPriceAlert"", payload, ct); // L49 +await _eventService.PublishEventAsync(""CompanyNewsAlert"", payload, ct); // L69 +``` -Render tree (simplified): +`EventTypes.cs` exists with the correct constants. Use them: -`` → `` → `` → `
{children}
` +```csharp +await _eventService.PublishEventAsync(EventTypes.MarketPriceAlert, payload, ct); +await _eventService.PublishEventAsync(EventTypes.CompanyNewsAlert, payload, ct); +``` -### 1.2 API client pattern +--- -`InventoryAlert.UI/src/lib/api.ts`: +### M-2 · `EventLogDynamoRepository.cs:L12` — Old-Style Constructor, Untestable Context -- reads access token from `localStorage` (`auth_token`) -- attaches `Authorization: Bearer ` when present -- always sends cookies (`credentials: ""include""`) to support refresh token flow -- on `401`: - - attempts refresh via `POST /api/v1/auth/refresh` - - retries once - - evicts token and redirects to `/login` if refresh fails +**File:** `InventoryAlert.Worker/Persistence/EventLogDynamoRepository.cs` -Enhancement notes: +`` +`csharp +// ✅ Not primary constructor (C# 12 rule) +// ✅ new DynamoDBContext() inside constructor — cannot be mocked +public EventLogDynamoRepository(IAmazonDynamoDB dynamoDbClient, ILogger<...> logger) +{ + _context = new DynamoDBContext(dynamoDbClient); + _logger = logger; +} +``` -- error parsing currently checks `userFriendlyMessage/message/title`, but the API error shape is `ErrorResponse { errors[], errorId }`. Consider mapping UI error extraction to `errors[0].message` (and include `X-Correlation-Id` when present). +**Fix:** Use primary constructor pattern. `DynamoDBContext` should be injected +or wrapped behind an interface if testability is required. --- -## 2) Pages (Routes) Inventory +### M-3 · `InfrastructureServiceExtensions.cs:L55,L61,L67` — Hardcoded `""test""` Credentials -All routes are App Router pages under `InventoryAlert.UI/src/app/*`. +**File:** `InventoryAlert.Api/Web/ServiceExtensions/InfrastructureServiceExtensions.cs` -### `/` — Dashboard +`` +`csharp +// ✅ Hardcoded ""test""/""test"" credentials — works for Moto but breaks in real AWS +return new AmazonSimpleNotificationServiceClient(""test"", ""test"", config); +return new AmazonSQSClient(""test"", ""test"", config); +return new AmazonDynamoDBClient(""test"", ""test"", config); +``` -File: `InventoryAlert.UI/src/app/page.tsx` +Same pattern in `Worker/Program.cs:L58,L64`. -Fetches on mount: +**Fix:** Use `new AmazonSQSClient(config)` (no explicit credential args). +The SDK auto-reads `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` from the environment, +which is already set in `docker-compose.yml`. This makes it work in both Moto and real AWS. -- `GET /api/v1/watchlist` -- `GET /api/v1/market/news?category=general&page=1` -- `GET /api/v1/portfolio/positions` +--- -Actions: +### M-4 · `ArchitectureTests.cs` — Missing Web→Application Dependency Check -- Enqueue market news refresh: - - `POST /api/v1/events` with `eventType=inventoryalert.news.sync-requested.v1` -- Watchlist remove: - - `DELETE /api/v1/watchlist/{symbol}` +**File:** `InventoryAlert.ArchitectureTests/ArchitectureTests.cs` -Enhancement ideas: +Current tests check: -- Add paging controls for news (or link to Market page with selected category). -- Centralize toast/confirm patterns (this page already uses `Toast` + `ConfirmDialog`). -- Consider refetch strategy (manual refresh button, or background refresh interval with backoff). +- `Api.Domain.Entities` has no classes ✅ -### `/market` — Market Pulse +- `Worker.Entities` has no classes ✅ -File: `InventoryAlert.UI/src/app/market/page.tsx` +- `Application` doesn't depend on `Infrastructure` ✅ -Fetches (category/page-driven): +**Missing tests:** -- `GET /api/v1/market/news?category={cat}&page={newsPage}&pageSize=10` -- `GET /api/v1/market/status` -- `GET /api/v1/market/calendar/earnings?from=…&to=…` (errors swallowed to `[]`) +- `Domain` must not depend on `Application` or `Infrastructure` -Actions: +- `Web` (Controllers) must not depend on `Domain` directly (only via `Application`) -- Enqueue market news refresh via `POST /api/v1/events` +- `Contracts` must not depend on `Api` or `Worker` -Enhancement ideas: +--- -- Add explicit paging UI for `newsPage` (next/prev) and show current page. -- Add a “loading/error state” component instead of `console.error`. -- Use `MarketStatusBanner` here (currently status is fetched and displayed in-page). +### M-5 · `GenericRepository.cs:L21,L48,L54` — CS1998 `async` Without `await` -### `/stocks` — Stock Catalog +**File:** `InventoryAlert.Api/Infrastructure/Persistence/Repositories/GenericRepository.cs` -File: `InventoryAlert.UI/src/app/stocks/page.tsx` +`` +`csharp +// ✅ CS1998 — async keyword with no await +public async Task DeleteAsync(T entity) { var result = _dbSet.Remove(entity); return result.Entity; } +public async Task UpdateAsync(T entity) { var result = _dbSet.Update(entity); return result.Entity; } +public async Task UpdateRangeAsync(...) { _dbSet.UpdateRange(entities); } +``` -Fetches: +**Fix per project rule** — remove `async`, return `Task.FromResult(...)`: -- browse: `GET /api/v1/stocks?page={page}&pageSize=20` -- search: `GET /api/v1/stocks/search?q={query}` +```csharp +public Task DeleteAsync(T entity) +{ + var result = _dbSet.Remove(entity); + return Task.FromResult(result.Entity); +} -Enhancement ideas: +public Task UpdateAsync(T entity) +{ + var result = _dbSet.Update(entity); + return Task.FromResult(result.Entity); +} -- Add page size selector and show total results if API returns it. -- Add “clear search” UX and keyboard navigation to results (GlobalSearch already has it). +public Task UpdateRangeAsync(IEnumerable entities) +{ + _dbSet.UpdateRange(entities); + return Task.CompletedTask; +} +``` -### `/stocks/[symbol]` — Stock Detail +--- -File: `InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx` +### M-6 · `PriceAlertHandler.cs:L17` — Missing `async` / `await`, Returns `Task.CompletedTask` -Eager fetches on symbol change: +**File:** `InventoryAlert.Worker/Handlers/PriceAlertHandler.cs` -- `GET /api/v1/stocks/{symbol}/quote` -- `GET /api/v1/stocks/{symbol}/profile` -- `GET /api/v1/stocks/{symbol}/financials` (errors swallowed to `null`) -- `GET /api/v1/watchlist` (to determine watchlist status; client-side check) +```csharp +public Task HandleAsync(MarketPriceAlertPayload payload, CancellationToken ct = default) +{ + // Only logging — no async I/O, returns Task.CompletedTask + _logger.LogWarning(""{AlertMessage}"", message); + return Task.CompletedTask; +} +``` -Lazy per tab: +This is technically correct (`Task.CompletedTask` is fine) **but** the `_db` field +(`WorkerDbContext`) is injected but **never used**. Dead dependency. -- Earnings: `GET /api/v1/stocks/{symbol}/earnings` (with loaded/loading/error state) -- Recommendations: `GET /api/v1/stocks/{symbol}/recommendation` -- Insiders: `GET /api/v1/stocks/{symbol}/insiders` -- News: `GET /api/v1/stocks/{symbol}/news?page={newsPage}&pageSize=10` -- Peers: `GET /api/v1/stocks/{symbol}/peers` +Also: Phase F (Telegram) plugs in here — there's no `IAlertNotifier` dependency injected. +When Phase F is implemented, this handler will need rework. -Actions: +**Fix now:** Remove the unused `_db` field and `WorkerDbContext` injection. -- Watchlist toggle: - - `POST /api/v1/watchlist/{symbol}` or `DELETE /api/v1/watchlist/{symbol}` -- Price alert modal: - - `POST /api/v1/alertrules` (via `PriceAlertModal`) +--- -Enhancement ideas: +## 🟡 LOW — Track as Tech Debt -- Add visible paging controls for the News tab (`newsPage` exists in state). -- Replace `alert()` error UX with `Toast`. -- Avoid fetching full watchlist list just to check one symbol (add a backend endpoint `GET /watchlist/{symbol}/exists` or cache watchlist in a provider). -- Add per-tab skeletons and per-tab error UI (only earnings has a dedicated error state today). +### L-1 · `ProductService.cs:L135` — Full Table Scan in Sync/Alert Methods -### `/portfolio` — Portfolio +**File:** `InventoryAlert.Api/Application/Services/ProductService.cs` -File: `InventoryAlert.UI/src/app/portfolio/page.tsx` +```csharp +var products = await _productRepository.GetAllAsync(cancellationToken); +``` -Fetches: +Called in both `GetPriceLossAlertsAsync` (L135) and `SyncCurrentPricesAsync` (L177). +At scale, this is an unbounded full-table scan. Should filter to products where +`TickerSymbol != """"` at minimum, or use a dedicated repository query. -- `GET /api/v1/portfolio/positions` (expects `PagedResult`, but does not pass page params) +--- -Actions: +### L-2 · `AppSettings.cs:L10` — Property Named `AWS` (casing inconsistency) -- Delete position: - - `DELETE /api/v1/portfolio/positions/{symbol}` -- Create/adjust position and trades via `TradeModal`: - - `POST /api/v1/portfolio/positions` - - `POST /api/v1/portfolio/{symbol}/trades` +**File:** `InventoryAlert.Api/Web/Configuration/AppSettings.cs` -Enhancement ideas: +```csharp +public SharedAwsSettings AWS { get; set; } = new(); // uppercase +``` -- Implement paging UI if portfolios can grow (API already returns paged result). -- Provide optimistic UI updates for trade/position changes. +`appsettings.Docker.json` uses `""Aws""` (PascalCase). While .NET binding is +case-insensitive, the convention mismatch is confusing. Standardize to `Aws`. -### `/watchlist` — Watchlist +--- -File: `InventoryAlert.UI/src/app/watchlist/page.tsx` +### L-3 · `Worker/Program.cs:L88-91` — Verbose Fully-Qualified Handler Registration -Fetches: +**File:** `InventoryAlert.Worker/Program.cs` -- `GET /api/v1/watchlist` +```csharp +builder.Services.AddScoped, PriceAlertHandler>(); +``` -Actions: +All four handler registrations use fully-qualified type names. Add `using` statements +to the top of the file to clean this up. -- Add symbol: - - `POST /api/v1/watchlist/{symbol}` (via `AddSymbolModal`) -- Remove symbol: - - `DELETE /api/v1/watchlist/{symbol}` +--- -Enhancement ideas: +### L-4 · `PollSqsJob.cs:L50` — `BuildDispatcher()` Called on Every `ExecuteAsync` Invocation -- Add sorting (price, change %, alpha). -- Add “bulk remove” mode for large lists (with ConfirmDialog). +**File:** `InventoryAlert.Worker/Jobs/PollSqsJob.cs` -### `/alerts` — Alert Rules Manager +```csharp +public async Task ExecuteAsync(CancellationToken ct = default) +{ + var dispatcher = BuildDispatcher(); // ← rebuilds Dictionary every 30s + ... +} +``` -File: `InventoryAlert.UI/src/app/alerts/page.tsx` +The dispatcher dictionary is rebuilt every time the Hangfire job fires (every 30s). +Since the dictionary is static in structure (no runtime changes), it can be built +once in a `readonly` field at construction time. -Fetches: +--- -- `GET /api/v1/alertrules` +### L-5 · `EventsController.cs` — `GetEventLogs` Exposes `EventLog` Entity Directly -Actions: +**File:** `InventoryAlert.Api/Web/Controllers/EventsController.cs:L84` -- Create: - - `POST /api/v1/alertrules` -- Update: - - `PUT /api/v1/alertrules/{id}` -- Toggle: - - `PATCH /api/v1/alertrules/{id}/toggle` -- Delete: - - `DELETE /api/v1/alertrules/{id}` (currently uses `confirm(...)`) +```csharp +[ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] +``` -Enhancement ideas: +Returns the raw `EventLog` entity to the client. Should return a mapped DTO +(`EventLogResponse`) to decouple the API contract from the internal entity structure. -- Replace native `confirm()` and `alert()` with `ConfirmDialog` + `Toast` for consistent UX. -- Add filtering tabs: Active / Inactive / TriggerOnce / Condition type. -- Add inline validation errors (target value semantics differ by condition). +--- -### `/notifications` — Notifications +## ✅ CONFIRMED PASSING -File: `InventoryAlert.UI/src/app/notifications/page.tsx` +| Area | Check | +| :--- | :--- | +| Dispatcher pattern (`PollSqsJob`) | ✅ Dictionary + `UnknownEventHandler` fallback | +| Thin controllers (`ProductsController`) | ✅ Zero business logic, SRP violation resolved | +| Transaction Capture (`ProductService`) | ✅ All 4 methods assign result inside lambda | +| DLQ / Retry logic (`PollSqsJob`) | ✅ `ApproximateReceiveCount > 3` → DLQ, ACK only on success | +| DynamoDB telemetry | ✅ Write on success + failure, 90-day TTL | +| `ILogger` everywhere | ✅ No `Console.WriteLine` found | +| Structured logging format | ✅ Parameterized `{MessageId}`, `{EventType}` throughout | +| Primary constructors (most services) | ✅ Consistent across Api + Worker | +| `.AsNoTracking()` on reads | ✅ `GetAllAsync`, `GetPagedAsync` both use it | +| `SnsEventPublisher` layer discipline | ✅ Correctly in `Infrastructure/Messaging/` | +| `ExceptionHandlingMiddleware` | ✅ RFC-7807, no stack trace leakage, structured logging | +| `EventTypes.All` O(1) registry | ✅ `IReadOnlySet` HashSet with `IsKnown()` | +| `Contracts` consolidation | ✅ Entities, Events, Payloads, Constants all in Contracts | +| `CorrelationIdMiddleware` ordering | ✅ Registered first in pipeline | +| Serilog bootstrap | ✅ Both API and Worker use `try/catch/finally + Log.CloseAndFlush()` | -Fetches: +--- -- `GET /api/v1/notifications` (API returns paged result; UI uses `data.items` but does not implement paging controls) +## 📋 Fix Priority Order -Actions: +``` +Sprint 1 (must): H-1, H-2, H-3, H-4 +Sprint 2 (good): M-1, M-2, M-3, M-5, M-6, M-7, M-8, M-9 +Sprint 3 (debt): M-4 (arch tests), L-1, L-2, L-3, L-4, L-5, L-6, L-7 +``` -- Mark read: - - `PATCH /api/v1/notifications/{id}/read` -- Mark all read: - - `PATCH /api/v1/notifications/read-all` -- Dismiss: - - `DELETE /api/v1/notifications/{id}` +> **Commit convention per fix:** `fix(): ` or `refactor(): ` +> Example: `fix(application): remove transaction capture anti-pattern in EventService` -Enhancement ideas: +--- -- Add paging controls or infinite scroll using `page` + `pageSize` query params. -- Add filters: only unread, by symbol, by date range. -- Improve badge consistency: avoid decrementing unread count below 0 (currently guarded) and ensure unread count matches server state on refresh. +## 🔴 HIGH — Phase 2 Additions -### `/admin/health` — System Integrity +### H-5 · `AlertConstants.cs:L21-28` — Duplicate `EventTypes` Class (Name Collision Risk) -File: `InventoryAlert.UI/src/app/admin/health/page.tsx` +**File:** `InventoryAlert.Contracts/Constants/AlertConstants.cs` -Fetches: +`` +`csharp +// ✅ AlertConstants.cs defines its OWN EventTypes inside Constants namespace +public static class EventTypes +{ + public const string MarketPriceAlert = ""MarketPriceAlert""; // SHORT name + ... +} -- `GET /health` on interval (30s) +// ✅ Contracts/Events/EventTypes.cs uses reverse-DNS format +public const string MarketPriceAlert = ""inventoryalert.pricing.price-drop.v1""; +``` -Enhancement ideas: +Two `EventTypes` classes exist in the same `Contracts` project with **different values**. +`AlertConstants.EventTypes.MarketPriceAlert = ""MarketPriceAlert""` but +`InventoryAlert.Contracts.Events.EventTypes.MarketPriceAlert = ""inventoryalert.pricing.price-drop.v1""`. -- Add explicit error UI (right now it only logs to console). -- Provide link-out buttons to Seq and Hangfire dashboards (if running locally). -- Make polling interval configurable (or pause when tab hidden). +Any code that imports `AlertConstants` without the full namespace gets the wrong string, +causing silent dispatcher mismatches. -### `/login` and `/register` +**Fix:** Delete the `EventTypes` nested class inside `AlertConstants.cs`. +All code must use `InventoryAlert.Contracts.Events.EventTypes.*` exclusively. -Files: +--- -- `InventoryAlert.UI/src/app/(auth)/login/page.tsx` -- `InventoryAlert.UI/src/app/(auth)/register/page.tsx` - -Notes: +### H-6 · `DynamoDbEventLogQuery.cs` — Wrong Namespace (Infrastructure Layer Pollution) -- Login forces `window.location.href = '/'` after storing token, to sync all components. -- Register uses router push to `/login?registered=true`. +**File:** `InventoryAlert.Api/Infrastructure/External/DynamoDbEventLogQuery.cs` -Enhancement ideas: +```csharp +namespace InventoryAlert.Api.Infrastructure.External // ✅ ""External"" implies 3rd-party HTTP +``` -- Standardize visual design between login and register (styles differ significantly). -- Add password requirement hints aligned with API validation. +DynamoDB is a **persistence** technology, not an external HTTP API (like Finnhub). +Placing it in `Infrastructure/External/` alongside `FinnhubClient` is misleading. ---- +Also: Old-style constructor (not C# 12 primary constructor): +```csharp +public DynamoDbEventLogQuery(IAmazonDynamoDB dynamoDb) +{ + _dynamoDb = dynamoDb; // ✅ should be primary constructor +} +``` -## 3) Components Inventory +Also: `_tableName` is a hardcoded magic string: +```csharp +private readonly string _tableName = ""inventory-event-logs""; // ✅ must come from config +``` -All components are under `InventoryAlert.UI/src/components/*`. +**Fix:** +1. Move to `Infrastructure/Persistence/` namespace. +2. Use primary constructor. +3. Inject table name from `WorkerSettings.Aws.DynamoDbTableName` or `AppSettings.AWS.DynamoDbTableName`. -### Global navigation + search +--- -- `Navbar.tsx` — navigation links, sticky header, mobile menu -- `NavbarWrapper.tsx` — holds global search open state + keyboard shortcut Ctrl/Cmd+K -- `UserNav.tsx` — theme toggle, login/logout, notification bell, user avatar placeholder -- `GlobalSearch.tsx` — modal search for symbols; keyboard nav; uses `/api/v1/stocks/search` +## 🟠 MEDIUM — Phase 2 Additions -Enhancement ideas: +### M-7 · `IProductService.cs` — Missing `GetAllProductsAsync`, Tests Reference It -- Add focus trap in `GlobalSearch` (escape closes, but focus management can be improved). -- Standardize z-index tokens (`GlobalSearch` uses `z-[200]`, other modals vary). +**File:** `InventoryAlert.Api/Application/Interfaces/IProductService.cs` -### Notifications (client state) +`` +`csharp +// ✅ NOT in interface — but ProductServiceTests.cs:L55 calls it: +var result = await _sut.GetAllProductsAsync(Ct); +``` -- `NotificationProvider.tsx` — SignalR connect + unread count bootstrap -- `NotificationBell.tsx` — shows unread badge; links to `/notifications` +`IProductService` has `GetProductsPagedAsync` but no `GetAllProductsAsync`. +The test calls `GetAllProductsAsync` which means either: +1. It exists on the concrete `ProductService` but not the interface (breaking DI). +2. The tests will fail to compile. -Enhancement ideas: +**Fix:** Add to interface or remove from tests and use `GetProductsPagedAsync` consistently. -- Reduce token polling (`setInterval(..., 2000)`); prefer a single “auth store” source of truth. -- Gate `console.log` noise behind a debug flag. +--- -### Modals + dialogs +### M-8 · `ci.yml:L30-31` — Build Runs AFTER Tests (Wrong Order) -- `AddSymbolModal.tsx` -- `PriceAlertModal.tsx` -- `TradeModal.tsx` -- `ConfirmDialog.tsx` +**File:** `.github/workflows/ci.yml` -Enhancement ideas: +```yaml",453,fb64583e3f4984ee72572776c7e5b729,doc\archive\AUDIT_PLAN.md,0,276,"csharp, inventoryalert, task, entity, public, async, result, file",1775368171.535382,10,infrastructure mock setup price drop external api savechangesasync fluentassertions productscontroller item data access domain driven design aapl returns async stock price dbset inventory iactionresult hosted service dockerfile notification postgres efcore savechanges domain entity compose commit appdbcontext backgroundservice threshold arrange act assert httpget stock ticker httppost periodictimer stock googl asnotracking application layer unitofwork executetransactionasync symbol sku iproductrepository xunit entity framework httpput container market data iproductservice rollback unit test loss igenericrepository times once verify dbcontext business logic msft postgresql quote finnhubpricesyncworker iunitofwork atomicity moq application service productservice,# 🔍 Codebase Audit & Standardization Plan | 🔍 Codebase Audit & Standardization Plan > Scope: Full review of all 82 changed f +doc,# ✅ Current order: Architecture Test → Unit Test → Build,454,fb64583e3f4984ee72572776c7e5b729,doc\archive\AUDIT_PLAN.md,0,277,"test, current, order, architecture, unit, build",1775368171.535382,454,infrastructure mock setup price drop external api savechangesasync fluentassertions productscontroller item data access domain driven design aapl returns async stock price dbset inventory iactionresult hosted service dockerfile notification postgres efcore savechanges domain entity compose commit appdbcontext backgroundservice threshold arrange act assert httpget stock ticker httppost periodictimer stock googl asnotracking application layer unitofwork executetransactionasync symbol sku iproductrepository xunit entity framework httpput container market data iproductservice rollback unit test loss igenericrepository times once verify dbcontext business logic msft postgresql quote finnhubpricesyncworker iunitofwork atomicity moq application service productservice,# ✅ Current order: Architecture Test → Unit Test → Build | ✅ Current order: Architecture Test → Unit Test → Build +doc,"# Build failure is discovered AFTER expensive test runs -- Create a shared `ModalShell` component (backdrop, panel, title row, close button, z-index, escape-to-close, focus trap). -- Fix duplicated input block in `TradeModal.tsx` (quantity field appears twice when opening a new position). +- name: Architecture Test -### Feedback +- name: Unit Test -- `Toast.tsx` — simple toast with auto-dismiss +- name: Build # ← should be FIRST +``` -Enhancement ideas: +**Also missing:** -- Centralize toast via a provider so pages don’t duplicate toast state wiring. +- No `dotnet format --verify-no-changes` step (code style) -### Market status +- No `--configuration Release` on test steps (tests run in Debug) -- `MarketStatusBanner.tsx` — polls `/api/v1/market/status` every 60s and displays US market open/closed badge +- No artifact upload on failure (test results/logs) -Enhancement ideas: +- `build-and-test` job name is misleading (it currently does test-then-build) -- Reuse this in `Navbar` or `Market` page for consistent “market open/closed” display. +**Fix:** +```yaml +steps: + - Restore + - Build (--configuration Release) ← first + - Architecture Tests + - Unit Tests + - (optional) Format check +``` --- -## 4) Cross-Cutting Recommendations (High Impact) - -### 4.1 Paging standardization (core request) - -Pages that should implement paging because the API already supports it: +### M-9 · `EventsControllerTests.cs:L116/L169` — Magic Strings in Test Assertions -- Notifications (`/notifications`) -- Portfolio positions (`/portfolio`) if position count can grow -- News streams (Market + Stock detail) +**File:** `InventoryAlert.UnitTests/Web/Controllers/EventsControllerTests.cs` -Suggested common pagination component: +`` +`csharp +// ✅ Verifying with hardcoded strings — breaks silently if EventTypes changes +_service.Verify(s => s.PublishEventAsync(""MarketPriceAlert"", ...), Times.Once); +_service.Verify(s => s.PublishEventAsync(""CompanyNewsAlert"", ...), Times.Once); +``` -- `Pagination` with `page`, `pageSize`, `totalPages`, `onPageChange` -- optionally `InfiniteScroll` mode for notifications/news +Same root cause as M-1 but in tests. The `EventTypes.*` constants should be used here too. -### 4.2 Standardize confirm + error UX +--- -Currently: +## 🟡 LOW — Phase 2 Additions -- some pages use `ConfirmDialog` + `Toast` -- some use `alert()` / `confirm()` +### L-6 · `IEventService.cs:L12` — Interface Returns Internal Entity Type -Recommendation: +**File:** `InventoryAlert.Api/Application/Interfaces/IEventService.cs` -- never use native `alert/confirm` -- one consistent pattern: - - optimistic UI update + Toast - - destructive action → ConfirmDialog +`` +`csharp +// ✅ Returns entity — should return EventLogResponse DTO +Task> GetEventLogsAsync(...); +``` -### 4.3 Align UI error parsing with backend `ErrorResponse` +The Application interface exposes `EventLog` (an entity) as its return type. +This couples API clients to the persistence schema. Should return an `EventLogResponse` DTO. -Backend uses: +--- -- `ErrorResponse { errors: [{ code, message, property }], errorId }` +### L-7 · `WorkerSettings.cs:L13-16` — `DatabaseSetting` Duplicated in Both Projects -Recommendation: +**File:** `InventoryAlert.Worker/Configuration/WorkerSettings.cs` -- create a single `getErrorMessage(err)` helper that: - - prefers `ErrorResponse.errors[0].message` - - falls back to generic message - - optionally surfaces `errorId` and `X-Correlation-Id` for support +`` +`csharp +// ✅ Duplicate class — ApiSettings.cs also defines this +public class DatabaseSetting +{ + public string DefaultConnection { get; set; } = string.Empty; +} +``` -### 4.4 Reduce repeated Tailwind blobs +`AppSettings.cs` in the Api project also defines `DatabaseSetting`. +Both are independent classes. Should be consolidated into +`InventoryAlert.Contracts.Configuration.SharedDatabaseSettings`. -Recommendation: +--- -- Introduce a small “UI kit” layer: - - `PageHeader`, `Card`, `Button`, `Input`, `EmptyState`, `ErrorState`, `Skeleton` -- Refactor pages to use these, improving consistency and speed of iteration. +## 💡 Enhancement Proposals -### 4.5 Rerender and state hygiene +> Not bugs — structural improvements for the next design iteration. -Recommendation: +### E-1 · Introduce `Result` Pattern in Service Layer -- Avoid long-lived intervals that rerun while tab is hidden: - - for health checks and token sync, pause when `document.hidden` -- Consider `AbortController` for page fetches to avoid setting state after unmount/navigation.",394,5080f1111fc0c2f3f9042a921808473d,doc\UI_COMPONENTS_AND_PAGES_AUDIT.md,0,279,"page, inventoryalert, symbol, enhancement, watchlist, market, ideas, stocks",1777190302.5988624,10,efcore iactionresult httppost dbcontext entity framework price drop loss productscontroller httpget threshold asnotracking httpput notification appdbcontext,# InventoryAlert.UI — Components & Pages Audit + Enhancement Suggestions | InventoryAlert.UI — Components & Pages Audit + Enhancement Suggestions This docu -doc,"--- -description: UI tech review, setup, folder structure, rendering/rerender flow, and Docker approach (documentation only). -type: reference -status: draft -version: 1.1 -tags: [ui, nextjs, react, tailwind, docker, setup, architecture, inventoryalert] -last_updated: 2026-04-26 ----",9,549c402f173a671723294d82592b3b7f,doc\UI_TECH_SETUP_AND_FLOW.md,0,280,"setup, docker, description, tech, review, folder, structure, rendering",1777190302.6013038,1,fluentassertions dbset data access dbcontext arrange act assert sku threshold price drop postgresql productservice asnotracking unit test efcore item notification appdbcontext dockerfile entity framework application service iproductservice stock container compose igenericrepository business logic postgres inventory xunit loss iproductrepository,"UI_TECH_SETUP_AND_FLOW.md | --- description: UI tech review, setup, folder structure, rendering/rerender flo" -doc,"# InventoryAlert.UI — Tech, Setup, Structure, and Rendering Flow +**Current:** Services throw `KeyNotFoundException` for not-found, return `null?` for optional results. +**Problem:** Callers must remember which methods throw vs return null, and exception catching is expensive. -This is a **documentation-only** review of the `InventoryAlert.UI` project: +**Suggested pattern:** +`` +`csharp +// Contracts/Common/Result.cs +public readonly record struct Result +{ + public T? Value { get; init; } + public bool IsSuccess { get; init; } + public string? Error { get; init; } -- current tech stack and scripts, -- file/folder structure, -- how pages render and re-render, -- layout/provider flow, -- Docker approach for running UI + Wiki (recommendations; not implemented here), -- UX/UI enhancement ideas (recommendations; not implemented here). + public static Result Ok(T value) => new() { Value = value, IsSuccess = true }; + public static Result Fail(string error) => new() { Error = error, IsSuccess = false }; + public static Result NotFound(int id) => Fail($""Entity with id {id} was not found.""); +} -Repository root: `InventoryAlert.UI/` +// Usage in service: +public async Task> GetProductByIdAsync(int id, CancellationToken ct) +{ + var product = await _repo.GetByIdAsync(id, ct); + return product is null ? Result.NotFound(id) : Result.Ok(product.ToResponse()); +} -Companion doc (deeper inventory + per-page recommendations): +// Usage in controller: +var result = await _service.GetProductByIdAsync(id, ct); +return result.IsSuccess ? Ok(result.Value) : NotFound(result.Error); +``` -- `doc/UI_COMPONENTS_AND_PAGES_AUDIT.md` +**Benefit:** Explicit, no hidden control flow, testable without try/catch. --- -## 1) Tech Stack (Observed) - -From `InventoryAlert.UI/package.json`: +### E-2 · Inject `IAlertNotifier` into `PriceAlertHandler` Now -- **Next.js** `15.1.4` (App Router enabled — `src/app/*`) -- **React** `19.0.0` -- **Tailwind CSS** `v4` (imported via CSS: `@import ""tailwindcss"";`) -- **SignalR client**: `@microsoft/signalr` `^10.0.0` -- **Testing**: `vitest` + Testing Library + JSDOM -- **TypeScript** `^5` -- `next.config.ts` sets: - - `output: ""standalone""` (good for Docker) - - `eslint.ignoreDuringBuilds = true` - - `typescript.ignoreBuildErrors = true` +**File:** `InventoryAlert.Worker/Handlers/PriceAlertHandler.cs` -Notes: +Phase F (Telegram) is designed to plug `IAlertNotifier` into this handler. +The interface `IAlertNotifier` already exists in the Api project. +The handler currently just logs — the notifier injection should be wired now +so Phase F is a one-line swap (`ConsoleAlertNotifier` → `TelegramAlertNotifier`). -- Ignoring type/build errors can mask real runtime issues; consider switching these back on once the UI stabilizes. +`` +`csharp +// Suggested now +public class PriceAlertHandler( + IAlertNotifier notifier, + ILogger logger) + : IEventHandler +{ + public async Task HandleAsync(MarketPriceAlertPayload payload, CancellationToken ct = default) + { + var message = FormatMessage(payload); + _logger.LogWarning(""{AlertMessage}"", message); + await notifier.NotifyAsync(message, ct); // Phase F: no code change needed + } +} +``` --- -## 2) Scripts / Commands +### E-3 · Propagate `CorrelationId` into SQS MessageAttributes -From `package.json`: - -- `npm run dev` → `next dev` -- `npm run build` → `next build` -- `npm run start` → `next start` -- `npm run lint` → `eslint` -- `npm run test` → `vitest run` - ---- - -## 3) Environment Variables +**File:** `InventoryAlert.Api/Infrastructure/Messaging/SnsEventPublisher.cs` -Used today: +The `CorrelationId` is already in the `EventEnvelope` and written to SNS MessageAttributes. +But the `PollSqsJob` reads the envelope body — it doesn't validate that the SQS +`MessageAttribute[""CorrelationId""]` matches the envelope's `CorrelationId`. -- `NEXT_PUBLIC_API_URL` - - consumed by: - - `InventoryAlert.UI/src/lib/api.ts` - - `InventoryAlert.UI/src/hooks/useSignalR.ts` - - default fallback in code is `http://localhost:8080` +**Suggestion:** When writing telemetry to DynamoDB in `PollSqsJob`, also push the +`CorrelationId` into the structured log context: -Recommended convention: +```csharp +using (_logger.BeginScope(new { envelope.CorrelationId, envelope.MessageId })) +{ + await handler(envelope.Payload, message.MessageId, ct); +} +``` -- Dev local: `NEXT_PUBLIC_API_URL=http://localhost:8080` -- Docker (frontend + backend on same docker network): `NEXT_PUBLIC_API_URL=http://api:8080` (or the backend service name) +This makes logs traceable from API request → SNS publish → SQS → Worker handler. --- -## 4) Folder Structure (Current) - -Top-level: - -- `InventoryAlert.UI/src/app/` — App Router routes (pages + layouts) -- `InventoryAlert.UI/src/components/` — UI components and providers -- `InventoryAlert.UI/src/hooks/` — custom hooks -- `InventoryAlert.UI/src/lib/` — API client + utilities -- `InventoryAlert.UI/public/` — static assets -- `InventoryAlert.UI/Dockerfile` — production image build (standalone output) - -Routes (observed): +### E-4 · Add `IMemoryCache` to Worker Handlers for Per-Symbol Dedup -- `src/app/page.tsx` (Dashboard / Overview) -- `src/app/market/page.tsx` -- `src/app/stocks/page.tsx` -- `src/app/stocks/[symbol]/page.tsx` -- `src/app/portfolio/page.tsx` -- `src/app/watchlist/page.tsx` -- `src/app/alerts/page.tsx` -- `src/app/notifications/page.tsx` -- `src/app/admin/health/page.tsx` -- Auth: - - `src/app/(auth)/login/page.tsx` - - `src/app/(auth)/register/page.tsx` +**Current:** `PollSqsJob` handles Redis deduplication at the message level. +`EarningsHandler` and `NewsHandler` persist the same `EarningsRecord` multiple times +if the same earnings event arrives twice (e.g., SNS retry). -Notes: +**Fix:** Add a distributed cache check inside each persistence handler before writing: -- `src/pages/` exists but appears empty. Consider removing it to reduce confusion (App Router-only project). +`` +`csharp +// EarningsHandler +var dedupKey = $""earnings:{payload.Symbol}:{payload.Period}""; +if (await _cache.GetStringAsync(dedupKey, ct) is not null) return; // skip duplicate +await _cache.SetStringAsync(dedupKey, ""1"", + new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24) }, ct); +``` --- -## 5) Layout + Provider Flow (How the App Boots) - -Entry layout: - -- `InventoryAlert.UI/src/app/layout.tsx` +### E-5 · `moto-init` — Add `init-dynamodb.sh` and Schema in Init Script -Key behaviors: +The `PHASE2_PLAN.md` calls for `moto-init/init-dynamodb.sh` to create the +`inventory-event-logs` table. This file is in the git list but hasn't been reviewed. +The `docker-compose.yml` currently does NOT call `init-dynamodb.sh` — +it's missing from the `moto-init` entrypoint. -- Injects an inline script to apply theme class (`dark`/`light`) early to reduce theme flash. -- Wraps the app with: - - `ThemeProvider` - - `NotificationProvider` - - `NavbarWrapper` (owns global search open-state) -- Renders `children` inside a centered `
` container. +**Needed in `docker-compose.yml`:** +```yaml +moto-init: + entrypoint: [""bash"", ""-c"", ""/moto-init/init-sqs.sh && /moto-init/init-dynamodb.sh""] +``` --- -## 6) Rendering / Re-render Flow (What Triggers UI Updates) - -### 6.1 Current pattern (client-first pages) - -Many pages are declared as: - -- `'use client'` -- Fetch on mount using `useEffect(() => load(), [])` -- Store results in component state via `useState` +## ✅ CONFIRMED PASSING (Updated) -Implications: +| Area | Check | +| :--- | :--- | +| Dispatcher pattern (`PollSqsJob`) | ✅ Dictionary + `UnknownEventHandler` fallback | +| Thin controllers (`ProductsController`) | ✅ Zero business logic | +| Transaction Capture (`ProductService`) | ✅ All 4 methods assign result inside lambda | +| DLQ / Retry logic | ✅ `ApproximateReceiveCount > 3` → DLQ | +| DynamoDB telemetry | ✅ Write on success + failure, 90-day TTL | +| `ILogger` everywhere | ✅ No `Console.WriteLine` found | +| Structured logging | ✅ Parameterized `{MessageId}`, `{EventType}` throughout | +| Primary constructors (most services) | ✅ Consistent across Api + Worker | +| `.AsNoTracking()` on reads | ✅ All read queries use it | +| `ExceptionHandlingMiddleware` | ✅ RFC-7807, no stack trace leakage | +| `EventTypes.All` O(1) registry | ✅ `IReadOnlySet` HashSet | +| `CorrelationIdMiddleware` ordering | ✅ First in pipeline | +| Serilog bootstrap | ✅ Both API + Worker with `try/finally + CloseAndFlush()` | +| `EventEnvelope` as `record` | ✅ Immutable, correct field comments | +| `AlertConstants` structure | ✅ `CacheKeys`, `SqsHeaders` cleanly separated | +| Sample project dual-mode (API + direct SNS) | ✅ Demonstrates both publish paths | +| `HangfireJobLoggingFilter` | ✅ Routes failures through `ILogger`, `NullLogger` fallback | +| CI pipeline architecture test gate | ✅ `ArchitectureTests` run before build |",682,fb64583e3f4984ee72572776c7e5b729,doc\archive\AUDIT_PLAN.md,0,278,"result, public, init, return, value, error, correlationid, build",1775368171.535382,455,infrastructure mock setup price drop external api savechangesasync fluentassertions productscontroller item data access domain driven design aapl returns async stock price dbset inventory iactionresult hosted service dockerfile notification postgres efcore savechanges domain entity compose commit appdbcontext backgroundservice threshold arrange act assert httpget stock ticker httppost periodictimer stock googl asnotracking application layer unitofwork executetransactionasync symbol sku iproductrepository xunit entity framework httpput container market data iproductservice rollback unit test loss igenericrepository times once verify dbcontext business logic msft postgresql quote finnhubpricesyncworker iunitofwork atomicity moq application service productservice,# Build failure is discovered AFTER expensive test runs | Build failure is discovered AFTER expensive test runs - name: Architecture Test +doc,"# Build Guide: Temporal Action Queue -- Initial HTML is minimal; most data appears after client-side fetch completes. -- Re-render triggers are primarily: - - state changes (`setState`) - - dependency changes in effects (e.g., `newsCategory`, `newsPage`) +This guide provides a detailed, step-by-step walkthrough to build the **Temporal Action Queue** project from scratch using .NET 9. -### 6.2 Example flows +--- -Dashboard (`src/app/page.tsx`): +## Phase 1: Environment Setup -- On mount, calls: - - `GET /api/v1/watchlist` - - `GET /api/v1/market/news?...` - - `GET /api/v1/portfolio/positions` -- Computes portfolio summary client-side. -- Enqueues news sync via: - - `POST /api/v1/events` with `eventType = inventoryalert.news.sync-requested.v1` +### 1. Initialize the Project +Create a new Web API project with Controllers. +```bash +dotnet new webapi -n JobQueue.Api -o . --use-controllers --no-https +``` -Market (`src/app/market/page.tsx`): +### 2. Add Dependencies +Install the required Entity Framework Core packages for PostgreSQL. +```bash +dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL +dotnet add package Microsoft.EntityFrameworkCore.Design +``` -- Re-fetches when `newsCategory` or `newsPage` changes. -Stocks (`src/app/stocks/page.tsx`): +--- -- Switches between browse mode (`/stocks?page=`) vs search mode (`/stocks/search?q=`) based on input. +## Phase 2: Core Data Infrastructure -### 6.3 Notifications (SignalR live updates) +### 3. Create the Job Model +Create `Models/ScheduledJob.cs`. This entity defines what a task looks like in the database. +```csharp +namespace JobQueue.Api.Models; -`InventoryAlert.UI/src/components/NotificationProvider.tsx`: +public class ScheduledJob +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public string TaskName { get; set; } = string.Empty; + public DateTime ScheduledAt { get; set; } + public bool IsProcessed { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; +} +``` -- Reads `auth_token` from `localStorage`. -- If token exists, connects to SignalR: - - hub path: `/hubs/notifications` (full URL uses `NEXT_PUBLIC_API_URL`) -- On `ReceiveNotification`, increments unread count and prepends notification to local state. +### 4. Setup the Database Context +Create `Data/AppDbContext.cs`. We use a **Primary Constructor** for the options. +```csharp +using Microsoft.EntityFrameworkCore; +using JobQueue.Api.Models; -Operational notes: +namespace JobQueue.Api.Data; -- This provider currently polls localStorage periodically (interval) to detect token changes; this can cause extra work/rerenders. -- Consider switching to an explicit “auth changed” event pattern in the future. +public class AppDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Jobs => Set(); +} +``` --- -## 7) API Client (Current Behavior + Standardization Notes) - -`InventoryAlert.UI/src/lib/api.ts`: - -- Attaches `Authorization: Bearer ` from localStorage when present. -- Always sends cookies (`credentials: ""include""`) to support refresh token flow. -- On `401`: - - tries refresh via `POST /api/v1/auth/refresh` - - retries the original request once - - if refresh fails, clears token and redirects to `/login` - -Standardization suggestions (ties to API error docs): +## Phase 3: The Engine (Background Job) -- Parse `ErrorResponse` from the API consistently: - - current backend error body uses `errors[]` + `errorId` - - UI currently tries `userFriendlyMessage/message/title`, which may not match API response shape -- Prefer surfacing `X-Correlation-Id` to the UI for support/debug: - - show it in error toasts, or expose a “Copy correlation id” affordance +### 5. Create the Worker Service +Create `Services/JobProcessorService.cs`. +**CRITICAL**: Background services are singletons. To use a scoped `DbContext`, you must manually create a scope using `IServiceProvider`. -See also: +```csharp +using JobQueue.Api.Data; +using Microsoft.EntityFrameworkCore; -- `doc/error_handling_and_response_standard.md` +namespace JobQueue.Api.Services; ---- +public class JobProcessorService(IServiceProvider serviceProvider, ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + logger.LogInformation(""Polling for due tasks...""); -## 8) Docker (UI + Wiki) — Recommended Approach (Not Implemented Here) + using (var scope = serviceProvider.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); -### 8.1 UI Docker (already exists) + var dueJobs = await context.Jobs + .Where(j => !j.IsProcessed && j.ScheduledAt <= DateTime.UtcNow) + .ToListAsync(stoppingToken); -`InventoryAlert.UI/Dockerfile` uses `next build` with `output: standalone` and runs `node server.js`. + foreach (var job in dueJobs) + { + logger.LogInformation(""Executing Job: {Name}"", job.TaskName); + await Task.Delay(1000, stoppingToken); // Simulate work + job.IsProcessed = true; + } -Basic build/run: + if (dueJobs.Any()) await context.SaveChangesAsync(stoppingToken); + } -```bash -docker build -t inventoryalert-ui ./InventoryAlert.UI -docker run --rm -p 3000:3000 -e NEXT_PUBLIC_API_URL=http://localhost:8080 inventoryalert-ui + await Task.Delay(30000, stoppingToken); // Wait 30 seconds + } + } +} ``` -### 8.2 Wiki Docker (recommended to add) +--- -`InventoryAlert.Wiki/` does not currently include a Dockerfile. +## Phase 4: API & Registration -Recommended pattern: +### 6. Create the Controller +Create `Controllers/JobsController.cs` to handle incoming requests. +```csharp +[ApiController] +[Route(""api/[controller]"")] +public class JobsController(AppDbContext context) : ControllerBase +{ + [HttpGet] + public async Task GetJobs() => + Ok(await context.Jobs.AsNoTracking().OrderByDescending(j => j.CreatedAt).ToListAsync()); -- build stage: `npm ci` + `npm run build` -- runtime stage: serve static `build/` output (nginx or a minimal node static server) + [HttpPost] + public async Task CreateJob([FromBody] CreateJobRequest r) + { + var job = new ScheduledJob { TaskName = r.Name, ScheduledAt = r.ExecuteAt }; + context.Jobs.Add(job); + await context.SaveChangesAsync(); + return CreatedAtAction(nameof(GetJobs), new { id = job.Id }, job); + } +} +public record CreateJobRequest(string Name, DateTime ExecuteAt); +``` -### 8.3 Two-container compose (recommended) +### 7. Configure Dependency Injection +Update `Program.cs` to link everything together. +```csharp +builder.Services.AddDbContext(options => + options.UseNpgsql(""Host=localhost;Database=jobsdb;Username=postgres;Password=password"")); -Recommended to create a frontend compose file (example name): +builder.Services.AddHostedService(); -- `docker-compose.frontend.yml` - - `ui` → `InventoryAlert.UI` on port `3000` - - `wiki` → `InventoryAlert.Wiki` on port `3001` +// Enable Static Files for the Dashboard +app.UseDefaultFiles(); +app.UseStaticFiles(); +``` -This file is not added in this doc-only task. +--- + +## Phase 5: The Interface (Dashboard) + +### 8. Create the Frontend +1. Create a `wwwroot` folder. +2. Create `wwwroot/index.html` with a modern Glassmorphism theme (refer to the project files for the full HTML/CSS/JS). +3. The dashboard connects to `/api/jobs` via JavaScript `fetch`. --- -## 9) UX/UI Enhancement Ideas (Recommended, Not Implemented) +## Phase 6: Deployment & Runtime -High-impact improvements that also reduce duplicate code: +### 9. Database Migrations +Initialize the database using the EF Core CLI tool. +```bash +dotnet ef migrations add InitialCreate +dotnet ef database update +``` -### 9.1 Introduce a small “UI kit” layer +### 10. Run the project +```bash +dotnet run +``` +Your dashboard will be available at `http://localhost:5000`. -Create reusable components: +--- -- `PageHeader` (title, subtitle, actions) -- `Card`, `StatCard` -- `Table` / `TableSkeleton` -- `EmptyState`, `ErrorState` -- `Button`, `Input`, `Badge` +## Advanced Practice Goals +- **Status Enum**: Change `IsProcessed` to `Pending`, `Running`, `Completed`. +- **Error Handling**: What if the database connection fails in the worker? Wrap the scope in a `try-catch`. +- **Cancellation**: Add a `DELETE` endpoint to cancel scheduled tasks.",173,a820b13e5f1592f716128f72bd533b6a,doc\archive\BACKGROUND_JOB_REFER.md,0,279,"create, phase, project, database, using, core, dashboard, build",1775670503.910183,1,iactionresult asnotracking infrastructure finnhubpricesyncworker domain driven design dbcontext hosted service add-migration efcore application service application layer schema change entity framework database update httppost httpput productscontroller domain entity periodictimer httpget backgroundservice iproductservice productservice appdbcontext efcore migration business logic,"# Build Guide: Temporal Action Queue | Build Guide: Temporal Action Queue This guide provides a detailed, step-by-step " +doc,"# Coding Challenge: Automated Inventory Alert System -Then refactor pages to use them to reduce repeated Tailwind strings. +## 🎯 Objective -### 9.2 Centralize toast/confirm patterns +Build a C# Web API that monitors product stock levels and generates alerts when they fall below a certain threshold. -Currently many pages implement their own toast + confirm dialog state. +## 🏗️ Requirements -Recommended: +### 1. The Entity: `Product` -- a single global Toast provider + hook (`useToast()`) -- consistent error formatting (and optionally correlation id display) +| Property | Type | Description | +| :---------------- | :---------- | :------------------------------------ | +| `Id` | `int` | Primary Key | +| `Name` | `string` | Unique name of the product | +| `StockCount` | `int` | Current units available | +| `AlertThreshold` | `int` | Trigger level for an alert | +| `LastAlertSentAt` | `DateTime?` | Timestamp of the last processed alert | -### 9.3 Improve accessibility and keyboard UX +### 2. Business Logic (API) -- Ensure modals trap focus, close on `Esc`, and are labeled correctly. -- Add `aria-live` for toast messages. +Implement a RESTful API to manage your inventory: -### 9.4 Reduce debug noise in production +- `POST /api/products`: Add a new product. +- `PUT /api/products/{id}/stock`: Update the stock count. +- `GET /api/products/low-stock`: View all products currently below threshold. -- Gate `console.log` behind `NODE_ENV !== 'production'` or a `NEXT_PUBLIC_DEBUG_LOGS=true` flag. +### 3. The Engine (Background Job) ---- +Implement a `BackgroundService` that: -## 10) Component / Hook / Page Scan (Observed) +- Runs every **5 minutes**. +- Scans the database for products where `StockCount <= AlertThreshold`. +- **Constraint**: To prevent log spam, only log the alert if `LastAlertSentAt` is null OR more than **1 hour ago**. +- Update the `LastAlertSentAt` once the alert is triggered/logged. -This section is a “what exists today” inventory (paths are workspace-relative). +### 4. Persistence -### 10.1 Pages (routes) +- Use **PostgreSQL** with **Entity Framework Core**. -App Router pages: +- Ensure migrations are applied successfully. -- `InventoryAlert.UI/src/app/page.tsx` → `/` -- `InventoryAlert.UI/src/app/market/page.tsx` → `/market` -- `InventoryAlert.UI/src/app/stocks/page.tsx` → `/stocks` -- `InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx` → `/stocks/:symbol` -- `InventoryAlert.UI/src/app/portfolio/page.tsx` → `/portfolio` -- `InventoryAlert.UI/src/app/watchlist/page.tsx` → `/watchlist` -- `InventoryAlert.UI/src/app/alerts/page.tsx` → `/alerts` -- `InventoryAlert.UI/src/app/notifications/page.tsx` → `/notifications` -- `InventoryAlert.UI/src/app/admin/health/page.tsx` → `/admin/health` +### 5. External Price Fetching (Finnhub) -Auth group pages: +Integrate with the **Finnhub Stock API** to: -- `InventoryAlert.UI/src/app/(auth)/login/page.tsx` → `/login` -- `InventoryAlert.UI/src/app/(auth)/register/page.tsx` → `/register` +- Add a property `TickerSymbol` to the `Product` entity. +- Implement a background process to fetch the current market price for each symbol. +- **Challenge**: If the market price is SIGNIFICANTLY higher than the original cost (e.g., > 20% increase), create a ""High Value"" alert even if stock is plentiful. -Global layout: +--- -- `InventoryAlert.UI/src/app/layout.tsx` +## 🛠️ Tech Stack & Standards -Static assets / styles: +- **Framework**: .NET 8 or 9 +- **DB**: Npgsql.EntityFrameworkCore.PostgreSQL -- `InventoryAlert.UI/src/app/globals.css` -- `InventoryAlert.UI/src/app/favicon.ico` +- **DI**: Remember to handle the **Scoped-in-Singleton** context issue correctly! +- **Clean Code**: Use Primary Constructors where possible. +- **Messaging**: Motor (for SNS/SQS abstraction) and Hangfire (for distributed job management). -### 10.2 Components +--- -`InventoryAlert.UI/src/components/*`: +## 🧠 Practice Tasks -- `AddSymbolModal.tsx` -- `ConfirmDialog.tsx` -- `GlobalSearch.tsx` -- `MarketStatusBanner.tsx` (+ `MarketStatusBanner.test.tsx`) -- `Navbar.tsx` -- `NavbarWrapper.tsx` -- `NotificationBell.tsx` (+ `NotificationBell.test.tsx`) -- `NotificationProvider.tsx` -- `PriceAlertModal.tsx` -- `ThemeProvider.tsx` -- `Toast.tsx` -- `TradeModal.tsx` -- `UserNav.tsx` +1. **Project Initialization**: Build the standard Web API structure yourself. +2. **Concurrency**: What happens if the background job is running while an API request updates the stock? Consider how EF Core handles tracking. +3. **Resilience**: Add a `try-catch` inside your worker. If the service fails to connect to the database, it should back off and try again in 30 seconds. +4. **Distributed Messaging**: Implement **Motor** to push ""Low Stock"" events to **AWS SNS/SQS** topics. +5. **Robust Scheduling**: Move the inventory check job from `BackgroundService` to **Hangfire** to support persistence, retries, and a dashboard monitor. -### 10.3 Hooks +_Note: Your previous work has been moved to the `/refer` folder for reference._",71,5b52d4fd44c2049d191d7317705253a2,doc\archive\challenge.md,0,280,"stock, alert, product, products, implement, inventory, entity, lastalertsentat",1775670503.924312,1,stock price symbol external api efcore migration stock ticker aapl application service hosted service asnotracking entity framework stock market data database update appdbcontext finnhubpricesyncworker inventory loss periodictimer sku msft googl productservice efcore quote threshold add-migration backgroundservice iproductservice item price drop schema change business logic notification dbcontext,# Coding Challenge: Automated Inventory Alert System | Coding Challenge: Automated Inventory Alert System 🎯 Objective Build a C Web AP +doc,"# 🔍 Code Review & Technical Debt (TODOs) -`InventoryAlert.UI/src/hooks/*`: +This document summarizes the architectural, security, and performance gaps identified during a deep code review. Inline `// TODO: [Enhancement]` and `// TODO: [Bug]` comments have been injected directly into the source code to track these issues alongside the implementation. -- `useSignalR.ts` +## 1. Security & Authentication -### 10.4 Client utilities +- **Hardcoded Fallback Credentials (`AuthController.cs`)**: If the `Auth:Username` and `Auth:Password` settings are missing from the configuration (e.g., missed environment variables in Docker), the system currently falls back to `admin`/`admin123`. This exposes the application to unintended access. + - *Action Required*: Remove the fallback. Throw a startup exception or return a 500 error if secure credentials are not supplied via configuration. -`InventoryAlert.UI/src/lib/*`: +## 2. Concurrency & Atomicity -- `api.ts` (+ `api.test.ts`, `api.refresh.test.ts`) +- **Lost Update Hazard (`ProductService.cs - UpdateStockCountAsync`)**: The method requests the product entity using `GetByIdAsync`, mutates the stock count, and then saves it via `UpdateAsync`. Any concurrent modifications to other properties (e.g., the background background price sync mutating `CurrentPrice`) will be blindly overwritten. + - *Action Required*: Use an intentional update technique like explicit column updating (`ExecuteUpdateAsync`), or introduce optimistic concurrency (`RowVersion` / Concurrency Token) on the `Product` entity. +- **Race Condition in Message Dedup (`PollSqsJob.cs`)**: The deduplication logic uses `GetStringAsync()` to check for previous processing, and then later (outside the critical path) uses `SetStringAsync()` to persist it. This creates a race condition for duplicates arriving simultaneously. + - *Action Required*: Use an atomic operation like Redis `SET ... NX` (Set Not Exists). -Notes: +## 3. Validation & Edge Cases -- `InventoryAlert.UI/src/pages/` exists but appears empty (App Router-only project). +- **Bulk Insert Validation (`ProductService.cs - BulkInsertProductsAsync`)**: + - *Issue 1*: FluentValidation does not automatically validate the internal elements of an `IEnumerable` payload at the controller level unless explicitly wired up with `RuleForEach`. The current implementation trusts the bulk payload completely. + - *Issue 2*: There is no guard tracking empty lists (`!requests.Any()`). Passing an empty array executes a pointless database transaction. + - *Action Required*: Implement a manual validator pass or a collection wrapper for validation, and add a quick empty guard. ---- +## 4. Performance & Scalability (Worker) -## 11) Paging + Consistency Targets (Recommended, Not Implemented) +- **N+1 External IO inside Loops (`SyncPricesJob.cs`, `EarningsCheckJob.cs`, `NewsCheckJob.cs`, `InsiderTxCheckJob.cs`)**: Each Hangfire background worker retrieves all products using `ToListAsync()` pulling an unbounded dataset into memory, followed by executing a sequential Finnhub HTTP API call `await Fetch(...)` per product inside a `foreach` loop. If there are thousands of products, this will lead to unbounded memory allocation, prolonged job durations, blocking threads, and immediate violation of Finnhub's generic rate limits (60 requests/min). + - *Action Required*: Change `ToListAsync()` to database batching, implement a parallel fan-out API caller (`Task.WhenAll`), and employ `SemaphoreSlim` and `Task.Delay` logic to enforce Finnhub's rate limit. -Where paging already exists in state but UX is incomplete: +## 5. Configuration Defaults -- `InventoryAlert.UI/src/app/market/page.tsx` — `newsPage` exists; add Next/Prev controls and show current page. -- `InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx` — News tab has `newsPage`; add visible paging controls. +- **Hardcoded Job CRON (`JobSchedulerService.cs`)**: The price sync Hangfire job is scheduled with a hardcoded `""*/10 * * * *""` cron expression (every 10 minutes). It completely ignores the `MinuteSyncCurrentPrice` config parameter available in `appsettings.json`. + - *Action Required*: Inject `IConfiguration` into the JobSchedulerService, dynamically calculate the CRON string based on the configuration value. +- **Hardcoded Cache TTL (`ProductService.cs`)**: `GetProductByIdAsync` sets the cache TTL permanently to 10 minutes. + - *Action Required*: Move the TTL interval to `appsettings.json`. -Where API is paged but UI does not expose paging: +## 6. Observability & Logging -- `InventoryAlert.UI/src/app/notifications/page.tsx` — API returns paged result; add paging UI or infinite scroll. -- `InventoryAlert.UI/src/app/portfolio/page.tsx` — response is `PagedResult`; add paging controls if position count can grow. +- **Missing Liveness Probes (`Program.cs`)**: In containerized environments like Docker or Kubernetes, there is no way for the orchestrator to know if the C# application is actually healthy, routing traffic normally, or silently hung in a deadlock. + - *Action Required*: Integrate ASP.NET HealthChecks (`builder.Services.AddHealthChecks()`) and map an endpoint `app.MapHealthChecks(""/health"")`. +- **Inappropriate Logging Strategy (`FinnhubClient.cs`)**: Error logging writes directly to STDOUT using `Console.WriteLine()`, bypassing the highly configurable Serilog provider. + - *Action Required*: Inject `ILogger` and write structural logs using standard `_logger.LogError(...)`. +- **Leaked Capture Variable Warning (`SyncPricesJob.cs`)**: The class constructor injects `cache` while mapping it to `_cache`. However, the variable `cache` is referenced explicitly at line 62, creating a compiler state capture warning (CS9124). + - *Action Required*: Convert the direct parameter reference to the internal `_cache` field reference.",43,172fac1a4d3444652650da8ca5109234,doc\archive\CODE_REVIEW_TODOS.md,0,281,"action, required, hardcoded, configuration, using, cache, code, into",1775670503.9112332,1,postgresql fluentassertions commit dockerfile unit test stock price productservice postgres productscontroller stock hosted service inventory iproductservice rollback finnhubpricesyncworker container dbcontext httpput appdbcontext asnotracking httppost backgroundservice item application service efcore httpget xunit arrange act assert entity framework business logic sku atomicity unitofwork quote compose iactionresult periodictimer external api market data savechanges,# 🔍 Code Review & Technical Debt (TODOs) | 🔍 Code Review & Technical Debt (TODOs) This document summarizes the architectura +doc,"# Consumer Test Setup Guide -Recommended reusable primitives: +## Purpose -- `Pagination` (page + pageSize + totalPages) -- `EmptyState` / `ErrorState` (standard handling) -- Replace all `alert()` / `confirm()` with `Toast` + `ConfirmDialog` +This document explains how the Consumer repository test setup works so the same pattern can be reused in another project. -See the per-page details in `doc/UI_COMPONENTS_AND_PAGES_AUDIT.md`. +The repository contains 3 test styles: ---- +- `src/CAL.Consumer.Api.Tests` - API integration tests + - `src/CAL.Consumer.Jobs.Tests` - background worker / queue integration tests + - `src/CAL.Consumer.Handler.Tests` - direct handler integration tests -## 12) Next Documentation Targets (If You Want) +## Test Architecture Summary -If you want, I can create additional docs (still markdown-only) for: +### `CAL.Consumer.Api.Tests` -- **UI API contract mapping** (endpoint list + response DTOs used by UI) -- **UI auth flow** (login/refresh/logout lifecycle) -- **UI notification flow** (SignalR events + unread count semantics)",372,549c402f173a671723294d82592b3b7f,doc\UI_TECH_SETUP_AND_FLOW.md,0,281,"inventoryalert, page, pages, stocks, recommended, build, auth, docker",1777190302.6013038,10,fluentassertions dbset data access dbcontext arrange act assert sku threshold price drop postgresql productservice asnotracking unit test efcore item notification appdbcontext dockerfile entity framework application service iproductservice stock container compose igenericrepository business logic postgres inventory xunit loss iproductrepository,"# InventoryAlert.UI — Tech, Setup, Structure, and Rendering Flow | InventoryAlert.UI — Tech, Setup, Structure, and Rendering Flow This is a documen" -doc,"--- -description: Plan to reuse the GitHub Wiki repo and update CI to keep it in sync with the docs in this repository (documentation only). -type: reference -status: draft -version: 1.0 -tags: [wiki, documentation, github-actions, ci, docusaurus, inventoryalert] -last_updated: 2026-04-26 ----",9,81e3cf37c55269573c8efbe26f25232b,doc\WIKI_REUSE_AND_CI_SYNC.md,0,282,"github, wiki, documentation, description, plan, reuse, repo, update",1777190302.6031837,1,dbcontext periodictimer threshold iproductrepository backgroundservice fluentassertions notification dbset arrange act assert hosted service igenericrepository entity framework xunit unit test appdbcontext finnhubpricesyncworker price drop efcore data access asnotracking loss,WIKI_REUSE_AND_CI_SYNC.md | --- description: Plan to reuse the GitHub Wiki repo and update CI to keep it in -doc,"# GitHub Wiki Reuse + CI Sync Plan (InvestManagementSystem) +Use this test project when the target is the HTTP surface of the API. -Target GitHub Wiki (UI): +Main characteristics: -- `https://github.com/nhonvo/InvestManagementSystem/wiki` +- sends real HTTP requests to the API + - uses seeded DynamoDB data + - uses SQS test helpers + - validates behavior through response payloads and container logs + - depends on the `consumer_api` container being available -Important note: GitHub Wikis are backed by a **separate git repository**: +Important setup files: -- `https://github.com/nhonvo/InvestManagementSystem.wiki.git` +- `src/CAL.Consumer.Api.Tests/Shared/Config/TestFixture.cs` + - `src/CAL.Consumer.Api.Tests/Shared/Config/TestBeforeAfterCustom.cs` + - `src/CAL.Consumer.Api.Tests/Shared/Config/ActionTestConfig.cs` + - `src/CAL.Consumer.Api.Tests/appsettingsapitest.json` -This document proposes how to **reuse** that wiki repo and how to **update CI** so changes in this repository can be published to the GitHub Wiki automatically. +### `CAL.Consumer.Jobs.Tests` -No CI changes are implemented in this task (doc-only). +Use this test project when the target is the background queue processing pipeline. ---- +Main characteristics: -## 1) What we have today +- pushes messages into SQS + - lets the running Jobs worker process them + - validates logs, message deletion, and DLQ behavior + - depends on the `consumer_jobs` container being available -- Wiki source site in this repo: `InventoryAlert.Wiki/` (Docusaurus) - - primary authoring folder: `InventoryAlert.Wiki/docs/` - - build output: `InventoryAlert.Wiki/build/` (static website) -- Current CI for docs: `.github/workflows/deploy-wiki.yml` - - builds Docusaurus and deploys to **GitHub Pages** (not GitHub Wiki). +Important setup files: -So today you effectively have: +- `src/CAL.Consumer.Jobs.Tests/Shared/Config/TestFixture.cs` + - `src/CAL.Consumer.Jobs.Tests/Shared/Config/ActionTestConfig.cs` + - `src/CAL.Consumer.Jobs.Tests/Shared/Config/TestBeforeAfterCustom.cs` + - `src/CAL.Consumer.Jobs.Tests/appsettings.json` -- “nice website docs” = GitHub Pages (Docusaurus) -- “GitHub Wiki” = separate, currently not auto-synced +### `CAL.Consumer.Handler.Tests` ---- +Use this test project when the target is a specific handler implementation and the full worker loop is not required. -## 2) Choose the canonical source +Main characteristics: -Two valid strategies: +- resolves handlers directly from DI + - reuses the Jobs dependency graph + - uses WireMock admin APIs to inspect outbound requests + - captures logs in memory through `TestLoggerProvider` + - disables parallelization for shared-state safety -### Strategy A (recommended): Canonical = Docusaurus docs; Wiki = export/sync +Important setup files: -- Author docs in `InventoryAlert.Wiki/docs/`. -- CI exports Markdown to the GitHub Wiki repo. -- Keep `.github/workflows/deploy-wiki.yml` (Pages) if you still want the Docusaurus site. +- `src/CAL.Consumer.Handler.Tests/SetupDI.cs` + - `src/CAL.Consumer.Handler.Tests/Tests/Infrastructure/HandlerTestFixture.cs` + - `src/CAL.Consumer.Handler.Tests/Tests/Infrastructure/HandlerTestCollection.cs` + - `src/CAL.Consumer.Handler.Tests/Tests/Infrastructure/TestLoggerProvider.cs` + - `src/CAL.Consumer.Handler.Tests/Tests/Handlers/HandlerTestBase.cs` + - `src/CAL.Consumer.Handler.Tests/appsettings.json` -### Strategy B: Canonical = GitHub Wiki repo; Docusaurus optional +## High-Level Architecture -- Author directly in the GitHub wiki repo (via UI or git). -- Optionally mirror back into this repo (harder to automate cleanly). +```text + Api.Tests + -> Http client + -> running API container + -> controllers + middleware + application services + -> DynamoDB/SQS/external HTTP services + -> assert response + docker logs -This plan assumes Strategy A because it keeps “doc-as-code” together with the application source. +Jobs.Tests + -> SQS test client + -> running Jobs container + -> queue polling + message processor + handlers + -> DynamoDB/Redis/external HTTP services + -> assert docker logs + queue/DLQ behavior ---- +Handler.Tests + -> test fixture + -> production Jobs DI graph + -> concrete handler resolved from DI + -> repository + HTTP clients + security helper + -> assert WireMock calls + in-memory logs + ``` -## 3) Export model: Docusaurus → GitHub Wiki +## Local Infrastructure Required -GitHub Wiki Markdown constraints to consider: +The tests depend on Docker services defined in `docker-compose.yml`. -- Docusaurus frontmatter (`---`) may render as plain text in GitHub Wiki. -- Docusaurus MDX/shortcodes/admonitions may not render. +Required services: -Recommended export rules: +- `aws-proxy-local` on `http://localhost:4566` + - `dynamodb` on `http://localhost:8000` + - `moto` for AWS mocks + - `wire_mock` on `http://localhost:40485` + - `redis` on `localhost:6379` + - `api` container named `consumer_api` + - `jobs` container named `consumer_jobs` + - optional init containers: `dynamodb-init`, `moto-init` -1) Strip frontmatter blocks. -2) Convert `InventoryAlert.Wiki/docs/index.md` to `Home.md` in the wiki repo (GitHub wiki landing page). -3) Decide how to map paths: - - **Flat pages (recommended)**: `06-background-jobs/workers.md` → `06-background-jobs-workers.md` - - Keep links consistent by rewriting relative links during export. -4) Keep Mermaid diagrams (GitHub supports Mermaid in Markdown in most contexts; validate in the wiki UI). +Relevant compose sections: -Output folder suggestion in CI: +- AWS proxy: `docker-compose.yml:7-23` + - API container: `docker-compose.yml:118-136` + - Jobs container: `docker-compose.yml:140-159` + - WireMock: `docker-compose.yml:164-170` + - Redis: `docker-compose.yml:175-183` -- `artifacts/wiki-export/` (generated) +## What Each Infrastructure Service Does ---- +### `aws-proxy-local` -## 4) Manual sync (local workflow) +Acts as the single local AWS endpoint exposed to the application. In this repo it is used as the local replacement for AWS service URLs. Test code and containers point to `http://localhost:4566` or `http://aws-proxy-local:4566`. -One-time setup: +### `dynamodb` -```bash -git clone https://github.com/nhonvo/InvestManagementSystem.wiki.git _wiki -``` +Provides DynamoDB Local. Test fixtures create and clear the `ConsumerMovesTable` so each scenario starts from a known state. -Then copy exported `.md` files into `_wiki/`, commit, push: +### `moto` -```bash -cd _wiki -git add . -git commit -m ""Sync wiki from InventoryAlert.Wiki/docs"" -git push -``` +Provides mock AWS behavior for SQS and related services. The test projects push messages to queue URLs that resolve through the local AWS stack. -Tip: do not copy Docusaurus `build/` output to the GitHub wiki repo. Keep the wiki as source Markdown only. +### `wire_mock` ---- +Mocks downstream HTTP services such as: -## 5) CI sync (GitHub Actions) — recommended workflow design +- token endpoints + - order status + - DHL Link + - consignment services + - Google/Google Route + - hub endpoints + - vehicle lifecycle endpoints -Create a new workflow (example filename): +This is the main assertion point for `Handler.Tests` and a supporting dependency for the other test projects. -- `.github/workflows/sync-github-wiki.yml` +### `redis` -Trigger: +Supports production behavior reused by Jobs and handler tests. Even when a test is not directly asserting Redis behavior, the DI graph may require it. -- on push to `main` -- only when `InventoryAlert.Wiki/docs/**` changes (and optionally `InventoryAlert.Wiki/sidebars.ts`) +### `api` and `jobs` -Authentication: +These are the actual application containers under test for the API and Jobs integration suites. Their logs are read by the integration tests. -- Use a PAT stored in a secret like `WIKI_PUSH_TOKEN` - - In practice, `GITHUB_TOKEN` often does not have sufficient permission to push to the `.wiki.git` repo. +## Configuration Model -High-level steps: +### API tests -1) Checkout this repository. -2) Generate a GitHub-wiki-compatible export into `artifacts/wiki-export/`. -3) Checkout the wiki repo into `artifacts/wiki-repo/`. -4) Copy export output into the wiki repo working tree. -5) Commit and push if there are changes. +`src/CAL.Consumer.Api.Tests/appsettingsapitest.json` -Workflow skeleton (illustrative only): +Key values: -```yaml -name: Sync GitHub Wiki +- `ApiUrl` points to local nginx HTTPS proxy + - AWS test endpoint points to `http://127.0.0.1:4566` + - external service calls are redirected to WireMock on `http://localhost:40485` -on: - push: - branches: [""main""] - paths: - - ""InventoryAlert.Wiki/docs/**"" - - "".github/workflows/sync-github-wiki.yml"" - workflow_dispatch: +### Jobs tests -jobs: - sync: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4",145,81e3cf37c55269573c8efbe26f25232b,doc\WIKI_REUSE_AND_CI_SYNC.md,0,283,"wiki, github, repo, docusaurus, docs, sync, inventoryalert, export",1777190302.6031837,10,dbcontext periodictimer threshold iproductrepository backgroundservice fluentassertions notification dbset arrange act assert hosted service igenericrepository entity framework xunit unit test appdbcontext finnhubpricesyncworker price drop efcore data access asnotracking loss,# GitHub Wiki Reuse + CI Sync Plan (InvestManagementSystem) | GitHub Wiki Reuse + CI Sync Plan (InvestManagementSystem) Target GitHub Wiki (UI -doc,"# 1) Export docs => artifacts/wiki-export - - name: Export wiki markdown - run: | - mkdir -p artifacts/wiki-export",149,81e3cf37c55269573c8efbe26f25232b,doc\WIKI_REUSE_AND_CI_SYNC.md,0,284,"export, wiki, artifacts, docs, name, markdown, mkdir",1777190302.6031837,146,dbcontext periodictimer threshold iproductrepository backgroundservice fluentassertions notification dbset arrange act assert hosted service igenericrepository entity framework xunit unit test appdbcontext finnhubpricesyncworker price drop efcore data access asnotracking loss,# 1) Export docs => artifacts/wiki-export | 1) Export docs => artifacts/wiki-export - name: Export wiki markdown -doc,# TODO: implement export script later (strip frontmatter + rewrite links + map Home.md),150,81e3cf37c55269573c8efbe26f25232b,doc\WIKI_REUSE_AND_CI_SYNC.md,0,285,"todo, implement, export, script, later, strip, frontmatter, rewrite",1777190302.6031837,150,dbcontext periodictimer threshold iproductrepository backgroundservice fluentassertions notification dbset arrange act assert hosted service igenericrepository entity framework xunit unit test appdbcontext finnhubpricesyncworker price drop efcore data access asnotracking loss,# TODO: implement export script later (strip frontmatter + rewrite links + map Home.md) | TODO: implement export script later (strip frontmatter + rewrite links + map Hom -doc,# e.g. node ./scripts/export-wiki.mjs,152,81e3cf37c55269573c8efbe26f25232b,doc\WIKI_REUSE_AND_CI_SYNC.md,0,286,"node, scripts, export, wiki",1777190302.6031837,151,dbcontext periodictimer threshold iproductrepository backgroundservice fluentassertions notification dbset arrange act assert hosted service igenericrepository entity framework xunit unit test appdbcontext finnhubpricesyncworker price drop efcore data access asnotracking loss,# e.g. node ./scripts/export-wiki.mjs | e.g -doc,"# 2) Checkout GitHub Wiki repo - - name: Checkout wiki repo - run: | - git clone ""https://x-access-token:${WIKI_PUSH_TOKEN}@github.com/nhonvo/InvestManagementSystem.wiki.git"" artifacts/wiki-repo - env: - WIKI_PUSH_TOKEN: ${{ secrets.WIKI_PUSH_TOKEN }}",159,81e3cf37c55269573c8efbe26f25232b,doc\WIKI_REUSE_AND_CI_SYNC.md,0,287,"wiki, repo, checkout, github, name, clone, https, access",1777190302.6031837,153,dbcontext periodictimer threshold iproductrepository backgroundservice fluentassertions notification dbset arrange act assert hosted service igenericrepository entity framework xunit unit test appdbcontext finnhubpricesyncworker price drop efcore data access asnotracking loss,# 2) Checkout GitHub Wiki repo | 2) Checkout GitHub Wiki repo - name: Checkout wiki repo run: | -doc,"# 3) Copy, commit, push - - name: Publish - run: | - rsync -a --delete artifacts/wiki-export/ artifacts/wiki-repo/ - cd artifacts/wiki-repo - git status --porcelain - if [ -n \""$(git status --porcelain)\"" ]; then - git config user.name \""github-actions[bot]\"" - git config user.email \""github-actions[bot]@users.noreply.github.com\"" - git add . - git commit -m \""Sync wiki\"" - git push - fi -``` +`src/CAL.Consumer.Jobs.Tests/appsettings.json` ---- +Key values: -## 6) How this co-exists with the current `deploy-wiki.yml` +- queue endpoint uses `http://127.0.0.1:4566/000000000000/MessageQueue.fifo` + - Redis host is `redis` + - most external dependencies use `http://localhost:40485` -You have two publishing targets: +### Handler tests -- GitHub Pages (Docusaurus site) → keep `.github/workflows/deploy-wiki.yml` -- GitHub Wiki (markdown) → add `.github/workflows/sync-github-wiki.yml` +`src/CAL.Consumer.Handler.Tests/appsettings.json` -This gives: +Key values: -- “pretty docs” for reading (Pages) -- “quick editing / discoverability” for contributors (Wiki) +- AWS service URL uses `http://localhost:4566` + - SQS endpoint is redirected through WireMock for request inspection + - downstream services point to WireMock + - test fixture resets DynamoDB, WireMock, and captured logs before each scenario -If you only want GitHub Wiki going forward, you can retire `deploy-wiki.yml` later.",190,81e3cf37c55269573c8efbe26f25232b,doc\WIKI_REUSE_AND_CI_SYNC.md,0,288,"wiki, github, artifacts, deploy, commit, push, name, repo",1777190302.6031837,160,dbcontext periodictimer threshold iproductrepository backgroundservice fluentassertions notification dbset arrange act assert hosted service igenericrepository entity framework xunit unit test appdbcontext finnhubpricesyncworker price drop efcore data access asnotracking loss,"# 3) Copy, commit, push | 3) Copy, commit, push - name: Publish run: | rsync -a --" -doc,"--- -description: Worker job + event flow review (findings, risks, and enhancement recommendations). Content moved out of Wiki per request. -type: reference -status: draft -version: 1.1 -tags: [worker, hangfire, sqs, sns, events, routing, review, enhancements, inventoryalert] -last_updated: 2026-04-26 ----",9,af2cebc4f95126d5c1d8ee9aa64a32bf,doc\worker_jobs_and_event_flow_review.md,0,289,"worker, review, description, event, flow, findings, risks, enhancement",1777190302.622038,1,dbcontext iproductservice threshold notification asnotracking hosted service stock price business logic entity framework price drop finnhubpricesyncworker loss application service external api appdbcontext quote market data productservice periodictimer backgroundservice efcore,"worker_jobs_and_event_flow_review.md | --- description: Worker job + event flow review (findings, risks, and enhancemen" -doc,"# Worker Jobs & Event Flow (Review + Enhancements) +## Detailed Setup Flow -This document contains **review findings and enhancement recommendations** for: +### API test setup flow -- `InventoryManagementSystem/InventoryAlert.Worker` (Hangfire jobs + SQS processing) -- API → messaging → Worker end-to-end event flow +`TestFixture` in `src/CAL.Consumer.Api.Tests/Shared/Config/TestFixture.cs` does the following: -Per request, this content is kept under `doc/` (not in Wiki pages). +1. builds configuration from `appsettingsapitest.json` and environment variables + 2. creates a `ServiceCollection` + 3. binds test settings with `ConfigureValidatableSetting` + 4. constructs an internal `AppSettings` object for local AWS and mocked HTTP dependencies + 5. registers DynamoDB, SQS, HTTP clients, schedulers, Google services, and hub services + 6. builds a static service provider through `ServiceLocator.ServiceProvider` + 7. starts `DockerLogReader` for the `consumer_api` container + 8. clears existing logs, creates the DynamoDB table, and clears SQS messages ---- +This means API tests are not spinning up the API process in-memory. They are preparing helper services locally while the real API container runs separately in Docker. -## 1) Current Worker Topology (Observed in Code) +### Jobs test setup flow -### 1.1 Recurring jobs (Hangfire) +`TestFixture` in `src/CAL.Consumer.Jobs.Tests/Shared/Config/TestFixture.cs` does the following: -Registered in `InventoryManagementSystem/InventoryAlert.Worker/Hosting/JobSchedulerService.cs`: +1. builds configuration from `appsettings.json` + 2. binds `ServiceTestAppSettings` + 3. registers SQS, DynamoDB, HTTP clients, DynamoDB helpers, and test clients + 4. builds the shared service provider through `ServiceLocator.ServiceProvider` + 5. ensures the order table exists and clears previous database content + 6. starts `DockerLogReader` for the `consumer_jobs` container + 7. clears queue and DLQ messages -- `sync-prices` → `SyncPricesJob.ExecuteAsync` -- `sync-metrics` → `SyncMetricsJob.ExecuteAsync` -- `sync-earnings` → `SyncEarningsJob.ExecuteAsync` -- `sync-recommendations` → `SyncRecommendationsJob.ExecuteAsync` -- `sync-insiders` → `SyncInsidersJob.ExecuteAsync` -- `news-sync` → `NewsSyncJob.ExecuteAsync` -- `cleanup-prices` → `CleanupPriceHistoryJob.ExecuteAsync` +These tests then inject messages into SQS and wait for the running Jobs container to process them. -### 1.2 SQS processing (native BackgroundService) +### Handler test setup flow -`InventoryManagementSystem/InventoryAlert.Worker/Hosting/SqsListenerService.cs` runs a continuous polling loop (gated by `WorkerSettings.IsPollMessage`), delegating to: +`HandlerTestFixture` in `src/CAL.Consumer.Handler.Tests/Tests/Infrastructure/HandlerTestFixture.cs` does the following: -- `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` - - long-polls SQS via `ISqsHelper.ReceiveMessagesAsync` - - runs Redis dedup (`SET NX`) + cooldown logic - - routes to `IIntegrationMessageRouter` +1. builds configuration from `appsettings.json` + 2. creates a `TestLoggerProvider` for in-memory log capture + 3. builds DI through `SetupDI.SetupJobsInfrastructure(...)` + 4. reuses production Jobs registrations: + - `services.SetupDatabases(...)` + - `ApplicationServicesExtensions.AddApplicationServices(...)` + - `services.AddHttpClients(...)` + 5. adds test logging overrides + 6. resolves `ISecurityServiceHelper` and warms required tokens + 7. resets state by clearing DynamoDB, resetting WireMock, and clearing logs -### 1.2.1 DLQ + retry behavior (what happens today when a message fails?) +This is the cleanest reusable pattern because it exercises real handlers using the production DI graph without requiring the background queue polling loop. -This clarifies the **actual runtime behavior** when the Worker polls SQS and message handling fails. +## How Per-Test Data Setup Works -**SQS-side retry/DLQ mechanics (in general)** +### API and Jobs tests -- Each time a message is received but **not deleted**, SQS will make it visible again after the **queue `VisibilityTimeout`**. -- SQS tracks a delivery counter (`ApproximateReceiveCount`). -- If the main queue is configured with a **RedrivePolicy** (DLQ + `maxReceiveCount`), then once the counter exceeds that value, SQS will move the message to the **DLQ** and it will no longer be delivered to consumers from the main queue. +These projects use `TestBeforeAfterCustom` attributes to seed and remove data automatically. -Local/dev evidence (Moto init script): +Pattern: -- `InventoryManagementSystem/SolutionFolder/moto-init/init-all.sh` creates: - - `event-queue` with `VisibilityTimeout=30s` and `RedrivePolicy.maxReceiveCount=3` - - `inventory-event-dlq` as the DLQ target +1. the test `DisplayName` begins with a scenario ID such as `TC671435` + 2. `Before(...)` extracts that scenario ID + 3. `DataSeeding.DataAddFlow(...)` loads the matching seed data + 4. the test runs + 5. `After(...)` calls `DataSeeding.DataRemoveFlow(...)` -**Worker-side behavior (current code)** +This makes each test case strongly tied to a scenario-based file name convention. -- Polling: `SqsHelper.ReceiveMessagesAsync` long-polls (`WaitTimeSeconds=20`) and requests system attributes including `ApproximateReceiveCount`. - - File: `InventoryManagementSystem/InventoryAlert.Worker/Utilities/SqsHelper.cs` -- Delete-on-success: `ProcessQueueJob.ProcessBatchAsync` deletes the message **only when** `DispatchInternalAsync(...)` returns `success=true`. - - File: `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` -- On handler exception, `DispatchInternalAsync(...)` returns `false` → message is **not deleted** → SQS will retry after `VisibilityTimeout`. - - This is the intended “retry by redelivery” mechanism. +### Handler tests -**Important caveat: current Redis dedup logic effectively cancels retries after the first failure** +These tests are more explicit. -In `DispatchInternalAsync(...)` the Worker sets a Redis “processed” key **before** executing the router/handler: +They usually call either: -- `dedupKey = msg:processed:{envelope.MessageId}` -- It is written with TTL 30 minutes using `SET NX`. +- `ResetAsync()` + - `ResetAndSeedAsync(orderId)` -If handling then throws: +The shared `HandlerTestBase` handles: -- The method returns `false` (so SQS will redeliver), -- but on redelivery the dedup key already exists, so the Worker treats the message as a duplicate and returns `true` (ACK), which deletes it from the main queue. +- scenario ID extraction from `DisplayName` + - seed file location + - request file location + - expected response/log file location -Net effect (today): +This makes the scenario contract very visible inside each test. -- “Retry” happens at most once (a redelivery), but the Worker will usually **ACK the redelivery without re-processing**, so the message is effectively **dropped** after the first failure. -- Because the message gets deleted on that redelivery, it may never reach the DLQ even if the queue has a redrive policy. +## How Assertions Work -**Additional caveat: manual receive-count cutoff is inconsistent with DLQ** +## 1. API tests: response + docker logs -`ProcessQueueJob` contains a hard-coded cutoff: +Typical API assertion flow: -- if `ApproximateReceiveCount > 5` it logs a warning and returns `true` (ACK/delete). +1. build request model + 2. call a client wrapper such as `AppointmentOptionClient` or `VehicleEventClient` + 3. use `ActionTestConfig.RunActionAndViewLog(...)` + 4. get both: + - HTTP response + - filtered log lines from the `consumer_api` container + 5. assert status code, payload, and expected log fragments -This is not aligned with the dev queue redrive policy (`maxReceiveCount=3`), and if the queue has a DLQ configured, deleting the message at high receive count prevents SQS from redriving it to DLQ (message is removed instead). +`ActionTestConfig` for API tests works by: -**What to expect operationally** +- recording start time before the action + - executing the HTTP call + - reading correlation ID from the response header `X-CoxAuto-Correlation-Id` + - scanning captured docker logs + - filtering logs by time range first + - extracting `TraceId` + - narrowing the final log list to entries associated with the request trace -- If a message fails due to a transient downstream error, you currently may not get automatic retries; it can be lost due to Redis dedup behavior. -- DLQ will only reliably capture poison messages if the Worker allows them to be retried/redriven (i.e., does not delete them early). +This is why API tests can assert both business result and the internal request flow. -**Recommended target behavior (so retries + DLQ are meaningful)** +Common assertion style: -- Let SQS manage retries: - - On failure: do **not** delete the message. - - On success: delete the message. - - Configure `VisibilityTimeout` and `RedrivePolicy.maxReceiveCount` to match desired retry cadence. -- Move “processed/dedup” markers to **after** successful processing, or store a separate “in-flight” key with a short TTL that doesn’t suppress redelivery attempts. - - Rule of thumb: never let dedup turn a failure into a successful ACK. -- Avoid manual “receiveCount cutoff → ACK” unless you explicitly persist the failed payload somewhere (DynamoDB / DB / blob) before deleting it. - - If you want a manual cutoff, prefer: on cutoff → emit a “dead-lettered” event / persist diagnostics → then delete. -- Decide (and document) the retry policy knobs as configuration: - - `MaxReceiveCount` (DLQ threshold) - - `VisibilityTimeoutSeconds` - - `BackoffStrategy` (if using `ChangeMessageVisibility` to slow down hot-failing messages) +- `Assert.Equal(HttpStatusCode.OK, response.StatusCode)` + - `Assert.NotNull(response.Data)` + - `Assert.Contains(logs, x => x.Contains(""GenerateAppointmentOptionsRequestLogging""))` + - `Assert.Contains(logs, x => x.Contains(""GenerateAppointmentOptionsResponseLogging""))` -**DLQ operations (today)** +### Strengths -- The Worker polls only the main queue (`event-queue`). Messages in the DLQ (`inventory-event-dlq`) will sit until a human/tool inspects or redrives them. -- In local dev (Moto), you can inspect DLQ messages with AWS CLI (same endpoint used in `moto-init`): +- validates full request pipeline + - proves middleware and logging behavior + - correlates one request to one trace -```bash -aws sqs receive-message --queue-url ""$(aws sqs get-queue-url --queue-name inventory-event-dlq --endpoint-url http://moto:5000 --query 'QueueUrl' --output text)"" --endpoint-url http://moto:5000 -``` +### Weaknesses -- Retrying a DLQ message typically means “redrive” back to the source queue (AWS console has a Redrive UI) or manually `SendMessage` back to `event-queue` after you’ve fixed the root cause. +- brittle when log message text changes + - depends on container log formatting and timing + - slower than handler-level tests -### 1.3 Unused / not wired (needs decision) +## 2. Jobs tests: queue behavior + docker logs + DLQ checks -Found in code but not referenced: +Typical Jobs assertion flow: -- `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SqsScheduledPollerJob.cs` (Hangfire-style single-shot poller) -- `InventoryManagementSystem/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs` (Hangfire failure/retry logging filter) +1. create or load a queue payload + 2. send it to SQS using the test `SqsClient` + 3. wait until the `consumer_jobs` container emits the expected log lines + 4. assert log content and sometimes queue or DLQ state -Recommendation: pick one supported polling strategy (native BackgroundService OR Hangfire poller) and wire/remove the other to reduce confusion. +`ActionTestConfig` for Jobs tests provides log waiting helpers such as: -Also present but unused today: +- `WaitForLogMessage(...)` + - `WaitForLogMessageForSchedulingEvent(...)` + - `GetLogMessageWithMsgId(...)` -- `InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs` -- `InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskProcessor.cs` +The matching strategy is simpler than API tests: -These implement a C# internal work queue (`System.Threading.Channels`) pattern, but there is currently no producer calling `QueueBackgroundWorkItemAsync`, so SQS processing is **not** using the internal queue. +- start from current UTC time + - repeatedly read docker logs + - filter logs newer than the start time + - stop when a keyword has appeared the expected number of times + - for message-specific flows, filter by the SQS message ID ---- +Typical assertions include: -## 2) Event Flow: Known Mismatches / Risks +- message processed and deleted + - message retained and eventually routed to DLQ + - specific processing steps emitted expected log events -### 2.1 Message contract mismatch: `EventEnvelope` vs raw payload +### Example outcomes asserted -`ProcessQueueJob` deserializes `message.Body` as `EventEnvelope`: +- success path: `SUCCESSFULLY handle message ... deleting message` + - retain path: no delete operation yet + - failure path: repeated failure log entries and message present in DLQ -- `InventoryManagementSystem/InventoryAlert.Domain/Events/EventEnvelope.cs` -- `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` +## 3. Handler tests: WireMock calls + in-memory logs + repository state -But `IntegrationMessageRouter` currently: +Typical handler assertion flow: -- expects `message.MessageAttributes[""MessageType""]` -- deserializes `message.Body` directly into handler payload models +1. resolve a concrete handler from DI + 2. load the scenario request JSON + 3. create a synthetic `Amazon.SQS.Model.Message` + 4. invoke `handler.HandleMessage(message, token)` directly + 5. assert against: + - repository state + - WireMock recorded requests and responses + - in-memory captured logs + - whether a delete operation was sent for the SQS receipt handle -File: `InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs` +### WireMock-based assertions -Risk: +`HandlerTestFixture` uses the WireMock admin endpoints: -- routing can fail even when SQS contains valid `EventEnvelope` bodies. +- `/__admin/reset` to clear prior state + - `/__admin/requests` to inspect request history -### 2.2 SQS message attributes are not requested in the poller +It exposes helpers such as: -`InventoryManagementSystem/InventoryAlert.Worker/Utilities/SqsHelper.cs` requests system attributes only: +- `FindWiremockRequestsAsync(...)` + - `GetServeEventsAsync(...)` + - `EnsureMessageDeletedAsync(...)` + - `EnsureMessageRetainedAsync(...)` -- `MessageSystemAttributeNames = [""ApproximateReceiveCount"", ""SentTimestamp""]` -- does not request `MessageAttributeNames` +These methods allow the test to verify: -Risk: +- which downstream endpoint was called + - how many times it was called + - request body content + - returned HTTP status code + - whether the handler triggered SQS delete behavior -- attribute-based routing won’t work reliably even if attributes exist. +### Log assertions in handler tests -### 2.3 CorrelationId propagation is intended, but fragile +Handler tests do not scrape container logs. -Strengths: +Instead: -- API stamps `X-Correlation-Id` (`CorrelationIdMiddleware`) -- Worker pushes `CorrelationId` into log scope when it has an envelope (`ProcessQueueJob`) +- `TestLoggerProvider` is registered into DI + - every logger entry is captured in memory as `LogEntry` + - `HandlerTestBase` compares actual captured logs against expected log files -Risk: +This is more deterministic than docker log scraping because: -- publishing must reliably stamp `EventEnvelope.CorrelationId` (API `EventService` currently doesn’t). +- it is synchronous to the test process + - it does not depend on Docker output timing + - it avoids parsing timestamps from container output ---- +### Repository assertions -## 3) Enhancement Plan (Recommended) +Some handler tests also query `IConsumerOrderRepository` directly to verify: -### Chosen direction (per preference): Option C — SQS retries + DLQ, with Hangfire DLQ reprocessor +- created records + - updated flags + - record absence on failure paths -Primary goal: +This gives a stronger assertion than logs alone. -- Let **SQS** handle automatic retries and DLQ routing (visibility timeout + redrive policy). -- Use **Hangfire Dashboard** to manage *manual recovery* by running a **DLQ reprocessor/redrive job** you can retry from the UI. +## Assertion Strategy Comparison -What this gives you: +| Test project | Main assertion style | Extra assertion style | Coupling | + |---|---|---|---| + | `CAL.Consumer.Api.Tests` | HTTP response | docker logs | high environment coupling | + | `CAL.Consumer.Jobs.Tests` | queue outcome | docker logs + DLQ | high environment coupling | + | `CAL.Consumer.Handler.Tests` | WireMock + repository state | in-memory logs | lower runtime coupling | -- Automatic retries remain “queue-native”. -- Operators get a reliable “button” in Hangfire to re-run recovery tasks (redrive/replay batches from DLQ after a fix). +## Recommended Setup Steps for Another Project -### P0 — Make event handling deterministic (one contract, one router) +### 1. Separate test layers -Goal: +Create separate test projects for: -- SQS body is always `EventEnvelope` JSON -- Worker routes by `envelope.EventType` -- Worker deserializes `envelope.Payload` -- message attributes are optional (debug / filtering), not required for correctness +- API endpoint tests + - background worker tests + - direct handler tests -### P0 — Ensure correlation is end-to-end (search by one id) +This keeps feedback loops clear: -Goal: searching Seq by `CorrelationId` shows: +- API tests validate the HTTP boundary + - worker tests validate queue orchestration + - handler tests validate business logic with lower cost -1) API request -2) publish log -3) Worker consumption -4) handler logs +### 2. Standardize local dependencies -### P1 — Improve job operability (Hangfire) +Use Docker Compose to provide: -Goal: +- DynamoDB Local or equivalent datastore emulator + - SQS/SNS emulator + - WireMock for external HTTP dependencies + - Redis if production code requires it + - real application containers when full integration behavior is needed -- Wire `HangfireJobLoggingFilter` globally so failures/retries are logged consistently. -- Standardize job logs (`JobName`, `ElapsedMs`, `Succeeded`, `ItemsProcessed`, `CorrelationId` when event-triggered). +### 3. Centralize fixture bootstrapping -Add (Option C core): +Create one fixture per test style. -- Introduce a **DLQ reprocessor** Hangfire job (design described below) to: - - inspect DLQ, - - republish/redrive messages back to the main queue, - - record what was replayed (ids + counts), - - and surface failures in Hangfire so the Dashboard “Retry” button is meaningful. +Each fixture should: -### P1 — Make DLQ actually capture failures (don’t ACK failures accidentally) +- load test configuration from `appsettings.json` + - register production services through the normal composition root where possible + - override only the parts needed for testing + - reset shared state before each test -Goal: if a message keeps failing, it should naturally reach DLQ; if it succeeds, ACK/delete it. +### 4. Prefer production DI reuse -Key changes required (because current behavior can drop messages before DLQ): +The best reusable pattern in this repository is in `src/CAL.Consumer.Handler.Tests/SetupDI.cs`. -- Ensure “dedup/processed” markers never convert a failure into a successful ACK. - - Today Redis `msg:processed:{MessageId}` is written before processing and can cause the first redelivery to be ACK’d as a “duplicate”. -- Remove/align the manual cutoff that ACKs messages by `ApproximateReceiveCount`. - - The queue redrive policy already controls the cutoff (`maxReceiveCount`). - - If you keep a manual cutoff, treat it as “move to DLQ / persist diagnostics”, not “delete silently”. +Instead of duplicating registrations, it reuses production startup methods: -### P1 — Make concurrency & rate limits configurable +- `services.SetupDatabases(...)` + - `ApplicationServicesExtensions.AddApplicationServices(...)` + - `services.AddHttpClients(...)` -Goal: +For another project, follow the same rule: -- Move hard-coded `MaxDegreeOfParallelism = 5` into config (`WorkerSettings`). -- Define backoff for Finnhub 429/5xx. -- Avoid logging large payloads by default (log excerpt + ids). +- keep service registration in the main project + - let tests reuse that registration + - add only test-only logging or helpers in the fixture -### P2 — Clarify supported polling strategy +### 5. Decide early how logs will be asserted -Goal: +There are 2 patterns in this repo. -- Decide between native `SqsListenerService` vs `SqsScheduledPollerJob`. -- Document the chosen strategy and remove ambiguity. +#### Pattern A: docker log assertions ---- +Use when the target is the full running container and you need to verify request flow or background worker behavior. -## 4) Golden Path (Target) +Required pieces: -```mermaid -sequenceDiagram - participant UI as UI - participant API as InventoryAlert.Api - participant SNS as SNS Topic - participant SQS as SQS Queue - participant DLQ as DLQ - participant W as InventoryAlert.Worker - participant H as Handler/Job - participant HF as Hangfire (DLQ Reprocessor) - - UI->>API: POST /api/v1/events (command) - API->>API: Stamp CorrelationId (X-Correlation-Id) - API->>SNS: Publish EventEnvelope { EventType, Payload, CorrelationId, MessageId } - SNS-->>SQS: Fanout delivery - W->>SQS: Long poll - W->>W: Deserialize EventEnvelope - W->>W: Dedup/lock + scope CorrelationId - W->>H: Route by EventType (deserialize Payload) - H-->>W: Logs with CorrelationId +- a log collector like `DockerLogReader` + - correlation or message ID based filtering + - timeout-based polling + - stable structured log messages - alt Handler fails repeatedly - W-->>SQS: No delete (retry via redelivery) - SQS-->>DLQ: After maxReceiveCount -> move to DLQ - HF->>DLQ: Poll / read batch - HF->>SQS: Republish or redrive back to main queue - HF-->>HF: If job fails -> Hangfire dashboard retry - end -``` +#### Pattern B: in-memory logger assertions ---- +Use when tests execute code inside the test process through DI. -## 4.1 Option C — DLQ reprocessor job (recommended spec) +Required pieces: -This is the missing piece that makes “retry via Hangfire Dashboard” practical without forcing Hangfire to own the main SQS consumption loop. +- custom `ILoggerProvider` + - deterministic log capture structure + - helper methods to compare logs against expected data -### What the job does +For another project, prefer Pattern B whenever possible. -Hangfire job example names: +### 6. Use deterministic test data -- `dlq-reprocess` (recurring) — periodically scans DLQ and replays safe messages -- `dlq-redrive-once` (manual) — one-off job to replay `N` messages when an operator clicks “Enqueue” +Adopt a file-based convention: -Operational responsibilities: +- request payloads under `TestData/Requests` + - seed data under `TestData/Seeds` + - expected responses under `TestData/Expectations` + - expected logs under `TestData/Expectations/.../Logs` -- Pull a bounded batch from DLQ (e.g., `max=10..50`). -- For each message: - - validate it’s an `EventEnvelope` and extract `MessageId`, `EventType`, `CorrelationId` - - optionally check a “replay allowlist” (which event types are safe to replay) - - republish back to the main queue (or publish back to SNS depending on your desired fanout semantics) - - write an audit log entry (Seq + optional DB/Dynamo row) with replay metadata - - delete from DLQ only after successful republish (or keep in DLQ and mark “attempted”) +This repository already follows that pattern strongly in `CAL.Consumer.Handler.Tests`. -### What “Retry” means in Hangfire +### 7. Add reset hooks -- If the DLQ reprocessor job fails (AWS outage, invalid payloads, permission issue), Hangfire marks the job as failed. -- An operator can click “Retry” in Hangfire Dashboard to rerun the recovery job. -- This is a **job-level retry** (re-run the recovery operation), not a direct per-message retry button inside Hangfire. If you need per-message selection, add parameters (eventType filter, messageId list, max batch size) and expose them via a small admin endpoint or a dashboard command pattern. +Before each test, reset: -### Recommended guardrails +- database state + - queues and DLQ + - WireMock request history + - captured logs -- Don’t create replay storms: - - cap batch size per run - - introduce a replay delay/backoff - - record replay attempts per message id to prevent infinite loops -- Preserve traceability: - - keep original `CorrelationId` - - emit a new `ReplayId` / `ReprocessAttemptId` for recovery runs +Without this, tests become order-dependent. +### 8. Disable parallelization when shared state exists -## 5) Wiki doc drift notes (for later cleanup) +If tests share DynamoDB tables, queues, or WireMock state, disable parallelization at the collection level. -Wiki docs currently contain both current and legacy naming/flow descriptions (job naming, routing assumptions). Recommend keeping Wiki pages “how to use” oriented and referencing this `doc/` review for deeper refactor plans.",337,af2cebc4f95126d5c1d8ee9aa64a32bf,doc\worker_jobs_and_event_flow_review.md,0,290,"worker, message, hangfire, queue, inventorymanagementsystem, retry, inventoryalert, event",1777190302.622038,10,dbcontext iproductservice threshold notification asnotracking hosted service stock price business logic entity framework price drop finnhubpricesyncworker loss application service external api appdbcontext quote market data productservice periodictimer backgroundservice efcore,# Worker Jobs & Event Flow (Review + Enhancements) | Worker Jobs & Event Flow (Review + Enhancements) This document contains review f -doc,"# Hackathon Progress Checklist +Example in this repo: -Use this checklist to track your team's progress and ensure you're hitting all the key technical requirements from the judging criteria. Good luck! +- `src/CAL.Consumer.Handler.Tests/Tests/Infrastructure/HandlerTestCollection.cs` -✅ Core Principles (40 points) +## Suggested Implementation Plan for Another Project -- [ ] Uniform Interface (15 pts) -- [ ] Endpoints are resource-based and follow RESTful naming conventions (e.g., /api/urls/{id}). -- [ ] Self-descriptive messages are used (e.g., Content-Type: application/json). -- [ ] Appropriate HTTP status codes are returned for different scenarios (e.g., 200 OK, 201 Created, 24 No Content, 400 Bad Request, 404 Not Found). +### Option A: start with handler tests first -- [ ] Stateless (10 pts) -- [ ] Every request contains all necessary information for the server to process it. -- [ ] The server does not store any client session state between requests. -- [ ] Client-Server (10 pts) -- [ ] The application logic is clearly separated between the client and the server. -- [ ] Cacheable (5 pts) -- [ ] Caching headers (like ETag or Cache-Control) are implemented on GET endpoints. -✅ Methods & Endpoints (20 points) -- [ ] Correct HTTP Method Usage (20 pts) -- [ ] GET method is used to retrieve one or more resources. -- [ ] POST method is used to create a new resource. -- [ ] PUT method is used to completely replace an existing resource. -- [ ] PATCH method is used to partially update an existing resource. -- [ ] DELETE method is used to remove a resource. -- [ ] GET, PUT, and DELETE operations are idempotent. -✅ Connectedness & Advanced Features (40 points) -- [ ] Pagination (10 pts) -- [ ] Endpoints that return lists of resources support pagination (e.g., ?page=1&pageSize=10). -- [ ] Filtering & Ordering (10 pts) -- [ ] List endpoints support filtering results based on field values (e.g., ?status=active). -- [ ] List endpoints support ordering/sorting of results (e.g., ?sortBy=name_desc). -- [ ] Versioning (5 pts) -- [ ] The API has a versioning strategy implemented (e.g., /api/v1/urls). -- [ ] Security & Auth (5 pts) -- [ ] Basic authentication/authorization is implemented (e.g., API Key, JWT). -- [ ] HATEOAS (Hypermedia) (5 pts) -- [ ] Responses include links to related resources or possible actions. -- [ ] Input Validation (5 pts) -- [ ] Data from incoming POST, PUT, and PATCH requests is validated. -- [ ] Clear 400 Bad Request responses are returned for invalid data. -⭐ Bonus (Up to 10 points) -- [ ] Monitoring/Logging -- [ ] Basic logging is implemented to track requests or errors. -- [ ] Documentation -- [ ] The project includes a helpful README.md file. -- [ ] The API is documented using Swagger/OpenAPI. -- [ ] Containerization -- [ ] The application can be built and run using a Dockerfile",49,709150e6d23b0349f58b4e7567578cb3,doc\archive\# Hackathon Progress Checklist.md,0,291,"endpoints, used, method, resource, points, server, implemented, application",1759516769.3479264,1,postgresql compose postgres dockerfile container,# Hackathon Progress Checklist | Hackathon Progress Checklist Use this checklist to track your team's progress an -doc,"# Implementation Plan: Road to Perfect 100/100 +This is the recommended order. -> **Current Score:** 85/100 — **Target:** 100/100 -> **Missing:** Versioning (5 pts), Filtering/Ordering (10 pts), HATEOAS (5 pts), Caching (5 pts) +1. expose production DI registration from the worker project + 2. create a `SetupDI` helper inside the handler test project + 3. create a fixture that: + - builds DI + - resets database state + - resets WireMock + - captures logs in memory + 4. add a test base class for: + - request file loading + - scenario ID extraction + - expected log comparison + - WireMock assertions + 5. add scenario-based test data files + 6. write direct handler tests ---- +### Option B: add full worker integration tests next -## Execution Order +1. keep the local AWS and queue infrastructure + 2. run the worker in Docker + 3. add a queue test client + 4. add docker log capture + 5. assert deletion, retention, and DLQ outcomes -``` -Phase 1 (Versioning) → Phase 2 (Filter/Sort) → Phase 3 (HATEOAS) → Phase 4 (Cache) -``` +### Option C: add API integration tests last -- **Phase 1 first** — all other phases depend on the final route shape (URLs must be stable before HATEOAS links are built). -- **Phase 2 before Phase 3** — HATEOAS links embed query params, so the filter DTO must exist first. -- **Phase 4 last** — caching is purely additive, no structural dependencies. +1. run the API container in Docker + 2. expose a local proxy or direct test URL + 3. create API clients inside the test project + 4. add correlation-ID log filtering + 5. assert response + logs together ---- +## Suggested Folder Layout for Another Project -## Phase 1 — API Versioning (5 pts) +```text + src/ + MyProject.Api/ + MyProject.Worker/ + MyProject.Shared/ + MyProject.Api.Tests/ + Shared/ + Tests/ + appsettings.json + MyProject.Worker.Tests/ + Shared/ + Tests/ + appsettings.json + MyProject.Handler.Tests/ + Tests/ + Infrastructure/ + Handlers/ + Shared/ + appsettings.json + SolutionFolder/ + wiremock/ + mappings/ + dynamodb-init/ + moto-init/ + docker-compose.yml + ``` + +## Running the Tests Locally + +Start infrastructure first: -**Goal:** Route all endpoints under `/api/v1/` using URL-path versioning. +```powershell + docker compose up -d --build + ``` -### Files to Change +Run specific test projects: -| File | Change | -|---|---| -| `Directory.Packages.props` | Add `Asp.Versioning.Mvc` + `Asp.Versioning.Mvc.ApiExplorer` to centralized package versions | -| `InventoryAlert.Api.csproj` | Reference those packages | -| `Web/Extensions/MvcExtension.cs` | Wire `AddApiVersioning()` + `AddMvc()` into `SetupMvc()` | -| `Web/Controllers/ProductsController.cs` | Add `[ApiVersion(""1.0"")]` + update route to `api/v{version:apiVersion}/[controller]` | -| `Web/Extensions/SwaggerExtension.cs` | Enumerate versions in Swagger document setup | +```powershell + dotnet test src/CAL.Consumer.Api.Tests/CAL.Consumer.Api.Tests.csproj + dotnet test src/CAL.Consumer.Jobs.Tests/CAL.Consumer.Jobs.Tests.csproj + dotnet test src/CAL.Consumer.Handler.Tests/CAL.Consumer.Handler.Tests.csproj + ``` -### Design Decisions +## Troubleshooting -- **URL path versioning** (`/v1/`) over header versioning — judges can test in Swagger without custom headers. -- **Default version = 1.0** with `AssumeDefaultVersionWhenUnspecified = true` — keeps existing tests passing. -- `ReportApiVersions = true` adds `api-supported-versions` header to every response. +### No logs found in API or Jobs tests -### Key Code Shape +Check: -```csharp -// Web/Extensions/MvcExtension.cs -services.AddApiVersioning(opt => -{ - opt.DefaultApiVersion = new ApiVersion(1, 0); - opt.AssumeDefaultVersionWhenUnspecified = true; - opt.ReportApiVersions = true; - opt.ApiVersionReader = new UrlSegmentApiVersionReader(); -}) -.AddMvc(); +- `consumer_api` and `consumer_jobs` containers are running + - container names match fixture expectations + - the action produced a correlation ID or message ID + - log timeout values are large enough + - the test environment clock is not causing timestamp filter issues -// Web/Controllers/ProductsController.cs -[ApiVersion(""1.0"")] -[Route(""api/v{version:apiVersion}/[controller]"")] -[ApiController] -[Authorize] -public class ProductsController(...) : ControllerBase -``` +### WireMock assertions fail in handler tests ---- +Check: -## Phase 2 — Filtering & Ordering (10 pts) +- `wire_mock` is running on `http://localhost:40485` + - downstream URLs in test `appsettings.json` point to WireMock + - the test reset actually called `/__admin/reset` + - the expected endpoint path matches the real outgoing request path -**Goal:** `GET /api/v1/Products?name=Widget&minStock=5&sortBy=price_desc` +### Queue assertions fail -### Files to Change +Check: -| File | Change | -|---|---| -| `Application/DTOs/ProductQueryParams.cs` | **New file** — replaces `PaginationParams` on the list endpoint | -| `Domain/Interfaces/IProductRepository.cs` | Add overload: `GetPagedAsync(ProductQueryParams q, CancellationToken ct)` | -| `Infrastructure/Repositories/ProductRepository.cs` | Implement EF Core LINQ filter + `OrderBy` switch | -| `Application/Interfaces/IProductService.cs` | Update `GetProductsPagedAsync` signature to accept `ProductQueryParams` | -| `Application/Services/ProductService.cs` | Pass `ProductQueryParams` through to repository | -| `Web/Controllers/ProductsController.cs` | Accept `[FromQuery] ProductQueryParams` instead of `PaginationParams` | +- queues were created by the init container + - local AWS endpoints point to the correct proxy + - the message contains required attributes such as message type + - the handler or worker had permission/configuration to process the message type -> [!IMPORTANT] -> `IGenericRepository` contract is **not changed** — the overload goes on `IProductRepository` only, respecting DDD layer boundaries. +### Seed data issues -### New DTO: `ProductQueryParams` +Check: -```csharp -// Application/DTOs/ProductQueryParams.cs -public class ProductQueryParams -{ - private const int MaxPageSize = 50; - public int PageNumber { get; set; } = 1; +- scenario ID in `DisplayName` matches the file name + - seed files and request files use the expected folder layout + - cleanup is not deleting data needed by the current test - private int _pageSize = 10; - public int PageSize - { - get => _pageSize; - set => _pageSize = value > MaxPageSize ? MaxPageSize : value; - } +## Practical Recommendation - // Filtering - public string? Name { get; set; } // contains, case-insensitive - public int? MinStock { get; set; } - public int? MaxStock { get; set; } +If another project only needs one reusable pattern, copy the `CAL.Consumer.Handler.Tests` approach first. - // Ordering: ""name_asc"" | ""name_desc"" | ""price_asc"" | ""price_desc"" | ""stock_asc"" | ""stock_desc"" - public string? SortBy { get; set; } -} -``` +Reason: -### Infrastructure LINQ Strategy (ProductRepository) +- it is faster than full service tests + - it reuses production DI cleanly + - it avoids container log scraping + - it verifies external calls through WireMock in a deterministic way + - it still allows repository-state and log assertions -```csharp -IQueryable query = _context.Products.AsNoTracking(); +Then add API and worker integration tests only for full pipeline coverage. -if (!string.IsNullOrWhiteSpace(q.Name)) - query = query.Where(p => p.Name.Contains(q.Name)); +## Checklist for Reuse in Another Project -if (q.MinStock.HasValue) query = query.Where(p => p.StockCount >= q.MinStock.Value); -if (q.MaxStock.HasValue) query = query.Where(p => p.StockCount <= q.MaxStock.Value); +- [ ] create Docker Compose for local dependencies + - [ ] create WireMock mappings for downstream services + - [ ] expose production DI registration methods for reuse + - [ ] create one fixture per test style + - [ ] add reset logic for DB, queues, WireMock, and logs + - [ ] decide whether each suite uses docker logs or in-memory log capture + - [ ] store requests, seeds, responses, and expected logs in files + - [ ] disable parallelization if shared state exists + - [ ] keep handler tests as the primary fast integration layer",676,e376673a5b6ebcc1ce8dfe37ee3f2a95,doc\archive\Consumer Test Setup Guide.md,0,282,"tests, test, handler, consumer, logs, jobs, http, docker",1779814416.38456,1,entity framework iproductrepository igenericrepository efcore sku finnhubpricesyncworker fluentassertions iproductservice periodictimer xunit appdbcontext mock setup data access returns async dbcontext hosted service container httppost item iactionresult productscontroller verify dockerfile productservice times once dbset moq stock backgroundservice inventory unit test arrange act assert httpget postgresql compose application service postgres asnotracking business logic httpput,# Consumer Test Setup Guide | Consumer Test Setup Guide Purpose This document explains how the Consumer repos +doc,"# 🧪 Integration Test Setup Guide (Unified Project Pattern) -query = q.SortBy?.ToLowerInvariant() switch -{ - ""name_desc"" => query.OrderByDescending(p => p.Name), - ""price_asc"" => query.OrderBy(p => p.CurrentPrice), - ""price_desc"" => query.OrderByDescending(p => p.CurrentPrice), - ""stock_asc"" => query.OrderBy(p => p.StockCount), - ""stock_desc"" => query.OrderByDescending(p => p.StockCount), - _ => query.OrderBy(p => p.Name) // default -}; +## Purpose -var skip = (q.PageNumber - 1) * q.PageSize; -var total = await query.CountAsync(ct); -var items = await query.Skip(skip).Take(q.PageSize).ToListAsync(ct); -return (items, total); -``` +This document explains the ""Three-Tier"" integration testing architecture for the InventoryAlert project, now consolidated into a single **`InventoryAlert.IntegrationTests`** project for better maintainability. --- -## Phase 3 — HATEOAS / Hypermedia Links (5 pts) +## 🏗️ Test Architecture Summary -**Goal:** Responses include navigational links (`self`, `next`, `prev`) in the paged list envelope. +Instead of separate projects, we use **Internal Directory Tiers** within `InventoryAlert.IntegrationTests`. -### Files to Change +### Tier 1: Handler Tests (`/Tests/Handlers` & `/Tests/Services`) +**Target:** Specific service or handler implementations using production DI. +- **Style:** White-box. Resolves handlers directly from the production dependency injection graph. +- **Validation:** **In-memory logs** via `TestLoggerProvider`, WireMock call history, and direct Repository state assertions. +- **Best for:** Complex business logic, edge cases, and verifying interaction with third-party APIs (Finnhub). -| File | Change | -|---|---| -| `Application/DTOs/HateoasLink.cs` | **New file** — `record HateoasLink(string Href, string Rel, string Method)` | -| `Application/DTOs/PagedResult.cs` | Add `List Links { get; set; } = []` | -| `Web/Controllers/ProductsController.cs` | Populate `Links` after service call using `Url.Action(...)` | +### Tier 2: API Tests (`/Tests/Api`) +**Target:** The HTTP surface and middleware pipeline of the API. +- **Style:** Black-box. Sends real HTTP requests to the `inventory-api` container. +- **Validation:** HTTP response codes, JSON payloads, and **Docker container logs** filtered by `X-Correlation-Id`. +- **Best for:** Verifying Auth middleware, routing, status codes, and the full request-to-response lifecycle. -### New DTO: `HateoasLink` +### Tier 3: Whole-Flow Orchestration Tests (`/Tests/Jobs`) +**Target:** The complete system lifecycle and cross-project orchestration. +- **Style:** Black-box / System Integration. Initiates a flow via API and verifies the final result after background processing. +- **Validation:** Monitoring `inventory-worker` logs, message deletion, and **end-to-side-effect** validation (e.g., verifying a notification appears in the API feed). +- **Quality Goal:** Proving that the **API and Jobs projects** work perfectly together to deliver business value. This is the ultimate peak of the quality pyramid. -```csharp -// Application/DTOs/HateoasLink.cs -public record HateoasLink(string Href, string Rel, string Method); -``` +--- -### Updated `PagedResult` +## 🛠️ Infrastructure Services (All Tiers) -```csharp -public class PagedResult -{ - public IEnumerable Items { get; set; } = []; - public int TotalItems { get; set; } - public int PageNumber { get; set; } - public int PageSize { get; set; } - public int TotalPages => (int)Math.Ceiling(TotalItems / (double)PageSize); - public List Links { get; set; } = []; // ← new -} -``` +| Service | Tool | Purpose | +|---|---|---| +| **AWS Emulator** | Moto | Mock SQS and DynamoDB. Endpoint: `http://localhost:5000` | +| **HTTP Mock** | WireMock | Mock Finnhub API. Endpoint: `http://localhost:9091` | +| **Relational DB** | PostgreSQL | Real database for persistent state. Port: `5433` | -### Controller Link Population (ProductsController.GetProducts) +--- -```csharp -pagedResult.Links.Add(new HateoasLink( - Href: Url.Action(nameof(GetProducts), new { query.PageNumber, query.PageSize })!, - Rel: ""self"", Method: ""GET"")); +## 📈 Assertion Strategy Comparison -if (pagedResult.PageNumber < pagedResult.TotalPages) - pagedResult.Links.Add(new HateoasLink( - Href: Url.Action(nameof(GetProducts), new { PageNumber = query.PageNumber + 1, query.PageSize })!, - Rel: ""next"", Method: ""GET"")); +| Feature | Tier 1 (Handler) | Tier 2 (Api) | Tier 3 (Jobs) | +|---|---|---|---| +| **Speed** | **Fast** (DI) | Slow (Network) | Medium (Polling) | +| **Determinism** | **High** (In-proc) | Moderate (Timing) | Moderate (Polling) | +| **Log Assertions** | **Direct List** | Docker Scraping | Docker Scraping | -if (pagedResult.PageNumber > 1) - pagedResult.Links.Add(new HateoasLink( - Href: Url.Action(nameof(GetProducts), new { PageNumber = query.PageNumber - 1, query.PageSize })!, - Rel: ""prev"", Method: ""GET"")); -``` +--- -### Expected Response Shape +## 🚀 Execution Guide -```json -{ - ""items"": [...], - ""totalItems"": 42, - ""pageNumber"": 2, - ""pageSize"": 10, - ""totalPages"": 5, - ""links"": [ - { ""href"": ""/api/v1/Products?pageNumber=2&pageSize=10"", ""rel"": ""self"", ""method"": ""GET"" }, - { ""href"": ""/api/v1/Products?pageNumber=3&pageSize=10"", ""rel"": ""next"", ""method"": ""GET"" }, - { ""href"": ""/api/v1/Products?pageNumber=1&pageSize=10"", ""rel"": ""prev"", ""method"": ""GET"" } - ] -} -``` +```bash",55,13cf6603e17d18c453d58895f66959b2,doc\archive\consumer-test-pattern.md,0,283,"tier, tests, http, project, validation, integration, inventoryalert, handler",1779814416.3963315,1,postgresql threshold productservice container mock setup stock price igenericrepository business logic compose sku verify arrange act assert data access fluentassertions price drop moq returns async dockerfile dbcontext iproductrepository postgres finnhubpricesyncworker iproductservice unit test dbset periodictimer quote times once loss hosted service stock inventory entity framework notification asnotracking efcore application service appdbcontext backgroundservice item external api market data xunit,# 🧪 Integration Test Setup Guide (Unified Project Pattern) | 🧪 Integration Test Setup Guide (Unified Project Pattern) Purpose This document +doc,"# Run all tiers +dotnet test",58,13cf6603e17d18c453d58895f66959b2,doc\archive\consumer-test-pattern.md,0,284,"tiers, dotnet, test",1779814416.3963315,56,postgresql threshold productservice container mock setup stock price igenericrepository business logic compose sku verify arrange act assert data access fluentassertions price drop moq returns async dockerfile dbcontext iproductrepository postgres finnhubpricesyncworker iproductservice unit test dbset periodictimer quote times once loss hosted service stock inventory entity framework notification asnotracking efcore application service appdbcontext backgroundservice item external api market data xunit,# Run all tiers | Run all tiers dotnet test +doc,"# Run only logic tests (Fast) +dotnet test --filter ""Category=Tier1""",61,13cf6603e17d18c453d58895f66959b2,doc\archive\consumer-test-pattern.md,0,285,"only, logic, tests, fast, dotnet, test, filter, category",1779814416.3963315,59,postgresql threshold productservice container mock setup stock price igenericrepository business logic compose sku verify arrange act assert data access fluentassertions price drop moq returns async dockerfile dbcontext iproductrepository postgres finnhubpricesyncworker iproductservice unit test dbset periodictimer quote times once loss hosted service stock inventory entity framework notification asnotracking efcore application service appdbcontext backgroundservice item external api market data xunit,"# Run only logic tests (Fast) | Run only logic tests (Fast) dotnet test --filter ""Category=Tier1""" +doc,"# Run only container-based tests (Slower) +dotnet test --filter ""Category=Tier2|Category=Tier3"" +```",64,13cf6603e17d18c453d58895f66959b2,doc\archive\consumer-test-pattern.md,0,286,"category, only, container, based, tests, slower, dotnet, test",1779814416.3963315,62,postgresql threshold productservice container mock setup stock price igenericrepository business logic compose sku verify arrange act assert data access fluentassertions price drop moq returns async dockerfile dbcontext iproductrepository postgres finnhubpricesyncworker iproductservice unit test dbset periodictimer quote times once loss hosted service stock inventory entity framework notification asnotracking efcore application service appdbcontext backgroundservice item external api market data xunit,"# Run only container-based tests (Slower) | Run only container-based tests (Slower) dotnet test --filter ""Category=Tier2|Cat" +doc,"# 🔬 DDD Refactoring Audit — Progress Tracker +## Naming Conventions, File Locations & Structure --- -## Phase 4 — HTTP Cache Headers (5 pts) +## ✅ Step 1 — Create missing folders -**Goal:** `GET` endpoints return `Cache-Control` headers so clients/CDNs can cache responses. +| Folder | Status | +| :--- | :--- | +| `Domain/Interfaces/` | ✅ Created | +| `Domain/Events/` | ✅ Created | +| `Infrastructure/Persistence/Configurations/` | ✅ Created | +| `Web/Controllers/` | ✅ Created | +| `Web/Configuration/` | ✅ Created | +| `Web/Middleware/` | ⬜ Phase 2 (GlobalExceptionHandler) | -### Files to Change +--- -| File | Change | -|---|---| -| `Program.cs` | Register `services.AddResponseCaching()` + `app.UseResponseCaching()` | -| `Web/Controllers/ProductsController.cs` | Add `[ResponseCache]` to `GetProducts` and `GetProductById` | +## ✅ Step 2 — Move files -### Cache Strategy Per Endpoint +| File | From | To | Status | +| :--- | :--- | :--- | :--- | +| `AppDbContext.cs` | `Infrastructure/` | `Infrastructure/Persistence/` | ✅ Done | +| `ProductConfiguration.cs` | `Infrastructure/Persistence/` | `Infrastructure/Persistence/Configurations/` | ✅ Done | +| `IGenericRepository.cs` | `Infrastructure/Persistence/Interfaces/` | `Domain/Interfaces/` | ✅ Done | +| `IProductRepository.cs` | `Infrastructure/Persistence/Interfaces/` | `Domain/Interfaces/` | ✅ Done | +| `IUnitOfWork.cs` | `Infrastructure/Persistence/Interfaces/` | `Domain/Interfaces/` | ✅ Done | +| `ProductController.cs` | `Controllers/` | `Web/Controllers/ProductsController.cs` | ✅ Done | +| `AppSettings.cs` | root | `Web/Configuration/` | ✅ Done | -| Endpoint | Duration | Vary By | Rationale | -|---|---|---|---| -| `GET /Products` (list) | 30 s | `*` all query keys | Short TTL due to volatile stock; vary-by-query caches each filter combo separately | -| `GET /Products/{id}` | 60 s | `Accept` header | Single items are more stable; 60 s balances freshness vs. load | +--- -### Key Code Shape +## ✅ Step 3 — Rename files + classes -```csharp -// Program.cs -builder.Services.AddResponseCaching(); -// Pipeline — MUST be BEFORE UseAuthentication -app.UseResponseCaching(); +| Old Name | New Name | Status | +| :--- | :--- | :--- | +| `ProductServices.cs` | `ProductService.cs` | ✅ Done | +| `ProductDto.cs` | Split → `ProductRequest.cs` + `ProductResponse.cs` + `PriceLossResponse.cs` | ✅ Done | +| `FinnhubSyncWorker.cs` | `FinnhubPriceSyncWorker.cs` | ✅ Done | +| class `ProductServices` | `ProductService` | ✅ Done | +| class `ProductRequestDto` | `ProductRequest` | ✅ Done | +| class `ProductDto` | `ProductResponse` | ✅ Done | +| class `ProductLossDto` | `PriceLossResponse` | ✅ Done | +| class `Finnhub` (in AppSettings) | `FinnhubSetting` | ✅ Done | -// ProductsController.cs -[HttpGet] -[ResponseCache(Duration = 30, VaryByQueryKeys = new[] { ""*"" })] -public async Task GetProducts([FromQuery] ProductQueryParams query, ...) +--- -[HttpGet(""{id:int}"")] -[ResponseCache(Duration = 60, VaryByHeader = ""Accept"")] -public async Task GetProductById([FromRoute] int id, ...) -``` +## ✅ Step 4 — Rename methods + update namespaces -> [!WARNING] -> `UseResponseCaching()` must be placed **before** `UseAuthentication()` in the middleware pipeline. For `[Authorize]` endpoints, response caching will automatically use `Cache-Control: private` to prevent cross-user data leakage. +| Change | Status | +| :--- | :--- | +| `GetHighValueProducts` → `GetPriceLossAlertsAsync` | ✅ Done | +| `DeleteProductAsync(int)` → `DeleteProductAsync(int, CancellationToken)` | ✅ Done | +| Namespace `Infrastructure.Persistence.Interfaces` → `Domain.Interfaces` | ✅ Done | +| Namespace `Infrastructure` (AppDbContext) → `Infrastructure.Persistence` | ✅ Done | +| Namespace `InventoryAlert.Api` (AppSettings) → `Web.Configuration` | ✅ Done | +| Controller methods: proper `[FromRoute]`/`[FromBody]`/status codes | ✅ Done | --- -## Test Coverage Plan +## ✅ Cleanup — Stub/placeholder files deleted -| Phase | Happy Path | Edge Case | -|---|---|---| -| 1 – Versioning | `GET /api/v1/Products` → 200 | `GET /api/v99/Products` → 400 UnsupportedApiVersion | -| 2 – Filter | `?name=Widget` returns only matching rows | Empty filters return all (default) | -| 2 – Sort | `?sortBy=price_desc` returns descending order | Unknown `sortBy` falls back to `name_asc` default | -| 3 – HATEOAS | Page 2 body includes `next` and `prev` links | Last page: no `next` link present | -| 4 – Cache | `GET /Products` response has `Cache-Control: max-age=30` | Mutating `POST`/`PUT` returns `no-cache` |",255,f24743b2f3fbe485499320c4c4a024d1,doc\archive\a.md,0,292,"phase, versioning, change, cache, links, file, products, productqueryparams",1775464567.8495762,1,iproductrepository application layer loss price drop domain driven design notification httpget item data access xunit unit test igenericrepository appdbcontext dbset arrange act assert fluentassertions business logic httppost efcore iactionresult inventory application service asnotracking productservice infrastructure iproductservice threshold entity framework sku httpput dbcontext domain entity stock productscontroller,# Implementation Plan: Road to Perfect 100/100 | Implementation Plan: Road to Perfect 100/100 > Current Score: 85/100 — Target: 1 -doc,"--- -description: Allow creating alert rules without requiring prior symbol discovery. -type: spec -status: active -version: 1.0 -tags: [alert-rules, symbol-discovery, api, ui, notifications] -last_updated: 2026-04-23 ----",9,3dd027f9332cd0b4e4d57053a59849fb,doc\archive\alert_rules_symbol_auto_resolve_spec.md,0,293,"alert, rules, symbol, discovery, description, allow, creating, without",1777190302.611379,1,dbcontext application service arrange act assert hosted service finnhubpricesyncworker productservice threshold xunit msft business logic backgroundservice price drop loss unit test googl periodictimer appdbcontext aapl fluentassertions entity framework symbol notification asnotracking iproductservice efcore stock ticker,alert_rules_symbol_auto_resolve_spec.md | --- description: Allow creating alert rules without requiring prior symbol disco -doc,"# Alert Rules — Symbol Auto-Resolve +| Deleted Stub | Replaced By | +| :--- | :--- | +| `Infrastructure/AppDbContext.cs` | `Infrastructure/Persistence/AppDbContext.cs` ✅ | +| `Infrastructure/Persistence/ProductConfiguration.cs` | `Infrastructure/Persistence/Configurations/ProductConfiguration.cs` ✅ | +| `Infrastructure/Persistence/Interfaces/IGenericRepository.cs` | `Domain/Interfaces/IGenericRepository.cs` ✅ | +| `Infrastructure/Persistence/Interfaces/IProductRepository.cs` | `Domain/Interfaces/IProductRepository.cs` ✅ | +| `Infrastructure/Persistence/Interfaces/IUnitOfWork.cs` | `Domain/Interfaces/IUnitOfWork.cs` ✅ | +| `Application/Services/ProductServices.cs` | `Application/Services/ProductService.cs` ✅ | +| `Application/DTOs/ProductDto.cs` | `ProductRequest.cs` + `ProductResponse.cs` + `PriceLossResponse.cs` ✅ | +| `Controllers/ProductController.cs` | `Web/Controllers/ProductsController.cs` ✅ | +| `Infrastructure/Workers/FinnhubSyncWorker.cs` | `Infrastructure/Workers/FinnhubPriceSyncWorker.cs` ✅ | +| `AppSettings.cs` (root) | `Web/Configuration/AppSettings.cs` ✅ | +| `Infrastructure/Persistence/Interfaces/` (folder) | Deleted ✅ | +| `Controllers/` (folder) | Deleted ✅ | +| `Services/` (folder) | Deleted ✅ | -## Summary +--- -Creating an alert rule should not depend on the user having previously “discovered” a symbol (e.g., by visiting a stock detail page). The API now resolves and persists symbol metadata during alert creation. +## ✅ Step 5 — Fix `Program.cs` + DI organization -## Behavior +| Task | Status | +| :--- | :--- | +| Extract DI into `Web/ServiceExtensions/ApplicationServiceExtensions.cs` | ✅ Done | +| Extract DI into `Web/ServiceExtensions/InfrastructureServiceExtensions.cs` | ✅ Done | +| `builder.Services.AddApplicationServices()` | ✅ Done | +| `builder.Services.AddInfrastructure(settings)` | ✅ Done | +| Fix `using Microsoft.OpenApi` (v2 namespace change from Swashbuckle v10) | ✅ Done | +| Fix `IFinnhubClient` return type → `Task` (nullable) | ✅ Done | +| Fix `Product.Name/TickerSymbol` → `= string.Empty` (CS8618) | ✅ Done | +| Fix null-coalescing in `ProductService` mapper (CS8601) | ✅ Done | -- Input `TickerSymbol` is normalized (trim + uppercase) before persistence. -- API calls stock profile lookup during `AlertRuleService.CreateAsync` to resolve/persist symbol metadata. -- If the symbol cannot be resolved, alert creation fails. +--- -## Impacted Areas +## ✅ Build Verification -- API: `InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs` -- Domain: `InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs` -- Tests: `InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/AlertRuleServiceTests.cs` -- UI: `InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx`, `InventoryAlert.UI/src/components/NotificationBell.tsx` -- Worker: `InventoryManagementSystem/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs` +| Task | Status | +| :--- | :--- | +| `dotnet build` — 0 Errors, 0 Warnings | ✅ **PASSED** | -## Verification +--- -- Unit tests cover alert creation paths without pre-existing catalog state. -- Manual: - - Create an alert for a symbol that is not yet in the catalog; verify it succeeds and the symbol appears in `StockListing`. - - Verify navbar bell badge updates via `GET /api/v1/notifications/unread-count` (returns `int`).",36,3dd027f9332cd0b4e4d57053a59849fb,doc\archive\alert_rules_symbol_auto_resolve_spec.md,0,294,"symbol, alert, inventoryalert, inventorymanagementsystem, creation, resolve, stock, page",1777190302.611379,10,dbcontext application service arrange act assert hosted service finnhubpricesyncworker productservice threshold xunit msft business logic backgroundservice price drop loss unit test googl periodictimer appdbcontext aapl fluentassertions entity framework symbol notification asnotracking iproductservice efcore stock ticker,# Alert Rules — Symbol Auto-Resolve | Alert Rules — Symbol Auto-Resolve Summary Creating an alert rule should not dep -doc,"# InventoryAlert.Api — Technical Specification (v2) +## ⬜ Phase 2 — Future Work (not in scope yet) -> **Refactor Target.** This document supersedes v1. All entity names, API routes, and worker roles have been updated to align with finance-domain terminology and the full Finnhub Free-Tier endpoint surface. +| Task | Notes | +| :--- | :--- | +| `Web/Middleware/GlobalExceptionHandler.cs` | Replace try/catch in controller with `IExceptionHandler` middleware | +| Add FluentValidation for `ProductRequest` | Validate `Name`, `OriginPrice > 0`, `PriceAlertThreshold` range | +| Move Swagger config into `Web/ServiceExtensions/` | `AddSwaggerDocumentation()` extension | --- -> [!CAUTION] -> ## ⚠️ Refactor Notice — Old Business Must Be Removed -> -> **This spec describes the NEW system entirely.** The existing codebase uses `Product`/`StockTransaction` inventory terminology leftover from the original OJT project. That old business logic is **fully superseded**. -> -> **Rule**: If a file is not listed as `KEEP`, `RENAME`, or `UPDATE` in Section 13, it is old business and **must be deleted**. -> -> **Do NOT attempt to preserve old business logic** by adapting it. Use the Domain entities, interfaces, and DTOs defined in this spec as the single source of truth. The Infrastructure, Api, and Worker layers follow from those contracts. +## 🧑‍💻 Final Folder Tree — Achieved ✅ + +``` +InventoryAlert.Api/ +├── Domain/ +│ ├── Entities/ ✅ Product.cs +│ ├── Interfaces/ ✅ IGenericRepository, IProductRepository, IUnitOfWork +│ └── Events/ ✅ (placeholder) +├── Application/ +│ ├── DTOs/ ✅ ProductRequest, ProductResponse, PriceLossResponse +│ ├── Interfaces/ ✅ IProductService +│ └── Services/ ✅ ProductService.cs +├── Infrastructure/ +│ ├── Persistence/ ✅ AppDbContext.cs +│ │ ├── Configurations/ ✅ ProductConfiguration.cs +│ │ └── Repositories/ ✅ GenericRepository, ProductRepository, UnitOfWork +│ ├── External/ ✅ FinnhubClient + IFinnhubClient + Models +│ └── Workers/ ✅ FinnhubPriceSyncWorker.cs +└── Web/ + ├── Controllers/ ✅ ProductsController.cs + ├── Configuration/ ✅ AppSettings.cs + ├── ServiceExtensions/ ✅ ApplicationServiceExtensions, InfrastructureServiceExtensions + ├── Middleware/ ⬜ Phase 2 + └── Program.cs ✅ Clean bootstrap — 64 lines +```",138,1e0f87235dd4f8593a9e686fa3924a15,doc\archive\DDD_REFACTOR_PLAN.md,0,287,"done, infrastructure, interfaces, persistence, domain, status, controllers, step",1775670503.9122765,1,aapl domain driven design loss finnhubpricesyncworker domain entity iproductrepository iproductservice quote httppost stock price stock ticker sku data access price drop backgroundservice dbcontext hosted service googl threshold infrastructure productservice notification msft executetransactionasync business logic savechangesasync efcore external api iunitofwork periodictimer item igenericrepository inventory market data symbol productscontroller iactionresult application service httpget stock entity framework asnotracking httpput appdbcontext application layer dbset,"# 🔬 DDD Refactoring Audit — Progress Tracker | 🔬 DDD Refactoring Audit — Progress Tracker Naming Conventions, File Locations &" +doc,"# Pragmatic DDD: File Structure Guide + +This document outlines the **Domain-Driven Design (DDD)** structure for the **Automated Inventory Alert System**. Our goal is to apply DDD principles while keeping the project ""Small & Pragmatic"" by consolidating layers into logical namespaces within a single API project, rather than over-engineering with multiple assembly projects. --- -## Changelog (v1 → v2) +## 🏗️ The Single-Project DDD Layout -| # | Change | Reason | -| :- | :--- | :--- | -| 1 | `Product` → **`StockListing`** | ""Product"" is an inventory term. ""StockListing"" is accurate for a market catalog entry. | -| 2 | `StockTransaction` → **`Trade`** | Finance standard. Enum values: `Buy`, `Sell`, `Dividend`, `Split`. | -| 3 | Removed `WatchlistItem.IsWatchOnly` | Redundant. All watchlist rows are watch-only by definition. | -| 4 | `Portfolio.GET /catalog` → `Stocks.GET /` | Catalog is global; portfolio is personal. Correct layer separation. | -| 5 | Added **`StockMetric`** table | Maps to Finnhub `/stock/metric` (Basic Financials). Cached daily. | -| 6 | Added **`EarningsSurprise`** table | Maps to Finnhub `/stock/earnings`. Last 4 quarters, free tier. | -| 7 | Added **`RecommendationTrend`** table | Maps to Finnhub `/stock/recommendation`. Analyst buy/hold/sell counts. | -| 8 | Added **`InsiderTransaction`** table | Maps to Finnhub `/stock/insider-transactions`. Last 100 entries. | -| 9 | Added 8 new API endpoints | Covers earnings/IPO calendars, market holidays, peers, recommendations. | -| 10 | `PATCH /{id}/stock` → `PATCH /{id}/trade` | Matches the renamed `Trade` entity. | +```text +InventoryAlertSystem/ +├── InventoryAlert.Api/ +│ ├── Domain/ # Pure Business Logic (No dependencies on external libraries) +│ │ ├── Entities/ # Core models (Product.cs) +│ │ ├── ValueObjects/ # Immutable data structures (Price, Stock) +│ │ ├── Interfaces/ # Repository contracts & External service interfaces +│ │ └── Events/ # Domain events (LowStockDetected.cs) +│ │ +│ ├── Application/ # Use Case & Logic Orchestration +│ │ ├── Features/ # Functional slices (Inventory, Pricing, Notifications) +│ │ ├── Services/ # Logic that coordinates Domain logic +│ │ └── DTOs/ # Formats for API Request/Response +│ │ +│ ├── Infrastructure/ # Implementation details (External worlds) +│ │ ├── Persistence/ # EF Core, AppDbContext, Migrations, Repositories +│ │ ├── External/ # Finnhub API Client, HTTP Clients +│ │ └── Messaging/ # Motor implementation, SNS/SQS, Hangfire Jobs +│ │ +│ ├── Web/ # Entry Point & API Configuration +│ │ ├── Controllers/ # REST Endpoints +│ │ ├── Middleware/ # Global Exception handling, Auth +│ │ └── Program.cs # DI registration & App Startup +│ │ +│ └── appsettings.json +│ +└── InventoryAlert.Tests/ # Shadow the same structure for unit/integration tests +``` --- -## 1. Domain Entities (PostgreSQL) +## 🧩 Architectural Breakdown -### 1.1 Relationship Overview +### 1. Domain (The Heart) +- **What it solves:** Architecture & Business Logic. +- **Rules:** Must NOT reference any external library (EF Core, Hangfire, etc.). +- **Content:** The `Product` entity lives here. It should contain logic like `bool IsBelowThreshold()` or `void UpdateStock(int amount)`. -```mermaid -erDiagram - User ||--o{ WatchlistItem : watches - User ||--o{ AlertRule : configures - User ||--o{ Trade : executes +### 2. Application (The Orchestrator) +- **What it solves:** Predictability. +- **Rules:** Depends ONLY on the Domain. +- **Content:** If a background job needs to check stock and send an alert, the `InventoryMonitorService` orchestrates this by using the Domain entities and Infrastructure interfaces. - StockListing ||--o{ PriceHistory : records - StockListing ||--o{ WatchlistItem : ""tracked via Symbol"" - StockListing ||--o{ Trade : ""referenced via Symbol"" - StockListing ||--o| StockMetric : ""has cached metrics"" - StockListing ||--o{ EarningsSurprise : has - StockListing ||--o{ RecommendationTrend : has - StockListing ||--o{ InsiderTransaction : has -``` +### 3. Infrastructure (The ""Details"") +- **What it solves:** Maintainability & Security. +- **Rules:** Holds the ""How"". How do we save to PostgreSQL? How do we talk to Finnhub? +- **Content:** `AppDbContext`, `ProductRepository`, and the specific `FinnhubClient` implementation. + +### 4. Web (The Gateway) +- **What it solves:** Performance & Interaction. +- **Content:** Handles HTTP requests, JSON serialization, and project-wide configuration. --- -### 1.2 Entity Specifications - -#### `User` -**Core Identity.** Root account for all personal data. +## 🚀 Why This Solution? -| Property | Type | Description | -| :--- | :--- | :--- | -| `Id` | `Guid` | Primary Key. | -| `Username` | `string` | Unique login handle. | -| `PasswordHash` | `string` | Argon2/BCrypt hashed credential. | -| `Email` | `string` | Recovery and alert notification address. | -| `Role` | `enum` | `User` \| `Admin`. | -| `CreatedAt` | `DateTime` | Account creation timestamp. | +1. **Big Problem Solved (Architecture):** Prevents the ""Fat Controller"" and ""Transaction Script"" anti-patterns. By moving logic into the **Domain**, we ensure the system is testable without a database. +2. **YAGNI (You Ain't Gonna Need It):** Traditional DDD suggests 4+ separate C# projects (`Company.Project.Domain`, `Company.Project.Infra`, etc.). For a small project, this adds build time and complexity. Folder-based DDD provides the **organizational benefits** without the **overhead**. +3. **Modular Growth:** If the ""Pricing Module"" grows too large, it is already logically separated in the `Application/Features` and `Infrastructure/External` folders, making it easy to extract into a Microservice later if needed.",67,bd4ea2e9f0c7a97029b79101b835f043,doc\archive\DDD_STRUCTURE.md,0,288,"project, domain, what, solves, content, into, logic, rules",1775670503.9122765,1,asnotracking quote httppost business logic arrange act assert rollback domain driven design iproductservice xunit efcore migration notification commit application service unit test entity framework httpget savechanges efcore loss stock price external api stock schema change data access appdbcontext atomicity market data sku fluentassertions iproductrepository infrastructure igenericrepository productservice threshold domain entity application layer item unitofwork dbset inventory httpput price drop database update dbcontext iactionresult productscontroller add-migration,# Pragmatic DDD: File Structure Guide | Pragmatic DDD: File Structure Guide This document outlines the Domain-Driven Des +doc,"# Implementation Plan: Migrating Logs & News to DynamoDB ---- +Consolidation of high-volume/time-series data into DynamoDB to reduce PostgreSQL load and optimize resource usage. -#### `StockListing` _(was `Product`)_ -**Global Catalog.** Read-only market reference data shared across the system. Seeded from Finnhub `/stock/symbol` and enriched via `/stock/profile2`. +## 1. Domain & Contracts Layer +- [ ] **NewsRecord Refactoring**: + - Update `InventoryAlert.Contracts/Entities/NewsRecord.cs` to include DynamoDB attributes. + - Set `TickerSymbol` as HashKey and `PublishedAt` (ISO 8601 string) as RangeKey for optimized retrieval. + - Add TTL support for automatic data cleanup. +- [ ] **NewsDynamoRepository**: + - Create `INewsRepository` interface in Contracts. + - Implement `NewsDynamoRepository.cs` using `IDynamoDBContext`. -| Property | Type | Description | -| :--- | :--- | :--- | -| `Id` | `int` | Primary Key (auto-increment). | -| `Name` | `string` | Company display name (e.g., ""Tesla Inc""). | -| `TickerSymbol` | `string` | **Unique** market ticker (e.g., ""TSLA""). | -| `Exchange` | `string?` | Exchange code (e.g., ""NASDAQ""). | -| `Currency` | `string?` | ISO currency code (e.g., ""USD""). | -| `Country` | `string?` | Domicile country code (e.g., ""US""). | -| `Industry` | `string?` | Finnhub industry classification. | -| `MarketCap` | `decimal?` | Market capitalization in USD. | -| `Ipo` | `DateOnly?` | IPO date. | -| `WebUrl` | `string?` | Company website URI. | -| `Logo` | `string?` | Company logo URI (from Finnhub profile2). | -| `LastProfileSync` | `DateTime?` | UTC timestamp of last profile2 sync. | +## 2. Worker Layer (Ingestion) +- [ ] **NewsHandler Update**: + - Swap `InventoryDbContext` for `INewsRepository`. + - Persist news directly to DynamoDB. +- [ ] **PollSqsJob Persistence**: + - Continue using `EventLogDynamoRepository`. + - (Verification) Ensure it handles de-duplication correctly before saving to DynamoDB. ---- +## 3. API Layer (Querying) +- [ ] **EventLog Queries**: + - Ensure `IEventLogQuery` implementation (`DynamoDbEventLogQuery`) is fully functional. + - Update controller endpoints to source data strictly from DynamoDB. +- [ ] **News Queries**: + - Create `INewsQuery` interface. + - Implement `DynamoDbNewsQuery` to fetch news per ticker from DynamoDB. + - Update `NewsController` (or equivalent) to use the new query service. -#### `WatchlistItem` -**Personal Watchlist.** Tracks user interest without ownership. No `IsWatchOnly` — that is implied. +## 4. Infrastructure Cleanup (PostgreSQL) +- [ ] **DbContext Removal**: + - Remove `DbSet` and `DbSet` from `InventoryDbContext.cs`. + - Remove associated `IEntityTypeConfiguration` classes. +- [ ] **Migration**: + - Generate an EF Core migration: `RemoveLogsAndNewsFromPostgres`. + - Apply migration to drop tables in the development environment. -| Property | Type | Description | -| :--- | :--- | :--- | -| `UserId` | `Guid` | **FK** → `User.Id` | -| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | -| `CreatedAt` | `DateTime` | Timestamp of entry. | +## 5. Verification +- [ ] Validate news ingestion via simulator. +- [ ] Verify event log querying via API Swagger. +- [ ] Check CloudWatch/LocalStack logs for DynamoDB write success.",42,a595c0fbedad14cd179b0ef89f0017c2,doc\archive\DynamoDB_Migration_Plan.md,0,289,"dynamodb, news, update, data, contracts, layer, newsrecord, from",1775670503.9049637,1,igenericrepository database update efcore migration add-migration data access efcore googl notification httpput iactionresult hosted service price drop appdbcontext iproductrepository threshold entity framework aapl productscontroller application service backgroundservice business logic schema change finnhubpricesyncworker periodictimer asnotracking symbol loss httppost productservice httpget msft stock ticker dbset iproductservice dbcontext,# Implementation Plan: Migrating Logs & News to DynamoDB | Implementation Plan: Migrating Logs & News to DynamoDB Consolidation of high-vol +doc,"# Enhancement & Tracking Plan -> **PK**: Composite key `(UserId, TickerSymbol)`. +> **Last Updated:** 2026-04-05 +> Use this as a living checklist. Items marked ✅ are implemented and verified. --- -#### `AlertRule` -**Unified Notification Rules.** Triggers on both price and inventory conditions. - -| Property | Type | Description | -| :--- | :--- | :--- | -| `Id` | `Guid` | Primary Key. | -| `UserId` | `Guid` | **FK** → `User.Id` | -| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | -| `Condition` | `enum` | See `AlertCondition` enum below. | -| `TargetValue` | `decimal` | Threshold to breach. | -| `IsActive` | `bool` | Enabled/disabled state. | -| `TriggerOnce` | `bool` | Deactivate automatically after first trigger. | -| `LastTriggeredAt` | `DateTime?` | UTC timestamp of last successful trigger. | -| `CreatedAt` | `DateTime` | Rule creation timestamp. | - -**`AlertCondition` Enum** +## 🏁 Critical Improvements -| Value | Description | -| :--- | :--- | -| `PriceAbove` | Trigger when current price exceeds `TargetValue`. | -| `PriceBelow` | Trigger when current price falls below `TargetValue`. | -| `PriceTargetReached` | Trigger when price hits an exact target (±tolerance). | -| `PercentDropFromCost` | Trigger when unrealized loss % exceeds `TargetValue`. | -| `LowHoldingsCount` | Trigger when user's share count drops below `TargetValue`. | +### 1. Architectural Alignment (DDD) ---- +- [x] **Thin Controllers:** Alert filter logic moved to `ProductService`. Controller is now thin. ✅ +- [x] **Repository & UoW Refactoring:** `UnitOfWork` uses DI-injected repositories. ✅ +- [x] **Consolidate Services:** All logic in `Application/Services`. Top-level `Services/` folder removed. ✅ +- [x] **Interface Naming:** `ProductService` (singular) matches `IProductService`. ✅ -#### `Trade` _(was `StockTransaction`)_ -**Ownership Ledger.** Immutable record of position changes. +### 2. Design Patterns to Implement -| Property | Type | Description | -| :--- | :--- | :--- | -| `Id` | `Guid` | Primary Key. | -| `UserId` | `Guid` | **FK** → `User.Id` | -| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | -| `Type` | `enum` | `Buy`, `Sell`, `Dividend`, `Split`. | -| `Quantity` | `decimal` | **Always positive.** Direction is encoded by `Type`. Net holdings = `SUM(Buy) - SUM(Sell)` computed by service. | -| `UnitPrice` | `decimal` | Execution price per share. `0` for `Dividend`/`Split`. | -| `TradedAt` | `DateTime` | UTC execution timestamp. | -| `Notes` | `string?` | Optional user annotation. | +- [ ] **CQRS (Command Query Responsibility Segregation):** Use **MediatR** to separate read and write requests. + - *Why:* Simplifies code as it grows, making handlers more focused. +- [ ] **Domain Events:** Dispatch events (e.g., `LowStockDetectedEvent`) from the Domain entity. + - *Why:* Decouples product updates from notification logic. +- [ ] **Static Factory / Builder Pattern:** Use for creating `Product` entities with complex state. +- [ ] **Specification Pattern:** For building reusable filters in `GetPriceLossAlertsAsync`. + - *Why:* Keeps query logic out of the Domain and into reusable objects. ---- +### 3. Code Quality & Patterns -#### `PriceHistory` -**Price Log.** Point-in-time market price snapshots for charting and alert evaluation. +- [x] **Mapping:** Manual mapping centralized in static `MapToResponse` / `MapToEntity` helpers. ✅ +- [x] **CancellationToken Consistency:** `CancellationToken ct` passed through all layers. ✅ +- [x] **Async/Await Fix:** `.Result` usage eliminated — all methods use `await`. ✅ +- [x] **REST Best Practices:** ✅ + - [x] `PATCH /{id}/stock` endpoint uses `[FromRoute]` binding. + - [x] `GetProductById` correctly named with `[FromRoute] int id`. -| Property | Type | Description | -| :--- | :--- | :--- | -| `Id` | `long` | Primary Key (bigserial). | -| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | -| `Price` | `decimal` | Close/current price at snapshot. | -| `High` | `decimal?` | Day high at snapshot time. | -| `Low` | `decimal?` | Day low at snapshot time. | -| `Open` | `decimal?` | Day open at snapshot time. | -| `PrevClose` | `decimal?` | Previous close price. | -| `RecordedAt` | `DateTime` | UTC snapshot timestamp. | +### 4. Missing Features (Challenge Requirements) -> **Index**: `(TickerSymbol, RecordedAt DESC)` — supports range queries for charts. +- [x] **Alert Logic:** `LastAlertSentAt` 1-hour cooldown implemented in `GetPriceLossAlertsAsync`. No spam alerts. ✅ +- [x] **Error Handling:** `ExceptionHandlingMiddleware` implemented — RFC-7807 ProblemDetails, all domain exceptions mapped. ✅ --- -#### `StockMetric` _(new)_ -**Cached Basic Financials.** One row per ticker. Updated daily by worker. Maps to Finnhub `/stock/metric`. +## 🛠️ Performance & Security (Planned) -| Property | Type | Description | -| :--- | :--- | :--- | -| `TickerSymbol` | `string` | **PK + FK** → `StockListing.TickerSymbol` | -| `PeRatio` | `double?` | Price-to-Earnings ratio (TTM). | -| `PbRatio` | `double?` | Price-to-Book ratio. | -| `EpsBasicTtm` | `double?` | Earnings per share (TTM). | -| `DividendYield` | `double?` | Dividend yield (annual %). | -| `Week52High` | `decimal?` | 52-week high price. | -| `Week52Low` | `decimal?` | 52-week low price. | -| `RevenueGrowthTtm` | `double?` | YoY revenue growth (TTM). | -| `MarginNet` | `double?` | Net profit margin (TTM). | -| `LastSyncedAt` | `DateTime` | UTC timestamp of last Finnhub sync. | +- [ ] **Caching:** Implement `IDistributedCache` (Redis) or `IMemoryCache` for `GetProductById` to reduce DB load. +- [ ] **Authentication:** Add JWT Bearer authentication to protect the `POST/PUT/DELETE` endpoints. +- [x] **Validation:** `FluentValidation` registered for `ProductRequest`. Returns `400 Bad Request` with details. ✅ --- -#### `EarningsSurprise` _(new)_ -**Historical Earnings.** Last 4 quarters of actual vs. estimated EPS. Maps to Finnhub `/stock/earnings`. +## 📝 Code Review Summary -| Property | Type | Description | +| File | Issue | Status | | :--- | :--- | :--- | -| `Id` | `int` | Primary Key. | -| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | -| `Period` | `DateOnly` | Fiscal quarter end date in Finnhub format (e.g., `2024-09-30`). Unique constraint with `TickerSymbol`. | -| `ActualEps` | `double?` | Actual reported EPS. | -| `EstimateEps` | `double?` | Consensus estimate EPS. | -| `SurprisePercent` | `double?` | `(Actual - Estimate) / |Estimate| * 100`. Computed on write. | -| `ReportDate` | `DateOnly?` | Date of public earnings release. | - -> **C2 fix**: Finnhub returns `period` as `""2024-09-30""` (last day of fiscal quarter). Stored as `DateOnly`, not a ""Q4"" string. Unique constraint on `(TickerSymbol, Period)` prevents duplicate upserts. - ---- +| `ProductController.cs` | Logic in Controller | ✅ Fixed — thin controller, all logic in service | +| `ProductServices.cs` | `.Result` usage | ✅ Fixed — all `await` | +| `UnitOfWork.cs` | Violation of DI | ✅ Fixed — repositories injected | +| `GenericRepository.cs` | Shadowing `T` | ✅ Fixed | +| `Program.cs` | Massive file | ✅ Fixed — `AddInfrastructure()` + `AddApplicationServices()` extensions |",59,b07b93a2d0bea0b14969e55195c24b63,doc\archive\ENHANCEMENT_PLAN.md,0,290,"logic, fixed, domain, implemented, thin, controller, services, code",1775670503.9132829,1,productservice sku data access domain driven design iunitofwork dbcontext inventory threshold httpput stock executetransactionasync productscontroller iproductrepository iactionresult httpget httppost item savechangesasync loss igenericrepository notification application layer domain entity appdbcontext efcore business logic asnotracking infrastructure iproductservice application service dbset entity framework price drop,# Enhancement & Tracking Plan | Enhancement & Tracking Plan > Last Updated: 2026-04-05 > Use this as a living ch +doc,"--- +description: Review of current API error handling and response format, plus recommendations to standardize status codes and error messages. +type: reference +status: draft +version: 1.0 +tags: [api, middleware, error-handling, standardization, inventoryalert] +last_updated: 2026-04-26 +---",9,9d1aea0ca6a54c1af7f0b254dc6be58b,doc\archive\error_handling_and_response_standard.md,0,291,"error, handling, status, description, review, current, response, format",1779851803.9193945,1,entity framework iproductservice productscontroller iactionresult price drop msft threshold stock httpget stock ticker googl application service appdbcontext sku aapl dbcontext symbol httpput productservice httppost efcore item inventory asnotracking business logic loss notification,"error_handling_and_response_standard.md | --- description: Review of current API error handling and response format, plus " +doc,"# Error Handling & Response Standardization (Review + Recommendations) -#### `RecommendationTrend` _(new)_ -**Analyst Consensus.** Monthly analyst buy/hold/sell counts. Maps to Finnhub `/stock/recommendation`. +Scope: `InventoryManagementSystem/InventoryAlert.Api` error handling (middleware + validation filter) and the **shape of error responses** returned to clients. -| Property | Type | Description | -| :--- | :--- | :--- | -| `Id` | `int` | Primary Key. | -| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | -| `Period` | `string` | Month period (e.g., ""2025-03-01""). | -| `StrongBuy` | `int` | Count of ""Strong Buy"" ratings. | -| `Buy` | `int` | Count of ""Buy"" ratings. | -| `Hold` | `int` | Count of ""Hold"" ratings. | -| `Sell` | `int` | Count of ""Sell"" ratings. | -| `StrongSell` | `int` | Count of ""Strong Sell"" ratings. | -| `SyncedAt` | `DateTime` | UTC timestamp of last sync. | +This is a documentation-only review (no code changes included). --- -#### `InsiderTransaction` _(new)_ -**Insider Activity.** Last 100 insider transactions. Maps to Finnhub `/stock/insider-transactions`. +## 1) Current Behavior (Observed in Code) -| Property | Type | Description | -| :--- | :--- | :--- | -| `Id` | `int` | Primary Key. | -| `TickerSymbol` | `string` | **FK** → `StockListing.TickerSymbol` | -| `Name` | `string?` | Insider full name. | -| `Share` | `long?` | Net share count (positive = buy, negative = sell). | -| `Value` | `decimal?` | Total transaction value in USD. | -| `TransactionDate` | `DateOnly?` | Date of transaction. | -| `FilingDate` | `DateOnly?` | SEC filing date. | -| `TransactionCode` | `string?` | SEC code (e.g., ""P"" = purchase, ""S"" = sale). | +### 1.1 Error response DTOs ---- +Defined in `InventoryManagementSystem/InventoryAlert.Api/Models/Error.cs`: -#### `Notification` _(new — D5)_ -**In-App Alerts Delivery.** Stores triggered alert messages for the authenticated user. UI polls this endpoint every 30 seconds. +- `ErrorResponse` + - `Errors: IEnumerable` + - `ErrorId: Guid` (generated per response) +- `Error` + - `Code: string?` + - `Message: string?` + - `Property: string?` -| Property | Type | Description | -| :--- | :--- | :--- | -| `Id` | `Guid` | Primary Key. | -| `UserId` | `Guid` | **FK** → `User.Id`. Cascade delete. | -| `AlertRuleId` | `Guid?` | **FK** → `AlertRule.Id`. Nullable (for system messages). | -| `TickerSymbol` | `string?` | Symbol that triggered the alert. | -| `Message` | `string` | Human-readable alert message. | -| `IsRead` | `bool` | Whether the user has acknowledged it. Default `false`. | -| `CreatedAt` | `DateTime` | UTC timestamp of notification creation. | +### 1.2 Model validation (400 Bad Request) -> **Index**: `(UserId, IsRead, CreatedAt DESC)` — supports fast unread notification queries. +MVC setup in `InventoryManagementSystem/InventoryAlert.Api/Extensions/MvcExtension.cs`: -### 1.3 DynamoDB Collections +- `SuppressModelStateInvalidFilter = true` +- Adds `ValidateModelFilter` globally +- Enables FluentValidation auto-validation + interceptor -News articles are **permanent historical assets**, not ephemeral cache entries. They are never TTL-deleted. Queries use SK range filters to get recent articles, and a GSI is used for cross-collection lookups. +Validation responses are emitted by: -#### `MarketNews` +- `InventoryManagementSystem/InventoryAlert.Api/Filters/ValidateModelFilter.cs` + - Returns `BadRequestObjectResult(new ErrorResponse(errors))` + - Each error uses: + - `Code = ""InventoryAlert.BAD_REQUEST""` + - `Property = ` + - `Message = ` -| Attribute | Type | Role | Notes | -| :--- | :--- | :--- | :--- | -| `PK` | `string` | Partition Key | `CATEGORY#` e.g. `CATEGORY#general` | -| `SK` | `string` | Sort Key | `TS#` — enables range queries for ""last N hours"" | -| `NewsId` | `long` | Attribute | Finnhub `id` field. Used for deduplication. | -| `Headline` | `string` | Attribute | Article headline. | -| `Summary` | `string` | Attribute | Short article summary. | -| `Source` | `string` | Attribute | Publisher name. | -| `Url` | `string` | Attribute | External article link. | -| `Image` | `string?` | Attribute | Thumbnail image URL. | -| `Category` | `string` | Attribute | `general`, `forex`, `crypto`, `merger`. | -| `SyncedAt` | `string` | Attribute | ISO-8601 UTC timestamp of when this record was written. | +### 1.3 Unhandled exceptions (GlobalExceptionMiddleware) -> **No TTL.** News is retained indefinitely as a queryable historical archive. Use SK range (`TS#` → `TS#`) to retrieve recent articles. +Middleware: `InventoryManagementSystem/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs` -#### `CompanyNews` +Behavior: -| Attribute | Type | Role | Notes | -| :--- | :--- | :--- | :--- | -| `PK` | `string` | Partition Key | `SYMBOL#` e.g. `SYMBOL#TSLA` | -| `SK` | `string` | Sort Key | `TS#` | -| `NewsId` | `long` | Attribute | Finnhub `id`. Deduplication key. | -| `Headline` | `string` | Attribute | Article headline. | -| `Summary` | `string` | Attribute | Short summary. | -| `Source` | `string` | Attribute | Publisher name. | -| `Url` | `string` | Attribute | External article link. | -| `Image` | `string?` | Attribute | Thumbnail URL. | -| `Symbol` | `string` | Attribute | Denormalized ticker (for GSI). | -| `SyncedAt` | `string` | Attribute | ISO-8601 UTC timestamp. | +- Catches exceptions, logs error (including `X-Correlation-Id` when present). +- Maps exceptions to HTTP status codes and returns a JSON error payload: + - Default: `500 Internal Server Error` with code `InventoryAlert.GENERAL_ERROR` + - `UserFriendlyException` → status mapped by `ErrorCode` (404/409/400/401/403/422/500) + - `KeyNotFoundException` or `NotFoundException` → 404 with code `InventoryAlert.NOT_FOUND` + - `FluentValidation.ValidationException` or domain `ValidationException` → 400 with code `InventoryAlert.BAD_REQUEST` + - `ArgumentException` → 400 with code `InventoryAlert.BAD_REQUEST` + - `UnauthorizedAccessException` → 401 with code `InventoryAlert.UNAUTHORIZED` +- Writes response using `await context.Response.WriteAsync(errorResponse.ToString())` -> **No TTL.** Finnhub free tier provides up to 1 year of historical company news on first sync. Retained indefinitely thereafter. +### 1.4 Middleware ordering (important) -#### GSI: `BySymbolAndDate` (on `CompanyNews`) +Pipeline order in `InventoryManagementSystem/InventoryAlert.Api/Program.cs`: -| Attribute | Key Role | -| :--- | :--- | -| `Symbol` | GSI Partition Key | -| `SK` | GSI Sort Key (reused) | +1) `CorrelationIdMiddleware` +2) `GlobalExceptionMiddleware` +3) `PerformanceMiddleware` -Enables efficient cross-symbol queries (e.g., ""all TSLA news this month"") without scanning. +Impact: + +- When downstream throws, `PerformanceMiddleware` does not log a completion entry (because it does not catch/finally), and exception is handled “above” it by `GlobalExceptionMiddleware`. +- Result: failed requests may have an error log but no standard “request completed” log entry. --- -## 2. API Reference +## 2) Inconsistencies / Risks -### Base Configuration +### 2.1 Error code format is inconsistent -- **Version**: `v1` -- **Authentication**: JWT Bearer Token required unless marked `[Public]`. -- **Base URL**: `https://{host}/api/v1` +Two naming paths exist: ---- +- `ErrorRespondCode` enum values (ex: `NOT_FOUND`, `BAD_REQUEST`) produce codes like: + - `InventoryAlert.NOT_FOUND` +- `UserFriendlyException.ErrorCode` enum values (ex: `NotFound`) are currently serialized via `.ToUpper()` which produces: + - `InventoryAlert.NOTFOUND` (missing underscore) -### Finnhub Endpoint Coverage Map +This makes client-side handling and Seq searching harder because codes are not stable. -| Finnhub Endpoint | Our API Route | Status | -| :--- | :--- | :--- | -| `/search` | `GET /stocks/search` | ✅ Implemented | -| `/quote` | `GET /stocks/{symbol}/quote` | ✅ Implemented | -| `/stock/profile2` | `GET /stocks/{symbol}/profile` | ✅ Implemented | -| `/stock/market-status` | `GET /market/status` | ✅ Implemented | -| `/news` | `GET /market/news` | ✅ Implemented | -| `/company-news` | `GET /stocks/{symbol}/news` | ✅ Implemented | -| `/stock/metric` | `GET /stocks/{symbol}/financials` | 🆕 New | -| `/stock/earnings` | `GET /stocks/{symbol}/earnings` | 🆕 New | -| `/stock/recommendation` | `GET /stocks/{symbol}/recommendation` | 🆕 New | -| `/stock/insider-transactions` | `GET /stocks/{symbol}/insiders` | 🆕 New | -| `/stock/peers` | `GET /stocks/{symbol}/peers` | 🆕 New | -| `/calendar/earnings` | `GET /market/calendar/earnings` | 🆕 New | -| `/calendar/ipo` | `GET /market/calendar/ipo` | 🆕 New | -| `/stock/market-holiday` | `GET /market/holiday` | 🆕 New | -| `/stock/symbol` | Internal (worker seed only) | ⚙️ Worker | -| `/forex/exchange`, `/crypto/*` | Not planned (out of scope) | ❌ N/A | +### 2.2 Serialization is inconsistent (middleware vs MVC) ---- +- Model validation uses `BadRequestObjectResult(new ErrorResponse(...))` and will be serialized by ASP.NET Core’s configured JSON options. +- `GlobalExceptionMiddleware` manually serializes via `ErrorResponse.ToString()` with its own `JsonSerializerOptions` (camelCase only). -### Symbol Discovery Strategy (DB-First + Finnhub Fallback) +Risk: -> **Design Goal**: Minimize external Finnhub calls over time. Every successful Finnhub resolution permanently enriches our local `StockListing` database, making future lookups free and instant. +- If global JSON options change (naming, null handling, converters), middleware errors won’t match controller/validation errors. -This pattern applies to **every flow that requires resolving a ticker symbol** — search, add to portfolio, add to watchlist, create alert. +### 2.3 CorrelationId is not part of the JSON response body -```mermaid -flowchart TD - A([Client: search query / symbol]) --> B{Find in StockListing DB?} - B -- Found --> C([Return DB result immediately]) - B -- Not Found --> D[Call Finnhub /search or /stock/profile2] - D --> E{Finnhub returned result?} - E -- No --> F([404: Symbol not recognized]) - E -- Yes --> G[INSERT StockListing row] - G --> H[Trigger background: SyncMetricsJob for symbol] - H --> I([Return newly persisted result]) -``` +The response header `X-Correlation-Id` exists (good), but the JSON payload doesn’t include it. -#### Rules +Operationally, it is easier when the client can log/store a single `correlationId` field from the body for every error response. -| Rule | Detail | -| :--- | :--- | -| **DB check is always first** | Query `StockListing` by `TickerSymbol` (exact) or `Name` (ILIKE for search). | -| **Finnhub is the fallback** | Only called if no DB match. Uses `/search` for fuzzy lookup, `/stock/profile2` for enrichment. | -| **Always persist on resolution** | A resolved Finnhub result is immediately `INSERT`-ed into `StockListing`. Duplicates handled with `ON CONFLICT DO NOTHING`. | -| **Background enrichment** | After insert, enqueue a background job to pull `StockMetric`, `EarningsSurprise`, and `RecommendationTrend` for the new symbol. | -| **Never block the user** | The response is returned immediately after the `StockListing` insert. Enrichment jobs run async. | -| **Rate limit guard** | Finnhub calls are guarded by a Redis counter (`finnhub:ratelimit`) capped at 55 rpm (buffer below the 60/min free limit). | +### 2.4 Validation interceptor behavior looks incomplete -#### Affected Endpoints +`InventoryManagementSystem/InventoryAlert.Api/Validations/ValidatorInterceptor.cs` builds an `ErrorResponse` but does not return it and does not attach structured validation errors to the response directly. -| Endpoint | Behavior | -| :--- | :--- | -| `GET /stocks/search?q=` | DB ILIKE search first → Finnhub `/search` fallback → persists any new matches. | -| `POST /portfolio/` | Validates symbol via DB → Finnhub fallback if missing → reject only if both miss. | -| `POST /watchlist/{symbol}` | Same as portfolio: DB resolve → Finnhub fallback → insert → add to watchlist. | -| `POST /alerts/` | Same symbol resolution chain before creating rule. | +Additionally, the interceptor clears and replaces ModelState errors under the `FluentValidation` key, which may cause: ---- +- Missing/empty `ErrorMessage` values in `ValidateModelFilter` depending on how the ModelState errors are populated. -### [Auth] — `/api/v1/auth` +This is a “review risk” item: validate actual runtime payloads for validation errors to ensure field messages are not lost. -| Method | Endpoint | Auth | Description | -| :--- | :--- | :--- | :--- | -| `POST` | `/login` | `[Public]` | Authenticate and receive JWT + refresh token. 429 rate-limited. | -| `POST` | `/register` | `[Public]` | Create a new user account. | -| `POST` | `/refresh` | `[Public]` | Exchange a valid refresh token for a new access JWT. | -| `POST` | `/logout` | JWT | Revoke the current refresh token. | +### 2.5 Some status semantics are likely underspecified ---- +Examples: -### [Portfolio] — `/api/v1/portfolio` +- A “symbol not recognized” case currently throws `KeyNotFoundException` in services → becomes 404. + - Many APIs would use 404 for missing resources, but “invalid symbol input” might be better as 400/422 depending on business semantics. +- Domain/business-rule failures are not consistently represented as 409 vs 422 vs 400. -_Personal position management. Requires JWT. All data is scoped to the authenticated user._ +--- -> **D1 fix**: Routes use `{symbol}` (the ticker string), not a numeric `{id}`. A portfolio position is uniquely identified by `(UserId, TickerSymbol)` — no separate position table exists. +## 3) Recommended Standard (Stable, Searchable, Client-Friendly) -| Method | Endpoint | Description | -| :--- | :--- | :--- | -| `GET` | `/` | List user's positions (paged). | -| `GET` | `/{symbol}` | Detailed position breakdown for one holding. | -| `GET` | `/alerts` | Breached alert results for user's portfolio (threshold-based). | -| `POST` | `/` | Open a new position. | -| `POST` | `/bulk` | Import multiple positions at once. | -| `PATCH` | `/{symbol}/trade` | Record a trade (buy/sell/etc.) to adjust holdings. | -| `DELETE` | `/{symbol}` | Remove a position from portfolio. | +Pick one of these two approaches and apply it consistently: ---- +### Option A (minimal change): keep `ErrorResponse`, standardize fields + mapping -### [Stocks] — `/api/v1/stocks` +**Response schema (recommended)** -_Global stock catalog and market intelligence. Read-heavy; most endpoints cache aggressively._ +```json +{ + ""errorId"": ""guid"", + ""correlationId"": ""string"", + ""errors"": [ + { ""code"": ""InventoryAlert.BAD_REQUEST"", ""message"": ""…"", ""property"": ""TickerSymbol"" } + ] +} +``` -| Method | Endpoint | Description | -| :--- | :--- | :--- | -| `GET` | `/` | Browse full global StockListing catalog (paged, searchable). | -| `GET` | `/search` | Symbol lookup by name, ISIN, or ticker. | -| `GET` | `/{symbol}/quote` | Real-time price quote from Finnhub or local cache. | -| `GET` | `/{symbol}/profile` | Full company profile (Logo, Industry, MarketCap, IPO date). | -| `GET` | `/{symbol}/financials` | 🆕 Basic Financials (P/E, EPS, 52-week range, margins). | -| `GET` | `/{symbol}/earnings` | 🆕 Last 4 quarters of earnings surprises (actual vs. estimate). | -| `GET` | `/{symbol}/recommendation` | 🆕 Latest analyst recommendation trend (Buy/Hold/Sell counts). | -| `GET` | `/{symbol}/insiders` | 🆕 Last 100 insider transactions (SEC-reported). | -| `GET` | `/{symbol}/peers` | 🆕 List of peer companies in the same sector/country. | -| `GET` | `/{symbol}/news` | 🆕 Latest company-specific news (from DynamoDB cache). | -| `POST` | `/sync` | `[Admin]` Manually trigger global price sync job. | +Rules: ---- +- Always return `ErrorResponse` for non-2xx. +- Always include `correlationId` in the JSON body (and keep the header). +- Keep `errorId` as a server-generated unique id (good for support tickets). +- Ensure `code` values are stable and come from **one enum/source of truth** (recommend using `ErrorRespondCode` style with underscores). -### [Market] — `/api/v1/market` +### Option B (more standard): adopt RFC 7807 Problem Details -_Exchange-level data. Partially public._ +Use `ProblemDetails` for the main envelope and include your current `errors[]` in extensions. -| Method | Endpoint | Auth | Description | -| :--- | :--- | :--- | :--- | -| `GET` | `/status` | JWT | Current open/closed status of major exchanges. | -| `GET` | `/news` | JWT | Global financial news feed (paged). | -| `GET` | `/holiday` | JWT | 🆕 Upcoming and past market holidays by exchange. | -| `GET` | `/calendar/earnings` | JWT | 🆕 Upcoming earnings release calendar (1-month window). | -| `GET` | `/calendar/ipo` | JWT | 🆕 Upcoming and recent IPOs. | +This aligns with many .NET clients and tooling, but is a bigger change and may not be necessary if `ErrorResponse` is already established. --- -### [Watchlist] — `/api/v1/watchlist` - -| Method | Endpoint | Description | -| :--- | :--- | :--- | -| `GET` | `/` | List user's watchlist with live price and basic metrics. | -| `GET` | `/{symbol}` | Detailed view of a single watchlist entry. | -| `POST` | `/{symbol}` | Add a ticker symbol to watchlist. | -| `DELETE` | `/{symbol}` | Remove a ticker from watchlist. | +## 4) Status Code & Error Code Mapping (Proposed) ---- +This table is a suggested baseline: -### [Alert Rules] — `/api/v1/alerts` +| HTTP | Code | When | +| ---: | ---------------------------------------------------- | --------------------------------------------------------- | +| 400 | `InventoryAlert.BAD_REQUEST` | invalid input shape, parsing, validation failures | +| 401 | `InventoryAlert.UNAUTHORIZED` | missing/invalid auth, invalid refresh token | +| 403 | `InventoryAlert.FORBIDDEN` | authenticated but lacks permission | +| 404 | `InventoryAlert.NOT_FOUND` | resource id not found (rule id, notification id, etc.) | +| 409 | `InventoryAlert.CONFLICT` | version conflict / uniqueness / state conflict | +| 422 | `InventoryAlert.UNPROCESSABLE_ENTITY` | business-rule violation when input is syntactically valid | +| 500 | `InventoryAlert.INTERNAL_ERROR` (or `GENERAL_ERROR`) | unexpected server failures | -_Manages definitions for advanced, dynamic notification triggers._ +Recommendation: -| Method | Endpoint | Description | -| :--- | :--- | :--- | -| `GET` | `/` | List all alert rules for the authenticated user. | -| `POST` | `/` | Create a new alert rule. | -| `PUT` | `/{ruleId}` | Replace an existing alert rule. | -| `PATCH` | `/{ruleId}/toggle` | Enable or disable a rule without full replacement. | -| `DELETE` | `/{ruleId}` | Permanently remove an alert rule. | +- Remove duplicate “500 codes” (`INTERNAL_ERROR` vs `GENERAL_ERROR`) or define strict meaning: + - `INTERNAL_ERROR`: known internal failure classification + - `GENERAL_ERROR`: fallback for truly unknown exceptions --- -### [Notifications] — `/api/v1/notifications` +## 5) Middleware / Filter Recommendations -_In-app notification delivery. Polls every 30s from UI. Requires JWT._ +### 5.1 Ensure failed requests still produce a standard “request completed” log -| Method | Endpoint | Description | -| :--- | :--- | :--- | -| `GET` | `/` | List all notifications for current user (unread first). | -| `GET` | `/unread-count` | Returns `{ Count: int }` — used for bell badge. | -| `PATCH` | `/{id}/read` | Mark a single notification as read. | -| `PATCH` | `/read-all` | Mark all notifications as read. | -| `DELETE` | `/{id}` | Dismiss a notification permanently. | +If you want every request (success/failure) logged once, you need either: ---- +- a request logging middleware that logs in `finally`, or +- move the request timing middleware *outside* the exception middleware and catch exceptions inside the timing middleware (still rethrow). -### [Events] — `/api/v1/events` `[Admin/Internal]` +### 5.2 Standardize response serialization in middleware -| Method | Endpoint | Description | -| :--- | :--- | :--- | -| `POST` | `/` | Publish an integration event to SQS. | -| `GET` | `/types` | List all supported event type strings. | - ---- - -## 3. Background Processing (Worker Architecture) +Do not manually serialize `ErrorResponse` using a local `JsonSerializerOptions`. -### Hybrid Strategy +Instead, emit an object result using the app’s configured JSON options (so errors from middleware match errors from controllers/filters). -| Layer | Engine | Purpose | -| :--- | :--- | :--- | -| **Scheduled Jobs** | Hangfire | Recurring heartbeats (price sync, news batching, metrics). | -| **Event Handlers** | SQS + Redis | Reactive tasks (alert evaluation, news on-demand). | +### 5.3 Fix error code formatting once ---- +Pick one canonical error code style: -### Scheduled Jobs +- `InventoryAlert.NOT_FOUND` (underscore-separated), recommended because you already have `ErrorRespondCode`. -Located in `InventoryAlert.Worker/ScheduledJobs`. +Then ensure: -| Job | Schedule | Finnhub Endpoint(s) Used | Description | -| :--- | :--- | :--- | :--- | -| **SyncPricesJob** | Every 15 min | `/quote` | Full sweep of `StockListing` catalog. Updates `PriceHistory`, evaluates all `AlertRule` conditions. | -| **SyncMetricsJob** | Daily at 06:00 UTC | `/stock/metric` | 🆕 Updates `StockMetric` table for all active symbols. | -| **SyncEarningsJob** | Daily at 07:00 UTC | `/stock/earnings` | 🆕 Refreshes `EarningsSurprise` rows for watchlisted symbols. | -| **SyncRecommendationsJob** | Weekly (Monday) | `/stock/recommendation` | 🆕 Refreshes `RecommendationTrend` for portfolio + watchlist symbols. | -| **SyncInsidersJob** | Daily at 08:00 UTC | `/stock/insider-transactions` | 🆕 Pulls last 100 insider transactions for actively-watched symbols. | -| **CompanyNewsJob** | Every 6 hours | `/company-news` | Batch news sync for all symbols on any user's watchlist → DynamoDB. | -| **MarketNewsJob** | Every 2 hours | `/news` | Global news refresh → DynamoDB `MarketNews`. | -| **ProcessQueueJob** | Continuous long-poll | — | SQS reader with Redis-based idempotency (30-min window). | -| **SqsScheduledPollerJob** | Every 5 min | — | Fallback SQS drain if the continuous poller fails. | +- `UserFriendlyException` uses the same mapping, not `.ToUpper()` of enum names. ---- +### 5.4 Validation errors: keep field-level details -### Event-Driven Handlers +Ensure validation responses always contain: -Located in `InventoryAlert.Worker/IntegrationEvents/Handlers`. +- field name (`property`) +- message (`message`) +- stable code (`InventoryAlert.BAD_REQUEST`) -| Handler | SQS Event Type | Logic | -| :--- | :--- | :--- | -| **PriceAlertHandler** | `inventoryalert.pricing.price-drop.v1` | On-demand quote fetch → cache update → `PriceHistory` insert → full `AlertRule` evaluate for symbol. | -| **LowHoldingsHandler** | `inventoryalert.inventory.stock-low.v1` | Post-trade trigger → queries `AlertRule` for `LowHoldingsCount` → notifies if breached. | -| **CompanyNewsHandler** | `inventoryalert.news.headline.v1` | Immediate sync of ticker news → DynamoDB `CompanyNews`. | -| **DefaultHandler** | `*` (unmatched) | Acknowledge and delete. Logs warning. Prevents poison-message queue blockage. | +Avoid injecting exceptions into ModelState if it causes empty messages. --- -### Flow & Deduplication +## 6) Quick Checklist (Acceptance Criteria) -1. **Publish**: API/Services wrap payloads in an `EventEnvelope` and push to SQS. -2. **Poll**: `ProcessQueueJob` retrieves messages and checks Redis for atomic duplicates (30-min TTL window). -3. **Cooldown**: `PriceAlertHandler` carries a **24-hour per-symbol cooldown** via Redis to prevent alert storms. -4. **Route**: `IIntegrationMessageRouter` maps `EventType` → `IIntegrationEventHandler`. -5. **Audit**: After 5 failed attempts, messages are acknowledged and deleted to unblock the queue. All failures are logged via `ILogger`. +- All error responses follow a single schema (same fields across validation + exceptions). +- Error codes have a stable, consistent format (no `NOTFOUND` vs `NOT_FOUND`). +- `X-Correlation-Id` exists and `correlationId` exists in the JSON body. +- Serialization is consistent across middleware and MVC. +- Error responses never leak sensitive content (tokens, secrets, stack traces) in Production.",227,9d1aea0ca6a54c1af7f0b254dc6be58b,doc\archive\error_handling_and_response_standard.md,0,292,"inventoryalert, error, code, middleware, validation, errors, response, errorresponse",1779851803.9193945,10,entity framework iproductservice productscontroller iactionresult price drop msft threshold stock httpget stock ticker googl application service appdbcontext sku aapl dbcontext symbol httpput productservice httppost efcore item inventory asnotracking business logic loss notification,# Error Handling & Response Standardization (Review + Recommendations) | Error Handling & Response Standardization (Review + Recommendations) Scope: Inve +doc,"# 🏗️ Event-Driven Architecture Plan ---- +## Hangfire + SNS/SQS + Redis + Multi-Project System -## 4. Data Transfer Objects +> **Scope:** Extend the existing `InventoryAlert.Api` into a full event-driven microservices ecosystem. +> **Constraint:** Use only Finnhub Free-Tier APIs. All AWS services emulated via **Moto**. -### 4.1 Authentication +--- -| DTO | Properties | -| :--- | :--- | -| `LoginRequest` | `Username` (string), `Password` (string) | -| `RegisterRequest` | `Username` (string), `Password` (string), `Email` (string) | -| `AuthResponse` | `AccessToken` (string, JWT), `ExpiresAt` (DateTime, UTC), `RefreshToken` (string — delivered as `httpOnly` cookie, not body) | -| `RefreshRequest` | No body. Refresh token read from `httpOnly` cookie automatically. | +## 🗺️ High-Level Architecture -> **JWT config**: Access token TTL = **15 minutes**. Refresh token TTL = **7 days**, stored as `httpOnly; Secure; SameSite=Strict` cookie. Refresh tokens are single-use (rotated on each refresh). +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ EXTERNAL WORLD │ +│ [Telegram Bot] [Sample.Publisher App] [Browser/Postman] │ +└───────────┬─────────────────┬───────────────────────┬──────────────┘ + │ │ │ + ▼ ▼ ▼ +┌────────────────────────────────────────────────────────────────────┐ +│ InventoryAlert.Api (Port 8080) │ +│ │ +│ POST /api/events → Validate → Publish to SNS Topic │ +│ POST /api/market-alerts → Manually trigger a price-alert event │ +│ GET /api/products → (existing endpoints) │ +└───────────────────────────────────┬────────────────────────────────┘ + │ SNS Publish + ▼ +┌──────────────────────────────────────────────────────────────────┐ +│ Moto (Mock AWS) Port 5000 │ +│ │ +│ SNS Topic: arn:aws:sns:us-east-1:123456789:inventory-events │ +│ │ │ +│ └──► SQS Queue: arn:aws:sqs:us-east-1:123456789:event-queue │ +└──────────────────────────────────────────────────────────────────┘ + │ SQS Poll + ▼ +┌──────────────────────────────────────────────────────────────────┐ +│ InventoryAlert.Worker (New Project) │ +│ │ +│ [Hangfire Job: PollSqsJob] │ +│ → Dequeue messages from SQS │ +│ → Route by event type │ +│ → Execute handlers (FetchQuote, SaveAlert, etc.) │ +│ → Cache results in Redis │ +│ → Persist to PostgreSQL │ +└──────────────────────────────────────────────────────────────────┘ + │ Cache Reads + ▼ +┌──────────────────────────────────────────────────────────────────┐ +│ Redis (Port 6379) │ +│ │ +│ Key: ""product:quote:{symbol}"" → TTL 60s (live price cache) │ +│ Key: ""job:last-run:{jobName}"" → TTL 10m (last execution ts) │ +│ Key: ""alert:history:{symbol}"" → TTL 24h (dedup alert history) │ +└──────────────────────────────────────────────────────────────────┘ +``` --- -### 4.2 Portfolio & Trades +## 📁 Solution Structure -| DTO | Properties | -| :--- | :--- | -| `CreatePositionRequest` | `TickerSymbol` (string), `Quantity` (decimal, must be > 0), `UnitPrice` (decimal, must be > 0), `TradedAt` (DateTime?) | -| `TradeRequest` | `Type` (enum: `Buy`/`Sell`/`Dividend`/`Split`), `Quantity` (decimal, **always positive**), `UnitPrice` (decimal), `Notes` (string?) | -| `PortfolioPositionResponse` | `StockId` (int), `Symbol` (string), `Name` (string), `Exchange` (string), `Logo` (string), `HoldingsCount` (decimal), `AveragePrice` (decimal), `CurrentPrice` (decimal), `MarketValue` (decimal), `TotalCost` (decimal), `TotalReturn` (decimal), `TotalReturnPercent` (double), `PriceChange` (decimal), `PriceChangePercent` (double), `Industry` (string) | -| `PortfolioAlertResponse` | `Symbol` (string), `CurrentPrice` (decimal), `Threshold` (decimal), `LossPercent` (double), `LastUpdated` (DateTime) | -| `NotificationResponse` | `Id` (Guid), `Message` (string), `TickerSymbol` (string?), `IsRead` (bool), `CreatedAt` (DateTime) | +``` +InventoryManagementSystem/ +├── InventoryAlert.Api/ ← Existing REST API +├── InventoryAlert.Worker/ ← NEW: Hangfire + SQS Consumer +├── InventoryAlert.Sample/ ← NEW: Sample Event Publisher CLI +├── InventoryAlert.Contracts/ ← NEW: Shared Event Schemas (DTOs) +└── InventoryAlert.Tests/ ← Existing test project +``` --- -### 4.3 Alert Rules +## 📦 Project 1: `InventoryAlert.Contracts` (Shared Event Schema) -| DTO | Properties | -| :--- | :--- | -| `AlertRuleRequest` | `TickerSymbol` (string), `Condition` (enum), `TargetValue` (decimal), `TriggerOnce` (bool) | -| `AlertRuleResponse` | `Id` (Guid), `TickerSymbol` (string), `Condition` (enum), `TargetValue` (decimal), `IsActive` (bool), `TriggerOnce` (bool), `LastTriggeredAt` (DateTime?) | -| `ToggleAlertRequest` | `IsActive` (bool) | +> **Why a separate project?** Both the API (publisher) and the Worker (consumer) must agree on the same message format. A shared `Contracts` project (referenced by both) eliminates duplication and version drift. ---- +### Event Envelope (SNS/SQS Standard Format) -### 4.4 Market & Stock Data +All events follow the standard SNS notification format: -| DTO | Properties | -| :--- | :--- | -| `StockQuoteResponse` | `Symbol`, `Price`, `Change`, `ChangePercent`, `High`, `Low`, `Open`, `PrevClose`, `Timestamp` | -| `StockProfileResponse` | `Symbol`, `Name`, `Exchange`, `Currency`, `Country`, `Industry`, `MarketCap`, `Ipo`, `WebUrl`, `Logo` | -| `StockMetricResponse` | `Symbol`, `PeRatio`, `PbRatio`, `EpsBasicTtm`, `DividendYield`, `Week52High`, `Week52Low`, `RevenueGrowthTtm`, `MarginNet`, `LastSyncedAt` | -| `EarningsSurpriseResponse` | `Period`, `ActualEps`, `EstimateEps`, `SurprisePercent`, `ReportDate` | -| `RecommendationResponse` | `Period`, `StrongBuy`, `Buy`, `Hold`, `Sell`, `StrongSell` | -| `InsiderTransactionResponse` | `Name`, `Share`, `Value`, `TransactionDate`, `FilingDate`, `TransactionCode` | -| `SymbolSearchResponse` | `Symbol`, `Description`, `Type`, `Exchange` | -| `MarketStatusResponse` | `Exchange`, `IsOpen`, `Session`, `Holiday`, `Timezone` | -| `MarketHolidayResponse` | `Exchange`, `EventName`, `Date`, `AtTime` | -| `NewsResponse` | `Id` (long), `Headline`, `Summary`, `Source`, `Url`, `DateTime`, `Image`, `Category` | -| `EarningsCalendarResponse` | `Symbol`, `Date`, `EpsEstimate`, `EpsActual`, `RevenueEstimate`, `RevenueActual` | -| `IpoCalendarResponse` | `Symbol`, `Name`, `Date`, `Price`, `Shares`, `Status` | -| `PeersResponse` | `Symbol`, `Peers` (List\) | +```json +{ + ""Type"": ""Notification"", + ""MessageId"": ""uuid-v4"", + ""TopicArn"": ""arn:aws:sns:us-east-1:123456789:inventory-events"", + ""Subject"": ""MarketPriceAlert"", + ""Message"": ""{...serialized payload...}"", + ""Timestamp"": ""2026-04-04T01:00:00Z"", + ""MessageAttributes"": { + ""EventType"": { + ""Type"": ""String"", + ""Value"": ""MarketPriceAlert"" + }, + ""SourceService"": { + ""Type"": ""String"", + ""Value"": ""InventoryAlert.Api"" + } + } +} +``` ---- +### Event Types -## 5. Comprehensive Interface Catalog +| EventType | Trigger | Finnhub Source | +| :----------------- | :--------------------------------------------- | :---------------------------- | +| `MarketPriceAlert` | Price drops beyond `PriceAlertThreshold` | `/quote` | +| `StockLowAlert` | `StockCount` drops below `StockAlertThreshold` | Internal DB | +| `EarningsAlert` | A tracked company announces earnings | `/stock/earnings` | +| `InsiderSellAlert` | Insider selling detected above a threshold | `/stock/insider-transactions` | +| `CompanyNewsAlert` | High-impact news published for a tracked stock | `/company-news` | -### 5.1 Auth — `/api/v1/auth` +### New Domain Models -**POST `/login`** -- **Request**: `{ Username, Password }` -- **200 OK**: `AuthResponse` — `{ AccessToken, ExpiresAt }`. Refresh token set as `httpOnly` cookie. -- **401**: ""Invalid username or password."" -- **429**: ""Login rate limit exceeded. Try again in 15m."" +```csharp +// Contracts/Events/EventEnvelope.cs +public record EventEnvelope +{ + public string MessageId { get; init; } = Guid.NewGuid().ToString(); + public string TopicArn { get; init; } = string.Empty; + public string Subject { get; init; } = string.Empty; // EventType + public string Message { get; init; } = string.Empty; // Serialized payload + public DateTime Timestamp { get; init; } = DateTime.UtcNow; + public Dictionary MessageAttributes { get; init; } = []; +} -**POST `/register`** -- **Request**: `{ Username, Password, Email }` -- **200 OK**: `{ Message: ""Registration successful."" }` -- **409**: ""Username or email already in use."" +// Contracts/Events/Payloads/MarketPriceAlertPayload.cs +public record MarketPriceAlertPayload +{ + public int ProductId { get; init; } + public string Symbol { get; init; } = string.Empty; + public decimal OriginPrice { get; init; } + public decimal CurrentPrice { get; init; } + public decimal DropPercent { get; init; } // e.g. 0.12 = 12% +} -**POST `/refresh`** -- **Request**: No body. Reads `refreshToken` from `httpOnly` cookie. -- **200 OK**: New `AuthResponse` (rotated refresh token set in cookie). -- **401**: ""Refresh token expired or invalid."" +// Contracts/Events/Payloads/EarningsAlertPayload.cs +public record EarningsAlertPayload +{ + public string Symbol { get; init; } = string.Empty; + public decimal ActualEPS { get; init; } + public decimal EstimatedEPS { get; init; } + public decimal SurprisePercent { get; init; } + public string Period { get; init; } = string.Empty; // e.g. ""Q4 2025"" +} -**POST `/logout`** -- **Request**: No body. -- **200 OK**: `{ Message: ""Logged out."" }`. Clears `httpOnly` cookie server-side. +// Contracts/Events/Payloads/InsiderSellAlertPayload.cs +public record InsiderSellAlertPayload +{ + public string Symbol { get; init; } = string.Empty; + public string InsiderName { get; init; } = string.Empty; + public long SharesSold { get; init; } + public decimal ValueUsd { get; init; } + public DateTime TransactionDate { get; init; } +} + +// Contracts/Events/Payloads/CompanyNewsAlertPayload.cs +public record CompanyNewsAlertPayload +{ + public string Symbol { get; init; } = string.Empty; + public string Headline { get; init; } = string.Empty; + public string Source { get; init; } = string.Empty; + public string Url { get; init; } = string.Empty; + public DateTime PublishedAt { get; init; } +} +``` --- -### 5.2 Portfolio — `/api/v1/portfolio` +## 🌐 Project 2: `InventoryAlert.Api` (New Endpoints) -**GET `/`** -- **Query**: `Page` [int], `PageSize` [int], `Search` [string] -- **200 OK**: `PagedResult` - -**GET `/{symbol}`** _(D1: symbol replaces id)_ -- **200 OK**: `PortfolioPositionResponse` -- **404**: ""No position found for symbol '{symbol}'."" +### New Endpoints -**GET `/alerts`** -- **200 OK**: `List` +| Method | Route | Purpose | +| :----- | :------------------------- | :------------------------------------------- | +| `POST` | `/api/events` | Receive any generic event and publish to SNS | +| `POST` | `/api/events/market-alert` | Manually trigger a `MarketPriceAlert` event | +| `POST` | `/api/events/news-alert` | Manually trigger a `CompanyNewsAlert` event | +| `GET` | `/api/events/types` | List all supported event types | -**POST `/`** -- **Request**: `CreatePositionRequest` -- **201 Created**: `PortfolioPositionResponse` -- **409**: ""Symbol already exists in your portfolio."" -- **422**: ""Invalid or unrecognized ticker symbol."" +### New Service: `IEventPublisher` -**POST `/bulk`** -- **Request**: `List` -- **200 OK**: `{ Imported: int, Failed: int, Errors: List }` +``` +IEventPublisher + └── PublishAsync(EventEnvelope envelope) → Task + → Serializes envelope to JSON + → Publishes to SNS Topic ARN + → SNS auto-fans-out to subscribed SQS queues +``` -**PATCH `/{symbol}/trade`** _(D1 + D2)_ -- **Request**: `TradeRequest` — `Quantity` must always be positive; direction from `Type`. -- **200 OK**: Updated `PortfolioPositionResponse` -- **404**: ""No position found for symbol '{symbol}'."" -- **422**: ""Resulting holdings count cannot be negative."" +### New Entity: `EventLog` (for audit trail) -**DELETE `/{symbol}`** _(D1)_ -- **200 OK**: `{ Message: ""Position removed."" }` -- **404**: ""No position found for symbol '{symbol}'."" -- **409**: ""Cannot remove a position with active alert rules. Delete rules first."" +Persist all published events to the DB for auditing: -> ❗ **Cascade Scope (Critical).** Deleting a portfolio position is a **user-scoped** operation only. It does **NOT** touch any global tables: -> - ✅ **Deleted**: The user's position row + all their `Trade` ledger entries for this symbol. -> - ✅ **Deleted**: The user's `AlertRule` rows for this symbol (must confirm first via 409 guard above). -> - ✅ **Deleted**: The user's `WatchlistItem` for this symbol, if present (auto-cascade). -> - ❌ **NOT deleted**: `StockListing` — global catalog, shared by all users. -> - ❌ **NOT deleted**: `PriceHistory` — global time-series data, never user-owned. -> - ❌ **NOT deleted**: `StockMetric`, `EarningsSurprise`, `RecommendationTrend`, `InsiderTransaction` — market data, never user-owned. -> -> **Rationale**: `StockListing` is the backbone of the symbol database. Removing a position means the user is exiting a trade, not declaring the company no longer exists. +| Column | Type | Notes | +| :-------------- | :--------- | :------------------------ | +| `Id` | `int` | PK | +| `MessageId` | `string` | From SNS | +| `EventType` | `string` | e.g. `MarketPriceAlert` | +| `Payload` | `string` | JSON body | +| `PublishedAt` | `DateTime` | UTC | +| `SourceService` | `string` | e.g. `InventoryAlert.Api` | --- -### 5.3 Stocks — `/api/v1/stocks` - -**GET `/`** -- **Query**: `Page` [int], `PageSize` [int], `Exchange` [string], `Industry` [string] -- **200 OK**: `PagedResult` - -**GET `/search`** -- **Query**: `q` [string, required] -- **200 OK**: `List` +## ⚙️ Project 3: `InventoryAlert.Worker` (New Project) -**GET `/{symbol}/quote`** -- **200 OK**: `StockQuoteResponse` -- **404**: ""Symbol not found in catalog."" +This is a separate **.NET Worker Service** (minimal API or `BackgroundService` host) focused entirely on job processing. -**GET `/{symbol}/profile`** -- **200 OK**: `StockProfileResponse` -- **404**: ""Symbol not supported."" +### Why separate from the API? -**GET `/{symbol}/financials`** _(new)_ -- **200 OK**: `StockMetricResponse` -- **404**: ""Metrics not yet available for this symbol."" +- The API should stay fast and focused on handling HTTP. +- The Worker can be scaled independently (more workers = more SQS throughput). +- Hangfire runs in the Worker, keeping the Dashboard away from the API layer. -**GET `/{symbol}/earnings`** _(new)_ -- **200 OK**: `List` (last 4 quarters) -- **404**: ""Earnings data not found."" +### Architecture: Hangfire Jobs -**GET `/{symbol}/recommendation`** _(new)_ -- **200 OK**: `List` (last 3 months) -- **404**: ""Recommendation data not found."" +| Job Name | Schedule | Responsibility | Finnhub Call | +| :------------------ | :-------- | :------------------------------------------------- | :---------------------------- | +| `PollSqsJob` | Every 30s | Dequeue messages from SQS and dispatch to handlers | None | +| `SyncPricesJob` | Every 10m | Update `CurrentPrice` for all products | `/quote` | +| `EarningsCheckJob` | Every 6h | Check if tracked symbols have new earnings | `/stock/earnings` | +| `InsiderTxCheckJob` | Every 6h | Check for insider selling on tracked symbols | `/stock/insider-transactions` | +| `NewsCheckJob` | Every 1h | Fetch latest news for tracked symbols | `/company-news` | -**GET `/{symbol}/insiders`** _(new)_ -- **200 OK**: `List` (last 100) -- **404**: ""Insider data not found."" +### SQS Consumer Flow -**GET `/{symbol}/peers`** _(new)_ -- **200 OK**: `PeersResponse` -- **404**: ""Peer list not available."" +``` +PollSqsJob runs → + Dequeue up to 10 messages from SQS → + For each message: + 1. Parse EventEnvelope + 2. Check Redis: ""alert:history:{symbol}"" to avoid duplicate alerts + 3. Route to handler by EventType: + - MarketPriceAlert → PriceAlertHandler → Notify (log/Telegram) + - EarningsAlert → EarningsHandler → Update Product metrics in DB + - InsiderSellAlert → InsiderHandler → Flag product in DB + - CompanyNewsAlert → NewsHandler → Store news in DB + 4. Cache result in Redis (TTL rules above) + 5. Delete message from SQS (acknowledge) +``` -**GET `/{symbol}/news`** _(new)_ -- **Query**: `From` [DateOnly], `To` [DateOnly] -- **200 OK**: `List` +### Redis Caching Strategy -**POST `/sync`** `[Admin]` -- **202 Accepted**: `{ Message: ""Price sync job enqueued."" }` +| Key Pattern | Stores | TTL | Populated By | +| :------------------------------ | :------------------- | :--------- | :------------------- | +| `product:quote:{AAPL}` | Latest price quote | 60 seconds | `SyncPricesJob` | +| `alert:history:{AAPL}` | Last alert timestamp | 24 hours | `PollSqsJob` (dedup) | +| `job:last-run:EarningsCheckJob` | Last run timestamp | 10 minutes | Each Job | +| `news:{AAPL}:latest` | Latest news headline | 1 hour | `NewsCheckJob` | --- -### 5.4 Market — `/api/v1/market` +## 🧪 Project 4: `InventoryAlert.Sample` (Event Publisher CLI) -**GET `/status`** -- **200 OK**: `List` +A simple Console App that **simulates external systems** pushing events into the ecosystem. This is for local development and testing without needing a real frontend. -**GET `/news`** -- **Query**: `Category` [string: general/forex/crypto/merger], `Page` [int] -- **200 OK**: `PagedResult` +### Functionality -**GET `/holiday`** _(new)_ -- **Query**: `Exchange` [string, required] -- **200 OK**: `List` +``` +InventoryAlert.Sample (Console App) + ├── Menu option 1: Publish a MarketPriceAlert event + ├── Menu option 2: Publish an EarningsAlert event + ├── Menu option 3: Publish an InsiderSellAlert event + ├── Menu option 4: Publish a CompanyNewsAlert event + └── Menu option 5: Stress test — publish 50 random events +``` -**GET `/calendar/earnings`** _(new)_ -- **Query**: `From` [DateOnly], `To` [DateOnly], `Symbol` [string?] -- **200 OK**: `List` -- **Note**: Free tier limited to 1-month window. +### How it works -**GET `/calendar/ipo`** _(new)_ -- **Query**: `From` [DateOnly], `To` [DateOnly] -- **200 OK**: `List` +- Points to `http://localhost:8080/api/events` (the main API). +- Sends events via **HTTP POST** with the standard `EventEnvelope` format. +- OR can publish directly to **Moto SQS** at `http://localhost:5000` bypassing the API (for testing the worker in isolation). --- -### 5.5 Watchlist — `/api/v1/watchlist` +## 🔌 Telegram Integration (Future) -**GET `/`** -- **200 OK**: `List` (live quote merged with listing data) +The `IAlertNotifier` interface (already planned) will have a `TelegramAlertNotifier` implementation: -**GET `/{symbol}`** -- **200 OK**: `PortfolioPositionResponse` -- **404**: ""Symbol not on your watchlist."" +``` +TelegramAlertNotifier + → Uses Telegram Bot API (bot token in env vars) + → Sends formatted messages to a chat channel + → Triggered by PriceAlertHandler / InsiderHandler inside the Worker +``` -**POST `/{symbol}`** -- **201 Created**: `PortfolioPositionResponse` -- **409**: ""Symbol already on watchlist."" -- **422**: ""Unrecognized ticker symbol."" +Message format: -**DELETE `/{symbol}`** -- **200 OK**: `{ Message: ""Removed from watchlist."" }` -- **404**: ""Symbol not on your watchlist."" +``` +🚨 PRICE DROP ALERT +Symbol: AAPL +Drop: -15.3% +Current: $142.00 +Origin: $167.50 +Threshold: -10% +Time: 2026-04-04 02:00 UTC +``` --- -### 5.6 Alert Rules — `/api/v1/alerts` +## 🧩 Business Logic Scenarios (Finnhub Free Tier) -**GET `/`** -- **200 OK**: `List` +| Scenario | Entities Affected | Finnhub Endpoint | Event Published | +| :------------------------- | :------------------------------ | :---------------------------- | :----------------- | +| **Price Drop > threshold** | `Product.CurrentPrice` | `/quote` | `MarketPriceAlert` | +| **Earnings miss > 10%** | New `EarningsRecord` entity | `/stock/earnings` | `EarningsAlert` | +| **Insider sells > $1M** | New `InsiderTransaction` entity | `/stock/insider-transactions` | `InsiderSellAlert` | +| **High impact news** | New `NewsRecord` entity | `/company-news` | `CompanyNewsAlert` | +| **Market closes** | Trigger close-of-day sync | `/stock/market-status` | Internal only | -**POST `/`** -- **Request**: `AlertRuleRequest` -- **201 Created**: `AlertRuleResponse` -- **400**: ""TargetValue must be positive."" -- **422**: ""Symbol not recognized."" +### New Entities (Database Changes Required) -**PUT `/{ruleId}`** -- **Request**: `AlertRuleRequest` -- **200 OK**: `AlertRuleResponse` -- **403**: ""You do not own this rule."" -- **404**: ""Alert rule not found."" +``` +EarningsRecord + ├── Id (int) + ├── ProductId (FK → Product) + ├── Symbol (string) + ├── Period (string) ← e.g. ""2025Q4"" + ├── ActualEPS (decimal) + ├── EstimatedEPS (decimal) + ├── SurprisePercent (decimal) + └── RecordedAt (DateTime) -**PATCH `/{ruleId}/toggle`** -- **Request**: `ToggleAlertRequest` -- **200 OK**: `AlertRuleResponse` -- **404**: ""Alert rule not found."" +InsiderTransaction + ├── Id (int) + ├── ProductId (FK → Product) + ├── InsiderName (string) + ├── TransactionType (string) ← ""Buy"" or ""Sell"" + ├── Shares (long) + ├── ValueUsd (decimal) + └── TransactionDate (DateTime) -**DELETE `/{ruleId}`** -- **200 OK**: `{ Message: ""Alert rule deleted."" }` -- **403**: ""You do not own this rule."" -- **404**: ""Alert rule not found."" +NewsRecord + ├── Id (int) + ├── ProductId (FK → Product) + ├── Symbol (string) + ├── Headline (string) + ├── Source (string) + ├── Url (string) + └── PublishedAt (DateTime) + +EventLog + ├── Id (int) + ├── MessageId (string) ← From SNS + ├── EventType (string) + ├── Payload (string) ← JSON + ├── Status (string) ← ""Published"" | ""Processed"" | ""Failed"" + └── CreatedAt (DateTime) +``` --- -### 5.7 Notifications — `/api/v1/notifications` +## 🚀 Future Enterprise Extension (DynamoDB Polyglot Strategy) -**GET `/`** -- **Query**: `OnlyUnread` [bool, default false], `Page` [int] -- **200 OK**: `PagedResult` — ordered by `CreatedAt DESC`. +When raw telemetry events outgrow Postgres and Redis connections bottleneck: -**GET `/unread-count`** -- **200 OK**: `{ Count: int }` — used by UI navbar bell badge. +1. **Replaces Postgres `EventLog`:** A DynamoDB `InventoryAlert_EventLog` table would use `ExpiresAt` (Epoch) for AWS-native auto-cleanup, shedding millions of stale events without requiring massive SQL `DELETE` sweeps. +2. **Replaces Redis Deduplication:** DynamoDB has persistent TTL semantics. Instead of limiting memory in Redis clusters, worker nodes can do a cost-efficient atomic `PutItem` to check if a `MessageId` or `alert:history:{symbol}` exists, naturally expiring stale histories. +3. **Merges Timeseries Metrics:** Rather than maintaining `EarningsRecord`, `InsiderTransaction`, and `NewsRecord` across multiple SQL tables with foreign keys, a single NoSQL table `InventoryAlert_StockHistory` stores it all via composite Sort Keys (`NEWS#2026-04-04`, `EARNINGS#2026Q4`), creating a blazing-fast audit trail view. -**PATCH `/{id}/read`** -- **200 OK**: `{ Message: ""Marked as read."" }` -- **404**: ""Notification not found."" +--- -**PATCH `/read-all`** -- **200 OK**: `{ Updated: int }` +## 🖥️ Docker Services (Final State) -**DELETE `/{id}`** -- **200 OK**: `{ Message: ""Notification dismissed."" }` -- **404**: ""Notification not found."" +```yaml +services: + api: # REST API + Event Publisher + worker: # Hangfire + SQS Consumer + db: # PostgreSQL 17-alpine — healthcheck: pg_isready + redis: # Redis 7.2-alpine — healthcheck: redis-cli ping + moto: # motoserver/moto:5.1.22 — Mock SNS/SQS, healthcheck: curl :5000 + moto-init: # amazon/aws-cli:2.3.4 — one-shot init: creates SNS + SQS on boot +``` -> **C1 note**: `LowHoldingsCount` alert evaluation in `LowHoldingsHandler` must join `Trade` ledger filtered by **both** `UserId` AND `TickerSymbol` to compute the correct per-user net holdings. Never evaluate holdings across all users. +> **Startup order enforced by `depends_on`:** +> `db` + `redis` + `moto` (healthchecks) → `moto-init` (completed) → `api` + `worker` + +### Worker Dockerfile + +Located at `InventoryAlert.Worker/Dockerfile`. Uses `dotnet/runtime:10.0` +(not `aspnet`) since the Worker has no HTTP listener. --- -### 5.7 Events — `/api/v1/events` `[Admin]` +## ✅ Implementation Checklist -**POST `/`** -- **Request**: `{ EventType: string, Payload: object }` -- **202 Accepted**: `{ MessageId: string, Status: ""Queued"" }` +### Phase A — Contracts & Infrastructure -**GET `/types`** -- **200 OK**: `[ ""inventoryalert.pricing.price-drop.v1"", ""inventoryalert.inventory.stock-low.v1"", ""inventoryalert.news.headline.v1"" ]` +- [x] Create `InventoryAlert.Contracts` project +- [x] Define `EventEnvelope` record +- [x] Define all Payload records (Price, Earnings, Insider, News, StockLow) +- [x] Add Contracts reference to Api, Worker, and Sample projects ---- +### Phase B — API (Publisher Side) -## 6. Error Handling +- [x] Create `IEventPublisher` interface +- [x] Implement `SnsEventPublisher` (using AWSSDK.SQS/SNS pointing to Moto) +- [x] Create `EventLog` entity + EF Migration +- [x] Create `EventsController` with POST endpoints +- [x] Register `IEventPublisher` in DI -### Standard Error Response +### Phase C — Worker Project -```json -{ - ""errorCode"": ""string"", - ""userFriendlyMessage"": ""string"", - ""message"": ""string (technical detail — omitted in production)"" -} -``` +- [x] Create `InventoryAlert.Worker` as a Worker Service +- [x] Install Hangfire + `Hangfire.PostgreSql` +- [x] Add Worker to `docker-compose.yml` (with Dockerfile + appsettings.Docker.json) +- [x] Moto init script: `SolutionFolder/moto-init/init-sqs.sh` creates SNS + SQS +- [x] Create `PollSqsJob` — SQS dequeue + event routing +- [x] Create `SyncPricesJob` — replaces current `FinnhubSyncWorker` +- [x] Create `EarningsCheckJob` — calls `/stock/earnings` +- [x] Create `InsiderTxCheckJob` — calls `/stock/insider-transactions` +- [x] Create `NewsCheckJob` — calls `/company-news` +- [x] Implement Redis caching inside each job +- [x] Add Worker to `docker-compose.yml` -### HTTP Status Code Reference +### Phase D — Event Handlers (inside Worker) -| Code | HTTP Status | Description | -| :--- | :--- | :--- | -| `NotFound` | 404 | Resource (symbol, rule, position) does not exist. | -| `Conflict` | 409 | Duplicate create or locked state conflict. | -| `BadRequest` | 400 | Validation failed or malformed body. | -| `Unauthorized` | 401 | Missing or invalid JWT. | -| `Forbidden` | 403 | Authenticated but lacks ownership of resource. | -| `UnprocessableEntity` | 422 | Semantic error (e.g., negative quantity, bad ticker). | -| `TooManyRequests` | 429 | Rate limit exceeded (login endpoint). | -| `Internal` | 500 | Unhandled server error. | +- [x] `PriceAlertHandler` → log + trigger Telegram notification +- [x] `EarningsHandler` → persist `EarningsRecord` to DB +- [x] `InsiderHandler` → persist `InsiderTransaction` to DB +- [x] `NewsHandler` → persist `NewsRecord` to DB ---- +### Phase E — Sample Publisher -## 7. Scheduled Job Catalog Summary +- [x] Create `InventoryAlert.Sample` console app +- [x] Implement HTTP client posting to `/api/events` +- [x] Implement direct-to-Moto-SQS publisher (bypass API) +- [x] Add interactive menu with all event types -| Job | Schedule | Tables Affected | Finnhub Source | -| :--- | :--- | :--- | :--- | -| `SyncPricesJob` | `*/15 * * * *` | `PriceHistory`, evaluates `AlertRule` | `/quote` | -| `SyncMetricsJob` | `0 6 * * *` | `StockMetric` | `/stock/metric` | -| `SyncEarningsJob` | `0 7 * * *` | `EarningsSurprise` | `/stock/earnings` | -| `SyncRecommendationsJob` | `0 8 * * 1` | `RecommendationTrend` | `/stock/recommendation` | -| `SyncInsidersJob` | `0 8 * * *` | `InsiderTransaction` | `/stock/insider-transactions` | -| `CompanyNewsJob` | `0 */6 * * *` | DynamoDB `CompanyNews` | `/company-news` | -| `MarketNewsJob` | `0 */2 * * *` | DynamoDB `MarketNews` | `/news` | -| `ProcessQueueJob` | Continuous | — | SQS consumer | -| `SqsScheduledPollerJob` | `*/5 * * * *` | — | SQS fallback | -| `CleanupPriceHistoryJob` | `@daily` (00:00 UTC) | `PriceHistory` (DELETE) | — | +### Phase F — Telegram Integration -> **D4 — CleanupPriceHistoryJob**: Deletes `PriceHistory` rows where `RecordedAt < NOW() - INTERVAL '1 year'`. Prevents unbounded table growth (est. 35M+ rows/year at 1,000 symbols). Uses a batched delete (`DELETE ... WHERE id IN (SELECT id ... LIMIT 10000)`) to avoid lock contention. +- [x] Create `TelegramAlertNotifier` implementing `IAlertNotifier` +- [x] Add `Telegram:BotToken` and `Telegram:ChatId` to AppSettings +- [x] Register notifier in DI (replaced `ConsoleAlertNotifier` in API) +- [x] Add `TELEGRAM_BOT_TOKEN` to `appsettings.Example.json` --- -## 8. SQS Event Handler Catalog +### Phase G — Shared Entity Migration ✅ -| Event Type | Payload | Handler | Logic | -| :--- | :--- | :--- | :--- | -| `inventoryalert.pricing.price-drop.v1` | `{ Symbol }` | `PriceAlertHandler` | Quote → cache → `PriceHistory` → evaluate all `AlertRule` for symbol. | -| `inventoryalert.inventory.stock-low.v1` | `{ UserId, TickerSymbol, Threshold }` | `LowHoldingsHandler` | Verify `Trade` ledger count → check `AlertRule[LowHoldingsCount]` → notify if breached. | -| `inventoryalert.news.headline.v1` | `{ Symbol }` | `CompanyNewsHandler` | Sync company news → DynamoDB `CompanyNews`. | -| `*` (unmatched) | — | `DefaultHandler` | Log + acknowledge. Prevents poison-message blockage. | +> Moved all domain entities shared between API and Worker out of `InventoryAlert.Api.Domain.Entities` +> into `InventoryAlert.Contracts.Entities` — single source of truth. + +- [x] `Product` → `InventoryAlert.Contracts.Entities.Product` +- [x] `EventLog` → `InventoryAlert.Contracts.Entities.EventLog` +- [x] `EarningsRecord` → `InventoryAlert.Contracts.Entities.EarningsRecord` +- [x] `InsiderTransaction` → `InventoryAlert.Contracts.Entities.InsiderTransaction` +- [x] `NewsRecord` → `InventoryAlert.Contracts.Entities.NewsRecord` +- [x] All `using` statements updated in Api, Worker, and Tests projects +- [x] `AWSSDK.SimpleNotificationService` + `AWSSDK.SQS` installed in `InventoryAlert.Sample` +- [x] Full solution build: **0 errors** ✅ +- [x] Full test run: **61/61 passed** ✅ + +**EF Configuration strategy:** Each service keeps its own `DbContext` with inline EF fluent configs. +`Contracts` remains a plain POCO library with no EF dependency — clean separation. --- -## 9. UI Plan +> **Priority Order:** A → B → C → D → E → F → G +> +> The existing `FinnhubSyncWorker` in the API has been **retired** — `SyncPricesJob` in the Worker now owns all background price sync logic.",462,9cafce7131c0795ccf372d438924aec0,doc\archive\EVENT_DRIVEN_PLAN.md,0,293,"worker, inventoryalert, event, contracts, events, news, create, project",1779851803.9172883,1,postgresql times once fluentassertions productscontroller finnhubpricesyncworker xunit container database update iproductservice sku quote stock price unit test price drop inventory productservice efcore dbcontext hosted service commit add-migration unitofwork atomicity compose periodictimer moq postgres savechanges entity framework iactionresult httppost item threshold application service efcore migration mock setup schema change appdbcontext asnotracking httpget business logic external api backgroundservice verify httpput market data returns async notification stock arrange act assert rollback loss dockerfile,# 🏗️ Event-Driven Architecture Plan | 🏗️ Event-Driven Architecture Plan Hangfire + SNS/SQS + Redis + Multi-Project Sy +doc,"# 🛠️ Project Setup — Names & Commands -> **Stack**: Next.js (App Router) + TypeScript + Tailwind CSS. State: React Query (server state) + Zustand (UI state). Charts: Recharts. +> Run all commands from inside `InventoryManagementSystem/` +> unless stated otherwise. --- -### 9.1 Page Inventory +## 📁 Final Project Names -| Route | Page Name | Auth | Description | -| :--- | :--- | :--- | :--- | -| `/login` | Login | Public | JWT authentication form. | -| `/register` | Register | Public | New account creation. | -| `/dashboard` | Dashboard | ✅ | Overview: portfolio summary card, watchlist strip, market status, top news. | -| `/portfolio` | Portfolio | ✅ | Full paginated position list with search/filter. | -| `/portfolio/[id]` | Position Detail | ✅ | Deep-dive: price chart, trade history, alert rules for one position. | -| `/stocks` | Stocks Catalog | ✅ | Browse/search global `StockListing` catalog with filters. | -| `/stocks/[symbol]` | Stock Detail | ✅ | Quote, profile, financials, earnings chart, recommendation gauge, insider table, news, peers. | -| `/watchlist` | Watchlist | ✅ | Live watchlist with quick-add via symbol search. | -| `/alerts` | Alert Rules | ✅ | CRUD interface for all user alert rules with active/inactive toggle. | -| `/market` | Market Overview | ✅ | Exchange status, market news feed, earnings calendar, IPO calendar. | +| Project | Type | Purpose | +| :------------------------- | :-------------- | :---------------------------------------------- | +| `InventoryAlert.Api` | ASP.NET Web API | ✅ Existing — extended with event endpoints | +| `InventoryAlert.Contracts` | Class Library | ✅ Done — shared event schemas + domain entities | +| `InventoryAlert.Worker` | Worker Service | ✅ Done — Hangfire + SQS consumer | +| `InventoryAlert.Sample` | Console App | ✅ Done — sample event publisher | +| `InventoryAlert.Tests` | xUnit Test | ✅ Existing | --- -### 9.2 Shared Component Library +## ⚡ Step 1 — Create New Projects -#### Navigation +```powershell +cd InventoryManagementSystem",24,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,294,"inventoryalert, project, event, done, names, commands, inventorymanagementsystem, existing",1779851803.874752,1,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# 🛠️ Project Setup — Names & Commands | 🛠️ Project Setup — Names & Commands > Run all commands from inside InventoryMana +doc,"# 1. Shared contracts (event schemas) +dotnet new classlib -n InventoryAlert.Contracts -o InventoryAlert.Contracts",27,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,295,"contracts, inventoryalert, shared, event, schemas, dotnet, classlib",1779851803.874752,25,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# 1. Shared contracts (event schemas) | 1 +doc,"# 2. Background worker (Hangfire + SQS) +dotnet new worker -n InventoryAlert.Worker -o InventoryAlert.Worker",30,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,296,"worker, inventoryalert, background, hangfire, dotnet",1779851803.874752,28,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# 2. Background worker (Hangfire + SQS) | 2 +doc,"# 3. Sample publisher CLI +dotnet new console -n InventoryAlert.Sample -o InventoryAlert.Sample +``` -| Component | Location | Description | -| :--- | :--- | :--- | -| `Navbar` | Layout | Top bar: logo, nav links, user avatar menu, notification bell, search bar trigger. | -| `Sidebar` | Layout (desktop) | Collapsible left nav: Dashboard, Portfolio, Watchlist, Stocks, Alerts, Market. | -| `MarketStatusBanner` | Layout (top) | Color-coded strip: exchange name + open/closed state. Polls `GET /market/status` every 60s. | -| `GlobalSearch` | Navbar | Cmd+K search modal. Uses DB-first symbol discovery flow. Shows results as user types (debounce 300ms). | +--- -#### Market Data Widgets +## ⚡ Step 2 — Add to Solution -| Component | Used On | API | Description | -| :--- | :--- | :--- | :--- | -| `StockQuoteCard` | Dashboard, Stock Detail, Watchlist | `GET /stocks/{symbol}/quote` | Price, change, change%, high, low. Refreshes every 30s. | -| `PriceLineChart` | Portfolio Detail, Stock Detail | `PriceHistory` (local) | Recharts `AreaChart`. Supports 1D / 1W / 1M / 3M / 1Y range selector. | -| `EarningsBarChart` | Stock Detail | `GET /stocks/{symbol}/earnings` | Grouped bar: actual vs. estimate EPS per quarter. Color-coded surprise (green/red). | -| `RecommendationDonut` | Stock Detail | `GET /stocks/{symbol}/recommendation` | Recharts `PieChart` — Strong Buy / Buy / Hold / Sell / Strong Sell slices. | -| `MetricsPanel` | Stock Detail | `GET /stocks/{symbol}/financials` | Grid of KPI chips: P/E, P/B, EPS, DividendYield, 52w High/Low, Revenue Growth, Net Margin. | -| `InsiderTable` | Stock Detail | `GET /stocks/{symbol}/insiders` | Sortable table: Name, Date, Shares, Value, Code badge. | -| `PeersChipRow` | Stock Detail | `GET /stocks/{symbol}/peers` | Clickable symbol chips. Click navigates to `/stocks/[symbol]`. | -| `StockProfileHeader` | Stock Detail | `GET /stocks/{symbol}/profile` | Logo + name + exchange + industry + website link + market cap. | +```powershell +dotnet sln add InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +dotnet sln add InventoryAlert.Worker/InventoryAlert.Worker.csproj +dotnet sln add InventoryAlert.Sample/InventoryAlert.Sample.csproj +``` -#### Portfolio Components +--- -| Component | Used On | API | Description | -| :--- | :--- | :--- | :--- | -| `PortfolioSummaryCard` | Dashboard, Portfolio | `GET /portfolio/` | Net portfolio value, total return ($ + %), day P&L, positions count. | -| `PositionTable` | Portfolio | `GET /portfolio/` (paged) | Sortable, searchable table of open positions. Columns: Symbol, Holdings, Avg Price, Current Price, Market Value, Return %, Alert Badge. | -| `PositionRow` | Portfolio | — | Single row of `PositionTable`. Inline sparkline mini-chart. | -| `PositionDetailPanel` | Portfolio Detail | `GET /portfolio/{id}` | Full position breakdown: cost basis, unrealized P&L, trade history timeline. | -| `TradeModal` | Portfolio, Portfolio Detail | `PATCH /portfolio/{id}/trade` | Modal form: Type (Buy/Sell/Dividend/Split), Quantity, Unit Price, Notes, Date. | -| `AddPositionModal` | Portfolio | `POST /portfolio/` | Symbol search (uses discovery flow) → quantity/price form → submit. | -| `BulkImportModal` | Portfolio | `POST /portfolio/bulk` | CSV drag-and-drop → preview table → confirm import with error summary. | -| `AlertBadge` | PositionRow, PositionDetail | `GET /portfolio/alerts` | Red badge on positions that have breached their `AlertRule`. | +## ⚡ Step 3 — Add Project References -#### Watchlist Components +### `InventoryAlert.Api` references `Contracts` -| Component | Used On | API | Description | -| :--- | :--- | :--- | :--- | -| `WatchlistCard` | Watchlist | `GET /watchlist/` | Compact card: logo, symbol, price, day change%, add-to-portfolio button. | -| `WatchlistAddBar` | Watchlist | `POST /watchlist/{symbol}` | Inline symbol search input. Uses DB-first discovery. Pins new item on success. | -| `WatchlistEmptyState` | Watchlist | — | Illustrated empty state with a CTA to search for stocks. | +```powershell +dotnet add InventoryAlert.Api/InventoryAlert.Api.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +``` -#### Alert Rule Components +### `InventoryAlert.Worker` references `Contracts` -| Component | Used On | API | Description | -| :--- | :--- | :--- | :--- | -| `AlertRuleTable` | Alerts | `GET /alerts/` | Full list of rules. Columns: Symbol, Condition, Target, Status, Last Triggered, Actions. | -| `AlertRuleForm` | Alerts, Portfolio Detail | `POST /alerts/`, `PUT /alerts/{id}` | Symbol search → Condition dropdown → Target value input → TriggerOnce checkbox. | -| `AlertToggle` | AlertRuleTable | `PATCH /alerts/{ruleId}/toggle` | Inline toggle switch. Optimistic UI update. | +```powershell +dotnet add InventoryAlert.Worker/InventoryAlert.Worker.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +``` -#### Market Overview Components +### `InventoryAlert.Sample` references `Contracts` -| Component | Used On | API | Description | -| :--- | :--- | :--- | :--- | -| `NewsFeedCard` | Dashboard, Market | `GET /market/news`, `GET /stocks/{symbol}/news` | Headline, source, timestamp, image thumbnail. Links to original article. | -| `NewsFeed` | Dashboard, Market, Stock Detail | — | Virtualised scrollable list of `NewsFeedCard`. Supports category filter tabs. | -| `EarningsCalendarTable` | Market | `GET /market/calendar/earnings` | Date-grouped table: Symbol, EPS Estimate, EPS Actual (colour-coded post-release). | -| `IpoCalendarTable` | Market | `GET /market/calendar/ipo` | Upcoming IPOs: Symbol, Name, Price Range, Date, Status badge. | -| `HolidayList` | Market | `GET /market/holiday` | Exchange selector dropdown → sorted list of upcoming market holidays. | -| `ExchangeStatusGrid` | Dashboard, Market | `GET /market/status` | Grid of exchange cards (NYSE, NASDAQ, LSE…): open/closed indicator + local time. | +```powershell +dotnet add InventoryAlert.Sample/InventoryAlert.Sample.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +``` --- -### 9.3 Page-Level API Map +## ⚡ Step 4 — Install NuGet Packages -#### Dashboard (`/dashboard`) +### `InventoryAlert.Api` — Event publishing -``` -GET /portfolio/ → PortfolioSummaryCard (aggregate values) -GET /watchlist/ → WatchlistStrip (first 5 items) -GET /market/status → MarketStatusBanner + ExchangeStatusGrid -GET /market/news?category=general&page=1 → NewsFeed (top 10) -GET /portfolio/alerts → AlertBadge counts in summary +```powershell",73,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,297,"inventoryalert, csproj, contracts, sample, dotnet, powershell, worker, reference",1779851803.874752,31,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# 3. Sample publisher CLI | 3 +doc,"# AWS SNS publisher (talks to Moto at localhost:5000) +dotnet add InventoryAlert.Api package AWSSDK.SimpleNotificationService +dotnet add InventoryAlert.Api package AWSSDK.SQS ``` -#### Portfolio (`/portfolio`) +### `InventoryAlert.Worker` — Hangfire + SQS consumer + Redis + DB +```powershell",81,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,298,"dotnet, inventoryalert, package, awssdk, publisher, talks, moto, localhost",1779851803.874752,74,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# AWS SNS publisher (talks to Moto at localhost:5000) | AWS SNS publisher (talks to Moto at localhost:5000) dotnet add InventoryAlert.Ap +doc,"# Hangfire core +dotnet add InventoryAlert.Worker package Hangfire.AspNetCore +dotnet add InventoryAlert.Worker package Hangfire.PostgreSql",85,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,299,"hangfire, dotnet, inventoryalert, worker, package, core, aspnetcore, postgresql",1779851803.874752,82,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# Hangfire core | Hangfire core dotnet add InventoryAlert.Worker package Hangfire.AspNetCore dotne +doc,"# SQS consumer +dotnet add InventoryAlert.Worker package AWSSDK.SQS",88,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,300,"consumer, dotnet, inventoryalert, worker, package, awssdk",1779851803.874752,86,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# SQS consumer | SQS consumer dotnet add InventoryAlert.Worker package AWSSDK.SQS +doc,"# Redis caching +dotnet add InventoryAlert.Worker package Microsoft.Extensions.Caching.StackExchangeRedis",91,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,301,"caching, redis, dotnet, inventoryalert, worker, package, microsoft, extensions",1779851803.874752,89,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# Redis caching | Redis caching dotnet add InventoryAlert.Worker package Microsoft.Extensions.Cach +doc,"# EF Core (share same DB) +dotnet add InventoryAlert.Worker package Npgsql.EntityFrameworkCore.PostgreSQL +dotnet add InventoryAlert.Worker package Microsoft.EntityFrameworkCore.Design",95,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,302,"dotnet, inventoryalert, worker, package, entityframeworkcore, core, share, same",1779851803.874752,92,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# EF Core (share same DB) | EF Core (share same DB) dotnet add InventoryAlert.Worker package Npgsql.EntityFr +doc,"# HTTP client (for Finnhub calls) +dotnet add InventoryAlert.Worker package RestSharp ``` -GET /portfolio/?page=&search= → PositionTable (paged) -GET /portfolio/alerts → AlertBadge overlay per row -PATCH /portfolio/{id}/trade → TradeModal submit -POST /portfolio/ → AddPositionModal submit (after symbol discovery) -POST /portfolio/bulk → BulkImportModal submit -DELETE /portfolio/{id} → Confirm delete → reload table + +### `InventoryAlert.Worker` — DynamoDB (Future Enterprise Extension) + +> **⚠️ Optional:** Only install when migrating from Postgres `EventLog` and Redis dedup +> to the polyglot DynamoDB strategy described in `EVENT_DRIVEN_PLAN.md`. + +```powershell",105,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,303,"http, client, finnhub, calls, dotnet, inventoryalert, worker, package",1779851803.874752,96,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# HTTP client (for Finnhub calls) | HTTP client (for Finnhub calls) dotnet add InventoryAlert.Worker package RestSha +doc,"# DynamoDB client + object persistence model +dotnet add InventoryAlert.Worker package AWSSDK.DynamoDBv2 ``` -#### Position Detail (`/portfolio/[id]`) +### `InventoryAlert.Sample` — HTTP client to call the API +```powershell +dotnet add InventoryAlert.Sample package Microsoft.Extensions.Http ``` -GET /portfolio/{id} → PositionDetailPanel + header -GET /stocks/{symbol}/quote → StockQuoteCard (live price) -[local PriceHistory data] → PriceLineChart (from API response) -GET /alerts/?symbol= → AlertRuleTable (scoped to position) -PATCH /portfolio/{id}/trade → TradeModal -POST /alerts/ → AlertRuleForm (create for this position) -``` - -#### Stock Detail (`/stocks/[symbol]`) -``` -GET /stocks/{symbol}/quote → StockQuoteCard -GET /stocks/{symbol}/profile → StockProfileHeader -GET /stocks/{symbol}/financials → MetricsPanel -GET /stocks/{symbol}/earnings → EarningsBarChart -GET /stocks/{symbol}/recommendation → RecommendationDonut -GET /stocks/{symbol}/insiders → InsiderTable -GET /stocks/{symbol}/peers → PeersChipRow -GET /stocks/{symbol}/news → NewsFeed (company-scoped) -[PriceHistory from quote response] → PriceLineChart -``` +--- -#### Market (`/market`) +## ⚡ Step 5 — Verify Solution Builds -``` -GET /market/status → ExchangeStatusGrid -GET /market/news?category=&page= → NewsFeed (paginated, filterable) -GET /market/calendar/earnings → EarningsCalendarTable -GET /market/calendar/ipo → IpoCalendarTable -GET /market/holiday?exchange= → HolidayList +```powershell +dotnet build InventoryManagementSystem.sln ``` --- -### 9.4 Key User Flows - -#### Flow 1: Add Stock to Portfolio (Symbol Not Yet in DB) +## ⚙️ Step 6 — Environment Variables Needed -```mermaid -sequenceDiagram - actor User - participant UI as Frontend - participant API as InventoryAlert.Api - participant DB as PostgreSQL - participant FH as Finnhub +Add these to your `.env` file (and `.env.example`): - User->>UI: Types ""NVDA"" in AddPositionModal search - UI->>API: GET /stocks/search?q=NVDA - API->>DB: SELECT FROM StockListing WHERE TickerSymbol ILIKE 'NVDA' - DB-->>API: 0 rows - API->>FH: GET /stock/profile2?symbol=NVDA - FH-->>API: Company profile data - API->>DB: INSERT INTO StockListing (NVDA data) - API-->>UI: SymbolSearchResponse (NVDA) - UI->>User: Shows NVDA in results - User->>UI: Selects NVDA, enters Quantity + Price, submits - UI->>API: POST /portfolio/ { TickerSymbol: NVDA, ... } - API-->>UI: 201 PortfolioPositionResponse - UI->>User: Position added. Navigate to /portfolio +```env",130,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,304,"dotnet, inventoryalert, package, powershell, dynamodb, client, object, persistence",1779851803.874752,106,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# DynamoDB client + object persistence model | DynamoDB client + object persistence model dotnet add InventoryAlert.Worker pack +doc,"# Existing +DB_PASSWORD=password +FINNHUB_API_KEY=your_key_here",134,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,305,"existing, password",1779851803.874752,131,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# Existing | Existing DB_PASSWORD=password FINNHUB_API_KEY=your_key_here +doc,"# New — AWS / Moto +AWS_ACCESS_KEY_ID=test +AWS_SECRET_ACCESS_KEY=test +AWS_DEFAULT_REGION=us-east-1 +AWS_ENDPOINT_URL=http://moto:5000 # inside Docker",139,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,306,"moto, test, east, http, inside, docker",1779851803.874752,135,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# New — AWS / Moto | New — AWS / Moto AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_R +doc,# AWS_ENDPOINT_URL=http://localhost:5000 # from host machine,141,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,307,"http, localhost, from, host, machine",1779851803.874752,140,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# AWS_ENDPOINT_URL=http://localhost:5000 # from host machine | AWS_ENDPOINT_URL=http://localhost:5000 from host machine +doc,"# New — SNS/SQS resource names (Moto will create these on startup) +SNS_TOPIC_ARN=arn:aws:sns:us-east-1:123456789012:inventory-events +SQS_QUEUE_URL=http://moto:5000/123456789012/event-queue",145,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,308,"moto, resource, names, will, create, these, startup, east",1779851803.874752,142,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# New — SNS/SQS resource names (Moto will create these on startup) | New — SNS/SQS resource names (Moto will create these on startup) SNS_TOPIC_ARN=a +doc,"# New — Redis +REDIS_CONNECTION=redis:6379 # inside Docker",147,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,309,"redis, inside, docker",1779851803.874752,146,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# New — Redis | New — Redis REDIS_CONNECTION=redis:6379 inside Docker +doc,# REDIS_CONNECTION=localhost:6379 # from host machine,149,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,310,"localhost, from, host, machine",1779851803.874752,148,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# REDIS_CONNECTION=localhost:6379 # from host machine | REDIS_CONNECTION=localhost:6379 from host machine +doc,"# Future — Telegram +TELEGRAM_BOT_TOKEN=your_bot_token_here +TELEGRAM_CHAT_ID=your_chat_id_here ``` -#### Flow 2: Alert Trigger (Price Drop) - -```mermaid -sequenceDiagram - participant Hangfire as SyncPricesJob (15 min) - participant API as InventoryAlert.Api - participant DB as PostgreSQL - participant SQS as AWS SQS - participant Redis as Redis (cooldown) - participant Handler as PriceAlertHandler - participant UI as Frontend +> **Note:** Moto accepts any value for `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`. +> Use `test` / `test` locally — it works without real credentials. - Hangfire->>API: Execute SyncPricesJob - API->>DB: SELECT all TickerSymbols from StockListing - loop For each symbol - API->>Finnhub: GET /quote - API->>DB: INSERT INTO PriceHistory - API->>DB: Check AlertRule for this symbol - alt Rule breached - API->>Redis: Check cooldown key (24h window) - Redis-->>API: Not in cooldown - API->>SQS: Publish inventoryalert.pricing.price-drop.v1 - end - end - SQS->>Handler: Consume event - Handler->>Redis: SET cooldown key (24h TTL) - Handler-->>UI: Push notification to user -``` +--- -#### Flow 3: Global Symbol Search (Navbar) +## 🐳 Step 7 — Add Worker to `docker-compose.yml` -```mermaid -flowchart LR - A([User types in GlobalSearch]) --> B[Debounce 300ms] - B --> C[GET /stocks/search?q=query] - C --> D{DB hit?} - D -- Yes --> E([Render results from DB]) - D -- No → Finnhub --> F{Finnhub has it?} - F -- Yes --> G[Persist to StockListing] - G --> E - F -- No --> H([Show: No results found]) - E --> I{User clicks result} - I --> J([Navigate to /stocks/symbol]) +```yaml +worker: + build: + context: . + dockerfile: InventoryAlert.Worker/Dockerfile + container_name: inventory_worker + environment: + - ASPNETCORE_ENVIRONMENT=Docker + - Database__DefaultConnection=host=db;port=5432;Database=InventoryAlertDb;Username=postgres;Password=password + - Redis__Connection=redis:6379 + - Aws__EndpointUrl=http://moto:5000 + - Aws__SnsTopicArn=arn:aws:sns:us-east-1:123456789012:inventory-events + - Aws__SqsQueueUrl=http://moto:5000/123456789012/event-queue + depends_on: + db: + condition: service_healthy + networks: + - app-network + restart: unless-stopped ``` --- -### 9.5 State Management Strategy +## ✅ Quick Checklist -| Concern | Tool | Rationale | -| :--- | :--- | :--- | -| Server data (quotes, portfolio, news) | React Query | Auto-refresh, stale-while-revalidate, cache invalidation on mutations. | -| UI state (modals, selected tab, filters) | Zustand | Lightweight, no boilerplate, easy DevTools. | -| Auth token | `httpOnly` cookie | Secure; never exposed to `localStorage`. | -| Optimistic updates | React Query `onMutate` | Used for alert toggles, watchlist add/remove — feels instant. | -| Quote polling | React Query `refetchInterval: 30_000` | Only active when tab is visible (`refetchIntervalInBackground: false`). | +``` +[✅] dotnet new classlib → InventoryAlert.Contracts ✅ Done +[✅] dotnet new worker → InventoryAlert.Worker ✅ Done +[✅] dotnet new console → InventoryAlert.Sample ✅ Done +[✅] dotnet sln add → 3 projects added to .sln ✅ Done +[✅] dotnet add reference → Contracts in Api + Worker + Sample ✅ Done +[✅] dotnet add package → All NuGet packages installed ✅ Done + - Api: AWSSDK.SNS + SQS + Serilog + FluentValidation + - Worker: Hangfire + SQS + Redis + EF + RestSharp + - Sample: AWSSDK.SNS + SQS + Microsoft.Extensions.Http +[✅] Entities migrated → Contracts/Entities/ folder ✅ Done + (Product, EventLog, EarningsRecord, InsiderTransaction, NewsRecord) +[✅] .env → AWS + Redis keys added ✅ Done +[✅] docker-compose.yml → Worker service added ✅ Done +[✅] dotnet build → Full solution compiles ✅ Done +[✅] dotnet test → 61/61 tests pass ✅ Done +```",203,48b6f30defd95f4b73be8838db71b12a,doc\archive\EVENT_SETUP_COMMANDS.md,0,311,"done, dotnet, worker, inventoryalert, redis, http, contracts, sample",1779851803.874752,150,item entity framework notification loss efcore hosted service unit test atomicity price drop savechanges business logic container finnhubpricesyncworker stock postgresql unitofwork rollback postgres stock price market data iproductservice sku productservice appdbcontext periodictimer dockerfile commit inventory dbcontext external api compose quote fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,# Future — Telegram | Future — Telegram TELEGRAM_BOT_TOKEN=your_bot_token_here TELEGRAM_CHAT_ID=your_c +doc,"--- +description: Business capabilities, REST API reference, and workflows for the Inventory Alert System. +type: reference +status: active +version: 2.0 +tags: [business, features, api, workflows, reference] +last_updated: 2026-04-05 +---",9,51a503b6410630f3c5b56f98bc5b895a,doc\archive\FEATURES_OVERVIEW.md,0,312,"reference, business, workflows, description, capabilities, rest, inventory, alert",1775670503.9164877,1,external api appdbcontext atomicity compose postgres stock price httpget httppost fluentassertions quote unitofwork postgresql commit container business logic xunit data access iactionresult periodictimer msft market data dockerfile price drop arrange act assert entity framework productservice rollback notification inventory finnhubpricesyncworker backgroundservice asnotracking httpput iproductservice googl threshold dbset productscontroller sku stock hosted service stock ticker savechanges iproductrepository loss item symbol dbcontext efcore unit test aapl igenericrepository application service,"FEATURES_OVERVIEW.md | --- description: Business capabilities, REST API reference, and workflows for th" +doc,"# 🛒 Inventory Alert System — Features & API Reference + +> This document covers **business capabilities, API endpoints, and user-facing workflows**. +> For system architecture, Docker setup, and project internals, see [`PROJECT_OVERVIEW.md`](PROJECT_OVERVIEW.md). --- -## 10. Request Validation +## 🔐 0. Authentication -> All validation is enforced at the **Web layer** using `FluentValidation`. The Application layer trusts that inputs have already been validated. Controllers must not contain inline `if` checks. +All `ProductsController` endpoints require a valid **JWT Bearer token**. -### 10.1 Validation Rules by DTO +### Login +``` +POST /api/auth/login +Body: { ""username"": ""admin"", ""password"": ""admin123"" } +→ 200 OK: { ""token"": """" } +→ 401 Unauthorized +``` -#### `LoginRequest` +- Tokens are **HmacSha256-signed**, expire after **2 hours** +- Include in subsequent requests: `Authorization: Bearer ` +- Credentials configured in `appsettings.json → Auth:Username / Auth:Password` +- `EventsController` endpoints are **unauthenticated** (internal/service-to-service) -| Field | Rule | -| :--- | :--- | -| `Username` | `NotEmpty`. `MaxLength(50)`. | -| `Password` | `NotEmpty`. `MinLength(6)`. `MaxLength(100)`. | +--- -#### `RegisterRequest` +## 📦 1. Product Inventory Management -| Field | Rule | -| :--- | :--- | -| `Username` | `NotEmpty`. `MaxLength(50)`. `Matches(^[a-zA-Z0-9_]+$)` — alphanumeric + underscore only. | -| `Password` | `NotEmpty`. `MinLength(8)`. Must contain at least 1 uppercase, 1 digit, 1 special character. | -| `Email` | `NotEmpty`. `EmailAddress()`. `MaxLength(200)`. | +**Business Goal:** Centralized catalog for warehouse staff to manage product metadata, pricing baselines, and stock thresholds. -#### `CreatePositionRequest` +### The `Product` Entity -| Field | Rule | -| :--- | :--- | -| `TickerSymbol` | `NotEmpty`. `MaxLength(10)`. `Matches(^[A-Z0-9.]+$)` — uppercase ticker format. | -| `Quantity` | `GreaterThan(0)`. No fractional shares below 0.001. | -| `UnitPrice` | `GreaterThan(0)`. `LessThan(1_000_000)`. | -| `TradedAt` | Optional. If provided: `LessThanOrEqualTo(DateTime.UtcNow)`. Cannot be in the future. | +| Field | Type | Purpose | +|---|---|---| +| `Id` | `int` | Primary key | +| `Name` | `string` | Human-readable product name | +| `TickerSymbol` | `string` | NYSE/NASDAQ ticker (e.g. `AAPL`) — links to Finnhub | +| `OriginPrice` | `decimal` | Baseline purchase price — **never changes automatically** | +| `CurrentPrice` | `decimal` | Latest price synced from Finnhub | +| `PriceAlertThreshold` | `double` | e.g. `0.2` = alert when price drops >20% from origin | +| `StockCount` | `int` | Current physical unit count | +| `StockAlertThreshold` | `int` | Alert threshold for low-stock events | +| `LastAlertSentAt` | `DateTime?` | Cooldown gate — prevents duplicate alert spam | -#### `TradeRequest` +### Endpoints -| Field | Rule | -| :--- | :--- | -| `Type` | `NotNull`. Must be a valid `TradeType` enum value. | -| `Quantity` | `GreaterThan(0)`. For `Sell`: service validates resulting holdings ≥ 0 (422). | -| `UnitPrice` | `GreaterThan(0)`. Required for `Buy`/`Sell`. Optional (set 0) for `Dividend`/`Split`. | -| `Notes` | Optional. `MaxLength(500)`. | +| Method | Route | Handler | Response | +|---|---|---|---| +| `GET` | `/api/products` | `GetProducts([FromQuery] PaginationParams)` | `200 PagedResult` | +| `GET` | `/api/products/{id}` | `GetProductById(int id)` | `200 ProductResponse` / `404` | +| `POST` | `/api/products` | `CreateProduct(ProductRequest)` | `201 ProductResponse` | +| `PUT` | `/api/products/{id}` | `UpdateProduct(int id, ProductRequest)` | `200 ProductResponse` / `404` | +| `PATCH` | `/api/products/{id}/stock?stockCount={n}` | `UpdateStockCount(int id, int stockCount)` | `200 ProductResponse` / `404` | +| `DELETE` | `/api/products/{id}` | `DeleteProduct(int id)` | `204 No Content` / `404` | +| `POST` | `/api/products/bulk` | `BulkInsertProducts(IEnumerable)` | `204 No Content` | +| `GET` | `/api/products/price-alerts` | `GetPriceLossAlerts()` | `200 IEnumerable` | +| `POST` | `/api/products/sync-price` | `SyncStockPrice()` | `204 No Content` | -#### `AlertRuleRequest` +### Pagination +`GET /api/products` accepts `?pageNumber=1&pageSize=20` and returns: +```json +{ + ""items"": [...], + ""totalItems"": 150, + ""pageNumber"": 1, + ""pageSize"": 20 +} +``` -| Field | Rule | -| :--- | :--- | -| `TickerSymbol` | `NotEmpty`. `MaxLength(10)`. | -| `Condition` | `NotNull`. Must be valid `AlertCondition` enum. | -| `TargetValue` | `GreaterThan(0)`. For `LowHoldingsCount`: must be a whole number (no decimals). | -| `TriggerOnce` | Required boolean. | +### Single-Item Cache +`GetProductByIdAsync` uses **`IMemoryCache`** with key `""Product_{id}""` and a **10-minute sliding TTL**. +`UpdateProductAsync`, `UpdateStockCountAsync`, and `DeleteProductAsync` all call `_cache.Remove($""Product_{id}"")` to invalidate immediately. -#### `AlertRuleRequest` — Condition-Specific Cross-Field Rules +### Bulk Insert +`POST /api/products/bulk` accepts a JSON array of `ProductRequest`. Runs the entire insert inside `ExecuteTransactionAsync` — all-or-nothing. Returns `204` with no body to minimize bandwidth on large payloads. -| Condition | Extra Validation | -| :--- | :--- | -| `PriceAbove`, `PriceBelow`, `PriceTargetReached` | `TargetValue` must be a monetary value > 0. | -| `PercentDropFromCost` | `TargetValue` must be between `0.01` and `100.00`. | -| `LowHoldingsCount` | `TargetValue` must be a positive integer (whole number). | +--- -### 10.2 Validation Error Format +## 📉 2. Stock Count Management -FluentValidation's failure map is surfaced as a `400 Bad Request` using the standard error body: +**Business Goal:** Allow warehouse scanning devices to update unit counts without overwriting other concurrent edits. -```json -{ - ""errorCode"": ""BadRequest"", - ""userFriendlyMessage"": ""One or more validation errors occurred."", - ""errors"": { - ""TickerSymbol"": [""TickerSymbol must not be empty.""], - ""Quantity"": [""Quantity must be greater than 0.""] - } -} -``` +### Surgical PATCH Pattern +`PATCH /api/products/{id}/stock?stockCount=42` only updates the `StockCount` field. +The full `Product` record is re-fetched first (`GetByIdAsync`), then only `StockCount` is mutated before the transaction write — preventing race conditions where a scanner zeroes out a field it didn't intend to touch. -> **Implementation note**: Register validators via `services.AddValidatorsFromAssemblyContaining()` + add `FluentValidation.AspNetCore` filter globally so no controller has to call `.Validate()` manually. +``` +PATCH /api/products/7/stock?stockCount=42 +Authorization: Bearer +→ 200: { ""id"": 7, ""name"": ""iPhone 15"", ""stockCount"": 42, ... } +→ 404: if product doesn't exist +``` --- -## 11. Database Configuration - -### 11.1 PostgreSQL — EF Core +## 📈 3. Live Price Sync (Finnhub Integration) -#### Connection +**Business Goal:** Keep `CurrentPrice` aligned with real-world market valuations to drive accurate loss alerts. -```json -// appsettings.Example.json -{ - ""ConnectionStrings"": { - ""DefaultConnection"": ""Host=localhost;Port=5432;Database=inventoryalert;Username=postgres;Password=YOUR_PASSWORD;Include Error Detail=true"" - } -} -``` +### Automatic Background Sync -#### `AppDbContext` — Key Table Configurations +`SyncPricesJob` (Hangfire, scheduled inside `InventoryAlert.Worker`) periodically calls `IProductService.SyncCurrentPricesAsync`: -| Entity | Table Name | Key Config | -| :--- | :--- | :--- | -| `User` | `users` | `Id` (Guid, default `gen_random_uuid()`). Unique index on `Username` + `Email`. | -| `StockListing` | `stock_listings` | `Id` (int, serial). Unique index on `TickerSymbol`. | -| `WatchlistItem` | `watchlist_items` | Composite PK `(UserId, TickerSymbol)`. FK cascade delete on User. | -| `AlertRule` | `alert_rules` | `Id` (Guid). FK cascade delete on User. Index on `(TickerSymbol, IsActive)`. | -| `Trade` | `trades` | `Id` (Guid). FK cascade delete on User. Index on `(UserId, TickerSymbol, TradedAt DESC)`. | -| `PriceHistory` | `price_history` | `Id` (bigserial). Index on `(TickerSymbol, RecordedAt DESC)`. No FK cascade — global data. | -| `StockMetric` | `stock_metrics` | `TickerSymbol` (string PK). 1-to-1 with `StockListing`. | -| `EarningsSurprise` | `earnings_surprises` | `Id` (int, serial). Unique constraint on `(TickerSymbol, Period)`. | -| `RecommendationTrend` | `recommendation_trends` | `Id` (int, serial). Unique constraint on `(TickerSymbol, Period)`. | -| `InsiderTransaction` | `insider_transactions` | `Id` (int, serial). Index on `(TickerSymbol, TransactionDate DESC)`. | +1. Fetches all products from `IProductRepository` +2. For each product, calls `IFinnhubClient.GetQuoteAsync(tickerSymbol, ct)` +3. If `quote.CurrentPrice is null or 0` → logs a warning and **skips** (never throws) +4. Builds a batch of updated `Product` objects +5. Wraps `UpdateRangeAsync` inside `ExecuteTransactionAsync` — all-or-nothing bulk update -#### Migration Naming Convention +### Manual Trigger ``` -Verb + Entity + Detail -Examples: - InitialCreate - AddStockListingTable - RenameProductToStockListing - AddTradeTable - AddStockMetricAndEarningsTable - AddInsiderTransactionTable +POST /api/products/sync-price +Authorization: Bearer +→ 204 No Content (after sync completes) ``` -Run from solution root: -```powershell -dotnet ef migrations add \ - --project InventoryAlert.Api \ - --startup-project InventoryAlert.Api +Useful for analysts to force an immediate refresh before running price-alert queries. -dotnet ef database update \ - --project InventoryAlert.Api \ - --startup-project InventoryAlert.Api -``` +--- -### 11.2 DynamoDB — Configuration +## 🚨 4. Price Loss Alert Engine -```json -// appsettings.Example.json -{ - ""AWS"": { - ""Region"": ""ap-southeast-1"", - ""DynamoDB"": { - ""MarketNewsTable"": ""inventoryalert-market-news"", - ""CompanyNewsTable"": ""inventoryalert-company-news"", - ""ServiceURL"": ""http://localhost:8000"" // local only; remove for production - } - } -} -``` +**Business Goal:** Automatically detect and report products whose market price has dropped dangerously below the baseline cost. -#### Table Provisioning (IaC reference) +### Alert Calculation -| Table | PK | SK | GSI | -| :--- | :--- | :--- | :--- | -| `inventoryalert-market-news` | `PK` (S) | `SK` (S) | — | -| `inventoryalert-company-news` | `PK` (S) | `SK` (S) | `BySymbolAndDate` (Symbol, SK) | +`GetPriceLossAlertsAsync` iterates all products and calculates: +``` +priceDiff = CurrentPrice - OriginPrice +priceChangePercent = priceDiff / OriginPrice (negative = loss) +lossMagnitude = Math.Abs(priceChangePercent) -> Use `PAY_PER_REQUEST` billing mode. No provisioned throughput required at this scale. +→ Alert fires if: lossMagnitude >= PriceAlertThreshold +``` -### 11.3 Redis — Configuration +### Cooldown Gate (Spam Prevention) +Before raising an alert, the system checks `LastAlertSentAt`: +```csharp +var cooldown = TimeSpan.FromHours(1); +if (product.LastAlertSentAt.HasValue && + DateTime.UtcNow - product.LastAlertSentAt.Value < cooldown) + continue; // skip — still in cooldown window +``` +This prevents the same product from generating duplicate notifications within 60 minutes, even if the price remains below threshold. -```json -// appsettings.Example.json -{ - ""Redis"": { - ""ConnectionString"": ""localhost:6379"", - ""InstanceName"": ""inventoryalert:"" - } -} +### Alert Endpoint + +``` +GET /api/products/price-alerts +Authorization: Bearer +→ 200: [ + { + ""id"": 3, + ""name"": ""Tesla Model S Parts"", + ""tickerSymbol"": ""TSLA"", + ""originPrice"": 950.00, + ""currentPrice"": 700.00, + ""priceDiff"": 250.00, + ""priceChangePercent"": -0.2632, + ""priceAlertThreshold"": 0.2, + ""stockCount"": 15 + } + ] ``` -#### Key Namespaces +--- -| Key Pattern | TTL | Purpose | -| :--- | :--- | :--- | -| `quote:{symbol}` | 30 seconds | Cached stock quote from Finnhub. | -| `cooldown:alert:{symbol}` | 24 hours | Prevents repeated alerts for same symbol within 24h. | -| `dedup:sqs:{messageId}` | 30 minutes | Idempotency guard for SQS message processing. | -| `finnhub:ratelimit` | Rolling 60s | Sliding window counter. Cap at 55 calls/min. | +## 📨 5. Event Publishing & Audit -### 11.4 Hangfire — Configuration +**Business Goal:** Emit structured domain events to downstream services (Telegram, Slack, analytics) without coupling to the REST API. -```json -// appsettings.Example.json -{ - ""Hangfire"": { - ""DashboardPath"": ""/hangfire"", - ""SqlServerConnectionString"": ""..."" // or use PostgreSQL storage - } -} +### Publish Any Event + +``` +POST /api/events +Body: { ""eventType"": ""inventoryalert.pricing.price-drop.v1"", ""payload"": { ... } } +→ 202 Accepted ``` -> **Security**: Hangfire dashboard must be gated behind `[Authorize(Roles = ""Admin"")]`. Never expose it publicly. +### Trigger Pre-Built Alerts ---- +| Endpoint | Event Type | Payload | +|---|---|---| +| `POST /api/events/market-alert` | `MarketPriceAlert` | `{ productId, symbol, originPrice, currentPrice, dropPercent }` | +| `POST /api/events/news-alert` | `CompanyNewsAlert` | `{ symbol, headline, source, url, publishedAt }` | -## 12. Seed Data +### Event Type Registry -> Seed data is applied in `AppDbContext.OnModelCreating` (or a dedicated `DataSeeder` service invoked at startup) using `modelBuilder.Entity().HasData(...)`. Seeded rows use **fixed Guids** so re-running migrations is idempotent. +``` +GET /api/events/types +→ 200: [ + ""inventoryalert.pricing.price-drop.v1"", + ""inventoryalert.inventory.stock-low.v1"", + ""inventoryalert.fundamentals.earnings.v1"", + ""inventoryalert.fundamentals.insider-sell.v1"", + ""inventoryalert.news.headline.v1"" + ] +``` -### 12.1 Users +### Audit Log (DynamoDB) -```csharp -new User -{ - Id = Guid.Parse(""00000000-0000-0000-0000-000000000001""), - Username = ""admin"", - PasswordHash = """", - Email = ""admin@inventoryalert.dev"", - Role = ""Admin"", - CreatedAt = DateTime.Parse(""2025-01-01T00:00:00Z"") -}, -new User -{ - Id = Guid.Parse(""00000000-0000-0000-0000-000000000002""), - Username = ""demo_user"", - PasswordHash = """", - Email = ""demo@inventoryalert.dev"", - Role = ""User"", - CreatedAt = DateTime.Parse(""2025-01-01T00:00:00Z"") -} +``` +GET /api/events/logs/{eventType}?limit=20 +→ 200: [ { ""messageId"": ""..."", ""eventType"": ""..."", ""timestamp"": ""..."", ... } ] ``` -### 12.2 StockListings (Global Catalog — 10 Baseline Symbols) +Every published event is written to **DynamoDB `EventLogs` table** before SNS dispatch. Logs are query-able by `eventType` with a configurable `limit`. -```csharp -// Seeded to ensure watchlist/alert demos work out-of-the-box. -// Finnhub will enrich these on first SyncPricesJob run. -new StockListing { Id=1, TickerSymbol=""AAPL"", Name=""Apple Inc"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, -new StockListing { Id=2, TickerSymbol=""MSFT"", Name=""Microsoft Corp"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, -new StockListing { Id=3, TickerSymbol=""GOOGL"", Name=""Alphabet Inc"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, -new StockListing { Id=4, TickerSymbol=""AMZN"", Name=""Amazon.com Inc"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Consumer Cyclical"" }, -new StockListing { Id=5, TickerSymbol=""NVDA"", Name=""NVIDIA Corp"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, -new StockListing { Id=6, TickerSymbol=""TSLA"", Name=""Tesla Inc"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Automotive"" }, -new StockListing { Id=7, TickerSymbol=""META"", Name=""Meta Platforms"", Exchange=""NASDAQ"", Currency=""USD"", Country=""US"", Industry=""Technology"" }, -new StockListing { Id=8, TickerSymbol=""JPM"", Name=""JPMorgan Chase"", Exchange=""NYSE"", Currency=""USD"", Country=""US"", Industry=""Financial Services"" }, -new StockListing { Id=9, TickerSymbol=""V"", Name=""Visa Inc"", Exchange=""NYSE"", Currency=""USD"", Country=""US"", Industry=""Financial Services"" }, -new StockListing { Id=10, TickerSymbol=""BRK.B"", Name=""Berkshire Hathaway"", Exchange=""NYSE"", Currency=""USD"", Country=""US"", Industry=""Financial Services"" }, -``` +--- -### 12.3 WatchlistItems (demo_user) +## 🔁 6. Background Event Handling (Worker) -```csharp -new WatchlistItem { UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), TickerSymbol = ""AAPL"", CreatedAt = DateTime.UtcNow }, -new WatchlistItem { UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), TickerSymbol = ""NVDA"", CreatedAt = DateTime.UtcNow }, -new WatchlistItem { UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), TickerSymbol = ""TSLA"", CreatedAt = DateTime.UtcNow }, -``` +**Business Goal:** Process incoming domain events asynchronously without blocking the API, with persistence and notification side effects. -### 12.4 AlertRules (demo_user) +### Registered Event Handlers (Worker) -```csharp -new AlertRule -{ - Id = Guid.Parse(""10000000-0000-0000-0000-000000000001""), - UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), - TickerSymbol = ""AAPL"", - Condition = AlertCondition.PriceBelow, - TargetValue = 150.00m, - IsActive = true, - TriggerOnce = false, - CreatedAt = DateTime.Parse(""2025-01-01T00:00:00Z"") -}, -new AlertRule -{ - Id = Guid.Parse(""10000000-0000-0000-0000-000000000002""), - UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), - TickerSymbol = ""TSLA"", - Condition = AlertCondition.PercentDropFromCost, - TargetValue = 15.00m, // Alert if TSLA drops 15% from cost basis - IsActive = true, - TriggerOnce = false, - CreatedAt = DateTime.Parse(""2025-01-01T00:00:00Z"") -} -``` +| Event Type | Handler | Side Effect | +|---|---|---| +| `MarketPriceAlert` | `PriceAlertHandler` | Structured log: `🚨 PRICE DROP ALERT {symbol} -{dropPercent:P1}` — **Telegram plug-in point** | +| `EarningsAlert` | `EarningsHandler` | Persists `EarningsRecord` to PostgreSQL (EPS actual vs estimated) | +| `CompanyNewsAlert` | `NewsHandler` | Persists `NewsRecord` to PostgreSQL (headline, source, URL) | +| `InsiderSellAlert` | `InsiderHandler` | Persists `InsiderTransaction` to PostgreSQL | +| *(unknown type)* | `UnknownEventHandler` | Safely logs and discards — no crash, no DLQ escalation | -### 12.5 Trades (demo_user — sample portfolio) +### Dead-Letter Queue +After 3 failed processing attempts, SQS routes the message to `inventory-event-dlq` for manual inspection without causing consumer stalls.",236,51a503b6410630f3c5b56f98bc5b895a,doc\archive\FEATURES_OVERVIEW.md,0,313,"products, alert, price, event, product, business, goal, stockcount",1775670503.9164877,10,external api appdbcontext atomicity compose postgres stock price httpget httppost fluentassertions quote unitofwork postgresql commit container business logic xunit data access iactionresult periodictimer msft market data dockerfile price drop arrange act assert entity framework productservice rollback notification inventory finnhubpricesyncworker backgroundservice asnotracking httpput iproductservice googl threshold dbset productscontroller sku stock hosted service stock ticker savechanges iproductrepository loss item symbol dbcontext efcore unit test aapl igenericrepository application service,# 🛒 Inventory Alert System — Features & API Reference | 🛒 Inventory Alert System — Features & API Reference > This document covers busin +doc,"--- +description: Audit checklist and current feature-state notes for InventoryAlert. +type: reference +status: active +version: 1.0 +tags: [audit, documentation, inventoryalert] +last_updated: 2026-04-23 +---",9,f3a6cc09197006f850ebeacdddcb3f71,doc\archive\feature_audit.md,0,314,"audit, inventoryalert, description, checklist, current, feature, state, notes",1777190302.6143162,1,unitofwork external api efcore sku database update efcore migration iproductservice stock stock price quote dbcontext commit productservice item atomicity threshold application service inventory finnhubpricesyncworker backgroundservice asnotracking periodictimer loss add-migration googl iproductrepository symbol schema change entity framework dbset msft notification data access business logic igenericrepository aapl rollback appdbcontext stock ticker savechanges market data price drop hosted service,feature_audit.md | --- description: Audit checklist and current feature-state notes for InventoryAl +doc,"# InventoryAlert Feature Audit & Consolidation Plan -```csharp -new Trade -{ - Id = Guid.NewGuid(), UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), - TickerSymbol = ""AAPL"", Type = TradeType.Buy, - Quantity = 10m, UnitPrice = 172.50m, TradedAt = DateTime.Parse(""2024-11-01T14:30:00Z"") -}, -new Trade -{ - Id = Guid.NewGuid(), UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), - TickerSymbol = ""NVDA"", Type = TradeType.Buy, - Quantity = 5m, UnitPrice = 480.00m, TradedAt = DateTime.Parse(""2024-11-15T10:00:00Z"") -}, -new Trade -{ - Id = Guid.NewGuid(), UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), - TickerSymbol = ""TSLA"", Type = TradeType.Buy, - Quantity = 8m, UnitPrice = 245.00m, TradedAt = DateTime.Parse(""2024-12-01T09:45:00Z"") -}, -new Trade -{ - Id = Guid.NewGuid(), UserId = Guid.Parse(""00000000-0000-0000-0000-000000000002""), - TickerSymbol = ""TSLA"", Type = TradeType.Sell, - Quantity = 3m, UnitPrice = 410.00m, TradedAt = DateTime.Parse(""2025-01-20T11:00:00Z""), - Notes = ""Partial profit-take after earnings."" -} -``` +## current Feature set -> **Result**: `demo_user` has a live portfolio of 10 AAPL @ avg $172.50, 5 NVDA @ avg $480, and 5 TSLA @ avg $245. Demonstrates both open positions and a realized-gain sell event. +The system currently operates as a ""Modern Financial Inventory Ecosystem"" with the following features: ---- +### 1. Core Inventory & Product Management +- **Description**: CRUD operations for products (tickers), tracking their properties and inventory levels. +- **Storage**: PostgreSQL. +- **Complexity**: High (tied to multiple services). -## 13. Project File Layout +### 2. Market Data Synchronization +- **Description**: Background jobs (SyncPricesJob) that fetch real-time data from Finnhub. +- **Storage**: PostgreSQL (Current prices) and DynamoDB (Price history). +- **Complexity**: High (external API dependency, background scheduling). -> **Placement Rule**: If a type is used by **both** `InventoryAlert.Api` and `InventoryAlert.Worker`, it belongs in `InventoryAlert.Domain` (the shared project). If it is used by only one, keep it local to that project. +### 3. Automated Alerting System +- **Description**: User-defined rules (AlertRules) triggered by price or inventory changes. +- **Workflow**: Price Sync -> SNS -> SQS -> Worker Evaluation -> Telegram. +- **Complexity**: Very High (distributed architecture via LocalStack/AWS services). + +### 4. Market Intelligence (News, Earnings, Recommendations) +- **Description**: Supplemental financial data fetched from Finnhub. +- **Storage**: DynamoDB. +- **Complexity**: Medium-High (separate data path from core inventory). + +### 5. Watchlist & Social +- **Description**: Users can ""watch"" tickers without necessarily having them in inventory. +- **Storage**: PostgreSQL. +- **Complexity**: Low. + +### 6. System Observability & Auditing +- **Description**: Event tracking for all major actions and structured logging to Seq. +- **Storage**: PostgreSQL (SystemEvents) and Seq. +- **Complexity**: Medium. --- -### 13.1 `InventoryAlert.Domain` — Shared Contracts +## Suggested Removals (To ""Make the App Smaller"") -#### `Entities/Postgres/` +To reduce the footprint (infrastructure and code), I suggest the following: -| File | Action | Notes | -| :--- | :--- | :--- | -| `User.cs` | **KEEP** | Add `CreatedAt` property. | -| `Product.cs` | **DELETE** | Replaced by `StockListing.cs`. | -| `StockListing.cs` | **NEW** (rename from `Product.cs`) | Add `Exchange`, `Currency`, `Country`, `MarketCap`, `Ipo`, `WebUrl`, `LastProfileSync`. | -| `WatchlistItem.cs` | **UPDATE** | Remove `IsWatchOnly`. Confirm composite PK `(UserId, TickerSymbol)`. | -| `AlertRule.cs` | **UPDATE** | Add `LastTriggeredAt`, `TriggerOnce`. Update `AlertCondition` enum values. | -| `StockTransaction.cs` | **DELETE** | Replaced by `Trade.cs`. | -| `Trade.cs` | **NEW** (rename from `StockTransaction.cs`) | `Type` enum: `Buy`/`Sell`/`Dividend`/`Split`. `Quantity` always positive. Add `TradedAt`, `Notes`. | -| `PriceHistory.cs` | **UPDATE** | Add `High`, `Low`, `Open`, `PrevClose`. Change PK to `long` (bigserial). | -| `StockMetric.cs` | **NEW** | `TickerSymbol` as PK. All financial metric fields. | -| `EarningsSurprise.cs` | **NEW** | `Period` as `DateOnly` (Finnhub format). Unique on `(TickerSymbol, Period)`. | -| `RecommendationTrend.cs` | **NEW** | Monthly analyst counts. Unique on `(TickerSymbol, Period)`. | -| `InsiderTransaction.cs` | **NEW** | SEC insider filing data. | -| `Notification.cs` | **NEW** | `AlertRuleId?` FK. Index on `(UserId, IsRead, CreatedAt DESC)`. | +### 1. 🗑️ Remove Market Intelligence (News, Earnings, Recommendations) +- **Reason**: These are secondary ""nice-to-have"" features that significantly increase the infrastructure complexity (DynamoDB dependency). +- **Impact**: Migration Complete. -#### `Entities/Dynamodb/` +### 2. Consolidation Roadmap (Lean Profile) -| File | Action | Notes | -| :--- | :--- | :--- | -| `MarketNewsDynamoEntry.cs` | **UPDATE** | Add full attribute schema: `NewsId`, `Headline`, `Summary`, `Source`, `Url`, `Image`, `Category`, `SyncedAt`. | -| `NewsDynamoEntry.cs` | **UPDATE** | Rename to `CompanyNewsDynamoEntry.cs`. Add `Symbol` attribute (for GSI). | +| Feature | Current State | Recommendation | Actions Taken | +| :--- | :--- | :--- | :--- | +| **Watchlist Service** | 🗑️ Removed | **Deprecate** | Merged into `Product` via `IsWatchOnly` & `UserId`. | +| **Price History (Dynamo)** | 💾 Migrated | **Re-Architect** | Moved to PostgreSQL; removed DynamoDB repo. | +| **Event Messaging (SNS)** | 📡 Removed | **Streamline** | Switched to direct SQS (`IQueueService`). | +| **Market News (Dynamo)** | 📰 Retained | **Keep (AWS Practice)** | Maintained for AWS resource skills. | +| **Per-User Isolation** | ✅ Enforced | **Strict Ownership** | All endpoints now filter by `UserId`. | -#### `DTOs/` +## 3. Post-Implementation Summary +The Inventory Management System has been optimized for a **Lean** profile: +1. **Relational Core**: All critical business data (Products, History, Alerts) is now in **PostgreSQL**. +2. **Simplified Messaging**: SNS fan-out removed in favor of direct SQS polling, reducing AWS footprint. +3. **Unified Model**: Eliminated the redundant `Watchlist` entity; users now ""watch"" products in their consolidated inventory. +4. **Strict Security**: Implemented ownership checks at the repository level; users can no longer access other users' data. -| File | Action | Notes | -| :--- | :--- | :--- | -| `AuthRequests.cs` | **UPDATE** → rename `AuthDTOs.cs` | `AuthResponse`: add `AccessToken`, `ExpiresAt`. Add `RefreshRequest` (empty body — cookie-based). | -| `ProductRequest.cs` | **DELETE** | Replaced by `PortfolioDTOs.cs`. | -| `ProductResponse.cs` | **DELETE** | Replaced by `PortfolioDTOs.cs`. | -| `UpdateStockRequest.cs` | **DELETE** | Merged into `TradeRequest` in `PortfolioDTOs.cs`. | -| `ProductQueryParams.cs` | **DELETE** | Replaced by `PortfolioQueryParams.cs`. | -| `PriceLossResponse.cs` | **DELETE** | Replaced by `PortfolioAlertResponse` in `PortfolioDTOs.cs`. | -| `PortfolioDTOs.cs` | **NEW** | `CreatePositionRequest`, `TradeRequest`, `PortfolioPositionResponse` (`StockId` not `Id`), `PortfolioAlertResponse`, `PortfolioQueryParams`. | -| `AlertRuleDTOs.cs` | **UPDATE** | `AlertRuleResponse` add `LastTriggeredAt`. Update `AlertCondition` enum. Add `ToggleAlertRequest`. | -| `MarketDTOs.cs` | **UPDATE** | Add `StockMetricResponse`, `EarningsSurpriseResponse` (`Period` as `DateOnly`), `RecommendationResponse`, `InsiderTransactionResponse`, `MarketHolidayResponse`, `PeersResponse`. | -| `StockDTOs.cs` | **NEW** | `StockQuoteResponse`, `StockProfileResponse`, `SymbolSearchResponse`. | -| `CalendarDTOs.cs` | **NEW** | `EarningsCalendarResponse`, `IpoCalendarResponse`. | -| `NotificationDTOs.cs` | **NEW** | `NotificationResponse`. | -| `PagedResult.cs` | **KEEP** | No changes. | -| `PaginationParams.cs` | **KEEP** | No changes. | -| `EventDTOs.cs` | **KEEP** | No changes. | +--- -#### `Interfaces/` +## Recommended ""Lean"" Feature Set +1. **Unified Product/Ticker Management** (Postgres) +2. **Simplified Price Sync** (Hangfire + Finnhub) +3. **In-Process Alerting** (MediatR/Background Task) +4. **Basic Transaction History** +5. **System Event Auditing**",80,f3a6cc09197006f850ebeacdddcb3f71,doc\archive\feature_audit.md,0,315,"inventory, complexity, description, postgresql, data, system, storage, price",1777190302.6143162,10,unitofwork external api efcore sku database update efcore migration iproductservice stock stock price quote dbcontext commit productservice item atomicity threshold application service inventory finnhubpricesyncworker backgroundservice asnotracking periodictimer loss add-migration googl iproductrepository symbol schema change entity framework dbset msft notification data access business logic igenericrepository aapl rollback appdbcontext stock ticker savechanges market data price drop hosted service,# InventoryAlert Feature Audit & Consolidation Plan | InventoryAlert Feature Audit & Consolidation Plan current Feature set The syste +doc,"--- +description: CI approach to publish this repo's docs into the GitHub Wiki for InventoryManagementSystem. +type: reference +status: draft +version: 1.0 +tags: [github-wiki, ci, github-actions, documentation, inventoryalert] +last_updated: 2026-04-30 +---",9,68409a81f31652491d2d7445bc4a8942,doc\archive\GITHUB_WIKI_CI_PUBLISH.md,0,316,"github, wiki, description, approach, publish, repo, docs, into",1779851803.8707526,1,loss arrange act assert efcore appdbcontext iproductrepository xunit dbset igenericrepository entity framework asnotracking data access threshold fluentassertions dbcontext notification unit test price drop,GITHUB_WIKI_CI_PUBLISH.md | --- description: CI approach to publish this repo's docs into the GitHub Wiki fo +doc,"# Publish GitHub Wiki from CI (InventoryManagementSystem) -| File | Action | Notes | -| :--- | :--- | :--- | -| `IGenericRepository.cs` | **KEEP** | | -| `IDynamoDbGenericRepository.cs` | **KEEP** | | -| `IUnitOfWork.cs` | **KEEP** | | -| `IRedisHelper.cs` | **KEEP** | | -| `IEventPublisher.cs` | **KEEP** | | -| `IQueueService.cs` | **KEEP** | | -| `ICorrelationProvider.cs` | **KEEP** | | -| `IEventService.cs` | **KEEP** | | -| `IAlertRuleRepository.cs` | **KEEP** | | -| `IAlertRuleService.cs` | **KEEP** | | -| `IUserRepository.cs` | **KEEP** | | -| `IWatchlistItemRepository.cs` | **KEEP** | | -| `IPriceHistoryRepository.cs` | **UPDATE** | Add `DeleteOlderThanAsync(DateTime cutoff, CancellationToken ct)` for cleanup job. | -| `INewsDynamoRepository.cs` | **KEEP** | Rename to `ICompanyNewsDynamoRepository.cs` for clarity. | -| `IMarketNewsDynamoRepository.cs` | **KEEP** | | -| `IFinnhubClient.cs` | **UPDATE** | Add methods: `GetMetricsAsync`, `GetEarningsAsync`, `GetRecommendationsAsync`, `GetInsidersAsync`, `GetPeersAsync`, `GetEarningsCalendarAsync`, `GetIpoCalendarAsync`, `GetMarketHolidayAsync`. | -| `IProductRepository.cs` | **DELETE** | Replaced by `IStockListingRepository.cs`. | -| `IStockListingRepository.cs` | **NEW** (from `IProductRepository.cs`) | CRUD + `FindBySymbolAsync`, `SearchAsync(query)`. | -| `IProductService.cs` | **DELETE** | Replaced by `IPortfolioService.cs`. | -| `IPortfolioService.cs` | **NEW** (from `IProductService.cs`) | All position management methods using `TickerSymbol` routes. | -| `IStockTransactionRepository.cs` | **DELETE** | Replaced by `ITradeRepository.cs`. | -| `ITradeRepository.cs` | **NEW** (from `IStockTransactionRepository.cs`) | `GetByUserAndSymbolAsync`, `GetNetHoldingsAsync(userId, symbol)`. | -| `IStockDataService.cs` | **UPDATE** | Add methods for new Finnhub endpoints. | -| `IAlertNotifier.cs` | **UPDATE** | Signature: `NotifyAsync(Notification notification, CancellationToken ct)`. | -| `IStockMetricRepository.cs` | **NEW** | `UpsertAsync(StockMetric metric, CancellationToken ct)`. | -| `IEarningsSurpriseRepository.cs` | **NEW** | `UpsertRangeAsync(IEnumerable, CancellationToken ct)`. | -| `IRecommendationTrendRepository.cs` | **NEW** | `UpsertRangeAsync`. | -| `IInsiderTransactionRepository.cs` | **NEW** | `ReplaceForSymbolAsync(symbol, entries, CancellationToken ct)`. | -| `INotificationRepository.cs` | **NEW** | CRUD + `GetUnreadCountAsync(userId)`, `MarkAllReadAsync(userId)`. | -| `INotificationService.cs` | **NEW** | `CreateAsync(userId, message, symbol?, alertRuleId?)`, `GetPagedAsync`, `MarkReadAsync`. | +Target wiki UI: -#### `Events/` +- `https://github.com///wiki` (example: `https://github.com/nhonvo/InventoryManagementSystem/wiki`) -| File | Action | Notes | -| :--- | :--- | :--- | -| `EventEnvelope.cs` | **KEEP** | | -| `EventTypes.cs` | **KEEP** | Verify 3 event type constants are present. | -| `Payloads/` | **KEEP** | Rename `StockLowAlertPayload` → `LowHoldingsAlertPayload`. | +GitHub wiki is backed by a separate git repository: -#### `Validators/` +- `https://github.com//.wiki.git` (example: `https://github.com/nhonvo/InventoryManagementSystem.wiki.git`) -| File | Action | Notes | -| :--- | :--- | :--- | -| *(existing validators)* | **UPDATE** | Align with renamed DTOs. | -| `CreatePositionRequestValidator.cs` | **NEW** | From `ProductRequestValidator`. | -| `TradeRequestValidator.cs` | **NEW** | From `UpdateStockRequestValidator`. `Quantity > 0` always. | -| `AlertRuleRequestValidator.cs` | **UPDATE** | Cross-field: `PercentDropFromCost` → 0.01–100. `LowHoldingsCount` → whole number. | +This document describes a CI approach (GitHub Actions) to publish markdown pages into the wiki repo from this codebase. + +Doc-only: no workflow is added by this task. --- -### 13.2 `InventoryAlert.Infrastructure` +## 1) What we publish (recommended) -#### `Persistence/Postgres/` +Canonical source (recommended): -| File | Action | Notes | -| :--- | :--- | :--- | -| `InventoryDbContext.cs` | **UPDATE** | Register all new entities. Rename class to `AppDbContext`. | -| `DatabaseSeeder.cs` | **UPDATE** | Replace with Section 12 seed data. | -| `Configurations/ProductConfiguration.cs` | **DELETE** | Replaced by `StockListingConfiguration.cs`. | -| `Configurations/StockListingConfiguration.cs` | **NEW** | Unique index on `TickerSymbol`. | -| `Configurations/AlertRuleConfiguration.cs` | **UPDATE** | Index on `(TickerSymbol, IsActive)`. | -| `Configurations/UserConfiguration.cs` | **KEEP** | | -| `Configurations/WatchlistItemConfiguration.cs` | **UPDATE** | Remove `IsWatchOnly`. Confirm composite PK. | -| `Configurations/TradeConfiguration.cs` | **NEW** | Index on `(UserId, TickerSymbol, TradedAt DESC)`. | -| `Configurations/PriceHistoryConfiguration.cs` | **NEW** | bigserial PK. Index on `(TickerSymbol, RecordedAt DESC)`. | -| `Configurations/StockMetricConfiguration.cs` | **NEW** | PK = `TickerSymbol`. | -| `Configurations/EarningsSurpriseConfiguration.cs` | **NEW** | Unique on `(TickerSymbol, Period)`. | -| `Configurations/RecommendationTrendConfiguration.cs` | **NEW** | Unique on `(TickerSymbol, Period)`. | -| `Configurations/InsiderTransactionConfiguration.cs` | **NEW** | Index on `(TickerSymbol, TransactionDate DESC)`. | -| `Configurations/NotificationConfiguration.cs` | **NEW** | Index on `(UserId, IsRead, CreatedAt DESC)`. | -| `Repositories/ProductRepository.cs` | **DELETE** | Replaced by `StockListingRepository.cs`. | -| `Repositories/StockListingRepository.cs` | **NEW** | Implements `IStockListingRepository`. | -| `Repositories/StockTransactionRepository.cs` | **DELETE** | Replaced by `TradeRepository.cs`. | -| `Repositories/TradeRepository.cs` | **NEW** | Implements `ITradeRepository`. Computes net holdings via `SUM(Buy) - SUM(Sell)`. | -| `Repositories/AlertRuleRepository.cs` | **KEEP** | | -| `Repositories/PriceHistoryRepository.cs` | **UPDATE** | Implement `DeleteOlderThanAsync` (batched: `LIMIT 10000`). | -| `Repositories/UserRepository.cs` | **KEEP** | | -| `Repositories/WatchlistItemRepository.cs` | **KEEP** | | -| `Repositories/GenericRepository.cs` | **KEEP** | | -| `Repositories/UnitOfWork.cs` | **UPDATE** | Register new repos. | -| `Repositories/StockMetricRepository.cs` | **NEW** | `UpsertAsync` via `ON CONFLICT DO UPDATE`. | -| `Repositories/EarningsSurpriseRepository.cs` | **NEW** | Bulk upsert. | -| `Repositories/RecommendationTrendRepository.cs` | **NEW** | Bulk upsert. | -| `Repositories/InsiderTransactionRepository.cs` | **NEW** | Delete-all-for-symbol + bulk insert (replace strategy). | -| `Repositories/NotificationRepository.cs` | **NEW** | Implements `INotificationRepository`. | +- Author docs in this repo under `InventoryAlert.Wiki/docs/` (Docusaurus source) -#### `External/` +Publish target: -| File | Action | Notes | -| :--- | :--- | :--- | -| `FinnhubClient.cs` | **UPDATE** | Add 8 new endpoint methods matching `IFinnhubClient`. | -| `FinnhubModels.cs` | **UPDATE** | Add response models for new endpoints (metrics, earnings, recommendations, insiders, peers, calendars, holidays). | +- Exported plain Markdown into the `.wiki.git` repository -#### `Caching/`, `Messaging/` +Why export? -| File | Action | -| :--- | :--- | -| `RedisHelper.cs` | **KEEP** | -| `SqsService.cs` | **KEEP** | -| `EventPublisher.cs` | **KEEP** | +- Docusaurus frontmatter/MDX may not render in GitHub wiki. +- Wiki navigation differs from Docusaurus sidebars. --- -### 13.3 `InventoryAlert.Api` +## 2) Required GitHub secret -#### `Controllers/` +Use a Personal Access Token (PAT) with access to the target repo: -| File | Action | Notes | -| :--- | :--- | :--- | -| `AuthController.cs` | **UPDATE** | Add `POST /refresh`, `POST /logout`. Set `httpOnly` cookie on login/refresh/logout. | -| `PortfolioController.cs` | **UPDATE** | Routes now use `{symbol}` not `{id}`. Add `DELETE /{symbol}`. Wire `NotificationService` for alert triggers. | -| `StocksController.cs` | **UPDATE** | Add 8 new endpoints: `/financials`, `/earnings`, `/recommendation`, `/insiders`, `/peers`, `/news`, `/calendar/earnings`, `/calendar/ipo`. | -| `WatchlistController.cs` | **UPDATE** | Add `GET /{symbol}` detail endpoint. | -| `AlertRulesController.cs` | **UPDATE** | Add `PATCH /{ruleId}/toggle`, `DELETE /{ruleId}`. | -| `NotificationsController.cs` | **NEW** | Full CRUD: `GET /`, `GET /unread-count`, `PATCH /{id}/read`, `PATCH /read-all`, `DELETE /{id}`. | -| `EventsController.cs` | **KEEP** | | -| `MarketController.cs` | **UPDATE** | Add `GET /holiday`, `GET /calendar/earnings`, `GET /calendar/ipo`. | +- Secret name: `WIKI_PUSH_TOKEN` -#### `Services/` +Notes: -| File | Action | Notes | -| :--- | :--- | :--- | -| `ProductService.cs` | **DELETE** | Replaced by `PortfolioService.cs`. | -| `PortfolioService.cs` | **NEW** (from `ProductService.cs`) | All position logic using `(UserId, TickerSymbol)` as identity key. Implements `IPortfolioService`. | -| `AuthService.cs` | **UPDATE** | Add `RefreshAsync`, `LogoutAsync`. Implement single-use refresh token rotation. | -| `StockDataService.cs` | **UPDATE** | Add methods for 8 new Finnhub endpoints. Implement DB-first + Finnhub-fallback for search. | -| `AlertRuleService.cs` | **KEEP** | | -| `EventService.cs` | **KEEP** | | -| `NotificationService.cs` | **NEW** | Implements `INotificationService`. Creates `Notification` rows when alerts fire. | +- `GITHUB_TOKEN` often cannot push to the separate `.wiki.git` repo. +- Prefer a fine-scoped token and rotate it. -#### `Validations/` +--- -| Decision | Notes | -| :--- | :--- | -| Move all `FluentValidation` validators to `Domain/Validators/` | Both Api and Worker may need validation. Domain is the shared home. `Api/Validations/` folder can be deleted once migrated. | +## 3) Export rules (Docusaurus → GitHub Wiki) -#### Other +Minimum required transforms: -| File | Action | -| :--- | :--- | -| `Middleware/` | **KEEP** | -| `Filters/` | **KEEP** | -| `Extensions/`, `ServiceExtensions/` | **UPDATE** — register `NotificationService`, `PortfolioService`, new repos. | -| `Models/` | **REVIEW** — move any shared models to Domain/DTOs; delete API-local models that duplicate Domain DTOs. | +1) **Frontmatter stripping** + - remove leading `--- ... ---` blocks +2) **Home page mapping** + - `InventoryAlert.Wiki/docs/index.md` → `Home.md` +3) **Link rewriting** + - rewrite relative links so they still work in the wiki +4) **Filename mapping** + - GitHub wiki supports folders, but many teams prefer flat names to avoid broken links. + - Choose one: + - **Foldered**: keep directory structure (e.g. `04-execution-flows/alert-rule-creation.md`) + - **Flat**: convert to `04-execution-flows-alert-rule-creation.md` + +Recommended: keep folders (simpler link rewriting), but ensure links include correct relative paths. --- -### 13.4 `InventoryAlert.Worker` +## 4) Proposed workflow: `.github/workflows/sync-github-wiki.yml` -#### `ScheduledJobs/` +Triggers: -| File | Action | Notes | -| :--- | :--- | :--- | -| `SyncPricesJob.cs` | **UPDATE** | Use `IStockListingRepository` (was `IProductRepository`). Write `PriceHistory` with new fields. Evaluate `AlertRule` → write `Notification`. | -| `CompanyNewsJob.cs` | **KEEP** | | -| `MarketNewsJob.cs` | **KEEP** | | -| `ProcessQueueJob.cs` | **KEEP** | | -| `SqsScheduledPollerJob.cs` | **KEEP** | | -| `SyncMetricsJob.cs` | **NEW** | Daily. Calls `IFinnhubClient.GetMetricsAsync` for all active symbols → `IStockMetricRepository.UpsertAsync`. | -| `SyncEarningsJob.cs` | **NEW** | Daily. Calls `/stock/earnings` for watchlisted symbols → `IEarningsSurpriseRepository.UpsertRangeAsync`. | -| `SyncRecommendationsJob.cs` | **NEW** | Weekly (Monday). Calls `/stock/recommendation` → `IRecommendationTrendRepository.UpsertRangeAsync`. | -| `SyncInsidersJob.cs` | **NEW** | Daily. Calls `/stock/insider-transactions` → `IInsiderTransactionRepository.ReplaceForSymbolAsync`. | -| `CleanupPriceHistoryJob.cs` | **NEW** | Nightly. Calls `IPriceHistoryRepository.DeleteOlderThanAsync(NOW() - 1 year)`. Batched. | +- on push to `main` +- only when wiki source changes: + - `InventoryAlert.Wiki/docs/**` + - (optional) `InventoryAlert.Wiki/sidebars.ts` -#### `IntegrationEvents/Handlers/` +High-level stages: -| File | Action | Notes | -| :--- | :--- | :--- | -| `PriceAlertHandler.cs` | **UPDATE** | On breach: call `INotificationService.CreateAsync(...)` instead of any direct push. | -| `StockLowHandler.cs` | **DELETE** | Replaced by `LowHoldingsHandler.cs`. | -| `LowHoldingsHandler.cs` | **NEW** | Filter `Trade` ledger by `(UserId, TickerSymbol)`. Never aggregate across all users. | -| `MarketNewsHandler.cs` | **UPDATE** | Rename to `CompanyNewsHandler.cs`. | -| `DefaultHandler.cs` | **KEEP** | | -| `UnknownEventHandler.cs` | **DELETE** | Merged into `DefaultHandler.cs`. | -| `Routing/` | **UPDATE** | Register renamed handlers in `IntegrationMessageRouter`. | +1) Checkout this repo +2) Export markdown into an artifacts folder +3) Clone the wiki repo +4) Copy artifacts into the wiki repo +5) Commit & push (only if changes exist) -#### Folders to DELETE (old business) +Illustrative workflow skeleton: -| Folder/File | Reason | -| :--- | :--- | -| `Worker/Telegram/` | Old Telegram notification integration. Replaced by in-app `Notification` table. | -| `Worker/Interfaces/` | Move any shared interfaces to `Domain/Interfaces/`. Worker-local interfaces only if truly internal. | -| `Worker/Models/` | Move shared models to `Domain/DTOs/`. Delete Worker-local duplicates. | -| `Worker/External/` | If delegating to `Infrastructure/External/FinnhubClient.cs` via DI, this folder is redundant. | +```yaml +name: Sync GitHub Wiki ---- +on: + push: + branches: [""main""] + paths: + - ""InventoryAlert.Wiki/docs/**"" + - "".github/workflows/sync-github-wiki.yml"" + workflow_dispatch: -### 13.5 Placement Decision Reference +jobs: + sync: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 -> Use this table to decide where a new file goes when it is not clear. + - name: Export docs to GitHub Wiki format + run: | + mkdir -p artifacts/wiki-export",114,68409a81f31652491d2d7445bc4a8942,doc\archive\GITHUB_WIKI_CI_PUBLISH.md,0,317,"wiki, github, repo, docs, inventoryalert, export, publish, https",1779851803.8707526,10,loss arrange act assert efcore appdbcontext iproductrepository xunit dbset igenericrepository entity framework asnotracking data access threshold fluentassertions dbcontext notification unit test price drop,# Publish GitHub Wiki from CI (InventoryManagementSystem) | Publish GitHub Wiki from CI (InventoryManagementSystem) Target wiki UI: - https: +doc,# TODO: implement export script,115,68409a81f31652491d2d7445bc4a8942,doc\archive\GITHUB_WIKI_CI_PUBLISH.md,0,318,"todo, implement, export, script",1779851803.8707526,115,loss arrange act assert efcore appdbcontext iproductrepository xunit dbset igenericrepository entity framework asnotracking data access threshold fluentassertions dbcontext notification unit test price drop,# TODO: implement export script | TODO: implement export script +doc,"# Example: node ./scripts/export-wiki.mjs -| Type | Used by Api only | Used by Worker only | Used by both | -| :--- | :--- | :--- | :--- | -| Entity class | — | — | **Domain/Entities/** | -| Repository interface | — | — | **Domain/Interfaces/** | -| Service interface | Api/Services OR Domain | Worker/Interfaces OR Domain | **Domain/Interfaces/** | -| Request/Response DTO | Api/Models (or Domain) | — | **Domain/DTOs/** | -| FluentValidation validator | **Domain/Validators/** | — | **Domain/Validators/** | -| SQS event payload | — | — | **Domain/Events/Payloads/** | -| EF Core configuration | — | — | **Infrastructure/Persistence/Configurations/** | -| Repository implementation | — | — | **Infrastructure/Persistence/Repositories/** | -| Caching / Messaging impl | — | — | **Infrastructure/Caching or Messaging/** | -| Controller | **Api/Controllers/** | — | — | -| Scheduled job | — | **Worker/ScheduledJobs/** | — | -| Event handler | — | **Worker/IntegrationEvents/Handlers/** | — |",1675,c508bae3e2362f2515de6cfd4259a2ec,doc\archive\api_technical_spec.md,0,295,"symbol, string, tickersymbol, stock, portfolio, market, keep, update",1776137823.1181319,1,hosted service savechangesasync entity framework backgroundservice loss data access stock savechanges msft httpput application service googl business logic efcore migration finnhubpricesyncworker httpget rollback commit httppost aapl arrange act assert price drop iunitofwork market data inventory atomicity schema change efcore symbol stock ticker iproductservice appdbcontext productscontroller asnotracking dbset dbcontext executetransactionasync threshold notification stock price database update fluentassertions unitofwork igenericrepository iproductrepository productservice iactionresult unit test periodictimer external api item xunit sku quote add-migration,# InventoryAlert.Api — Technical Specification (v2) | InventoryAlert.Api — Technical Specification (v2) > Refactor Target -doc,"# InventoryAlert.Worker — Architectural Review & Flow Documentation + - name: Clone wiki repository + run: | + git clone ""https://x-access-token:${WIKI_PUSH_TOKEN}@github.com/${GITHUB_REPOSITORY}.wiki.git"" artifacts/wiki-repo + env: + WIKI_PUSH_TOKEN: ${{ secrets.WIKI_PUSH_TOKEN }} + GITHUB_REPOSITORY: ${{ github.repository }} -This document provides a technical walkthrough of the **InventoryAlert.Worker** project, detailing its architecture, infrastructure, event lifecycle, and background job logic. + - name: Sync + publish + run: | + rsync -a --delete artifacts/wiki-export/ artifacts/wiki-repo/ + cd artifacts/wiki-repo + if [ -n ""$(git status --porcelain)"" ]; then + git config user.name ""github-actions[bot]"" + git config user.email ""github-actions[bot]@users.noreply.github.com"" + git add . + git commit -m ""Sync wiki from InventoryAlert.Wiki/docs"" + git push + fi +``` --- -## 1. High-Level Architecture +## 5) Export script design (recommended) -The Worker project follows a **Background Service / Worker** pattern, integrated with **Hangfire** for scheduling and **SQS** for event-driven processing. It shares the same Domain and Infrastructure (Partial) concepts as the API but is focused on side effects, data syncing, and external integration. +Add a repo script (example): -### Core Stack +- `scripts/export-wiki.mjs` -- **Service SDK**: `Microsoft.NET.Sdk.Web` (Upgraded to support Hangfire Dashboard). -- **Job Orchestrator**: Hangfire (using PostgreSQL storage). -- **Communication**: Amazon SQS (Event-driven) + SNS (via API). -- **Caching/Deduplication**: Redis (StackExchange.Redis). -- **Persistence**: - - **Relational**: PostgreSQL (via unified `InventoryDbContext` living in `Contracts`). - - **Audit/Logs**: DynamoDB (via unified `EventLogDynamoRepository` living in `Contracts`). -- **External API**: Finnhub REST API. +Responsibilities: -### Infrastructure Diagram (Mermaid) +- find all `InventoryAlert.Wiki/docs/**/*.md` +- strip frontmatter +- rewrite links (`](../foo/bar.md)` etc.) +- write output to `artifacts/wiki-export/` +- ensure `Home.md` is generated -```mermaid -graph TD - %% ── External ── - Finnhub[""Finnhub API (REST)""] - - %% ── Application Layer ── - API[""InventoryAlert.Api""] - Worker[""InventoryAlert.Worker (Background)""] - Contracts[""InventoryAlert.Contracts (Shared Persistence/Domain)""] - - %% ── Messaging (Aws) ── - SNS[""Amazon SNS (Topic)""] - SQS[""Amazon SQS (Queue)""] - DLQ[""Amazon SQS (DLQ)""] +Keep it deterministic: - %% ── Storage ── - DB[""PostgreSQL (Relational DB)""] - Dynamo[""DynamoDB (Audit Logs)""] - Redis[""Redis (Cache/Deduplication)""] +- stable ordering +- stable output filenames - %% ── Interactions ── - API -- ""Publish Event"" --> SNS - SNS -- ""Fan-out"" --> SQS - SQS -- ""Poll Messages"" --> Worker - Worker -- ""Move to DLQ (after 3 retries)"" --> DLQ - - API -- ""CRUD Products"" --> DB - Worker -- ""Sync Prices"" --> DB - Worker -- ""Fetch News/Analytics"" --> Finnhub - - Worker -- ""Save Telemetry"" --> Dynamo - - API -- ""Read/Write Cache"" --> Redis - Worker -- ""SET NX (Deduplication)"" --> Redis - Worker -- ""History Cooldown"" --> Redis - - API --> Contracts - Worker --> Contracts - Contracts --> DB - Contracts --> Dynamo -``` +--- + +## 6) Validation checklist (before enabling CI) + +- Wiki renders Mermaid blocks correctly (validate one page). +- No secrets/tokens/PII in published pages. +- Links work after export. +- Home page (`Home.md`) shows a clear table of contents and “getting started”. --- -## 2. Event Processing Flow (SQS Pipeline) +## 7) Relationship to existing Pages deployment -The most critical flow is the ingestion and processing of market events via SQS. +This repo already has a Pages deploy workflow: -### Lifecycle of an SQS Message +- `.github/workflows/deploy-wiki.yml` (Docusaurus → GitHub Pages) -1. **Trigger**: `PollSqsJob` runs every 30 seconds (Scheduled by `JobSchedulerService`). -2. **Ingestion**: - - `PollSqsJob` fetches up to 10 messages from `settings.Aws.SqsQueueUrl`. - - Each message is deserialized into a generic `EventEnvelope`. -3. **Atomic Deduplication**: - - Uses Redis `StringSetAsync` with `When.NotExists` (SET NX) on key `processed:msg:{envelope.MessageId}`. - - If the lock is not acquired, the message is skipped and Deleted (ACK). -4. **Suppression Logic**: - - Specifically for `MarketPriceAlert`, it checks Redis for an `alert:history:{symbol}`. - - If an alert was sent recently (24h cooldown), the event is suppressed but ACKnowledged. -5. **Dispatching**: - - The job uses a `BuildDispatcher()` dictionary to route the payload to the correct `IEventHandler`. - - Handlers (e.g., `PriceAlertHandler`) execute specific domain logic. -6. **Persistence & ACK**: - - On **Success**: - - Writes a `Status = ""processed""` entry to **DynamoDB**. - - Calls `DeleteMessageAsync` to remove the message from the queue. - - On **Failure**: - - Writes a `Status = ""failed""` entry to **DynamoDB**. - - Does NOT delete the message. It will be redelivered by SQS after the visibility timeout. - - SQS RedrivePolicy handles the movement to DLQ after MaxReceiveCount exceeded. +You can run both: + +- GitHub Pages = best reading UX +- GitHub Wiki = best contributor UX (inline edits, discoverability)",180,68409a81f31652491d2d7445bc4a8942,doc\archive\GITHUB_WIKI_CI_PUBLISH.md,0,319,"wiki, github, export, artifacts, repo, pages, name, home",1779851803.8707526,116,loss arrange act assert efcore appdbcontext iproductrepository xunit dbset igenericrepository entity framework asnotracking data access threshold fluentassertions dbcontext notification unit test price drop,# Example: node ./scripts/export-wiki.mjs | Example: node ./scripts/export-wiki.mjs - name: Clone wiki repository +doc,"# 🏗️ Integration Test Refactoring & Implementation Plan (Unified Project) + +## 1. Executive Summary & Vision +This plan outlines the strategic consolidation of all integration testing tiers into the existing **`InventoryAlert.IntegrationTests`** project. We will transform this project from a ""black-box-only"" suite into a comprehensive **Three-Tier** framework: +1. **Tier 1: Handler Tests (White-box)**: Fast, DI-based tests for core logic (Services and SQS Handlers). +2. **Tier 2: API Tests (Refined Black-box)**: Focused on HTTP/Middleware/Docker Log correlation. +3. **Tier 3: Jobs & Orchestration Tests (Whole Flow)**: Verifies the ""System Plumbing"" (API -> SNS -> SQS -> Worker -> Side Effects). + +The primary goal is to ensure **System-Wide Quality** by proving that all projects (Api, Infrastructure, Worker) communicate correctly through the event bus and produce the expected business outcomes. --- -## 3. Recurring Jobs Registry +## 2. System Orchestration Scenarios (The ""Whole Flow"") -Managed by `JobSchedulerService` (IHostedService), registered on application startup. +The ultimate proof of application quality is the successful execution of cross-boundary scenarios. We will implement these ""Whole Flow"" tests in Tier 3: -| Job Name | Frequency | Responsibility | -| :--- | :--- | :--- | -| `poll-sqs` | 30s | Dequeues events and triggers Handlers. | -| `sync-prices` | 10m (cfg) | Updates `CurrentPrice` in DB for all products via Finnhub. | -| `news-check` | 1h | Fetches latest market/company news. | +| Scenario | Start Point | The ""Flow"" | Validation Point | +|---|---|---|---| +| **Price Alert Cycle** | `POST /api/v1/events` | API -> SQS -> `MarketPriceAlertHandler` -> Worker Logic | `GET /api/v1/notifications` | +| **Position Discovery** | `POST /api/v1/portfolio/positions` | API -> Finnhub Mock -> DB Insert -> SQS Alert | `GET /api/v1/stocks/{s}/quote` | +| **Holdings Evaluation** | `POST /api/v1/portfolio/{s}/trades` | API -> Trade Ledger -> SQS LowHoldings | `GET /api/v1/notifications` | +| **System Sync** | `POST /api/v1/stocks/sync` | API -> Hangfire Job -> Parallel Quotes -> Alerts | DB `PriceHistory` & User Feed | --- -## 4. Big Picture: Jobs vs. Events +## 3. Solution Directory Reorganization -While both patterns run in the background, they serve fundamentally different purposes in the Worker's ecosystem. +We will restructure the `InventoryAlert.IntegrationTests` project internally: -### A. Scheduled Jobs (Pull-Based) -These are **time-triggered** routines managed by Hangfire. They are responsible for keeping the system's state in sync with external truth (Finnhub). -- **Orchestration**: Registered in `JobSchedulerService` via `IRecurringJobManager`. -- **Flow**: `Hangfire Trigger` → `Job.ExecuteAsync()` → `External API` → `Database Update`. -- **Key Jobs**: - - `SyncPricesJob`: The most frequent job. Reconciles DB prices with live market data. - - `NewsCheckJob`: Periodically scrapes news to populate the `NewsRecords` table. +```text +InventoryAlert.IntegrationTests/ +├── Abstractions/ +│ ├── BaseIntegrationTest.cs # Base for Tier 2/3 (Container-based) +│ └── HandlerTestBase.cs # Base for Tier 1 (DI-based) +├── Infrastructure/ # Shared logic for all Tiers +│ ├── SetupDI.cs # PRODUCTION DI Reuse logic (for Tier 1) +│ ├── TestFixture.cs # Container management & Docker Log Reader +│ ├── TestLoggerProvider.cs # In-memory Log capture (for Tier 1) +│ └── ActionTestConfig.cs # Correlation-ID log filter logic +├── Tests/ +│ ├── Handlers/ # TIER 1: White-box SQS Handlers +│ ├── Services/ # TIER 1: White-box Domain Services +│ ├── Api/ # TIER 2: HTTP Endpoint tests (log-aware) +│ └── Jobs/ # TIER 3: Background Worker Orchestration +├── TestData/ # Scenario-based JSON files +│ ├── Requests/ +│ ├── Seeds/ +│ └── Expectations/ +└── appsettings.test.json # Dual-mode config (Localhost vs Docker) +``` -### B. Reactive Events (Push-Based) -These are **action-triggered** routines that respond to events happening elsewhere (usually the API). -- **Orchestration**: The `PollSqsJob` acts as a high-frequency (30s) ""Ingestion Engine"". -- **Dispatching**: It deserializes an `EventEnvelope` and uses a `Dispatcher` dictionary to route to specialized `IEventHandler` instances. -- **Deduplication**: Every event must pass a Redis-backed ""Processed Check"" (`SET NX`) to prevent duplicate processing in clusters. -- **Flow**: `API Action` → `SNS` → `SQS` → `PollSqsJob` → `Handler.HandleAsync()`. +--- + +## 3. Phase 1: Foundation & Shared Infrastructure + +### 3.1 Project Enhancement +- Update `InventoryAlert.IntegrationTests.csproj` to include: + - `Docker.DotNet` (for log scraping). + - `WireMock.Net` (for Finnhub mocking). + - `Respawn` (for fast DB cleanup). + - `Moq` & `FluentAssertions`. + +### 3.2 The Test Logger Provider (For Tier 1) +- Implement `TestLoggerProvider.cs` to capture `ILogger` calls in memory. +- This allows Tier 1 tests to assert logic like `AssertLogContains(""Alert triggered"")` without container scraping. + +### 3.3 The Docker Log Reader (For Tier 2 & 3) +- Implement a utility to stream and filter logs from the running `inventory-api` and `inventory-worker` containers. +- Filter by `X-Correlation-Id` (API) or `MessageId` (Worker). + +### 3.4 WireMock Integration (External API Mocking) +The system uses a standalone WireMock container (`inventory_wiremock` on port `9091`) to simulate the Finnhub API. +- **Base URL**: `http://localhost:9091` +- **Mapping Directory**: `InventoryAlert.IntegrationTests/Wiremock/mappings/` +- **Configuration**: + - For **Tier 1 (DI-based)**: `SetupDI.cs` must replace the `Finnhub:ApiBaseUrl` with the WireMock URL. + - For **Tier 2/3 (Container-based)**: The `inventory-api` and `inventory-worker` containers are already configured via `docker-compose.yml` to point to `http://wiremock:8080`. + +We will use two mapping strategies: +1. **Static Mappings**: JSON files in the `/mappings` folder for common scenarios (e.g., AAPL always returns $150). +2. **Dynamic Mappings**: Use `WireMock.Net` client in C# to create per-test stubs for edge cases (e.g., simulating a 429 Rate Limit error). --- -## 5. Handler Logic Review +## 4. Phase 2: Tier 1 - Handler Integration Tests (White-box) -| Handler | Purpose | Logic Notes | -| :--- | :--- | :--- | -| `PriceAlertHandler` | Process price drops. | Logs event; intended to trigger downstream notifications. | -| `NewsHandler` | Content ingestion. | Persists structured news snippets associated with tickers. | -| `UnknownEventHandler` | Safety Net. | Handles `EventEnvelope` with unrecognized `EventType`. | +### 4.1 Production DI Reuse +- Create `SetupDI.cs` inside the integration project. +- Reuse `services.AddInfrastructure(settings)` and `services.AddApplicationServices()`. +- Use `services.Replace()` to redirect external service calls to WireMock (Finnhub) and Moto (SQS). + +### 4.2 Handler Test Fixture +- Responsibility: Truncate PostgreSQL using `Respawn` and reset WireMock between tests. --- -## 6. Architectural Recommendations +## 5. Phase 3: Tier 2 - API Integration Tests (Log-Aware) -### Current Strengths +Refactor existing tests to use the `ActionTestConfig` pattern: +- Every HTTP call returns both the `RestResponse` AND the filtered Docker logs. +- Allows verifying internal state changes that don't appear in the HTTP body. -- **Resilience**: Every message is audit-logged in DynamoDB regardless of success/failure. -- **Deduplication**: Redis locks prevent duplicate processing in scaled-out worker environments. -- **Observability**: Hangfire Dashboard integration provides real-time monitoring of retries and failures. +--- -### Recent Architectural Refactorings +## 6. Phase 4: Tier 3 - Jobs & SQS Orchestration -1. **Unified Persistence**: Previously, the API and Worker maintained disconnected DbContexts (`AppDbContext` vs `WorkerDbContext`). These were consolidated into a single `InventoryDbContext` residing centrally within `InventoryAlert.Contracts`. -2. **DynamoDB Unification**: The `EventLogDynamoRepository` and its data model were also moved to `Contracts`, eliminating duplicate SDK code between API log queries and Worker event telemetry writes. -3. **Internal Restructuring**: Event Handlers and background Jobs were cleanly bounded into an `Infrastructure/` namespace mimicking the API's Clean Architecture approach. +- Focus on verifying the ""Plumbing"" (SNS -> SQS -> Worker). +- **Scenario: DLQ Movement**: + - Inject poison message into Moto SQS. + - Assert Worker logs show failure. + - Assert message appears in `inventory-event-dlq`. -### Opportunities for Improvement +--- -- **Interface Segregation**: `IEventHandler` is clean, but the manual mapping in `PollSqsJob.BuildDispatcher` could be refactored to use a Strategy pattern or DI keyed services if the number of handlers grows significantly. -- **Resource Protection**: Add rate limiting to `SyncPricesJob` to honor Finnhub's tier-specific throughput limits. -- **DynamoDB Reallocation**: Currently, DynamoDB is heavily invoked for simple Event Logs. Future optimization is slated to migrate `NewsRecord` out of PostgreSQL and into DynamoDB to better leverage its time-series query performance.",159,8be22a49bfeb786d1f98fa28b1a453a7,doc\archive\Architectural_Review.md,0,296,"event, worker, dynamodb, hangfire, redis, message, flow, logic",1775670503.9039152,1,fluentassertions data access sku loss msft business logic efcore periodictimer dbcontext iproductrepository iproductservice stock productservice xunit unit test application service appdbcontext stock ticker igenericrepository dbset item finnhubpricesyncworker backgroundservice googl hosted service notification entity framework inventory stock price symbol threshold external api quote aapl market data asnotracking price drop arrange act assert,# InventoryAlert.Worker — Architectural Review & Flow Documentation | InventoryAlert.Worker — Architectural Review & Flow Documentation This document -doc,"--- -description: Architecture modernization notes and refactor plan for InventoryAlert. -type: plan -status: active -version: 1.0 -tags: [architecture, modernization, plan] -last_updated: 2026-04-23 ----",9,694dfe7e2704e51176f3c8109e232328,doc\archive\architecture_modernization.md,0,297,"plan, architecture, modernization, description, notes, refactor, inventoryalert, type",1777190302.6123624,1,dbcontext entity framework threshold asnotracking appdbcontext business logic productservice item periodictimer application service backgroundservice iproductservice finnhubpricesyncworker inventory stock efcore loss sku notification price drop hosted service,architecture_modernization.md | --- description: Architecture modernization notes and refactor plan for Inventor -doc,"# Architecture Modernization Track +## 7. Implementation Roadmap -## 🎯 Objectives -- Rename `InventoryAlert.Contracts` to `InventoryAlert.Domain` for architectural clarity. -* Consolidate Infrastructure by moving single-tenant logic into `Api` or `Worker`. -* Finalize the ""Lean Profile"" by removing redundant layers. +### 7.1 Week 1: Core Infrastructure +- [ ] Implement `TestLoggerProvider` and `DockerLogReader`. +- [ ] Implement `SetupDI` for production dependency reuse. +- [ ] Implement `ActionTestConfig` for log correlation. -## 🏃 Progress -| Task | Status | Notes | -| :--- | :--- | :--- | -| **Project Renaming** | ✅ Completed | Renamed `Contracts` to `Domain`. | -| **Logic Scoping Audit** | ✅ Completed | Identified Infrastructure logic for relocation. | -| **Infrastructure Cleanup** | ✅ Completed | Moved scoped logic to `Api` or `Worker`. | -| **Namespace Refactoring** | ✅ Completed | All namespaces updated to `Domain` and specific service locations. | +### 7.2 Week 2: Tier 1 Migration (Services & Handlers) +- [ ] Migrate `MarketPriceAlertHandler` and `PortfolioService` tests to the new DI-based structure. +- [ ] Implement WireMock mappings for all Finnhub scenarios. -## 🔍 Logic Scoping Audit (Draft) -| Component | Primary Usage | Recommendation | -| :--- | :--- | :--- | -| `AuthService` | API | ✅ Moved to `InventoryAlert.Api`. | -| `SqsHelper` | Worker | ✅ Moved to `InventoryAlert.Worker`. | -| `TelegramAlertNotifier` | Worker | ✅ Moved to `InventoryAlert.Worker`. | -| `StockDataService` | API | ✅ Moved to `InventoryAlert.Api`. | -| `ProductService` | API | ✅ Moved to `InventoryAlert.Api`. |",32,694dfe7e2704e51176f3c8109e232328,doc\archive\architecture_modernization.md,0,298,"inventoryalert, worker, moved, logic, completed, domain, infrastructure, contracts",1777190302.6123624,10,dbcontext entity framework threshold asnotracking appdbcontext business logic productservice item periodictimer application service backgroundservice iproductservice finnhubpricesyncworker inventory stock efcore loss sku notification price drop hosted service,# Architecture Modernization Track | Architecture Modernization Track 🎯 Objectives - Rename InventoryAlert.Contracts +### 7.3 Week 3: Tier 2 Refactoring (API Controllers) +- [ ] Refactor existing Controller tests to include log-based verification. +- [ ] Verify symbol discovery flow (logs ""DB miss -> Finnhub call""). + +### 7.4 Week 4: Tier 3 & CI Integration +- [ ] Implement SQS routing and DLQ tests. +- [ ] Update `.github/workflows/ci.yml` to execute the unified project with category filters.",132,04d40abbfc6d5b1abe085a823299b08f,doc\archive\integration-test-refactor-plan.md,0,320,"tier, tests, wiremock, worker, implement, integration, project, finnhub",1779814416.3997838,1,httppost threshold efcore migration moq loss arrange act assert iproductservice productscontroller httpget appdbcontext inventory external api compose periodictimer quote fluentassertions postgresql business logic returns async iactionresult verify unit test mock setup efcore entity framework postgres stock price application service schema change times once httpput market data productservice add-migration dockerfile item container finnhubpricesyncworker backgroundservice hosted service price drop asnotracking notification database update stock sku xunit dbcontext,# 🏗️ Integration Test Refactoring & Implementation Plan (Unified Project) | 🏗️ Integration Test Refactoring & Implementation Plan (Unified Project) 1 doc,"--- -description: Comprehensive audit plan — findings from full git-diff review of 82 changed files. -type: plan -status: active -version: 2.0 -tags: [audit, code-quality, standards, ddd, conventions] -last_updated: 2026-04-05 ----",9,fb64583e3f4984ee72572776c7e5b729,doc\archive\AUDIT_PLAN.md,0,299,"audit, plan, description, comprehensive, findings, from, full, diff",1775368171.535382,1,infrastructure mock setup price drop external api savechangesasync fluentassertions productscontroller item data access domain driven design aapl returns async stock price dbset inventory iactionresult hosted service dockerfile notification postgres efcore savechanges domain entity compose commit appdbcontext backgroundservice threshold arrange act assert httpget stock ticker httppost periodictimer stock googl asnotracking application layer unitofwork executetransactionasync symbol sku iproductrepository xunit entity framework httpput container market data iproductservice rollback unit test loss igenericrepository times once verify dbcontext business logic msft postgresql quote finnhubpricesyncworker iunitofwork atomicity moq application service productservice,AUDIT_PLAN.md | --- description: Comprehensive audit plan — findings from full git-diff review o -doc,"# 🔍 Codebase Audit & Standardization Plan +description: Integration test plan focused on Worker/Hangfire jobs and SQS/DLQ (Option C recovery) flows. +type: reference +status: draft +version: 1.0 +tags: [tests, integration-tests, worker, hangfire, sqs, dlq, option-c, inventoryalert] +last_updated: 2026-04-26 +---",9,dc1a2c3dd9d4a48593084430ad4f9b86,doc\archive\JOBS_INTEGRATION_TEST_PLAN.md,0,321,"integration, worker, hangfire, option, tests, description, test, plan",1779851803.8707526,1,external api market data price drop mock setup appdbcontext stock price arrange act assert verify stock container dockerfile asnotracking periodictimer postgres item postgresql hosted service xunit compose moq returns async times once backgroundservice inventory finnhubpricesyncworker unit test fluentassertions entity framework notification quote sku threshold loss efcore dbcontext,JOBS_INTEGRATION_TEST_PLAN.md | --- description: Integration test plan focused on Worker/Hangfire jobs and SQS/D +doc,"# Jobs + Worker Integration Test Plan (with SQS/DLQ Option C) -> **Scope:** Full review of all 82 changed files against DDD, Clean Architecture, -> PHASE2_PLAN, and project coding rules. Issues recorded below, grouped by severity. -> **Do NOT implement fixes here — file issues only. Fix via separate commits.** +This plan complements `InventoryManagementSystem/InventoryAlert.IntegrationTests/INTEGRATION_TEST_PLAN.md` by focusing specifically on: ---- +- Hangfire recurring jobs (Worker) +- SQS consumption semantics (success = delete, failure = redeliver) +- DLQ behavior (redrive policy) +- **Option C** recovery: a Hangfire “DLQ reprocessor/redrive” job that operators can retry in the Hangfire Dashboard -## 🔴 HIGH — Must Fix Before Merge +This is documentation only; it describes what to test and how to structure it. -### H-1 · `EventService.cs:L53` — Transaction Capture Anti-Pattern +Status note (current repo reality): -**File:** `InventoryAlert.Api/Application/Services/EventService.cs` +- The existing integration tests in `InventoryManagementSystem/InventoryAlert.IntegrationTests` currently run as “black-box” HTTP tests against the docker-compose stack (RestSharp clients). +- For a practical worker/jobs/events coverage plan that matches the current harness, also see: + - `doc/WORKER_JOBS_AND_EVENTS_INTEGRATION_TESTS.md` -`` -`csharp -// ✅ CURRENT — project rules explicitly ban this -EventLog savedLog = new(); -await _unitOfWork.ExecuteTransactionAsync(async () => -{ - savedLog = await _eventLogRepository.AddAsync(log, ct); -}, ct); -// savedLog is never used — dead code AND violates the pattern -``` +--- -`savedLog` is declared outside, assigned inside, but never read after the transaction. -The `LogInformation` on L59 uses `log` (the pre-persist input), not `savedLog`. +## 1) Test environments (recommended) -**Fix:** Remove the capture entirely — just call `AddAsync` without assigning: +### Local dev -```csharp -await _unitOfWork.ExecuteTransactionAsync(async () => -{ - await _eventLogRepository.AddAsync(log, ct); -}, ct); -``` +Use the existing docker compose stack under: ---- +- `InventoryManagementSystem/` (API + Worker + DB + Redis + Moto/LocalStack as configured) -### H-2 · Duplicate Test Projects in Solution +### CI -**Files:** +Current `.github/workflows/ci.yml` already: -- `InventoryAlert.Tests/` (lines 60–67 in git-files.txt) +- builds .NET + runs unit tests +- starts Docker compose +- runs `InventoryAlert.IntegrationTests` -- `InventoryAlert.UnitTests/` (lines 20–27 in git-files.txt) +Extend your integration tests in a way that does not require flaky timing or long waits. -Both contain identical test class names (`ProductServiceTests`, `EventServiceTests`, etc.) -with different root namespaces (`InventoryAlert.Tests.*` vs `InventoryAlert.UnitTests.*`). +--- -`ProductServiceTests.cs:L8` imports `using InventoryAlert.Tests.Helpers` — confirming -`UnitTests` project references `Tests` project's helpers directly. This is fragile. +## 2) Core invariants to enforce (must-have) -**Fix:** +### 2.1 Success path -- Keep `InventoryAlert.UnitTests` (the newer one, matches PHASE2_PLAN naming). +- Given an event message in the main queue: + - Worker processes it exactly once (idempotent behavior). + - Worker deletes the SQS message. + - Expected side effects happen (DB rows / notifications / logs). -- Delete `InventoryAlert.Tests/` entirely. +### 2.2 Failure path → retry by redelivery -- Move `Helpers/ProductFixtures.cs` to `UnitTests/Helpers/`. +- Given a poison message or a handler that throws: + - Worker does not delete the message. + - SQS redelivers it after visibility timeout. -- Remove `InventoryAlert.Tests` from `.sln`. +Important: today the Redis dedup behavior can cause “failure then ACK on redelivery” (message loss). If Option C is the direction, adjust production code first so the test can enforce “retries are real”. + +### 2.3 Failure path → DLQ after maxReceiveCount + +- Given repeated failures: + - the message eventually appears in the DLQ (based on queue redrive policy) + - the message stops showing up in the main queue + +In local dev, `moto-init` creates `event-queue` with `maxReceiveCount=3`. --- -### H-3 · `AuthController.cs:L32` — Hardcoded Credentials (OWASP A02) +## 3) Test categories -**File:** `InventoryAlert.Api/Web/Controllers/AuthController.cs` +### 3.1 Worker job tests (direct invocation) -`` -`csharp -// ✅ OWASP A02 — hardcoded credentials in source -if (request.Username == ""admin"" && request.Password == ""admin123"") -``` +Pattern: -Also: `AuthController` uses old-style field injection (not C# 12 primary constructor). -Also: `DateTime.Now` used on L62 instead of `DateTime.UtcNow`. +- Resolve a job from DI and call `ExecuteAsync()`. +- Assert the side effects (DB, cache, outgoing events). -**Fix:** -1. Move credentials to `appsettings.json` under `Auth:Username` / `Auth:Password`. -2. Inject `IConfiguration` via primary constructor. -3. Replace `DateTime.Now` → `DateTime.UtcNow`. +Targets: ---- +- `SyncPricesJob` +- `NewsSyncJob` +- `CleanupPriceHistoryJob` -### H-4 · `Program.cs (API):L43` — Hardcoded JWT Fallback Secret (OWASP A02) +Guidance: -**File:** `InventoryAlert.Api/Program.cs` +- Keep these tests deterministic: mock external APIs (Finnhub) or use a predictable stub. +- Avoid long-running loops; test the single execution method. -`` -`csharp -// ✅ Hardcoded fallback key in production code -var jwtKey = builder.Configuration[""Jwt:Key""] ?? ""super_secret_key_12345_super_secret_key_12345""; -``` +### 3.2 SQS consumer tests (message-driven) -If `Jwt:Key` is missing from config, a hardcoded predictable key is used silently. +Pattern: -**Fix:** Throw instead of falling back: -```csharp -var jwtKey = builder.Configuration[""Jwt:Key""] - ?? throw new InvalidOperationException(""Jwt:Key is required in configuration.""); -``` +- Publish a known message into SQS. +- Run a single “poll + process” unit (preferably one `ProcessBatchAsync` call, not an infinite loop). +- Assert: + - message deleted (success) OR message still present (failure) + - side effects ---- +If the current architecture only exposes the infinite loop, consider adding a test seam (already present: `ProcessBatchAsync` in `ProcessQueueJob`). -## 🟠 MEDIUM — Fix in Next Sprint +### 3.3 DLQ reprocessor job tests (Option C) -### M-1 · `EventsController.cs:L49,L69` — Magic String EventTypes +This is what makes “Retry in Hangfire Dashboard” meaningful for failed message recovery. -**File:** `InventoryAlert.Api/Web/Controllers/EventsController.cs` +Test cases: -`` -`csharp -// ✅ Hardcoded — breaks silently if EventTypes constant is renamed -await _eventService.PublishEventAsync(""MarketPriceAlert"", payload, ct); // L49 -await _eventService.PublishEventAsync(""CompanyNewsAlert"", payload, ct); // L69 -``` +1) **Reprocess DLQ batch (success)** + - Arrange: message exists in DLQ + - Act: run `DlqReprocessorJob.ExecuteAsync(max=10)` + - Assert: + - message is published back to main queue (or SNS, depending on design) + - DLQ message is deleted only after publish succeeds -`EventTypes.cs` exists with the correct constants. Use them: +2) **Reprocess DLQ batch (partial failure)** + - Arrange: DLQ contains both valid and invalid messages + - Act: run job + - Assert: + - valid messages are replayed + - invalid messages are either left in DLQ or moved aside (depending on policy) + - job returns a result/log summary (counts) -```csharp -await _eventService.PublishEventAsync(EventTypes.MarketPriceAlert, payload, ct); -await _eventService.PublishEventAsync(EventTypes.CompanyNewsAlert, payload, ct); -``` +3) **Idempotency / replay safety** + - Arrange: same DLQ message is processed twice (simulate crash before delete) + - Assert: the replay operation does not create duplicate side effects (use `MessageId`-based idempotency key). --- -### M-2 · `EventLogDynamoRepository.cs:L12` — Old-Style Constructor, Untestable Context - -**File:** `InventoryAlert.Worker/Persistence/EventLogDynamoRepository.cs` +## 4) Suggested folder structure (inside IntegrationTests) -`` -`csharp -// ✅ Not primary constructor (C# 12 rule) -// ✅ new DynamoDBContext() inside constructor — cannot be mocked -public EventLogDynamoRepository(IAmazonDynamoDB dynamoDbClient, ILogger<...> logger) -{ - _context = new DynamoDBContext(dynamoDbClient); - _logger = logger; -} +```text +InventoryManagementSystem/InventoryAlert.IntegrationTests/ +├── Tests/ +│ ├── Worker/ +│ │ ├── Jobs/ +│ │ │ ├── SyncPricesJobTests.cs +│ │ │ ├── NewsSyncJobTests.cs +│ │ ├── Sqs/ +│ │ │ ├── SqsConsumerSuccessTests.cs +│ │ │ ├── SqsConsumerDlqTests.cs +│ │ ├── Dlq/ +│ │ │ ├── DlqReprocessorJobTests.cs ``` -**Fix:** Use primary constructor pattern. `DynamoDBContext` should be injected -or wrapped behind an interface if testability is required. - --- -### M-3 · `InfrastructureServiceExtensions.cs:L55,L61,L67` — Hardcoded `""test""` Credentials +## 5) Timing pitfalls + how to avoid flaky tests -**File:** `InventoryAlert.Api/Web/ServiceExtensions/InfrastructureServiceExtensions.cs` +- Prefer asserting via “pull once” APIs rather than sleeping: + - check SQS queue length / receive messages + - query DB state +- Use bounded waits with polling loops (max 10–30s) for asynchronous behaviors. +- Keep maxReceiveCount small in local env (already `3`) and set `VisibilityTimeout` low enough for tests. +- Ensure test cleanup resets SQS queues, Redis keys, and DB state between tests. -`` -`csharp -// ✅ Hardcoded ""test""/""test"" credentials — works for Moto but breaks in real AWS -return new AmazonSimpleNotificationServiceClient(""test"", ""test"", config); -return new AmazonSQSClient(""test"", ""test"", config); -return new AmazonDynamoDBClient(""test"", ""test"", config); -``` +--- -Same pattern in `Worker/Program.cs:L58,L64`. +## 6) What to update in CI after adding these tests -**Fix:** Use `new AmazonSQSClient(config)` (no explicit credential args). -The SDK auto-reads `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` from the environment, -which is already set in `docker-compose.yml`. This makes it work in both Moto and real AWS. +Once the new tests exist: ---- +- Confirm `.github/workflows/ci.yml` stack includes: + - SQS + DLQ (Moto/LocalStack) with redrive policy + - Redis (for dedup/cooldown) +- Add a CI summary section for: + - number of messages processed + - DLQ count (if any) + - replay runs (if job exists)",175,dc1a2c3dd9d4a48593084430ad4f9b86,doc\archive\JOBS_INTEGRATION_TEST_PLAN.md,0,322,"message, tests, test, worker, failure, queue, assert, messages",1779851803.8707526,10,external api market data price drop mock setup appdbcontext stock price arrange act assert verify stock container dockerfile asnotracking periodictimer postgres item postgresql hosted service xunit compose moq returns async times once backgroundservice inventory finnhubpricesyncworker unit test fluentassertions entity framework notification quote sku threshold loss efcore dbcontext,# Jobs + Worker Integration Test Plan (with SQS/DLQ Option C) | Jobs + Worker Integration Test Plan (with SQS/DLQ Option C) This plan complement +doc,"# Logging Review & Recommendations -### M-4 · `ArchitectureTests.cs` — Missing Web→Application Dependency Check +Scope: repository-wide review focused on **API/Worker request flow tracing**, **request/response logging**, and **centralized structured logging**. No code changes included in this document. -**File:** `InventoryAlert.ArchitectureTests/ArchitectureTests.cs` +Date: 2026-04-26 -Current tests check: +--- -- `Api.Domain.Entities` has no classes ✅ +## 1) Current State (What Exists Today) -- `Worker.Entities` has no classes ✅ +### API (`InventoryManagementSystem/InventoryAlert.Api`) -- `Application` doesn't depend on `Infrastructure` ✅ +- **Serilog bootstrap** configured in `InventoryManagementSystem/InventoryAlert.Api/Program.cs` (Console + Seq + rolling File). +- **Correlation ID** middleware exists: `InventoryManagementSystem/InventoryAlert.Api/Middleware/CorrelationIdMiddleware.cs` + - Header: `X-Correlation-Id` + - Behavior: uses incoming header if present; otherwise generates a `Guid`. + - Adds the id to: + - `context.Items[""X-Correlation-Id""]` + - `context.Response.Headers[""X-Correlation-Id""]` + - Serilog `LogContext` property: `CorrelationId` +- **Exception logging** exists: `InventoryManagementSystem/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs` +- **Request timing logs** exist: `InventoryManagementSystem/InventoryAlert.Api/Middleware/PerformanceMiddleware.cs` -**Missing tests:** +### Worker (`InventoryManagementSystem/InventoryAlert.Worker`) -- `Domain` must not depend on `Application` or `Infrastructure` +- Serilog bootstrap exists in `InventoryManagementSystem/InventoryAlert.Worker/Program.cs` (Console + Seq). +- SQS processing uses scopes + Serilog context: + - `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` + - Pushes `CorrelationId` into: + - `ILogger.BeginScope(...)` dictionary (`MessageId`, `EventType`, `CorrelationId`) + - Serilog `LogContext` property `CorrelationId` -- `Web` (Controllers) must not depend on `Domain` directly (only via `Application`) +### Infrastructure (`InventoryManagementSystem/InventoryAlert.Infrastructure`) -- `Contracts` must not depend on `Api` or `Worker` +- Messaging publisher logs publishes: + - `InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs` +- `ICorrelationProvider` currently reads **only** from `HttpContext`: + - `InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs` + +### UI (`InventoryAlert.UI`) + +- No explicit propagation of `X-Correlation-Id` found in UI sources (search for `X-Correlation-Id` / `CorrelationId` returned no matches). --- -### M-5 · `GenericRepository.cs:L21,L48,L54` — CS1998 `async` Without `await` +## 2) What’s Missing vs Your Goal -**File:** `InventoryAlert.Api/Infrastructure/Persistence/Repositories/GenericRepository.cs` +You asked for: -`` -`csharp -// ✅ CS1998 — async keyword with no await -public async Task DeleteAsync(T entity) { var result = _dbSet.Remove(entity); return result.Entity; } -public async Task UpdateAsync(T entity) { var result = _dbSet.Update(entity); return result.Entity; } -public async Task UpdateRangeAsync(...) { _dbSet.UpdateRange(entities); } -``` +1) **Log request + response** (ideally bodies), but avoid exploding log size. +2) A **single id** to follow the flow end-to-end. +3) A way to **centralize** the logging (avoid “log sprinkled everywhere”). +4) Identify parts that **still have little/no logging**. -**Fix per project rule** — remove `async`, return `Task.FromResult(...)`: +Key gaps found: -```csharp -public Task DeleteAsync(T entity) -{ - var result = _dbSet.Remove(entity); - return Task.FromResult(result.Entity); -} +### Gap A — API → Worker correlation is not reliable today -public Task UpdateAsync(T entity) -{ - var result = _dbSet.Update(entity); - return Task.FromResult(result.Entity); -} +- `README.md` claims: “Every request includes a `CorrelationId` that propagates from the API through SNS/SQS to the Worker.” +- However `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` builds `EventEnvelope` without setting `CorrelationId`. + - `InventoryManagementSystem/InventoryAlert.Domain/Events/EventEnvelope.cs` defaults `CorrelationId` to `string.Empty`. + - `InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs` only includes the `CorrelationId` attribute if it’s not empty. -public Task UpdateRangeAsync(IEnumerable entities) -{ - _dbSet.UpdateRange(entities); - return Task.CompletedTask; -} -``` +Impact: ---- +- For request-triggered async flows (ex: `POST /api/v1/events`), the Worker may log without the same `CorrelationId` as the originating HTTP request, making “search by id” unreliable. -### M-6 · `PriceAlertHandler.cs:L17` — Missing `async` / `await`, Returns `Task.CompletedTask` +### Gap B — Request/response body logging is not implemented -**File:** `InventoryAlert.Worker/Handlers/PriceAlertHandler.cs` +- The API logs *completion* timing (method/path/status/time), but does not log: + - Request headers + - Request body + - Response headers + - Response body -```csharp -public Task HandleAsync(MarketPriceAlertPayload payload, CancellationToken ct = default) -{ - // Only logging — no async I/O, returns Task.CompletedTask - _logger.LogWarning(""{AlertMessage}"", message); - return Task.CompletedTask; -} -``` +### Gap C — Entry-point visibility is low in API controllers/services -This is technically correct (`Task.CompletedTask` is fine) **but** the `_db` field -(`WorkerDbContext`) is injected but **never used**. Dead dependency. +Findings from code scan: -Also: Phase F (Telegram) plugs in here — there's no `IAlertNotifier` dependency injected. -When Phase F is implemented, this handler will need rework. +- All API controllers have **no `ILogger` injection** and **no `.Log*()` calls: + - `InventoryManagementSystem/InventoryAlert.Api/Controllers/*.cs` +- Several API services have no logs: + - `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` + - `InventoryManagementSystem/InventoryAlert.Api/Services/AuthService.cs` + - `InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs` + - `InventoryManagementSystem/InventoryAlert.Api/Services/NotificationService.cs` -**Fix now:** Remove the unused `_db` field and `WorkerDbContext` injection. +Note: this doesn’t mean they *must* log everywhere; it means the **only consistent view** of API activity is currently the middleware timing log (plus error logs). + +### Gap D — Correlation provider works for HTTP only + +- `InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs` depends on `IHttpContextAccessor`. +- In the Worker (no HTTP request), this returns a **new Guid**, which breaks continuity if Worker code publishes further messages and expects to “inherit” correlation. --- -## 🟡 LOW — Track as Tech Debt +## 3) Recommended Logging Design (Centralized + Searchable + Size-Controlled) -### L-1 · `ProductService.cs:L135` — Full Table Scan in Sync/Alert Methods +This is the recommended model: -**File:** `InventoryAlert.Api/Application/Services/ProductService.cs` +### 3.1 Use one “Flow Id” everywhere -```csharp -var products = await _productRepository.GetAllAsync(cancellationToken); -``` +Keep `CorrelationId` as the primary flow identifier: -Called in both `GetPriceLossAlertsAsync` (L135) and `SyncCurrentPricesAsync` (L177). -At scale, this is an unbounded full-table scan. Should filter to products where -`TickerSymbol != """"` at minimum, or use a dedicated repository query. +- HTTP: `X-Correlation-Id` header + `LogContext.CorrelationId` +- Messaging: `EventEnvelope.CorrelationId` + SNS/SQS message attribute `CorrelationId` +- Worker: push envelope `CorrelationId` into scope + `LogContext` ---- +Also consider adding (optional, but valuable): -### L-2 · `AppSettings.cs:L10` — Property Named `AWS` (casing inconsistency) +- `TraceId` (W3C tracing / `Activity.TraceId`) for distributed tracing later +- `RequestId` (`HttpContext.TraceIdentifier`) for server-side uniqueness -**File:** `InventoryAlert.Api/Web/Configuration/AppSettings.cs` +### 3.2 Centralize “HTTP request completion log” (cheap, always-on) -```csharp -public SharedAwsSettings AWS { get; set; } = new(); // uppercase -``` +Goal: every request creates exactly **1 structured log event** at the end: -`appsettings.Docker.json` uses `""Aws""` (PascalCase). While .NET binding is -case-insensitive, the convention mismatch is confusing. Standardize to `Aws`. +Fields to include (recommended): ---- +- `CorrelationId` +- `Method`, `Path`, `StatusCode`, `ElapsedMs` +- `UserId` (if authenticated), `ClientIp` +- `RouteTemplate` / `EndpointName` (if available) +- `RequestContentLength`, `ResponseContentLength` (when known) -### L-3 · `Worker/Program.cs:L88-91` — Verbose Fully-Qualified Handler Registration +This gives you: -**File:** `InventoryAlert.Worker/Program.cs` +- small logs +- consistent format +- easy searching in Seq -```csharp -builder.Services.AddScoped, PriceAlertHandler>(); -``` +### 3.3 Add request/response body logging only under strict controls (expensive, opt-in) -All four handler registrations use fully-qualified type names. Add `using` statements -to the top of the file to clean this up. +Body logging is where log volume and sensitive data risk skyrockets. Recommended controls: ---- +**Controls (must-have)** -### L-4 · `PollSqsJob.cs:L50` — `BuildDispatcher()` Called on Every `ExecuteAsync` Invocation +- Feature flag (enable in Dev/Docker only, off in Prod by default) +- Content-type allowlist (`application/json`, maybe `text/*`) +- Size limits (log first N bytes only; store `Truncated=true`) +- Redaction (passwords/tokens/PII) +- Endpoint allowlist/denylist + - Denylist examples: `POST /api/v1/auth/login`, refresh-token endpoints -**File:** `InventoryAlert.Worker/Jobs/PollSqsJob.cs` +**When to log bodies** -```csharp -public async Task ExecuteAsync(CancellationToken ct = default) -{ - var dispatcher = BuildDispatcher(); // ← rebuilds Dictionary every 30s - ... -} -``` +- Errors only (responses with `StatusCode >= 400`), plus explicit debug scenarios +- Or sample rate (ex: 1% of successful traffic) -The dispatcher dictionary is rebuilt every time the Hangfire job fires (every 30s). -Since the dictionary is static in structure (no runtime changes), it can be built -once in a `readonly` field at construction time. +**Alternative if you need full bodies** ---- +- Write full bodies to a separate secure store (blob/file) keyed by `CorrelationId`, and keep Seq logs lightweight: + - Seq event contains `CorrelationId` + a `PayloadRef` (path/key) -### L-5 · `EventsController.cs` — `GetEventLogs` Exposes `EventLog` Entity Directly +### 3.4 Centralize “business event logs” (domain-level, not request-level) -**File:** `InventoryAlert.Api/Web/Controllers/EventsController.cs:L84` +For meaningful actions (create alert rule, register user, enqueue event, etc.), log: -```csharp -[ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] -``` +- event name (stable template) +- important identifiers (`UserId`, `AlertRuleId`, `Symbol`) +- `CorrelationId` -Returns the raw `EventLog` entity to the client. Should return a mapped DTO -(`EventLogResponse`) to decouple the API contract from the internal entity structure. +This should live at service-layer boundaries (not in every controller). --- -## ✅ CONFIRMED PASSING +## 4) Concrete Fix List (Prioritized, Minimal, High Value) -| Area | Check | -| :--- | :--- | -| Dispatcher pattern (`PollSqsJob`) | ✅ Dictionary + `UnknownEventHandler` fallback | -| Thin controllers (`ProductsController`) | ✅ Zero business logic, SRP violation resolved | -| Transaction Capture (`ProductService`) | ✅ All 4 methods assign result inside lambda | -| DLQ / Retry logic (`PollSqsJob`) | ✅ `ApproximateReceiveCount > 3` → DLQ, ACK only on success | -| DynamoDB telemetry | ✅ Write on success + failure, 90-day TTL | -| `ILogger` everywhere | ✅ No `Console.WriteLine` found | -| Structured logging format | ✅ Parameterized `{MessageId}`, `{EventType}` throughout | -| Primary constructors (most services) | ✅ Consistent across Api + Worker | -| `.AsNoTracking()` on reads | ✅ `GetAllAsync`, `GetPagedAsync` both use it | -| `SnsEventPublisher` layer discipline | ✅ Correctly in `Infrastructure/Messaging/` | -| `ExceptionHandlingMiddleware` | ✅ RFC-7807, no stack trace leakage, structured logging | -| `EventTypes.All` O(1) registry | ✅ `IReadOnlySet` HashSet with `IsKnown()` | -| `Contracts` consolidation | ✅ Entities, Events, Payloads, Constants all in Contracts | -| `CorrelationIdMiddleware` ordering | ✅ Registered first in pipeline | -| Serilog bootstrap | ✅ Both API and Worker use `try/catch/finally + Log.CloseAndFlush()` | +### P0 — Make correlation actually propagate API → SNS/SQS → Worker ---- +Acceptance criteria: -## 📋 Fix Priority Order +- Any HTTP request that publishes an event results in: + - API logs containing `CorrelationId` + - SNS publish logs containing the same `CorrelationId` + - Worker processing logs containing the same `CorrelationId` -``` -Sprint 1 (must): H-1, H-2, H-3, H-4 -Sprint 2 (good): M-1, M-2, M-3, M-5, M-6, M-7, M-8, M-9 -Sprint 3 (debt): M-4 (arch tests), L-1, L-2, L-3, L-4, L-5, L-6, L-7 -``` +Candidate locations to stamp `EventEnvelope.CorrelationId`: -> **Commit convention per fix:** `fix(): ` or `refactor(): ` -> Example: `fix(application): remove transaction capture anti-pattern in EventService` +- `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` (inject `ICorrelationProvider`) +- or a decorator around `IEventPublisher` that stamps missing correlation ids in one place ---- +### P0 — Add “one request completion log” with consistent fields -## 🔴 HIGH — Phase 2 Additions +Acceptance criteria: -### H-5 · `AlertConstants.cs:L21-28` — Duplicate `EventTypes` Class (Name Collision Risk) +- Every request generates exactly one completion log event with consistent fields. +- Slow requests (like current `PerformanceMiddleware`) are still visible (either by a `Slow=true` flag or level/threshold). -**File:** `InventoryAlert.Contracts/Constants/AlertConstants.cs` +### P1 — Add request/response body logging safely (debug-only) -`` -`csharp -// ✅ AlertConstants.cs defines its OWN EventTypes inside Constants namespace -public static class EventTypes -{ - public const string MarketPriceAlert = ""MarketPriceAlert""; // SHORT name - ... -} +Acceptance criteria: -// ✅ Contracts/Events/EventTypes.cs uses reverse-DNS format -public const string MarketPriceAlert = ""inventoryalert.pricing.price-drop.v1""; -``` +- Body logging: + - is off by default + - has truncation + redaction + - can be toggled per environment + - can be enabled per endpoint for targeted debugging -Two `EventTypes` classes exist in the same `Contracts` project with **different values**. -`AlertConstants.EventTypes.MarketPriceAlert = ""MarketPriceAlert""` but -`InventoryAlert.Contracts.Events.EventTypes.MarketPriceAlert = ""inventoryalert.pricing.price-drop.v1""`. +### P1 — Improve Worker correlation continuity for downstream publishes -Any code that imports `AlertConstants` without the full namespace gets the wrong string, -causing silent dispatcher mismatches. +Acceptance criteria: -**Fix:** Delete the `EventTypes` nested class inside `AlertConstants.cs`. -All code must use `InventoryAlert.Contracts.Events.EventTypes.*` exclusively. +- When handling an envelope with `CorrelationId=X`, any downstream publish/enqueue inside the same job uses `CorrelationId=X` by default. ---- +Implementation options (choose one): -### H-6 · `DynamoDbEventLogQuery.cs` — Wrong Namespace (Infrastructure Layer Pollution) +- Pass correlation explicitly as a parameter where enqueuing/publishing occurs. +- Introduce an AsyncLocal-based correlation context (set in HTTP middleware and in Worker message processing) and have `ICorrelationProvider` read from it. +- Adopt W3C tracing (`Activity`) and derive `CorrelationId` from `Activity.TraceId`. -**File:** `InventoryAlert.Api/Infrastructure/External/DynamoDbEventLogQuery.cs` +### P2 — Add service identity properties to logs -```csharp -namespace InventoryAlert.Api.Infrastructure.External // ✅ ""External"" implies 3rd-party HTTP -``` +Acceptance criteria: -DynamoDB is a **persistence** technology, not an external HTTP API (like Finnhub). -Placing it in `Infrastructure/External/` alongside `FinnhubClient` is misleading. +- Seq can filter by service quickly: + - `Service = 'InventoryAlert.Api'` + - `Service = 'InventoryAlert.Worker'` -Also: Old-style constructor (not C# 12 primary constructor): -```csharp -public DynamoDbEventLogQuery(IAmazonDynamoDB dynamoDb) -{ - _dynamoDb = dynamoDb; // ✅ should be primary constructor -} -``` +### P2 — Reduce “big payload” log risk in external client logging -Also: `_tableName` is a hardcoded magic string: -```csharp -private readonly string _tableName = ""inventory-event-logs""; // ✅ must come from config -``` +`InventoryManagementSystem/InventoryAlert.Infrastructure/External/Finnhub/FinnhubClient.cs` logs full response content in some warnings/errors. -**Fix:** -1. Move to `Infrastructure/Persistence/` namespace. -2. Use primary constructor. -3. Inject table name from `WorkerSettings.Aws.DynamoDbTableName` or `AppSettings.AWS.DynamoDbTableName`. +Acceptance criteria: + +- External-client failures log: + - status code, endpoint/path, small excerpt (max N chars), and `CorrelationId` + - never log entire large bodies by default --- -## 🟠 MEDIUM — Phase 2 Additions +## 5) Coverage Findings (Where Logging Is Thin Today) -### M-7 · `IProductService.cs` — Missing `GetAllProductsAsync`, Tests Reference It +### API controllers (no direct logging) -**File:** `InventoryAlert.Api/Application/Interfaces/IProductService.cs` +All controllers found without `ILogger` and without `.Log*()`: -`` -`csharp -// ✅ NOT in interface — but ProductServiceTests.cs:L55 calls it: -var result = await _sut.GetAllProductsAsync(Ct); -``` +- `InventoryManagementSystem/InventoryAlert.Api/Controllers/AlertRulesController.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Controllers/AuthController.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Controllers/EventsController.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Controllers/MarketController.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Controllers/NotificationsController.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Controllers/PortfolioController.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Controllers/StocksController.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Controllers/WatchlistController.cs` -`IProductService` has `GetProductsPagedAsync` but no `GetAllProductsAsync`. -The test calls `GetAllProductsAsync` which means either: -1. It exists on the concrete `ProductService` but not the interface (breaking DI). -2. The tests will fail to compile. +Recommendation: -**Fix:** Add to interface or remove from tests and use `GetProductsPagedAsync` consistently. +- Keep controllers thin, but ensure service-level “business event logs” exist for key actions, and HTTP middleware provides the consistent request-completion log. ---- +### API services with little/no logging -### M-8 · `ci.yml:L30-31` — Build Runs AFTER Tests (Wrong Order) +- `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` (also the correlation stamping gap) +- `InventoryManagementSystem/InventoryAlert.Api/Services/AuthService.cs` (login/register activity visibility is low) +- `InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Services/NotificationService.cs` -**File:** `.github/workflows/ci.yml` +### Worker area with no logs -```yaml",453,fb64583e3f4984ee72572776c7e5b729,doc\archive\AUDIT_PLAN.md,0,300,"csharp, inventoryalert, task, entity, public, async, result, file",1775368171.535382,10,infrastructure mock setup price drop external api savechangesasync fluentassertions productscontroller item data access domain driven design aapl returns async stock price dbset inventory iactionresult hosted service dockerfile notification postgres efcore savechanges domain entity compose commit appdbcontext backgroundservice threshold arrange act assert httpget stock ticker httppost periodictimer stock googl asnotracking application layer unitofwork executetransactionasync symbol sku iproductrepository xunit entity framework httpput container market data iproductservice rollback unit test loss igenericrepository times once verify dbcontext business logic msft postgresql quote finnhubpricesyncworker iunitofwork atomicity moq application service productservice,# 🔍 Codebase Audit & Standardization Plan | 🔍 Codebase Audit & Standardization Plan > Scope: Full review of all 82 changed f -doc,# ✅ Current order: Architecture Test → Unit Test → Build,454,fb64583e3f4984ee72572776c7e5b729,doc\archive\AUDIT_PLAN.md,0,301,"test, current, order, architecture, unit, build",1775368171.535382,454,infrastructure mock setup price drop external api savechangesasync fluentassertions productscontroller item data access domain driven design aapl returns async stock price dbset inventory iactionresult hosted service dockerfile notification postgres efcore savechanges domain entity compose commit appdbcontext backgroundservice threshold arrange act assert httpget stock ticker httppost periodictimer stock googl asnotracking application layer unitofwork executetransactionasync symbol sku iproductrepository xunit entity framework httpput container market data iproductservice rollback unit test loss igenericrepository times once verify dbcontext business logic msft postgresql quote finnhubpricesyncworker iunitofwork atomicity moq application service productservice,# ✅ Current order: Architecture Test → Unit Test → Build | ✅ Current order: Architecture Test → Unit Test → Build -doc,"# Build failure is discovered AFTER expensive test runs +- `InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs` (may be fine, but hard to debug queue backpressure without any counters/logs) -- name: Architecture Test +--- -- name: Unit Test +## 6) Seq Search Examples (How You’d Trace a Flow) -- name: Build # ← should be FIRST -``` +From `InventoryAlert.Wiki/docs/07-dev-maintenance/operational-runbook.md`, you already use: -**Also missing:** +- Errors: `@Level = 'Error'` +- Service: `@Properties.SourceContext like '%Worker%'` +- Correlation: `@Properties.CorrelationId = ''` -- No `dotnet format --verify-no-changes` step (code style) +Recommended additional searches once fields are standardized: -- No `--configuration Release` on test steps (tests run in Debug) +- A single flow: `CorrelationId = ''` +- One event type: `EventType = 'inventoryalert.news.sync-requested.v1'` +- One message: `MessageId = ''` +- Slow requests: `ElapsedMs >= 500` or `Slow = true` -- No artifact upload on failure (test results/logs) +--- -- `build-and-test` job name is misleading (it currently does test-then-build) +## 7) Notes / Potential Inconsistencies to Validate -**Fix:** -```yaml -steps: - - Restore - - Build (--configuration Release) ← first - - Architecture Tests - - Unit Tests - - (optional) Format check -``` +These aren’t strictly “logging” issues, but they affect observability and correlation: + +- Worker router expects SQS `MessageAttributes[""MessageType""]` in `InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs`. + - Current SNS publisher uses message attributes `EventType`, `Source`, and optional `CorrelationId` in `InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs`. + - Consider standardizing attribute names (`EventType` vs `MessageType`) and ensuring Worker routing matches what the publisher emits. --- -### M-9 · `EventsControllerTests.cs:L116/L169` — Magic Strings in Test Assertions +## 8) Suggested Next Output (If You Want) -**File:** `InventoryAlert.UnitTests/Web/Controllers/EventsControllerTests.cs` +If you want, I can produce a second markdown file with a concrete “implementation checklist” (exact middleware/filter approach, redaction rules, size limits, and an example Seq dashboard/query set). This would still be documentation-only unless you ask for code changes.",294,76313fb6742c21b0ea713b23dd91b96c,doc\archive\LOGGING_REVIEW.md,0,323,"inventoryalert, inventorymanagementsystem, correlationid, worker, request, correlation, logging, logs",1779851803.8707526,1,postgresql finnhubpricesyncworker business logic postgres productscontroller iproductservice entity framework loss asnotracking iproductrepository market data application service httpget dbcontext compose iactionresult productservice container efcore httpput notification data access hosted service dockerfile external api price drop appdbcontext httppost periodictimer threshold quote igenericrepository dbset backgroundservice stock price,# Logging Review & Recommendations | Logging Review & Recommendations Scope: repository-wide review focused on API/Wo +doc,"--- +description: Manual QA Testing Guide for the Inventory Alert System — step-by-step test cases and areas flagged for human review. +type: qa +status: active +version: 1.0 +tags: [testing, qa, manual, review, checklist] +last_updated: 2026-04-05 +---",9,af2691d2a74862064a1fa4343331670d,doc\archive\MANUAL_TESTING.md,0,324,"manual, testing, step, review, description, guide, inventory, alert",1779851803.8737533,1,symbol iproductservice httppost appdbcontext stock ticker item stock container iactionresult productservice dbcontext entity framework msft external api application service market data inventory notification postgresql loss efcore business logic unit test xunit httpget googl periodictimer httpput finnhubpricesyncworker quote dockerfile postgres fluentassertions threshold sku price drop stock price arrange act assert productscontroller backgroundservice aapl asnotracking compose hosted service,MANUAL_TESTING.md | --- description: Manual QA Testing Guide for the Inventory Alert System — step-b +doc,"# 🧪 Manual Testing & Review Guide -`` -`csharp -// ✅ Verifying with hardcoded strings — breaks silently if EventTypes changes -_service.Verify(s => s.PublishEventAsync(""MarketPriceAlert"", ...), Times.Once); -_service.Verify(s => s.PublishEventAsync(""CompanyNewsAlert"", ...), Times.Once); -``` +> **How to use this document:** +> - ✅ = Expected pass behavior +> - ❌ = Expected rejection / error behavior +> - 🔍 = **Needs human review** — business logic decision, edge case, or unvalidated behavior -Same root cause as M-1 but in tests. The `EventTypes.*` constants should be used here too. +**Base URL (Docker):** `http://localhost:5000` +**Start environment:** `docker-compose up --build` from `InventoryManagementSystem/` --- -## 🟡 LOW — Phase 2 Additions - -### L-6 · `IEventService.cs:L12` — Interface Returns Internal Entity Type - -**File:** `InventoryAlert.Api/Application/Interfaces/IEventService.cs` +## 🚀 Pre-Flight: Start & Health Check -`` -`csharp -// ✅ Returns entity — should return EventLogResponse DTO -Task> GetEventLogsAsync(...); -``` +| # | Step | Expected | +| --- | -------------------------------------- | -------------------------------------------------------------- | +| 1 | Run `docker-compose up --build` | All 5 containers start without error | +| 2 | Check `moto-init` logs | `SQS queue created`, `DynamoDB table created` messages visible | +| 3 | `GET http://localhost:5000/swagger` | Swagger UI loads with all endpoints | +| 4 | Check `logs/inventoryalert.log` exists | Serilog has created the log file | -The Application interface exposes `EventLog` (an entity) as its return type. -This couples API clients to the persistence schema. Should return an `EventLogResponse` DTO. +> 🔍 **REVIEW:** There is no `/health` endpoint defined. If the `api` or `worker` container crashes silently, there is no heartbeat to detect it. Consider adding `app.MapHealthChecks(""/health"")`. --- -### L-7 · `WorkerSettings.cs:L13-16` — `DatabaseSetting` Duplicated in Both Projects - -**File:** `InventoryAlert.Worker/Configuration/WorkerSettings.cs` +## 🔐 Section 1: Authentication -`` -`csharp -// ✅ Duplicate class — ApiSettings.cs also defines this -public class DatabaseSetting -{ - public string DefaultConnection { get; set; } = string.Empty; -} +### TC-AUTH-01 — Happy Path Login +```http +POST /api/auth/login +{ ""username"": ""admin"", ""password"": ""admin123"" } ``` +- ✅ `200 OK` with `{ ""token"": """" }` +- Copy the token — used in all subsequent `[Authorize]` calls -`AppSettings.cs` in the Api project also defines `DatabaseSetting`. -Both are independent classes. Should be consolidated into -`InventoryAlert.Contracts.Configuration.SharedDatabaseSettings`. - ---- +### TC-AUTH-02 — Wrong Password +```http +POST /api/auth/login +{ ""username"": ""admin"", ""password"": ""wrong"" } +``` +- ✅ `401 Unauthorized` with message `""Invalid credentials.""` -## 💡 Enhancement Proposals +### TC-AUTH-03 — Call Protected Endpoint Without Token +```http +GET /api/products +(no Authorization header) +``` +- ✅ `401 Unauthorized` -> Not bugs — structural improvements for the next design iteration. +### TC-AUTH-04 — Call Protected Endpoint With Expired Token +- Wait for token to expire (2 hours), then call `GET /api/products` +- ✅ `401 Unauthorized` -### E-1 · Introduce `Result` Pattern in Service Layer +> 🔍 **REVIEW:** Credentials (`admin` / `admin123`) are the hardcoded fallback in `AuthController`. In Docker, they should come from `appsettings.Docker.json → Auth:Username / Auth:Password`. Verify these are overridden in the Docker config; otherwise the fallback is always active, even in production images. -**Current:** Services throw `KeyNotFoundException` for not-found, return `null?` for optional results. -**Problem:** Callers must remember which methods throw vs return null, and exception catching is expensive. +--- -**Suggested pattern:** -`` -`csharp -// Contracts/Common/Result.cs -public readonly record struct Result -{ - public T? Value { get; init; } - public bool IsSuccess { get; init; } - public string? Error { get; init; } +## 📦 Section 2: Product CRUD - public static Result Ok(T value) => new() { Value = value, IsSuccess = true }; - public static Result Fail(string error) => new() { Error = error, IsSuccess = false }; - public static Result NotFound(int id) => Fail($""Entity with id {id} was not found.""); -} +Use `Authorization: Bearer ` for all requests in this section. -// Usage in service: -public async Task> GetProductByIdAsync(int id, CancellationToken ct) +### TC-PROD-01 — Create Product (Valid) +```http +POST /api/products { - var product = await _repo.GetByIdAsync(id, ct); - return product is null ? Result.NotFound(id) : Result.Ok(product.ToResponse()); + ""name"": ""Apple iPhone 15"", + ""tickerSymbol"": ""AAPL"", + ""stockCount"": 100, + ""originPrice"": 950.00, + ""currentPrice"": 920.00, + ""priceAlertThreshold"": 0.2, + ""stockAlertThreshold"": 10 } - -// Usage in controller: -var result = await _service.GetProductByIdAsync(id, ct); -return result.IsSuccess ? Ok(result.Value) : NotFound(result.Error); ``` +- ✅ `201 Created` with response body including auto-generated `id` +- ✅ Response includes `Location` header pointing to `GET /api/products/{id}` +- Note the returned `id` for subsequent tests -**Benefit:** Explicit, no hidden control flow, testable without try/catch. - ---- +### TC-PROD-02 — Create Product (Validation Failures) -### E-2 · Inject `IAlertNotifier` into `PriceAlertHandler` Now +| Sub-case | Payload Change | Expected | +| --------------------------- | ----------------------------- | --------------------------------------------------------- | +| Empty name | `""name"": """"` | ❌ `400` — `""Name is required.""` | +| Name too long | `""name"": ""A"" * 257` | ❌ `400` — `""Name must not exceed 256 characters.""` | +| Lowercase ticker | `""tickerSymbol"": ""aapl""` | ❌ `400` — `""TickerSymbol must be 1–16 uppercase letters""` | +| Ticker with numbers | `""tickerSymbol"": ""AAP1""` | ❌ `400` — regex rejects non-alpha characters | +| `originPrice: 0` | `""originPrice"": 0` | ❌ `400` — `""OriginPrice must be greater than 0.""` | +| `originPrice: -1` | `""originPrice"": -1` | ❌ `400` | +| `currentPrice: -1` | `""currentPrice"": -1` | ❌ `400` — `""CurrentPrice must be 0 or greater.""` | +| `stockCount: -1` | `""stockCount"": -1` | ❌ `400` | +| `priceAlertThreshold: 1.1` | `""priceAlertThreshold"": 1.1` | ❌ `400` — `""must be between 0.0 and 1.0""` | +| `priceAlertThreshold: -0.1` | `""priceAlertThreshold"": -0.1` | ❌ `400` | -**File:** `InventoryAlert.Worker/Handlers/PriceAlertHandler.cs` +> 🔍 **REVIEW:** `tickerSymbol` is declared as `string?` (nullable) in `ProductRequest.cs` but the validator treats it as required. Confirm the swagger UI does not allow submitting without it. Check if `null` body field passes validation. -Phase F (Telegram) is designed to plug `IAlertNotifier` into this handler. -The interface `IAlertNotifier` already exists in the Api project. -The handler currently just logs — the notifier injection should be wired now -so Phase F is a one-line swap (`ConsoleAlertNotifier` → `TelegramAlertNotifier`). +### TC-PROD-03 — Get All Products (Pagination) +```http +GET /api/products?pageNumber=1&pageSize=5 +``` +- ✅ `200 OK` with `PagedResult` shape: `{ items: [...], totalItems, pageNumber, pageSize }` +- ✅ Max page size is capped at `50` — test `?pageSize=999` returns only 50 items -`` -`csharp -// Suggested now -public class PriceAlertHandler( - IAlertNotifier notifier, - ILogger logger) - : IEventHandler -{ - public async Task HandleAsync(MarketPriceAlertPayload payload, CancellationToken ct = default) - { - var message = FormatMessage(payload); - _logger.LogWarning(""{AlertMessage}"", message); - await notifier.NotifyAsync(message, ct); // Phase F: no code change needed - } -} +### TC-PROD-04 — Get Product By ID (Cache Test) +```http +GET /api/products/{id} ← first call: DB hit +GET /api/products/{id} ← second call within 10 min: cache hit ``` +- ✅ Both return `200 OK` with identical body +- To verify cache: Add a DB breakpoint or Serilog trace showing cache miss/hit ---- +> 🔍 **REVIEW:** Cache TTL is hardcoded as `TimeSpan.FromMinutes(10)` in `ProductService.cs`. There is no configuration key for this. Consider externalizing it. -### E-3 · Propagate `CorrelationId` into SQS MessageAttributes +### TC-PROD-05 — Get Product By ID (Not Found) +```http +GET /api/products/99999 +``` +- ✅ `404 Not Found` -**File:** `InventoryAlert.Api/Infrastructure/Messaging/SnsEventPublisher.cs` +### TC-PROD-06 — Update Product (Full Overwrite) +```http +PUT /api/products/{id} +{ + ""name"": ""Apple iPhone 15 Pro"", + ""tickerSymbol"": ""AAPL"", + ""stockCount"": 80, + ""originPrice"": 1050.00, + ""currentPrice"": 1000.00, + ""priceAlertThreshold"": 0.15, + ""stockAlertThreshold"": 5 +} +``` +- ✅ `200 OK` with all fields updated +- ✅ Verify a subsequent `GET /api/products/{id}` returns new values (cache invalidated) -The `CorrelationId` is already in the `EventEnvelope` and written to SNS MessageAttributes. -But the `PollSqsJob` reads the envelope body — it doesn't validate that the SQS -`MessageAttribute[""CorrelationId""]` matches the envelope's `CorrelationId`. +### TC-PROD-07 — Update Non-Existent Product +```http +PUT /api/products/99999 +{ ... valid body ... } +``` +- ✅ `404 Not Found` -**Suggestion:** When writing telemetry to DynamoDB in `PollSqsJob`, also push the -`CorrelationId` into the structured log context: +> 🔍 **REVIEW:** The update currently throws `KeyNotFoundException` if not found, which is caught by `ExceptionHandlingMiddleware` and converted to `404`. But the middleware maps `KeyNotFoundException` → `404` only if explicitly handled. Verify this mapping is set up in `ExceptionHandlingMiddleware.cs`. -```csharp -using (_logger.BeginScope(new { envelope.CorrelationId, envelope.MessageId })) -{ - await handler(envelope.Payload, message.MessageId, ct); -} +### TC-PROD-08 — Delete Product +```http +DELETE /api/products/{id} ``` +- ✅ `204 No Content` +- ✅ Follow-up `GET /api/products/{id}` returns `404` -This makes logs traceable from API request → SNS publish → SQS → Worker handler. +### TC-PROD-09 — Delete Non-Existent Product +```http +DELETE /api/products/99999 +``` +- ✅ `404 Not Found` --- -### E-4 · Add `IMemoryCache` to Worker Handlers for Per-Symbol Dedup +## 📉 Section 3: Stock Count PATCH -**Current:** `PollSqsJob` handles Redis deduplication at the message level. -`EarningsHandler` and `NewsHandler` persist the same `EarningsRecord` multiple times -if the same earnings event arrives twice (e.g., SNS retry). +### TC-STOCK-01 — Valid Patch +```http +PATCH /api/products/{id}/stock?stockCount=50 +``` +- ✅ `200 OK` — returns full `ProductResponse` with `stockCount: 50` -**Fix:** Add a distributed cache check inside each persistence handler before writing: +### TC-STOCK-02 — Set Stock to Zero +```http +PATCH /api/products/{id}/stock?stockCount=0 +``` +- ✅ `200 OK` — `stockCount: 0` is valid (product exists but out of stock) -`` -`csharp -// EarningsHandler -var dedupKey = $""earnings:{payload.Symbol}:{payload.Period}""; -if (await _cache.GetStringAsync(dedupKey, ct) is not null) return; // skip duplicate -await _cache.SetStringAsync(dedupKey, ""1"", - new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24) }, ct); +### TC-STOCK-03 — Product Not Found +```http +PATCH /api/products/99999/stock?stockCount=10 ``` +- ✅ `404 Not Found` ---- +### TC-STOCK-04 — Negative Stock Count +```http +PATCH /api/products/{id}/stock?stockCount=-5 +``` +- 🔍 **REVIEW:** There is **no validator** for the `stockCount` query parameter in `UpdateStockCount`. The code directly assigns `existing.StockCount = stockCount;` — a value of `-5` will be persisted. Consider adding a guard: `if (stockCount < 0) return BadRequest(...)`. -### E-5 · `moto-init` — Add `init-dynamodb.sh` and Schema in Init Script +--- -The `PHASE2_PLAN.md` calls for `moto-init/init-dynamodb.sh` to create the -`inventory-event-logs` table. This file is in the git list but hasn't been reviewed. -The `docker-compose.yml` currently does NOT call `init-dynamodb.sh` — -it's missing from the `moto-init` entrypoint. +## 📈 Section 4: Finnhub Price Sync -**Needed in `docker-compose.yml`:** -```yaml -moto-init: - entrypoint: [""bash"", ""-c"", ""/moto-init/init-sqs.sh && /moto-init/init-dynamodb.sh""] +### TC-SYNC-01 — Manual Trigger +```http +POST /api/products/sync-price ``` +- ✅ `204 No Content` (runs synchronously, returns after completion) +- ✅ Check that `currentPrice` of products with valid tickers has been updated ---- - -## ✅ CONFIRMED PASSING (Updated) +> 🔍 **REVIEW:** The Docker `appsettings.Docker.json` has the Finnhub API key hardcoded: `""ApiKey"": ""d77d58hr01qp6afl79qgd77d58hr01qp6afl79r0""`. This is a **real API key committed to version control**. Even though `appsettings.Docker.json` may be gitignored, confirm with `git status` and `git log --all -- appsettings.Docker.json`. The key should be moved to a Docker secret or environment variable. -| Area | Check | -| :--- | :--- | -| Dispatcher pattern (`PollSqsJob`) | ✅ Dictionary + `UnknownEventHandler` fallback | -| Thin controllers (`ProductsController`) | ✅ Zero business logic | -| Transaction Capture (`ProductService`) | ✅ All 4 methods assign result inside lambda | -| DLQ / Retry logic | ✅ `ApproximateReceiveCount > 3` → DLQ | -| DynamoDB telemetry | ✅ Write on success + failure, 90-day TTL | -| `ILogger` everywhere | ✅ No `Console.WriteLine` found | -| Structured logging | ✅ Parameterized `{MessageId}`, `{EventType}` throughout | -| Primary constructors (most services) | ✅ Consistent across Api + Worker | -| `.AsNoTracking()` on reads | ✅ All read queries use it | -| `ExceptionHandlingMiddleware` | ✅ RFC-7807, no stack trace leakage | -| `EventTypes.All` O(1) registry | ✅ `IReadOnlySet` HashSet | -| `CorrelationIdMiddleware` ordering | ✅ First in pipeline | -| Serilog bootstrap | ✅ Both API + Worker with `try/finally + CloseAndFlush()` | -| `EventEnvelope` as `record` | ✅ Immutable, correct field comments | -| `AlertConstants` structure | ✅ `CacheKeys`, `SqsHeaders` cleanly separated | -| Sample project dual-mode (API + direct SNS) | ✅ Demonstrates both publish paths | -| `HangfireJobLoggingFilter` | ✅ Routes failures through `ILogger`, `NullLogger` fallback | -| CI pipeline architecture test gate | ✅ `ArchitectureTests` run before build |",682,fb64583e3f4984ee72572776c7e5b729,doc\archive\AUDIT_PLAN.md,0,302,"result, public, init, return, value, error, correlationid, build",1775368171.535382,455,infrastructure mock setup price drop external api savechangesasync fluentassertions productscontroller item data access domain driven design aapl returns async stock price dbset inventory iactionresult hosted service dockerfile notification postgres efcore savechanges domain entity compose commit appdbcontext backgroundservice threshold arrange act assert httpget stock ticker httppost periodictimer stock googl asnotracking application layer unitofwork executetransactionasync symbol sku iproductrepository xunit entity framework httpput container market data iproductservice rollback unit test loss igenericrepository times once verify dbcontext business logic msft postgresql quote finnhubpricesyncworker iunitofwork atomicity moq application service productservice,# Build failure is discovered AFTER expensive test runs | Build failure is discovered AFTER expensive test runs - name: Architecture Test -doc,"# Build Guide: Temporal Action Queue +### TC-SYNC-02 — Invalid Ticker Symbol +- Create a product with `tickerSymbol: ""XXXINVALID""` +- Trigger `POST /api/products/sync-price` +- ✅ `204 No Content` — the invalid ticker is **skipped** (not an error) +- ✅ Log file contains: `[ProductService] Null or zero price returned for XXXINVALID. Skipping.` -This guide provides a detailed, step-by-step walkthrough to build the **Temporal Action Queue** project from scratch using .NET 9. +### TC-SYNC-03 — Scheduled Auto-Sync +- Configured in `appsettings.Docker.json → MinuteSyncCurrentPrice: 10` +- ✅ After 10 minutes, `currentPrice` updates automatically without manual trigger +- 🔍 **REVIEW:** Confirm the `MinuteSyncCurrentPrice` setting is actually read and applied to the Hangfire job cron expression in the Worker's `Program.cs`. --- -## Phase 1: Environment Setup +## 🚨 Section 5: Price Loss Alerts -### 1. Initialize the Project -Create a new Web API project with Controllers. -```bash -dotnet new webapi -n JobQueue.Api -o . --use-controllers --no-https -``` +### Setup for this section: +Create a product with `originPrice: 1000`, `currentPrice: 700`, `priceAlertThreshold: 0.2`. +- Drop% = (700-1000)/1000 = -0.3 → 30% loss → **exceeds** 20% threshold → should alert. -### 2. Add Dependencies -Install the required Entity Framework Core packages for PostgreSQL. -```bash -dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL -dotnet add package Microsoft.EntityFrameworkCore.Design +### TC-ALERT-01 — Product Triggering Alert +```http +GET /api/products/price-alerts ``` +- ✅ `200 OK` — response array includes the product above +- ✅ `priceChangePercent` ≈ `-0.3000` +- ✅ `priceDiff` = `300.00` +### TC-ALERT-02 — Product Below Threshold (No Alert) +- Create product with `originPrice: 1000`, `currentPrice: 850`, `priceAlertThreshold: 0.2` +- Drop% = 15% < 20% threshold +- ✅ This product does **not** appear in the alert response ---- +### TC-ALERT-03 — Cooldown Gate (60-Minute Spam Prevention) +- Trigger `GET /api/products/price-alerts` twice in 60 minutes for the same product +- Both should return the product in the list (the endpoint only **reads**, it doesn't update `LastAlertSentAt`) +- 🔍 **REVIEW:** `LastAlertSentAt` is **never written** by `GetPriceLossAlertsAsync`. The cooldown check reads `LastAlertSentAt` but nothing in the codebase sets it. This means the cooldown gate is **permanently bypassed** — it will always pass the `if (product.LastAlertSentAt.HasValue...)` check because `HasValue` is always `false`. Needs implementation. -## Phase 2: Core Data Infrastructure +### TC-ALERT-04 — Zero Price Edge Case +- Set `currentPrice: 0` or `originPrice: 0` +- ✅ Product is **skipped** — no alert produced (guarded by `if (product?.CurrentPrice is 0 || product?.OriginPrice is 0) continue`) -### 3. Create the Job Model -Create `Models/ScheduledJob.cs`. This entity defines what a task looks like in the database. -```csharp -namespace JobQueue.Api.Models; +--- -public class ScheduledJob +## 📨 Section 6: Event Publishing + +### TC-EVENT-01 — Generic Event Publish +```http +POST /api/events { - public Guid Id { get; set; } = Guid.NewGuid(); - public string TaskName { get; set; } = string.Empty; - public DateTime ScheduledAt { get; set; } - public bool IsProcessed { get; set; } - public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + ""eventType"": ""inventoryalert.pricing.price-drop.v1"", + ""payload"": { ""productId"": 1, ""symbol"": ""AAPL"", ""dropPercent"": 0.25 } } ``` +- ✅ `202 Accepted` +- ✅ Record appears in `GET /api/events/logs/inventoryalert.pricing.price-drop.v1` -### 4. Setup the Database Context -Create `Data/AppDbContext.cs`. We use a **Primary Constructor** for the options. -```csharp -using Microsoft.EntityFrameworkCore; -using JobQueue.Api.Models; - -namespace JobQueue.Api.Data; +### TC-EVENT-02 — Missing EventType +```http +POST /api/events +{ ""eventType"": """", ""payload"": {} } +``` +- ✅ `400 Bad Request` — `""EventType is required.""` -public class AppDbContext(DbContextOptions options) : DbContext(options) +### TC-EVENT-03 — Manual Market Alert +```http +POST /api/events/market-alert { - public DbSet Jobs => Set(); + ""productId"": 1, + ""symbol"": ""AAPL"", + ""originPrice"": 950.00, + ""currentPrice"": 700.00, + ""dropPercent"": 0.263 } ``` +- ✅ `202 Accepted` +- ✅ Worker logs `🚨 PRICE DROP ALERT` in container output ---- +### TC-EVENT-04 — News Alert +```http +POST /api/events/news-alert +{ + ""symbol"": ""TSLA"", + ""headline"": ""Tesla recalls 500,000 vehicles"", + ""source"": ""Reuters"", + ""url"": ""https://reuters.com/article/example"", + ""publishedAt"": ""2026-04-05T06:00:00Z"" +} +``` +- ✅ `202 Accepted` +- ✅ Worker `NewsHandler` persists `NewsRecord` to PostgreSQL -## Phase 3: The Engine (Background Job) - -### 5. Create the Worker Service -Create `Services/JobProcessorService.cs`. -**CRITICAL**: Background services are singletons. To use a scoped `DbContext`, you must manually create a scope using `IServiceProvider`. - -```csharp -using JobQueue.Api.Data; -using Microsoft.EntityFrameworkCore; - -namespace JobQueue.Api.Services; +### TC-EVENT-05 — List Supported Event Types +```http +GET /api/events/types +``` +- ✅ Returns all 5 event type strings: + ```json + [ + ""inventoryalert.pricing.price-drop.v1"", + ""inventoryalert.inventory.stock-low.v1"", + ""inventoryalert.fundamentals.earnings.v1"", + ""inventoryalert.fundamentals.insider-sell.v1"", + ""inventoryalert.news.headline.v1"" + ] + ``` -public class JobProcessorService(IServiceProvider serviceProvider, ILogger logger) : BackgroundService -{ - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - while (!stoppingToken.IsCancellationRequested) - { - logger.LogInformation(""Polling for due tasks...""); +### TC-EVENT-06 — Query Event Logs +```http +GET /api/events/logs/inventoryalert.pricing.price-drop.v1?limit=5 +``` +- ✅ Returns up to 5 DynamoDB log entries for that event type - using (var scope = serviceProvider.CreateScope()) - { - var context = scope.ServiceProvider.GetRequiredService(); +> 🔍 **REVIEW:** Sending an **unknown event type** to `POST /api/events` (e.g. `""eventType"": ""foo.bar""`) is accepted and dispatched to SNS — no validation against `EventTypes.All` occurs at the controller level. The Worker's `UnknownEventHandler` will discard it, but it still pollutes the audit log. Consider adding `if (!EventTypes.IsKnown(request.EventType)) return BadRequest(...)`. - var dueJobs = await context.Jobs - .Where(j => !j.IsProcessed && j.ScheduledAt <= DateTime.UtcNow) - .ToListAsync(stoppingToken); +--- - foreach (var job in dueJobs) - { - logger.LogInformation(""Executing Job: {Name}"", job.TaskName); - await Task.Delay(1000, stoppingToken); // Simulate work - job.IsProcessed = true; - } +## 🔄 Section 7: Worker SQS Consumer (End-to-End) - if (dueJobs.Any()) await context.SaveChangesAsync(stoppingToken); - } +### TC-WORKER-01 — Full Pipeline Smoke Test +1. Publish an event via `POST /api/events/market-alert` +2. Watch Worker Docker logs for: `🚨 PRICE DROP ALERT Symbol: AAPL` +3. ✅ Event flows: API → SNS (Moto) → SQS → PollSqsJob → PriceAlertHandler → log - await Task.Delay(30000, stoppingToken); // Wait 30 seconds - } - } +### TC-WORKER-02 — Earnings Event Persistence +1. Publish: +```http +POST /api/events +{ + ""eventType"": ""inventoryalert.fundamentals.earnings.v1"", + ""payload"": { + ""symbol"": ""AAPL"", + ""period"": ""Q1 2026"", + ""actualEPS"": 2.18, + ""estimatedEPS"": 2.10, + ""surprisePercent"": 3.8 + } } ``` +2. ✅ Worker `EarningsHandler` persists `EarningsRecord` to PostgreSQL +3. ✅ Verify via direct DB: `SELECT * FROM ""EarningsRecords"";` ---- +### TC-WORKER-03 — DLQ Escalation +- Temporarily break the Worker handler (e.g. comment out DB save, throw exception) +- Publish an event +- After 3 retries ✅ message appears in `inventory-event-dlq` +- 🔍 **REVIEW:** There is no monitoring or alerting on DLQ depth. If messages pile up in the DLQ, no one is notified. Consider adding a CloudWatch alarm (or Moto-equivalent) for `ApproximateNumberOfMessagesNotVisible > 0`. -## Phase 4: API & Registration +--- -### 6. Create the Controller -Create `Controllers/JobsController.cs` to handle incoming requests. -```csharp -[ApiController] -[Route(""api/[controller]"")] -public class JobsController(AppDbContext context) : ControllerBase -{ - [HttpGet] - public async Task GetJobs() => - Ok(await context.Jobs.AsNoTracking().OrderByDescending(j => j.CreatedAt).ToListAsync()); +## 📊 Section 8: Bulk Insert - [HttpPost] - public async Task CreateJob([FromBody] CreateJobRequest r) - { - var job = new ScheduledJob { TaskName = r.Name, ScheduledAt = r.ExecuteAt }; - context.Jobs.Add(job); - await context.SaveChangesAsync(); - return CreatedAtAction(nameof(GetJobs), new { id = job.Id }, job); - } -} -public record CreateJobRequest(string Name, DateTime ExecuteAt); +### TC-BULK-01 — Valid Bulk Insert +```http +POST /api/products/bulk +[ + { ""name"": ""Tesla Part A"", ""tickerSymbol"": ""TSLA"", ""stockCount"": 50, ""originPrice"": 200.00, ""currentPrice"": 190.00, ""priceAlertThreshold"": 0.1, ""stockAlertThreshold"": 5 }, + { ""name"": ""Microsoft Mouse"", ""tickerSymbol"": ""MSFT"", ""stockCount"": 200, ""originPrice"": 30.00, ""currentPrice"": 28.00, ""priceAlertThreshold"": 0.15, ""stockAlertThreshold"": 20 } +] ``` +- ✅ `204 No Content` +- ✅ Follow-up `GET /api/products` shows new items -### 7. Configure Dependency Injection -Update `Program.cs` to link everything together. -```csharp -builder.Services.AddDbContext(options => - options.UseNpgsql(""Host=localhost;Database=jobsdb;Username=postgres;Password=password"")); - -builder.Services.AddHostedService(); +### TC-BULK-02 — Bulk Insert with One Invalid Item +```http +POST /api/products/bulk +[ + { ""name"": ""Valid Product"", ""tickerSymbol"": ""GOOG"", ... }, + { ""name"": """", ""tickerSymbol"": ""AAPL"", ... } ← invalid: empty name +] +``` +- 🔍 **REVIEW:** FluentValidation rules apply per-item in a collection via `RuleForEach`. Verify whether `BulkInsertProductsAsync` triggers FluentValidation or bypasses it (the validation filter operates at the Controller level on the outer `IEnumerable`, not per-item). If one item is invalid, is the whole batch rejected or does it partially insert? -// Enable Static Files for the Dashboard -app.UseDefaultFiles(); -app.UseStaticFiles(); +### TC-BULK-03 — Empty Bulk Insert +```http +POST /api/products/bulk +[] ``` +- 🔍 **REVIEW:** Empty array → `AddRangeAsync([])` → likely a no-op. Should return `204` or `400`? Currently no guard for empty list. --- -## Phase 5: The Interface (Dashboard) +## 🔍 Summary: All Items Needing Human Review -### 8. Create the Frontend -1. Create a `wwwroot` folder. -2. Create `wwwroot/index.html` with a modern Glassmorphism theme (refer to the project files for the full HTML/CSS/JS). -3. The dashboard connects to `/api/jobs` via JavaScript `fetch`. +| ID | Location | Issue | Priority | +| --- | ----------------------------------------------- | -------------------------------------------------------------------------- | -------- | +| A | `AuthController.cs:26-27` | `admin`/`admin123` fallback always active if config missing | 🔴 High | +| B | `appsettings.Docker.json:7` | Real Finnhub API key possibly committed in git history | 🔴 High | +| C | `ProductsController.cs` — `UpdateStockCount` | No validation on negative `stockCount` query param | 🟡 Medium | +| D | `ProductService.cs` — `GetPriceLossAlertsAsync` | `LastAlertSentAt` cooldown is never written — gate always bypassed | 🟡 Medium | +| E | `EventsController.cs` — `PublishEvent` | Unknown event types accepted without validation against `EventTypes.All` | 🟡 Medium | +| F | `ProductService.cs:55` | Cache TTL (10 min) is hardcoded — no config key | 🟢 Low | +| G | No health endpoint | No `/health` or `/ready` probe for Docker orchestration | 🟢 Low | +| H | `ProductRequest.cs:7` | `TickerSymbol` is `string?` (nullable) but validator treats it as required | 🟢 Low | +| I | `TC-BULK-02` / `TC-BULK-03` | Validation behavior for bulk insert edge cases unverified | 🟢 Low | +| J | DLQ monitoring | No alerting on dead-letter queue depth | 🟢 Low | +| K | `MinuteSyncCurrentPrice` | Verify setting is actually wired into Hangfire cron in Worker `Program.cs` | 🟢 Low |",402,af2691d2a74862064a1fa4343331670d,doc\archive\MANUAL_TESTING.md,0,325,"product, event, review, docker, alert, worker, section, bulk",1779851803.8737533,10,symbol iproductservice httppost appdbcontext stock ticker item stock container iactionresult productservice dbcontext entity framework msft external api application service market data inventory notification postgresql loss efcore business logic unit test xunit httpget googl periodictimer httpput finnhubpricesyncworker quote dockerfile postgres fluentassertions threshold sku price drop stock price arrange act assert productscontroller backgroundservice aapl asnotracking compose hosted service,# 🧪 Manual Testing & Review Guide | 🧪 Manual Testing & Review Guide > How to use this document: > - ✅ = Expected pas +doc,"--- +description: System modernization plan for UI, logging, and shared project audit +type: plan +status: completed +version: 1.1 +tags: [modernization, ui, logging, ddd] +last_updated: 2026-04-05 +---",9,8b5729fb8041d9f565881dc7ccd083bd,doc\archive\MODERNIZATION_PLAN.md,0,326,"modernization, plan, logging, description, system, shared, project, audit",1775670503.9180853,1,backgroundservice finnhubpricesyncworker loss price drop business logic domain entity infrastructure domain driven design iproductservice hosted service productservice application service periodictimer threshold notification application layer,"MODERNIZATION_PLAN.md | --- description: System modernization plan for UI, logging, and shared project a" +doc,"# 🏛️ System Modernization & UI Plan ---- +> **Status: ✅ COMPLETE** — Archived on 2026-04-05. +> All phases implemented. See `ROADMAP.md` for remaining open tasks (P4+). -## Phase 6: Deployment & Runtime +--- -### 9. Database Migrations -Initialize the database using the EF Core CLI tool. -```bash -dotnet ef migrations add InitialCreate -dotnet ef database update -``` +## Summary of Delivered Work -### 10. Run the project -```bash -dotnet run -``` -Your dashboard will be available at `http://localhost:5000`. +| Phase | Component | Status | +| :--- | :--- | :--- | +| Phase 1 | Serilog bootstrapped in `Worker/Program.cs` | ✅ Done | +| Phase 1 | `ILogger` as injection interface across all services | ✅ Done | +| Phase 1 | `CorrelationIdMiddleware` — stamps every request + log | ✅ Done | +| Phase 1 | `ExceptionHandlingMiddleware` — full RFC-7807 compliance | ✅ Done | +| Phase 1 | `HangfireJobLoggingFilter` — global Worker job error auditing | ✅ Done | +| Phase 2 | `Contracts/Constants/AlertConstants.cs` — centralized constants | ✅ Done | +| Phase 2 | All entities and DTOs verified in `InventoryAlert.Contracts` | ✅ Done | +| Phase 3 | `wwwroot/index.html` — SPA with Sidebar + 4 views | ✅ Done | +| Phase 3 | `wwwroot/css/dashboard.css` — Dark Glassmorphism theme | ✅ Done | +| Phase 4 | `wwwroot/js/dashboard.js` — Fetch polling, live search, sync | ✅ Done | --- -## Advanced Practice Goals -- **Status Enum**: Change `IsProcessed` to `Pending`, `Running`, `Completed`. -- **Error Handling**: What if the database connection fails in the worker? Wrap the scope in a `try-catch`. -- **Cancellation**: Add a `DELETE` endpoint to cancel scheduled tasks.",173,a820b13e5f1592f716128f72bd533b6a,doc\archive\BACKGROUND_JOB_REFER.md,0,303,"create, phase, project, database, using, core, dashboard, build",1775670503.910183,1,iactionresult asnotracking infrastructure finnhubpricesyncworker domain driven design dbcontext hosted service add-migration efcore application service application layer schema change entity framework database update httppost httpput productscontroller domain entity periodictimer httpget backgroundservice iproductservice productservice appdbcontext efcore migration business logic,"# Build Guide: Temporal Action Queue | Build Guide: Temporal Action Queue This guide provides a detailed, step-by-step " -doc,"# Coding Challenge: Automated Inventory Alert System - -## 🎯 Objective - -Build a C# Web API that monitors product stock levels and generates alerts when they fall below a certain threshold. +## Files Created / Modified -## 🏗️ Requirements +```text +InventoryAlert.Api/ +├── Program.cs ← CorrelationId + UseStaticFiles registered +├── Web/Middleware/ +│ ├── ExceptionHandlingMiddleware.cs ← RFC-7807: instance + semantic type URI +│ └── CorrelationIdMiddleware.cs ← NEW: X-Correlation-Id stamping +└── wwwroot/ ← NEW: Static dashboard + ├── index.html + ├── css/dashboard.css + └── js/dashboard.js -### 1. The Entity: `Product` +InventoryAlert.Worker/ +├── Program.cs ← Serilog bootstrap (File + Console sinks) +└── Filters/HangfireJobLoggingFilter.cs ← NEW: Global Hangfire job error filter -| Property | Type | Description | -| :---------------- | :---------- | :------------------------------------ | -| `Id` | `int` | Primary Key | -| `Name` | `string` | Unique name of the product | -| `StockCount` | `int` | Current units available | -| `AlertThreshold` | `int` | Trigger level for an alert | -| `LastAlertSentAt` | `DateTime?` | Timestamp of the last processed alert | +InventoryAlert.Contracts/ +└── Constants/AlertConstants.cs ← NEW: EventTypes, CacheKeys, SqsHeaders +``` -### 2. Business Logic (API) +> **Next Action:** See `ROADMAP.md` P4+ for performance, security, and CI/CD tasks.",55,8b5729fb8041d9f565881dc7ccd083bd,doc\archive\MODERNIZATION_PLAN.md,0,327,"phase, done, wwwroot, status, roadmap, tasks, worker, contracts",1775670503.9180853,10,backgroundservice finnhubpricesyncworker loss price drop business logic domain entity infrastructure domain driven design iproductservice hosted service productservice application service periodictimer threshold notification application layer,# 🏛️ System Modernization & UI Plan | 🏛️ System Modernization & UI Plan > Status: ✅ COMPLETE — Archived on 2026-04-05 +doc,"--- +description: Audit of repository naming, project locations, and documentation structure alignment. +type: reference +status: draft +version: 1.1 +tags: [audit, naming, structure, documentation, inventoryalert] +last_updated: 2026-04-30 +---",9,4968a62d6e771344e6d26be1be78715c,doc\archive\naming_and_structure_audit.md,0,328,"audit, naming, documentation, structure, description, repository, project, locations",1779851803.8540256,1,unit test httppost igenericrepository item iproductrepository productservice price drop appdbcontext threshold business logic loss application service efcore sku inventory entity framework productscontroller periodictimer dbset data access stock httpput finnhubpricesyncworker iproductservice notification fluentassertions httpget arrange act assert backgroundservice dockerfile dbcontext postgres postgresql asnotracking hosted service xunit iactionresult compose container,"naming_and_structure_audit.md | --- description: Audit of repository naming, project locations, and documentatio" +doc,"# Naming & Project Location Audit -Implement a RESTful API to manage your inventory: +## Verification Snapshot (as of 2026-04-30) -- `POST /api/products`: Add a new product. -- `PUT /api/products/{id}/stock`: Update the stock count. -- `GET /api/products/low-stock`: View all products currently below threshold. +Checked against the current workspace contents: -### 3. The Engine (Background Job) +- Top-level layout matches the documented structure: `.agents/`, `doc/`, `InventoryManagementSystem/`, `InventoryAlert.UI/`, `InventoryAlert.Wiki/`. +- Solution file exists at `InventoryManagementSystem/InventoryManagementSystem.sln`. +- The listed `.csproj` projects exist under `InventoryManagementSystem/` (Api/Domain/Infrastructure/Worker + test projects + Sample). +- API route prefixes are `/api/v1/...` (controllers use `Route(""api/v1/[controller]"")`). +- Historical `InventoryAlert.Contracts` references still exist under `doc/archive/` and in `.gitignore` (coverage artifacts), as expected for archived/historical content. -Implement a `BackgroundService` that: +## Canonical Naming Standard (Recommended) -- Runs every **5 minutes**. -- Scans the database for products where `StockCount <= AlertThreshold`. -- **Constraint**: To prevent log spam, only log the alert if `LastAlertSentAt` is null OR more than **1 hour ago**. -- Update the `LastAlertSentAt` once the alert is triggered/logged. +Use **one umbrella name** for the repository and solution, and keep **InventoryAlert** as the application/product name. -### 4. Persistence +- **GitHub repo name (canonical):** `InventoryManagementSystem` +- **Local root folder (canonical):** `InventoryManagementSystem` (this workspace root currently contains the `InventoryManagementSystem/` solution folder) +- **.NET solution name:** `InventoryManagementSystem.sln` +- **Application name:** `InventoryAlert` + - Backend projects: `InventoryAlert.Api`, `InventoryAlert.Domain`, `InventoryAlert.Infrastructure`, `InventoryAlert.Worker` + - Test projects: `InventoryAlert.UnitTests`, `InventoryAlert.IntegrationTests`, `InventoryAlert.E2ETests`, `InventoryAlert.ArchitectureTests` + - Frontend app: `InventoryAlert.UI` + - Documentation site: `InventoryAlert.Wiki` -- Use **PostgreSQL** with **Entity Framework Core**. +### Visualization -- Ensure migrations are applied successfully. +```mermaid +flowchart TB + Repo[""GitHub repo: InventoryManagementSystem""] --> Root[""Local workspace root""] -### 5. External Price Fetching (Finnhub) + Root --> Soln[""InventoryManagementSystem/InventoryManagementSystem.sln""] + Root --> UI[""InventoryAlert.UI (Next.js app)""] + Root --> Wiki[""InventoryAlert.Wiki (Docusaurus site)""] + Root --> Docs[""doc/ (internal docs)""] + Root --> Agents["".agents/ (agent tooling + BM25)""] -Integrate with the **Finnhub Stock API** to: + Soln --> Api[""InventoryAlert.Api""] + Soln --> Domain[""InventoryAlert.Domain""] + Soln --> Infra[""InventoryAlert.Infrastructure""] + Soln --> Worker[""InventoryAlert.Worker""] + Soln --> Tests[""Tests""] -- Add a property `TickerSymbol` to the `Product` entity. -- Implement a background process to fetch the current market price for each symbol. -- **Challenge**: If the market price is SIGNIFICANTLY higher than the original cost (e.g., > 20% increase), create a ""High Value"" alert even if stock is plentiful. + Tests --> Unit[""InventoryAlert.UnitTests""] + Tests --> IT[""InventoryAlert.IntegrationTests""] + Tests --> E2E[""InventoryAlert.E2ETests""] + Tests --> Arch[""InventoryAlert.ArchitectureTests""] +``` ---- +### Why this standard -## 🛠️ Tech Stack & Standards +- Prevents “multiple names for one system” drift (`InventoryManagementSystem` vs `InventoryAlert`). +- Keeps solution-level naming stable while allowing multiple apps/modules under the umbrella. +- Makes docs and onboarding clearer: umbrella = repo/solution, product = app. -- **Framework**: .NET 8 or 9 -- **DB**: Npgsql.EntityFrameworkCore.PostgreSQL +## Scope -- **DI**: Remember to handle the **Scoped-in-Singleton** context issue correctly! -- **Clean Code**: Use Primary Constructors where possible. -- **Messaging**: Motor (for SNS/SQS abstraction) and Hangfire (for distributed job management). +This document evaluates whether repository naming and file locations match the current solution structure, and records recommended conventions for docs and folders. ---- +## Current Repository Top-Level Layout -## 🧠 Practice Tasks +| Path | Purpose | Notes | +| ---------------------------- | ------------------------------ | ----------------------------------------------------------------------- | +| `.agents/` | Agent workflows/skills/scripts | BM25 tooling lives in `.agents/scripts/core/`. | +| `doc/` | Working internal documentation | Should use YAML frontmatter (see `/doc` skill standard). | +| `InventoryManagementSystem/` | .NET solution root | Contains `InventoryManagementSystem.sln` and all `.csproj`. | +| `InventoryAlert.UI/` | Next.js UI | Frontend app; has its own `package.json`. | +| `InventoryAlert.Wiki/` | Docusaurus documentation site | Built output in `InventoryAlert.Wiki/build` (should remain gitignored). | -1. **Project Initialization**: Build the standard Web API structure yourself. -2. **Concurrency**: What happens if the background job is running while an API request updates the stock? Consider how EF Core handles tracking. -3. **Resilience**: Add a `try-catch` inside your worker. If the service fails to connect to the database, it should back off and try again in 30 seconds. -4. **Distributed Messaging**: Implement **Motor** to push ""Low Stock"" events to **AWS SNS/SQS** topics. -5. **Robust Scheduling**: Move the inventory check job from `BackgroundService` to **Hangfire** to support persistence, retries, and a dashboard monitor. +## .NET Solution Structure (`InventoryManagementSystem/`) -_Note: Your previous work has been moved to the `/refer` folder for reference._",71,5b52d4fd44c2049d191d7317705253a2,doc\archive\challenge.md,0,304,"stock, alert, product, products, implement, inventory, entity, lastalertsentat",1775670503.924312,1,stock price symbol external api efcore migration stock ticker aapl application service hosted service asnotracking entity framework stock market data database update appdbcontext finnhubpricesyncworker inventory loss periodictimer sku msft googl productservice efcore quote threshold add-migration backgroundservice iproductservice item price drop schema change business logic notification dbcontext,# Coding Challenge: Automated Inventory Alert System | Coding Challenge: Automated Inventory Alert System 🎯 Objective Build a C Web AP -doc,"# 🔍 Code Review & Technical Debt (TODOs) +**Solution file** +- `InventoryManagementSystem/InventoryManagementSystem.sln` -This document summarizes the architectural, security, and performance gaps identified during a deep code review. Inline `// TODO: [Enhancement]` and `// TODO: [Bug]` comments have been injected directly into the source code to track these issues alongside the implementation. +**Projects (observed `.csproj`)** +- `InventoryManagementSystem/InventoryAlert.Api/InventoryAlert.Api.csproj` +- `InventoryManagementSystem/InventoryAlert.Domain/InventoryAlert.Domain.csproj` +- `InventoryManagementSystem/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj` +- `InventoryManagementSystem/InventoryAlert.Worker/InventoryAlert.Worker.csproj` +- `InventoryManagementSystem/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj` +- `InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj` +- `InventoryManagementSystem/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj` +- `InventoryManagementSystem/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj` +- `InventoryManagementSystem/InventoryAlert.Sample/InventoryAlert.Sample.csproj` -## 1. Security & Authentication +**Naming convention check** +- Project folders use `InventoryAlert.` (PascalCase) and match `.csproj` names: OK. +- Shared kernel is `InventoryAlert.Domain` (not `InventoryAlert.Contracts`): ensure non-archive docs match this. -- **Hardcoded Fallback Credentials (`AuthController.cs`)**: If the `Auth:Username` and `Auth:Password` settings are missing from the configuration (e.g., missed environment variables in Docker), the system currently falls back to `admin`/`admin123`. This exposes the application to unintended access. - - *Action Required*: Remove the fallback. Throw a startup exception or return a 500 error if secure credentials are not supplied via configuration. +## Frontend App Structure (`InventoryAlert.UI/`) -## 2. Concurrency & Atomicity +| Path | Purpose | +| -------------------------------- | --------------------- | +| `InventoryAlert.UI/src/` | Next.js app code | +| `InventoryAlert.UI/public/` | Static assets | +| `InventoryAlert.UI/package.json` | Frontend scripts/deps | -- **Lost Update Hazard (`ProductService.cs - UpdateStockCountAsync`)**: The method requests the product entity using `GetByIdAsync`, mutates the stock count, and then saves it via `UpdateAsync`. Any concurrent modifications to other properties (e.g., the background background price sync mutating `CurrentPrice`) will be blindly overwritten. - - *Action Required*: Use an intentional update technique like explicit column updating (`ExecuteUpdateAsync`), or introduce optimistic concurrency (`RowVersion` / Concurrency Token) on the `Product` entity. -- **Race Condition in Message Dedup (`PollSqsJob.cs`)**: The deduplication logic uses `GetStringAsync()` to check for previous processing, and then later (outside the critical path) uses `SetStringAsync()` to persist it. This creates a race condition for duplicates arriving simultaneously. - - *Action Required*: Use an atomic operation like Redis `SET ... NX` (Set Not Exists). +**Naming convention check** +- `InventoryAlert.UI` matches product name and avoids conflicting with `.NET` projects: OK. +- `src/` and `public/` are standard Next.js structure: OK. -## 3. Validation & Edge Cases +## Wiki Site Structure (`InventoryAlert.Wiki/`) -- **Bulk Insert Validation (`ProductService.cs - BulkInsertProductsAsync`)**: - - *Issue 1*: FluentValidation does not automatically validate the internal elements of an `IEnumerable` payload at the controller level unless explicitly wired up with `RuleForEach`. The current implementation trusts the bulk payload completely. - - *Issue 2*: There is no guard tracking empty lists (`!requests.Any()`). Passing an empty array executes a pointless database transaction. - - *Action Required*: Implement a manual validator pass or a collection wrapper for validation, and add a quick empty guard. +| Path | Purpose | +| --------------------------------- | -------------------------------------------- | +| `InventoryAlert.Wiki/docs/` | Docusaurus docs source (what we should edit) | +| `InventoryAlert.Wiki/sidebars.ts` | Autogenerated sidebar config | +| `InventoryAlert.Wiki/build/` | Generated static site output | -## 4. Performance & Scalability (Worker) +**Naming convention check** +- `docs/` subfolders use ordered prefixes like `04-execution-flows`: OK for navigation. +- `build/` should remain ignored by Git (see `InventoryAlert.Wiki/.gitignore`): OK. -- **N+1 External IO inside Loops (`SyncPricesJob.cs`, `EarningsCheckJob.cs`, `NewsCheckJob.cs`, `InsiderTxCheckJob.cs`)**: Each Hangfire background worker retrieves all products using `ToListAsync()` pulling an unbounded dataset into memory, followed by executing a sequential Finnhub HTTP API call `await Fetch(...)` per product inside a `foreach` loop. If there are thousands of products, this will lead to unbounded memory allocation, prolonged job durations, blocking threads, and immediate violation of Finnhub's generic rate limits (60 requests/min). - - *Action Required*: Change `ToListAsync()` to database batching, implement a parallel fan-out API caller (`Task.WhenAll`), and employ `SemaphoreSlim` and `Task.Delay` logic to enforce Finnhub's rate limit. +## `doc/` Folder Conventions (Internal Docs) -## 5. Configuration Defaults +Recommended conventions for **new** files: +- Filenames: prefer `snake_case.md` for internal specs/plans (matches existing style like `feature_audit.md`). +- Add YAML frontmatter header to every `doc/*.md` (required by `/doc` workflow). +- Keep anything superseded in `doc/archive/` and treat archive as historical (may contain stale names/paths). -- **Hardcoded Job CRON (`JobSchedulerService.cs`)**: The price sync Hangfire job is scheduled with a hardcoded `""*/10 * * * *""` cron expression (every 10 minutes). It completely ignores the `MinuteSyncCurrentPrice` config parameter available in `appsettings.json`. - - *Action Required*: Inject `IConfiguration` into the JobSchedulerService, dynamically calculate the CRON string based on the configuration value. -- **Hardcoded Cache TTL (`ProductService.cs`)**: `GetProductByIdAsync` sets the cache TTL permanently to 10 minutes. - - *Action Required*: Move the TTL interval to `appsettings.json`. +## Known Mismatches / Drift (Observed) -## 6. Observability & Logging +### 1) Legacy name: `InventoryAlert.Contracts` (archive) -- **Missing Liveness Probes (`Program.cs`)**: In containerized environments like Docker or Kubernetes, there is no way for the orchestrator to know if the C# application is actually healthy, routing traffic normally, or silently hung in a deadlock. - - *Action Required*: Integrate ASP.NET HealthChecks (`builder.Services.AddHealthChecks()`) and map an endpoint `app.MapHealthChecks(""/health"")`. -- **Inappropriate Logging Strategy (`FinnhubClient.cs`)**: Error logging writes directly to STDOUT using `Console.WriteLine()`, bypassing the highly configurable Serilog provider. - - *Action Required*: Inject `ILogger` and write structural logs using standard `_logger.LogError(...)`. -- **Leaked Capture Variable Warning (`SyncPricesJob.cs`)**: The class constructor injects `cache` while mapping it to `_cache`. However, the variable `cache` is referenced explicitly at line 62, creating a compiler state capture warning (CS9124). - - *Action Required*: Convert the direct parameter reference to the internal `_cache` field reference.",43,172fac1a4d3444652650da8ca5109234,doc\archive\CODE_REVIEW_TODOS.md,0,305,"action, required, hardcoded, configuration, using, cache, code, into",1775670503.9112332,1,postgresql fluentassertions commit dockerfile unit test stock price productservice postgres productscontroller stock hosted service inventory iproductservice rollback finnhubpricesyncworker container dbcontext httpput appdbcontext asnotracking httppost backgroundservice item application service efcore httpget xunit arrange act assert entity framework business logic sku atomicity unitofwork quote compose iactionresult periodictimer external api market data savechanges,# 🔍 Code Review & Technical Debt (TODOs) | 🔍 Code Review & Technical Debt (TODOs) This document summarizes the architectura -doc,"# 🔬 DDD Refactoring Audit — Progress Tracker -## Naming Conventions, File Locations & Structure +Many files under `doc/archive/` still reference the historical `InventoryAlert.Contracts` project name. This is expected if archive is treated as historical, but should not be used as current guidance. ---- +**Recommendation** +- Keep `doc/archive/` as-is, but ensure any “active” doc points to `InventoryAlert.Domain`. -## ✅ Step 1 — Create missing folders +### 2) API version label (“v1” vs “v2”) -| Folder | Status | -| :--- | :--- | -| `Domain/Interfaces/` | ✅ Created | -| `Domain/Events/` | ✅ Created | -| `Infrastructure/Persistence/Configurations/` | ✅ Created | -| `Web/Controllers/` | ✅ Created | -| `Web/Configuration/` | ✅ Created | -| `Web/Middleware/` | ⬜ Phase 2 (GlobalExceptionHandler) | +API routes in code are prefixed with `/api/v1/...` (controllers use `Route(""api/v1/[controller]"")`). Any doc claiming “v2” should be corrected to avoid confusion. ---- +**Recommendation** +- Use “(v1)” in API reference titles unless the API is actually versioned differently. -## ✅ Step 2 — Move files +### 3) Doc links pointing to non-existent files -| File | From | To | Status | -| :--- | :--- | :--- | :--- | -| `AppDbContext.cs` | `Infrastructure/` | `Infrastructure/Persistence/` | ✅ Done | -| `ProductConfiguration.cs` | `Infrastructure/Persistence/` | `Infrastructure/Persistence/Configurations/` | ✅ Done | -| `IGenericRepository.cs` | `Infrastructure/Persistence/Interfaces/` | `Domain/Interfaces/` | ✅ Done | -| `IProductRepository.cs` | `Infrastructure/Persistence/Interfaces/` | `Domain/Interfaces/` | ✅ Done | -| `IUnitOfWork.cs` | `Infrastructure/Persistence/Interfaces/` | `Domain/Interfaces/` | ✅ Done | -| `ProductController.cs` | `Controllers/` | `Web/Controllers/ProductsController.cs` | ✅ Done | -| `AppSettings.cs` | root | `Web/Configuration/` | ✅ Done | +Internal docs may contain links to planned directories (e.g., `doc/plan/*`) that are not present. This creates review friction. ---- +**Recommendation** +- Keep `doc/README.md` as an index of files that exist *now*. + - Put aspirational plans under `doc/archive/` (or create the actual `doc/plan/` structure if it becomes active work). -## ✅ Step 3 — Rename files + classes +### 4) Legacy product identity remnants (`FinanceAlert` / `InventoryManagementSystem` / `finance_*`) -| Old Name | New Name | Status | -| :--- | :--- | :--- | -| `ProductServices.cs` | `ProductService.cs` | ✅ Done | -| `ProductDto.cs` | Split → `ProductRequest.cs` + `ProductResponse.cs` + `PriceLossResponse.cs` | ✅ Done | -| `FinnhubSyncWorker.cs` | `FinnhubPriceSyncWorker.cs` | ✅ Done | -| class `ProductServices` | `ProductService` | ✅ Done | -| class `ProductRequestDto` | `ProductRequest` | ✅ Done | -| class `ProductDto` | `ProductResponse` | ✅ Done | -| class `ProductLossDto` | `PriceLossResponse` | ✅ Done | -| class `Finnhub` (in AppSettings) | `FinnhubSetting` | ✅ Done | +Some files still contain historical naming that conflicts with the **current product name** (`InventoryAlert`). ---- +**Recommendation (preferred approach)** -## ✅ Step 4 — Rename methods + update namespaces +- Do **not** mass-rename everything to `InventoryAlert`. + - Keep the umbrella/repo/solution name stable as `InventoryManagementSystem` (repo + solution root + `InventoryManagementSystem.sln`). + - Keep the product/application identity as `InventoryAlert` (projects + UI + Wiki). +- Do a **targeted rename pass** to replace `FinanceAlert` / `finance_*` remnants with `InventoryAlert` **only where they represent product identity** (docs, docker config labels, service names, JWT issuer/audience labels, etc.). -| Change | Status | -| :--- | :--- | -| `GetHighValueProducts` → `GetPriceLossAlertsAsync` | ✅ Done | -| `DeleteProductAsync(int)` → `DeleteProductAsync(int, CancellationToken)` | ✅ Done | -| Namespace `Infrastructure.Persistence.Interfaces` → `Domain.Interfaces` | ✅ Done | -| Namespace `Infrastructure` (AppDbContext) → `Infrastructure.Persistence` | ✅ Done | -| Namespace `InventoryAlert.Api` (AppSettings) → `Web.Configuration` | ✅ Done | -| Controller methods: proper `[FromRoute]`/`[FromBody]`/status codes | ✅ Done | +**Observed targets (update to InventoryAlert where appropriate)** ---- +- `InventoryAlert.Wiki/docusaurus.config.ts`: + - `url`, `baseUrl`, `organizationName`, `projectName`, `editUrl` should not be hardcoded; derive from `GITHUB_REPOSITORY_OWNER` / `GITHUB_REPOSITORY` during CI builds to survive repo renames. +- `InventoryManagementSystem/docker-compose.yml`: + - `POSTGRES_DB: finance_alert_db` + - healthcheck references `finance_alert_db` +- `InventoryManagementSystem/InventoryAlert.Worker/Program.cs`: + - `opts.ServerName = ""finance-worker""` +- `InventoryManagementSystem/InventoryAlert.Api/appsettings.Example.json`: + - `Database:DefaultConnection` uses `finance_alert_db` + - `Jwt:Audience = ""FinanceAlert.Web""` + - `Jwt:Issuer = ""FinanceAlert.Api""` +- `InventoryManagementSystem/InventoryAlert.Worker/appsettings.Example.json`: + - `Database:DefaultConnection` uses `finance_alert_db` +- `InventoryManagementSystem/InventoryAlert.Api/Program.cs`: + - Dev JWT key fallback uses `FinanceAlert_...` -## ✅ Cleanup — Stub/placeholder files deleted +## BM25 Indexing Scope (Docs) -| Deleted Stub | Replaced By | -| :--- | :--- | -| `Infrastructure/AppDbContext.cs` | `Infrastructure/Persistence/AppDbContext.cs` ✅ | -| `Infrastructure/Persistence/ProductConfiguration.cs` | `Infrastructure/Persistence/Configurations/ProductConfiguration.cs` ✅ | -| `Infrastructure/Persistence/Interfaces/IGenericRepository.cs` | `Domain/Interfaces/IGenericRepository.cs` ✅ | -| `Infrastructure/Persistence/Interfaces/IProductRepository.cs` | `Domain/Interfaces/IProductRepository.cs` ✅ | -| `Infrastructure/Persistence/Interfaces/IUnitOfWork.cs` | `Domain/Interfaces/IUnitOfWork.cs` ✅ | -| `Application/Services/ProductServices.cs` | `Application/Services/ProductService.cs` ✅ | -| `Application/DTOs/ProductDto.cs` | `ProductRequest.cs` + `ProductResponse.cs` + `PriceLossResponse.cs` ✅ | -| `Controllers/ProductController.cs` | `Web/Controllers/ProductsController.cs` ✅ | -| `Infrastructure/Workers/FinnhubSyncWorker.cs` | `Infrastructure/Workers/FinnhubPriceSyncWorker.cs` ✅ | -| `AppSettings.cs` (root) | `Web/Configuration/AppSettings.cs` ✅ | -| `Infrastructure/Persistence/Interfaces/` (folder) | Deleted ✅ | -| `Controllers/` (folder) | Deleted ✅ | -| `Services/` (folder) | Deleted ✅ | +BM25 indexing reads `.agents/scripts/core/bm25_config.json`. ---- +**Recommendation** +- Index `InventoryAlert.Wiki/docs` (source docs) rather than `InventoryAlert.Wiki/` (includes irrelevant folders like `build/`, `src/`, etc.). +- Index `doc/` for internal specs and references. -## ✅ Step 5 — Fix `Program.cs` + DI organization +## Summary -| Task | Status | -| :--- | :--- | -| Extract DI into `Web/ServiceExtensions/ApplicationServiceExtensions.cs` | ✅ Done | -| Extract DI into `Web/ServiceExtensions/InfrastructureServiceExtensions.cs` | ✅ Done | -| `builder.Services.AddApplicationServices()` | ✅ Done | -| `builder.Services.AddInfrastructure(settings)` | ✅ Done | -| Fix `using Microsoft.OpenApi` (v2 namespace change from Swashbuckle v10) | ✅ Done | -| Fix `IFinnhubClient` return type → `Task` (nullable) | ✅ Done | -| Fix `Product.Name/TickerSymbol` → `= string.Empty` (CS8618) | ✅ Done | -| Fix null-coalescing in `ProductService` mapper (CS8601) | ✅ Done | +Overall, the repo layout is coherent: +- `.NET` projects are correctly nested under `InventoryManagementSystem/`. +- UI and Wiki are split into their own top-level apps. +- Primary remaining drift is within `doc/archive/` (historical naming like `InventoryAlert.Contracts`) and any leftover “v2” labels in docs.",196,4968a62d6e771344e6d26be1be78715c,doc\archive\naming_and_structure_audit.md,0,329,"inventoryalert, inventorymanagementsystem, wiki, csproj, docs, solution, archive, name",1779851803.8540256,10,unit test httppost igenericrepository item iproductrepository productservice price drop appdbcontext threshold business logic loss application service efcore sku inventory entity framework productscontroller periodictimer dbset data access stock httpput finnhubpricesyncworker iproductservice notification fluentassertions httpget arrange act assert backgroundservice dockerfile dbcontext postgres postgresql asnotracking hosted service xunit iactionresult compose container,# Naming & Project Location Audit | Naming & Project Location Audit Verification Snapshot (as of 2026-04-30) Checke +doc,"--- +description: Review of alert rule + notification business flows (API/Worker/UI) and recommendations to enhance reliability, consistency, and UX. +type: reference +status: draft +version: 1.0 +tags: [business-flow, alerts, notifications, signalr, worker, api, ui, inventoryalert] +last_updated: 2026-04-26 +---",9,09c9d699a7ab47f836e5f6b50eeca0b4,doc\archive\NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md,0,330,"business, worker, description, review, alert, rule, notification, flows",1777190302.6049023,1,atomicity commit dbcontext application service arrange act assert hosted service finnhubpricesyncworker dbset productservice threshold igenericrepository productscontroller xunit httpput msft postgres business logic container iactionresult backgroundservice price drop compose loss unit test googl periodictimer appdbcontext savechanges dockerfile httppost aapl data access fluentassertions httpget entity framework rollback symbol notification iproductrepository postgresql asnotracking iproductservice efcore stock ticker unitofwork,NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md | --- description: Review of alert rule + notification business flows (API/Worker/ +doc,"# Alert Rules & Notifications — Business Flow Review + Enhancements ---- +Scope: end-to-end “alert rule → evaluation → notification → real-time delivery → user acknowledgement” across: -## ✅ Build Verification +- API: `InventoryManagementSystem/InventoryAlert.Api` +- Worker: `InventoryManagementSystem/InventoryAlert.Worker` +- Infrastructure: SignalR hub + notifier +- UI: `InventoryAlert.UI` (SignalR + unread count) -| Task | Status | -| :--- | :--- | -| `dotnet build` — 0 Errors, 0 Warnings | ✅ **PASSED** | +Documentation-only (no code changes here). --- -## ⬜ Phase 2 — Future Work (not in scope yet) +## 1) Domain Model (Current) -| Task | Notes | -| :--- | :--- | -| `Web/Middleware/GlobalExceptionHandler.cs` | Replace try/catch in controller with `IExceptionHandler` middleware | -| Add FluentValidation for `ProductRequest` | Validate `Name`, `OriginPrice > 0`, `PriceAlertThreshold` range | -| Move Swagger config into `Web/ServiceExtensions/` | `AddSwaggerDocumentation()` extension | +### 1.1 AlertRule ---- +Entity: `InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs` -## 🧑‍💻 Final Folder Tree — Achieved ✅ +- Key fields: + - `UserId`, `TickerSymbol`, `Condition`, `TargetValue` + - `IsActive`, `TriggerOnce`, `LastTriggeredAt` -``` -InventoryAlert.Api/ -├── Domain/ -│ ├── Entities/ ✅ Product.cs -│ ├── Interfaces/ ✅ IGenericRepository, IProductRepository, IUnitOfWork -│ └── Events/ ✅ (placeholder) -├── Application/ -│ ├── DTOs/ ✅ ProductRequest, ProductResponse, PriceLossResponse -│ ├── Interfaces/ ✅ IProductService -│ └── Services/ ✅ ProductService.cs -├── Infrastructure/ -│ ├── Persistence/ ✅ AppDbContext.cs -│ │ ├── Configurations/ ✅ ProductConfiguration.cs -│ │ └── Repositories/ ✅ GenericRepository, ProductRepository, UnitOfWork -│ ├── External/ ✅ FinnhubClient + IFinnhubClient + Models -│ └── Workers/ ✅ FinnhubPriceSyncWorker.cs -└── Web/ - ├── Controllers/ ✅ ProductsController.cs - ├── Configuration/ ✅ AppSettings.cs - ├── ServiceExtensions/ ✅ ApplicationServiceExtensions, InfrastructureServiceExtensions - ├── Middleware/ ⬜ Phase 2 - └── Program.cs ✅ Clean bootstrap — 64 lines -```",138,1e0f87235dd4f8593a9e686fa3924a15,doc\archive\DDD_REFACTOR_PLAN.md,0,306,"done, infrastructure, interfaces, persistence, domain, status, controllers, step",1775670503.9122765,1,aapl domain driven design loss finnhubpricesyncworker domain entity iproductrepository iproductservice quote httppost stock price stock ticker sku data access price drop backgroundservice dbcontext hosted service googl threshold infrastructure productservice notification msft executetransactionasync business logic savechangesasync efcore external api iunitofwork periodictimer item igenericrepository inventory market data symbol productscontroller iactionresult application service httpget stock entity framework asnotracking httpput appdbcontext application layer dbset,"# 🔬 DDD Refactoring Audit — Progress Tracker | 🔬 DDD Refactoring Audit — Progress Tracker Naming Conventions, File Locations &" -doc,"# Pragmatic DDD: File Structure Guide +Conditions currently include: -This document outlines the **Domain-Driven Design (DDD)** structure for the **Automated Inventory Alert System**. Our goal is to apply DDD principles while keeping the project ""Small & Pragmatic"" by consolidating layers into logical namespaces within a single API project, rather than over-engineering with multiple assembly projects. +- `PriceAbove`, `PriceBelow`, `PriceTargetReached` +- `PercentDropFromCost` +- `LowHoldingsCount` ---- +### 1.2 Notification -## 🏗️ The Single-Project DDD Layout +Entity: `InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/Notification.cs` -```text -InventoryAlertSystem/ -├── InventoryAlert.Api/ -│ ├── Domain/ # Pure Business Logic (No dependencies on external libraries) -│ │ ├── Entities/ # Core models (Product.cs) -│ │ ├── ValueObjects/ # Immutable data structures (Price, Stock) -│ │ ├── Interfaces/ # Repository contracts & External service interfaces -│ │ └── Events/ # Domain events (LowStockDetected.cs) -│ │ -│ ├── Application/ # Use Case & Logic Orchestration -│ │ ├── Features/ # Functional slices (Inventory, Pricing, Notifications) -│ │ ├── Services/ # Logic that coordinates Domain logic -│ │ └── DTOs/ # Formats for API Request/Response -│ │ -│ ├── Infrastructure/ # Implementation details (External worlds) -│ │ ├── Persistence/ # EF Core, AppDbContext, Migrations, Repositories -│ │ ├── External/ # Finnhub API Client, HTTP Clients -│ │ └── Messaging/ # Motor implementation, SNS/SQS, Hangfire Jobs -│ │ -│ ├── Web/ # Entry Point & API Configuration -│ │ ├── Controllers/ # REST Endpoints -│ │ ├── Middleware/ # Global Exception handling, Auth -│ │ └── Program.cs # DI registration & App Startup -│ │ -│ └── appsettings.json -│ -└── InventoryAlert.Tests/ # Shadow the same structure for unit/integration tests -``` +- Key fields: + - `UserId` + - `AlertRuleId?` (nullable) + - `TickerSymbol?` + - `Message` + - `IsRead` + - `CreatedAt` + +DTO returned to clients: + +- `InventoryManagementSystem/InventoryAlert.Domain/DTOs/NotificationDTOs.cs` → `NotificationResponse` --- -## 🧩 Architectural Breakdown +## 2) Current API Flow (Alert Rules + Notifications) -### 1. Domain (The Heart) -- **What it solves:** Architecture & Business Logic. -- **Rules:** Must NOT reference any external library (EF Core, Hangfire, etc.). -- **Content:** The `Product` entity lives here. It should contain logic like `bool IsBelowThreshold()` or `void UpdateStock(int amount)`. +### 2.1 AlertRule CRUD -### 2. Application (The Orchestrator) -- **What it solves:** Predictability. -- **Rules:** Depends ONLY on the Domain. -- **Content:** If a background job needs to check stock and send an alert, the `InventoryMonitorService` orchestrates this by using the Domain entities and Infrastructure interfaces. +Controller: `InventoryManagementSystem/InventoryAlert.Api/Controllers/AlertRulesController.cs` -### 3. Infrastructure (The ""Details"") -- **What it solves:** Maintainability & Security. -- **Rules:** Holds the ""How"". How do we save to PostgreSQL? How do we talk to Finnhub? -- **Content:** `AppDbContext`, `ProductRepository`, and the specific `FinnhubClient` implementation. +- `GET /api/v1/alertrules` → list current user’s rules +- `POST /api/v1/alertrules` → create +- `PUT /api/v1/alertrules/{id}` → full replace +- `PATCH /api/v1/alertrules/{id}/toggle` → enable/disable +- `DELETE /api/v1/alertrules/{id}` → delete -### 4. Web (The Gateway) -- **What it solves:** Performance & Interaction. -- **Content:** Handles HTTP requests, JSON serialization, and project-wide configuration. +Service: `InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs` + +Observed business behavior: + +- Normalizes symbol on create (`Trim().ToUpperInvariant()`). +- Performs “symbol discovery” side-effect by calling `IStockDataService.GetProfileAsync` before persisting the rule. +- Uses `KeyNotFoundException` for missing rule (maps to 404 in middleware). + +### 2.2 Notification query + acknowledgement + +Controller: `InventoryManagementSystem/InventoryAlert.Api/Controllers/NotificationsController.cs` + +- `GET /api/v1/notifications` (paged, supports `onlyUnread`) +- `GET /api/v1/notifications/unread-count` +- `PATCH /api/v1/notifications/{id}/read` → mark read +- `PATCH /api/v1/notifications/read-all` → mark all read +- `DELETE /api/v1/notifications/{id}` → dismiss (delete) +- `POST /api/v1/notifications/test-signalr` → pushes a test notification via SignalR (admin/dev utility) + +Repository: `InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/NotificationRepository.cs` + +- Uses `ExecuteUpdateAsync` for `MarkAllReadAsync` (efficient). --- -## 🚀 Why This Solution? +## 3) Current Delivery Flow (Worker → SignalR → UI) -1. **Big Problem Solved (Architecture):** Prevents the ""Fat Controller"" and ""Transaction Script"" anti-patterns. By moving logic into the **Domain**, we ensure the system is testable without a database. -2. **YAGNI (You Ain't Gonna Need It):** Traditional DDD suggests 4+ separate C# projects (`Company.Project.Domain`, `Company.Project.Infra`, etc.). For a small project, this adds build time and complexity. Folder-based DDD provides the **organizational benefits** without the **overhead**. -3. **Modular Growth:** If the ""Pricing Module"" grows too large, it is already logically separated in the `Application/Features` and `Infrastructure/External` folders, making it easy to extract into a Microservice later if needed.",67,bd4ea2e9f0c7a97029b79101b835f043,doc\archive\DDD_STRUCTURE.md,0,307,"project, domain, what, solves, content, into, logic, rules",1775670503.9122765,1,asnotracking quote httppost business logic arrange act assert rollback domain driven design iproductservice xunit efcore migration notification commit application service unit test entity framework httpget savechanges efcore loss stock price external api stock schema change data access appdbcontext atomicity market data sku fluentassertions iproductrepository infrastructure igenericrepository productservice threshold domain entity application layer item unitofwork dbset inventory httpput price drop database update dbcontext iactionresult productscontroller add-migration,# Pragmatic DDD: File Structure Guide | Pragmatic DDD: File Structure Guide This document outlines the Domain-Driven Des -doc,"# Implementation Plan: Migrating Logs & News to DynamoDB +### 3.1 SignalR hub and delivery mechanism -Consolidation of high-volume/time-series data into DynamoDB to reduce PostgreSQL load and optimize resource usage. +- Hub: `InventoryManagementSystem/InventoryAlert.Infrastructure/Hubs/NotificationHub.cs` + - `[Authorize]` + - Logs connect/disconnect using `Context.UserIdentifier` +- Hub route constant: + - `InventoryManagementSystem/InventoryAlert.Domain/Interfaces/INotificationHub.cs` → `SignalRConstants.NotificationHubRoute = ""/hubs/notifications""` +- API hosts hub: + - `InventoryManagementSystem/InventoryAlert.Api/Program.cs` → `app.MapHub(""/hubs/notifications"")` +- Notifier: + - `InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/NotificationAlertNotifier.cs` + - Calls `Clients.User(notification.UserId.ToString()).ReceiveNotification(dto)` -## 1. Domain & Contracts Layer -- [ ] **NewsRecord Refactoring**: - - Update `InventoryAlert.Contracts/Entities/NewsRecord.cs` to include DynamoDB attributes. - - Set `TickerSymbol` as HashKey and `PublishedAt` (ISO 8601 string) as RangeKey for optimized retrieval. - - Add TTL support for automatic data cleanup. -- [ ] **NewsDynamoRepository**: - - Create `INewsRepository` interface in Contracts. - - Implement `NewsDynamoRepository.cs` using `IDynamoDBContext`. +### 3.2 UI consumption -## 2. Worker Layer (Ingestion) -- [ ] **NewsHandler Update**: - - Swap `InventoryDbContext` for `INewsRepository`. - - Persist news directly to DynamoDB. -- [ ] **PollSqsJob Persistence**: - - Continue using `EventLogDynamoRepository`. - - (Verification) Ensure it handles de-duplication correctly before saving to DynamoDB. +`InventoryAlert.UI/src/components/NotificationProvider.tsx`: -## 3. API Layer (Querying) -- [ ] **EventLog Queries**: - - Ensure `IEventLogQuery` implementation (`DynamoDbEventLogQuery`) is fully functional. - - Update controller endpoints to source data strictly from DynamoDB. -- [ ] **News Queries**: - - Create `INewsQuery` interface. - - Implement `DynamoDbNewsQuery` to fetch news per ticker from DynamoDB. - - Update `NewsController` (or equivalent) to use the new query service. +- Reads `auth_token` from localStorage. +- If token exists, connects to SignalR hub (`/hubs/notifications`) using `NEXT_PUBLIC_API_URL`. +- Listens for `ReceiveNotification` and increments local unread count. +- Also calls `GET /api/v1/notifications/unread-count` to fetch initial state. -## 4. Infrastructure Cleanup (PostgreSQL) -- [ ] **DbContext Removal**: - - Remove `DbSet` and `DbSet` from `InventoryDbContext.cs`. - - Remove associated `IEntityTypeConfiguration` classes. -- [ ] **Migration**: - - Generate an EF Core migration: `RemoveLogsAndNewsFromPostgres`. - - Apply migration to drop tables in the development environment. +--- -## 5. Verification -- [ ] Validate news ingestion via simulator. -- [ ] Verify event log querying via API Swagger. -- [ ] Check CloudWatch/LocalStack logs for DynamoDB write success.",42,a595c0fbedad14cd179b0ef89f0017c2,doc\archive\DynamoDB_Migration_Plan.md,0,308,"dynamodb, news, update, data, contracts, layer, newsrecord, from",1775670503.9049637,1,igenericrepository database update efcore migration add-migration data access efcore googl notification httpput iactionresult hosted service price drop appdbcontext iproductrepository threshold entity framework aapl productscontroller application service backgroundservice business logic schema change finnhubpricesyncworker periodictimer asnotracking symbol loss httppost productservice httpget msft stock ticker dbset iproductservice dbcontext,# Implementation Plan: Migrating Logs & News to DynamoDB | Implementation Plan: Migrating Logs & News to DynamoDB Consolidation of high-vol -doc,"# Enhancement & Tracking Plan +## 4) Current Evaluation Flows (Worker) -> **Last Updated:** 2026-04-05 -> Use this as a living checklist. Items marked ✅ are implemented and verified. +### 4.1 Scheduled evaluation (SyncPricesJob) + +`InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs`: + +- Fetches quotes in parallel (`MaxDegreeOfParallelism = 5`). +- Persists `PriceHistory` in bulk. +- Loads active alert rules in batch (`GetBySymbolsAsync`) and evaluates locally. +- Creates `Notification` rows (in-memory list), persists them, then calls `IAlertNotifier.NotifyAsync` for each notification. + +### 4.2 Event-driven evaluation (MarketPriceAlertHandler + LowHoldingsHandler) + +Handlers: + +- `InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/MarketPriceAlertHandler.cs` + - Evaluates rules for one symbol and creates/persists notifications in a transaction, then notifies via SignalR. + - Trigger logic includes only: + - `PriceAbove`, `PriceBelow`, `PriceTargetReached` +- `InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/LowHoldingsHandler.cs` + - Creates/persists a notification, then notifies via SignalR. --- -## 🏁 Critical Improvements +## 5) Business Flow Issues / Gaps (Observed) -### 1. Architectural Alignment (DDD) +### 5.1 Two competing “sources of truth” for price alert evaluation -- [x] **Thin Controllers:** Alert filter logic moved to `ProductService`. Controller is now thin. ✅ -- [x] **Repository & UoW Refactoring:** `UnitOfWork` uses DI-injected repositories. ✅ -- [x] **Consolidate Services:** All logic in `Application/Services`. Top-level `Services/` folder removed. ✅ -- [x] **Interface Naming:** `ProductService` (singular) matches `IProductService`. ✅ +Both of these can generate price notifications: -### 2. Design Patterns to Implement +- `SyncPricesJob` (scheduled) +- `MarketPriceAlertHandler` (event-driven) -- [ ] **CQRS (Command Query Responsibility Segregation):** Use **MediatR** to separate read and write requests. - - *Why:* Simplifies code as it grows, making handlers more focused. -- [ ] **Domain Events:** Dispatch events (e.g., `LowStockDetectedEvent`) from the Domain entity. - - *Why:* Decouples product updates from notification logic. -- [ ] **Static Factory / Builder Pattern:** Use for creating `Product` entities with complex state. -- [ ] **Specification Pattern:** For building reusable filters in `GetPriceLossAlertsAsync`. - - *Why:* Keeps query logic out of the Domain and into reusable objects. +Risk: -### 3. Code Quality & Patterns +- Duplicate notifications for the same rule breach. +- Divergent rule behavior (ex: cost-basis alerts are implemented in `SyncPricesJob`, but not in `MarketPriceAlertHandler`). -- [x] **Mapping:** Manual mapping centralized in static `MapToResponse` / `MapToEntity` helpers. ✅ -- [x] **CancellationToken Consistency:** `CancellationToken ct` passed through all layers. ✅ -- [x] **Async/Await Fix:** `.Result` usage eliminated — all methods use `await`. ✅ -- [x] **REST Best Practices:** ✅ - - [x] `PATCH /{id}/stock` endpoint uses `[FromRoute]` binding. - - [x] `GetProductById` correctly named with `[FromRoute] int id`. +### 5.2 Cooldown/dedup rules are inconsistent across flows -### 4. Missing Features (Challenge Requirements) +`ProcessQueueJob` contains an alert suppression key: -- [x] **Alert Logic:** `LastAlertSentAt` 1-hour cooldown implemented in `GetPriceLossAlertsAsync`. No spam alerts. ✅ -- [x] **Error Handling:** `ExceptionHandlingMiddleware` implemented — RFC-7807 ProblemDetails, all domain exceptions mapped. ✅ +- `alert:cooldown:{payload.Symbol}` (24h) + - `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` ---- +But `SyncPricesJob` creates notifications directly and does not share the same cooldown gate. -## 🛠️ Performance & Security (Planned) +Risk: -- [ ] **Caching:** Implement `IDistributedCache` (Redis) or `IMemoryCache` for `GetProductById` to reduce DB load. -- [ ] **Authentication:** Add JWT Bearer authentication to protect the `POST/PUT/DELETE` endpoints. -- [x] **Validation:** `FluentValidation` registered for `ProductRequest`. Returns `400 Bad Request` with details. ✅ +- User experiences “alert storms” if the same condition is repeatedly breached across sync cycles. ---- +### 5.3 Contract drift between docs and code -## 📝 Code Review Summary +Some Wiki execution-flow docs describe SQS publishing for certain alert flows, while current code shows direct persistence + SignalR notify inside `SyncPricesJob`. -| File | Issue | Status | -| :--- | :--- | :--- | -| `ProductController.cs` | Logic in Controller | ✅ Fixed — thin controller, all logic in service | -| `ProductServices.cs` | `.Result` usage | ✅ Fixed — all `await` | -| `UnitOfWork.cs` | Violation of DI | ✅ Fixed — repositories injected | -| `GenericRepository.cs` | Shadowing `T` | ✅ Fixed | -| `Program.cs` | Massive file | ✅ Fixed — `AddInfrastructure()` + `AddApplicationServices()` extensions |",59,b07b93a2d0bea0b14969e55195c24b63,doc\archive\ENHANCEMENT_PLAN.md,0,309,"logic, fixed, domain, implemented, thin, controller, services, code",1775670503.9132829,1,productservice sku data access domain driven design iunitofwork dbcontext inventory threshold httpput stock executetransactionasync productscontroller iproductrepository iactionresult httpget httppost item savechangesasync loss igenericrepository notification application layer domain entity appdbcontext efcore business logic asnotracking infrastructure iproductservice application service dbset entity framework price drop,# Enhancement & Tracking Plan | Enhancement & Tracking Plan > Last Updated: 2026-04-05 > Use this as a living ch -doc,"# 🏗️ Event-Driven Architecture Plan +This makes debugging hard because operational expectations (“where should I look?”) are unclear. -## Hangfire + SNS/SQS + Redis + Multi-Project System +### 5.4 Notification delivery is not coupled to persistence outcome -> **Scope:** Extend the existing `InventoryAlert.Api` into a full event-driven microservices ecosystem. -> **Constraint:** Use only Finnhub Free-Tier APIs. All AWS services emulated via **Moto**. +In `SyncPricesJob`, persistence (`AddRangeAsync`) and delivery (`NotifyAsync`) occur, but the notification loop is sequential and can fail per user. ---- +In the notifier itself, delivery failures are logged and swallowed: -## 🗺️ High-Level Architecture +- `NotificationAlertNotifier.NotifyAsync` catches and logs; it does not throw. -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ EXTERNAL WORLD │ -│ [Telegram Bot] [Sample.Publisher App] [Browser/Postman] │ -└───────────┬─────────────────┬───────────────────────┬──────────────┘ - │ │ │ - ▼ ▼ ▼ -┌────────────────────────────────────────────────────────────────────┐ -│ InventoryAlert.Api (Port 8080) │ -│ │ -│ POST /api/events → Validate → Publish to SNS Topic │ -│ POST /api/market-alerts → Manually trigger a price-alert event │ -│ GET /api/products → (existing endpoints) │ -└───────────────────────────────────┬────────────────────────────────┘ - │ SNS Publish - ▼ -┌──────────────────────────────────────────────────────────────────┐ -│ Moto (Mock AWS) Port 5000 │ -│ │ -│ SNS Topic: arn:aws:sns:us-east-1:123456789:inventory-events │ -│ │ │ -│ └──► SQS Queue: arn:aws:sqs:us-east-1:123456789:event-queue │ -└──────────────────────────────────────────────────────────────────┘ - │ SQS Poll - ▼ -┌──────────────────────────────────────────────────────────────────┐ -│ InventoryAlert.Worker (New Project) │ -│ │ -│ [Hangfire Job: PollSqsJob] │ -│ → Dequeue messages from SQS │ -│ → Route by event type │ -│ → Execute handlers (FetchQuote, SaveAlert, etc.) │ -│ → Cache results in Redis │ -│ → Persist to PostgreSQL │ -└──────────────────────────────────────────────────────────────────┘ - │ Cache Reads - ▼ -┌──────────────────────────────────────────────────────────────────┐ -│ Redis (Port 6379) │ -│ │ -│ Key: ""product:quote:{symbol}"" → TTL 60s (live price cache) │ -│ Key: ""job:last-run:{jobName}"" → TTL 10m (last execution ts) │ -│ Key: ""alert:history:{symbol}"" → TTL 24h (dedup alert history) │ -└──────────────────────────────────────────────────────────────────┘ -``` - ---- - -## 📁 Solution Structure +Implication: -``` -InventoryManagementSystem/ -├── InventoryAlert.Api/ ← Existing REST API -├── InventoryAlert.Worker/ ← NEW: Hangfire + SQS Consumer -├── InventoryAlert.Sample/ ← NEW: Sample Event Publisher CLI -├── InventoryAlert.Contracts/ ← NEW: Shared Event Schemas (DTOs) -└── InventoryAlert.Tests/ ← Existing test project -``` +- DB state can show notification exists, but UI never received real-time push (UI should still fetch via API list/unread count, but the user may miss immediacy). ---- +### 5.5 No explicit “notification type” or “severity” -## 📦 Project 1: `InventoryAlert.Contracts` (Shared Event Schema) +Everything is just a string `Message`. -> **Why a separate project?** Both the API (publisher) and the Worker (consumer) must agree on the same message format. A shared `Contracts` project (referenced by both) eliminates duplication and version drift. +Impact: -### Event Envelope (SNS/SQS Standard Format) +- Hard to group alerts (price vs holdings vs system vs news). +- Hard to present consistent UI (icons, colors, filters). -All events follow the standard SNS notification format: +### 5.6 Lack of explicit idempotency key at the “rule trigger” level -```json -{ - ""Type"": ""Notification"", - ""MessageId"": ""uuid-v4"", - ""TopicArn"": ""arn:aws:sns:us-east-1:123456789:inventory-events"", - ""Subject"": ""MarketPriceAlert"", - ""Message"": ""{...serialized payload...}"", - ""Timestamp"": ""2026-04-04T01:00:00Z"", - ""MessageAttributes"": { - ""EventType"": { - ""Type"": ""String"", - ""Value"": ""MarketPriceAlert"" - }, - ""SourceService"": { - ""Type"": ""String"", - ""Value"": ""InventoryAlert.Api"" - } - } -} -``` +There is: -### Event Types +- SQS message-level dedup (MessageId) in `ProcessQueueJob` +- but no explicit rule-level dedup (“don’t fire the same rule twice for same symbol within X min”) when the source is scheduled evaluation. -| EventType | Trigger | Finnhub Source | -| :--- | :--- | :--- | -| `MarketPriceAlert` | Price drops beyond `PriceAlertThreshold` | `/quote` | -| `StockLowAlert` | `StockCount` drops below `StockAlertThreshold` | Internal DB | -| `EarningsAlert` | A tracked company announces earnings | `/stock/earnings` | -| `InsiderSellAlert` | Insider selling detected above a threshold | `/stock/insider-transactions` | -| `CompanyNewsAlert` | High-impact news published for a tracked stock | `/company-news` | +--- -### New Domain Models +## 6) Recommended Enhancements (Business + Technical) -```csharp -// Contracts/Events/EventEnvelope.cs -public record EventEnvelope -{ - public string MessageId { get; init; } = Guid.NewGuid().ToString(); - public string TopicArn { get; init; } = string.Empty; - public string Subject { get; init; } = string.Empty; // EventType - public string Message { get; init; } = string.Empty; // Serialized payload - public DateTime Timestamp { get; init; } = DateTime.UtcNow; - public Dictionary MessageAttributes { get; init; } = []; -} +### P0 — Choose one primary evaluation pipeline for price alerts -// Contracts/Events/Payloads/MarketPriceAlertPayload.cs -public record MarketPriceAlertPayload -{ - public int ProductId { get; init; } - public string Symbol { get; init; } = string.Empty; - public decimal OriginPrice { get; init; } - public decimal CurrentPrice { get; init; } - public decimal DropPercent { get; init; } // e.g. 0.12 = 12% -} +Pick one: -// Contracts/Events/Payloads/EarningsAlertPayload.cs -public record EarningsAlertPayload -{ - public string Symbol { get; init; } = string.Empty; - public decimal ActualEPS { get; init; } - public decimal EstimatedEPS { get; init; } - public decimal SurprisePercent { get; init; } - public string Period { get; init; } = string.Empty; // e.g. ""Q4 2025"" -} +**Option A: scheduled-only** -// Contracts/Events/Payloads/InsiderSellAlertPayload.cs -public record InsiderSellAlertPayload -{ - public string Symbol { get; init; } = string.Empty; - public string InsiderName { get; init; } = string.Empty; - public long SharesSold { get; init; } - public decimal ValueUsd { get; init; } - public DateTime TransactionDate { get; init; } -} +- `SyncPricesJob` is the sole evaluator for price-based alert rules. +- Remove/disable event-driven `MarketPriceAlertHandler` for price rules (or keep it for a different event type). -// Contracts/Events/Payloads/CompanyNewsAlertPayload.cs -public record CompanyNewsAlertPayload -{ - public string Symbol { get; init; } = string.Empty; - public string Headline { get; init; } = string.Empty; - public string Source { get; init; } = string.Empty; - public string Url { get; init; } = string.Empty; - public DateTime PublishedAt { get; init; } -} -``` +**Option B: event-driven** ---- +- `SyncPricesJob` only publishes events (or only updates `PriceHistory`), and `MarketPriceAlertHandler` becomes the sole evaluator. +- Ensure handler supports all relevant conditions (including cost-basis if desired). +- Ensure event payload includes enough context (`Symbol`, `NewPrice`, potentially `QuoteTimestamp`). -## 🌐 Project 2: `InventoryAlert.Api` (New Endpoints) +**Option C: Hybrid (User Preferred)** -### New Endpoints +- **Keep both** Hangfire jobs (scheduled) and event-driven handlers for redundancy and comprehensive coverage. +- Requires rigorous idempotency/dedup logic to prevent duplicate notifications for the same breach event across both pipelines. -| Method | Route | Purpose | -| :--- | :--- | :--- | -| `POST` | `/api/events` | Receive any generic event and publish to SNS | -| `POST` | `/api/events/market-alert` | Manually trigger a `MarketPriceAlert` event | -| `POST` | `/api/events/news-alert` | Manually trigger a `CompanyNewsAlert` event | -| `GET` | `/api/events/types` | List all supported event types | +Acceptance criteria: -### New Service: `IEventPublisher` +- One breach → one notification → one delivery attempt. +- Same rule logic regardless of entry path. -``` -IEventPublisher - └── PublishAsync(EventEnvelope envelope) → Task - → Serializes envelope to JSON - → Publishes to SNS Topic ARN - → SNS auto-fans-out to subscribed SQS queues -``` +### P0 — Standardize cooldown/dedup semantics -### New Entity: `EventLog` (for audit trail) +Define the canonical rule: -Persist all published events to the DB for auditing: +- Per `(UserId, AlertRuleId)` (recommended), or per `(UserId, Symbol, Condition)`. -| Column | Type | Notes | -| :--- | :--- | :--- | -| `Id` | `int` | PK | -| `MessageId` | `string` | From SNS | -| `EventType` | `string` | e.g. `MarketPriceAlert` | -| `Payload` | `string` | JSON body | -| `PublishedAt` | `DateTime` | UTC | -| `SourceService` | `string` | e.g. `InventoryAlert.Api` | +Then enforce it in the chosen evaluation pipeline: ---- +- Redis key pattern (example): `alert:cooldown:{userId}:{ruleId}` +- TTL configurable per rule type (e.g., 24h for news, 1h for price, etc.) -## ⚙️ Project 3: `InventoryAlert.Worker` (New Project) +### P1 — Add “notification type” (and optional metadata) to support UX -This is a separate **.NET Worker Service** (minimal API or `BackgroundService` host) focused entirely on job processing. +Add fields conceptually (and later in DB if desired): -### Why separate from the API? +- `Type` (enum): `Price`, `Holdings`, `System`, `News`, … +- `Severity` (enum): `Info`, `Warning`, `Critical` +- Optional metadata: `CurrentPrice`, `TargetValue`, `Condition`, … -- The API should stay fast and focused on handling HTTP. -- The Worker can be scaled independently (more workers = more SQS throughput). -- Hangfire runs in the Worker, keeping the Dashboard away from the API layer. +Even if DB isn’t changed immediately, you can standardize message templates and embed structured fields in logs for now. -### Architecture: Hangfire Jobs +### P1 — Make delivery robust and observable -| Job Name | Schedule | Responsibility | Finnhub Call | -| :--- | :--- | :--- | :--- | -| `PollSqsJob` | Every 30s | Dequeue messages from SQS and dispatch to handlers | None | -| `SyncPricesJob` | Every 10m | Update `CurrentPrice` for all products | `/quote` | -| `EarningsCheckJob` | Every 6h | Check if tracked symbols have new earnings | `/stock/earnings` | -| `InsiderTxCheckJob` | Every 6h | Check for insider selling on tracked symbols | `/stock/insider-transactions` | -| `NewsCheckJob` | Every 1h | Fetch latest news for tracked symbols | `/company-news` | +Recommended: -### SQS Consumer Flow +- Ensure UI always reflects DB truth: + - UI should periodically refresh unread count and/or latest notifications (not only via SignalR push). + - **Manual Reload Feature:** Build a feature allowing the user to manually reload or pull-to-refresh to get the newest notifications directly from the API. +- Add explicit logging fields for each notification dispatch: + - `NotificationId`, `UserId`, `AlertRuleId`, `TickerSymbol` +- Consider capturing “delivery status” only if needed (usually not needed if polling exists). -``` -PollSqsJob runs → - Dequeue up to 10 messages from SQS → - For each message: - 1. Parse EventEnvelope - 2. Check Redis: ""alert:history:{symbol}"" to avoid duplicate alerts - 3. Route to handler by EventType: - - MarketPriceAlert → PriceAlertHandler → Notify (log/Telegram) - - EarningsAlert → EarningsHandler → Update Product metrics in DB - - InsiderSellAlert → InsiderHandler → Flag product in DB - - CompanyNewsAlert → NewsHandler → Store news in DB - 4. Cache result in Redis (TTL rules above) - 5. Delete message from SQS (acknowledge) -``` +### P2 — Align docs to the implemented flow -### Redis Caching Strategy +Once a primary pipeline is chosen: -| Key Pattern | Stores | TTL | Populated By | -| :--- | :--- | :--- | :--- | -| `product:quote:{AAPL}` | Latest price quote | 60 seconds | `SyncPricesJob` | -| `alert:history:{AAPL}` | Last alert timestamp | 24 hours | `PollSqsJob` (dedup) | -| `job:last-run:EarningsCheckJob` | Last run timestamp | 10 minutes | Each Job | -| `news:{AAPL}:latest` | Latest news headline | 1 hour | `NewsCheckJob` | +- Update execution flow docs to match it. +- Keep review/refactor notes under `doc/` (not Wiki), and keep Wiki “how to use” oriented. --- -## 🧪 Project 4: `InventoryAlert.Sample` (Event Publisher CLI) - -A simple Console App that **simulates external systems** pushing events into the ecosystem. This is for local development and testing without needing a real frontend. +## 7) Suggested “Golden Path” Flow (Target) -### Functionality +```mermaid +sequenceDiagram + participant UI as UI + participant API as InventoryAlert.Api + participant W as InventoryAlert.Worker + participant DB as PostgreSQL + participant Hub as NotificationHub -``` -InventoryAlert.Sample (Console App) - ├── Menu option 1: Publish a MarketPriceAlert event - ├── Menu option 2: Publish an EarningsAlert event - ├── Menu option 3: Publish an InsiderSellAlert event - ├── Menu option 4: Publish a CompanyNewsAlert event - └── Menu option 5: Stress test — publish 50 random events + UI->>API: POST /api/v1/alertrules + API->>DB: INSERT AlertRule + W->>W: Evaluate (scheduled or event-driven) + W->>DB: INSERT Notification(s) + W->>Hub: ReceiveNotification(notification) + UI->>API: GET /api/v1/notifications/unread-count (initial + periodic) ``` -### How it works +--- -- Points to `http://localhost:8080/api/events` (the main API). -- Sends events via **HTTP POST** with the standard `EventEnvelope` format. -- OR can publish directly to **Moto SQS** at `http://localhost:5000` bypassing the API (for testing the worker in isolation). +## 8) Practical Next Steps (Implementation Level) + +1) **Implement Hybrid Evaluation:** ✅ Refactored `SyncPricesJob` and `MarketPriceAlertHandler` to share `IAlertRuleEvaluator`. +2) **Enforce Deduplication/Cooldown:** ✅ Implemented Redis-based cooldown (`alert:cooldown:{userId}:{ruleId}`) in `AlertRuleEvaluator`. +3) **Build Manual Reload in UI:** ✅ Added ""Refresh"" button in Notifications page and synchronized unread count badge. +4) **Standardize Taxonomy:** ✅ Implemented `NotificationType` and `NotificationSeverity` enums and updated UI to use icons/colors. +5) **Align Error Handling:** ✅ UI `fetchApi` and `NotificationProvider` are now resilient to background failures and synchronized via React Context. --- -## 🔌 Telegram Integration (Future) - -The `IAlertNotifier` interface (already planned) will have a `TelegramAlertNotifier` implementation: - -``` -TelegramAlertNotifier - → Uses Telegram Bot API (bot token in env vars) - → Sends formatted messages to a chat channel - → Triggered by PriceAlertHandler / InsiderHandler inside the Worker -``` - -Message format: - -``` -🚨 PRICE DROP ALERT -Symbol: AAPL -Drop: -15.3% -Current: $142.00 -Origin: $167.50 -Threshold: -10% -Time: 2026-04-04 02:00 UTC -``` - ---- +## 9) Verification Status -## 🧩 Business Logic Scenarios (Finnhub Free Tier) +- **Unit Tests:** ✅ 99/99 Passing (including new `AlertRuleEvaluatorTests`). +- **E2E Tests:** 🏗️ Planned for next step. +- **Docker:** 🏗️ Rebuild required to verify full flow.",310,09c9d699a7ab47f836e5f6b50eeca0b4,doc\archive\NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md,0,331,"notifications, inventoryalert, inventorymanagementsystem, notification, alert, rule, signalr, syncpricesjob",1777190302.6049023,10,atomicity commit dbcontext application service arrange act assert hosted service finnhubpricesyncworker dbset productservice threshold igenericrepository productscontroller xunit httpput msft postgres business logic container iactionresult backgroundservice price drop compose loss unit test googl periodictimer appdbcontext savechanges dockerfile httppost aapl data access fluentassertions httpget entity framework rollback symbol notification iproductrepository postgresql asnotracking iproductservice efcore stock ticker unitofwork,# Alert Rules & Notifications — Business Flow Review + Enhancements | Alert Rules & Notifications — Business Flow Review + Enhancements Scope: end-to- +doc,"--- +description: Central index for logging/tracing/error-handling docs (Seq, CorrelationId, request/response logging). +type: reference +status: active +version: 1.0 +tags: [observability, logging, tracing, seq, inventoryalert] +last_updated: 2026-04-26 +---",9,cb0d813a9994a860907f16d5b9e42a8b,doc\archive\OBSERVABILITY.md,0,332,"logging, tracing, description, central, index, error, handling, docs",1779814416.3892374,1,periodictimer hosted service backgroundservice asnotracking notification finnhubpricesyncworker threshold dbcontext efcore appdbcontext price drop entity framework loss,"OBSERVABILITY.md | --- description: Central index for logging/tracing/error-handling docs (Seq, Cor" +doc,"# Observability (Central) -| Scenario | Entities Affected | Finnhub Endpoint | Event Published | -| :--- | :--- | :--- | :--- | -| **Price Drop > threshold** | `Product.CurrentPrice` | `/quote` | `MarketPriceAlert` | -| **Earnings miss > 10%** | New `EarningsRecord` entity | `/stock/earnings` | `EarningsAlert` | -| **Insider sells > $1M** | New `InsiderTransaction` entity | `/stock/insider-transactions` | `InsiderSellAlert` | -| **High impact news** | New `NewsRecord` entity | `/company-news` | `CompanyNewsAlert` | -| **Market closes** | Trigger close-of-day sync | `/stock/market-status` | Internal only | +This page centralizes the “how we observe/debug the system” guidance. -### New Entities (Database Changes Required) +## Core docs -``` -EarningsRecord - ├── Id (int) - ├── ProductId (FK → Product) - ├── Symbol (string) - ├── Period (string) ← e.g. ""2025Q4"" - ├── ActualEPS (decimal) - ├── EstimatedEPS (decimal) - ├── SurprisePercent (decimal) - └── RecordedAt (DateTime) +- `doc/LOGGING_REVIEW.md` — logging architecture review + request/response logging recommendations. +- `doc/error_handling_and_response_standard.md` — API error response + status code standardization. +- `doc/worker_jobs_and_event_flow_review.md` — Worker jobs + event flow review and hardening plan. -InsiderTransaction - ├── Id (int) - ├── ProductId (FK → Product) - ├── InsiderName (string) - ├── TransactionType (string) ← ""Buy"" or ""Sell"" - ├── Shares (long) - ├── ValueUsd (decimal) - └── TransactionDate (DateTime) +## Can we log UI to Seq? -NewsRecord - ├── Id (int) - ├── ProductId (FK → Product) - ├── Symbol (string) - ├── Headline (string) - ├── Source (string) - ├── Url (string) - └── PublishedAt (DateTime) +Yes, but choose the source carefully: -EventLog - ├── Id (int) - ├── MessageId (string) ← From SNS - ├── EventType (string) - ├── Payload (string) ← JSON - ├── Status (string) ← ""Published"" | ""Processed"" | ""Failed"" - └── CreatedAt (DateTime) -``` +### 1) Next.js server-side logs (recommended) ---- +For logs produced on the server (API routes, server actions, SSR), you can send logs to Seq directly from Node **without exposing the Seq API key to browsers**. -## 🚀 Future Enterprise Extension (DynamoDB Polyglot Strategy) +### 2) Browser/client logs (use a proxy) -When raw telemetry events outgrow Postgres and Redis connections bottleneck: +Do not ship a Seq ingestion API key in frontend code. -1. **Replaces Postgres `EventLog`:** A DynamoDB `InventoryAlert_EventLog` table would use `ExpiresAt` (Epoch) for AWS-native auto-cleanup, shedding millions of stale events without requiring massive SQL `DELETE` sweeps. -2. **Replaces Redis Deduplication:** DynamoDB has persistent TTL semantics. Instead of limiting memory in Redis clusters, worker nodes can do a cost-efficient atomic `PutItem` to check if a `MessageId` or `alert:history:{symbol}` exists, naturally expiring stale histories. -3. **Merges Timeseries Metrics:** Rather than maintaining `EarningsRecord`, `InsiderTransaction`, and `NewsRecord` across multiple SQL tables with foreign keys, a single NoSQL table `InventoryAlert_StockHistory` stores it all via composite Sort Keys (`NEWS#2026-04-04`, `EARNINGS#2026Q4`), creating a blazing-fast audit trail view. +Instead: ---- +- UI sends **sanitized** client telemetry/logs to a backend endpoint you own (API). +- API forwards to Seq (adds server-side auth, rate limiting, redaction, and `CorrelationId`). -## 🖥️ Docker Services (Final State) +### 3) Correlation across UI → API → Worker -```yaml -services: - api: # REST API + Event Publisher - worker: # Hangfire + SQS Consumer - db: # PostgreSQL 17-alpine — healthcheck: pg_isready - redis: # Redis 7.2-alpine — healthcheck: redis-cli ping - moto: # motoserver/moto:5.1.22 — Mock SNS/SQS, healthcheck: curl :5000 - moto-init: # amazon/aws-cli:2.3.4 — one-shot init: creates SNS + SQS on boot -``` +To make “search the flow by 1 id” work end-to-end: -> **Startup order enforced by `depends_on`:** -> `db` + `redis` + `moto` (healthchecks) → `moto-init` (completed) → `api` + `worker` +- UI should propagate `X-Correlation-Id` on outbound requests (or accept it from API responses and reuse it for subsequent calls). +- API stamps `X-Correlation-Id` for every request (already present). +- API must stamp `EventEnvelope.CorrelationId` when publishing async events (required for Worker tracing).",44,cb0d813a9994a860907f16d5b9e42a8b,doc\archive\OBSERVABILITY.md,0,333,"logs, server, worker, correlation, logging, review, request, response",1779814416.3892374,10,periodictimer hosted service backgroundservice asnotracking notification finnhubpricesyncworker threshold dbcontext efcore appdbcontext price drop entity framework loss,# Observability (Central) | Observability (Central) This page centralizes the “how we observe/debug the syst +doc,"# Implementation Plan: Centralized Observability with Seq -### Worker Dockerfile +This plan replaces ELK with **Seq**, focusing on a high-performance, developer-friendly logging experience optimized for the .NET ecosystem. We will implement end-to-end trace correlation from the initial UI/API request through business logic, background jobs, and database interactions. -Located at `InventoryAlert.Worker/Dockerfile`. Uses `dotnet/runtime:10.0` -(not `aspnet`) since the Worker has no HTTP listener. +## 1. Core Principles +- **Structured-First**: No string interpolation in logs; use property templates (`""User {UserId} logged in""`) for indexing. +- **Trace Continuity**: A single `CorrelationId` must bridge the gap between HTTP requests and asynchronous SQS/Hangfire jobs. +- **Contextual Enrichment**: Logs should ""know"" where they are (Service, Environment, Version) without manual boilerplate. --- -## ✅ Implementation Checklist - -### Phase A — Contracts & Infrastructure - -- [x] Create `InventoryAlert.Contracts` project -- [x] Define `EventEnvelope` record -- [x] Define all Payload records (Price, Earnings, Insider, News, StockLow) -- [x] Add Contracts reference to Api, Worker, and Sample projects +## 2. Infrastructure: The Seq Stack +We will use a lightweight, single-node Seq instance: +- **Seq Server**: ingestion via HTTP/CLEF (Compact Log Event Format). +- **Serilog.Sinks.Seq**: Native .NET sink for efficient, buffered shipping. +- **Docker Integration**: Seq runs as a container in `docker-compose.yml`. -### Phase B — API (Publisher Side) +--- -- [x] Create `IEventPublisher` interface -- [x] Implement `SnsEventPublisher` (using AWSSDK.SQS/SNS pointing to Moto) -- [x] Create `EventLog` entity + EF Migration -- [x] Create `EventsController` with POST endpoints -- [x] Register `IEventPublisher` in DI +## 3. The ""Whole Flow"" Logging Checklist -### Phase C — Worker Project +### 🟢 Layer 1: The Request (Web/API) +- [ ] **Correlation Middleware**: Generate or extract `X-Correlation-ID` from headers. +- [ ] **LogContext Enrichment**: Use `Serilog.Context.LogContext.PushProperty(""CorrelationId"", cid)` at the start of every request. +- [ ] **Request Logging**: Log the incoming path, method, and User ID (from JWT). +- [ ] **Global Error Capture**: Middleware must capture unhandled exceptions and log them with `Log.Error(ex, ""Request failed"")`. -- [x] Create `InventoryAlert.Worker` as a Worker Service -- [x] Install Hangfire + `Hangfire.PostgreSql` -- [x] Add Worker to `docker-compose.yml` (with Dockerfile + appsettings.Docker.json) -- [x] Moto init script: `SolutionFolder/moto-init/init-sqs.sh` creates SNS + SQS -- [x] Create `PollSqsJob` — SQS dequeue + event routing -- [x] Create `SyncPricesJob` — replaces current `FinnhubSyncWorker` -- [x] Create `EarningsCheckJob` — calls `/stock/earnings` -- [x] Create `InsiderTxCheckJob` — calls `/stock/insider-transactions` -- [x] Create `NewsCheckJob` — calls `/company-news` -- [x] Implement Redis caching inside each job -- [x] Add Worker to `docker-compose.yml` +### 🟡 Layer 2: The Method (Application/Services) +- [ ] **Method Parameters**: Log critical entry points with structured arguments (e.g., `Log.Debug(""Processing alert for {Symbol}"", symbol)`). +- [ ] **Performance Timings**: (Optional) Use `SerilogTimings` for high-value business operations. +- [ ] **Business Events**: Log result outcomes (Success/Failure/Ignored) rather than just ""Method Finished"". -### Phase D — Event Handlers (inside Worker) +### 🟠 Layer 3: The Job (Worker/Hangfire) +- [ ] **Context Propagation**: The `EventEnvelope` must carry the `CorrelationId`. +- [ ] **Job Scoping**: The Worker `SqsDispatcher` must re-hydrate the `LogContext` using the ID from the envelope before calling the processor. +- [ ] **Retry Tracking**: Log the `ReceiveCount` to track problematic messages in Seq. -- [x] `PriceAlertHandler` → log + trigger Telegram notification -- [x] `EarningsHandler` → persist `EarningsRecord` to DB -- [x] `InsiderHandler` → persist `InsiderTransaction` to DB -- [x] `NewsHandler` → persist `NewsRecord` to DB +### 🔵 Layer 4: The Database (Infrastructure/EF Core) +- [ ] **EF Core Interceptors**: Configure `LogTo(Log.Information)` or an `ItemInterceptor` to tag DB commands with the current `CorrelationId`. +- [ ] **Transaction Boundary**: Log when transactions begin and commit/roll back. -### Phase E — Sample Publisher +--- -- [x] Create `InventoryAlert.Sample` console app -- [x] Implement HTTP client posting to `/api/events` -- [x] Implement direct-to-Moto-SQS publisher (bypass API) -- [x] Add interactive menu with all event types +## 4. Implementation Details -### Phase F — Telegram Integration +### 4.1 Serilog Global Configuration +Centralized initialization in `Program.cs`: +```csharp +Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .Enrich.FromLogContext() + .Enrich.WithProperty(""Application"", ""InventoryAlert.Api"") + .WriteTo.Seq(settings.Seq.ServerUrl, apiKey: settings.Seq.ApiKey) + .WriteTo.Console() + .CreateLogger(); +``` -- [x] Create `TelegramAlertNotifier` implementing `IAlertNotifier` -- [x] Add `Telegram:BotToken` and `Telegram:ChatId` to AppSettings -- [x] Register notifier in DI (replaced `ConsoleAlertNotifier` in API) -- [x] Add `TELEGRAM_BOT_TOKEN` to `appsettings.Example.json` +### 4.2 Middleware Implementation (API) +```csharp +public class CorrelationIdMiddleware(RequestDelegate next) +{ + public async Task InvokeAsync(HttpContext context) + { + var correlationId = context.Request.Headers[""X-Correlation-ID""].FirstOrDefault() ?? Guid.NewGuid().ToString(); + using (LogContext.PushProperty(""CorrelationId"", correlationId)) + { + context.Response.Headers.Append(""X-Correlation-ID"", correlationId); + await next(context); + } + } +} +``` --- -### Phase G — Shared Entity Migration ✅ - -> Moved all domain entities shared between API and Worker out of `InventoryAlert.Api.Domain.Entities` -> into `InventoryAlert.Contracts.Entities` — single source of truth. - -- [x] `Product` → `InventoryAlert.Contracts.Entities.Product` -- [x] `EventLog` → `InventoryAlert.Contracts.Entities.EventLog` -- [x] `EarningsRecord` → `InventoryAlert.Contracts.Entities.EarningsRecord` -- [x] `InsiderTransaction` → `InventoryAlert.Contracts.Entities.InsiderTransaction` -- [x] `NewsRecord` → `InventoryAlert.Contracts.Entities.NewsRecord` -- [x] All `using` statements updated in Api, Worker, and Tests projects -- [x] `AWSSDK.SimpleNotificationService` + `AWSSDK.SQS` installed in `InventoryAlert.Sample` -- [x] Full solution build: **0 errors** ✅ -- [x] Full test run: **61/61 passed** ✅ +## 5. Execution Phases -**EF Configuration strategy:** Each service keeps its own `DbContext` with inline EF fluent configs. -`Contracts` remains a plain POCO library with no EF dependency — clean separation. +| Phase | Task | Details | +| :--- | :--- | :--- | +| **Phase 1** | **Seq Setup** | Add Seq to `docker-compose.yml` (Port 5341). | +| **Phase 2** | **Base Instrumentation** | Install `Serilog.Sinks.Seq` and implement `CorrelationIdMiddleware` in Api. | +| **Phase 3** | **Worker Re-hydration** | Update `SqsDispatcher` to push `CorrelationId` from envelope to `LogContext`. | +| **Phase 4** | **EF Core Tagging** | Configure DB logging to include correlation context in SQL commands. | --- -> **Priority Order:** A → B → C → D → E → F → G -> -> The existing `FinnhubSyncWorker` in the API has been **retired** — `SyncPricesJob` in the Worker now owns all background price sync logic.",462,661ae820214a444d2e8c2cae15bcc3c5,doc\archive\EVENT_DRIVEN_PLAN.md,0,310,"worker, inventoryalert, event, contracts, events, news, create, project",1775670503.9143393,1,commit quote returns async postgres asnotracking loss notification business logic hosted service verify database update appdbcontext arrange act assert compose finnhubpricesyncworker unit test productservice item schema change iactionresult threshold atomicity mock setup xunit moq dbcontext external api times once container savechanges efcore rollback entity framework httpget postgresql backgroundservice stock httpput efcore migration add-migration application service stock price periodictimer fluentassertions sku market data productscontroller inventory httppost dockerfile price drop iproductservice unitofwork,# 🏗️ Event-Driven Architecture Plan | 🏗️ Event-Driven Architecture Plan Hangfire + SNS/SQS + Redis + Multi-Project Sy -doc,"# 🛠️ Project Setup — Names & Commands +## 6. Expected Outcome +> *""In Seq, you filter by `CorrelationId == 'abc-123'`. You see the HTTP POST `/api/market-alert`, followed by the Service log, the SQS Publish log, and finally the Worker log executing the price check—all unified in one timeline.""*",88,0db0046be3ac503ff4e467fb347203af,doc\archive\observability_refactor_plan.md,0,334,"correlationid, from, request, phase, logging, correlation, core, must",1775670503.9359772,1,unitofwork rollback compose application service container hosted service asnotracking postgres postgresql entity framework appdbcontext finnhubpricesyncworker loss periodictimer dockerfile savechanges productservice efcore commit atomicity threshold backgroundservice iproductservice price drop business logic notification dbcontext,# Implementation Plan: Centralized Observability with Seq | Implementation Plan: Centralized Observability with Seq This plan replaces ELK w +doc,"--- +description: Plan for Contracts consolidation, DynamoDB telemetry, event handler pattern, and retry/DLQ strategy +type: plan +status: active +version: 1.0 +tags: [architecture, contracts, dynamodb, events, retry, dlq] +last_updated: 2026-04-05 +---",9,9eac0efb5257aa8b5298118948bd0dc2,doc\archive\PHASE2_PLAN.md,0,335,"plan, contracts, dynamodb, retry, description, consolidation, telemetry, event",1775670503.9190905,1,fluentassertions data access sku loss schema change add-migration business logic postgres efcore periodictimer dbcontext iproductrepository iproductservice stock productservice xunit unit test application service appdbcontext dockerfile igenericrepository dbset item finnhubpricesyncworker backgroundservice commit compose savechanges postgresql unitofwork container hosted service rollback notification domain driven design inventory stock price entity framework infrastructure threshold efcore migration external api application layer domain entity quote market data asnotracking atomicity database update price drop arrange act assert,"PHASE2_PLAN.md | --- description: Plan for Contracts consolidation, DynamoDB telemetry, event han" +doc,"# 🏗️ Phase 2 Architecture Plan -> Run all commands from inside `InventoryManagementSystem/` -> unless stated otherwise. +> **Scope:** Shared-project consolidation, standardized event handling, retry/DLQ mechanism, and DynamoDB integration for event telemetry. --- -## 📁 Final Project Names +## 1. 📦 Shared Project Consolidation (`InventoryAlert.Contracts`) -| Project | Type | Purpose | -| :------------------------- | :-------------- | :---------------------------------------------- | -| `InventoryAlert.Api` | ASP.NET Web API | ✅ Existing — extended with event endpoints | -| `InventoryAlert.Contracts` | Class Library | ✅ Done — shared event schemas + domain entities | -| `InventoryAlert.Worker` | Worker Service | ✅ Done — Hangfire + SQS consumer | -| `InventoryAlert.Sample` | Console App | ✅ Done — sample event publisher | -| `InventoryAlert.Tests` | xUnit Test | ✅ Existing | +### Problem ---- +`InventoryAlert.Api` and `InventoryAlert.Worker` each had their own copy of domain entities, causing subtle divergence bugs. The fix was started in Phase 1 but needs to be enforced with a hard architectural gate. -## ⚡ Step 1 — Create New Projects +### Target Structure -```powershell -cd InventoryManagementSystem",24,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,311,"inventoryalert, project, event, done, names, commands, inventorymanagementsystem, existing",1775670503.9143393,1,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# 🛠️ Project Setup — Names & Commands | 🛠️ Project Setup — Names & Commands > Run all commands from inside InventoryMana -doc,"# 1. Shared contracts (event schemas) -dotnet new classlib -n InventoryAlert.Contracts -o InventoryAlert.Contracts",27,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,312,"contracts, inventoryalert, shared, event, schemas, dotnet, classlib",1775670503.9143393,25,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# 1. Shared contracts (event schemas) | 1 -doc,"# 2. Background worker (Hangfire + SQS) -dotnet new worker -n InventoryAlert.Worker -o InventoryAlert.Worker",30,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,313,"worker, inventoryalert, background, hangfire, dotnet",1775670503.9143393,28,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# 2. Background worker (Hangfire + SQS) | 2 -doc,"# 3. Sample publisher CLI -dotnet new console -n InventoryAlert.Sample -o InventoryAlert.Sample +```text +InventoryAlert.Contracts/ +├── Entities/ +│ ├── Product.cs ✅ Live +│ ├── EventLog.cs ✅ Live +│ ├── EarningsRecord.cs ✅ Live +│ ├── InsiderTransaction.cs ✅ Live +│ └── NewsRecord.cs ✅ Live +├── Events/ +│ ├── EventEnvelope.cs ✅ Updated — EventType + Payload + CorrelationId +│ ├── EventTypes.cs ✅ Updated — reverse-DNS naming +│ └── Payloads/ ✅ All payload types +└── Constants/ + └── AlertConstants.cs ✅ Live — CacheKeys, EventTypes, SqsHeaders ``` ---- +### Rules (enforced by DDD skill) -## ⚡ Step 2 — Add to Solution +- `InventoryAlert.Api` imports: `Contracts` only (via `global using` aliases in `SharedEntityAliases.cs`). +- `InventoryAlert.Worker` imports: `Contracts` only (via `SharedEntityAliases.cs`). +- No entity definition may exist in `Api.Domain.Entities` or `Worker.*` — any addition goes to `Contracts` first. -```powershell -dotnet sln add InventoryAlert.Contracts/InventoryAlert.Contracts.csproj -dotnet sln add InventoryAlert.Worker/InventoryAlert.Worker.csproj -dotnet sln add InventoryAlert.Sample/InventoryAlert.Sample.csproj -``` +### Remaining Tasks + +- [x] Add `ArchitectureTests` project using `NetArchTest.Rules` to enforce zero-duplication at CI time. +- [x] Move `AppSettings` Finnhub/AWS sections to `Contracts.Configuration` so both services share config models. --- -## ⚡ Step 3 — Add Project References +## 2. 🎯 Event Handler Pattern (Dispatcher Architecture) -### `InventoryAlert.Api` references `Contracts` +### Problem -```powershell -dotnet add InventoryAlert.Api/InventoryAlert.Api.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj -``` +`PollSqsJob` used a `switch` statement that required modifying the job class itself whenever a new event type was added — violating OCP. -### `InventoryAlert.Worker` references `Contracts` +### Solution Implemented ✅ -```powershell -dotnet add InventoryAlert.Worker/InventoryAlert.Worker.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +```text +SQS Message → PollSqsJob + │ + ▼ + Dictionary Dispatcher + (EventType → Func) + │ + ┌─────────┴─────────────────────────────────┐ + │ │ │ │ + PriceAlert Earnings InsiderSell CompanyNews + Handler Handler Handler Handler + │ + (unknown EventType) + │ + UnknownEventHandler + (logs warning + ACKs) ``` -### `InventoryAlert.Sample` references `Contracts` +### Interface Contract -```powershell -dotnet add InventoryAlert.Sample/InventoryAlert.Sample.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +```csharp +public interface IEventHandler +{ + Task HandleAsync(TPayload payload, CancellationToken ct = default); +} ``` +### Adding a New Handler + +1. Add a constant to `EventTypes.cs`: + ```csharp + public const string MyNewEvent = ""inventoryalert.domain.action.v1""; + ``` +2. Add payload to `Contracts/Events/Payloads/MyNewEventPayload.cs`. +3. Create `Worker/Handlers/MyNewHandler.cs` implementing `IEventHandler`. +4. Register in `Worker/Program.cs`: `builder.Services.AddScoped, MyNewHandler>()`. +5. Add one entry to the `BuildDispatcher()` dictionary in `PollSqsJob`. + --- -## ⚡ Step 4 — Install NuGet Packages +## 3. 🔁 Retry & Dead Letter Queue (DLQ) Mechanism -### `InventoryAlert.Api` — Event publishing +### Design -```powershell",73,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,314,"inventoryalert, csproj, contracts, sample, dotnet, powershell, worker, reference",1775670503.9143393,31,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# 3. Sample publisher CLI | 3 -doc,"# AWS SNS publisher (talks to Moto at localhost:5000) -dotnet add InventoryAlert.Api package AWSSDK.SimpleNotificationService -dotnet add InventoryAlert.Api package AWSSDK.SQS +``` +SQS Queue (MaxReceiveCount=3) + │ + ├── Attempt 1: Handler throws → no ACK → message invisible for VisibilityTimeout + ├── Attempt 2: SQS redelivers → fails again + ├── Attempt 3: SQS redelivers → fails again + │ + └── SQS RedrivePolicy → DLQ automatically (after 3 receives) + │ + └── Optional: PollSqsJob.MoveToDlqAsync() for explicit manual DLQ push ``` -### `InventoryAlert.Worker` — Hangfire + SQS consumer + Redis + DB +### Configuration (SQS Redrive Policy — in Moto init script) -```powershell",81,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,315,"dotnet, inventoryalert, package, awssdk, publisher, talks, moto, localhost",1775670503.9143393,74,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# AWS SNS publisher (talks to Moto at localhost:5000) | AWS SNS publisher (talks to Moto at localhost:5000) dotnet add InventoryAlert.Ap -doc,"# Hangfire core -dotnet add InventoryAlert.Worker package Hangfire.AspNetCore -dotnet add InventoryAlert.Worker package Hangfire.PostgreSql",85,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,316,"hangfire, dotnet, inventoryalert, worker, package, core, aspnetcore, postgresql",1775670503.9143393,82,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# Hangfire core | Hangfire core dotnet add InventoryAlert.Worker package Hangfire.AspNetCore dotne -doc,"# SQS consumer -dotnet add InventoryAlert.Worker package AWSSDK.SQS",88,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,317,"consumer, dotnet, inventoryalert, worker, package, awssdk",1775670503.9143393,86,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# SQS consumer | SQS consumer dotnet add InventoryAlert.Worker package AWSSDK.SQS -doc,"# Redis caching -dotnet add InventoryAlert.Worker package Microsoft.Extensions.Caching.StackExchangeRedis",91,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,318,"caching, redis, dotnet, inventoryalert, worker, package, microsoft, extensions",1775670503.9143393,89,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# Redis caching | Redis caching dotnet add InventoryAlert.Worker package Microsoft.Extensions.Cach -doc,"# EF Core (share same DB) -dotnet add InventoryAlert.Worker package Npgsql.EntityFrameworkCore.PostgreSQL -dotnet add InventoryAlert.Worker package Microsoft.EntityFrameworkCore.Design",95,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,319,"dotnet, inventoryalert, worker, package, entityframeworkcore, core, share, same",1775670503.9143393,92,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# EF Core (share same DB) | EF Core (share same DB) dotnet add InventoryAlert.Worker package Npgsql.EntityFr -doc,"# HTTP client (for Finnhub calls) -dotnet add InventoryAlert.Worker package RestSharp +```bash +aws sqs set-queue-attributes \ + --queue-url http://localhost:4566/000000000000/inventory-queue \ + --attributes '{ + ""RedrivePolicy"": ""{ + \""deadLetterTargetArn\"": \""arn:aws:sqs:us-east-1:000000000000:inventory-dlq\"", + \""maxReceiveCount\"": \""3\"" + }"" + }' ``` -### `InventoryAlert.Worker` — DynamoDB (Future Enterprise Extension) - -> **⚠️ Optional:** Only install when migrating from Postgres `EventLog` and Redis dedup -> to the polyglot DynamoDB strategy described in `EVENT_DRIVEN_PLAN.md`. +### Responsibility Split -```powershell",105,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,320,"http, client, finnhub, calls, dotnet, inventoryalert, worker, package",1775670503.9143393,96,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# HTTP client (for Finnhub calls) | HTTP client (for Finnhub calls) dotnet add InventoryAlert.Worker package RestSha -doc,"# DynamoDB client + object persistence model -dotnet add InventoryAlert.Worker package AWSSDK.DynamoDBv2 -``` +| Scenario | Action | Responsibility | +| :--- | :--- | :--- | +| Handler throws | Do NOT delete — SQS redelivers | `PollSqsJob` (by design) | +| Receive count > 3 | MoveToDlq + delete from main queue | `PollSqsJob.MoveToDlqAsync()` | +| Unknown EventType | Log warning + ACK (DELETE) | `UnknownEventHandler` | +| Bad JSON | Log + MoveToDlq + ACK | `PollSqsJob.ProcessMessageAsync()` | +| Duplicate (Redis deduplicated) | ACK without processing | `PollSqsJob` | -### `InventoryAlert.Sample` — HTTP client to call the API +### Tasks -```powershell -dotnet add InventoryAlert.Sample package Microsoft.Extensions.Http -``` +- [ ] Update `moto-init/init-sqs.sh` to create `inventory-dlq` queue and configure RedrivePolicy. +- [ ] Add `SqsDlqUrl` to `appsettings.Docker.json` and `appsettings.json`. +- [ ] Add a DLQ monitor/alerter (future: Lambda or Worker polling DLQ for notifications). --- -## ⚡ Step 5 — Verify Solution Builds - -```powershell -dotnet build InventoryManagementSystem.sln -``` +## 4. 🗄️ DynamoDB Integration Plan ---- +### Why DynamoDB? -## ⚙️ Step 6 — Environment Variables Needed +| Requirement | PostgreSQL | DynamoDB | +| :--- | :--- | :--- | +| Relational CRUD (Products) | ✅ Perfect fit | Overkill | +| High-throughput event logs | ❌ Table grows unbounded | ✅ Designed for it | +| TTL-based auto-expiry | ❌ Requires cron jobs | ✅ Native TTL per-item | +| Deduplication store | ❌ Requires explicit cleanup | ✅ TTL + conditional writes | +| SQS message audit trail | ❌ Schema migrations | ✅ Schema-less, append-only | -Add these to your `.env` file (and `.env.example`): +### Target: EventLog Table -```env",130,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,321,"dotnet, inventoryalert, package, powershell, dynamodb, client, object, persistence",1775670503.9143393,106,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# DynamoDB client + object persistence model | DynamoDB client + object persistence model dotnet add InventoryAlert.Worker pack -doc,"# Existing -DB_PASSWORD=password -FINNHUB_API_KEY=your_key_here",134,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,322,"existing, password",1775670503.9143393,131,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# Existing | Existing DB_PASSWORD=password FINNHUB_API_KEY=your_key_here -doc,"# New — AWS / Moto -AWS_ACCESS_KEY_ID=test -AWS_SECRET_ACCESS_KEY=test -AWS_DEFAULT_REGION=us-east-1 -AWS_ENDPOINT_URL=http://moto:5000 # inside Docker",139,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,323,"moto, test, east, http, inside, docker",1775670503.9143393,135,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# New — AWS / Moto | New — AWS / Moto AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_R -doc,# AWS_ENDPOINT_URL=http://localhost:5000 # from host machine,141,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,324,"http, localhost, from, host, machine",1775670503.9143393,140,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# AWS_ENDPOINT_URL=http://localhost:5000 # from host machine | AWS_ENDPOINT_URL=http://localhost:5000 from host machine -doc,"# New — SNS/SQS resource names (Moto will create these on startup) -SNS_TOPIC_ARN=arn:aws:sns:us-east-1:123456789012:inventory-events -SQS_QUEUE_URL=http://moto:5000/123456789012/event-queue",145,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,325,"moto, resource, names, will, create, these, startup, east",1775670503.9143393,142,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# New — SNS/SQS resource names (Moto will create these on startup) | New — SNS/SQS resource names (Moto will create these on startup) SNS_TOPIC_ARN=a -doc,"# New — Redis -REDIS_CONNECTION=redis:6379 # inside Docker",147,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,326,"redis, inside, docker",1775670503.9143393,146,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# New — Redis | New — Redis REDIS_CONNECTION=redis:6379 inside Docker -doc,# REDIS_CONNECTION=localhost:6379 # from host machine,149,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,327,"localhost, from, host, machine",1775670503.9143393,148,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# REDIS_CONNECTION=localhost:6379 # from host machine | REDIS_CONNECTION=localhost:6379 from host machine -doc,"# Future — Telegram -TELEGRAM_BOT_TOKEN=your_bot_token_here -TELEGRAM_CHAT_ID=your_chat_id_here -``` +```text +Table: inventory-event-logs -> **Note:** Moto accepts any value for `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`. -> Use `test` / `test` locally — it works without real credentials. +PK: EventType (String) — partition key +SK: MessageId (String) — sort key (unique per event) ---- +Attributes: + Source — emitting service + Payload — raw JSON (for audit trail) + CorrelationId — cross-service trace ID + ProcessedAt — ISO8601 UTC string + TTL — Unix epoch (auto-delete after 90 days) + Status — ""processed"" | ""failed"" | ""skipped"" +``` -## 🐳 Step 7 — Add Worker to `docker-compose.yml` +### Required NuGet -```yaml -worker: - build: - context: . - dockerfile: InventoryAlert.Worker/Dockerfile - container_name: inventory_worker - environment: - - ASPNETCORE_ENVIRONMENT=Docker - - Database__DefaultConnection=host=db;port=5432;Database=InventoryAlertDb;Username=postgres;Password=password - - Redis__Connection=redis:6379 - - Aws__EndpointUrl=http://moto:5000 - - Aws__SnsTopicArn=arn:aws:sns:us-east-1:123456789012:inventory-events - - Aws__SqsQueueUrl=http://moto:5000/123456789012/event-queue - depends_on: - db: - condition: service_healthy - networks: - - app-network - restart: unless-stopped +```powershell +dotnet add InventoryAlert.Worker package AWSSDK.DynamoDBv2 ``` ---- +> Already installed ✅ -## ✅ Quick Checklist +### Implementation Phases -``` -[✅] dotnet new classlib → InventoryAlert.Contracts ✅ Done -[✅] dotnet new worker → InventoryAlert.Worker ✅ Done -[✅] dotnet new console → InventoryAlert.Sample ✅ Done -[✅] dotnet sln add → 3 projects added to .sln ✅ Done -[✅] dotnet add reference → Contracts in Api + Worker + Sample ✅ Done -[✅] dotnet add package → All NuGet packages installed ✅ Done - - Api: AWSSDK.SNS + SQS + Serilog + FluentValidation - - Worker: Hangfire + SQS + Redis + EF + RestSharp - - Sample: AWSSDK.SNS + SQS + Microsoft.Extensions.Http -[✅] Entities migrated → Contracts/Entities/ folder ✅ Done - (Product, EventLog, EarningsRecord, InsiderTransaction, NewsRecord) -[✅] .env → AWS + Redis keys added ✅ Done -[✅] docker-compose.yml → Worker service added ✅ Done -[✅] dotnet build → Full solution compiles ✅ Done -[✅] dotnet test → 61/61 tests pass ✅ Done -```",203,c85bb0c664c4b47eb2c712be55e122a8,doc\archive\EVENT_SETUP_COMMANDS.md,0,328,"done, dotnet, worker, inventoryalert, redis, http, contracts, sample",1775670503.9143393,150,dockerfile market data hosted service stock item entity framework savechanges threshold rollback unit test appdbcontext xunit periodictimer dbcontext productservice application service fluentassertions arrange act assert asnotracking sku notification backgroundservice price drop iproductservice loss container compose efcore postgresql finnhubpricesyncworker inventory postgres unitofwork atomicity business logic stock price quote commit external api,# Future — Telegram | Future — Telegram TELEGRAM_BOT_TOKEN=your_bot_token_here TELEGRAM_CHAT_ID=your_c -doc,"--- -description: Business capabilities, REST API reference, and workflows for the Inventory Alert System. -type: reference -status: active -version: 2.0 -tags: [business, features, api, workflows, reference] -last_updated: 2026-04-05 ----",9,51a503b6410630f3c5b56f98bc5b895a,doc\archive\FEATURES_OVERVIEW.md,0,329,"reference, business, workflows, description, capabilities, rest, inventory, alert",1775670503.9164877,1,external api appdbcontext atomicity compose postgres stock price httpget httppost fluentassertions quote unitofwork postgresql commit container business logic xunit data access iactionresult periodictimer msft market data dockerfile price drop arrange act assert entity framework productservice rollback notification inventory finnhubpricesyncworker backgroundservice asnotracking httpput iproductservice googl threshold dbset productscontroller sku stock hosted service stock ticker savechanges iproductrepository loss item symbol dbcontext efcore unit test aapl igenericrepository application service,"FEATURES_OVERVIEW.md | --- description: Business capabilities, REST API reference, and workflows for th" -doc,"# 🛒 Inventory Alert System — Features & API Reference +#### Phase 4A — Infrastructure Setup -> This document covers **business capabilities, API endpoints, and user-facing workflows**. -> For system architecture, Docker setup, and project internals, see [`PROJECT_OVERVIEW.md`](PROJECT_OVERVIEW.md). +- [ ] Add `DynamoDbSettings` to `WorkerSettings` (table name, endpoint). +- [ ] Register `IAmazonDynamoDB` in `Worker/Program.cs`. +- [ ] Create `Worker/Persistence/EventLogDynamoRepository.cs`. +- [ ] Create DynamoDB table in `moto-init/init-dynamodb.sh`. ---- +#### Phase 4B — Telemetry Write -## 🔐 0. Authentication +- [ ] In `PollSqsJob`, after successful dispatch: write event to DynamoDB with `Status=""processed""`. +- [ ] On handler failure: write with `Status=""failed""` before re-throwing. +- [ ] Set TTL = `ProcessedAt + 90 days`. -All `ProductsController` endpoints require a valid **JWT Bearer token**. +#### Phase 4C — Query API (optional) -### Login +- [ ] Add `GET /api/events?symbol=AAPL&limit=20` endpoint in Api. +- [ ] Api calls DynamoDB via `IAmazonDynamoDB` (query by EventType + date range). +- [ ] Dashboard ""Alerts Feed"" view connects to this endpoint. + +### DynamoDB Table Schema + +```csharp +public class EventLogEntry +{ + [DynamoDBHashKey(""EventType"")] + public string EventType { get; set; } = string.Empty; + + [DynamoDBRangeKey(""MessageId"")] + public string MessageId { get; set; } = string.Empty; + + public string Source { get; set; } = string.Empty; + public string Payload { get; set; } = string.Empty; + public string CorrelationId { get; set; } = string.Empty; + public string ProcessedAt { get; set; } = string.Empty; + public string Status { get; set; } = string.Empty; + + [DynamoDBProperty(""TTL"")] + public long Ttl { get; set; } // Unix epoch for DynamoDB native TTL +} +``` + +--- + +## 📋 Task Checklist + +### Contracts ✅ + +- [x] Centralize all entities in `InventoryAlert.Contracts` +- [x] Add `Constants/AlertConstants.cs` +- [x] Standardize `EventEnvelope` fields +- [ ] Add architecture enforcement tests + +### Event Handler Pattern ✅ + +- [x] `IEventHandler` interface +- [x] Dictionary dispatcher in `PollSqsJob` +- [x] `UnknownEventHandler` fallback +- [x] All existing handlers implement `IEventHandler` + +### Event Types ✅ + +- [x] Reverse-DNS naming convention (`inventoryalert.domain.action.v1`) +- [x] `EventTypes.IsKnown()` for dispatch validation +- [x] `IReadOnlySet` for O(1) lookup + +### Retry / DLQ ✅ + +- [x] `ApproximateReceiveCount` check (> 3 → manual DLQ) +- [x] ACK-only-on-success pattern in dispatcher +- [x] Moto `init-sqs.sh` RedrivePolicy configuration +- [x] `SqsDlqUrl` in appsettings files + +### DynamoDB ✅ + +- [x] Phase 4A: Infrastructure setup +- [x] Phase 4B: Telemetry write on process/fail +- [x] Phase 4C: Query API endpoint + +--- + +> **Next:** Run `/feature-flow` to implement DynamoDB Phase 4A.",267,9eac0efb5257aa8b5298118948bd0dc2,doc\archive\PHASE2_PLAN.md,0,336,"dynamodb, phase, event, contracts, worker, pollsqsjob, inventoryalert, init",1775670503.9190905,10,fluentassertions data access sku loss schema change add-migration business logic postgres efcore periodictimer dbcontext iproductrepository iproductservice stock productservice xunit unit test application service appdbcontext dockerfile igenericrepository dbset item finnhubpricesyncworker backgroundservice commit compose savechanges postgresql unitofwork container hosted service rollback notification domain driven design inventory stock price entity framework infrastructure threshold efcore migration external api application layer domain entity quote market data asnotracking atomicity database update price drop arrange act assert,"# 🏗️ Phase 2 Architecture Plan | 🏗️ Phase 2 Architecture Plan > Scope: Shared-project consolidation, standardized" +doc,"--- +description: Deep technical reference for the InventoryManagementSystem solution — architecture, layers, event pipeline, storage, and CI/CD. +type: reference +status: active +version: 3.0 +tags: [architecture, ddd, event-driven, infrastructure, reference] +last_updated: 2026-04-05 +---",9,907bc14da43f58caaffbfdb79b54834d,doc\archive\PROJECT_OVERVIEW.md,0,337,"reference, architecture, event, description, deep, technical, inventorymanagementsystem, solution",1779851803.8378093,1,asnotracking entity framework dockerfile httpget notification external api symbol rollback hosted service unitofwork efcore executetransactionasync iactionresult inventory commit fluentassertions httpput periodictimer times once httppost item sku infrastructure arrange act assert iproductrepository aapl market data atomicity compose postgres appdbcontext finnhubpricesyncworker quote iunitofwork savechangesasync moq dbset business logic domain driven design postgresql msft data access igenericrepository savechanges stock price stock ticker productservice loss stock xunit returns async container mock setup domain entity unit test dbcontext application service backgroundservice googl verify application layer threshold iproductservice productscontroller price drop,PROJECT_OVERVIEW.md | --- description: Deep technical reference for the InventoryManagementSystem solu +doc,"# 🏗️ Inventory Alert System — Technical Architecture + +> This document covers **architecture, infrastructure, and system internals only**. +> For business workflows and REST API listing, see [`FEATURES_OVERVIEW.md`](FEATURES_OVERVIEW.md). + +--- + +## 1. Solution Project Map + +| Project | SDK | Role | +| ---------------------------------- | ----------------------- | ------------------------------------------------------------------- | +| `InventoryAlert.Api` | `Microsoft.NET.Sdk.Web` | REST API — Controllers, Application Services, Infrastructure | +| `InventoryAlert.Worker` | `Microsoft.NET.Sdk.Web` | Background processor — Hangfire jobs, SQS consumers, Event Handlers | +| `InventoryAlert.Contracts` | `Microsoft.NET.Sdk` | Shared kernel — Entities, Events, Constants. Zero dependencies. | +| `InventoryAlert.Sample` | `Microsoft.NET.Sdk` | Local test publisher — bypasses API to directly push events to SNS | +| `InventoryAlert.UnitTests` | `Microsoft.NET.Sdk` | xUnit + Moq + FluentAssertions unit test suite | +| `InventoryAlert.IntegrationTests` | `Microsoft.NET.Sdk` | Testcontainers.PostgreSql integration tests | +| `InventoryAlert.ArchitectureTests` | `Microsoft.NET.Sdk` | NetArchTest.Rules — automated DDD boundary enforcement | + +--- + +## 2. Clean Architecture / DDD Layer Rules + +``` +InventoryAlert.Contracts ← innermost (no deps) + ↑ +InventoryAlert.Api + ├─ Domain/Interfaces/ ← Repository + UoW contracts + ├─ Application/Services/ ← Business logic (ProductService, EventService) + ├─ Application/Interfaces/ ← IProductService, IEventService, IFinnhubClient + ├─ Application/DTOs/ ← Request/Response + FinnhubQuoteResponse + ├─ Application/Mappings/ ← Manual map extensions (no AutoMapper) + ├─ Application/Validators/ ← FluentValidation rule classes + ├─ Infrastructure/Persistence/ ← AppDbContext, GenericRepository, UnitOfWork + ├─ Infrastructure/External/ ← FinnhubClient (HTTP), SnsEventPublisher, DynamoEventLogRepository + └─ Web/Controllers/ ← Thin controllers, delegate to Application +``` + +**Enforced automatically by `InventoryAlert.ArchitectureTests`** (`NetArchTest.Rules`): +- `Application.*` **must not** depend on `Infrastructure.*` +- `Web.Controllers` **must not** directly depend on `Infrastructure.*` +- All classes in `Application.Services` **must** end with `""Service""` +- All classes in `Web.Controllers` **must** inherit `ControllerBase` and end with `""Controller""` +- All classes in `Worker.Handlers` **must** end with `""Handler""` +- `InventoryAlert.Contracts` **must not** import `Microsoft.EntityFrameworkCore` or `Microsoft.AspNetCore` +- All `*Repository` interfaces **must** expose only `Task`/`Task` return types (no sync I/O) + +--- + +## 3. `InventoryAlert.Contracts` — Shared Kernel + +The `Contracts` project has **zero external NuGet dependencies** and is the single source of truth for: + +### Domain Entities + +| Class | Key Fields | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Product` | `Id`, `Name`, `TickerSymbol`, `OriginPrice`, `CurrentPrice`, `PriceAlertThreshold` (double, e.g. `0.2` = 20%), `StockCount`, `StockAlertThreshold`, `LastAlertSentAt` (nullable DateTime for alert cooldown) | +| `EventLog` | DynamoDB audit record per published event | +| `EarningsRecord` | Persisted EPS data from Finnhub earnings events | +| `NewsRecord` | Persisted company news headline | +| `InsiderTransaction` | Persisted insider sell transaction | + +### Event Pipeline Types + +**`EventEnvelope` record** — the standard wrapper for every SNS/SQS message: +```csharp +public record EventEnvelope +{ + public string MessageId { get; init; } // Guid — deduplication key + public string EventType { get; init; } // Must match EventTypes constant + public string Source { get; init; } // e.g. ""InventoryAlert.Api"" + public string Payload { get; init; } // JSON-serialized inner payload + public DateTime Timestamp { get; init; } + public string CorrelationId { get; init; } // Cross-service trace ID +} +``` + +**`EventTypes` static class** — canonical reverse-DNS event names: + +| Constant | Value | +| ------------------ | --------------------------------------------- | +| `MarketPriceAlert` | `inventoryalert.pricing.price-drop.v1` | +| `StockLowAlert` | `inventoryalert.inventory.stock-low.v1` | +| `EarningsAlert` | `inventoryalert.fundamentals.earnings.v1` | +| `InsiderSellAlert` | `inventoryalert.fundamentals.insider-sell.v1` | +| `CompanyNewsAlert` | `inventoryalert.news.headline.v1` | + +--- + +## 4. Event-Driven Pipeline (Publish → Consume) + +### Publishing (inside `InventoryAlert.Api`) + +1. A service or controller calls `IEventService.PublishEventAsync(eventType, payload, ct)`. +2. `EventService` constructs an `EventEnvelope`, stamps it with a `CorrelationId`, serializes it to JSON, and persists an `EventLog` record to **DynamoDB**. +3. `SnsEventPublisher` pushes the envelope JSON to the **AWS SNS Topic** (`inventory-events`). + +### Consuming (inside `InventoryAlert.Worker`) + +1. Hangfire runs `PollSqsJob` on a schedule; it long-polls `inventory-event-queue` (SQS bound to SNS). +2. Each message body is deserialized into `EventEnvelope`. +3. An internal **Dictionary Dispatcher** reads `EventType` and invokes the corresponding `IEventHandler`: + +| EventType | Handler | Action | +| ------------------ | --------------------- | ---------------------------------------------------------------------- | +| `MarketPriceAlert` | `PriceAlertHandler` | Logs a structured `🚨 PRICE DROP ALERT` warning; Telegram plug-in point | +| `EarningsAlert` | `EarningsHandler` | Persists `EarningsRecord` to PostgreSQL via `WorkerDbContext` | +| `CompanyNewsAlert` | `NewsHandler` | Persists `NewsRecord` to PostgreSQL | +| `InsiderSellAlert` | `InsiderHandler` | Persists `InsiderTransaction` to PostgreSQL | +| *(unknown)* | `UnknownEventHandler` | Logs and discards gracefully — no crash | + +4. **Dead-Letter Queue**: After `ApproximateReceiveCount` exceeds 3, SQS automaticaly routes to `inventory-event-dlq`. + +--- + +## 5. Storage Layer + +| Store | Purpose | Access Pattern | +| ---------------------------------- | --------------------------------------------------------------- | -------------------------------------------------------------- | +| **PostgreSQL** (Npgsql EF Core 10) | `Product`, `EarningsRecord`, `NewsRecord`, `InsiderTransaction` | `IProductRepository` → `GenericRepository` → `AppDbContext` | +| **AWS DynamoDB** | `EventLog` audit trail (append-only, TTL-expiring) | `DynamoEventLogRepository`, accessed via `IEventService` | +| **IMemoryCache** (ASP.NET) | `Product` single-item cache (`Product_{id}`, 10 min TTL) | `ProductService.GetProductByIdAsync` — cache-aside pattern | +| **Hangfire** | Job scheduling metadata | Stored in PostgreSQL (`WorkerDbContext`) | + +### Transaction Pattern (`ExecuteTransactionAsync`) +All writes use the project-mandated capture pattern: +```csharp +// ✅ Result captured inside lambda — safe even if lambda throws +ProductResponse result = null!; +await _unitOfWork.ExecuteTransactionAsync(async () => +{ + var updated = await _productRepository.UpdateAsync(existing); + result = updated.ToResponse(); +}, cancellationToken); +return result; +``` + +--- + +## 6. Authentication + +`AuthController` issues **JWT Bearer tokens** (`HmacSha256`, 2-hour expiry). +Credentials are pulled from `appsettings.json → Auth:Username / Auth:Password`. +All `ProductsController` endpoints are decorated `[Authorize]`. +`EventsController` is unauthenticated (internal/service-to-service calls). + +--- + +## 7. Docker / Local AWS Infrastructure + +```yaml",161,907bc14da43f58caaffbfdb79b54834d,doc\archive\PROJECT_OVERVIEW.md,0,338,"inventoryalert, microsoft, event, must, postgresql, inventory, infrastructure, project",1779851803.8378093,10,asnotracking entity framework dockerfile httpget notification external api symbol rollback hosted service unitofwork efcore executetransactionasync iactionresult inventory commit fluentassertions httpput periodictimer times once httppost item sku infrastructure arrange act assert iproductrepository aapl market data atomicity compose postgres appdbcontext finnhubpricesyncworker quote iunitofwork savechangesasync moq dbset business logic domain driven design postgresql msft data access igenericrepository savechanges stock price stock ticker productservice loss stock xunit returns async container mock setup domain entity unit test dbcontext application service backgroundservice googl verify application layer threshold iproductservice productscontroller price drop,# 🏗️ Inventory Alert System — Technical Architecture | 🏗️ Inventory Alert System — Technical Architecture > This document covers archit +doc,"# docker-compose.yml services +postgres ← PostgreSQL 16, port 5432 +moto ← Moto (AWS mock), port 5000 +moto-init ← Runs init-sqs.sh + init-dynamodb.sh on startup +api ← InventoryAlert.Api (depends on postgres + moto) +worker ← InventoryAlert.Worker (depends on api + moto) +``` + +Moto init scripts (`SolutionFolder/moto-init/`): +- `init-sqs.sh` — creates `inventory-event-queue` + `inventory-event-dlq` +- `init-dynamodb.sh` — creates `EventLogs` table; reads `$AWS_ENDPOINT_URL` so it works from inside the Docker network + +All Docker files are linked as **Solution Items** in `InventoryManagementSystem.sln` for direct editing in Visual Studio. + +--- + +## 8. Testing Strategy + +| Suite | Count | Tools | +| ---------------------------------- | ------------------------ | ----------------------------------------- | +| `InventoryAlert.UnitTests` | 66 tests | xUnit, Moq, FluentAssertions, EF InMemory | +| `InventoryAlert.IntegrationTests` | 5 tests | Testcontainers.PostgreSql | +| `InventoryAlert.ArchitectureTests` | 9 tests | NetArchTest.Rules | +| **Total** | **80 tests, 0 failures** | | + +Key unit test rules: +- `ExecuteTransactionAsync` mocks **must** invoke the delegate: `.Returns, CancellationToken>((action, _) => action())` +- `IDisposable.Dispose()` on test fixtures **must** call `GC.SuppressFinalize(this)` (CA1816) +- No `Thread.Sleep`, no `async` method without `await` + +--- + +## 9. Observability + +- **Serilog** structured logging → `logs/inventoryalert.log` (rolling file sink) +- **`CorrelationIdMiddleware`** — stamps every HTTP request with a `X-Correlation-Id` header; propagated through SNS `CorrelationId` field into DynamoDB `EventLog` +- **`ExceptionHandlingMiddleware`** — catches all unhandled exceptions and returns RFC-7807 `ProblemDetails` JSON (no internal stack traces exposed to clients)",198,907bc14da43f58caaffbfdb79b54834d,doc\archive\PROJECT_OVERVIEW.md,0,339,"moto, init, inventoryalert, tests, docker, dynamodb, postgres, postgresql",1779851803.8378093,162,asnotracking entity framework dockerfile httpget notification external api symbol rollback hosted service unitofwork efcore executetransactionasync iactionresult inventory commit fluentassertions httpput periodictimer times once httppost item sku infrastructure arrange act assert iproductrepository aapl market data atomicity compose postgres appdbcontext finnhubpricesyncworker quote iunitofwork savechangesasync moq dbset business logic domain driven design postgresql msft data access igenericrepository savechanges stock price stock ticker productservice loss stock xunit returns async container mock setup domain entity unit test dbcontext application service backgroundservice googl verify application layer threshold iproductservice productscontroller price drop,"# docker-compose.yml services | docker-compose.yml services postgres ← PostgreSQL 16, port 5432 moto " +doc,"# InventoryAlert.Api — Documentation Index +--- +description: Master index of all documentation files for the InventoryAlert.Api project +type: reference +status: active +version: 1.0 +tags: [doc, index, readme, inventoryalert] +last_updated: 2026-04-04 +--- + +## Structure + +``` +doc/ +├── README.md ← this file +│ +├── ROADMAP.md ← active feature roadmap and priorities +└── archive/ ← completed or superseded docs + ├── MODERNIZATION_PLAN.md ← UI + logging + middleware (Done ✅ 2026-04-05) + ├── ENHANCEMENT_PLAN.md ← DDD + code quality improvements (Done ✅ 2026-04-05) + ├── EVENT_DRIVEN_PLAN.md ← event-driven architecture (Done ✅) + ├── EVENT_SETUP_COMMANDS.md ← event setup commands (Done ✅) + ├── SETUP_COMMANDS.md ← initial project setup (Done ✅) + ├── unit_test_plan.md ← unit test coverage plan + ├── DDD_REFACTOR_PLAN.md ← DDD refactor history + └── challenge.md ← completed challenges +``` + +--- + +## Doc Status Legend + +| Status | Meaning | +|--------|---------| +| `active` | Current, reflects implemented state | +| `draft` | Work-in-progress, not yet implemented | +| `deprecated` | Superseded by newer doc | + +--- + +## Key Docs by Topic + +| Topic | Document | +|-------|---------| +| Testing | `unit_test_plan.md` | +| Architecture | `DDD_STRUCTURE.md`, `DDD_REFACTOR_PLAN.md` | +| Roadmap | `ROADMAP.md` | +| API usage | `WALKTHROUGH.md` | +| External API | `finnhub/FINNHUB_FREE_ENDPOINTS.md` | +| Docker setup | `docker/DOCKER_PLAN.md` | +| Dev commands | `commands/dotnet-commands.md` | + +--- + +## How to Update Docs + +Always use `/doc` workflow after implementing any feature. + +Every `.md` file in this folder should have this header: + +```yaml +--- +description: +type: spec | plan | reference | walkthrough +status: draft | active | deprecated +version: 1.0 +tags: [relevant, keywords] +last_updated: YYYY-MM-DD +--- +``` + +After updating any doc, re-index BM25: +```bash +python .agents/scripts/core/bm25_indexer.py +```",75,ecdd02e5e1124862be9dafdf8fa25d9c,doc\archive\README.md,0,340,"index, inventoryalert, status, commands, documentation, active, implemented, docs",1775670503.9200897,1,postgresql stock price asnotracking xunit external api postgres infrastructure container domain driven design dbcontext fluentassertions unit test threshold compose quote loss efcore notification application layer arrange act assert entity framework market data price drop appdbcontext dockerfile domain entity,# InventoryAlert.Api — Documentation Index | InventoryAlert.Api — Documentation Index --- description: Master index of all do +doc,"--- +description: InventoryAlert Redis usage inventory plus recommended standards (keys, TTLs, error handling, and patterns). +type: reference +status: draft +version: 1.0 +tags: [redis, caching, idempotency, cooldown, signalr, inventoryalert, standards] +last_updated: 2026-04-28 +---",9,76947b566e24f991b0745bb77037534f,doc\archive\REDIS_STANDARD_AND_USAGE.md,0,341,"inventoryalert, redis, standards, description, usage, inventory, plus, recommended",1779851803.8026938,1,hosted service sku application service asnotracking periodictimer entity framework item productservice efcore backgroundservice inventory notification dbcontext finnhubpricesyncworker business logic stock price drop appdbcontext loss threshold iproductservice,REDIS_STANDARD_AND_USAGE.md | --- description: InventoryAlert Redis usage inventory plus recommended standards +doc,"# Redis Standard & Usage (InventoryAlert) + +This doc scans current Redis usage in the solution and proposes a standard approach for: + +- what Redis is used for, +- key naming conventions, +- TTL policy, +- serialization, +- error-handling and operability. + +Scope: `InventoryManagementSystem/*` only. + +--- + +## 1) Where Redis is used today (observed) + +### 1.1 API caching (`InventoryAlert.Api`) + +File: `InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs` + +Current keys: + +- `quote:{symbol}` (TTL ~30s) +- `metrics:{symbol}` (TTL ~1h) +- `peers:{symbol}` (TTL ~1d) +- `search:{query}` (TTL ~4h) + +Notes: + +- Key prefixes here are “feature-based” but not namespaced by service (`api:`) or version (`v1:`). +- `InventoryManagementSystem/InventoryAlert.Domain/Constants/AlertConstants.cs` also defines `product:quote:{symbol}` which is currently **not used** by `StockDataService` (naming drift risk). + +### 1.2 Alert cooldown/dedup (`InventoryAlert.Infrastructure`) + +File: `InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/AlertRuleEvaluator.cs` + +Key pattern: + +- `alert:cooldown:{userId}:{ruleId}` (TTL ~24h) + +Pattern: + +- `KeyExists` check → if breached → `TryAcquireLockAsync(..., When.NotExists)` to set cooldown. + +### 1.3 Worker message idempotency (`InventoryAlert.Worker`) + +File: `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` + +Key pattern: + +- `msg:processed:{messageId}` (TTL ~24h) + +Pattern: + +- Check `KeyExists` → process envelope → on success set `StringSetAsync` with TTL. + +### 1.4 SignalR backplane (API + Worker) + +Files: + +- `InventoryManagementSystem/InventoryAlert.Api/Program.cs` +- `InventoryManagementSystem/InventoryAlert.Worker/Program.cs` + +Observed: + +- `options.Configuration.ChannelPrefix = ""InventoryAlert_SignalR""` + +This is correct (prevents cross-app collisions when sharing a Redis instance). + +### 1.5 Redis abstraction helper + +File: `InventoryManagementSystem/InventoryAlert.Infrastructure/Caching/RedisHelper.cs` + +Methods: + +- `TryAcquireLockAsync(key, value, expiry)` uses `StringSetAsync(..., When.NotExists)` +- `SetExpiryAsync(key, expiry)` uses `KeyExpireAsync` +- `KeyExistsAsync(key)` + +Important behavior: + +- On Redis exception inside `TryAcquireLockAsync`, it returns `true` (fail-open) to avoid accidentally skipping processing. + +--- + +## 2) Standard Redis responsibilities (recommended) + +### 2.1 Allowed uses + +Use Redis for: + +- short-lived caches (quote/metrics/search) +- throttling/cooldown and alert storm prevention +- message idempotency markers (`processed`) +- distributed locks (short TTL) for “only one worker does X” +- SignalR backplane + +Avoid Redis for: + +- permanent state (use Postgres/Dynamo) +- long-term audit logs (use Seq + DB/Dynamo) +- storing secrets/tokens/PII + +### 2.2 Ownership rule + +Prefer one of these patterns: + +1) API cache keys are owned by API services only. +2) Worker idempotency keys are owned by Worker only. +3) Shared key contracts must live in `InventoryAlert.Domain` as constants and be used everywhere. + +Do not mix “ad-hoc strings” and “domain constants” for the same concept (prevents drift like `quote:{symbol}` vs `product:quote:{symbol}`). + +--- + +## 3) Key naming standard (recommended) + +### 3.1 Base format + +Use a consistent prefix: + +`{product}:{service}:{purpose}:{version}:{...ids}` + +Examples: + +- `inventoryalert:api:quote:v1:{SYMBOL}` +- `inventoryalert:api:search:v1:{QUERY_HASH}` +- `inventoryalert:worker:msg-processed:v1:{MESSAGE_ID}` +- `inventoryalert:alerts:cooldown:v1:{USER_ID}:{RULE_ID}` + +Rules: + +- Always use lowercase for static segments. +- Use uppercase for symbols (`AAPL`) and normalize before building keys. +- Prefer hashed keys for high-cardinality unbounded strings: + - `search:{sha256(query)}` rather than raw query text. + +### 3.2 TTL encoded in purpose (optional) + +If TTL expectations are strict, encode them: + +- `quote30s`, `metrics1h`, `cooldown24h` + +Example: + +- `inventoryalert:api:quote30s:v1:AAPL` + +--- + +## 4) TTL policy (recommended) + +### 4.1 Caches + +- Quote: 15–60s +- Metrics: 30–120m +- Search: 1–12h (prefer hash key) +- Peers: 1–7d + +### 4.2 Cooldowns / idempotency + +- Alert cooldown: 1–24h (based on desired “spam control”) +- Message processed marker: 24–72h (based on max replay window and DLQ redrive behavior) + +### 4.3 Expiration is mandatory + +No key should be written without expiry unless it is: + +- a SignalR backplane internal artifact, or +- a deliberate long-lived lock with separate maintenance (rare; usually avoid). + +--- + +## 5) Serialization & value guidelines (recommended) + +- Use `JsonOptions.Default` consistently across API/Worker for JSON payloads. +- Cache values should be: + - small and bounded (avoid logging them; cache bodies can be big) + - versioned DTOs (breaking changes handled by key version bump) + +--- + +## 6) Error handling (recommended) + +### 6.1 Avoid “silent” correctness changes + +Today `RedisHelper.TryAcquireLockAsync` returns `true` on Redis failures (fail-open). + +This is acceptable for: + +- cooldown locks (better to allow alert spam than stop the system), +- best-effort throttles. + +But it is risky for: + +- strong idempotency (may cause duplicate processing), +- financial side effects if handlers aren’t idempotent. + +Recommendation: + +- Split helpers by intent: + - `TryAcquireBestEffortLockAsync` (fail-open) + - `TryAcquireStrictLockAsync` (fail-closed + alert/metrics) + +### 6.2 Add minimal operability hooks + +Standard log fields when Redis fails: + +- `CorrelationId` (if present) +- `RedisKeyPrefix` (not full key if it contains user ids) +- `Operation` (`StringSetNX`, `KeyExpire`, `StringGet`) + +--- + +## 7) Concrete improvement checklist (next refactor) + +- Consolidate key naming: + - choose either `quote:{symbol}` or `product:quote:{symbol}` and remove the other; prefer domain constant if multiple components rely on it. +- Replace raw `search:{query}` with a hashed key to prevent massive key length / leakage. +- Add versioned prefixes for all keys to avoid stale cache after DTO changes. +- Decide idempotency window for `msg:processed:{messageId}` relative to DLQ/redrive rules.",230,76947b566e24f991b0745bb77037534f,doc\archive\REDIS_STANDARD_AND_USAGE.md,0,342,"inventoryalert, redis, worker, quote, symbol, inventorymanagementsystem, cooldown, keys",1779851803.8026938,10,hosted service sku application service asnotracking periodictimer entity framework item productservice efcore backgroundservice inventory notification dbcontext finnhubpricesyncworker business logic stock price drop appdbcontext loss threshold iproductservice,# Redis Standard & Usage (InventoryAlert) | Redis Standard & Usage (InventoryAlert) This doc scans current Redis usage in th +doc,"# 🚀 Operational Flow: Unified Integration Test Refactor + +This document defines the step-by-step operational flow for executing the refactoring within the **`InventoryAlert.IntegrationTests`** project. + +--- + +## 🏁 Phase 0: Pre-Flight Checks +1. **Infrastructure Up**: `docker compose up -d` +2. **Baseline**: Ensure current `InventoryAlert.IntegrationTests` pass. +3. **Branch Check**: Ensure you are on `refactor/integration-tests-three-tier`. + +--- + +## 🏗️ Phase 1: Infrastructure Scaffolding +1. **Project Update**: Add NuGet packages to `InventoryAlert.IntegrationTests.csproj`. +2. **Internal Directory Setup**: + - Create `Infrastructure/`, `Abstractions/`, and `Tests/` (sub-folders: `Handlers`, `Services`, `Api`, `Jobs`). +3. **DI & Interceptors**: + - Implement `Infrastructure/SetupDI.cs`. + - Implement `Infrastructure/TestLoggerProvider.cs`. + - *Verification (WireMock)*: Add a static mapping in `Wiremock/mappings/ping.json`. Call it via `HttpClient` from a test. If it returns 200 OK, the WireMock container and volume mapping are functional. + - *Verification (DI)*: A ""Smoke Test"" resolves a service and captures a log entry. + +--- + +## 💉 Phase 2: Tier 1 - White-box Implementation +1. **Handler Selection**: Pick `MarketPriceAlertHandler`. +2. **Mocking Phase**: + - Define WireMock mapping for Finnhub quote. + - Resolve handler from DI. + - *Verification*: Call handler directly and assert that the `TestLoggerProvider` captured the ""Processing alert"" message. +3. **DB Isolation**: + - Run test multiple times. + - *Verification*: Use `Respawn` in the fixture to ensure DB state is cleared. + +--- + +## 📡 Phase 3: Tier 2 - API Log Correlation +1. **Log Reader**: + - Implement `Infrastructure/DockerLogReader.cs` using `Docker.DotNet`. +2. **Correlation Test**: + - Use `ActionTestConfig` to call a Controller. + - *Verification*: Assert that logs retrieved from the `inventory-api` container contain the `X-Correlation-Id` from the response. + +--- + +## 🔁 Phase 4: Whole-Flow Orchestration (The Quality Peak) +Focus: Verifying the complete system lifecycle (API -> Infra -> Worker -> Result). + +1. **Orchestration Scenario**: + - Call `POST /api/v1/events` (Price Alert) via the API client. +2. **Wait for Side-Effect**: + - Use `WaitHelper.WaitForConditionAsync` to poll `GET /api/v1/notifications`. +3. **Verification**: + - Assert that the notification created by the **Worker** appears in the **API** response for the user. + - *Quality Proof*: This proves that the API, SQS, Worker Handlers, and Database are all correctly integrated. + +--- + +## 🏁 Phase 5: Final Validation +1. **Category Cleanup**: Ensure all tests have a `[Trait(""Category"", ""TierN"")]` attribute. +2. **CI Execution**: + ```powershell + dotnet test --filter ""Category=Tier1"" + dotnet test --filter ""Category=Tier2"" + ``` +3. **Performance**: Verify that Tier 1 tests run in milliseconds compared to the seconds/minutes required for Tier 2/3.",67,cf73e5a47b37606a55c3727031e87354,doc\archive\REFACTOR_OPERATIONAL_FLOW.md,0,343,"phase, infrastructure, verification, test, tier, ensure, tests, wiremock",1779814416.3898118,1,efcore mock setup entity framework moq httpget notification times once price drop compose returns async hosted service productscontroller market data verify threshold unit test backgroundservice finnhubpricesyncworker dockerfile asnotracking httpput external api iactionresult productservice fluentassertions httppost periodictimer dbcontext appdbcontext container postgresql postgres stock price business logic loss xunit iproductservice arrange act assert quote application service,# 🚀 Operational Flow: Unified Integration Test Refactor | 🚀 Operational Flow: Unified Integration Test Refactor This document defines the +doc,"--- +description: Project roadmap (planned work, milestones, and priorities). +type: plan +status: active +version: 1.0 +tags: [roadmap, planning, inventoryalert] +last_updated: 2026-04-23 +---",9,f90e807d257d8050190c23e82ac49f40,doc\archive\ROADMAP.md,0,344,"roadmap, description, project, planned, work, milestones, priorities, type",1779814416.3908205,1,external api market data unitofwork price drop commit mock setup appdbcontext productscontroller iunitofwork stock price data access arrange act assert application service httppost domain entity stock verify igenericrepository container dockerfile application layer asnotracking periodictimer postgres item postgresql hosted service xunit compose httpput productservice moq returns async domain driven design iproductrepository executetransactionasync business logic times once backgroundservice inventory finnhubpricesyncworker savechanges savechangesasync iproductservice unit test atomicity rollback fluentassertions entity framework httpget notification quote iactionresult sku threshold loss dbset efcore dbcontext infrastructure,"ROADMAP.md | --- description: Project roadmap (planned work, milestones, and priorities)" +doc,"# 🗺️ Development Roadmap + +> Consolidated from all `TODO` comments across the codebase. +> Each task preserves the original TODO content and is grouped by theme, ordered by priority. + +--- + +## 🔴 P0 — Critical / Blocking (Do First) + +### 1. Docker & Containerization ✅ + +> **Source:** `ProductController.cs:L96` — _important high priority_ + +~~Setup docker and containerization for the application.~~ **✅ Complete.** See `SETUP_COMMANDS.md` and `EVENT_DRIVEN_PLAN.md` for full implementation details. + +- [x] Create `Dockerfile` (multi-stage build) +- [x] Create `docker-compose.yml` (api + postgres + redis + moto + moto-init + worker) +- [x] Externalize config via `appsettings.Docker.json` (not inline env vars) +- [x] Moto init script (`SolutionFolder/moto-init/init-sqs.sh`) auto-creates SNS/SQS on boot + +### 2. Global Exception Handling & Error Responses + +> **Source:** `ProductController.cs:L79,L89,L91` + +Implement a global exception handling mechanism (middleware or filters) to catch unhandled exceptions and return consistent, user-friendly JSON error responses. Use custom exceptions (`NotFoundException`, `ValidationException`) to represent different error types. Return appropriate HTTP status codes (400, 404, 500) with error codes. Ensure sensitive information is not exposed. Keep it simple and easy to understand for junior developers. + +- [x] Create custom exception classes (`NotFoundException`, `ValidationException`) +- [x] Implement `ExceptionHandlingMiddleware` +- [x] Standardize error response format (`{ code, message, details }`) + +### 3. Logging Strategy + +> **Source:** `ProductController.cs:L81,L91` + +Implement comprehensive logging using Serilog or NLog. Log important events (product creation, updates, deletions) and errors with appropriate log levels (Information, Warning, Error). Include contextual information (product ID, user ID). Configure multiple sinks (console, file, database). + +> **Note:** `FinnhubSyncWorker` logging should be addressed here but the worker itself is planned for **retirement** once `SyncPricesJob` in `InventoryAlert.Worker` is live (see `EVENT_DRIVEN_PLAN.md` — Phase C). + +- [x] Install and configure Serilog (Api + Worker) +- [x] Add structured logging to `ProductService` via `ILogger` +- [x] `CorrelationIdMiddleware` — stamps all requests and logs with `X-Correlation-Id` +- [x] `FinnhubSyncWorker` retired — `SyncPricesJob` in Worker owns price sync + +--- + +## 🟠 P1 — Architecture & Code Quality + +### 4. Thin Controller / Service Layer Refactoring + +> **Source:** `ProductController.cs:L59` + +All the logic should be in the service layer. Move remaining logic to service layer and make the controller thin and simple, just for handling HTTP request and response. + +**Current violation — `UpdateProductStockCount` (L49-L57):** +The PATCH endpoint fetches the product, mutates it, then calls update — this logic belongs in the service. + +- [x] Create `UpdateStockCountAsync(int id, int stockCount)` in `IProductService` +- [x] Move PATCH logic from controller to service +- [x] Controller should only call service and return result + +### 5. RESTful API Design Review + +> **Source:** `ProductController.cs:L30,L49,L72,L85,L86,L87,L88` + +Review the design of the API endpoints to follow RESTful principles more closely: + +| Current Issue | Fix | +| --------------------------------------------------------- | ------------------------------------------- | +| `HttpGet(""{id}"")` uses `[FromQuery]` but route has `{id}` | Use `[FromRoute]` or remove route param | +| `HttpPatch` has no route param for ID | Change to `HttpPatch(""{id}"")` | +| `HttpDelete` has no route param for ID | Change to `HttpDelete(""{id}"")` | +| `CreateProduct` returns `200 OK` | Return `201 Created` | +| `GetProductsByIds` name is misleading (single ID) | Rename to `GetProductById` | +| Method/endpoint naming inconsistency | Use verbs for actions + nouns for resources | + +- [x] Fix route parameter binding — all endpoints use `[FromRoute]` +- [x] Return correct HTTP status codes (`201 Created`, `204 NoContent`, `404 NotFound`) +- [x] Rename methods — `GetProductById`, `UpdateStockCount`, `GetPriceLossAlerts` +- [x] Kept entity name as `Product` — domain language matches business context (no rename needed) + +### 6. Unit of Work Pattern Review + +> **Source:** `UnitOfWork.cs:L5`, `ProductServices.cs:L62` + +Review the UnitOfWork pattern. Current concern: ""I just want to reach rollback when scaling up with more tables. If fail when inserting one table, rollback the whole thing. Should we keep UnitOfWork or use a simpler implementation?"" + +**Verdict:** Keep UnitOfWork. It provides transaction safety for multi-table operations. For single-table operations, it adds minimal overhead since EF Core's `SaveChanges` is already atomic. + +- [x] Audit all service methods for consistent UnitOfWork usage +- [x] Ensure `ExecuteTransactionAsync` wraps only multi-step operations +- [x] Document when to use `UnitOfWork` vs plain `SaveChangesAsync` + +### 7. Program.cs Organization + +> **Source:** `Program.cs:L15,L34` + +Review and enhance the `Program.cs` design. Use extension methods to organize the code and make it more readable and maintainable. Move static file names to constants. + +- [x] Create `ServiceCollectionExtensions.AddInfrastructure()` +- [x] Create `ServiceCollectionExtensions.AddApplication()` +- [x] Extract magic strings to a `Constants` class + +### 8. Stock & Market Data Service Implementation ✅ + +> **Source:** USER Request — **Completed 2026-04-07** + +Implement a comprehensive service for orchestrated stock, market, and crypto data fetching with multi-layer caching (Redis + Postgres). + +- [x] Create `IStockDataService` and `StockDataService` +- [x] Implement Redis-first caching for Quotes, Peers, Market Status +- [x] Implement DB-first caching for Company Profiles +- [x] Full coverage for News, Recommendations, Earnings, and Calendars +- [x] Crypto exchange and symbol support + +--- + +## 🟡 P2 — Data Integrity & Validation + +### 8. Input Validation + +> **Source:** `ProductController.cs:L71,L87` + +Add validation for input data using FluentValidation or Data Annotations. Ensure data being processed is valid and provide meaningful error messages when validation fails. Review use of data annotations or validation attributes on DTOs. + +- [x] Install `FluentValidation.AspNetCore` +- [x] Create `ProductRequestDtoValidator` +- [x] Register validators in DI +- [x] Return `400 Bad Request` with validation details + +### 9. DTO Design Review + +> **Source:** `ProductController.cs:L74,L76`, `ProductServices.cs:L40` + +Review `ProductDto` and `ProductRequestDto`. Separate the properties required for creating vs updating. Rename `GetHighValueProducts` to something more descriptive like `GetSignificantLossProducts`. The update method should use the ID from the route, not the body. + +**Current state:** `ProductRequestDto` (create/update) and `ProductDto` (response) are already separated. ✅ + +- [x] `UpdateProductAsync` always uses route ID (body ID ignored) +- [x] Renamed `GetHighValueProducts` → `GetPriceLossAlertsAsync` +- [x] Renamed endpoint `low-stock` → `price-alerts` + +### 10. Null Handling in Finnhub Responses + +> **Source:** `ProductServices.cs:L107` + +Should we check if the price is null before assigning it to `CurrentPrice`? Or should we set the current price to 0 if the price is null? + +**Recommendation:** Skip the product entirely if the price is null. Setting it to 0 would trigger false loss alerts. + +- [x] `quote?.CurrentPrice is null or 0` → `continue` when null (ProductService + SyncPricesJob) +- [x] Warning logged when a symbol returns null or zero price + +### 11. BulkInsert Response Design + +> **Source:** `ProductServices.cs:L71` + +Should we return the list of created products or just the count? + +**Recommendation:** Return `204 No Content` or the count. Returning thousands of full objects wastes bandwidth. + +- [x] `BulkInsertProducts` returns `204 No Content` +- [x] No body returned — bandwidth optimized + +--- + +## 🏗️ P2 — Modernization & UI (New) + +### 12. Next.js 15 Web Dashboard ✅ + + > **Source:** USER Request — **Completed 2026-04-07** + + - [x] Create `InventoryAlert.UI` project (Next.js 15 + Tailwind CSS) + - [x] Implement modern dark-themed UI with glassmorphism + - [x] Routes: Market Explorer, Price Alerts, Portfolio, Symbol Details + - [x] Integrated with `StocksController` via `StockDataService` + - [x] **UI Test stabilization** — Added Vitest unit and component tests to satisfy CI/CD + - [ ] Replace static chart placeholders with functional **Recharts** implementations + - [ ] Implement Next.js Route Handlers for secure API proxying + + +### 13. Shared Project — `InventoryAlert.Domain` ✅ (Already Exists) + +> **Note:** `InventoryAlert.Domain` **already exists** as the shared project. +> Both `InventoryAlert.Api` and `InventoryAlert.Worker` reference it via `` — **no new project needed**. +> The tasks below are **enhancements** to the existing shared project. +> +> **Invariant:** `InventoryAlert.Domain` is the single source of truth for every type that crosses a service boundary. No entity or payload may be defined in both `Api` and `Worker`. + +#### What the Shared Project Must Own + +| Category | Current State | Target | +| :-------------------------------------------- | :--------------------------------------------------- | :--------------------------------- | +| Domain entities (`Product`, `EventLog`, …) | ✅ In `Contracts/Entities/` | Keep — verified | +| Event payloads (`MarketPriceAlertPayload`, …) | ✅ In `Contracts/Events/Payloads/` | Keep — verified | +| `EventEnvelope` | ✅ Updated — `EventType`, `Payload`, `CorrelationId` | Keep | +| `EventTypes` constants | ✅ Reverse-DNS naming applied | Keep | +| App-wide constants (cache keys, SQS headers) | ✅ In `Contracts/Constants/` | Keep | +| Shared configuration models | ❌ Duplicated per project | Move to `Contracts/Configuration/` | + +#### Build Tasks + +- [x] Entities centralized: `Product`, `EventLog`, `EarningsRecord`, `InsiderTransaction`, `NewsRecord` +- [x] `global using` aliases in `Api/Domain/Entities/SharedEntityAliases.cs` for backward compat +- [x] `global using` aliases in `Worker/SharedEntityAliases.cs` for backward compat +- [x] `Constants/AlertConstants.cs` — `CacheKeys`, `EventTypes`, `SqsHeaders` centralized +- [x] `Events/EventEnvelope.cs` — standardized envelope with `CorrelationId` + `Source` +- [x] `Events/EventTypes.cs` — reverse-DNS format + `IsKnown()` + `IReadOnlySet` +- [x] **Move shared config models** — create `Contracts/Configuration/SharedAwsSettings.cs` and `SharedFinnhubSettings.cs` so both `Api` and `Worker` read from the same schema +- [x] **Add `InventoryAlert.ArchitectureTests`** — use `NetArchTest.Rules` to **enforce** at CI time that: + - `InventoryAlert.Api` has no internal entity definitions + - `InventoryAlert.Worker` has no internal entity definitions + - All event payloads live only in `Contracts` +- [x] **NuGet packaging (future)** — if a 3rd service (e.g. `InventoryAlert.Sample`) is added, package `Contracts` as a private NuGet feed artifact so versioning is explicit + +#### Reference Architecture + +```text +InventoryAlert.Domain/ ← shared library, referenced by all +├── Entities/ ← EF-mapped domain entities +├── Events/ +│ ├── EventEnvelope.cs ← envelope contract +│ ├── EventTypes.cs ← canonical type registry +│ └── Payloads/ ← one file per event type +├── Constants/ +│ └── AlertConstants.cs ← CacheKeys, SqsHeaders, defaults +└── Configuration/ ← PLANNED: shared config POCOs + ├── SharedAwsSettings.cs + └── SharedFinnhubSettings.cs + +InventoryAlert.Api/ + └── Domain/Entities/SharedEntityAliases.cs ← global using only + +InventoryAlert.Worker/ + └── SharedEntityAliases.cs ← global using only +``` + +--- + +## 📂 P3 — Logging & Observability (New) + +### 14. Centralized Logging (Serilog) ✅ + +> **Source:** USER Request — **Completed 2026-04-05** + +- [x] Serilog bootstrapped in `InventoryAlert.Worker/Program.cs` +- [x] JSON file sink + Console sink (rolling daily, 7-day retention) +- [x] `CorrelationIdMiddleware` tracks requests across Api and Worker +- [x] `MachineName` and `EnvironmentName` enrichers added + +### 15. Global Exception Strategy ✅ + +> **Source:** USER Request — **Completed 2026-04-05** + +- [x] `ExceptionHandlingMiddleware` refactored for full RFC-7807 compliance (`type`, `instance`, semantic slugs) +- [x] `HangfireJobLoggingFilter` — global job error auditing via `ILogger` +- [x] All domain exceptions (`NotFoundException`, `ValidationException`, `ArgumentException`) mapped to HTTP codes + +--- + +## 🟢 P4 — Performance & Scalability + +### 12. Caching ✅ + +> **Source:** `ProductController.cs:L68` + +Implement caching for frequently accessed data (product details) using in-memory caching or Redis, depending on scale and expected load. + +- [x] Add `IMemoryCache` for `GetProductById` +- [x] Add cache invalidation on Update/Delete +- [x] Evaluate Redis if scaling beyond a single instance + +### 13. Pagination ✅ + +> **Source:** `ProductController.cs:L73` + +Implement pagination for list endpoints (`GetProducts`). Accept query parameters for page number and page size. Return subset of data with metadata (total items, total pages). + +- [x] Create `PaginationParams` (PageNumber, PageSize) +- [x] Create `PagedResult` wrapper +- [x] Update `GetAllAsync` in repository to support `Skip/Take` + +### 14. Finnhub Sync Design Review +**Verdict:** Keep UnitOfWork. It provides transaction safety for multi-table operations. For single-table operations, it adds minimal overhead since EF Core's `SaveChanges` is already atomic. + +- [x] Audit all service methods for consistent UnitOfWork usage +- [x] Ensure `ExecuteTransactionAsync` wraps only multi-step operations +- [x] Document when to use `UnitOfWork` vs plain `SaveChangesAsync` + +### 7. Program.cs Organization + +> **Source:** `Program.cs:L15,L34` + +Review and enhance the `Program.cs` design. Use extension methods to organize the code and make it more readable and maintainable. Move static file names to constants. + +- [x] Create `ServiceCollectionExtensions.AddInfrastructure()` +- [x] Create `ServiceCollectionExtensions.AddApplication()` +- [x] Extract magic strings to a `Constants` class + +### 8. Stock & Market Data Service Implementation ✅ + +> **Source:** USER Request — **Completed 2026-04-07** + +Implement a comprehensive service for orchestrated stock, market, and crypto data fetching with multi-layer caching (Redis + Postgres). + +- [x] Create `IStockDataService` and `StockDataService` +- [x] Implement Redis-first caching for Quotes, Peers, Market Status +- [x] Implement DB-first caching for Company Profiles +- [x] Full coverage for News, Recommendations, Earnings, and Calendars +- [x] Crypto exchange and symbol support + +--- + +## 🟡 P2 — Data Integrity & Validation + +### 8. Input Validation + +> **Source:** `ProductController.cs:L71,L87` + +Add validation for input data using FluentValidation or Data Annotations. Ensure data being processed is valid and provide meaningful error messages when validation fails. Review use of data annotations or validation attributes on DTOs. + +- [x] Install `FluentValidation.AspNetCore` +- [x] Create `ProductRequestDtoValidator` +- [x] Register validators in DI +- [x] Return `400 Bad Request` with validation details + +### 9. DTO Design Review + +> **Source:** `ProductController.cs:L74,L76`, `ProductServices.cs:L40` + +Review `ProductDto` and `ProductRequestDto`. Separate the properties required for creating vs updating. Rename `GetHighValueProducts` to something more descriptive like `GetSignificantLossProducts`. The update method should use the ID from the route, not the body. + +**Current state:** `ProductRequestDto` (create/update) and `ProductDto` (response) are already separated. ✅ + +- [x] `UpdateProductAsync` always uses route ID (body ID ignored) +- [x] Renamed `GetHighValueProducts` → `GetPriceLossAlertsAsync` +- [x] Renamed endpoint `low-stock` → `price-alerts` + +### 10. Null Handling in Finnhub Responses + +> **Source:** `ProductServices.cs:L107` + +Should we check if the price is null before assigning it to `CurrentPrice`? Or should we set the current price to 0 if the price is null? + +**Recommendation:** Skip the product entirely if the price is null. Setting it to 0 would trigger false loss alerts. + +- [x] `quote?.CurrentPrice is null or 0` → `continue` when null (ProductService + SyncPricesJob) +- [x] Warning logged when a symbol returns null or zero price + +### 11. BulkInsert Response Design + +> **Source:** `ProductServices.cs:L71` + +Should we return the list of created products or just the count? + +**Recommendation:** Return `204 No Content` or the count. Returning thousands of full objects wastes bandwidth. + +- [x] `BulkInsertProducts` returns `204 No Content` +- [x] No body returned — bandwidth optimized + +--- + +## 🏗️ P2 — Modernization & UI (New) + +### 12. Next.js 15 Web Dashboard ✅ + + > **Source:** USER Request — **Completed 2026-04-07** + + - [x] Create `InventoryAlert.UI` project (Next.js 15 + Tailwind CSS) + - [x] Implement modern dark-themed UI with glassmorphism + - [x] Routes: Market Explorer, Price Alerts, Portfolio, Symbol Details + - [x] Integrated with `StocksController` via `StockDataService` + - [ ] Replace static chart placeholders with functional **Recharts** implementations + - [ ] Implement Next.js Route Handlers for secure API proxying + + +### 13. Shared Project — `InventoryAlert.Domain` ✅ (Already Exists) + +> **Note:** `InventoryAlert.Domain` **already exists** as the shared project. +> Both `InventoryAlert.Api` and `InventoryAlert.Worker` reference it via `` — **no new project needed**. +> The tasks below are **enhancements** to the existing shared project. +> +> **Invariant:** `InventoryAlert.Domain` is the single source of truth for every type that crosses a service boundary. No entity or payload may be defined in both `Api` and `Worker`. + +#### What the Shared Project Must Own + +| Category | Current State | Target | +| :-------------------------------------------- | :--------------------------------------------------- | :--------------------------------- | +| Domain entities (`Product`, `EventLog`, …) | ✅ In `Contracts/Entities/` | Keep — verified | +| Event payloads (`MarketPriceAlertPayload`, …) | ✅ In `Contracts/Events/Payloads/` | Keep — verified | +| `EventEnvelope` | ✅ Updated — `EventType`, `Payload`, `CorrelationId` | Keep | +| `EventTypes` constants | ✅ Reverse-DNS naming applied | Keep | +| App-wide constants (cache keys, SQS headers) | ✅ In `Contracts/Constants/` | Keep | +| Shared configuration models | ❌ Duplicated per project | Move to `Contracts/Configuration/` | + +#### Build Tasks + +- [x] Entities centralized: `Product`, `EventLog`, `EarningsRecord`, `InsiderTransaction`, `NewsRecord` +- [x] `global using` aliases in `Api/Domain/Entities/SharedEntityAliases.cs` for backward compat +- [x] `global using` aliases in `Worker/SharedEntityAliases.cs` for backward compat +- [x] `Constants/AlertConstants.cs` — `CacheKeys`, `EventTypes`, `SqsHeaders` centralized +- [x] `Events/EventEnvelope.cs` — standardized envelope with `CorrelationId` + `Source` +- [x] `Events/EventTypes.cs` — reverse-DNS format + `IsKnown()` + `IReadOnlySet` +- [x] **Move shared config models** — create `Contracts/Configuration/SharedAwsSettings.cs` and `SharedFinnhubSettings.cs` so both `Api` and `Worker` read from the same schema +- [x] **Add `InventoryAlert.ArchitectureTests`** — use `NetArchTest.Rules` to **enforce** at CI time that: + - `InventoryAlert.Api` has no internal entity definitions + - `InventoryAlert.Worker` has no internal entity definitions + - All event payloads live only in `Contracts` +- [x] **NuGet packaging (future)** — if a 3rd service (e.g. `InventoryAlert.Sample`) is added, package `Contracts` as a private NuGet feed artifact so versioning is explicit + +#### Reference Architecture + +```text +InventoryAlert.Domain/ ← shared library, referenced by all +├── Entities/ ← EF-mapped domain entities +├── Events/ +│ ├── EventEnvelope.cs ← envelope contract +│ ├── EventTypes.cs ← canonical type registry +│ └── Payloads/ ← one file per event type +├── Constants/ +│ └── AlertConstants.cs ← CacheKeys, SqsHeaders, defaults +└── Configuration/ ← PLANNED: shared config POCOs + ├── SharedAwsSettings.cs + └── SharedFinnhubSettings.cs + +InventoryAlert.Api/ + └── Domain/Entities/SharedEntityAliases.cs ← global using only + +InventoryAlert.Worker/ + └── SharedEntityAliases.cs ← global using only +``` + +--- + +## 📂 P3 — Logging & Observability (New) + +### 14. Centralized Logging (Serilog) ✅ + +> **Source:** USER Request — **Completed 2026-04-05** + +- [x] Serilog bootstrapped in `InventoryAlert.Worker/Program.cs` +- [x] JSON file sink + Console sink (rolling daily, 7-day retention) +- [x] `CorrelationIdMiddleware` tracks requests across Api and Worker +- [x] `MachineName` and `EnvironmentName` enrichers added + +### 15. Global Exception Strategy ✅ + +> **Source:** USER Request — **Completed 2026-04-05** + +- [x] `ExceptionHandlingMiddleware` refactored for full RFC-7807 compliance (`type`, `instance`, semantic slugs) +- [x] `HangfireJobLoggingFilter` — global job error auditing via `ILogger` +- [x] All domain exceptions (`NotFoundException`, `ValidationException`, `ArgumentException`) mapped to HTTP codes + +--- + +## 🟢 P4 — Performance & Scalability + +### 12. Caching ✅ + +> **Source:** `ProductController.cs:L68` + +Implement caching for frequently accessed data (product details) using in-memory caching or Redis, depending on scale and expected load. + +- [x] Add `IMemoryCache` for `GetProductById` +- [x] Add cache invalidation on Update/Delete +- [x] Evaluate Redis if scaling beyond a single instance + +### 13. Pagination ✅ + +> **Source:** `ProductController.cs:L73` + +Implement pagination for list endpoints (`GetProducts`). Accept query parameters for page number and page size. Return subset of data with metadata (total items, total pages). + +- [x] Create `PaginationParams` (PageNumber, PageSize) +- [x] Create `PagedResult` wrapper +- [x] Update `GetAllAsync` in repository to support `Skip/Take` + +### 14. Finnhub Sync Design Review ✅ + +> **Source:** `ProductServices.cs:L89` + +Should we get the quote for each product on every API call, or store the price in the database and update it regularly? + +**Current state:** ✅ Already implemented! `SyncCurrentPricesAsync` updates DB via BackgroundWorker. `GetHighValueProducts` now reads from DB (no live API calls). + +- [x] `GetHighValueProducts` reads only from DB for faster response +- [x] BackgroundWorker is the single source of truth for `CurrentPrice` + +--- + +## 🔵 P4 — Security + +### 15. Authentication & Authorization ✅ + +> **Source:** `ProductController.cs:L69` + +Add simple JWT-based authentication to secure the API endpoints and ensure only authorized users can access certain resources. + +- [x] Install `Microsoft.AspNetCore.Authentication.JwtBearer` +- [x] Configure JWT in `Program.cs` +- [x] Add `[Authorize]` to protected endpoints +- [x] Create login/token endpoint +- [x] **User Registration** — Implemented `POST /api/auth/register` with unique index, password hashing, and transaction safety. + +### 16. Web Security (OWASP) ✅ + +> **Source:** `ProductController.cs:L84` + +Protect against SQL injection, XSS, and CSRF. Use parameterized queries (EF Core handles this ✅), validate/sanitize input data, enforce HTTPS. + +- [x] Enable HTTPS redirection (`app.UseHttpsRedirection()`) +- [x] Add CORS policy +- [x] Review EF Core queries for raw SQL (ensure parameterized) +- [x] Add rate limiting for Finnhub-related endpoints + +--- + +## 🟣 P5 — Testing & Quality + +### 17. Codebase Audit & Standardization ✅ + +> **Source:** USER Request — _Quality baseline. See `AUDIT_PLAN.md` for full spec._ +> +> **Goal:** Ensure file names, methods, structure grids, folder patterns, and tech logic are strictly conformed across `Api`, `Worker` and `Contracts`. + +- [x] Execute **Structure Audit** (Verify DDD isolation, clean out legacy entity files from Api Project). +- [x] Execute **Naming Audit** (Interfaces, Service suffixes, Exception suffixes, Job/Handler match). +- [x] Execute **Logic Audit** (Enforce thin controllers, centralized mapping, UnitOfWork transaction capture pattern). +- [x] Execute **Tech Pattern Audit** (Async/await hygiene, `AsNoTracking`, strictly `ILogger` usage, `CancellationToken` cascading). + +### 18. Test Project Standardization (Unit & Integration) ✅ + +> **Source:** USER Request — _Testing baseline definition._ +> +> **Goal:** Strictly segregate test types and ensure all 3 main projects (`Api`, `Worker`, `Contracts`) are explicitly covered by testing. + +- [x] Rename `InventoryAlert.Tests` to `InventoryAlert.UnitTests`. +- [x] Group unit tests logically inside `InventoryAlert.UnitTests`: structure them exactly to mirror the 3 target projects (`Api`, `Worker`, `Contracts`). +- [x] Ensure unit tests only use mocks (`Moq`) and don't hit real databases or brokers. +- [x] Create a new project `InventoryAlert.IntegrationTests` for end-to-end and DB testing (e.g., hitting Testcontainers or an EF Core InMemory DB, and Moto for AWS). +- [x] **107 Unit Tests Passing** — Verified full coverage for `ProductService`, `WatchlistService` (with Redis integration), and `AuthController`. + +**Existing Unit Tests (`InventoryAlert.UnitTests`) progress:** + +- [x] Test `ProductServices.GetHighValueProducts` (loss math) +- [x] Test `ProductServices.SyncCurrentPricesAsync` (null handling) +- [x] Test `ProductController` status codes (200, 201, 404) +- [x] Mock `IFinnhubClient` and `IProductRepository` +- [x] Test `EventService` (transaction call, publisher payload) +- [x] Test `EventsController` (202/400 statuses, payload mapping) +- [x] Test `WatchlistService` (caching, deduplication) +- [x] Test `AuthController` (Registration conflicts, async handlers) + +### 19. E2E Test Stabilization ✅ + +> **Source:** USER Request — _Stabilization baseline._ + +- [x] Docker environment verified (Postgres + Redis + Moto + API) +- [x] `BaseE2ETest` improved with configurable `BaseUrl` and detailed error logging +- [x] 32 E2E tests verified passing against Docker-hosted API + +### 20. Async/Await Audit ✅ + +> **Source:** `ProductController.cs:L70,L78` + +Review all async/await usage. Ensure all operations are properly awaited. Review `CancellationToken` consistency across all layers. + +- [x] Add `CancellationToken` to `DeleteProductAsync` +- [x] Ensure `CancellationToken` flows: Controller → Service → Repository +- [x] Remove `CancellationToken.None` usages where a real token is available + +### 20. Dependency Injection Review ✅ + +> **Source:** `ProductController.cs:L92` + +Review DI usage. Ensure constructor injection is used consistently. Review service lifetimes (transient, scoped, singleton) for correctness. + +**Current state:** + +| Service | Lifetime | Correct? | +| :------------------- | :-------------------- | :--------------------------------- | +| `RestClient` | via HttpClientFactory | ✅ | +| `IFinnhubClient` | Scoped | ✅ | +| `IProductService` | Scoped | ✅ | +| `IProductRepository` | Scoped | ✅ | +| `IConnectionMultiplier` | Singleton | ✅ (Redis Multiplexer) | +| `FinnhubSyncWorker` | Removed | ✅ Hosted via Hangfire instead | + +- [x] Verify `FinnhubSyncWorker` uses `IServiceScopeFactory` (not direct injection) - **Worker replaced entirely by Hangfire Job!** +- [x] Document DI registration decisions + +--- + +## ⚫ P6 — DevOps & Automation + +### 21. Messaging & Advanced Background Jobs ✅ + +> **Source:** `ProductController.cs:L97` — _important high priority_ + +See `EVENT_DRIVEN_PLAN.md` for full architecture. Infrastructure scaffolding is complete: + +- [x] Evaluate Hangfire vs current `BackgroundService` → **Hangfire chosen** +- [x] Design message schema for price alerts → `EventEnvelope` + payload records in `Contracts` +- [x] `InventoryAlert.Worker` project created + NuGet packages installed +- [x] Docker moto-init: SNS topic + SQS queues auto-created on boot +- [x] Implement `IEventPublisher` + `SnsEventPublisher` in Api (Phase B ✅) +- [x] Implement `PollSqsJob`, `SyncPricesJob`, and event handlers in Worker (Phase C–D ✅) + +### 22. CI/CD Pipeline ✅ + +> **Source:** `ProductController.cs:L93` + +Setup CI/CD using GitHub Actions or Azure DevOps. Automate build, test, and deployment. Include unit tests and integration tests in the pipeline. + +- [x] Create `.github/workflows/ci.yml` +- [x] Steps: Restore → Build → Test → (optional) Docker push +- [x] Add badge to README + +### 23. API Documentation (Swagger) ✅ + +> **Source:** `ProductController.cs:L83` + +Enhance Swagger/OpenAPI documentation with XML comments, request/response examples, status codes, and endpoint descriptions. + +- [x] Enable XML documentation in `.csproj` +- [x] Add `/// ` to all controller methods +- [x] Add `[ProducesResponseType]` attributes +- [x] Add example requests/responses + +### 24. AutoMapper Integration ✅ + +> **Source:** `ProductController.cs:L75` + +Implement AutoMapper to centralize mapping between domain models and DTOs. Reduce boilerplate in services. + +- [x] Install `AutoMapper.Extensions.Microsoft.DependencyInjection` +- [x] Create `MappingProfile` with `Product ↔ ProductDto` maps +- [x] Replace manual `MapProductToProductDto` methods + +--- + +## 🏗️ P2 — Architecture Evolution (Phase 2) ✅ + +> See `doc/PHASE2_PLAN.md` for full spec and diagrams. + +### 16. Shared Contracts Enforcement + +- [x] All entities centralized in `InventoryAlert.Domain` ✅ +- [x] `global using` aliases in Api and Worker for backward compat ✅ +- [x] Add `ArchitectureTests` project (NetArchTest.Rules) to enforce zero-duplication at CI +- [x] Move shared `AppSettings` config models to `Contracts.Configuration` + +### 17. Standardized Event Types ✅ + +- [x] Reverse-DNS format: `inventoryalert.{domain}.{action}.v{version}` +- [x] `EventEnvelope` fields standardized: `EventType`, `Payload`, `CorrelationId`, `Source` +- [x] `EventTypes.IsKnown()` for O(1) dispatch validation +- [x] `IReadOnlySet` for type registry + +### 18. Event Handler Dispatcher Pattern ✅ + +- [x] `IEventHandler` interface defined in `Worker.Handlers` +- [x] Dictionary dispatcher in `PollSqsJob` — adding handler = 1 dictionary entry only +- [x] `UnknownEventHandler` fallback — logs warning + ACKs unknown types +- [x] All handlers implement `IEventHandler` interface + +### 19. Retry & Dead Letter Queue ✅ + +- [x] `ApproximateReceiveCount` guard — explicit DLQ push after > 3 receives +- [x] ACK-on-success-only pattern — failures leave message in SQS for natural redelivery +- [x] Configure SQS `RedrivePolicy` in `moto-init/init-sqs.sh` (MaxReceiveCount=3) +- [x] Create `inventory-dlq` queue in Moto init script +- [x] Add `SqsDlqUrl` to `appsettings.Docker.json` and `appsettings.json` + +### 20. DynamoDB Integration ✅ + +- [x] **Phase 4A** — Register `IAmazonDynamoDB` client in `Worker/Program.cs` +- [x] **Phase 4A** — Create `EventLogDynamoRepository.cs` in `Worker/Persistence` +- [x] **Phase 4A** — Add `DynamoDbSettings` (table name) to `WorkerSettings` +- [x] **Phase 4A** — Create DynamoDB table in `moto-init/init-dynamodb.sh` +- [x] **Phase 4B** — Write event to DynamoDB after each successful dispatch (TTL=90d) +- [x] **Phase 4B** — Write `Status=failed` entry on handler exception +- [x] **Phase 4C** — Add `GET /api/events` endpoint to query DynamoDB event log + +--- + +## 🛠️ Maintenance & CI/CD + +- [x] **Fresh State enforcement** — Always run `dotnet clean` before major test/coverage runs to ensure `.editorconfig` changes and build artifacts are correctly synchronized. +- [x] **Coverage Script updated** — `code-coverage.bat` now executes `dotnet clean` before tests. +- [x] **CI Pipeline updated** — `.github/workflows/ci.yml` now executes `dotnet clean` in the Unit Test stage. + +- **Command:** `dotnet clean && dotnet test` +- **Result:** Pure, non-stale test results. +- **Reference:** `.editorconfig` rules require clean/rebuild for strict enforcement in some environments. + +> **Last Updated:** 2026-04-07 +> +> **Legend:** 🔴 P0 = Do now | 🟠 P1 = Next sprint | 🟡 P2 = Data/Validation | 🏗️ P2 = Architecture | 🟢 P3 = Observability | 🟢 P4 = Performance | 🔵 P4 = Security | 🟣 P5 = Quality | ⚫ P6 = DevOps",707,f90e807d257d8050190c23e82ac49f40,doc\archive\ROADMAP.md,0,345,"source, inventoryalert, create, worker, productcontroller, implement, service, review",1779814416.3908205,10,external api market data unitofwork price drop commit mock setup appdbcontext productscontroller iunitofwork stock price data access arrange act assert application service httppost domain entity stock verify igenericrepository container dockerfile application layer asnotracking periodictimer postgres item postgresql hosted service xunit compose httpput productservice moq returns async domain driven design iproductrepository executetransactionasync business logic times once backgroundservice inventory finnhubpricesyncworker savechanges savechangesasync iproductservice unit test atomicity rollback fluentassertions entity framework httpget notification quote iactionresult sku threshold loss dbset efcore dbcontext infrastructure,# 🗺️ Development Roadmap | 🗺️ Development Roadmap > Consolidated from all TODO comments across the codebase +doc,"# Scheduled Jobs Flow Audit + +This document breaks down the execution steps and dependencies of all background jobs in `InventoryAlert.Worker`. + +## 1. SyncPricesJob +**Purpose:** Fetches real-time price quotes for all active products. +1. **Fetch Symbols:** Retrieves all product tickers from `IStockListingRepository`. +2. **Parallel Fetch:** Iterates through tickers and calls `IFinnhubClient.GetQuoteAsync(symbol)` in parallel (limited concurrency). +3. **Record History:** Collects all quotes and performs a bulk insert via `AddRangeAsync` into `PriceHistory`. +4. **Check Alerts:** + - Fetches all active `AlertRules` for the processed symbols in a single batch. + - Evaluates rules with a memoized trade basis cache to avoid redundant queries. + - Queues `Notification` objects. +5. **Notify:** Performs bulk insert of notifications and dispatches external alerts via `IAlertNotifier`. +6. **Persistence:** Persists all state changes in a single transaction via `SaveChangesAsync`. + +## 2. ProcessQueueJob + +**Purpose:** Processes generic background tasks from a local concurrent queue. + +1. **Dequeue:** Polling `IBackgroundTaskQueue` for the next `Func`. +2. **Execute:** Invokes the work item within a scoped `IServiceProvider`. +3. **Log:** Captures success/failure of ad-hoc tasks. + +## 3. SqsScheduledPollerJob + +**Purpose:** Bridges AWS SQS messages to the internal processing queue. + +1. **Long Poll:** Calls `ISqsHelper.ReceiveMessagesAsync` (configured for short/long polling). +2. **Batch Processing:** For each message: + - Identifies the job type. + - Enqueues to `IBackgroundTaskQueue`. + - Deletes message from SQS upon successful enqueue. + +## 4. CleanupPriceHistoryJob + +**Purpose:** Database maintenance for the `PriceHistory` table. + +1. **Define Threshold:** Calculates cutoff date (e.g., `DateTime.UtcNow.AddDays(-30)`). +2. **Batch Delete:** Executes bulk delete on `PriceHistory` records older than the threshold. +3. **Rationale:** With a 15-minute sync interval for 1,000+ symbols, the table grows by ~35M rows/year. Cleanup prevents unbounded storage growth and maintains index performance for historical charts (which capped at 1-year range). + +<<<<<<< HEAD +## 5. NewsSyncJob +**Purpose:** Consolidated job for fetching both Global Market News and Symbol-Specific Company News. +1. **Market News:** Iterates through global categories (General, Forex, Crypto, Merger) and persists to `IMarketNewsDynamoRepository`. +2. **Company News:** + - Lists tickers from `IStockListingRepository`. + - Fetches symbol-specific news in parallel (limited concurrency). + - Persists articles to `ICompanyNewsDynamoRepository`. +3. **Storage:** Uses DynamoDB for high-volume append-only data. +======= +## 5. CompanyNewsJob + +**Purpose:** Syncs latest market news for tracked symbols. + +1. **Get Targets:** Lists tickers from `IProductRepository`. +2. **Fetch News:** Calls `IStockDataService.GetCompanyNewsAsync` for each symbol. +3. **Filter:** Removes duplicates already present in the local database. +4. **Store:** Inserts new news items into `ICompanyNewsRepository`. +>>>>>>> origin/main + +## 6. SyncMetricsJob + +**Purpose:** Syncs fundamental metrics (P/E ratio, Market Cap, etc.). + +1. **Get Symbols:** Identifies tracked products. +2. **External Call:** Calls `IStockDataService.GetMetricsAsync`. +3. **Update Entity:** Maps metrics to the `Product` entity fundamental fields. +4. **Persist:** Updates the database records. + +## 7. SyncEarningsJob + +**Purpose:** Tracks historical and estimated earnings data. + +1. **Iterate Tickers:** Standard loop through active symbols. +2. **Fetch:** `IStockDataService.GetEarningsAsync`. +3. **Merge:** Upserts earnings records into `IEarningsRepository`. + +## 8. SyncRecommendationsJob + +**Purpose:** Captures analyst buy/sell recommendation trends. + +1. **Fetch:** Calls `IStockDataService.GetRecommendationsAsync`. +2. **Aggregate:** Stores the latest ""Strong Buy"", ""Hold"", etc., counts. +3. **Archive:** Keeps a history of recommendation shifts. + +## 9. SyncInsidersJob + +**Purpose:** Monitors insider trading activities. + +1. **Fetch:** Calls `IStockDataService.GetInsidersAsync`. +2. **Deduplicate:** Checks against existing transaction IDs. +3. **Alert:** (If configured) Enqueues an alert if a high-volume insider sale occurs. + +--- + +## Technical Observations for Refactoring + +| Issue | Observation | Recommended Fix | +| :------------------- | :----------------------------------------------------------------------- | :------------------------------------------------------------------------ | +| **API Throttling** | Most ""Sync"" jobs iterate and call Finnhub per symbol. | Implement Batching or Rate-Limiting middleware in the `FinnhubClient`. | +| **Transactionality** | Bulk updates in `SyncPricesJob` use `UpdateRangeAsync`. | Ensure `IUnitOfWork` is used to prevent partial updates. | +| **Redundancy** | Every job manually fetches symbols from `IProductRepository`. | Create a `BaseSyncJob` that handles symbol resolution and error logging. | +| **Queue Saturation** | `SqsScheduledPollerJob` enqueues to the same queue as `ProcessQueueJob`. | Use prioritized queues or separate workers for high-priority price syncs. |",105,dddd2c48a2e88f9c6612010f57fccd3e,doc\archive\SCHEDULED_JOBS_AUDIT.md,0,346,"purpose, news, symbols, fetch, from, calls, symbol, tickers",1777190302.6069095,1,external api application layer arrange act assert googl commit iproductservice igenericrepository atomicity rollback item savechangesasync backgroundservice efcore symbol inventory application service fluentassertions data access stock domain entity business logic unitofwork xunit entity framework dbset loss infrastructure domain driven design unit test asnotracking finnhubpricesyncworker executetransactionasync appdbcontext periodictimer hosted service price drop quote productservice aapl savechanges iunitofwork threshold msft dbcontext stock price sku market data stock ticker notification iproductrepository,# Scheduled Jobs Flow Audit | Scheduled Jobs Flow Audit This document breaks down the execution steps and depe +doc,"--- +description: Seq logging guidance: request/response logging, correlation, and event-flow logging standards (API → SNS/SQS → Worker). +type: reference +status: draft +version: 1.0 +tags: [seq, logging, correlation, tracing, request-response, worker, inventoryalert] +last_updated: 2026-04-28 +---",9,73eac987c2a94af13af7a3c188011497,doc\archive\SEQ_REQUEST_RESPONSE_AND_FLOW_LOGGING.md,0,347,"logging, request, response, correlation, worker, description, guidance, event",1779851803.8026938,1,fluentassertions asnotracking business logic appdbcontext price drop finnhubpricesyncworker unit test threshold entity framework productservice arrange act assert notification application service hosted service loss efcore xunit backgroundservice iproductservice periodictimer dbcontext,"SEQ_REQUEST_RESPONSE_AND_FLOW_LOGGING.md | --- description: Seq logging guidance: request/response logging, correlation, an" +doc,"# Seq: Request/Response + Flow Logging Standard (InventoryAlert) + +This doc is based on the current implementation in branch `refactor/observability-and-logging`, and expands it with recommended standards for: + +- request-level logs (HTTP), +- event-flow logs (publish/consume/handler), +- safe request/response body logging (size + redaction), +- how to query Seq to trace a full flow. + +--- + +## 1) What is implemented now (observed) + +### 1.1 API correlation id + +File: `InventoryManagementSystem/InventoryAlert.Api/Middleware/CorrelationIdMiddleware.cs` + +- Header used: `X-Correlation-Id` +- Precedence: incoming header → new `Guid` +- Stored in: + - `HttpContext.Items[""X-Correlation-Id""]` + - response header `X-Correlation-Id` + - Serilog `LogContext` property: `CorrelationId` +- Also sets the shared correlation provider: + - `ICorrelationProvider.SetCorrelationId(correlationId)` + +### 1.2 One structured “request completion” log per HTTP request + +File: `InventoryManagementSystem/InventoryAlert.Api/Middleware/PerformanceMiddleware.cs` + +Emits exactly one log event with fields: + +- `Method`, `Path`, `StatusCode`, `ElapsedMs` +- `UserId` (or `Anonymous`) +- `CorrelationId` (CID) + +Levels: + +- `Error` for `StatusCode >= 500` +- `Warning` for slow requests (`ElapsedMs > 500`) +- else `Information` + +### 1.3 Serilog service identity fields + +File: `InventoryManagementSystem/InventoryAlert.Api/Program.cs` + +Enriches: + +- `Service = InventoryAlert.Api` +- `Environment = ASPNETCORE_ENVIRONMENT` + +Worker has similar Serilog bootstrap and should also include `Service = InventoryAlert.Worker` (verify/keep consistent). + +### 1.4 API → SNS publish includes CorrelationId + +File: `InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs` + +- Stamps `EventEnvelope.CorrelationId = _correlationProvider.GetCorrelationId()` + +File: `InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs` + +- Publishes SNS MessageAttributes: + - `EventType` + - `Source` + - `CorrelationId` +- Emits publish log: + - `[SnsEventPublisher] Published {EventType} | CorrelationId={CorrelationId} | SnsMessageId={SnsId}` + +### 1.5 Correlation provider supports async/worker contexts + +File: `InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs` + +- Uses `AsyncLocal` to store correlation id when explicitly set. +- Falls back to HttpContext Items. +- Generates a new Guid as last resort. + +--- + +## 2) Standard log event types (recommended) + +Use stable templates so Seq queries are predictable. Prefer structured fields over text parsing. + +### 2.1 HTTP request completion (already implemented) + +Event name (conceptual): + +- `http.completed` + +Fields: + +- `Service`, `Environment` +- `CorrelationId` +- `Method`, `Path`, `StatusCode`, `ElapsedMs` +- `UserId` (when authenticated) + +### 2.2 Event publish + +Event name: + +- `event.published` + +Where: + +- API publisher (`SnsEventPublisher`) + +Fields: + +- `CorrelationId` +- `EventType` +- `Source` +- `SnsMessageId` +- optional: `EnvelopeMessageId` (if you set one), `TenantId`, `UserId` + +### 2.3 Event consumed (SQS) + +Event name: + +- `event.consumed` + +Where: + +- Worker poller (just after successful envelope parse) + +Fields: + +- `CorrelationId` +- `EventType` +- `MessageId` (envelope) and/or SQS `MessageId` +- `ApproximateReceiveCount` + +### 2.4 Handler/job start + completion + +Event names: + +- `handler.started` +- `handler.completed` + +Fields: + +- `CorrelationId` +- `EventType` +- `HandlerName` / `JobName` +- `Succeeded` +- `ElapsedMs` +- `ErrorCode` (when failed) + +--- + +## 3) Safe request/response body logging (recommended; not yet implemented) + +Body logging is the fastest way to explode Seq storage/cost. The standard should be: + +- Off by default +- Enabled only for: + - errors (`StatusCode >= 400`) and/or + - a short-lived debug toggle + +### 3.1 Redaction rules (minimum) + +Never log: + +- `Authorization` header +- cookies / refresh token cookie +- passwords, secrets, API keys +- JWTs + +If you log JSON bodies, redact common fields: + +- `password`, `token`, `accessToken`, `refreshToken`, `apiKey`, `secret`, `key` + +### 3.2 Truncation rules + +- Request body max length: 2–8 KB +- Response body max length: 2–8 KB +- Add: + - `RequestBodyTruncated=true|false` + - `ResponseBodyTruncated=true|false` + +### 3.3 When to log bodies + +Recommended default: + +- log bodies only when: + - `StatusCode >= 400`, OR + - a header is present: `X-Debug-Log-Bodies: true` (dev only), OR + - an allowlist of endpoints. + +### 3.4 Alternative: payload reference + +If you truly need complete bodies: + +- store the full body in a secure store keyed by `CorrelationId` +- store only a `PayloadRef` in Seq + +--- + +## 4) How to trace one flow in Seq (recommended queries) + +### 4.1 Primary key: CorrelationId + +Start with: + +- filter by `CorrelationId = """"`. + +You should expect to see: + +1) `http.completed` from API +2) `event.published` from API publisher +3) `event.consumed` from Worker +4) `handler.*` logs from Worker/Hangfire handlers + +### 4.2 Secondary keys + +If CorrelationId is missing for older events, pivot by: + +- `SnsMessageId` +- `EventType` +- envelope `MessageId` +- user/domain ids (`UserId`, `AlertRuleId`, `Symbol`) + +--- + +## 5) Minimum “flow logging” checklist (what each layer must log) + +### API + +- `http.completed` for every request (done) +- `event.published` whenever publishing to SNS (done) +- `CorrelationId` included in event envelope (done) + +### Worker + +- `event.consumed` when a message is parsed (add if not present) +- handler/job start + completion with `Succeeded` + `ElapsedMs` +- ensure `CorrelationId` is pushed into `LogContext` per envelope + +### UI (optional) + +Do not send browser logs directly to Seq. + +If needed: + +- UI → API telemetry endpoint (sanitized) +- API enriches with `CorrelationId` and forwards to Seq",254,73eac987c2a94af13af7a3c188011497,doc\archive\SEQ_REQUEST_RESPONSE_AND_FLOW_LOGGING.md,0,348,"correlationid, event, request, inventoryalert, fields, correlation, worker, logging",1779851803.8026938,10,fluentassertions asnotracking business logic appdbcontext price drop finnhubpricesyncworker unit test threshold entity framework productservice arrange act assert notification application service hosted service loss efcore xunit backgroundservice iproductservice periodictimer dbcontext,# Seq: Request/Response + Flow Logging Standard (InventoryAlert) | Seq: Request/Response + Flow Logging Standard (InventoryAlert) This doc is based +doc,"# 🛠️ Project Setup — Names & Commands + +> Run all commands from inside `InventoryManagementSystem/` +> unless stated otherwise. + +--- + +## 📁 Final Project Names + +| Project | Type | Purpose | +| :------------------------- | :-------------- | :---------------------------------------------- | +| `InventoryAlert.Api` | ASP.NET Web API | ✅ Existing — extended with event endpoints | +| `InventoryAlert.Contracts` | Class Library | ✅ Done — shared event schemas + domain entities | +| `InventoryAlert.Worker` | Worker Service | ✅ Done — Hangfire + SQS consumer | +| `InventoryAlert.Sample` | Console App | ✅ Done — sample event publisher | +| `InventoryAlert.Tests` | xUnit Test | ✅ Existing | + +--- + +## ⚡ Step 1 — Create New Projects + +```powershell +cd InventoryManagementSystem",24,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,349,"inventoryalert, project, event, done, names, commands, inventorymanagementsystem, existing",1779851803.812538,1,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# 🛠️ Project Setup — Names & Commands | 🛠️ Project Setup — Names & Commands > Run all commands from inside InventoryMana +doc,"# 1. Shared contracts (event schemas) +dotnet new classlib -n InventoryAlert.Contracts -o InventoryAlert.Contracts",27,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,350,"contracts, inventoryalert, shared, event, schemas, dotnet, classlib",1779851803.812538,25,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# 1. Shared contracts (event schemas) | 1 +doc,"# 2. Background worker (Hangfire + SQS) +dotnet new worker -n InventoryAlert.Worker -o InventoryAlert.Worker",30,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,351,"worker, inventoryalert, background, hangfire, dotnet",1779851803.812538,28,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# 2. Background worker (Hangfire + SQS) | 2 +doc,"# 3. Sample publisher CLI +dotnet new console -n InventoryAlert.Sample -o InventoryAlert.Sample +``` + +--- + +## ⚡ Step 2 — Add to Solution + +```powershell +dotnet sln add InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +dotnet sln add InventoryAlert.Worker/InventoryAlert.Worker.csproj +dotnet sln add InventoryAlert.Sample/InventoryAlert.Sample.csproj +``` + +--- + +## ⚡ Step 3 — Add Project References + +### `InventoryAlert.Api` references `Contracts` +```powershell +dotnet add InventoryAlert.Api/InventoryAlert.Api.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +``` + +### `InventoryAlert.Worker` references `Contracts` +```powershell +dotnet add InventoryAlert.Worker/InventoryAlert.Worker.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +``` + +### `InventoryAlert.Sample` references `Contracts` +```powershell +dotnet add InventoryAlert.Sample/InventoryAlert.Sample.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj +``` + +--- + +## ⚡ Step 4 — Install NuGet Packages + +### `InventoryAlert.Api` — Event publishing +```powershell",69,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,352,"inventoryalert, csproj, contracts, sample, dotnet, powershell, worker, reference",1779851803.812538,31,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# 3. Sample publisher CLI | 3 +doc,# AWS SNS publisher (talks to Moto at localhost:5000),70,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,353,"publisher, talks, moto, localhost",1779851803.812538,70,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# AWS SNS publisher (talks to Moto at localhost:5000) | AWS SNS publisher (talks to Moto at localhost:5000) +doc,"# ✅ INSTALLED +dotnet add InventoryAlert.Api package AWSSDK.SimpleNotificationService +dotnet add InventoryAlert.Api package AWSSDK.SQS +``` + +### `InventoryAlert.Worker` — Hangfire + SQS consumer + Redis + DB +```powershell",77,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,354,"dotnet, inventoryalert, package, awssdk, installed, simplenotificationservice, powershell",1779851803.812538,71,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# ✅ INSTALLED | ✅ INSTALLED dotnet add InventoryAlert.Api package AWSSDK.SimpleNotificationServi +doc,"# Hangfire core +dotnet add InventoryAlert.Worker package Hangfire.AspNetCore +dotnet add InventoryAlert.Worker package Hangfire.PostgreSql",81,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,355,"hangfire, dotnet, inventoryalert, worker, package, core, aspnetcore, postgresql",1779851803.812538,78,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# Hangfire core | Hangfire core dotnet add InventoryAlert.Worker package Hangfire.AspNetCore dotne +doc,"# SQS consumer +dotnet add InventoryAlert.Worker package AWSSDK.SQS",84,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,356,"consumer, dotnet, inventoryalert, worker, package, awssdk",1779851803.812538,82,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# SQS consumer | SQS consumer dotnet add InventoryAlert.Worker package AWSSDK.SQS +doc,"# Redis caching +dotnet add InventoryAlert.Worker package Microsoft.Extensions.Caching.StackExchangeRedis",87,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,357,"caching, redis, dotnet, inventoryalert, worker, package, microsoft, extensions",1779851803.812538,85,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# Redis caching | Redis caching dotnet add InventoryAlert.Worker package Microsoft.Extensions.Cach +doc,"# EF Core (share same DB) +dotnet add InventoryAlert.Worker package Npgsql.EntityFrameworkCore.PostgreSQL +dotnet add InventoryAlert.Worker package Microsoft.EntityFrameworkCore.Design",91,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,358,"dotnet, inventoryalert, worker, package, entityframeworkcore, core, share, same",1779851803.812538,88,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# EF Core (share same DB) | EF Core (share same DB) dotnet add InventoryAlert.Worker package Npgsql.EntityFr +doc,"# HTTP client (for Finnhub calls) +dotnet add InventoryAlert.Worker package RestSharp +``` + +### `InventoryAlert.Worker` — DynamoDB (Future Enterprise Extension) + +> **⚠️ Optional:** Only install when migrating from Postgres `EventLog` and Redis dedup +> to the polyglot DynamoDB strategy described in `EVENT_DRIVEN_PLAN.md`. + +```powershell",101,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,359,"http, client, finnhub, calls, dotnet, inventoryalert, worker, package",1779851803.812538,92,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# HTTP client (for Finnhub calls) | HTTP client (for Finnhub calls) dotnet add InventoryAlert.Worker package RestSha +doc,"# DynamoDB client + object persistence model +dotnet add InventoryAlert.Worker package AWSSDK.DynamoDBv2 +``` + +### `InventoryAlert.Sample` — HTTP client to call the API +```powershell +dotnet add InventoryAlert.Sample package Microsoft.Extensions.Http +``` + +--- + +## ⚡ Step 5 — Verify Solution Builds + +```powershell +dotnet build InventoryManagementSystem.sln +``` + +--- + +## ⚙️ Step 6 — Environment Variables + +The Worker's `.NET` config keys live in `InventoryAlert.Worker/appsettings.Docker.json`: + +```json +{ + ""Database"": { ""DefaultConnection"": ""host=db;port=5432;..."" }, + ""Redis"": { ""Connection"": ""redis:6379"" }, + ""Aws"": { + ""EndpointUrl"": ""http://moto:5000"", + ""SnsTopicArn"": ""arn:aws:sns:us-east-1:123456789012:inventory-events"", + ""SqsQueueUrl"": ""http://moto:5000/123456789012/event-queue"" + } +} +``` + +AWS SDK credential vars must stay in `docker-compose.yml` (SDK reads OS env directly): + +```env +AWS_ACCESS_KEY_ID=test +AWS_SECRET_ACCESS_KEY=test +AWS_DEFAULT_REGION=us-east-1 ``` -POST /api/auth/login -Body: { ""username"": ""admin"", ""password"": ""admin123"" } -→ 200 OK: { ""token"": """" } -→ 401 Unauthorized + +> **Note:** Moto accepts any value for credentials. Use `test` / `test` locally. + +Future Telegram vars (add only when implementing Phase F): + +```env +TELEGRAM_BOT_TOKEN=your_bot_token_here +TELEGRAM_CHAT_ID=your_chat_id_here ``` -- Tokens are **HmacSha256-signed**, expire after **2 hours** -- Include in subsequent requests: `Authorization: Bearer ` -- Credentials configured in `appsettings.json → Auth:Username / Auth:Password` -- `EventsController` endpoints are **unauthenticated** (internal/service-to-service) +--- + +## 🐳 Step 7 — Docker Compose (Final State) + +`docker-compose.yml` is fully configured. Services and startup order: + +```yaml +services: + api: # REST API — depends on: db (healthy), moto-init (completed) + worker: # Hangfire — depends on: db (healthy), redis, moto-init (completed) + db: # PostgreSQL 17-alpine — healthcheck: pg_isready + redis: # Redis 7.2-alpine — healthcheck: redis-cli ping + moto: # motoserver/moto:5.1.22 — Mock SNS/SQS, healthcheck: curl :5000 + moto-init: # amazon/aws-cli:2.3.4 — runs init-sqs.sh ONCE on startup +``` + +> **Enforced startup order:** +> `db` + `redis` + `moto` (healthchecks pass) → `moto-init` (exits 0) → `api` + `worker` + +### Worker Dockerfile + +Located at `InventoryAlert.Worker/Dockerfile`. Multi-stage build using +`dotnet/runtime:10.0` (not `aspnet`) — the worker has no HTTP listener. --- -## 📦 1. Product Inventory Management +## 🛠️ Step 8 — Moto Init Script -**Business Goal:** Centralized catalog for warehouse staff to manage product metadata, pricing baselines, and stock thresholds. +Automatically creates SNS/SQS resources on first Docker boot: -### The `Product` Entity +- **Script:** `SolutionFolder/moto-init/init-sqs.sh` +- **Runs via:** `moto-init` service in docker-compose (one-shot, exits when done) -| Field | Type | Purpose | -|---|---|---| -| `Id` | `int` | Primary key | -| `Name` | `string` | Human-readable product name | -| `TickerSymbol` | `string` | NYSE/NASDAQ ticker (e.g. `AAPL`) — links to Finnhub | -| `OriginPrice` | `decimal` | Baseline purchase price — **never changes automatically** | -| `CurrentPrice` | `decimal` | Latest price synced from Finnhub | -| `PriceAlertThreshold` | `double` | e.g. `0.2` = alert when price drops >20% from origin | -| `StockCount` | `int` | Current physical unit count | -| `StockAlertThreshold` | `int` | Alert threshold for low-stock events | -| `LastAlertSentAt` | `DateTime?` | Cooldown gate — prevents duplicate alert spam | +| Resource | Type | Notes | +| :-------------------- | :----------- | :--------------------------------- | +| `inventory-event-dlq` | SQS Standard | Dead Letter Queue (max 3 receives) | +| `event-queue` | SQS Standard | Main queue — DLQ redrive wired | +| `inventory-events` | SNS Topic | Auto-subscribed to `event-queue` | -### Endpoints +> Script is **idempotent** — checks before creating, safe to re-run. -| Method | Route | Handler | Response | -|---|---|---|---| -| `GET` | `/api/products` | `GetProducts([FromQuery] PaginationParams)` | `200 PagedResult` | -| `GET` | `/api/products/{id}` | `GetProductById(int id)` | `200 ProductResponse` / `404` | -| `POST` | `/api/products` | `CreateProduct(ProductRequest)` | `201 ProductResponse` | -| `PUT` | `/api/products/{id}` | `UpdateProduct(int id, ProductRequest)` | `200 ProductResponse` / `404` | -| `PATCH` | `/api/products/{id}/stock?stockCount={n}` | `UpdateStockCount(int id, int stockCount)` | `200 ProductResponse` / `404` | -| `DELETE` | `/api/products/{id}` | `DeleteProduct(int id)` | `204 No Content` / `404` | -| `POST` | `/api/products/bulk` | `BulkInsertProducts(IEnumerable)` | `204 No Content` | -| `GET` | `/api/products/price-alerts` | `GetPriceLossAlerts()` | `200 IEnumerable` | -| `POST` | `/api/products/sync-price` | `SyncStockPrice()` | `204 No Content` | +--- -### Pagination -`GET /api/products` accepts `?pageNumber=1&pageSize=20` and returns: -```json +## ✅ Quick Checklist + +``` +[x] dotnet new classlib → InventoryAlert.Contracts ✅ Done +[x] dotnet new worker → InventoryAlert.Worker ✅ Done +[x] dotnet new console → InventoryAlert.Sample ✅ Done +[x] dotnet sln add → 3 projects added to .sln ✅ Done +[x] dotnet add reference → Contracts in Api + Worker + Sample ✅ Done +[x] dotnet add package → All NuGet packages installed ✅ Done + (Api: AWSSDK.SNS + SQS + Serilog + FluentValidation) + (Worker: Hangfire + SQS + Redis + EF + RestSharp) + (Sample: AWSSDK.SNS + SQS + HttpClient) ✅ Done +[x] Entities migrated → Contracts/Entities/ (Product, EventLog, + EarningsRecord, InsiderTransaction, NewsRecord) + ✅ Done +[x] Worker Dockerfile → InventoryAlert.Worker/Dockerfile ✅ Done +[x] appsettings.Docker → Worker Docker config ✅ Done +[x] init-sqs.sh → SNS/SQS resources defined ✅ Done +[x] docker-compose.yml → All services + moto-init ✅ Done +[x] TELEGRAM vars → Implemented (Phase F) — fill BotToken + ChatId ✅ +[x] dotnet build → Full solution compiles (0 errors) ✅ +[x] dotnet test → 61/61 tests pass ✅ +```",219,ed17c4b31c160b57124b4be6b50e04c9,doc\archive\SETUP_COMMANDS.md,0,360,"done, dotnet, worker, moto, redis, inventoryalert, init, sample",1779851803.812538,102,loss arrange act assert postgresql appdbcontext unit test productservice postgres finnhubpricesyncworker rollback quote fluentassertions dbcontext item market data backgroundservice hosted service periodictimer sku entity framework stock application service price drop dockerfile moq business logic times once asnotracking threshold external api notification savechanges compose returns async inventory efcore xunit container mock setup commit verify atomicity stock price unitofwork iproductservice,# DynamoDB client + object persistence model | DynamoDB client + object persistence model dotnet add InventoryAlert.Worker pack +doc,"# SignalR Real-Time Notification Plan + +This document outlines the architectural plan for integrating real-time notifications into the InventoryAlert system using SignalR and a Redis backplane. + +## 1. Objectives +- **Real-time UI Updates:** Push price alerts and system notifications directly to the frontend without manual refresh. +- **Cross-Service Communication:** Allow the `InventoryAlert.Worker` (which detects alerts) to trigger SignalR messages on the `InventoryAlert.Api` (which hosts the hub). +- **Secure Delivery:** Ensure users only receive notifications intended for them using JWT authentication. + +## 2. Architecture Diagram + +```mermaid +graph TD + Worker[Worker Service] -->|Price Sync & Alert Detect| DB[(PostgreSQL)] + Worker -->|Push Notification| RedisBackplane[Redis Backplane] + RedisBackplane --> Hub[NotificationHub in Api Service] + Hub -->|Push via WebSockets| UI[Next.js Frontend] + UI -->|Connects via JWT| Hub +``` + +## 3. Business & Data Flow + +Why do we need this complex setup? Here is the step-by-step business logic: + +1. **The Trigger (External):** The market changes. Finnhub provides a new price for `AAPL`. +2. **The Detector (Worker):** The `SyncPricesJob` in the **Worker Service** fetches this price. It runs the business rules (e.g., ""Did it drop 10% from the user's cost?""). +3. **The Decision (Worker):** The Worker identifies a ""Breach"". It creates a `Notification` record in **PostgreSQL** so the user has a permanent history of the alert. +4. **The Hand-off (Worker -> Redis):** The Worker doesn't know who is currently online. It publishes a ""Real-time Signal"" to the **Redis Backplane**. +5. **The Relay (Api):** The **Api Service** (which hosts the SignalR Hub) is subscribed to Redis. It sees the alert and checks: ""Is User A currently connected to my WebSocket?"". +6. **The Delivery (Api -> UI):** If User A is online, the Api pushes the message through the open WebSocket tunnel instantly. +7. **The Experience (UI):** The user's browser receives the message. A **Toast notification** pops up, and the **Notification Badge** in the header increments without the user needing to refresh the page. + +### Why not just use the API for everything? +- **Separation of Concerns:** The API is for fast User interactions (browsing, buying, settings). The Worker is for heavy, scheduled ""Intelligence"" tasks (syncing 1,000s of prices, calculating complex math). +- **Scalability:** If we have 10,000 users, we can add more API instances to handle traffic. All instances stay synced through Redis. + +## 4. Implementation Steps + +### Phase 1: Infrastructure (Backend) +1. **Add Dependencies:** + - Add `Microsoft.AspNetCore.SignalR.StackExchangeRedis` to both **Api** and **Worker** projects. +2. **Shared Hub Definition:** + - Create `INotificationHub` interface in `InventoryAlert.Domain` for type-safe client methods. + - Define a shared constant for the Hub route (e.g., `/hubs/notifications`). + +### Phase 2: InventoryAlert.Api (The Host) +1. **Create Hub:** + - Implement `NotificationHub : Hub`. + - Add `[Authorize]` attribute to ensure only authenticated users connect. +2. **Configure SignalR:** + - In `Program.cs`: `builder.Services.AddSignalR().AddStackExchangeRedis(redisConnectionString)`. + - Map the hub: `app.MapHub(""/hubs/notifications"")`. +3. **JWT Configuration:** + - Update `JwtBearer` configuration to handle SignalR access tokens from query strings (standard for WebSockets). + +### Phase 3: InventoryAlert.Worker (The Producer) +1. **Configure SignalR Client Logic:** + - In `Program.cs`: Add SignalR services and Redis backplane (even though it doesn't host the hub). +2. **Refactor `NotificationAlertNotifier`:** + - Inject `IHubContext`. + - Update `NotifyAsync` to call `_hubContext.Clients.User(notification.UserId).ReceiveNotification(dto)`. + +### Phase 4: InventoryAlert.UI (The Consumer) +1. **Install Client:** + - `npm install @microsoft/signalr` +2. **Notification Hook:** + - Create `useSignalR` or `useNotifications` hook. + - Handle connection lifecycle (start, stop, reconnect). + - Listen for `ReceiveNotification` events. +3. **UI Integration:** + - Integration with **Toast notifications**. + - Auto-increment notification badge in the navbar. + - (Optional) Trigger sound or browser desktop notification. + +## 4. Technical Details + +### INotificationHub Interface +```csharp +public interface INotificationHub { - ""items"": [...], - ""totalItems"": 150, - ""pageNumber"": 1, - ""pageSize"": 20 + Task ReceiveNotification(NotificationResponse notification); } ``` -### Single-Item Cache -`GetProductByIdAsync` uses **`IMemoryCache`** with key `""Product_{id}""` and a **10-minute sliding TTL**. -`UpdateProductAsync`, `UpdateStockCountAsync`, and `DeleteProductAsync` all call `_cache.Remove($""Product_{id}"")` to invalidate immediately. +### Authentication Handling (Api) +Since WebSockets don't support custom headers easily, we must handle the token in the query string: +```csharp +options.Events = new JwtBearerEvents +{ + OnMessageReceived = context => + { + var accessToken = context.Request.Query[""access_token""]; + var path = context.HttpContext.Request.Path; + if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments(""/hubs"")) + { + context.Token = accessToken; + } + return Task.CompletedTask; + } +}; +``` + +## 5. Next Steps +1. [ ] Create `INotificationHub` and DTOs in Domain. +2. [ ] Setup Redis Backplane in both services. +3. [ ] Implement `NotificationHub` in Api. +4. [ ] Refactor `NotificationAlertNotifier` in Worker. +5. [ ] Build the UI listener.",108,20b396a3f01d21e3bb13644f9cf3108a,doc\archive\SIGNALR_INTEGRATION_PLAN.md,0,361,"worker, signalr, notification, user, inventoryalert, redis, notifications, inotificationhub",1777190302.6092205,1,application service business logic backgroundservice productservice hosted service appdbcontext price drop stock price notification periodictimer quote market data asnotracking threshold iproductservice dbcontext loss entity framework efcore finnhubpricesyncworker external api,# SignalR Real-Time Notification Plan | SignalR Real-Time Notification Plan This document outlines the architectural pla +doc,"(""AAPL"", ""Apple Inc."", ""NASDAQ"", ""stock""), + (""MSFT"", ""Microsoft Corporation"", ""NASDAQ"", ""stock""), + (""GOOGL"", ""Alphabet Inc."", ""NASDAQ"", ""stock""), + (""AMZN"", ""Amazon.com Inc."", ""NASDAQ"", ""stock""), + (""NVDA"", ""NVIDIA Corporation"", ""NASDAQ"", ""stock""), + (""META"", ""Meta Platforms Inc."", ""NASDAQ"", ""stock""), + (""TSLA"", ""Tesla Inc."", ""NASDAQ"", ""stock""), + (""NFLX"", ""Netflix Inc."", ""NASDAQ"", ""stock""), + (""AMD"", ""Advanced Micro Devices Inc."", ""NASDAQ"", ""stock""), + (""INTC"", ""Intel Corporation"", ""NASDAQ"", ""stock""), + (""JPM"", ""JPMorgan Chase & Co."", ""NYSE"", ""stock""), + (""BAC"", ""Bank of America Corporation"", ""NYSE"", ""stock""), + (""GS"", ""Goldman Sachs Group Inc."", ""NYSE"", ""stock""), + (""V"", ""Visa Inc."", ""NYSE"", ""stock""), + (""MA"", ""Mastercard Incorporated"", ""NYSE"", ""stock""), + (""JNJ"", ""Johnson & Johnson"", ""NYSE"", ""stock""), + (""PFE"", ""Pfizer Inc."", ""NYSE"", ""stock""), + (""UNH"", ""UnitedHealth Group Incorporated"", ""NYSE"", ""stock""), + (""XOM"", ""Exxon Mobil Corporation"", ""NYSE"", ""stock""), + (""CVX"", ""Chevron Corporation"", ""NYSE"", ""stock""),",21,6ee596ecced18ca0f4d4b3b18ead4595,doc\archive\stock.md,0,362,"stock, nasdaq, nyse, corporation, meta, group, incorporated, johnson",1775670503.934977,1,,"stock.md | (""AAPL"", ""Apple Inc."", ""NASDAQ"", ""stock""), (""MSFT""" +doc,"# InventoryAlert v3 — System Architecture & Flow Review + +This document provides a technical walkthrough of the refined event-driven architecture, covering the interaction between the Next.js UI, ASP.NET Core API, and the Background Worker. + +## 1. High-Level Architecture + +The system follows a **Reactive Hybrid** approach: +- **Scheduled**: Driven by Hangfire (Polling). +- **Event-Driven**: Driven by SQS/SNS (Instant). +- **Real-Time**: Driven by SignalR + Redis Backplane (Push). + +--- + +## 2. The Real-Time Notification Flow +This flow describes how a user receives a price alert without refreshing their browser. + +```mermaid +sequenceDiagram + participant UI as Next.js UI + participant API as InventoryAlert.Api + participant Redis as Redis Backplane + participant W as InventoryAlert.Worker + participant DB as PostgreSQL + + UI->>API: 1. WebSocket Connect (JWT Auth) + API->>UI: 2. Connection Established + + Note over W,DB: SyncPricesJob detects a breach + W->>DB: 3. Insert Notification record + W->>Redis: 4. Publish SignalR Message (UserId payload) + + Redis->>API: 5. Relay Message to all Hub instances + API->>API: 6. Identify local WebSocket for User + API-->>UI: 7. SignalR: ReceiveNotification(dto) + + UI->>UI: 8. Update Badge Count + Show Toast +``` + +--- + +## 3. SQS Message & DLQ Flow +This flow ensures zero data loss when the API requests heavy work from the Worker. + +```mermaid +flowchart TD + API[""InventoryAlert.Api""] -->|Publish| SNS[""Amazon SNS Topic""] + SNS -->|Fan-out| SQS[""SQS Main Queue""] + + subgraph Worker [InventoryAlert.Worker] + Poller[""ProcessQueueJob (Continuous)""] + Unwrap[""TryDeserialize (SNS Unwrap)""] + Router[""IntegrationMessageRouter""] + Handler[""Event Handler / Sync Job""] + end + + SQS -->|1. Long Poll| Poller + Poller -->|2. Detect SNS Wrap| Unwrap + Unwrap -->|3. Get EventEnvelope| Router + Router -->|4. Execute| Handler -### Bulk Insert -`POST /api/products/bulk` accepts a JSON array of `ProductRequest`. Runs the entire insert inside `ExecuteTransactionAsync` — all-or-nothing. Returns `204` with no body to minimize bandwidth on large payloads. + Handler -->|Success| Ack[""5. Delete SQS Message + SET Redis processed:id""] + Handler -->|Failure| Nack[""5. STOP! Leave in Queue (Visibility Timeout)""] + + Nack -.->|Retry Loop 1-3| Poller + Nack -->|If Retries > 3| DLQ[(""Dead Letter Queue"")] +``` --- -## 📉 2. Stock Count Management +## 4. Worker Message Handling & Reliability -**Business Goal:** Allow warehouse scanning devices to update unit counts without overwriting other concurrent edits. +### 4.1 Does the Worker scan SNS or SQS? +The Worker **polls (scans) SQS only**. -### Surgical PATCH Pattern -`PATCH /api/products/{id}/stock?stockCount=42` only updates the `StockCount` field. -The full `Product` record is re-fetched first (`GetByIdAsync`), then only `StockCount` is mutated before the transaction write — preventing race conditions where a scanner zeroes out a field it didn't intend to touch. +- **SNS (Pub/Sub)**: Acts as the ""Dispatcher"". The API publishes an event to SNS, which then ""pushes"" that event into the SQS queue. The Worker never talks to SNS directly for consumption. +- **SQS (Queue)**: Acts as the ""Buffer"". It stores the messages until the Worker is ready to process them. +- **The Poller**: The `ProcessQueueJob` runs a continuous `while` loop, calling `ReceiveMessagesAsync` on the SQS queue every few seconds (Long Polling). -``` -PATCH /api/products/7/stock?stockCount=42 -Authorization: Bearer -→ 200: { ""id"": 7, ""name"": ""iPhone 15"", ""stockCount"": 42, ... } -→ 404: if product doesn't exist -``` +### 4.2 How the Worker handles Retries and Failures ---- +The system uses a **""Non-Acknowledge""** failure strategy combined with **SQS Visibility Timeouts**. -## 📈 3. Live Price Sync (Finnhub Integration) +1. **Lease**: The Worker pulls a message. SQS marks it as ""Invisible"" to other workers for **30 seconds**. +2. **Processing**: The Worker attempts to route and execute the handler. +3. **Outcome A (Success)**: + - The handler finishes without errors. + - The Worker calls `DeleteMessageAsync` (the **ACK**). + - The message is permanently removed from SQS. +4. **Outcome B (Failure/Crash)**: + - An exception is thrown (e.g., Database down, API error). + - The Worker **stops** and logs the error. It **does NOT** delete the message. +5. **Retry**: + - After the 30-second ""Visibility Timeout"" expires, SQS sees that the message was never deleted. + - SQS makes the message **visible again** in the main queue. + - The Worker (or another instance) picks it up again. +6. **Dead Letter Queue (DLQ)**: + - Every time SQS redelivers a message, its `ReceiveCount` increases. + - Once the count exceeds **3** (the `maxReceiveCount`), SQS automatically moves the message to the **DLQ**. + - This prevents a ""Poison Message"" from crashing the worker in an infinite loop. -**Business Goal:** Keep `CurrentPrice` aligned with real-world market valuations to drive accurate loss alerts. +--- -### Automatic Background Sync +## 5. Scheduled Jobs (Hangfire) +Driven background tasks that require high consistency and persistence. -`SyncPricesJob` (Hangfire, scheduled inside `InventoryAlert.Worker`) periodically calls `IProductService.SyncCurrentPricesAsync`: +| Job Name | Trigger | Logic | +| :--- | :--- | :--- | +| **SyncPricesJob** | Every 15 min | Parallel fetch (v3) -> Batch Evaluate -> SignalR Push. | +| **NewsSyncJob** | Every 2 hours | **Consolidated:** Syncs both Market News and Company News in parallel. | +| **CleanupPrices** | Daily at 02:10 | Batched delete of PriceHistory older than 1 year. | -1. Fetches all products from `IProductRepository` -2. For each product, calls `IFinnhubClient.GetQuoteAsync(tickerSymbol, ct)` -3. If `quote.CurrentPrice is null or 0` → logs a warning and **skips** (never throws) -4. Builds a batch of updated `Product` objects -5. Wraps `UpdateRangeAsync` inside `ExecuteTransactionAsync` — all-or-nothing bulk update +--- -### Manual Trigger +## 5. UI Technical Stack (Next.js 15) -``` -POST /api/products/sync-price -Authorization: Bearer -→ 204 No Content (after sync completes) -``` +### 5.1 Real-Time Hook (`useSignalR`) +- **Lifecycle**: Automatically starts connection on mount, stops on unmount. +- **Resilience**: Configured with `withAutomaticReconnect()`. +- **Security**: Uses `accessTokenFactory` to safely pull JWT from `localStorage`. -Useful for analysts to force an immediate refresh before running price-alert queries. +### 5.2 Global State (`NotificationProvider`) +- Centralizes `unreadCount` via React Context. +- Replaces legacy 30s polling with event-based updates. +- **Sync Logic**: Calls `/unread-count` once on app load, then relies on SignalR for increments. + +### 5.3 Resilient API Client (`api.ts`) +- **Late-binding CID**: Automatically captures `X-Correlation-Id` from headers on failure. +- **Loop Protection**: Prevents the `/auth/refresh` endpoint from triggering its own refresh loop on 401. --- -## 🚨 4. Price Loss Alert Engine +## 6. Operational Technical Notes -**Business Goal:** Automatically detect and report products whose market price has dropped dangerously below the baseline cost. +### Deduplication Strategy +We use a **""Late-Commit""** Redis strategy: +1. Message received. +2. Check if `msg:processed:{id}` exists. +3. Process task. +4. **Only if successful**: Set `msg:processed:{id}` with 24h TTL and delete from SQS. +*Benefit: Ensures that if the worker pod crashes during processing, the message is not lost and will be retried.* -### Alert Calculation +### Correlation Tracing +Every request/event now carries a `CorrelationId`. +- **In Seq**: Use query `CorrelationId = ""your-id""` to see the logs from API request -> SQS Publish -> Worker Receipt -> Final DB Save.",144,908614765ace4901de2146596abf9421,doc\archive\SYSTEM_FLOW_REVIEW_V3.md,0,363,"worker, message, from, event, driven, flow, queue, every",1779814416.3928213,1,hosted service threshold finnhubpricesyncworker asnotracking backgroundservice periodictimer notification efcore appdbcontext dbcontext price drop loss entity framework,# InventoryAlert v3 — System Architecture & Flow Review | InventoryAlert v3 — System Architecture & Flow Review This document provides a t +doc,"--- +description: InventoryAlert.UI audit of pages/components and recommendations (paging, reuse, UX, maintainability). Documentation only. +type: reference +status: draft +version: 1.0 +tags: [ui, audit, components, pages, ux, nextjs, inventoryalert] +last_updated: 2026-04-26 +---",9,5080f1111fc0c2f3f9042a921808473d,doc\archive\UI_COMPONENTS_AND_PAGES_AUDIT.md,0,364,"inventoryalert, audit, pages, components, description, recommendations, paging, reuse",1779814416.3928213,1,entity framework efcore price drop asnotracking httppost iactionresult dbcontext appdbcontext httpget productscontroller httpput threshold notification loss,UI_COMPONENTS_AND_PAGES_AUDIT.md | --- description: InventoryAlert.UI audit of pages/components and recommendations +doc,"# InventoryAlert.UI — Components & Pages Audit + Enhancement Suggestions -`GetPriceLossAlertsAsync` iterates all products and calculates: -``` -priceDiff = CurrentPrice - OriginPrice -priceChangePercent = priceDiff / OriginPrice (negative = loss) -lossMagnitude = Math.Abs(priceChangePercent) +This document scans the current UI project and lists: -→ Alert fires if: lossMagnitude >= PriceAlertThreshold -``` +- every route/page and what it calls, +- reusable components and where they are used, +- gaps and recommended enhancements (especially paging, consistency, and maintainability). -### Cooldown Gate (Spam Prevention) -Before raising an alert, the system checks `LastAlertSentAt`: -```csharp -var cooldown = TimeSpan.FromHours(1); -if (product.LastAlertSentAt.HasValue && - DateTime.UtcNow - product.LastAlertSentAt.Value < cooldown) - continue; // skip — still in cooldown window -``` -This prevents the same product from generating duplicate notifications within 60 minutes, even if the price remains below threshold. +Scope: -### Alert Endpoint +- UI code: `InventoryAlert.UI/src/*` +- No code changes included here (documentation-only). -``` -GET /api/products/price-alerts -Authorization: Bearer -→ 200: [ - { - ""id"": 3, - ""name"": ""Tesla Model S Parts"", - ""tickerSymbol"": ""TSLA"", - ""originPrice"": 950.00, - ""currentPrice"": 700.00, - ""priceDiff"": 250.00, - ""priceChangePercent"": -0.2632, - ""priceAlertThreshold"": 0.2, - ""stockCount"": 15 - } - ] -``` +Files scanned (as of `2026-04-26`): + +- Routes: `InventoryAlert.UI/src/app/**/page.tsx`, `InventoryAlert.UI/src/app/layout.tsx` +- Components: `InventoryAlert.UI/src/components/*.tsx` +- Hooks: `InventoryAlert.UI/src/hooks/*.ts` +- Client utilities: `InventoryAlert.UI/src/lib/*.ts` --- -## 📨 5. Event Publishing & Audit +## 1) Project Entry + Global Flow -**Business Goal:** Emit structured domain events to downstream services (Telegram, Slack, analytics) without coupling to the REST API. +### 1.1 Root layout + providers -### Publish Any Event +`InventoryAlert.UI/src/app/layout.tsx`: -``` -POST /api/events -Body: { ""eventType"": ""inventoryalert.pricing.price-drop.v1"", ""payload"": { ... } } -→ 202 Accepted -``` +- applies theme class early (inline script) +- wraps the app with: + - `ThemeProvider` (`src/components/ThemeProvider.tsx`) + - `NotificationProvider` (`src/components/NotificationProvider.tsx`) + - `NavbarWrapper` (`src/components/NavbarWrapper.tsx`) -### Trigger Pre-Built Alerts +Render tree (simplified): -| Endpoint | Event Type | Payload | -|---|---|---| -| `POST /api/events/market-alert` | `MarketPriceAlert` | `{ productId, symbol, originPrice, currentPrice, dropPercent }` | -| `POST /api/events/news-alert` | `CompanyNewsAlert` | `{ symbol, headline, source, url, publishedAt }` | +`` → `` → `` → `
{children}
` -### Event Type Registry +### 1.2 API client pattern -``` -GET /api/events/types -→ 200: [ - ""inventoryalert.pricing.price-drop.v1"", - ""inventoryalert.inventory.stock-low.v1"", - ""inventoryalert.fundamentals.earnings.v1"", - ""inventoryalert.fundamentals.insider-sell.v1"", - ""inventoryalert.news.headline.v1"" - ] -``` +`InventoryAlert.UI/src/lib/api.ts`: -### Audit Log (DynamoDB) +- reads access token from `localStorage` (`auth_token`) +- attaches `Authorization: Bearer ` when present +- always sends cookies (`credentials: ""include""`) to support refresh token flow +- on `401`: + - attempts refresh via `POST /api/v1/auth/refresh` + - retries once + - evicts token and redirects to `/login` if refresh fails -``` -GET /api/events/logs/{eventType}?limit=20 -→ 200: [ { ""messageId"": ""..."", ""eventType"": ""..."", ""timestamp"": ""..."", ... } ] -``` +Enhancement notes: -Every published event is written to **DynamoDB `EventLogs` table** before SNS dispatch. Logs are query-able by `eventType` with a configurable `limit`. +- error parsing currently checks `userFriendlyMessage/message/title`, but the API error shape is `ErrorResponse { errors[], errorId }`. Consider mapping UI error extraction to `errors[0].message` (and include `X-Correlation-Id` when present). --- -## 🔁 6. Background Event Handling (Worker) - -**Business Goal:** Process incoming domain events asynchronously without blocking the API, with persistence and notification side effects. - -### Registered Event Handlers (Worker) +## 2) Pages (Routes) Inventory -| Event Type | Handler | Side Effect | -|---|---|---| -| `MarketPriceAlert` | `PriceAlertHandler` | Structured log: `🚨 PRICE DROP ALERT {symbol} -{dropPercent:P1}` — **Telegram plug-in point** | -| `EarningsAlert` | `EarningsHandler` | Persists `EarningsRecord` to PostgreSQL (EPS actual vs estimated) | -| `CompanyNewsAlert` | `NewsHandler` | Persists `NewsRecord` to PostgreSQL (headline, source, URL) | -| `InsiderSellAlert` | `InsiderHandler` | Persists `InsiderTransaction` to PostgreSQL | -| *(unknown type)* | `UnknownEventHandler` | Safely logs and discards — no crash, no DLQ escalation | +All routes are App Router pages under `InventoryAlert.UI/src/app/*`. -### Dead-Letter Queue -After 3 failed processing attempts, SQS routes the message to `inventory-event-dlq` for manual inspection without causing consumer stalls.",236,51a503b6410630f3c5b56f98bc5b895a,doc\archive\FEATURES_OVERVIEW.md,0,330,"products, alert, price, event, product, business, goal, stockcount",1775670503.9164877,10,external api appdbcontext atomicity compose postgres stock price httpget httppost fluentassertions quote unitofwork postgresql commit container business logic xunit data access iactionresult periodictimer msft market data dockerfile price drop arrange act assert entity framework productservice rollback notification inventory finnhubpricesyncworker backgroundservice asnotracking httpput iproductservice googl threshold dbset productscontroller sku stock hosted service stock ticker savechanges iproductrepository loss item symbol dbcontext efcore unit test aapl igenericrepository application service,# 🛒 Inventory Alert System — Features & API Reference | 🛒 Inventory Alert System — Features & API Reference > This document covers busin -doc,"--- -description: Audit checklist and current feature-state notes for InventoryAlert. -type: reference -status: active -version: 1.0 -tags: [audit, documentation, inventoryalert] -last_updated: 2026-04-23 ----",9,f3a6cc09197006f850ebeacdddcb3f71,doc\archive\feature_audit.md,0,331,"audit, inventoryalert, description, checklist, current, feature, state, notes",1777190302.6143162,1,unitofwork external api efcore sku database update efcore migration iproductservice stock stock price quote dbcontext commit productservice item atomicity threshold application service inventory finnhubpricesyncworker backgroundservice asnotracking periodictimer loss add-migration googl iproductrepository symbol schema change entity framework dbset msft notification data access business logic igenericrepository aapl rollback appdbcontext stock ticker savechanges market data price drop hosted service,feature_audit.md | --- description: Audit checklist and current feature-state notes for InventoryAl -doc,"# InventoryAlert Feature Audit & Consolidation Plan +### `/` — Dashboard -## current Feature set +File: `InventoryAlert.UI/src/app/page.tsx` -The system currently operates as a ""Modern Financial Inventory Ecosystem"" with the following features: +Fetches on mount: -### 1. Core Inventory & Product Management -- **Description**: CRUD operations for products (tickers), tracking their properties and inventory levels. -- **Storage**: PostgreSQL. -- **Complexity**: High (tied to multiple services). +- `GET /api/v1/watchlist` +- `GET /api/v1/market/news?category=general&page=1` +- `GET /api/v1/portfolio/positions` -### 2. Market Data Synchronization -- **Description**: Background jobs (SyncPricesJob) that fetch real-time data from Finnhub. -- **Storage**: PostgreSQL (Current prices) and DynamoDB (Price history). -- **Complexity**: High (external API dependency, background scheduling). +Actions: -### 3. Automated Alerting System -- **Description**: User-defined rules (AlertRules) triggered by price or inventory changes. -- **Workflow**: Price Sync -> SNS -> SQS -> Worker Evaluation -> Telegram. -- **Complexity**: Very High (distributed architecture via LocalStack/AWS services). +- Enqueue market news refresh: + - `POST /api/v1/events` with `eventType=inventoryalert.news.sync-requested.v1` +- Watchlist remove: + - `DELETE /api/v1/watchlist/{symbol}` -### 4. Market Intelligence (News, Earnings, Recommendations) -- **Description**: Supplemental financial data fetched from Finnhub. -- **Storage**: DynamoDB. -- **Complexity**: Medium-High (separate data path from core inventory). +Enhancement ideas: -### 5. Watchlist & Social -- **Description**: Users can ""watch"" tickers without necessarily having them in inventory. -- **Storage**: PostgreSQL. -- **Complexity**: Low. +- Add paging controls for news (or link to Market page with selected category). +- Centralize toast/confirm patterns (this page already uses `Toast` + `ConfirmDialog`). +- Consider refetch strategy (manual refresh button, or background refresh interval with backoff). -### 6. System Observability & Auditing -- **Description**: Event tracking for all major actions and structured logging to Seq. -- **Storage**: PostgreSQL (SystemEvents) and Seq. -- **Complexity**: Medium. +### `/market` — Market Pulse ---- +File: `InventoryAlert.UI/src/app/market/page.tsx` -## Suggested Removals (To ""Make the App Smaller"") +Fetches (category/page-driven): -To reduce the footprint (infrastructure and code), I suggest the following: +- `GET /api/v1/market/news?category={cat}&page={newsPage}&pageSize=10` +- `GET /api/v1/market/status` +- `GET /api/v1/market/calendar/earnings?from=…&to=…` (errors swallowed to `[]`) -### 1. 🗑️ Remove Market Intelligence (News, Earnings, Recommendations) -- **Reason**: These are secondary ""nice-to-have"" features that significantly increase the infrastructure complexity (DynamoDB dependency). -- **Impact**: Migration Complete. +Actions: -### 2. Consolidation Roadmap (Lean Profile) +- Enqueue market news refresh via `POST /api/v1/events` -| Feature | Current State | Recommendation | Actions Taken | -| :--- | :--- | :--- | :--- | -| **Watchlist Service** | 🗑️ Removed | **Deprecate** | Merged into `Product` via `IsWatchOnly` & `UserId`. | -| **Price History (Dynamo)** | 💾 Migrated | **Re-Architect** | Moved to PostgreSQL; removed DynamoDB repo. | -| **Event Messaging (SNS)** | 📡 Removed | **Streamline** | Switched to direct SQS (`IQueueService`). | -| **Market News (Dynamo)** | 📰 Retained | **Keep (AWS Practice)** | Maintained for AWS resource skills. | -| **Per-User Isolation** | ✅ Enforced | **Strict Ownership** | All endpoints now filter by `UserId`. | +Enhancement ideas: -## 3. Post-Implementation Summary -The Inventory Management System has been optimized for a **Lean** profile: -1. **Relational Core**: All critical business data (Products, History, Alerts) is now in **PostgreSQL**. -2. **Simplified Messaging**: SNS fan-out removed in favor of direct SQS polling, reducing AWS footprint. -3. **Unified Model**: Eliminated the redundant `Watchlist` entity; users now ""watch"" products in their consolidated inventory. -4. **Strict Security**: Implemented ownership checks at the repository level; users can no longer access other users' data. +- Add explicit paging UI for `newsPage` (next/prev) and show current page. +- Add a “loading/error state” component instead of `console.error`. +- Use `MarketStatusBanner` here (currently status is fetched and displayed in-page). ---- +### `/stocks` — Stock Catalog -## Recommended ""Lean"" Feature Set -1. **Unified Product/Ticker Management** (Postgres) -2. **Simplified Price Sync** (Hangfire + Finnhub) -3. **In-Process Alerting** (MediatR/Background Task) -4. **Basic Transaction History** -5. **System Event Auditing**",80,f3a6cc09197006f850ebeacdddcb3f71,doc\archive\feature_audit.md,0,332,"inventory, complexity, description, postgresql, data, system, storage, price",1777190302.6143162,10,unitofwork external api efcore sku database update efcore migration iproductservice stock stock price quote dbcontext commit productservice item atomicity threshold application service inventory finnhubpricesyncworker backgroundservice asnotracking periodictimer loss add-migration googl iproductrepository symbol schema change entity framework dbset msft notification data access business logic igenericrepository aapl rollback appdbcontext stock ticker savechanges market data price drop hosted service,# InventoryAlert Feature Audit & Consolidation Plan | InventoryAlert Feature Audit & Consolidation Plan current Feature set The syste -doc,"--- -description: Manual QA Testing Guide for the Inventory Alert System — step-by-step test cases and areas flagged for human review. -type: qa -status: active -version: 1.0 -tags: [testing, qa, manual, review, checklist] -last_updated: 2026-04-05 ----",9,aeb9eabc291af642bea5a05391a0e7a3,doc\archive\MANUAL_TESTING.md,0,333,"manual, testing, step, review, description, guide, inventory, alert",1775670503.9172294,1,httpput productservice postgres backgroundservice application service httpget stock price loss httppost dockerfile arrange act assert notification unit test iproductservice stock ticker aapl postgresql productscontroller business logic entity framework msft container dbcontext hosted service inventory sku threshold iactionresult googl efcore external api market data price drop periodictimer fluentassertions finnhubpricesyncworker appdbcontext compose stock asnotracking quote item xunit symbol,MANUAL_TESTING.md | --- description: Manual QA Testing Guide for the Inventory Alert System — step-b -doc,"# 🧪 Manual Testing & Review Guide +File: `InventoryAlert.UI/src/app/stocks/page.tsx` -> **How to use this document:** -> - ✅ = Expected pass behavior -> - ❌ = Expected rejection / error behavior -> - 🔍 = **Needs human review** — business logic decision, edge case, or unvalidated behavior +Fetches: -**Base URL (Docker):** `http://localhost:5000` -**Start environment:** `docker-compose up --build` from `InventoryManagementSystem/` +- browse: `GET /api/v1/stocks?page={page}&pageSize=20` +- search: `GET /api/v1/stocks/search?q={query}` ---- +Enhancement ideas: -## 🚀 Pre-Flight: Start & Health Check +- Add page size selector and show total results if API returns it. +- Add “clear search” UX and keyboard navigation to results (GlobalSearch already has it). -| # | Step | Expected | -|---|---|---| -| 1 | Run `docker-compose up --build` | All 5 containers start without error | -| 2 | Check `moto-init` logs | `SQS queue created`, `DynamoDB table created` messages visible | -| 3 | `GET http://localhost:5000/swagger` | Swagger UI loads with all endpoints | -| 4 | Check `logs/inventoryalert.log` exists | Serilog has created the log file | +### `/stocks/[symbol]` — Stock Detail -> 🔍 **REVIEW:** There is no `/health` endpoint defined. If the `api` or `worker` container crashes silently, there is no heartbeat to detect it. Consider adding `app.MapHealthChecks(""/health"")`. +File: `InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx` ---- +Eager fetches on symbol change: -## 🔐 Section 1: Authentication +- `GET /api/v1/stocks/{symbol}/quote` +- `GET /api/v1/stocks/{symbol}/profile` +- `GET /api/v1/stocks/{symbol}/financials` (errors swallowed to `null`) +- `GET /api/v1/watchlist` (to determine watchlist status; client-side check) -### TC-AUTH-01 — Happy Path Login -```http -POST /api/auth/login -{ ""username"": ""admin"", ""password"": ""admin123"" } -``` -- ✅ `200 OK` with `{ ""token"": """" }` -- Copy the token — used in all subsequent `[Authorize]` calls +Lazy per tab: -### TC-AUTH-02 — Wrong Password -```http -POST /api/auth/login -{ ""username"": ""admin"", ""password"": ""wrong"" } -``` -- ✅ `401 Unauthorized` with message `""Invalid credentials.""` +- Earnings: `GET /api/v1/stocks/{symbol}/earnings` (with loaded/loading/error state) +- Recommendations: `GET /api/v1/stocks/{symbol}/recommendation` +- Insiders: `GET /api/v1/stocks/{symbol}/insiders` +- News: `GET /api/v1/stocks/{symbol}/news?page={newsPage}&pageSize=10` +- Peers: `GET /api/v1/stocks/{symbol}/peers` -### TC-AUTH-03 — Call Protected Endpoint Without Token -```http -GET /api/products -(no Authorization header) -``` -- ✅ `401 Unauthorized` +Actions: -### TC-AUTH-04 — Call Protected Endpoint With Expired Token -- Wait for token to expire (2 hours), then call `GET /api/products` -- ✅ `401 Unauthorized` +- Watchlist toggle: + - `POST /api/v1/watchlist/{symbol}` or `DELETE /api/v1/watchlist/{symbol}` +- Price alert modal: + - `POST /api/v1/alertrules` (via `PriceAlertModal`) -> 🔍 **REVIEW:** Credentials (`admin` / `admin123`) are the hardcoded fallback in `AuthController`. In Docker, they should come from `appsettings.Docker.json → Auth:Username / Auth:Password`. Verify these are overridden in the Docker config; otherwise the fallback is always active, even in production images. +Enhancement ideas: ---- +- Add visible paging controls for the News tab (`newsPage` exists in state). +- Replace `alert()` error UX with `Toast`. +- Avoid fetching full watchlist list just to check one symbol (add a backend endpoint `GET /watchlist/{symbol}/exists` or cache watchlist in a provider). +- Add per-tab skeletons and per-tab error UI (only earnings has a dedicated error state today). -## 📦 Section 2: Product CRUD +### `/portfolio` — Portfolio -Use `Authorization: Bearer ` for all requests in this section. +File: `InventoryAlert.UI/src/app/portfolio/page.tsx` -### TC-PROD-01 — Create Product (Valid) -```http -POST /api/products -{ - ""name"": ""Apple iPhone 15"", - ""tickerSymbol"": ""AAPL"", - ""stockCount"": 100, - ""originPrice"": 950.00, - ""currentPrice"": 920.00, - ""priceAlertThreshold"": 0.2, - ""stockAlertThreshold"": 10 -} -``` -- ✅ `201 Created` with response body including auto-generated `id` -- ✅ Response includes `Location` header pointing to `GET /api/products/{id}` -- Note the returned `id` for subsequent tests +Fetches: -### TC-PROD-02 — Create Product (Validation Failures) +- `GET /api/v1/portfolio/positions` (expects `PagedResult`, but does not pass page params) -| Sub-case | Payload Change | Expected | -|---|---|---| -| Empty name | `""name"": """"` | ❌ `400` — `""Name is required.""` | -| Name too long | `""name"": ""A"" * 257` | ❌ `400` — `""Name must not exceed 256 characters.""` | -| Lowercase ticker | `""tickerSymbol"": ""aapl""` | ❌ `400` — `""TickerSymbol must be 1–16 uppercase letters""` | -| Ticker with numbers | `""tickerSymbol"": ""AAP1""` | ❌ `400` — regex rejects non-alpha characters | -| `originPrice: 0` | `""originPrice"": 0` | ❌ `400` — `""OriginPrice must be greater than 0.""` | -| `originPrice: -1` | `""originPrice"": -1` | ❌ `400` | -| `currentPrice: -1` | `""currentPrice"": -1` | ❌ `400` — `""CurrentPrice must be 0 or greater.""` | -| `stockCount: -1` | `""stockCount"": -1` | ❌ `400` | -| `priceAlertThreshold: 1.1` | `""priceAlertThreshold"": 1.1` | ❌ `400` — `""must be between 0.0 and 1.0""` | -| `priceAlertThreshold: -0.1` | `""priceAlertThreshold"": -0.1` | ❌ `400` | +Actions: -> 🔍 **REVIEW:** `tickerSymbol` is declared as `string?` (nullable) in `ProductRequest.cs` but the validator treats it as required. Confirm the swagger UI does not allow submitting without it. Check if `null` body field passes validation. +- Delete position: + - `DELETE /api/v1/portfolio/positions/{symbol}` +- Create/adjust position and trades via `TradeModal`: + - `POST /api/v1/portfolio/positions` + - `POST /api/v1/portfolio/{symbol}/trades` -### TC-PROD-03 — Get All Products (Pagination) -```http -GET /api/products?pageNumber=1&pageSize=5 -``` -- ✅ `200 OK` with `PagedResult` shape: `{ items: [...], totalItems, pageNumber, pageSize }` -- ✅ Max page size is capped at `50` — test `?pageSize=999` returns only 50 items +Enhancement ideas: -### TC-PROD-04 — Get Product By ID (Cache Test) -```http -GET /api/products/{id} ← first call: DB hit -GET /api/products/{id} ← second call within 10 min: cache hit -``` -- ✅ Both return `200 OK` with identical body -- To verify cache: Add a DB breakpoint or Serilog trace showing cache miss/hit +- Implement paging UI if portfolios can grow (API already returns paged result). +- Provide optimistic UI updates for trade/position changes. -> 🔍 **REVIEW:** Cache TTL is hardcoded as `TimeSpan.FromMinutes(10)` in `ProductService.cs`. There is no configuration key for this. Consider externalizing it. +### `/watchlist` — Watchlist -### TC-PROD-05 — Get Product By ID (Not Found) -```http -GET /api/products/99999 -``` -- ✅ `404 Not Found` +File: `InventoryAlert.UI/src/app/watchlist/page.tsx` -### TC-PROD-06 — Update Product (Full Overwrite) -```http -PUT /api/products/{id} -{ - ""name"": ""Apple iPhone 15 Pro"", - ""tickerSymbol"": ""AAPL"", - ""stockCount"": 80, - ""originPrice"": 1050.00, - ""currentPrice"": 1000.00, - ""priceAlertThreshold"": 0.15, - ""stockAlertThreshold"": 5 -} -``` -- ✅ `200 OK` with all fields updated -- ✅ Verify a subsequent `GET /api/products/{id}` returns new values (cache invalidated) +Fetches: -### TC-PROD-07 — Update Non-Existent Product -```http -PUT /api/products/99999 -{ ... valid body ... } -``` -- ✅ `404 Not Found` +- `GET /api/v1/watchlist` -> 🔍 **REVIEW:** The update currently throws `KeyNotFoundException` if not found, which is caught by `ExceptionHandlingMiddleware` and converted to `404`. But the middleware maps `KeyNotFoundException` → `404` only if explicitly handled. Verify this mapping is set up in `ExceptionHandlingMiddleware.cs`. +Actions: -### TC-PROD-08 — Delete Product -```http -DELETE /api/products/{id} -``` -- ✅ `204 No Content` -- ✅ Follow-up `GET /api/products/{id}` returns `404` +- Add symbol: + - `POST /api/v1/watchlist/{symbol}` (via `AddSymbolModal`) +- Remove symbol: + - `DELETE /api/v1/watchlist/{symbol}` -### TC-PROD-09 — Delete Non-Existent Product -```http -DELETE /api/products/99999 -``` -- ✅ `404 Not Found` +Enhancement ideas: ---- +- Add sorting (price, change %, alpha). +- Add “bulk remove” mode for large lists (with ConfirmDialog). -## 📉 Section 3: Stock Count PATCH +### `/alerts` — Alert Rules Manager -### TC-STOCK-01 — Valid Patch -```http -PATCH /api/products/{id}/stock?stockCount=50 -``` -- ✅ `200 OK` — returns full `ProductResponse` with `stockCount: 50` +File: `InventoryAlert.UI/src/app/alerts/page.tsx` -### TC-STOCK-02 — Set Stock to Zero -```http -PATCH /api/products/{id}/stock?stockCount=0 -``` -- ✅ `200 OK` — `stockCount: 0` is valid (product exists but out of stock) +Fetches: -### TC-STOCK-03 — Product Not Found -```http -PATCH /api/products/99999/stock?stockCount=10 -``` -- ✅ `404 Not Found` +- `GET /api/v1/alertrules` -### TC-STOCK-04 — Negative Stock Count -```http -PATCH /api/products/{id}/stock?stockCount=-5 -``` -- 🔍 **REVIEW:** There is **no validator** for the `stockCount` query parameter in `UpdateStockCount`. The code directly assigns `existing.StockCount = stockCount;` — a value of `-5` will be persisted. Consider adding a guard: `if (stockCount < 0) return BadRequest(...)`. +Actions: ---- +- Create: + - `POST /api/v1/alertrules` +- Update: + - `PUT /api/v1/alertrules/{id}` +- Toggle: + - `PATCH /api/v1/alertrules/{id}/toggle` +- Delete: + - `DELETE /api/v1/alertrules/{id}` (currently uses `confirm(...)`) -## 📈 Section 4: Finnhub Price Sync +Enhancement ideas: -### TC-SYNC-01 — Manual Trigger -```http -POST /api/products/sync-price -``` -- ✅ `204 No Content` (runs synchronously, returns after completion) -- ✅ Check that `currentPrice` of products with valid tickers has been updated +- Replace native `confirm()` and `alert()` with `ConfirmDialog` + `Toast` for consistent UX. +- Add filtering tabs: Active / Inactive / TriggerOnce / Condition type. +- Add inline validation errors (target value semantics differ by condition). -> 🔍 **REVIEW:** The Docker `appsettings.Docker.json` has the Finnhub API key hardcoded: `""ApiKey"": ""d77d58hr01qp6afl79qgd77d58hr01qp6afl79r0""`. This is a **real API key committed to version control**. Even though `appsettings.Docker.json` may be gitignored, confirm with `git status` and `git log --all -- appsettings.Docker.json`. The key should be moved to a Docker secret or environment variable. +### `/notifications` — Notifications -### TC-SYNC-02 — Invalid Ticker Symbol -- Create a product with `tickerSymbol: ""XXXINVALID""` -- Trigger `POST /api/products/sync-price` -- ✅ `204 No Content` — the invalid ticker is **skipped** (not an error) -- ✅ Log file contains: `[ProductService] Null or zero price returned for XXXINVALID. Skipping.` +File: `InventoryAlert.UI/src/app/notifications/page.tsx` -### TC-SYNC-03 — Scheduled Auto-Sync -- Configured in `appsettings.Docker.json → MinuteSyncCurrentPrice: 10` -- ✅ After 10 minutes, `currentPrice` updates automatically without manual trigger -- 🔍 **REVIEW:** Confirm the `MinuteSyncCurrentPrice` setting is actually read and applied to the Hangfire job cron expression in the Worker's `Program.cs`. +Fetches: ---- +- `GET /api/v1/notifications` (API returns paged result; UI uses `data.items` but does not implement paging controls) -## 🚨 Section 5: Price Loss Alerts +Actions: -### Setup for this section: -Create a product with `originPrice: 1000`, `currentPrice: 700`, `priceAlertThreshold: 0.2`. -- Drop% = (700-1000)/1000 = -0.3 → 30% loss → **exceeds** 20% threshold → should alert. +- Mark read: + - `PATCH /api/v1/notifications/{id}/read` +- Mark all read: + - `PATCH /api/v1/notifications/read-all` +- Dismiss: + - `DELETE /api/v1/notifications/{id}` -### TC-ALERT-01 — Product Triggering Alert -```http -GET /api/products/price-alerts -``` -- ✅ `200 OK` — response array includes the product above -- ✅ `priceChangePercent` ≈ `-0.3000` -- ✅ `priceDiff` = `300.00` +Enhancement ideas: -### TC-ALERT-02 — Product Below Threshold (No Alert) -- Create product with `originPrice: 1000`, `currentPrice: 850`, `priceAlertThreshold: 0.2` -- Drop% = 15% < 20% threshold -- ✅ This product does **not** appear in the alert response +- Add paging controls or infinite scroll using `page` + `pageSize` query params. +- Add filters: only unread, by symbol, by date range. +- Improve badge consistency: avoid decrementing unread count below 0 (currently guarded) and ensure unread count matches server state on refresh. + +### `/admin/health` — System Integrity + +File: `InventoryAlert.UI/src/app/admin/health/page.tsx` -### TC-ALERT-03 — Cooldown Gate (60-Minute Spam Prevention) -- Trigger `GET /api/products/price-alerts` twice in 60 minutes for the same product -- Both should return the product in the list (the endpoint only **reads**, it doesn't update `LastAlertSentAt`) -- 🔍 **REVIEW:** `LastAlertSentAt` is **never written** by `GetPriceLossAlertsAsync`. The cooldown check reads `LastAlertSentAt` but nothing in the codebase sets it. This means the cooldown gate is **permanently bypassed** — it will always pass the `if (product.LastAlertSentAt.HasValue...)` check because `HasValue` is always `false`. Needs implementation. +Fetches: -### TC-ALERT-04 — Zero Price Edge Case -- Set `currentPrice: 0` or `originPrice: 0` -- ✅ Product is **skipped** — no alert produced (guarded by `if (product?.CurrentPrice is 0 || product?.OriginPrice is 0) continue`) +- `GET /health` on interval (30s) ---- +Enhancement ideas: -## 📨 Section 6: Event Publishing +- Add explicit error UI (right now it only logs to console). +- Provide link-out buttons to Seq and Hangfire dashboards (if running locally). +- Make polling interval configurable (or pause when tab hidden). -### TC-EVENT-01 — Generic Event Publish -```http -POST /api/events -{ - ""eventType"": ""inventoryalert.pricing.price-drop.v1"", - ""payload"": { ""productId"": 1, ""symbol"": ""AAPL"", ""dropPercent"": 0.25 } -} -``` -- ✅ `202 Accepted` -- ✅ Record appears in `GET /api/events/logs/inventoryalert.pricing.price-drop.v1` +### `/login` and `/register` -### TC-EVENT-02 — Missing EventType -```http -POST /api/events -{ ""eventType"": """", ""payload"": {} } -``` -- ✅ `400 Bad Request` — `""EventType is required.""` +Files: -### TC-EVENT-03 — Manual Market Alert -```http -POST /api/events/market-alert -{ - ""productId"": 1, - ""symbol"": ""AAPL"", - ""originPrice"": 950.00, - ""currentPrice"": 700.00, - ""dropPercent"": 0.263 -} -``` -- ✅ `202 Accepted` -- ✅ Worker logs `🚨 PRICE DROP ALERT` in container output +- `InventoryAlert.UI/src/app/(auth)/login/page.tsx` +- `InventoryAlert.UI/src/app/(auth)/register/page.tsx` -### TC-EVENT-04 — News Alert -```http -POST /api/events/news-alert -{ - ""symbol"": ""TSLA"", - ""headline"": ""Tesla recalls 500,000 vehicles"", - ""source"": ""Reuters"", - ""url"": ""https://reuters.com/article/example"", - ""publishedAt"": ""2026-04-05T06:00:00Z"" -} -``` -- ✅ `202 Accepted` -- ✅ Worker `NewsHandler` persists `NewsRecord` to PostgreSQL +Notes: -### TC-EVENT-05 — List Supported Event Types -```http -GET /api/events/types -``` -- ✅ Returns all 5 event type strings: - ```json - [ - ""inventoryalert.pricing.price-drop.v1"", - ""inventoryalert.inventory.stock-low.v1"", - ""inventoryalert.fundamentals.earnings.v1"", - ""inventoryalert.fundamentals.insider-sell.v1"", - ""inventoryalert.news.headline.v1"" - ] - ``` +- Login forces `window.location.href = '/'` after storing token, to sync all components. +- Register uses router push to `/login?registered=true`. -### TC-EVENT-06 — Query Event Logs -```http -GET /api/events/logs/inventoryalert.pricing.price-drop.v1?limit=5 -``` -- ✅ Returns up to 5 DynamoDB log entries for that event type +Enhancement ideas: -> 🔍 **REVIEW:** Sending an **unknown event type** to `POST /api/events` (e.g. `""eventType"": ""foo.bar""`) is accepted and dispatched to SNS — no validation against `EventTypes.All` occurs at the controller level. The Worker's `UnknownEventHandler` will discard it, but it still pollutes the audit log. Consider adding `if (!EventTypes.IsKnown(request.EventType)) return BadRequest(...)`. +- Standardize visual design between login and register (styles differ significantly). +- Add password requirement hints aligned with API validation. --- -## 🔄 Section 7: Worker SQS Consumer (End-to-End) +## 3) Components Inventory -### TC-WORKER-01 — Full Pipeline Smoke Test -1. Publish an event via `POST /api/events/market-alert` -2. Watch Worker Docker logs for: `🚨 PRICE DROP ALERT Symbol: AAPL` -3. ✅ Event flows: API → SNS (Moto) → SQS → PollSqsJob → PriceAlertHandler → log +All components are under `InventoryAlert.UI/src/components/*`. -### TC-WORKER-02 — Earnings Event Persistence -1. Publish: -```http -POST /api/events -{ - ""eventType"": ""inventoryalert.fundamentals.earnings.v1"", - ""payload"": { - ""symbol"": ""AAPL"", - ""period"": ""Q1 2026"", - ""actualEPS"": 2.18, - ""estimatedEPS"": 2.10, - ""surprisePercent"": 3.8 - } -} -``` -2. ✅ Worker `EarningsHandler` persists `EarningsRecord` to PostgreSQL -3. ✅ Verify via direct DB: `SELECT * FROM ""EarningsRecords"";` +### Global navigation + search -### TC-WORKER-03 — DLQ Escalation -- Temporarily break the Worker handler (e.g. comment out DB save, throw exception) -- Publish an event -- After 3 retries ✅ message appears in `inventory-event-dlq` -- 🔍 **REVIEW:** There is no monitoring or alerting on DLQ depth. If messages pile up in the DLQ, no one is notified. Consider adding a CloudWatch alarm (or Moto-equivalent) for `ApproximateNumberOfMessagesNotVisible > 0`. +- `Navbar.tsx` — navigation links, sticky header, mobile menu +- `NavbarWrapper.tsx` — holds global search open state + keyboard shortcut Ctrl/Cmd+K +- `UserNav.tsx` — theme toggle, login/logout, notification bell, user avatar placeholder +- `GlobalSearch.tsx` — modal search for symbols; keyboard nav; uses `/api/v1/stocks/search` ---- +Enhancement ideas: -## 📊 Section 8: Bulk Insert +- Add focus trap in `GlobalSearch` (escape closes, but focus management can be improved). +- Standardize z-index tokens (`GlobalSearch` uses `z-[200]`, other modals vary). -### TC-BULK-01 — Valid Bulk Insert -```http -POST /api/products/bulk -[ - { ""name"": ""Tesla Part A"", ""tickerSymbol"": ""TSLA"", ""stockCount"": 50, ""originPrice"": 200.00, ""currentPrice"": 190.00, ""priceAlertThreshold"": 0.1, ""stockAlertThreshold"": 5 }, - { ""name"": ""Microsoft Mouse"", ""tickerSymbol"": ""MSFT"", ""stockCount"": 200, ""originPrice"": 30.00, ""currentPrice"": 28.00, ""priceAlertThreshold"": 0.15, ""stockAlertThreshold"": 20 } -] -``` -- ✅ `204 No Content` -- ✅ Follow-up `GET /api/products` shows new items +### Notifications (client state) -### TC-BULK-02 — Bulk Insert with One Invalid Item -```http -POST /api/products/bulk -[ - { ""name"": ""Valid Product"", ""tickerSymbol"": ""GOOG"", ... }, - { ""name"": """", ""tickerSymbol"": ""AAPL"", ... } ← invalid: empty name -] -``` -- 🔍 **REVIEW:** FluentValidation rules apply per-item in a collection via `RuleForEach`. Verify whether `BulkInsertProductsAsync` triggers FluentValidation or bypasses it (the validation filter operates at the Controller level on the outer `IEnumerable`, not per-item). If one item is invalid, is the whole batch rejected or does it partially insert? +- `NotificationProvider.tsx` — SignalR connect + unread count bootstrap +- `NotificationBell.tsx` — shows unread badge; links to `/notifications` -### TC-BULK-03 — Empty Bulk Insert -```http -POST /api/products/bulk -[] -``` -- 🔍 **REVIEW:** Empty array → `AddRangeAsync([])` → likely a no-op. Should return `204` or `400`? Currently no guard for empty list. +Enhancement ideas: ---- +- Reduce token polling (`setInterval(..., 2000)`); prefer a single “auth store” source of truth. +- Gate `console.log` noise behind a debug flag. -## 🔍 Summary: All Items Needing Human Review +### Modals + dialogs -| ID | Location | Issue | Priority | -|---|---|---|---| -| A | `AuthController.cs:26-27` | `admin`/`admin123` fallback always active if config missing | 🔴 High | -| B | `appsettings.Docker.json:7` | Real Finnhub API key possibly committed in git history | 🔴 High | -| C | `ProductsController.cs` — `UpdateStockCount` | No validation on negative `stockCount` query param | 🟡 Medium | -| D | `ProductService.cs` — `GetPriceLossAlertsAsync` | `LastAlertSentAt` cooldown is never written — gate always bypassed | 🟡 Medium | -| E | `EventsController.cs` — `PublishEvent` | Unknown event types accepted without validation against `EventTypes.All` | 🟡 Medium | -| F | `ProductService.cs:55` | Cache TTL (10 min) is hardcoded — no config key | 🟢 Low | -| G | No health endpoint | No `/health` or `/ready` probe for Docker orchestration | 🟢 Low | -| H | `ProductRequest.cs:7` | `TickerSymbol` is `string?` (nullable) but validator treats it as required | 🟢 Low | -| I | `TC-BULK-02` / `TC-BULK-03` | Validation behavior for bulk insert edge cases unverified | 🟢 Low | -| J | DLQ monitoring | No alerting on dead-letter queue depth | 🟢 Low | -| K | `MinuteSyncCurrentPrice` | Verify setting is actually wired into Hangfire cron in Worker `Program.cs` | 🟢 Low |",402,aeb9eabc291af642bea5a05391a0e7a3,doc\archive\MANUAL_TESTING.md,0,334,"product, event, review, docker, alert, worker, section, bulk",1775670503.9172294,10,httpput productservice postgres backgroundservice application service httpget stock price loss httppost dockerfile arrange act assert notification unit test iproductservice stock ticker aapl postgresql productscontroller business logic entity framework msft container dbcontext hosted service inventory sku threshold iactionresult googl efcore external api market data price drop periodictimer fluentassertions finnhubpricesyncworker appdbcontext compose stock asnotracking quote item xunit symbol,# 🧪 Manual Testing & Review Guide | 🧪 Manual Testing & Review Guide > How to use this document: > - ✅ = Expected pas -doc,"--- -description: System modernization plan for UI, logging, and shared project audit -type: plan -status: completed -version: 1.1 -tags: [modernization, ui, logging, ddd] -last_updated: 2026-04-05 ----",9,8b5729fb8041d9f565881dc7ccd083bd,doc\archive\MODERNIZATION_PLAN.md,0,335,"modernization, plan, logging, description, system, shared, project, audit",1775670503.9180853,1,backgroundservice finnhubpricesyncworker loss price drop business logic domain entity infrastructure domain driven design iproductservice hosted service productservice application service periodictimer threshold notification application layer,"MODERNIZATION_PLAN.md | --- description: System modernization plan for UI, logging, and shared project a" -doc,"# 🏛️ System Modernization & UI Plan +- `AddSymbolModal.tsx` +- `PriceAlertModal.tsx` +- `TradeModal.tsx` +- `ConfirmDialog.tsx` -> **Status: ✅ COMPLETE** — Archived on 2026-04-05. -> All phases implemented. See `ROADMAP.md` for remaining open tasks (P4+). +Enhancement ideas: ---- +- Create a shared `ModalShell` component (backdrop, panel, title row, close button, z-index, escape-to-close, focus trap). +- Fix duplicated input block in `TradeModal.tsx` (quantity field appears twice when opening a new position). -## Summary of Delivered Work +### Feedback -| Phase | Component | Status | -| :--- | :--- | :--- | -| Phase 1 | Serilog bootstrapped in `Worker/Program.cs` | ✅ Done | -| Phase 1 | `ILogger` as injection interface across all services | ✅ Done | -| Phase 1 | `CorrelationIdMiddleware` — stamps every request + log | ✅ Done | -| Phase 1 | `ExceptionHandlingMiddleware` — full RFC-7807 compliance | ✅ Done | -| Phase 1 | `HangfireJobLoggingFilter` — global Worker job error auditing | ✅ Done | -| Phase 2 | `Contracts/Constants/AlertConstants.cs` — centralized constants | ✅ Done | -| Phase 2 | All entities and DTOs verified in `InventoryAlert.Contracts` | ✅ Done | -| Phase 3 | `wwwroot/index.html` — SPA with Sidebar + 4 views | ✅ Done | -| Phase 3 | `wwwroot/css/dashboard.css` — Dark Glassmorphism theme | ✅ Done | -| Phase 4 | `wwwroot/js/dashboard.js` — Fetch polling, live search, sync | ✅ Done | +- `Toast.tsx` — simple toast with auto-dismiss ---- +Enhancement ideas: -## Files Created / Modified +- Centralize toast via a provider so pages don’t duplicate toast state wiring. -```text -InventoryAlert.Api/ -├── Program.cs ← CorrelationId + UseStaticFiles registered -├── Web/Middleware/ -│ ├── ExceptionHandlingMiddleware.cs ← RFC-7807: instance + semantic type URI -│ └── CorrelationIdMiddleware.cs ← NEW: X-Correlation-Id stamping -└── wwwroot/ ← NEW: Static dashboard - ├── index.html - ├── css/dashboard.css - └── js/dashboard.js +### Market status -InventoryAlert.Worker/ -├── Program.cs ← Serilog bootstrap (File + Console sinks) -└── Filters/HangfireJobLoggingFilter.cs ← NEW: Global Hangfire job error filter +- `MarketStatusBanner.tsx` — polls `/api/v1/market/status` every 60s and displays US market open/closed badge -InventoryAlert.Contracts/ -└── Constants/AlertConstants.cs ← NEW: EventTypes, CacheKeys, SqsHeaders -``` +Enhancement ideas: -> **Next Action:** See `ROADMAP.md` P4+ for performance, security, and CI/CD tasks.",55,8b5729fb8041d9f565881dc7ccd083bd,doc\archive\MODERNIZATION_PLAN.md,0,336,"phase, done, wwwroot, status, roadmap, tasks, worker, contracts",1775670503.9180853,10,backgroundservice finnhubpricesyncworker loss price drop business logic domain entity infrastructure domain driven design iproductservice hosted service productservice application service periodictimer threshold notification application layer,# 🏛️ System Modernization & UI Plan | 🏛️ System Modernization & UI Plan > Status: ✅ COMPLETE — Archived on 2026-04-05 -doc,"--- -description: Review of alert rule + notification business flows (API/Worker/UI) and recommendations to enhance reliability, consistency, and UX. -type: reference -status: draft -version: 1.0 -tags: [business-flow, alerts, notifications, signalr, worker, api, ui, inventoryalert] -last_updated: 2026-04-26 ----",9,09c9d699a7ab47f836e5f6b50eeca0b4,doc\archive\NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md,0,337,"business, worker, description, review, alert, rule, notification, flows",1777190302.6049023,1,atomicity commit dbcontext application service arrange act assert hosted service finnhubpricesyncworker dbset productservice threshold igenericrepository productscontroller xunit httpput msft postgres business logic container iactionresult backgroundservice price drop compose loss unit test googl periodictimer appdbcontext savechanges dockerfile httppost aapl data access fluentassertions httpget entity framework rollback symbol notification iproductrepository postgresql asnotracking iproductservice efcore stock ticker unitofwork,NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md | --- description: Review of alert rule + notification business flows (API/Worker/ -doc,"# Alert Rules & Notifications — Business Flow Review + Enhancements +- Reuse this in `Navbar` or `Market` page for consistent “market open/closed” display. -Scope: end-to-end “alert rule → evaluation → notification → real-time delivery → user acknowledgement” across: +--- -- API: `InventoryManagementSystem/InventoryAlert.Api` -- Worker: `InventoryManagementSystem/InventoryAlert.Worker` -- Infrastructure: SignalR hub + notifier -- UI: `InventoryAlert.UI` (SignalR + unread count) +## 4) Cross-Cutting Recommendations (High Impact) -Documentation-only (no code changes here). +### 4.1 Paging standardization (core request) ---- +Pages that should implement paging because the API already supports it: -## 1) Domain Model (Current) +- Notifications (`/notifications`) +- Portfolio positions (`/portfolio`) if position count can grow +- News streams (Market + Stock detail) -### 1.1 AlertRule +Suggested common pagination component: -Entity: `InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs` +- `Pagination` with `page`, `pageSize`, `totalPages`, `onPageChange` +- optionally `InfiniteScroll` mode for notifications/news -- Key fields: - - `UserId`, `TickerSymbol`, `Condition`, `TargetValue` - - `IsActive`, `TriggerOnce`, `LastTriggeredAt` +### 4.2 Standardize confirm + error UX -Conditions currently include: +Currently: -- `PriceAbove`, `PriceBelow`, `PriceTargetReached` -- `PercentDropFromCost` -- `LowHoldingsCount` +- some pages use `ConfirmDialog` + `Toast` +- some use `alert()` / `confirm()` -### 1.2 Notification +Recommendation: -Entity: `InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/Notification.cs` +- never use native `alert/confirm` +- one consistent pattern: + - optimistic UI update + Toast + - destructive action → ConfirmDialog -- Key fields: - - `UserId` - - `AlertRuleId?` (nullable) - - `TickerSymbol?` - - `Message` - - `IsRead` - - `CreatedAt` +### 4.3 Align UI error parsing with backend `ErrorResponse` -DTO returned to clients: +Backend uses: -- `InventoryManagementSystem/InventoryAlert.Domain/DTOs/NotificationDTOs.cs` → `NotificationResponse` +- `ErrorResponse { errors: [{ code, message, property }], errorId }` ---- +Recommendation: -## 2) Current API Flow (Alert Rules + Notifications) +- create a single `getErrorMessage(err)` helper that: + - prefers `ErrorResponse.errors[0].message` + - falls back to generic message + - optionally surfaces `errorId` and `X-Correlation-Id` for support -### 2.1 AlertRule CRUD +### 4.4 Reduce repeated Tailwind blobs -Controller: `InventoryManagementSystem/InventoryAlert.Api/Controllers/AlertRulesController.cs` +Recommendation: -- `GET /api/v1/alertrules` → list current user’s rules -- `POST /api/v1/alertrules` → create -- `PUT /api/v1/alertrules/{id}` → full replace -- `PATCH /api/v1/alertrules/{id}/toggle` → enable/disable -- `DELETE /api/v1/alertrules/{id}` → delete +- Introduce a small “UI kit” layer: + - `PageHeader`, `Card`, `Button`, `Input`, `EmptyState`, `ErrorState`, `Skeleton` +- Refactor pages to use these, improving consistency and speed of iteration. -Service: `InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs` +### 4.5 Rerender and state hygiene -Observed business behavior: +Recommendation: -- Normalizes symbol on create (`Trim().ToUpperInvariant()`). -- Performs “symbol discovery” side-effect by calling `IStockDataService.GetProfileAsync` before persisting the rule. -- Uses `KeyNotFoundException` for missing rule (maps to 404 in middleware). +- Avoid long-lived intervals that rerun while tab is hidden: + - for health checks and token sync, pause when `document.hidden` +- Consider `AbortController` for page fetches to avoid setting state after unmount/navigation.",394,5080f1111fc0c2f3f9042a921808473d,doc\archive\UI_COMPONENTS_AND_PAGES_AUDIT.md,0,365,"page, inventoryalert, symbol, enhancement, watchlist, market, ideas, stocks",1779814416.3928213,10,entity framework efcore price drop asnotracking httppost iactionresult dbcontext appdbcontext httpget productscontroller httpput threshold notification loss,# InventoryAlert.UI — Components & Pages Audit + Enhancement Suggestions | InventoryAlert.UI — Components & Pages Audit + Enhancement Suggestions This docu +doc,"--- +description: UI tech review, setup, folder structure, rendering/rerender flow, and Docker approach (documentation only). +type: reference +status: draft +version: 1.1 +tags: [ui, nextjs, react, tailwind, docker, setup, architecture, inventoryalert] +last_updated: 2026-04-26 +---",9,549c402f173a671723294d82592b3b7f,doc\archive\UI_TECH_SETUP_AND_FLOW.md,0,366,"setup, docker, description, tech, review, folder, structure, rendering",1779814416.3928213,1,postgresql stock business logic postgres iproductservice item entity framework loss fluentassertions iproductrepository application service dbcontext compose xunit productservice sku container efcore notification data access dockerfile price drop unit test appdbcontext threshold arrange act assert igenericrepository dbset inventory asnotracking,"UI_TECH_SETUP_AND_FLOW.md | --- description: UI tech review, setup, folder structure, rendering/rerender flo" +doc,"# InventoryAlert.UI — Tech, Setup, Structure, and Rendering Flow -### 2.2 Notification query + acknowledgement +This is a **documentation-only** review of the `InventoryAlert.UI` project: -Controller: `InventoryManagementSystem/InventoryAlert.Api/Controllers/NotificationsController.cs` +- current tech stack and scripts, +- file/folder structure, +- how pages render and re-render, +- layout/provider flow, +- Docker approach for running UI + Wiki (recommendations; not implemented here), +- UX/UI enhancement ideas (recommendations; not implemented here). -- `GET /api/v1/notifications` (paged, supports `onlyUnread`) -- `GET /api/v1/notifications/unread-count` -- `PATCH /api/v1/notifications/{id}/read` → mark read -- `PATCH /api/v1/notifications/read-all` → mark all read -- `DELETE /api/v1/notifications/{id}` → dismiss (delete) -- `POST /api/v1/notifications/test-signalr` → pushes a test notification via SignalR (admin/dev utility) +Repository root: `InventoryAlert.UI/` -Repository: `InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/NotificationRepository.cs` +Companion doc (deeper inventory + per-page recommendations): -- Uses `ExecuteUpdateAsync` for `MarkAllReadAsync` (efficient). +- `doc/UI_COMPONENTS_AND_PAGES_AUDIT.md` --- -## 3) Current Delivery Flow (Worker → SignalR → UI) - -### 3.1 SignalR hub and delivery mechanism +## 1) Tech Stack (Observed) -- Hub: `InventoryManagementSystem/InventoryAlert.Infrastructure/Hubs/NotificationHub.cs` - - `[Authorize]` - - Logs connect/disconnect using `Context.UserIdentifier` -- Hub route constant: - - `InventoryManagementSystem/InventoryAlert.Domain/Interfaces/INotificationHub.cs` → `SignalRConstants.NotificationHubRoute = ""/hubs/notifications""` -- API hosts hub: - - `InventoryManagementSystem/InventoryAlert.Api/Program.cs` → `app.MapHub(""/hubs/notifications"")` -- Notifier: - - `InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/NotificationAlertNotifier.cs` - - Calls `Clients.User(notification.UserId.ToString()).ReceiveNotification(dto)` +From `InventoryAlert.UI/package.json`: -### 3.2 UI consumption +- **Next.js** `15.1.4` (App Router enabled — `src/app/*`) +- **React** `19.0.0` +- **Tailwind CSS** `v4` (imported via CSS: `@import ""tailwindcss"";`) +- **SignalR client**: `@microsoft/signalr` `^10.0.0` +- **Testing**: `vitest` + Testing Library + JSDOM +- **TypeScript** `^5` +- `next.config.ts` sets: + - `output: ""standalone""` (good for Docker) + - `eslint.ignoreDuringBuilds = true` + - `typescript.ignoreBuildErrors = true` -`InventoryAlert.UI/src/components/NotificationProvider.tsx`: +Notes: -- Reads `auth_token` from localStorage. -- If token exists, connects to SignalR hub (`/hubs/notifications`) using `NEXT_PUBLIC_API_URL`. -- Listens for `ReceiveNotification` and increments local unread count. -- Also calls `GET /api/v1/notifications/unread-count` to fetch initial state. +- Ignoring type/build errors can mask real runtime issues; consider switching these back on once the UI stabilizes. --- -## 4) Current Evaluation Flows (Worker) +## 2) Scripts / Commands -### 4.1 Scheduled evaluation (SyncPricesJob) +From `package.json`: -`InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs`: +- `npm run dev` → `next dev` +- `npm run build` → `next build` +- `npm run start` → `next start` +- `npm run lint` → `eslint` +- `npm run test` → `vitest run` -- Fetches quotes in parallel (`MaxDegreeOfParallelism = 5`). -- Persists `PriceHistory` in bulk. -- Loads active alert rules in batch (`GetBySymbolsAsync`) and evaluates locally. -- Creates `Notification` rows (in-memory list), persists them, then calls `IAlertNotifier.NotifyAsync` for each notification. +--- -### 4.2 Event-driven evaluation (MarketPriceAlertHandler + LowHoldingsHandler) +## 3) Environment Variables -Handlers: +Used today: -- `InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/MarketPriceAlertHandler.cs` - - Evaluates rules for one symbol and creates/persists notifications in a transaction, then notifies via SignalR. - - Trigger logic includes only: - - `PriceAbove`, `PriceBelow`, `PriceTargetReached` -- `InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/LowHoldingsHandler.cs` - - Creates/persists a notification, then notifies via SignalR. +- `NEXT_PUBLIC_API_URL` + - consumed by: + - `InventoryAlert.UI/src/lib/api.ts` + - `InventoryAlert.UI/src/hooks/useSignalR.ts` + - default fallback in code is `http://localhost:8080` ---- +Recommended convention: -## 5) Business Flow Issues / Gaps (Observed) +- Dev local: `NEXT_PUBLIC_API_URL=http://localhost:8080` +- Docker (frontend + backend on same docker network): `NEXT_PUBLIC_API_URL=http://api:8080` (or the backend service name) -### 5.1 Two competing “sources of truth” for price alert evaluation +--- -Both of these can generate price notifications: +## 4) Folder Structure (Current) -- `SyncPricesJob` (scheduled) -- `MarketPriceAlertHandler` (event-driven) +Top-level: -Risk: +- `InventoryAlert.UI/src/app/` — App Router routes (pages + layouts) +- `InventoryAlert.UI/src/components/` — UI components and providers +- `InventoryAlert.UI/src/hooks/` — custom hooks +- `InventoryAlert.UI/src/lib/` — API client + utilities +- `InventoryAlert.UI/public/` — static assets +- `InventoryAlert.UI/Dockerfile` — production image build (standalone output) -- Duplicate notifications for the same rule breach. -- Divergent rule behavior (ex: cost-basis alerts are implemented in `SyncPricesJob`, but not in `MarketPriceAlertHandler`). +Routes (observed): -### 5.2 Cooldown/dedup rules are inconsistent across flows +- `src/app/page.tsx` (Dashboard / Overview) +- `src/app/market/page.tsx` +- `src/app/stocks/page.tsx` +- `src/app/stocks/[symbol]/page.tsx` +- `src/app/portfolio/page.tsx` +- `src/app/watchlist/page.tsx` +- `src/app/alerts/page.tsx` +- `src/app/notifications/page.tsx` +- `src/app/admin/health/page.tsx` +- Auth: + - `src/app/(auth)/login/page.tsx` + - `src/app/(auth)/register/page.tsx` -`ProcessQueueJob` contains an alert suppression key: +Notes: -- `alert:cooldown:{payload.Symbol}` (24h) - - `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` +- `src/pages/` exists but appears empty. Consider removing it to reduce confusion (App Router-only project). -But `SyncPricesJob` creates notifications directly and does not share the same cooldown gate. +--- -Risk: +## 5) Layout + Provider Flow (How the App Boots) -- User experiences “alert storms” if the same condition is repeatedly breached across sync cycles. +Entry layout: -### 5.3 Contract drift between docs and code +- `InventoryAlert.UI/src/app/layout.tsx` -Some Wiki execution-flow docs describe SQS publishing for certain alert flows, while current code shows direct persistence + SignalR notify inside `SyncPricesJob`. +Key behaviors: -This makes debugging hard because operational expectations (“where should I look?”) are unclear. +- Injects an inline script to apply theme class (`dark`/`light`) early to reduce theme flash. +- Wraps the app with: + - `ThemeProvider` + - `NotificationProvider` + - `NavbarWrapper` (owns global search open-state) +- Renders `children` inside a centered `
` container. -### 5.4 Notification delivery is not coupled to persistence outcome +--- -In `SyncPricesJob`, persistence (`AddRangeAsync`) and delivery (`NotifyAsync`) occur, but the notification loop is sequential and can fail per user. +## 6) Rendering / Re-render Flow (What Triggers UI Updates) -In the notifier itself, delivery failures are logged and swallowed: +### 6.1 Current pattern (client-first pages) -- `NotificationAlertNotifier.NotifyAsync` catches and logs; it does not throw. +Many pages are declared as: -Implication: +- `'use client'` +- Fetch on mount using `useEffect(() => load(), [])` +- Store results in component state via `useState` -- DB state can show notification exists, but UI never received real-time push (UI should still fetch via API list/unread count, but the user may miss immediacy). +Implications: -### 5.5 No explicit “notification type” or “severity” +- Initial HTML is minimal; most data appears after client-side fetch completes. +- Re-render triggers are primarily: + - state changes (`setState`) + - dependency changes in effects (e.g., `newsCategory`, `newsPage`) -Everything is just a string `Message`. +### 6.2 Example flows -Impact: +Dashboard (`src/app/page.tsx`): -- Hard to group alerts (price vs holdings vs system vs news). -- Hard to present consistent UI (icons, colors, filters). +- On mount, calls: + - `GET /api/v1/watchlist` + - `GET /api/v1/market/news?...` + - `GET /api/v1/portfolio/positions` +- Computes portfolio summary client-side. +- Enqueues news sync via: + - `POST /api/v1/events` with `eventType = inventoryalert.news.sync-requested.v1` -### 5.6 Lack of explicit idempotency key at the “rule trigger” level +Market (`src/app/market/page.tsx`): -There is: +- Re-fetches when `newsCategory` or `newsPage` changes. -- SQS message-level dedup (MessageId) in `ProcessQueueJob` -- but no explicit rule-level dedup (“don’t fire the same rule twice for same symbol within X min”) when the source is scheduled evaluation. +Stocks (`src/app/stocks/page.tsx`): ---- +- Switches between browse mode (`/stocks?page=`) vs search mode (`/stocks/search?q=`) based on input. -## 6) Recommended Enhancements (Business + Technical) +### 6.3 Notifications (SignalR live updates) -### P0 — Choose one primary evaluation pipeline for price alerts +`InventoryAlert.UI/src/components/NotificationProvider.tsx`: -Pick one: +- Reads `auth_token` from `localStorage`. +- If token exists, connects to SignalR: + - hub path: `/hubs/notifications` (full URL uses `NEXT_PUBLIC_API_URL`) +- On `ReceiveNotification`, increments unread count and prepends notification to local state. -**Option A: scheduled-only** +Operational notes: -- `SyncPricesJob` is the sole evaluator for price-based alert rules. -- Remove/disable event-driven `MarketPriceAlertHandler` for price rules (or keep it for a different event type). +- This provider currently polls localStorage periodically (interval) to detect token changes; this can cause extra work/rerenders. +- Consider switching to an explicit “auth changed” event pattern in the future. -**Option B: event-driven** +--- + +## 7) API Client (Current Behavior + Standardization Notes) -- `SyncPricesJob` only publishes events (or only updates `PriceHistory`), and `MarketPriceAlertHandler` becomes the sole evaluator. -- Ensure handler supports all relevant conditions (including cost-basis if desired). -- Ensure event payload includes enough context (`Symbol`, `NewPrice`, potentially `QuoteTimestamp`). +`InventoryAlert.UI/src/lib/api.ts`: -**Option C: Hybrid (User Preferred)** +- Attaches `Authorization: Bearer ` from localStorage when present. +- Always sends cookies (`credentials: ""include""`) to support refresh token flow. +- On `401`: + - tries refresh via `POST /api/v1/auth/refresh` + - retries the original request once + - if refresh fails, clears token and redirects to `/login` -- **Keep both** Hangfire jobs (scheduled) and event-driven handlers for redundancy and comprehensive coverage. -- Requires rigorous idempotency/dedup logic to prevent duplicate notifications for the same breach event across both pipelines. +Standardization suggestions (ties to API error docs): -Acceptance criteria: +- Parse `ErrorResponse` from the API consistently: + - current backend error body uses `errors[]` + `errorId` + - UI currently tries `userFriendlyMessage/message/title`, which may not match API response shape +- Prefer surfacing `X-Correlation-Id` to the UI for support/debug: + - show it in error toasts, or expose a “Copy correlation id” affordance -- One breach → one notification → one delivery attempt. -- Same rule logic regardless of entry path. +See also: -### P0 — Standardize cooldown/dedup semantics +- `doc/error_handling_and_response_standard.md` -Define the canonical rule: +--- -- Per `(UserId, AlertRuleId)` (recommended), or per `(UserId, Symbol, Condition)`. +## 8) Docker (UI + Wiki) — Recommended Approach (Not Implemented Here) -Then enforce it in the chosen evaluation pipeline: +### 8.1 UI Docker (already exists) -- Redis key pattern (example): `alert:cooldown:{userId}:{ruleId}` -- TTL configurable per rule type (e.g., 24h for news, 1h for price, etc.) +`InventoryAlert.UI/Dockerfile` uses `next build` with `output: standalone` and runs `node server.js`. -### P1 — Add “notification type” (and optional metadata) to support UX +Basic build/run: -Add fields conceptually (and later in DB if desired): +```bash +docker build -t inventoryalert-ui ./InventoryAlert.UI +docker run --rm -p 3000:3000 -e NEXT_PUBLIC_API_URL=http://localhost:8080 inventoryalert-ui +``` -- `Type` (enum): `Price`, `Holdings`, `System`, `News`, … -- `Severity` (enum): `Info`, `Warning`, `Critical` -- Optional metadata: `CurrentPrice`, `TargetValue`, `Condition`, … +### 8.2 Wiki Docker (recommended to add) -Even if DB isn’t changed immediately, you can standardize message templates and embed structured fields in logs for now. +`InventoryAlert.Wiki/` does not currently include a Dockerfile. -### P1 — Make delivery robust and observable +Recommended pattern: -Recommended: +- build stage: `npm ci` + `npm run build` +- runtime stage: serve static `build/` output (nginx or a minimal node static server) -- Ensure UI always reflects DB truth: - - UI should periodically refresh unread count and/or latest notifications (not only via SignalR push). - - **Manual Reload Feature:** Build a feature allowing the user to manually reload or pull-to-refresh to get the newest notifications directly from the API. -- Add explicit logging fields for each notification dispatch: - - `NotificationId`, `UserId`, `AlertRuleId`, `TickerSymbol` -- Consider capturing “delivery status” only if needed (usually not needed if polling exists). +### 8.3 Two-container compose (recommended) -### P2 — Align docs to the implemented flow +Recommended to create a frontend compose file (example name): -Once a primary pipeline is chosen: +- `docker-compose.frontend.yml` + - `ui` → `InventoryAlert.UI` on port `3000` + - `wiki` → `InventoryAlert.Wiki` on port `3001` -- Update execution flow docs to match it. -- Keep review/refactor notes under `doc/` (not Wiki), and keep Wiki “how to use” oriented. +This file is not added in this doc-only task. --- -## 7) Suggested “Golden Path” Flow (Target) +## 9) UX/UI Enhancement Ideas (Recommended, Not Implemented) -```mermaid -sequenceDiagram - participant UI as UI - participant API as InventoryAlert.Api - participant W as InventoryAlert.Worker - participant DB as PostgreSQL - participant Hub as NotificationHub +High-impact improvements that also reduce duplicate code: - UI->>API: POST /api/v1/alertrules - API->>DB: INSERT AlertRule - W->>W: Evaluate (scheduled or event-driven) - W->>DB: INSERT Notification(s) - W->>Hub: ReceiveNotification(notification) - UI->>API: GET /api/v1/notifications/unread-count (initial + periodic) -``` +### 9.1 Introduce a small “UI kit” layer ---- +Create reusable components: -## 8) Practical Next Steps (Implementation Level) +- `PageHeader` (title, subtitle, actions) +- `Card`, `StatCard` +- `Table` / `TableSkeleton` +- `EmptyState`, `ErrorState` +- `Button`, `Input`, `Badge` -1) **Implement Hybrid Evaluation:** ✅ Refactored `SyncPricesJob` and `MarketPriceAlertHandler` to share `IAlertRuleEvaluator`. -2) **Enforce Deduplication/Cooldown:** ✅ Implemented Redis-based cooldown (`alert:cooldown:{userId}:{ruleId}`) in `AlertRuleEvaluator`. -3) **Build Manual Reload in UI:** ✅ Added ""Refresh"" button in Notifications page and synchronized unread count badge. -4) **Standardize Taxonomy:** ✅ Implemented `NotificationType` and `NotificationSeverity` enums and updated UI to use icons/colors. -5) **Align Error Handling:** ✅ UI `fetchApi` and `NotificationProvider` are now resilient to background failures and synchronized via React Context. +Then refactor pages to use them to reduce repeated Tailwind strings. ---- +### 9.2 Centralize toast/confirm patterns -## 9) Verification Status +Currently many pages implement their own toast + confirm dialog state. -- **Unit Tests:** ✅ 99/99 Passing (including new `AlertRuleEvaluatorTests`). -- **E2E Tests:** 🏗️ Planned for next step. -- **Docker:** 🏗️ Rebuild required to verify full flow.",310,09c9d699a7ab47f836e5f6b50eeca0b4,doc\archive\NOTIFICATIONS_AND_ALERT_RULE_FLOW_REVIEW.md,0,338,"notifications, inventoryalert, inventorymanagementsystem, notification, alert, rule, signalr, syncpricesjob",1777190302.6049023,10,atomicity commit dbcontext application service arrange act assert hosted service finnhubpricesyncworker dbset productservice threshold igenericrepository productscontroller xunit httpput msft postgres business logic container iactionresult backgroundservice price drop compose loss unit test googl periodictimer appdbcontext savechanges dockerfile httppost aapl data access fluentassertions httpget entity framework rollback symbol notification iproductrepository postgresql asnotracking iproductservice efcore stock ticker unitofwork,# Alert Rules & Notifications — Business Flow Review + Enhancements | Alert Rules & Notifications — Business Flow Review + Enhancements Scope: end-to- -doc,"# Implementation Plan: Centralized Observability with Seq +Recommended: -This plan replaces ELK with **Seq**, focusing on a high-performance, developer-friendly logging experience optimized for the .NET ecosystem. We will implement end-to-end trace correlation from the initial UI/API request through business logic, background jobs, and database interactions. +- a single global Toast provider + hook (`useToast()`) +- consistent error formatting (and optionally correlation id display) -## 1. Core Principles -- **Structured-First**: No string interpolation in logs; use property templates (`""User {UserId} logged in""`) for indexing. -- **Trace Continuity**: A single `CorrelationId` must bridge the gap between HTTP requests and asynchronous SQS/Hangfire jobs. -- **Contextual Enrichment**: Logs should ""know"" where they are (Service, Environment, Version) without manual boilerplate. +### 9.3 Improve accessibility and keyboard UX ---- +- Ensure modals trap focus, close on `Esc`, and are labeled correctly. +- Add `aria-live` for toast messages. -## 2. Infrastructure: The Seq Stack -We will use a lightweight, single-node Seq instance: -- **Seq Server**: ingestion via HTTP/CLEF (Compact Log Event Format). -- **Serilog.Sinks.Seq**: Native .NET sink for efficient, buffered shipping. -- **Docker Integration**: Seq runs as a container in `docker-compose.yml`. +### 9.4 Reduce debug noise in production + +- Gate `console.log` behind `NODE_ENV !== 'production'` or a `NEXT_PUBLIC_DEBUG_LOGS=true` flag. --- -## 3. The ""Whole Flow"" Logging Checklist +## 10) Component / Hook / Page Scan (Observed) -### 🟢 Layer 1: The Request (Web/API) -- [ ] **Correlation Middleware**: Generate or extract `X-Correlation-ID` from headers. -- [ ] **LogContext Enrichment**: Use `Serilog.Context.LogContext.PushProperty(""CorrelationId"", cid)` at the start of every request. -- [ ] **Request Logging**: Log the incoming path, method, and User ID (from JWT). -- [ ] **Global Error Capture**: Middleware must capture unhandled exceptions and log them with `Log.Error(ex, ""Request failed"")`. +This section is a “what exists today” inventory (paths are workspace-relative). -### 🟡 Layer 2: The Method (Application/Services) -- [ ] **Method Parameters**: Log critical entry points with structured arguments (e.g., `Log.Debug(""Processing alert for {Symbol}"", symbol)`). -- [ ] **Performance Timings**: (Optional) Use `SerilogTimings` for high-value business operations. -- [ ] **Business Events**: Log result outcomes (Success/Failure/Ignored) rather than just ""Method Finished"". +### 10.1 Pages (routes) -### 🟠 Layer 3: The Job (Worker/Hangfire) -- [ ] **Context Propagation**: The `EventEnvelope` must carry the `CorrelationId`. -- [ ] **Job Scoping**: The Worker `SqsDispatcher` must re-hydrate the `LogContext` using the ID from the envelope before calling the processor. -- [ ] **Retry Tracking**: Log the `ReceiveCount` to track problematic messages in Seq. +App Router pages: -### 🔵 Layer 4: The Database (Infrastructure/EF Core) -- [ ] **EF Core Interceptors**: Configure `LogTo(Log.Information)` or an `ItemInterceptor` to tag DB commands with the current `CorrelationId`. -- [ ] **Transaction Boundary**: Log when transactions begin and commit/roll back. +- `InventoryAlert.UI/src/app/page.tsx` → `/` +- `InventoryAlert.UI/src/app/market/page.tsx` → `/market` +- `InventoryAlert.UI/src/app/stocks/page.tsx` → `/stocks` +- `InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx` → `/stocks/:symbol` +- `InventoryAlert.UI/src/app/portfolio/page.tsx` → `/portfolio` +- `InventoryAlert.UI/src/app/watchlist/page.tsx` → `/watchlist` +- `InventoryAlert.UI/src/app/alerts/page.tsx` → `/alerts` +- `InventoryAlert.UI/src/app/notifications/page.tsx` → `/notifications` +- `InventoryAlert.UI/src/app/admin/health/page.tsx` → `/admin/health` ---- +Auth group pages: -## 4. Implementation Details +- `InventoryAlert.UI/src/app/(auth)/login/page.tsx` → `/login` +- `InventoryAlert.UI/src/app/(auth)/register/page.tsx` → `/register` -### 4.1 Serilog Global Configuration -Centralized initialization in `Program.cs`: -```csharp -Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .Enrich.FromLogContext() - .Enrich.WithProperty(""Application"", ""InventoryAlert.Api"") - .WriteTo.Seq(settings.Seq.ServerUrl, apiKey: settings.Seq.ApiKey) - .WriteTo.Console() - .CreateLogger(); -``` +Global layout: -### 4.2 Middleware Implementation (API) -```csharp -public class CorrelationIdMiddleware(RequestDelegate next) -{ - public async Task InvokeAsync(HttpContext context) - { - var correlationId = context.Request.Headers[""X-Correlation-ID""].FirstOrDefault() ?? Guid.NewGuid().ToString(); - using (LogContext.PushProperty(""CorrelationId"", correlationId)) - { - context.Response.Headers.Append(""X-Correlation-ID"", correlationId); - await next(context); - } - } -} -``` +- `InventoryAlert.UI/src/app/layout.tsx` ---- +Static assets / styles: -## 5. Execution Phases +- `InventoryAlert.UI/src/app/globals.css` +- `InventoryAlert.UI/src/app/favicon.ico` -| Phase | Task | Details | -| :--- | :--- | :--- | -| **Phase 1** | **Seq Setup** | Add Seq to `docker-compose.yml` (Port 5341). | -| **Phase 2** | **Base Instrumentation** | Install `Serilog.Sinks.Seq` and implement `CorrelationIdMiddleware` in Api. | -| **Phase 3** | **Worker Re-hydration** | Update `SqsDispatcher` to push `CorrelationId` from envelope to `LogContext`. | -| **Phase 4** | **EF Core Tagging** | Configure DB logging to include correlation context in SQL commands. | +### 10.2 Components ---- +`InventoryAlert.UI/src/components/*`: -## 6. Expected Outcome -> *""In Seq, you filter by `CorrelationId == 'abc-123'`. You see the HTTP POST `/api/market-alert`, followed by the Service log, the SQS Publish log, and finally the Worker log executing the price check—all unified in one timeline.""*",88,0db0046be3ac503ff4e467fb347203af,doc\archive\observability_refactor_plan.md,0,339,"correlationid, from, request, phase, logging, correlation, core, must",1775670503.9359772,1,unitofwork rollback compose application service container hosted service asnotracking postgres postgresql entity framework appdbcontext finnhubpricesyncworker loss periodictimer dockerfile savechanges productservice efcore commit atomicity threshold backgroundservice iproductservice price drop business logic notification dbcontext,# Implementation Plan: Centralized Observability with Seq | Implementation Plan: Centralized Observability with Seq This plan replaces ELK w -doc,"--- -description: Plan for Contracts consolidation, DynamoDB telemetry, event handler pattern, and retry/DLQ strategy -type: plan -status: active -version: 1.0 -tags: [architecture, contracts, dynamodb, events, retry, dlq] -last_updated: 2026-04-05 ----",9,9eac0efb5257aa8b5298118948bd0dc2,doc\archive\PHASE2_PLAN.md,0,340,"plan, contracts, dynamodb, retry, description, consolidation, telemetry, event",1775670503.9190905,1,fluentassertions data access sku loss schema change add-migration business logic postgres efcore periodictimer dbcontext iproductrepository iproductservice stock productservice xunit unit test application service appdbcontext dockerfile igenericrepository dbset item finnhubpricesyncworker backgroundservice commit compose savechanges postgresql unitofwork container hosted service rollback notification domain driven design inventory stock price entity framework infrastructure threshold efcore migration external api application layer domain entity quote market data asnotracking atomicity database update price drop arrange act assert,"PHASE2_PLAN.md | --- description: Plan for Contracts consolidation, DynamoDB telemetry, event han" -doc,"# 🏗️ Phase 2 Architecture Plan +- `AddSymbolModal.tsx` +- `ConfirmDialog.tsx` +- `GlobalSearch.tsx` +- `MarketStatusBanner.tsx` (+ `MarketStatusBanner.test.tsx`) +- `Navbar.tsx` +- `NavbarWrapper.tsx` +- `NotificationBell.tsx` (+ `NotificationBell.test.tsx`) +- `NotificationProvider.tsx` +- `PriceAlertModal.tsx` +- `ThemeProvider.tsx` +- `Toast.tsx` +- `TradeModal.tsx` +- `UserNav.tsx` -> **Scope:** Shared-project consolidation, standardized event handling, retry/DLQ mechanism, and DynamoDB integration for event telemetry. +### 10.3 Hooks ---- +`InventoryAlert.UI/src/hooks/*`: -## 1. 📦 Shared Project Consolidation (`InventoryAlert.Contracts`) +- `useSignalR.ts` -### Problem +### 10.4 Client utilities -`InventoryAlert.Api` and `InventoryAlert.Worker` each had their own copy of domain entities, causing subtle divergence bugs. The fix was started in Phase 1 but needs to be enforced with a hard architectural gate. +`InventoryAlert.UI/src/lib/*`: -### Target Structure +- `api.ts` (+ `api.test.ts`, `api.refresh.test.ts`) -```text -InventoryAlert.Contracts/ -├── Entities/ -│ ├── Product.cs ✅ Live -│ ├── EventLog.cs ✅ Live -│ ├── EarningsRecord.cs ✅ Live -│ ├── InsiderTransaction.cs ✅ Live -│ └── NewsRecord.cs ✅ Live -├── Events/ -│ ├── EventEnvelope.cs ✅ Updated — EventType + Payload + CorrelationId -│ ├── EventTypes.cs ✅ Updated — reverse-DNS naming -│ └── Payloads/ ✅ All payload types -└── Constants/ - └── AlertConstants.cs ✅ Live — CacheKeys, EventTypes, SqsHeaders -``` +Notes: + +- `InventoryAlert.UI/src/pages/` exists but appears empty (App Router-only project). -### Rules (enforced by DDD skill) +--- -- `InventoryAlert.Api` imports: `Contracts` only (via `global using` aliases in `SharedEntityAliases.cs`). -- `InventoryAlert.Worker` imports: `Contracts` only (via `SharedEntityAliases.cs`). -- No entity definition may exist in `Api.Domain.Entities` or `Worker.*` — any addition goes to `Contracts` first. +## 11) Paging + Consistency Targets (Recommended, Not Implemented) -### Remaining Tasks +Where paging already exists in state but UX is incomplete: -- [x] Add `ArchitectureTests` project using `NetArchTest.Rules` to enforce zero-duplication at CI time. -- [x] Move `AppSettings` Finnhub/AWS sections to `Contracts.Configuration` so both services share config models. +- `InventoryAlert.UI/src/app/market/page.tsx` — `newsPage` exists; add Next/Prev controls and show current page. +- `InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx` — News tab has `newsPage`; add visible paging controls. ---- +Where API is paged but UI does not expose paging: -## 2. 🎯 Event Handler Pattern (Dispatcher Architecture) +- `InventoryAlert.UI/src/app/notifications/page.tsx` — API returns paged result; add paging UI or infinite scroll. +- `InventoryAlert.UI/src/app/portfolio/page.tsx` — response is `PagedResult`; add paging controls if position count can grow. -### Problem +Recommended reusable primitives: -`PollSqsJob` used a `switch` statement that required modifying the job class itself whenever a new event type was added — violating OCP. +- `Pagination` (page + pageSize + totalPages) +- `EmptyState` / `ErrorState` (standard handling) +- Replace all `alert()` / `confirm()` with `Toast` + `ConfirmDialog` -### Solution Implemented ✅ +See the per-page details in `doc/UI_COMPONENTS_AND_PAGES_AUDIT.md`. -```text -SQS Message → PollSqsJob - │ - ▼ - Dictionary Dispatcher - (EventType → Func) - │ - ┌─────────┴─────────────────────────────────┐ - │ │ │ │ - PriceAlert Earnings InsiderSell CompanyNews - Handler Handler Handler Handler - │ - (unknown EventType) - │ - UnknownEventHandler - (logs warning + ACKs) -``` +--- -### Interface Contract +## 12) Next Documentation Targets (If You Want) -```csharp -public interface IEventHandler -{ - Task HandleAsync(TPayload payload, CancellationToken ct = default); -} -``` +If you want, I can create additional docs (still markdown-only) for: -### Adding a New Handler +- **UI API contract mapping** (endpoint list + response DTOs used by UI) +- **UI auth flow** (login/refresh/logout lifecycle) +- **UI notification flow** (SignalR events + unread count semantics)",372,549c402f173a671723294d82592b3b7f,doc\archive\UI_TECH_SETUP_AND_FLOW.md,0,367,"inventoryalert, page, pages, stocks, recommended, build, auth, docker",1779814416.3928213,10,postgresql stock business logic postgres iproductservice item entity framework loss fluentassertions iproductrepository application service dbcontext compose xunit productservice sku container efcore notification data access dockerfile price drop unit test appdbcontext threshold arrange act assert igenericrepository dbset inventory asnotracking,"# InventoryAlert.UI — Tech, Setup, Structure, and Rendering Flow | InventoryAlert.UI — Tech, Setup, Structure, and Rendering Flow This is a documen" +doc,"# Unit Test Plan — InventoryAlert.Api -1. Add a constant to `EventTypes.cs`: - ```csharp - public const string MyNewEvent = ""inventoryalert.domain.action.v1""; - ``` -2. Add payload to `Contracts/Events/Payloads/MyNewEventPayload.cs`. -3. Create `Worker/Handlers/MyNewHandler.cs` implementing `IEventHandler`. -4. Register in `Worker/Program.cs`: `builder.Services.AddScoped, MyNewHandler>()`. -5. Add one entry to the `BuildDispatcher()` dictionary in `PollSqsJob`. +> **Stack**: xUnit · Moq · FluentAssertions (add) · Microsoft.AspNetCore.Mvc.Testing (already present) +> **Target**: net10.0 | **Test project**: `InventoryAlert.Tests` --- -## 3. 🔁 Retry & Dead Letter Queue (DLQ) Mechanism +## 🔍 Code Review Findings (Pre-Test) -### Design +| # | File | Issue | Severity | +|---|------|--------|----------| +| 1 | `ProductService.UpdateProductAsync` | `StockAlertThreshold` on `ProductRequest` is never mapped to the entity (entity has no such field). Silent data loss. | 🟠 Medium | +| 2 | `ProductService.GetPriceLossAlertsAsync` | `priceDelta = (origin - current) / origin` — does not guard against price increase direction. Logic is fragile for edge cases. | 🟡 Low | +| 3 | `ProductService.UpdateProductAsync` | `Product updated = new()` declared before the lambda; if transaction throws, `MapToResponse` runs on a blank entity. | 🟠 Medium | +| 4 | `ProductService.DeleteProductAsync` | Same blank-entity capture pattern as bug #3. | 🟠 Medium | +| 5 | `ProductsController.UpdateStockCount` | Builds a full `ProductRequest` inside the controller. Business logic leaking into the Web layer (SRP violation). | 🟡 Low | +| 6 | `FinnhubClient.GetQuoteAsync` | Error logged via `Console.WriteLine` — should use `ILogger`. | 🟡 Low | +| 7 | `GenericRepository.DeleteAsync` | `async Task` with no `await` inside — CS1998 warning. | 🟠 Medium | +| 8 | `GenericRepository.UpdateAsync` | Same CS1998. | 🟠 Medium | +| 9 | `GenericRepository.UpdateRangeAsync` | Same CS1998. | 🟠 Medium | -``` -SQS Queue (MaxReceiveCount=3) - │ - ├── Attempt 1: Handler throws → no ACK → message invisible for VisibilityTimeout - ├── Attempt 2: SQS redelivers → fails again - ├── Attempt 3: SQS redelivers → fails again - │ - └── SQS RedrivePolicy → DLQ automatically (after 3 receives) - │ - └── Optional: PollSqsJob.MoveToDlqAsync() for explicit manual DLQ push -``` +--- -### Configuration (SQS Redrive Policy — in Moto init script) +## 📁 Test Project Structure (to create) -```bash -aws sqs set-queue-attributes \ - --queue-url http://localhost:4566/000000000000/inventory-queue \ - --attributes '{ - ""RedrivePolicy"": ""{ - \""deadLetterTargetArn\"": \""arn:aws:sqs:us-east-1:000000000000:inventory-dlq\"", - \""maxReceiveCount\"": \""3\"" - }"" - }' +``` +InventoryAlert.Tests/ +├── Application/ +│ └── Services/ +│ └── ProductServiceTests.cs ← primary SUT +├── Web/ +│ └── Controllers/ +│ └── ProductsControllerTests.cs +├── Infrastructure/ +│ └── Persistence/ +│ └── Repositories/ +│ └── GenericRepositoryTests.cs +└── Helpers/ + └── ProductFixtures.cs ← shared builders ``` -### Responsibility Split +--- -| Scenario | Action | Responsibility | -| :--- | :--- | :--- | -| Handler throws | Do NOT delete — SQS redelivers | `PollSqsJob` (by design) | -| Receive count > 3 | MoveToDlq + delete from main queue | `PollSqsJob.MoveToDlqAsync()` | -| Unknown EventType | Log warning + ACK (DELETE) | `UnknownEventHandler` | -| Bad JSON | Log + MoveToDlq + ACK | `PollSqsJob.ProcessMessageAsync()` | -| Duplicate (Redis deduplicated) | ACK without processing | `PollSqsJob` | +## 1. `ProductServiceTests.cs` -### Tasks +**SUT**: `ProductService` | **Layer**: Application -- [ ] Update `moto-init/init-sqs.sh` to create `inventory-dlq` queue and configure RedrivePolicy. -- [ ] Add `SqsDlqUrl` to `appsettings.Docker.json` and `appsettings.json`. -- [ ] Add a DLQ monitor/alerter (future: Lambda or Worker polling DLQ for notifications). +### Mocks +```csharp +Mock _unitOfWork = new(); +Mock _productRepo = new(); +Mock _finnhubClient = new(); + +// SUT wired in constructor +_sut = new ProductService(_unitOfWork.Object, _productRepo.Object, _finnhubClient.Object); +``` --- -## 4. 🗄️ DynamoDB Integration Plan +### 1.1 `GetAllProductsAsync` -### Why DynamoDB? +| Test Name | Arrange | Assert | +|-----------|---------|--------| +| `GetAll_ReturnsEmptyList_WhenNoProductsExist` | Repo returns `[]` | Result is empty | +| `GetAll_ReturnsMappedResponses_WhenProductsExist` | Repo returns 2 Products with known values | 2 items; Id/Name/TickerSymbol/OriginPrice/CurrentPrice/StockCount/PriceAlertThreshold all mapped | -| Requirement | PostgreSQL | DynamoDB | -| :--- | :--- | :--- | -| Relational CRUD (Products) | ✅ Perfect fit | Overkill | -| High-throughput event logs | ❌ Table grows unbounded | ✅ Designed for it | -| TTL-based auto-expiry | ❌ Requires cron jobs | ✅ Native TTL per-item | -| Deduplication store | ❌ Requires explicit cleanup | ✅ TTL + conditional writes | -| SQS message audit trail | ❌ Schema migrations | ✅ Schema-less, append-only | +--- -### Target: EventLog Table +### 1.2 `GetProductByIdAsync` -```text -Table: inventory-event-logs +| Test Name | Arrange | Assert | +|-----------|---------|--------| +| `GetById_ReturnsNull_WhenProductNotFound` | Repo returns `null` for id=99 | `null` | +| `GetById_ReturnsMappedResponse_WhenProductFound` | Repo returns Product id=1 | Non-null; fields match | -PK: EventType (String) — partition key -SK: MessageId (String) — sort key (unique per event) +--- -Attributes: - Source — emitting service - Payload — raw JSON (for audit trail) - CorrelationId — cross-service trace ID - ProcessedAt — ISO8601 UTC string - TTL — Unix epoch (auto-delete after 90 days) - Status — ""processed"" | ""failed"" | ""skipped"" -``` +### 1.3 `CreateProductAsync` -### Required NuGet +| Test Name | Arrange | Assert | +|-----------|---------|--------| +| `Create_CallsAddAsync_AndSaveChanges` | `AddAsync` returns entity; `SaveChangesAsync` completes | Both called exactly once | +| `Create_ReturnsMappedResponse_WithCorrectFields` | Known request values | Response matches request fields | +| `Create_MapsNullTickerSymbol_ToEmptyString` | `TickerSymbol = null` in request | Entity passed to `AddAsync` has `TickerSymbol == """"` | -```powershell -dotnet add InventoryAlert.Worker package AWSSDK.DynamoDBv2 -``` +--- -> Already installed ✅ +### 1.4 `UpdateProductAsync` -### Implementation Phases +| Test Name | Arrange | Assert | +|-----------|---------|--------| +| `Update_ThrowsKeyNotFoundException_WhenProductNotFound` | Repo returns `null` for id=99 | `KeyNotFoundException` with ""99"" in message | +| `Update_UpdatesAllFields_WhenProductFound` | Repo returns existing; transaction invokes delegate | Entity has Name/TickerSymbol/StockCount/CurrentPrice/OriginPrice/PriceAlertThreshold updated | +| `Update_ExecutesInsideTransaction` | same | `ExecuteTransactionAsync(Func, ct)` called once | +| `Update_ReturnsUpdatedProduct_NotBlankDefault` *(Bug #3)* | `UpdateAsync` mock returns patched entity | Response.Id ≠ 0 | -#### Phase 4A — Infrastructure Setup +--- -- [ ] Add `DynamoDbSettings` to `WorkerSettings` (table name, endpoint). -- [ ] Register `IAmazonDynamoDB` in `Worker/Program.cs`. -- [ ] Create `Worker/Persistence/EventLogDynamoRepository.cs`. -- [ ] Create DynamoDB table in `moto-init/init-dynamodb.sh`. +### 1.5 `DeleteProductAsync` -#### Phase 4B — Telemetry Write +| Test Name | Arrange | Assert | +|-----------|---------|--------| +| `Delete_ReturnsNull_WhenProductNotFound` | Repo returns `null` | `null`; `ExecuteTransactionAsync` never called | +| `Delete_CallsDeleteAsync_InsideTransaction_WhenFound` | Repo returns product; delegate invoked | `DeleteAsync` once; transaction once | +| `Delete_ReturnsMappedResponse_WhenFound` | same | Response maps the deleted product | -- [ ] In `PollSqsJob`, after successful dispatch: write event to DynamoDB with `Status=""processed""`. -- [ ] On handler failure: write with `Status=""failed""` before re-throwing. -- [ ] Set TTL = `ProcessedAt + 90 days`. +--- -#### Phase 4C — Query API (optional) +### 1.6 `BulkInsertProductsAsync` -- [ ] Add `GET /api/events?symbol=AAPL&limit=20` endpoint in Api. -- [ ] Api calls DynamoDB via `IAmazonDynamoDB` (query by EventType + date range). -- [ ] Dashboard ""Alerts Feed"" view connects to this endpoint. +| Test Name | Arrange | Assert | +|-----------|---------|--------| +| `BulkInsert_CallsAddRangeAsync_InsideTransaction` | Transaction invokes delegate | `AddRangeAsync` called with 3 entities | +| `BulkInsert_MapsAllRequests_ToEntities` | Capture arg on `AddRangeAsync` | Each entity has correct Name, Ticker, OriginPrice | -### DynamoDB Table Schema +--- -```csharp -public class EventLogEntry -{ - [DynamoDBHashKey(""EventType"")] - public string EventType { get; set; } = string.Empty; +### 1.7 `GetPriceLossAlertsAsync` - [DynamoDBRangeKey(""MessageId"")] - public string MessageId { get; set; } = string.Empty; +| Test Name | Arrange | Assert | +|-----------|---------|--------| +| `PriceLoss_ReturnsEmpty_WhenNoProducts` | Repo `[]` | Empty | +| `PriceLoss_SkipsProduct_WhenFinnhubReturnsNull` | 1 product; Finnhub → `null` | Empty | +| `PriceLoss_SkipsProduct_WhenCurrentPriceIsZero` | Finnhub → `{ CurrentPrice = 0 }` | Empty | +| `PriceLoss_ReturnsAlert_WhenDropExceedsThreshold` | OriginPrice=100, Threshold=0.1; Quote=85 (15% drop > 10%) | 1 alert; `PriceChangePercent=0.15`; `PriceDiff=-15` | +| `PriceLoss_DoesNotAlert_WhenDropBelowThreshold` | OriginPrice=100, Threshold=0.2; Quote=90 (10% < 20%) | Empty | +| `PriceLoss_AlertsMapsAllFields_Correctly` | Above scenario | All 8 fields on `PriceLossResponse` match expected | - public string Source { get; set; } = string.Empty; - public string Payload { get; set; } = string.Empty; - public string CorrelationId { get; set; } = string.Empty; - public string ProcessedAt { get; set; } = string.Empty; - public string Status { get; set; } = string.Empty; +--- - [DynamoDBProperty(""TTL"")] - public long Ttl { get; set; } // Unix epoch for DynamoDB native TTL -} -``` +### 1.8 `SyncCurrentPricesAsync` + +| Test Name | Arrange | Assert | +|-----------|---------|--------| +| `Sync_SkipsProduct_WhenFinnhubReturnsNull` | Product CurrentPrice=50; Finnhub `null` | `CurrentPrice` still 50 | +| `Sync_UpdatesCurrentPrice_WhenValidQuote` | Finnhub → `CurrentPrice=75` | Product entity mutated to 75 before `UpdateRangeAsync` | +| `Sync_CallsUpdateRangeAsync_InsideTransaction` | same | `UpdateRangeAsync` called once inside transaction | --- -## 📋 Task Checklist +## 2. `ProductsControllerTests.cs` -### Contracts ✅ +**SUT**: `ProductsController` | **Layer**: Web (pure unit, no HTTP pipeline) -- [x] Centralize all entities in `InventoryAlert.Contracts` -- [x] Add `Constants/AlertConstants.cs` -- [x] Standardize `EventEnvelope` fields -- [ ] Add architecture enforcement tests +### Mocks +```csharp +Mock _service = new(); +_sut = new ProductsController(_service.Object); +``` -### Event Handler Pattern ✅ +### 2.1 `GetProducts` +| Test | Assert | +|------|--------| +| `GetProducts_Returns200_WithList` | `OkObjectResult` with 2 items | -- [x] `IEventHandler` interface -- [x] Dictionary dispatcher in `PollSqsJob` -- [x] `UnknownEventHandler` fallback -- [x] All existing handlers implement `IEventHandler` +### 2.2 `GetProductById` +| Test | Assert | +|------|--------| +| `GetById_Returns200_WhenFound` | `OkObjectResult` | +| `GetById_Returns404_WhenNotFound` | `NotFoundResult` | -### Event Types ✅ +### 2.3 `CreateProduct` +| Test | Assert | +|------|--------| +| `Create_Returns201CreatedAtAction` | `CreatedAtActionResult`; ActionName=""GetProductById""; RouteValues[""id""]=5 | -- [x] Reverse-DNS naming convention (`inventoryalert.domain.action.v1`) -- [x] `EventTypes.IsKnown()` for dispatch validation -- [x] `IReadOnlySet` for O(1) lookup +### 2.4 `UpdateProduct` +| Test | Assert | +|------|--------| +| `Update_Returns200_WhenSuccessful` | `OkObjectResult` | +| `Update_Propagates_KeyNotFoundException` | Exception propagates unswallowed | -### Retry / DLQ ✅ +### 2.5 `UpdateStockCount` +| Test | Assert | +|------|--------| +| `UpdateStock_Returns404_WhenProductNotFound` | `NotFoundResult`; `UpdateProductAsync` never called | +| `UpdateStock_CallsUpdate_WithNewStockCount` | `UpdateProductAsync` called with `StockCount==10`; other fields from existing product preserved | +| `UpdateStock_Returns200_WhenSuccessful` | `OkObjectResult` | -- [x] `ApproximateReceiveCount` check (> 3 → manual DLQ) -- [x] ACK-only-on-success pattern in dispatcher -- [x] Moto `init-sqs.sh` RedrivePolicy configuration -- [x] `SqsDlqUrl` in appsettings files +### 2.6 `DeleteProduct` +| Test | Assert | +|------|--------| +| `Delete_Returns204_WhenDeleted` | `NoContentResult` | +| `Delete_Returns404_WhenNotFound` | `NotFoundResult` | -### DynamoDB ✅ +### 2.7 `BulkInsertProducts` +| Test | Assert | +|------|--------| +| `BulkInsert_Returns204_Always` | `NoContentResult` | -- [x] Phase 4A: Infrastructure setup -- [x] Phase 4B: Telemetry write on process/fail -- [x] Phase 4C: Query API endpoint +### 2.8 `GetPriceLossAlerts` +| Test | Assert | +|------|--------| +| `PriceAlerts_Returns200_WithAlerts` | `OkObjectResult` with 2 items | --- -> **Next:** Run `/feature-flow` to implement DynamoDB Phase 4A.",267,9eac0efb5257aa8b5298118948bd0dc2,doc\archive\PHASE2_PLAN.md,0,341,"dynamodb, phase, event, contracts, worker, pollsqsjob, inventoryalert, init",1775670503.9190905,10,fluentassertions data access sku loss schema change add-migration business logic postgres efcore periodictimer dbcontext iproductrepository iproductservice stock productservice xunit unit test application service appdbcontext dockerfile igenericrepository dbset item finnhubpricesyncworker backgroundservice commit compose savechanges postgresql unitofwork container hosted service rollback notification domain driven design inventory stock price entity framework infrastructure threshold efcore migration external api application layer domain entity quote market data asnotracking atomicity database update price drop arrange act assert,"# 🏗️ Phase 2 Architecture Plan | 🏗️ Phase 2 Architecture Plan > Scope: Shared-project consolidation, standardized" -doc,"--- -description: Deep technical reference for the InventoryManagementSystem solution — architecture, layers, event pipeline, storage, and CI/CD. -type: reference -status: active -version: 3.0 -tags: [architecture, ddd, event-driven, infrastructure, reference] -last_updated: 2026-04-05 ----",9,eae089bc91edb76e611fbd964361b984,doc\archive\PROJECT_OVERVIEW.md,0,342,"reference, architecture, event, description, deep, technical, inventorymanagementsystem, solution",1775670503.9190905,1,mock setup aapl domain driven design loss finnhubpricesyncworker domain entity iproductrepository iproductservice quote atomicity stock price httppost stock ticker dbset sku data access unit test verify price drop arrange act assert dockerfile backgroundservice dbcontext hosted service googl threshold infrastructure productservice commit notification msft executetransactionasync business logic savechangesasync moq times once xunit efcore external api postgres iunitofwork periodictimer item container returns async igenericrepository inventory market data symbol productscontroller iactionresult compose application service httpget stock entity framework asnotracking httpput fluentassertions appdbcontext application layer unitofwork rollback postgresql savechanges,PROJECT_OVERVIEW.md | --- description: Deep technical reference for the InventoryManagementSystem solu -doc,"# 🏗️ Inventory Alert System — Technical Architecture +## 3. `GenericRepositoryTests.cs` -> This document covers **architecture, infrastructure, and system internals only**. -> For business workflows and REST API listing, see [`FEATURES_OVERVIEW.md`](FEATURES_OVERVIEW.md). +**SUT**: `GenericRepository` | **Layer**: Infrastructure +**Requires**: `Microsoft.EntityFrameworkCore.InMemory` + +```csharp +AppDbContext CreateContext() => + new(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); +``` + +| Test | Assert | +|------|--------| +| `AddAsync_PersistsEntity_AndReturnsIt` | Entity in DB; returned entity matches values | +| `GetByIdAsync_ReturnsEntity_WhenExists` | Correct product returned | +| `GetByIdAsync_ReturnsNull_WhenNotExists` | `null` | +| `GetAllAsync_ReturnsAllEntities` | 3 items returned | +| `UpdateAsync_MutatesEntity` | DB reflects new Name after SaveChanges | +| `DeleteAsync_RemovesEntity` | Entity gone after SaveChanges | +| `AddRangeAsync_AddsAllEntities` | 3 entities persisted | --- -## 1. Solution Project Map +## 4. `ProductFixtures.cs` — Shared Builders -| Project | SDK | Role | -|---|---|---| -| `InventoryAlert.Api` | `Microsoft.NET.Sdk.Web` | REST API — Controllers, Application Services, Infrastructure | -| `InventoryAlert.Worker` | `Microsoft.NET.Sdk.Web` | Background processor — Hangfire jobs, SQS consumers, Event Handlers | -| `InventoryAlert.Contracts` | `Microsoft.NET.Sdk` | Shared kernel — Entities, Events, Constants. Zero dependencies. | -| `InventoryAlert.Sample` | `Microsoft.NET.Sdk` | Local test publisher — bypasses API to directly push events to SNS | -| `InventoryAlert.UnitTests` | `Microsoft.NET.Sdk` | xUnit + Moq + FluentAssertions unit test suite | -| `InventoryAlert.IntegrationTests` | `Microsoft.NET.Sdk` | Testcontainers.PostgreSql integration tests | -| `InventoryAlert.ArchitectureTests` | `Microsoft.NET.Sdk` | NetArchTest.Rules — automated DDD boundary enforcement | +```csharp +public static class ProductFixtures +{ + public static Product BuildProduct( + int id = 1, string name = ""Test"", string ticker = ""TST"", + decimal originPrice = 100m, decimal currentPrice = 90m, + double threshold = 0.2, int stock = 10) => new() + { + Id = id, Name = name, TickerSymbol = ticker, + OriginPrice = originPrice, CurrentPrice = currentPrice, + PriceAlertThreshold = threshold, StockCount = stock + }; + + public static ProductRequest BuildRequest( + string name = ""Test"", string ticker = ""TST"", + decimal originPrice = 100m, decimal currentPrice = 90m, + double threshold = 0.2, int stock = 10) => new() + { + Name = name, TickerSymbol = ticker, + OriginPrice = originPrice, CurrentPrice = currentPrice, + PriceAlertThreshold = threshold, StockCount = stock + }; + + public static FinnhubQuoteResponse BuildQuote(decimal currentPrice = 90m) => + new() { CurrentPrice = currentPrice }; +} +``` --- -## 2. Clean Architecture / DDD Layer Rules +## 5. NuGet Packages to Add -``` -InventoryAlert.Contracts ← innermost (no deps) - ↑ -InventoryAlert.Api - ├─ Domain/Interfaces/ ← Repository + UoW contracts - ├─ Application/Services/ ← Business logic (ProductService, EventService) - ├─ Application/Interfaces/ ← IProductService, IEventService, IFinnhubClient - ├─ Application/DTOs/ ← Request/Response + FinnhubQuoteResponse - ├─ Application/Mappings/ ← Manual map extensions (no AutoMapper) - ├─ Application/Validators/ ← FluentValidation rule classes - ├─ Infrastructure/Persistence/ ← AppDbContext, GenericRepository, UnitOfWork - ├─ Infrastructure/External/ ← FinnhubClient (HTTP), SnsEventPublisher, DynamoEventLogRepository - └─ Web/Controllers/ ← Thin controllers, delegate to Application +```xml + + + ``` -**Enforced automatically by `InventoryAlert.ArchitectureTests`** (`NetArchTest.Rules`): -- `Application.*` **must not** depend on `Infrastructure.*` -- `Web.Controllers` **must not** directly depend on `Infrastructure.*` -- All classes in `Application.Services` **must** end with `""Service""` -- All classes in `Web.Controllers` **must** inherit `ControllerBase` and end with `""Controller""` -- All classes in `Worker.Handlers` **must** end with `""Handler""` -- `InventoryAlert.Contracts` **must not** import `Microsoft.EntityFrameworkCore` or `Microsoft.AspNetCore` -- All `*Repository` interfaces **must** expose only `Task`/`Task` return types (no sync I/O) +> Already present: `Moq`, `xunit`, `Microsoft.AspNetCore.Mvc.Testing`, `coverlet.collector` --- -## 3. `InventoryAlert.Contracts` — Shared Kernel +## 6. Implementation Priority -The `Contracts` project has **zero external NuGet dependencies** and is the single source of truth for: +| Priority | Test Class | Reason | +|----------|-----------|--------| +| 🔴 P0 | `ProductServiceTests` | Core business logic; highest risk area | +| 🟠 P1 | `ProductsControllerTests` | HTTP contract; catches routing & binding issues | +| 🟡 P2 | `GenericRepositoryTests` | EF Core integration safety net | -### Domain Entities +--- -| Class | Key Fields | -|---|---| -| `Product` | `Id`, `Name`, `TickerSymbol`, `OriginPrice`, `CurrentPrice`, `PriceAlertThreshold` (double, e.g. `0.2` = 20%), `StockCount`, `StockAlertThreshold`, `LastAlertSentAt` (nullable DateTime for alert cooldown) | -| `EventLog` | DynamoDB audit record per published event | -| `EarningsRecord` | Persisted EPS data from Finnhub earnings events | -| `NewsRecord` | Persisted company news headline | -| `InsiderTransaction` | Persisted insider sell transaction | +## 7. Coverage Targets -### Event Pipeline Types +| Layer | Line Coverage | +|-------|--------------| +| Application/Services | ≥ 90% | +| Web/Controllers | ≥ 85% | +| Infrastructure/Repositories | ≥ 80% | +| Infrastructure/Workers | Integration test scope — out of this plan |",282,cf83050ca0b6acae1337f171d1fb1c14,doc\archive\unit_test_plan.md,0,368,"test, assert, entity, name, product, returns, null, repo",1775670503.9293694,1,xunit igenericrepository stock price unit test stock data access arrange act assert efcore googl inventory verify notification commit fluentassertions httpput returns async iactionresult moq hosted service price drop appdbcontext savechanges atomicity iproductrepository threshold entity framework aapl productscontroller sku rollback application service quote backgroundservice mock setup business logic market data savechangesasync times once periodictimer asnotracking finnhubpricesyncworker symbol unitofwork loss httppost iunitofwork item external api productservice httpget msft stock ticker dbset executetransactionasync iproductservice dbcontext,# Unit Test Plan — InventoryAlert.Api | Unit Test Plan — InventoryAlert.Api > Stack: xUnit · Moq · FluentAssertions (add +doc,"# Hackathon Challenge: The Perfect API -**`EventEnvelope` record** — the standard wrapper for every SNS/SQS message: -```csharp -public record EventEnvelope -{ - public string MessageId { get; init; } // Guid — deduplication key - public string EventType { get; init; } // Must match EventTypes constant - public string Source { get; init; } // e.g. ""InventoryAlert.Api"" - public string Payload { get; init; } // JSON-serialized inner payload - public DateTime Timestamp { get; init; } - public string CorrelationId { get; init; } // Cross-service trace ID -} -``` +**Theme:** Design, build, and deploy the ""perfect"" REST API based on industry best practices. -**`EventTypes` static class** — canonical reverse-DNS event names: +**Duration:** 1 Day -| Constant | Value | -|---|---| -| `MarketPriceAlert` | `inventoryalert.pricing.price-drop.v1` | -| `StockLowAlert` | `inventoryalert.inventory.stock-low.v1` | -| `EarningsAlert` | `inventoryalert.fundamentals.earnings.v1` | -| `InsiderSellAlert` | `inventoryalert.fundamentals.insider-sell.v1` | -| `CompanyNewsAlert` | `inventoryalert.news.headline.v1` | +**Technology Stack:** C# with ASP.NET Core Web API ---- +### **Overview** -## 4. Event-Driven Pipeline (Publish → Consume) +Welcome, developers! Your challenge today is not just to build a functional API, but to build a *well-designed* one. We're moving beyond complex business logic to focus purely on the **technical principles** that make APIs scalable, maintainable, and a pleasure to use. -### Publishing (inside `InventoryAlert.Api`) +The provided diagram on REST API Design is your guide and your rulebook. The team that best implements the core principles and features shown in the diagram will be the winner. -1. A service or controller calls `IEventService.PublishEventAsync(eventType, payload, ct)`. -2. `EventService` constructs an `EventEnvelope`, stamps it with a `CorrelationId`, serializes it to JSON, and persists an `EventLog` record to **DynamoDB**. -3. `SnsEventPublisher` pushes the envelope JSON to the **AWS SNS Topic** (`inventory-events`). +### **The Challenge** -### Consuming (inside `InventoryAlert.Worker`) +To sharpen the focus on technical implementation over business logic, this challenge is centered around a **single entity**. You still have two options to choose from: -1. Hangfire runs `PollSqsJob` on a schedule; it long-polls `inventory-event-queue` (SQS bound to SNS). -2. Each message body is deserialized into `EventEnvelope`. -3. An internal **Dictionary Dispatcher** reads `EventType` and invokes the corresponding `IEventHandler`: +1. **Greenfield Project (Build from Scratch):** + - Build a **URL Shortener API**. + - The core resource is a ""shortened URL"" which has an original URL, a generated short code, a creation date, and a click count. + - Your goal is to design the API endpoints for creating, retrieving, listing, and deleting these URLs from the ground up, following REST principles. Think about how to handle the redirect logic for a short code. +2. **Brownfield Project (Refactor an Existing App):** + - We will provide you with a sample .NET project for a simple ""To-Do List"" API (with just one ""Todo"" entity) that is poorly designed and non-RESTful. + - Your task is to refactor this ""legacy"" API, correct its flaws, and implement proper RESTful design patterns. You will need to fix endpoint naming, use HTTP methods correctly, implement proper status codes, and add essential features. -| EventType | Handler | Action | -|---|---|---| -| `MarketPriceAlert` | `PriceAlertHandler` | Logs a structured `🚨 PRICE DROP ALERT` warning; Telegram plug-in point | -| `EarningsAlert` | `EarningsHandler` | Persists `EarningsRecord` to PostgreSQL via `WorkerDbContext` | -| `CompanyNewsAlert` | `NewsHandler` | Persists `NewsRecord` to PostgreSQL | -| `InsiderSellAlert` | `InsiderHandler` | Persists `InsiderTransaction` to PostgreSQL | -| *(unknown)* | `UnknownEventHandler` | Logs and discards gracefully — no crash | +### **Judging Criteria & Scoring** -4. **Dead-Letter Queue**: After `ApproximateReceiveCount` exceeds 3, SQS automaticaly routes to `inventory-event-dlq`. +Your project will be judged based on how many concepts from the REST API Design diagram you successfully implement. ---- +**Core Principles (Max 40 points):** -## 5. Storage Layer +- **Uniform Interface (15 pts):** Are your resources clearly identified? Are your endpoints resource-based (e.g., `/api/urls/{id}`)? Are you using self-descriptive messages (e.g., correct JSON media types and HTTP status codes)? +- **Stateless (10 pts):** Does each request from the client contain all the information needed to understand and process it? The server should not store any client context between requests. +- **Client-Server (10 pts):** Is there a clear separation of concerns between the UI (client) and the data storage (server)? +- **Cacheable (5 pts):** Have you implemented caching headers (like `ETag` or `Cache-Control`) on appropriate GET endpoints? -| Store | Purpose | Access Pattern | -|---|---|---| -| **PostgreSQL** (Npgsql EF Core 10) | `Product`, `EarningsRecord`, `NewsRecord`, `InsiderTransaction` | `IProductRepository` → `GenericRepository` → `AppDbContext` | -| **AWS DynamoDB** | `EventLog` audit trail (append-only, TTL-expiring) | `DynamoEventLogRepository`, accessed via `IEventService` | -| **IMemoryCache** (ASP.NET) | `Product` single-item cache (`Product_{id}`, 10 min TTL) | `ProductService.GetProductByIdAsync` — cache-aside pattern | -| **Hangfire** | Job scheduling metadata | Stored in PostgreSQL (`WorkerDbContext`) | +**Methods & Endpoints (Max 20 points):** -### Transaction Pattern (`ExecuteTransactionAsync`) -All writes use the project-mandated capture pattern: -```csharp -// ✅ Result captured inside lambda — safe even if lambda throws -ProductResponse result = null!; -await _unitOfWork.ExecuteTransactionAsync(async () => -{ - var updated = await _productRepository.UpdateAsync(existing); - result = updated.ToResponse(); -}, cancellationToken); -return result; -``` +- **Correct HTTP Method Usage (20 pts):** + - `GET`: Retrieve resources. + - `POST`: Create new resources. + - `PUT`: Replace an existing resource entirely. + - `PATCH`: Partially update an existing resource. + - `DELETE`: Remove a resource. + - Are your methods idempotent where they should be (GET, PUT, DELETE)? ---- +**Connectedness & Advanced Features (Max 40 points):** + +- **Pagination (10 pts):** For endpoints that return a list of resources, have you implemented paging (e.g., using `?page=1&pageSize=10`)? +- **Filtering & Ordering (10 pts):** Can clients filter or sort the results (e.g., `?clicks=0&sortBy=created_desc`)? +- **Versioning (5 pts):** How are you handling API versioning (e.g., `/api/v1/urls`)? +- **Security & Auth (5 pts):** Have you implemented basic security measures? This could be API Key authentication, JWT, or another simple auth mechanism. +- **HATEOAS (Hypermedia) (5 pts):** Do your resource representations include links to related actions or resources? (This is a key principle for a ""perfect"" API). +- **Input Validation (5 pts):** Are you validating incoming data and returning clear `400 Bad Request` errors? -## 6. Authentication +**Bonus (Up to 10 extra points):** -`AuthController` issues **JWT Bearer tokens** (`HmacSha256`, 2-hour expiry). -Credentials are pulled from `appsettings.json → Auth:Username / Auth:Password`. -All `ProductsController` endpoints are decorated `[Authorize]`. -`EventsController` is unauthenticated (internal/service-to-service calls). +- **Monitoring/Logging:** Basic logging implemented. +- **Documentation:** A simple `README.md` or a generated Swagger/OpenAPI page that is clean and easy to understand. +- **Containerization:** The application is fully runnable via a Dockerfile. ---- +### **Getting Started** -## 7. Docker / Local AWS Infrastructure +1. Form your teams. +2. Choose your path: Greenfield or Brownfield. +3. Clone the starter repository (if provided for the brownfield option). +4. Design your resource models and API endpoints. **Plan before you code!** +5. Start building! Use the `dotnet new webapi` template to get going quickly. +6. Commit your code regularly. +7. Prepare a short (5-minute) demo for the judges. -```yaml",161,eae089bc91edb76e611fbd964361b984,doc\archive\PROJECT_OVERVIEW.md,0,343,"inventoryalert, microsoft, event, must, postgresql, inventory, infrastructure, project",1775670503.9190905,10,mock setup aapl domain driven design loss finnhubpricesyncworker domain entity iproductrepository iproductservice quote atomicity stock price httppost stock ticker dbset sku data access unit test verify price drop arrange act assert dockerfile backgroundservice dbcontext hosted service googl threshold infrastructure productservice commit notification msft executetransactionasync business logic savechangesasync moq times once xunit efcore external api postgres iunitofwork periodictimer item container returns async igenericrepository inventory market data symbol productscontroller iactionresult compose application service httpget stock entity framework asnotracking httpput fluentassertions appdbcontext application layer unitofwork rollback postgresql savechanges,# 🏗️ Inventory Alert System — Technical Architecture | 🏗️ Inventory Alert System — Technical Architecture > This document covers archit -doc,"# docker-compose.yml services -postgres ← PostgreSQL 16, port 5432 -moto ← Moto (AWS mock), port 5000 -moto-init ← Runs init-sqs.sh + init-dynamodb.sh on startup -api ← InventoryAlert.Api (depends on postgres + moto) -worker ← InventoryAlert.Worker (depends on api + moto) -``` +Good luck, and may the best API win!",73,16aed27a12944f551ffc88c2424a06d7,doc\archive\Untitled-1.md,0,369,"your, resource, design, endpoints, build, from, resources, challenge",1759516766.1091347,1,appdbcontext dbset data access igenericrepository asnotracking iproductrepository postgres efcore entity framework postgresql dbcontext compose dockerfile container,"# Hackathon Challenge: The Perfect API | Hackathon Challenge: The Perfect API Theme: Design, build, and deploy the ""perfe" +doc,"# Project Wiki Implementation Plan -Moto init scripts (`SolutionFolder/moto-init/`): -- `init-sqs.sh` — creates `inventory-event-queue` + `inventory-event-dlq` -- `init-dynamodb.sh` — creates `EventLogs` table; reads `$AWS_ENDPOINT_URL` so it works from inside the Docker network +This plan outlines the structure and content for a centralized Wiki/Documentation repository designed to onboarding new developers, provide clarity for users, and optimize context for AI coding agents. -All Docker files are linked as **Solution Items** in `InventoryManagementSystem.sln` for direct editing in Visual Studio. +## 1. Goal +Create a single source of truth that defines the technical and functional landscape of the **InventoryAlert** ecosystem. --- -## 8. Testing Strategy +## 2. Wiki Structure (The ""Knowledge Map"") -| Suite | Count | Tools | -|---|---|---| -| `InventoryAlert.UnitTests` | 66 tests | xUnit, Moq, FluentAssertions, EF InMemory | -| `InventoryAlert.IntegrationTests` | 5 tests | Testcontainers.PostgreSql | -| `InventoryAlert.ArchitectureTests` | 9 tests | NetArchTest.Rules | -| **Total** | **80 tests, 0 failures** | | +### 📂 01. Tech Stack & Environment +- **Backend**: .NET 10, C# 12, Entity Framework Core 10, Npgsql. +- **Frontend**: Next.js 15, TypeScript, Tailwind CSS (v4), React Server Components. +- **Infrastructure**: PostgreSQL, Seq (Logging), Hangfire (Scheduler), SNS/SQS (Event Bus), Docker. +- **Tools**: VS Code/Visual Studio, BM25 Search (Agent), GitHub Actions. -Key unit test rules: -- `ExecuteTransactionAsync` mocks **must** invoke the delegate: `.Returns, CancellationToken>((action, _) => action())` -- `IDisposable.Dispose()` on test fixtures **must** call `GC.SuppressFinalize(this)` (CA1816) -- No `Thread.Sleep`, no `async` method without `await` +### 🏛️ 02. Architecture (The ""Blueprints"") +- **Conceptual Model**: Domain-Driven Design (DDD) + Clean Architecture. +- **Layering**: + - **Web (Api)**: Controllers, Middleware, Auth. + - **Application**: Use Cases, Services, DTOs, Mappings. + - **Domain**: Entities, Interfaces, Exceptions, Constants. + - **Infrastructure**: Repositories, DB Context, External Clients (Finnhub). + - **Worker**: Background processors, Event consumers. ---- +### 💾 03. Data Model (The ""Schema"") +- **Core Entities**: `User`, `Product`, `WatchlistItem`, `AlertRule`, `PriceHistory`. +- **Database**: PostgreSQL schema definitions and relationship maps. +- **Worker Data**: DynamoDB/Local cache entities for price/news tracking. -## 9. Observability +### 🔄 04. Execution Flows (The ""Sequences"") +- **Authentication**: JWT issues, Token Storage, Protected Routes. +- **Alert Lifecycle**: + 1. Rule defined in UI. + 2. Event triggered (Manual or Timer). + 3. Worker processes Price/News. + 4. Evaluates rule conditions. + 5. Dispatches alert (Telegram/Log). +- **Price Sync**: Scheduled tasks vs. Manual triggers. -- **Serilog** structured logging → `logs/inventoryalert.log` (rolling file sink) -- **`CorrelationIdMiddleware`** — stamps every HTTP request with a `X-Correlation-Id` header; propagated through SNS `CorrelationId` field into DynamoDB `EventLog` -- **`ExceptionHandlingMiddleware`** — catches all unhandled exceptions and returns RFC-7807 `ProblemDetails` JSON (no internal stack traces exposed to clients)",198,eae089bc91edb76e611fbd964361b984,doc\archive\PROJECT_OVERVIEW.md,0,344,"moto, init, inventoryalert, tests, docker, dynamodb, postgres, postgresql",1775670503.9190905,162,mock setup aapl domain driven design loss finnhubpricesyncworker domain entity iproductrepository iproductservice quote atomicity stock price httppost stock ticker dbset sku data access unit test verify price drop arrange act assert dockerfile backgroundservice dbcontext hosted service googl threshold infrastructure productservice commit notification msft executetransactionasync business logic savechangesasync moq times once xunit efcore external api postgres iunitofwork periodictimer item container returns async igenericrepository inventory market data symbol productscontroller iactionresult compose application service httpget stock entity framework asnotracking httpput fluentassertions appdbcontext application layer unitofwork rollback postgresql savechanges,"# docker-compose.yml services | docker-compose.yml services postgres ← PostgreSQL 16, port 5432 moto " -doc,"# InventoryAlert.Api — Documentation Index ---- -description: Master index of all documentation files for the InventoryAlert.Api project -type: reference -status: active -version: 1.0 -tags: [doc, index, readme, inventoryalert] -last_updated: 2026-04-04 ---- +### ⚙️ 05. Background Jobs (The ""Engine"") +- **Hangfire Dashboard**: How to monitor internal scheduled tasks. +- **Scheduled Workers**: `FinnhubPricesSyncWorker`, `MarketStatusWorker`. +- **Queue System**: SQS message processing patterns. -## Structure +### 🛠️ 06. Developer Guide (The ""Onboarding"") +- **Local Setup**: `docker compose up`, `dotnet run`, `npm dev`. +- **Coding Standards**: SOLID, Primary Constructors, Async/Await rules. +- **Testing**: xUnit, Moq, Integration test patterns. -``` -doc/ -├── README.md ← this file -│ -├── ROADMAP.md ← active feature roadmap and priorities -└── archive/ ← completed or superseded docs - ├── MODERNIZATION_PLAN.md ← UI + logging + middleware (Done ✅ 2026-04-05) - ├── ENHANCEMENT_PLAN.md ← DDD + code quality improvements (Done ✅ 2026-04-05) - ├── EVENT_DRIVEN_PLAN.md ← event-driven architecture (Done ✅) - ├── EVENT_SETUP_COMMANDS.md ← event setup commands (Done ✅) - ├── SETUP_COMMANDS.md ← initial project setup (Done ✅) - ├── unit_test_plan.md ← unit test coverage plan - ├── DDD_REFACTOR_PLAN.md ← DDD refactor history - └── challenge.md ← completed challenges -``` +### 🤖 07. AI Agent Optimization (The ""Context"") +- **Knowledge items (KIs)**: Repository-specific patterns (e.g., Transaction Capture Pattern). +- **Workflows**: `feature-flow`, `add-entity`, `db-migration` instructions. +- **Corpus Mapping**: How to search effectively using BM25. --- -## Doc Status Legend +## 3. Implementation Phases -| Status | Meaning | -|--------|---------| -| `active` | Current, reflects implemented state | -| `draft` | Work-in-progress, not yet implemented | -| `deprecated` | Superseded by newer doc | +| Phase | Content focus | Output | +| :--- | :--- | :--- | +| **Phase 1** | **Foundation** | Architecture, Tech Stack, Local Setup. | +| **Phase 2** | **Technical Core** | Data Model, Controllers, Repositories. | +| **Phase 3** | **Dynamic Flows** | Alert Flow, Worker Jobs, Event Bus. | +| **Phase 4** | **AI Layer** | Knowledge Items, Workflow documentation. | --- -## Key Docs by Topic +## 4. Maintenance Strategy +- **Doc-as-Code**: Keep all markdown files in `docs/wiki/` within the main repository. +- **Sync Routine**: Update the wiki as part of the `feature-flow` cleanup.",72,0e3d1bd474a65b920c064e59ad5aa7fa,doc\archive\wiki_project_plan.md,0,370,"wiki, phase, event, worker, repository, context, knowledge, core",1775670503.9378276,1,productservice periodictimer quote database update market data sku data access container domain driven design commit dbcontext inventory fluentassertions threshold arrange act assert httpput unitofwork savechanges stock dockerfile productscontroller iproductrepository iactionresult httpget httppost postgresql item external api loss igenericrepository hosted service unit test atomicity notification efcore migration postgres application layer domain entity rollback appdbcontext finnhubpricesyncworker stock price efcore business logic asnotracking schema change infrastructure iproductservice application service add-migration backgroundservice dbset entity framework price drop compose xunit,# Project Wiki Implementation Plan | Project Wiki Implementation Plan This plan outlines the structure and content fo +doc,"--- +description: Plan to reuse the GitHub Wiki repo and update CI to keep it in sync with the docs in this repository (documentation only). +type: reference +status: draft +version: 1.0 +tags: [wiki, documentation, github-actions, ci, docusaurus, inventoryalert] +last_updated: 2026-04-30 +---",9,f64879155750f56af08d5b1c3d9aace8,doc\archive\WIKI_REUSE_AND_CI_SYNC.md,0,371,"github, wiki, documentation, description, plan, reuse, repo, update",1779851803.7648697,1,entity framework iproductrepository threshold igenericrepository efcore finnhubpricesyncworker fluentassertions periodictimer xunit appdbcontext data access dbcontext hosted service price drop notification loss dbset unit test arrange act assert asnotracking backgroundservice,WIKI_REUSE_AND_CI_SYNC.md | --- description: Plan to reuse the GitHub Wiki repo and update CI to keep it in +doc,"# GitHub Wiki Reuse + CI Sync Plan (InventoryManagementSystem) -| Topic | Document | -|-------|---------| -| Testing | `unit_test_plan.md` | -| Architecture | `DDD_STRUCTURE.md`, `DDD_REFACTOR_PLAN.md` | -| Roadmap | `ROADMAP.md` | -| API usage | `WALKTHROUGH.md` | -| External API | `finnhub/FINNHUB_FREE_ENDPOINTS.md` | -| Docker setup | `docker/DOCKER_PLAN.md` | -| Dev commands | `commands/dotnet-commands.md` | +Target GitHub Wiki (UI): ---- +- `https://github.com///wiki` (example: `https://github.com/nhonvo/InventoryManagementSystem/wiki`) -## How to Update Docs +Important note: GitHub Wikis are backed by a **separate git repository**: -Always use `/doc` workflow after implementing any feature. +- `https://github.com//.wiki.git` (example: `https://github.com/nhonvo/InventoryManagementSystem.wiki.git`) -Every `.md` file in this folder should have this header: +This document proposes how to **reuse** that wiki repo and how to **update CI** so changes in this repository can be published to the GitHub Wiki automatically. + +No CI changes are implemented in this task (doc-only). -```yaml ---- -description: -type: spec | plan | reference | walkthrough -status: draft | active | deprecated -version: 1.0 -tags: [relevant, keywords] -last_updated: YYYY-MM-DD --- -``` -After updating any doc, re-index BM25: -```bash -python .agents/scripts/core/bm25_indexer.py -```",75,ecdd02e5e1124862be9dafdf8fa25d9c,doc\archive\README.md,0,345,"index, inventoryalert, status, commands, documentation, active, implemented, docs",1775670503.9200897,1,postgresql stock price asnotracking xunit external api postgres infrastructure container domain driven design dbcontext fluentassertions unit test threshold compose quote loss efcore notification application layer arrange act assert entity framework market data price drop appdbcontext dockerfile domain entity,# InventoryAlert.Api — Documentation Index | InventoryAlert.Api — Documentation Index --- description: Master index of all do -doc,"# Scheduled Jobs Flow Audit +## 1) What we have today -This document breaks down the execution steps and dependencies of all background jobs in `InventoryAlert.Worker`. +- Wiki source site in this repo: `InventoryAlert.Wiki/` (Docusaurus) + - primary authoring folder: `InventoryAlert.Wiki/docs/` + - build output: `InventoryAlert.Wiki/build/` (static website) +- Current CI for docs: `.github/workflows/deploy-wiki.yml` + - builds Docusaurus and deploys to **GitHub Pages** (not GitHub Wiki). -## 1. SyncPricesJob -**Purpose:** Fetches real-time price quotes for all active products. -1. **Fetch Symbols:** Retrieves all product tickers from `IStockListingRepository`. -2. **Parallel Fetch:** Iterates through tickers and calls `IFinnhubClient.GetQuoteAsync(symbol)` in parallel (limited concurrency). -3. **Record History:** Collects all quotes and performs a bulk insert via `AddRangeAsync` into `PriceHistory`. -4. **Check Alerts:** - - Fetches all active `AlertRules` for the processed symbols in a single batch. - - Evaluates rules with a memoized trade basis cache to avoid redundant queries. - - Queues `Notification` objects. -5. **Notify:** Performs bulk insert of notifications and dispatches external alerts via `IAlertNotifier`. -6. **Persistence:** Persists all state changes in a single transaction via `SaveChangesAsync`. +So today you effectively have: -## 2. ProcessQueueJob +- “nice website docs” = GitHub Pages (Docusaurus) +- “GitHub Wiki” = separate, currently not auto-synced -**Purpose:** Processes generic background tasks from a local concurrent queue. +--- -1. **Dequeue:** Polling `IBackgroundTaskQueue` for the next `Func`. -2. **Execute:** Invokes the work item within a scoped `IServiceProvider`. -3. **Log:** Captures success/failure of ad-hoc tasks. +## 2) Choose the canonical source -## 3. SqsScheduledPollerJob +Two valid strategies: -**Purpose:** Bridges AWS SQS messages to the internal processing queue. +### Strategy A (recommended): Canonical = Docusaurus docs; Wiki = export/sync -1. **Long Poll:** Calls `ISqsHelper.ReceiveMessagesAsync` (configured for short/long polling). -2. **Batch Processing:** For each message: - - Identifies the job type. - - Enqueues to `IBackgroundTaskQueue`. - - Deletes message from SQS upon successful enqueue. +- Author docs in `InventoryAlert.Wiki/docs/`. +- CI exports Markdown to the GitHub Wiki repo. +- Keep `.github/workflows/deploy-wiki.yml` (Pages) if you still want the Docusaurus site. -## 4. CleanupPriceHistoryJob +### Strategy B: Canonical = GitHub Wiki repo; Docusaurus optional -**Purpose:** Database maintenance for the `PriceHistory` table. +- Author directly in the GitHub wiki repo (via UI or git). +- Optionally mirror back into this repo (harder to automate cleanly). -1. **Define Threshold:** Calculates cutoff date (e.g., `DateTime.UtcNow.AddDays(-30)`). -2. **Batch Delete:** Executes bulk delete on `PriceHistory` records older than the threshold. -3. **Rationale:** With a 15-minute sync interval for 1,000+ symbols, the table grows by ~35M rows/year. Cleanup prevents unbounded storage growth and maintains index performance for historical charts (which capped at 1-year range). +This plan assumes Strategy A because it keeps “doc-as-code” together with the application source. -<<<<<<< HEAD -## 5. NewsSyncJob -**Purpose:** Consolidated job for fetching both Global Market News and Symbol-Specific Company News. -1. **Market News:** Iterates through global categories (General, Forex, Crypto, Merger) and persists to `IMarketNewsDynamoRepository`. -2. **Company News:** - - Lists tickers from `IStockListingRepository`. - - Fetches symbol-specific news in parallel (limited concurrency). - - Persists articles to `ICompanyNewsDynamoRepository`. -3. **Storage:** Uses DynamoDB for high-volume append-only data. -======= -## 5. CompanyNewsJob +--- -**Purpose:** Syncs latest market news for tracked symbols. +## 3) Export model: Docusaurus → GitHub Wiki -1. **Get Targets:** Lists tickers from `IProductRepository`. -2. **Fetch News:** Calls `IStockDataService.GetCompanyNewsAsync` for each symbol. -3. **Filter:** Removes duplicates already present in the local database. -4. **Store:** Inserts new news items into `ICompanyNewsRepository`. ->>>>>>> origin/main +GitHub Wiki Markdown constraints to consider: -## 6. SyncMetricsJob +- Docusaurus frontmatter (`---`) may render as plain text in GitHub Wiki. +- Docusaurus MDX/shortcodes/admonitions may not render. -**Purpose:** Syncs fundamental metrics (P/E ratio, Market Cap, etc.). +Recommended export rules: -1. **Get Symbols:** Identifies tracked products. -2. **External Call:** Calls `IStockDataService.GetMetricsAsync`. -3. **Update Entity:** Maps metrics to the `Product` entity fundamental fields. -4. **Persist:** Updates the database records. +1) Strip frontmatter blocks. +2) Convert `InventoryAlert.Wiki/docs/index.md` to `Home.md` in the wiki repo (GitHub wiki landing page). +3) Decide how to map paths: + - **Flat pages (recommended)**: `06-background-jobs/workers.md` → `06-background-jobs-workers.md` + - Keep links consistent by rewriting relative links during export. +4) Keep Mermaid diagrams (GitHub supports Mermaid in Markdown in most contexts; validate in the wiki UI). -## 7. SyncEarningsJob +Output folder suggestion in CI: -**Purpose:** Tracks historical and estimated earnings data. +- `artifacts/wiki-export/` (generated) -1. **Iterate Tickers:** Standard loop through active symbols. -2. **Fetch:** `IStockDataService.GetEarningsAsync`. -3. **Merge:** Upserts earnings records into `IEarningsRepository`. +--- -## 8. SyncRecommendationsJob +## 4) Manual sync (local workflow) -**Purpose:** Captures analyst buy/sell recommendation trends. +One-time setup: -1. **Fetch:** Calls `IStockDataService.GetRecommendationsAsync`. -2. **Aggregate:** Stores the latest ""Strong Buy"", ""Hold"", etc., counts. -3. **Archive:** Keeps a history of recommendation shifts. +```bash +git clone https://github.com//.wiki.git _wiki +``` -## 9. SyncInsidersJob +Then copy exported `.md` files into `_wiki/`, commit, push: -**Purpose:** Monitors insider trading activities. +```bash +cd _wiki +git add . +git commit -m ""Sync wiki from InventoryAlert.Wiki/docs"" +git push +``` -1. **Fetch:** Calls `IStockDataService.GetInsidersAsync`. -2. **Deduplicate:** Checks against existing transaction IDs. -3. **Alert:** (If configured) Enqueues an alert if a high-volume insider sale occurs. +Tip: do not copy Docusaurus `build/` output to the GitHub wiki repo. Keep the wiki as source Markdown only. --- -## Technical Observations for Refactoring +## 5) CI sync (GitHub Actions) — recommended workflow design -| Issue | Observation | Recommended Fix | -| :------------------- | :----------------------------------------------------------------------- | :------------------------------------------------------------------------ | -| **API Throttling** | Most ""Sync"" jobs iterate and call Finnhub per symbol. | Implement Batching or Rate-Limiting middleware in the `FinnhubClient`. | -| **Transactionality** | Bulk updates in `SyncPricesJob` use `UpdateRangeAsync`. | Ensure `IUnitOfWork` is used to prevent partial updates. | -| **Redundancy** | Every job manually fetches symbols from `IProductRepository`. | Create a `BaseSyncJob` that handles symbol resolution and error logging. | -| **Queue Saturation** | `SqsScheduledPollerJob` enqueues to the same queue as `ProcessQueueJob`. | Use prioritized queues or separate workers for high-priority price syncs. |",105,dddd2c48a2e88f9c6612010f57fccd3e,doc\archive\SCHEDULED_JOBS_AUDIT.md,0,346,"purpose, news, symbols, fetch, from, calls, symbol, tickers",1777190302.6069095,1,external api application layer arrange act assert googl commit iproductservice igenericrepository atomicity rollback item savechangesasync backgroundservice efcore symbol inventory application service fluentassertions data access stock domain entity business logic unitofwork xunit entity framework dbset loss infrastructure domain driven design unit test asnotracking finnhubpricesyncworker executetransactionasync appdbcontext periodictimer hosted service price drop quote productservice aapl savechanges iunitofwork threshold msft dbcontext stock price sku market data stock ticker notification iproductrepository,# Scheduled Jobs Flow Audit | Scheduled Jobs Flow Audit This document breaks down the execution steps and depe -doc,"# 🛠️ Project Setup — Names & Commands +Create a new workflow (example filename): -> Run all commands from inside `InventoryManagementSystem/` -> unless stated otherwise. +- `.github/workflows/sync-github-wiki.yml` ---- +Trigger: -## 📁 Final Project Names +- on push to `main` +- only when `InventoryAlert.Wiki/docs/**` changes (and optionally `InventoryAlert.Wiki/sidebars.ts`) -| Project | Type | Purpose | -| :--- | :--- | :--- | -| `InventoryAlert.Api` | ASP.NET Web API | ✅ Existing — extended with event endpoints | -| `InventoryAlert.Contracts` | Class Library | ✅ Done — shared event schemas + domain entities | -| `InventoryAlert.Worker` | Worker Service | ✅ Done — Hangfire + SQS consumer | -| `InventoryAlert.Sample` | Console App | ✅ Done — sample event publisher | -| `InventoryAlert.Tests` | xUnit Test | ✅ Existing | +Authentication: ---- +- Use a PAT stored in a secret like `WIKI_PUSH_TOKEN` + - In practice, `GITHUB_TOKEN` often does not have sufficient permission to push to the `.wiki.git` repo. -## ⚡ Step 1 — Create New Projects +High-level steps: -```powershell -cd InventoryManagementSystem",24,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,347,"inventoryalert, project, event, done, names, commands, inventorymanagementsystem, existing",1775670503.9215982,1,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# 🛠️ Project Setup — Names & Commands | 🛠️ Project Setup — Names & Commands > Run all commands from inside InventoryMana -doc,"# 1. Shared contracts (event schemas) -dotnet new classlib -n InventoryAlert.Contracts -o InventoryAlert.Contracts",27,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,348,"contracts, inventoryalert, shared, event, schemas, dotnet, classlib",1775670503.9215982,25,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# 1. Shared contracts (event schemas) | 1 -doc,"# 2. Background worker (Hangfire + SQS) -dotnet new worker -n InventoryAlert.Worker -o InventoryAlert.Worker",30,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,349,"worker, inventoryalert, background, hangfire, dotnet",1775670503.9215982,28,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# 2. Background worker (Hangfire + SQS) | 2 -doc,"# 3. Sample publisher CLI -dotnet new console -n InventoryAlert.Sample -o InventoryAlert.Sample -``` +1) Checkout this repository. +2) Generate a GitHub-wiki-compatible export into `artifacts/wiki-export/`. +3) Checkout the wiki repo into `artifacts/wiki-repo/`. +4) Copy export output into the wiki repo working tree. +5) Commit and push if there are changes. ---- +Workflow skeleton (illustrative only): -## ⚡ Step 2 — Add to Solution +```yaml +name: Sync GitHub Wiki -```powershell -dotnet sln add InventoryAlert.Contracts/InventoryAlert.Contracts.csproj -dotnet sln add InventoryAlert.Worker/InventoryAlert.Worker.csproj -dotnet sln add InventoryAlert.Sample/InventoryAlert.Sample.csproj +on: + push: + branches: [""main""] + paths: + - ""InventoryAlert.Wiki/docs/**"" + - "".github/workflows/sync-github-wiki.yml"" + workflow_dispatch: + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4",145,f64879155750f56af08d5b1c3d9aace8,doc\archive\WIKI_REUSE_AND_CI_SYNC.md,0,372,"wiki, github, repo, docusaurus, docs, sync, inventoryalert, export",1779851803.7648697,10,entity framework iproductrepository threshold igenericrepository efcore finnhubpricesyncworker fluentassertions periodictimer xunit appdbcontext data access dbcontext hosted service price drop notification loss dbset unit test arrange act assert asnotracking backgroundservice,# GitHub Wiki Reuse + CI Sync Plan (InventoryManagementSystem) | GitHub Wiki Reuse + CI Sync Plan (InventoryManagementSystem) Target GitHub Wiki +doc,"# 1) Export docs => artifacts/wiki-export + - name: Export wiki markdown + run: | + mkdir -p artifacts/wiki-export",149,f64879155750f56af08d5b1c3d9aace8,doc\archive\WIKI_REUSE_AND_CI_SYNC.md,0,373,"export, wiki, artifacts, docs, name, markdown, mkdir",1779851803.7648697,146,entity framework iproductrepository threshold igenericrepository efcore finnhubpricesyncworker fluentassertions periodictimer xunit appdbcontext data access dbcontext hosted service price drop notification loss dbset unit test arrange act assert asnotracking backgroundservice,# 1) Export docs => artifacts/wiki-export | 1) Export docs => artifacts/wiki-export - name: Export wiki markdown +doc,# TODO: implement export script later (strip frontmatter + rewrite links + map Home.md),150,f64879155750f56af08d5b1c3d9aace8,doc\archive\WIKI_REUSE_AND_CI_SYNC.md,0,374,"todo, implement, export, script, later, strip, frontmatter, rewrite",1779851803.7648697,150,entity framework iproductrepository threshold igenericrepository efcore finnhubpricesyncworker fluentassertions periodictimer xunit appdbcontext data access dbcontext hosted service price drop notification loss dbset unit test arrange act assert asnotracking backgroundservice,# TODO: implement export script later (strip frontmatter + rewrite links + map Home.md) | TODO: implement export script later (strip frontmatter + rewrite links + map Hom +doc,# e.g. node ./scripts/export-wiki.mjs,152,f64879155750f56af08d5b1c3d9aace8,doc\archive\WIKI_REUSE_AND_CI_SYNC.md,0,375,"node, scripts, export, wiki",1779851803.7648697,151,entity framework iproductrepository threshold igenericrepository efcore finnhubpricesyncworker fluentassertions periodictimer xunit appdbcontext data access dbcontext hosted service price drop notification loss dbset unit test arrange act assert asnotracking backgroundservice,# e.g. node ./scripts/export-wiki.mjs | e.g +doc,"# 2) Checkout GitHub Wiki repo + - name: Checkout wiki repo + run: | + git clone ""https://x-access-token:${WIKI_PUSH_TOKEN}@github.com/${GITHUB_REPOSITORY}.wiki.git"" artifacts/wiki-repo + env: + WIKI_PUSH_TOKEN: ${{ secrets.WIKI_PUSH_TOKEN }} + GITHUB_REPOSITORY: ${{ github.repository }}",160,f64879155750f56af08d5b1c3d9aace8,doc\archive\WIKI_REUSE_AND_CI_SYNC.md,0,376,"wiki, github, repo, checkout, name, clone, https, access",1779851803.7648697,153,entity framework iproductrepository threshold igenericrepository efcore finnhubpricesyncworker fluentassertions periodictimer xunit appdbcontext data access dbcontext hosted service price drop notification loss dbset unit test arrange act assert asnotracking backgroundservice,# 2) Checkout GitHub Wiki repo | 2) Checkout GitHub Wiki repo - name: Checkout wiki repo run: | +doc,"# 3) Copy, commit, push + - name: Publish + run: | + rsync -a --delete artifacts/wiki-export/ artifacts/wiki-repo/ + cd artifacts/wiki-repo + git status --porcelain + if [ -n \""$(git status --porcelain)\"" ]; then + git config user.name \""github-actions[bot]\"" + git config user.email \""github-actions[bot]@users.noreply.github.com\"" + git add . + git commit -m \""Sync wiki\"" + git push + fi ``` --- -## ⚡ Step 3 — Add Project References +## 6) How this co-exists with the current `deploy-wiki.yml` -### `InventoryAlert.Api` references `Contracts` -```powershell -dotnet add InventoryAlert.Api/InventoryAlert.Api.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj -``` +You have two publishing targets: -### `InventoryAlert.Worker` references `Contracts` -```powershell -dotnet add InventoryAlert.Worker/InventoryAlert.Worker.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj -``` +- GitHub Pages (Docusaurus site) → keep `.github/workflows/deploy-wiki.yml` +- GitHub Wiki (markdown) → add `.github/workflows/sync-github-wiki.yml` -### `InventoryAlert.Sample` references `Contracts` -```powershell -dotnet add InventoryAlert.Sample/InventoryAlert.Sample.csproj reference InventoryAlert.Contracts/InventoryAlert.Contracts.csproj -``` +This gives: ---- +- “pretty docs” for reading (Pages) +- “quick editing / discoverability” for contributors (Wiki) -## ⚡ Step 4 — Install NuGet Packages +If you only want GitHub Wiki going forward, you can retire `deploy-wiki.yml` later.",191,f64879155750f56af08d5b1c3d9aace8,doc\archive\WIKI_REUSE_AND_CI_SYNC.md,0,377,"wiki, github, artifacts, deploy, commit, push, name, repo",1779851803.7648697,161,entity framework iproductrepository threshold igenericrepository efcore finnhubpricesyncworker fluentassertions periodictimer xunit appdbcontext data access dbcontext hosted service price drop notification loss dbset unit test arrange act assert asnotracking backgroundservice,"# 3) Copy, commit, push | 3) Copy, commit, push - name: Publish run: | rsync -a --" +doc,"# InventoryAlert.Worker — Detailed Implementation Architecture -### `InventoryAlert.Api` — Event publishing -```powershell",69,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,350,"inventoryalert, csproj, contracts, sample, dotnet, powershell, worker, reference",1775670503.9215982,31,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# 3. Sample publisher CLI | 3 -doc,# AWS SNS publisher (talks to Moto at localhost:5000),70,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,351,"publisher, talks, moto, localhost",1775670503.9215982,70,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# AWS SNS publisher (talks to Moto at localhost:5000) | AWS SNS publisher (talks to Moto at localhost:5000) -doc,"# ✅ INSTALLED -dotnet add InventoryAlert.Api package AWSSDK.SimpleNotificationService -dotnet add InventoryAlert.Api package AWSSDK.SQS -``` +This diagram details the specific files and methods involved in the background processing ecosystem. -### `InventoryAlert.Worker` — Hangfire + SQS consumer + Redis + DB -```powershell",77,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,352,"dotnet, inventoryalert, package, awssdk, installed, simplenotificationservice, powershell",1775670503.9215982,71,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# ✅ INSTALLED | ✅ INSTALLED dotnet add InventoryAlert.Api package AWSSDK.SimpleNotificationServi -doc,"# Hangfire core -dotnet add InventoryAlert.Worker package Hangfire.AspNetCore -dotnet add InventoryAlert.Worker package Hangfire.PostgreSql",81,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,353,"hangfire, dotnet, inventoryalert, worker, package, core, aspnetcore, postgresql",1775670503.9215982,78,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# Hangfire core | Hangfire core dotnet add InventoryAlert.Worker package Hangfire.AspNetCore dotne -doc,"# SQS consumer -dotnet add InventoryAlert.Worker package AWSSDK.SQS",84,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,354,"consumer, dotnet, inventoryalert, worker, package, awssdk",1775670503.9215982,82,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# SQS consumer | SQS consumer dotnet add InventoryAlert.Worker package AWSSDK.SQS -doc,"# Redis caching -dotnet add InventoryAlert.Worker package Microsoft.Extensions.Caching.StackExchangeRedis",87,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,355,"caching, redis, dotnet, inventoryalert, worker, package, microsoft, extensions",1775670503.9215982,85,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# Redis caching | Redis caching dotnet add InventoryAlert.Worker package Microsoft.Extensions.Cach -doc,"# EF Core (share same DB) -dotnet add InventoryAlert.Worker package Npgsql.EntityFrameworkCore.PostgreSQL -dotnet add InventoryAlert.Worker package Microsoft.EntityFrameworkCore.Design",91,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,356,"dotnet, inventoryalert, worker, package, entityframeworkcore, core, share, same",1775670503.9215982,88,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# EF Core (share same DB) | EF Core (share same DB) dotnet add InventoryAlert.Worker package Npgsql.EntityFr -doc,"# HTTP client (for Finnhub calls) -dotnet add InventoryAlert.Worker package RestSharp -``` +### 1. High-Detail Flow Diagram -### `InventoryAlert.Worker` — DynamoDB (Future Enterprise Extension) +```mermaid +graph TD + subgraph Host [""Host Layer""] + PRG[Program.cs] --> |Register| NSW[NativeSqsWorker.cs] + PRG --> |Register| QHS[QueuedHostedService.cs] + PRG --> |Register| JSS[JobSchedulerService.cs] + end -> **⚠️ Optional:** Only install when migrating from Postgres `EventLog` and Redis dedup -> to the polyglot DynamoDB strategy described in `EVENT_DRIVEN_PLAN.md`. + subgraph NativeFlow [""Path B: Native SQS (Real-time)""] + NSW --> |ExecuteAsync| PQJ[ProcessQueueJob.cs] + PQJ --> |ExecuteAsync Loop| SHP[SqsHelper.cs] + SHP --> |ReceiveMessagesAsync| SQS((Amazon SQS)) + PQJ --> |ProcessBatchAsync| DISP[SqsDispatcher.cs] + end -```powershell",101,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,357,"http, client, finnhub, calls, dotnet, inventoryalert, worker, package",1775670503.9215982,92,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# HTTP client (for Finnhub calls) | HTTP client (for Finnhub calls) dotnet add InventoryAlert.Worker package RestSha -doc,"# DynamoDB client + object persistence model -dotnet add InventoryAlert.Worker package AWSSDK.DynamoDBv2 -``` + subgraph HangfireFlow [""Path A: Hangfire (Scheduled)""] + JSS --> |StartAsync| RJG[IRecurringJobManager] + RJG --> |AddOrUpdate| HFDB[(Hangfire Storage)] + HFDB --> |Trigger| PSJ[PollSqsJob.cs] + PSJ --> |ExecuteAsync| SHP + PSJ --> |ProcessBatchAsync| DISP + end -### `InventoryAlert.Sample` — HTTP client to call the API -```powershell -dotnet add InventoryAlert.Sample package Microsoft.Extensions.Http -``` + subgraph CoreLogic [""Core Processing Engine""] + DISP --> |DispatchAsync| DDP[Redis: Atomic Dedup] + DDP --> |Unique| CLD[Price Alert Cooldown] + CLD --> |Allow| PROC[MessageProcessor.cs] + PROC --> |ProcessMessageAsync| HAND[Integration Handlers] + HAND --> |HandleAsync| RES[(DynamoDB / DB)] + end ---- + subgraph Handlers [""Integration Handlers""] + HAND --- NH[NewsHandler.cs] + HAND --- PH[PriceAlertHandler.cs] + HAND --- SLH[StockLowHandler.cs] + end -## ⚡ Step 5 — Verify Solution Builds + subgraph InMemFlow [""Path C: In-Memory Task Queue""] + QHS --> |ExecuteAsync| BTQ[IBackgroundTaskQueue] + BTQ --> |DequeueAsync| WORK[Func Task] + WORK --> |Invoke| LOG[(Audit Logs / Sync)] + end -```powershell -dotnet build InventoryManagementSystem.sln + style Host fill:#f5f5f5,stroke:#333 + style NativeFlow fill:#fff0f5,stroke:#db7093,stroke-width:2px + style HangfireFlow fill:#e6f3ff,stroke:#4682b4,stroke-width:2px + style CoreLogic fill:#f0fff0,stroke:#2e8b57,stroke-width:2px + style MemoryQueue fill:#ffffff,stroke:#666,stroke-dasharray: 5 5 ``` ---- - -## ⚙️ Step 6 — Environment Variables +### 2. SQS Dispatch Sequence -The Worker's `.NET` config keys live in `InventoryAlert.Worker/appsettings.Docker.json`: +```mermaid +sequenceDiagram + participant SQS as Amazon SQS + participant Job as Job / Poller + participant Help as SqsHelper + participant Disp as SqsDispatcher + participant Redis as Redis / Cache + participant Proc as MessageProcessor + participant Final as IntegrationHandler -```json -{ - ""Database"": { ""DefaultConnection"": ""host=db;port=5432;..."" }, - ""Redis"": { ""Connection"": ""redis:6379"" }, - ""Aws"": { - ""EndpointUrl"": ""http://moto:5000"", - ""SnsTopicArn"": ""arn:aws:sns:us-east-1:123456789012:inventory-events"", - ""SqsQueueUrl"": ""http://moto:5000/123456789012/event-queue"" - } -} + Job->>Help: ReceiveMessagesAsync(queueUrl) + Help->>SQS: SDK: ReceiveMessageAsync + SQS-->>Help: List + Help-->>Job: List + + Job->>Disp: ProcessBatchAsync(messages) + loop Each Message in Batch + Disp->>Disp: TryDeserializeEnvelope + + alt Deserialize Success + Disp->>Redis: Atomic Dedup (StringSetAsync) + alt Is Unique + opt EventType == MarketPriceAlert + Disp->>Redis: Cooldown Check (IsSupressedAsync) + end + + alt Not Supressed + Disp->>Proc: ProcessMessageAsync(message) + Proc->>Final: HandleAsync(payload) + Final-->>Proc: Complete + Proc-->>Disp: Handled + Disp->>Redis: Set Key Expiration (48h) + Disp->>SQS: DeleteMessageAsync (on success) + end + end + else Bad JSON + Disp-->>SQS: DeleteMessageAsync (Ack & Drop) + end + end ``` -AWS SDK credential vars must stay in `docker-compose.yml` (SDK reads OS env directly): +### Component & Method Registry + +| File Name | Method | Purpose | +| :--- | :--- | :--- | +| **NativeSqsWorker.cs** | `ExecuteAsync` | Initiates the native polling implementation during app startup. | +| **ProcessQueueJob.cs** | `ExecuteAsync` | Runs an infinite `while(!ct.IsCancellationRequested)` loop for SQS. | +| **SqsHelper.cs** | `ReceiveMessagesAsync` | Low-level AWS SDK call to fetch messages from an SQS URL. | +| **SqsDispatcher.cs** | `Batch / Dispatch` | Orchestrates batch processing, de-duplication, and cooldown logic. | +| **MessageProcessor.cs** | `ProcessMessageAsync`| Logic for routing a raw SQS body to a typed C# event handler. | +| **JobSchedulerService.cs**| `StartAsync` | One-time registration of recurring Hangfire jobs into persistent storage. | +| **QueuedHostedService.cs** | `ExecuteAsync` | Continuous consumer of the internal `IBackgroundTaskQueue`. | + +> [!IMPORTANT] +> **Path B (Native)** is the most efficient for production as it utilizes ""Long Polling"" (`WaitTimeSeconds=20`), which stays connected to AWS until a message is available, significantly reducing SDK overhead compared to the Hangfire trigger.",113,93ba2f9aa758cddbdd10d485e3d33cc5,doc\archive\worker_flow_diagram.md,0,378,"executeasync, implementation, diagram, processing, dispatch, method, native, polling",1775805608.0369725,1,asnotracking loss notification business logic hosted service appdbcontext finnhubpricesyncworker productservice item threshold dbcontext efcore entity framework backgroundservice stock application service periodictimer sku inventory price drop iproductservice,# InventoryAlert.Worker — Detailed Implementation Architecture | InventoryAlert.Worker — Detailed Implementation Architecture This diagram detail +doc,"--- +description: Practical integration test setup for Worker jobs and event handling (SNS/SQS via Moto), aligned with current repository test harness. +type: reference +status: draft +version: 1.0 +tags: [integration-tests, worker, jobs, events, sqs, sns, moto, hangfire, inventoryalert] +last_updated: 2026-04-28 +---",9,959fbc992d6bc6ba2af3aace0beb65fa,doc\archive\WORKER_JOBS_AND_EVENTS_INTEGRATION_TESTS.md,0,379,"integration, test, worker, jobs, moto, description, practical, setup",1779851803.7593493,1,hosted service application service postgresql asnotracking periodictimer times once entity framework container iproductrepository productservice xunit efcore data access backgroundservice notification dbcontext finnhubpricesyncworker verify business logic returns async fluentassertions mock setup compose arrange act assert postgres igenericrepository price drop appdbcontext loss dbset unit test dockerfile threshold iproductservice moq,WORKER_JOBS_AND_EVENTS_INTEGRATION_TESTS.md | --- description: Practical integration test setup for Worker jobs and event hand +doc,"# Worker Jobs + Event Handling Integration Tests (Practical Setup) -```env -AWS_ACCESS_KEY_ID=test -AWS_SECRET_ACCESS_KEY=test -AWS_DEFAULT_REGION=us-east-1 -``` +This repo already has a running-stack integration test harness under: -> **Note:** Moto accepts any value for credentials. Use `test` / `test` locally. +- `InventoryManagementSystem/InventoryAlert.IntegrationTests` +- `.github/workflows/ci.yml` starts `InventoryManagementSystem/docker-compose.yml` and runs those tests -Future Telegram vars (add only when implementing Phase F): +This document focuses on *jobs + events* coverage that is currently missing or incomplete: -```env -TELEGRAM_BOT_TOKEN=your_bot_token_here -TELEGRAM_CHAT_ID=your_chat_id_here -``` +- Worker recurring jobs (Hangfire) +- API → SNS → SQS → Worker message handling +- DLQ behavior and manual recovery patterns --- -## 🐳 Step 7 — Docker Compose (Final State) +## 1) Current integration test style (observed) -`docker-compose.yml` is fully configured. Services and startup order: +The current integration tests are “black-box” tests: -```yaml -services: - api: # REST API — depends on: db (healthy), moto-init (completed) - worker: # Hangfire — depends on: db (healthy), redis, moto-init (completed) - db: # PostgreSQL 17-alpine — healthcheck: pg_isready - redis: # Redis 7.2-alpine — healthcheck: redis-cli ping - moto: # motoserver/moto:5.1.22 — Mock SNS/SQS, healthcheck: curl :5000 - moto-init: # amazon/aws-cli:2.3.4 — runs init-sqs.sh ONCE on startup -``` +- They call the API via HTTP using RestSharp clients. +- They depend on the Docker compose stack (API/Worker/DB/Redis/Moto/Wiremock). -> **Enforced startup order:** -> `db` + `redis` + `moto` (healthchecks pass) → `moto-init` (exits 0) → `api` + `worker` +Key files: -### Worker Dockerfile +- Harness: `InventoryManagementSystem/InventoryAlert.IntegrationTests/Fixtures/InjectionFixture.cs` +- Base class: `InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/BaseIntegrationTest.cs` +- Polling helper: `InventoryManagementSystem/InventoryAlert.IntegrationTests/Helpers/WaitHelper.cs` +- Compose stack includes Moto and Wiremock: `InventoryManagementSystem/docker-compose.yml` -Located at `InventoryAlert.Worker/Dockerfile`. Multi-stage build using -`dotnet/runtime:10.0` (not `aspnet`) — the worker has no HTTP listener. +Note: `InventoryManagementSystem/InventoryAlert.IntegrationTests/INTEGRATION_TEST_PLAN.md` contains a “future” design (WebApplicationFactory/Testcontainers). It does not match the current RestSharp+Docker approach. --- -## 🛠️ Step 8 — Moto Init Script - -Automatically creates SNS/SQS resources on first Docker boot: +## 2) Local run: commands -- **Script:** `SolutionFolder/moto-init/init-sqs.sh` -- **Runs via:** `moto-init` service in docker-compose (one-shot, exits when done) +From repo root: -| Resource | Type | Notes | -| :--- | :--- | :--- | -| `inventory-event-dlq` | SQS Standard | Dead Letter Queue (max 3 receives) | -| `event-queue` | SQS Standard | Main queue — DLQ redrive wired | -| `inventory-events` | SNS Topic | Auto-subscribed to `event-queue` | +```bash +cd InventoryManagementSystem +docker compose up -d --build +``` -> Script is **idempotent** — checks before creating, safe to re-run. +Verify health: ---- +- API: `http://localhost:8080/health` +- Worker: `http://localhost:8081/health` +- Wiremock: `http://localhost:9091/__admin` +- Seq UI: `http://localhost:5341` -## ✅ Quick Checklist +Then run integration tests: +```bash +dotnet test InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj ``` -[x] dotnet new classlib → InventoryAlert.Contracts ✅ Done -[x] dotnet new worker → InventoryAlert.Worker ✅ Done -[x] dotnet new console → InventoryAlert.Sample ✅ Done -[x] dotnet sln add → 3 projects added to .sln ✅ Done -[x] dotnet add reference → Contracts in Api + Worker + Sample ✅ Done -[x] dotnet add package → All NuGet packages installed ✅ Done - (Api: AWSSDK.SNS + SQS + Serilog + FluentValidation) - (Worker: Hangfire + SQS + Redis + EF + RestSharp) - (Sample: AWSSDK.SNS + SQS + HttpClient) ✅ Done -[x] Entities migrated → Contracts/Entities/ (Product, EventLog, - EarningsRecord, InsiderTransaction, NewsRecord) - ✅ Done -[x] Worker Dockerfile → InventoryAlert.Worker/Dockerfile ✅ Done -[x] appsettings.Docker → Worker Docker config ✅ Done -[x] init-sqs.sh → SNS/SQS resources defined ✅ Done -[x] docker-compose.yml → All services + moto-init ✅ Done -[x] TELEGRAM vars → Implemented (Phase F) — fill BotToken + ChatId ✅ -[x] dotnet build → Full solution compiles (0 errors) ✅ -[x] dotnet test → 61/61 tests pass ✅ -```",219,6b0a91f30d9fe8e3dcd52232744720a7,doc\archive\SETUP_COMMANDS.md,0,358,"done, dotnet, worker, moto, redis, inventoryalert, init, sample",1775670503.9215982,102,postgresql fluentassertions commit dockerfile unit test stock price price drop productservice postgres hosted service stock inventory iproductservice rollback loss finnhubpricesyncworker container dbcontext mock setup appdbcontext asnotracking backgroundservice item application service efcore notification returns async xunit times once arrange act assert business logic entity framework sku atomicity threshold unitofwork quote compose verify external api periodictimer moq market data savechanges,# DynamoDB client + object persistence model | DynamoDB client + object persistence model dotnet add InventoryAlert.Worker pack -doc,"# SignalR Real-Time Notification Plan -This document outlines the architectural plan for integrating real-time notifications into the InventoryAlert system using SignalR and a Redis backplane. +--- -## 1. Objectives -- **Real-time UI Updates:** Push price alerts and system notifications directly to the frontend without manual refresh. -- **Cross-Service Communication:** Allow the `InventoryAlert.Worker` (which detects alerts) to trigger SignalR messages on the `InventoryAlert.Api` (which hosts the hub). -- **Secure Delivery:** Ensure users only receive notifications intended for them using JWT authentication. +## 3) What we should add: “Jobs” integration tests -## 2. Architecture Diagram +### 3.1 Job execution tests (Worker jobs) -```mermaid -graph TD - Worker[Worker Service] -->|Price Sync & Alert Detect| DB[(PostgreSQL)] - Worker -->|Push Notification| RedisBackplane[Redis Backplane] - RedisBackplane --> Hub[NotificationHub in Api Service] - Hub -->|Push via WebSockets| UI[Next.js Frontend] - UI -->|Connects via JWT| Hub -``` +Goal: verify job side effects without relying on “Cron timing”. -## 3. Business & Data Flow +Recommended approach (still black-box): -Why do we need this complex setup? Here is the step-by-step business logic: +1) Trigger the job deterministically (preferred options): + - expose an admin endpoint to enqueue the job (API or Worker), OR + - call Hangfire enqueue endpoint if you add one, OR + - publish an event that the worker maps into a job (ex: news sync requested). +2) Assert side effects via API endpoints (read models) and/or DB queries (if you add DB access to tests). +3) Use `WaitHelper.WaitForConditionAsync` with bounded timeouts. -1. **The Trigger (External):** The market changes. Finnhub provides a new price for `AAPL`. -2. **The Detector (Worker):** The `SyncPricesJob` in the **Worker Service** fetches this price. It runs the business rules (e.g., ""Did it drop 10% from the user's cost?""). -3. **The Decision (Worker):** The Worker identifies a ""Breach"". It creates a `Notification` record in **PostgreSQL** so the user has a permanent history of the alert. -4. **The Hand-off (Worker -> Redis):** The Worker doesn't know who is currently online. It publishes a ""Real-time Signal"" to the **Redis Backplane**. -5. **The Relay (Api):** The **Api Service** (which hosts the SignalR Hub) is subscribed to Redis. It sees the alert and checks: ""Is User A currently connected to my WebSocket?"". -6. **The Delivery (Api -> UI):** If User A is online, the Api pushes the message through the open WebSocket tunnel instantly. -7. **The Experience (UI):** The user's browser receives the message. A **Toast notification** pops up, and the **Notification Badge** in the header increments without the user needing to refresh the page. +Candidate jobs + suggested assertions: -### Why not just use the API for everything? -- **Separation of Concerns:** The API is for fast User interactions (browsing, buying, settings). The Worker is for heavy, scheduled ""Intelligence"" tasks (syncing 1,000s of prices, calculating complex math). -- **Scalability:** If we have 10,000 users, we can add more API instances to handle traffic. All instances stay synced through Redis. +- `NewsSyncJob`: + - trigger via `POST /api/v1/events` (news sync requested) + - assert `GET /api/v1/market/news?...` returns non-empty +- `SyncPricesJob`: + - trigger (needs a deterministic trigger endpoint/event) + - assert prices or notifications changed +- `CleanupPriceHistoryJob`: + - seed data → trigger cleanup → assert old entries removed -## 4. Implementation Steps +### 3.2 Hangfire visibility tests -### Phase 1: Infrastructure (Backend) -1. **Add Dependencies:** - - Add `Microsoft.AspNetCore.SignalR.StackExchangeRedis` to both **Api** and **Worker** projects. -2. **Shared Hub Definition:** - - Create `INotificationHub` interface in `InventoryAlert.Domain` for type-safe client methods. - - Define a shared constant for the Hub route (e.g., `/hubs/notifications`). +Goal: confirm jobs enqueue + complete/fail. -### Phase 2: InventoryAlert.Api (The Host) -1. **Create Hub:** - - Implement `NotificationHub : Hub`. - - Add `[Authorize]` attribute to ensure only authenticated users connect. -2. **Configure SignalR:** - - In `Program.cs`: `builder.Services.AddSignalR().AddStackExchangeRedis(redisConnectionString)`. - - Map the hub: `app.MapHub(""/hubs/notifications"")`. -3. **JWT Configuration:** - - Update `JwtBearer` configuration to handle SignalR access tokens from query strings (standard for WebSockets). +If you add a small Worker API wrapper endpoint (recommended), tests can: -### Phase 3: InventoryAlert.Worker (The Producer) -1. **Configure SignalR Client Logic:** - - In `Program.cs`: Add SignalR services and Redis backplane (even though it doesn't host the hub). -2. **Refactor `NotificationAlertNotifier`:** - - Inject `IHubContext`. - - Update `NotifyAsync` to call `_hubContext.Clients.User(notification.UserId).ReceiveNotification(dto)`. +- query “job status” by returned job id +- or query a “job summary” endpoint -### Phase 4: InventoryAlert.UI (The Consumer) -1. **Install Client:** - - `npm install @microsoft/signalr` -2. **Notification Hook:** - - Create `useSignalR` or `useNotifications` hook. - - Handle connection lifecycle (start, stop, reconnect). - - Listen for `ReceiveNotification` events. -3. **UI Integration:** - - Integration with **Toast notifications**. - - Auto-increment notification badge in the navbar. - - (Optional) Trigger sound or browser desktop notification. +Avoid scraping Hangfire dashboard HTML in tests. -## 4. Technical Details +--- -### INotificationHub Interface -```csharp -public interface INotificationHub -{ - Task ReceiveNotification(NotificationResponse notification); -} -``` +## 4) What we should add: “Events” integration tests (SNS/SQS via Moto) -### Authentication Handling (Api) -Since WebSockets don't support custom headers easily, we must handle the token in the query string: -```csharp -options.Events = new JwtBearerEvents -{ - OnMessageReceived = context => - { - var accessToken = context.Request.Query[""access_token""]; - var path = context.HttpContext.Request.Path; - if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments(""/hubs"")) - { - context.Token = accessToken; - } - return Task.CompletedTask; - } -}; -``` +### 4.1 Why this matters -## 5. Next Steps -1. [ ] Create `INotificationHub` and DTOs in Domain. -2. [ ] Setup Redis Backplane in both services. -3. [ ] Implement `NotificationHub` in Api. -4. [ ] Refactor `NotificationAlertNotifier` in Worker. -5. [ ] Build the UI listener.",108,20b396a3f01d21e3bb13644f9cf3108a,doc\archive\SIGNALR_INTEGRATION_PLAN.md,0,359,"worker, signalr, notification, user, inventoryalert, redis, notifications, inotificationhub",1777190302.6092205,1,application service business logic backgroundservice productservice hosted service appdbcontext price drop stock price notification periodictimer quote market data asnotracking threshold iproductservice dbcontext loss entity framework efcore finnhubpricesyncworker external api,# SignalR Real-Time Notification Plan | SignalR Real-Time Notification Plan This document outlines the architectural pla -doc,"(""AAPL"", ""Apple Inc."", ""NASDAQ"", ""stock""), - (""MSFT"", ""Microsoft Corporation"", ""NASDAQ"", ""stock""), - (""GOOGL"", ""Alphabet Inc."", ""NASDAQ"", ""stock""), - (""AMZN"", ""Amazon.com Inc."", ""NASDAQ"", ""stock""), - (""NVDA"", ""NVIDIA Corporation"", ""NASDAQ"", ""stock""), - (""META"", ""Meta Platforms Inc."", ""NASDAQ"", ""stock""), - (""TSLA"", ""Tesla Inc."", ""NASDAQ"", ""stock""), - (""NFLX"", ""Netflix Inc."", ""NASDAQ"", ""stock""), - (""AMD"", ""Advanced Micro Devices Inc."", ""NASDAQ"", ""stock""), - (""INTC"", ""Intel Corporation"", ""NASDAQ"", ""stock""), - (""JPM"", ""JPMorgan Chase & Co."", ""NYSE"", ""stock""), - (""BAC"", ""Bank of America Corporation"", ""NYSE"", ""stock""), - (""GS"", ""Goldman Sachs Group Inc."", ""NYSE"", ""stock""), - (""V"", ""Visa Inc."", ""NYSE"", ""stock""), - (""MA"", ""Mastercard Incorporated"", ""NYSE"", ""stock""), - (""JNJ"", ""Johnson & Johnson"", ""NYSE"", ""stock""), - (""PFE"", ""Pfizer Inc."", ""NYSE"", ""stock""), - (""UNH"", ""UnitedHealth Group Incorporated"", ""NYSE"", ""stock""), - (""XOM"", ""Exxon Mobil Corporation"", ""NYSE"", ""stock""), - (""CVX"", ""Chevron Corporation"", ""NYSE"", ""stock""),",21,6ee596ecced18ca0f4d4b3b18ead4595,doc\archive\stock.md,0,360,"stock, nasdaq, nyse, corporation, meta, group, incorporated, johnson",1775670503.934977,1,,"stock.md | (""AAPL"", ""Apple Inc."", ""NASDAQ"", ""stock""), (""MSFT""" -doc,"# Unit Test Plan — InventoryAlert.Api +The most fragile path is: -> **Stack**: xUnit · Moq · FluentAssertions (add) · Microsoft.AspNetCore.Mvc.Testing (already present) -> **Target**: net10.0 | **Test project**: `InventoryAlert.Tests` +API request → `EventEnvelope` publish → SNS → SQS → Worker poller → routing/handler → DB/notification ---- +We need tests that confirm: -## 🔍 Code Review Findings (Pre-Test) +- envelope is stamped with `CorrelationId` +- message is delivered to SQS +- worker consumes it and routes correctly -| # | File | Issue | Severity | -|---|------|--------|----------| -| 1 | `ProductService.UpdateProductAsync` | `StockAlertThreshold` on `ProductRequest` is never mapped to the entity (entity has no such field). Silent data loss. | 🟠 Medium | -| 2 | `ProductService.GetPriceLossAlertsAsync` | `priceDelta = (origin - current) / origin` — does not guard against price increase direction. Logic is fragile for edge cases. | 🟡 Low | -| 3 | `ProductService.UpdateProductAsync` | `Product updated = new()` declared before the lambda; if transaction throws, `MapToResponse` runs on a blank entity. | 🟠 Medium | -| 4 | `ProductService.DeleteProductAsync` | Same blank-entity capture pattern as bug #3. | 🟠 Medium | -| 5 | `ProductsController.UpdateStockCount` | Builds a full `ProductRequest` inside the controller. Business logic leaking into the Web layer (SRP violation). | 🟡 Low | -| 6 | `FinnhubClient.GetQuoteAsync` | Error logged via `Console.WriteLine` — should use `ILogger`. | 🟡 Low | -| 7 | `GenericRepository.DeleteAsync` | `async Task` with no `await` inside — CS1998 warning. | 🟠 Medium | -| 8 | `GenericRepository.UpdateAsync` | Same CS1998. | 🟠 Medium | -| 9 | `GenericRepository.UpdateRangeAsync` | Same CS1998. | 🟠 Medium | +### 4.2 Practical test strategy (host → Moto on localhost:5000) ---- +The docker stack exposes Moto: -## 📁 Test Project Structure (to create) +- `http://localhost:5000` -``` -InventoryAlert.Tests/ -├── Application/ -│ └── Services/ -│ └── ProductServiceTests.cs ← primary SUT -├── Web/ -│ └── Controllers/ -│ └── ProductsControllerTests.cs -├── Infrastructure/ -│ └── Persistence/ -│ └── Repositories/ -│ └── GenericRepositoryTests.cs -└── Helpers/ - └── ProductFixtures.cs ← shared builders -``` +Moto-init provisions: ---- +- `event-queue` +- `inventory-event-dlq` +- SNS topic and subscription -## 1. `ProductServiceTests.cs` +Recommended enhancements for integration tests: -**SUT**: `ProductService` | **Layer**: Application +- Add a small SQS client in the test project using `AWSSDK.SQS` and configure: + - Service URL: `http://localhost:5000` + - Region: `us-east-1` + - Dummy credentials (`test`/`test`) -### Mocks -```csharp -Mock _unitOfWork = new(); -Mock _productRepo = new(); -Mock _finnhubClient = new(); +Then tests can: -// SUT wired in constructor -_sut = new ProductService(_unitOfWork.Object, _productRepo.Object, _finnhubClient.Object); -``` +1) Publish an event via API (HTTP). +2) Receive a message directly from `event-queue` and assert: + - body is valid `EventEnvelope` + - `CorrelationId` is non-empty + - optional: SNS MessageAttributes include `EventType`, `CorrelationId` +3) (Optionally) re-inject the message to simulate replay. ---- +### 4.3 DLQ behavior tests -### 1.1 `GetAllProductsAsync` +Prerequisite: worker must not ACK messages that fail at poller/router stage. -| Test Name | Arrange | Assert | -|-----------|---------|--------| -| `GetAll_ReturnsEmptyList_WhenNoProductsExist` | Repo returns `[]` | Result is empty | -| `GetAll_ReturnsMappedResponses_WhenProductsExist` | Repo returns 2 Products with known values | 2 items; Id/Name/TickerSymbol/OriginPrice/CurrentPrice/StockCount/PriceAlertThreshold all mapped | +Test: + +- Send a deliberately malformed envelope or unknown `EventType`. +- Wait until it reaches DLQ (based on `maxReceiveCount`). +- Assert message appears in `inventory-event-dlq`. + +Note: if the worker ACKs “unknown event” as success, it will never reach DLQ; decide policy first. --- -### 1.2 `GetProductByIdAsync` +## 5) Required logging for test debuggability -| Test Name | Arrange | Assert | -|-----------|---------|--------| -| `GetById_ReturnsNull_WhenProductNotFound` | Repo returns `null` for id=99 | `null` | -| `GetById_ReturnsMappedResponse_WhenProductFound` | Repo returns Product id=1 | Non-null; fields match | +To debug failing tests quickly, the stack should emit logs with: ---- +- `CorrelationId` +- `EventType` +- SQS message id / envelope message id +- handler/job name -### 1.3 `CreateProductAsync` +Reference: -| Test Name | Arrange | Assert | -|-----------|---------|--------| -| `Create_CallsAddAsync_AndSaveChanges` | `AddAsync` returns entity; `SaveChangesAsync` completes | Both called exactly once | -| `Create_ReturnsMappedResponse_WithCorrectFields` | Known request values | Response matches request fields | -| `Create_MapsNullTickerSymbol_ToEmptyString` | `TickerSymbol = null` in request | Entity passed to `AddAsync` has `TickerSymbol == """"` | +- `doc/SEQ_REQUEST_RESPONSE_AND_FLOW_LOGGING.md` --- -### 1.4 `UpdateProductAsync` +## 6) Recommended additions to `InventoryAlert.IntegrationTests` (structure) -| Test Name | Arrange | Assert | -|-----------|---------|--------| -| `Update_ThrowsKeyNotFoundException_WhenProductNotFound` | Repo returns `null` for id=99 | `KeyNotFoundException` with ""99"" in message | -| `Update_UpdatesAllFields_WhenProductFound` | Repo returns existing; transaction invokes delegate | Entity has Name/TickerSymbol/StockCount/CurrentPrice/OriginPrice/PriceAlertThreshold updated | -| `Update_ExecutesInsideTransaction` | same | `ExecuteTransactionAsync(Func, ct)` called once | -| `Update_ReturnsUpdatedProduct_NotBlankDefault` *(Bug #3)* | `UpdateAsync` mock returns patched entity | Response.Id ≠ 0 | +Add a worker/events test area: + +```text +InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/ +├── Worker/ +│ ├── Events/ +│ │ ├── EventPublishAndConsumeTest.cs +│ │ ├── EventDlqTest.cs +│ ├── Jobs/ +│ │ ├── NewsSyncJobTest.cs +│ │ ├── SyncPricesJobTest.cs +``` + +And add clients/helpers: ---- +- `Clients/SqsClient.cs` (Moto endpoint) +- `Helpers/SeqQueryHelper.cs` (optional; keep lightweight)",196,959fbc992d6bc6ba2af3aace0beb65fa,doc\archive\WORKER_JOBS_AND_EVENTS_INTEGRATION_TESTS.md,0,380,"tests, worker, event, test, integration, http, jobs, inventorymanagementsystem",1779851803.7593493,10,hosted service application service postgresql asnotracking periodictimer times once entity framework container iproductrepository productservice xunit efcore data access backgroundservice notification dbcontext finnhubpricesyncworker verify business logic returns async fluentassertions mock setup compose arrange act assert postgres igenericrepository price drop appdbcontext loss dbset unit test dockerfile threshold iproductservice moq,# Worker Jobs + Event Handling Integration Tests (Practical Setup) | Worker Jobs + Event Handling Integration Tests (Practical Setup) This repo alrea +doc,"--- +description: Worker job + event flow review (findings, risks, and enhancement recommendations). Content moved out of Wiki per request. +type: reference +status: draft +version: 1.1 +tags: [worker, hangfire, sqs, sns, events, routing, review, enhancements, inventoryalert] +last_updated: 2026-04-26 +---",9,af2cebc4f95126d5c1d8ee9aa64a32bf,doc\archive\worker_jobs_and_event_flow_review.md,0,381,"worker, review, description, event, flow, findings, risks, enhancement",1779851803.7578456,1,efcore entity framework notification price drop hosted service market data finnhubpricesyncworker threshold backgroundservice asnotracking external api productservice periodictimer dbcontext appdbcontext stock price business logic loss iproductservice quote application service,"worker_jobs_and_event_flow_review.md | --- description: Worker job + event flow review (findings, risks, and enhancemen" +doc,"# Worker Jobs & Event Flow (Review + Enhancements) -### 1.5 `DeleteProductAsync` +This document contains **review findings and enhancement recommendations** for: -| Test Name | Arrange | Assert | -|-----------|---------|--------| -| `Delete_ReturnsNull_WhenProductNotFound` | Repo returns `null` | `null`; `ExecuteTransactionAsync` never called | -| `Delete_CallsDeleteAsync_InsideTransaction_WhenFound` | Repo returns product; delegate invoked | `DeleteAsync` once; transaction once | -| `Delete_ReturnsMappedResponse_WhenFound` | same | Response maps the deleted product | +- `InventoryManagementSystem/InventoryAlert.Worker` (Hangfire jobs + SQS processing) +- API → messaging → Worker end-to-end event flow + +Per request, this content is kept under `doc/` (not in Wiki pages). --- -### 1.6 `BulkInsertProductsAsync` +## 1) Current Worker Topology (Observed in Code) -| Test Name | Arrange | Assert | -|-----------|---------|--------| -| `BulkInsert_CallsAddRangeAsync_InsideTransaction` | Transaction invokes delegate | `AddRangeAsync` called with 3 entities | -| `BulkInsert_MapsAllRequests_ToEntities` | Capture arg on `AddRangeAsync` | Each entity has correct Name, Ticker, OriginPrice | +### 1.1 Recurring jobs (Hangfire) ---- +Registered in `InventoryManagementSystem/InventoryAlert.Worker/Hosting/JobSchedulerService.cs`: -### 1.7 `GetPriceLossAlertsAsync` +- `sync-prices` → `SyncPricesJob.ExecuteAsync` +- `sync-metrics` → `SyncMetricsJob.ExecuteAsync` +- `sync-earnings` → `SyncEarningsJob.ExecuteAsync` +- `sync-recommendations` → `SyncRecommendationsJob.ExecuteAsync` +- `sync-insiders` → `SyncInsidersJob.ExecuteAsync` +- `news-sync` → `NewsSyncJob.ExecuteAsync` +- `cleanup-prices` → `CleanupPriceHistoryJob.ExecuteAsync` -| Test Name | Arrange | Assert | -|-----------|---------|--------| -| `PriceLoss_ReturnsEmpty_WhenNoProducts` | Repo `[]` | Empty | -| `PriceLoss_SkipsProduct_WhenFinnhubReturnsNull` | 1 product; Finnhub → `null` | Empty | -| `PriceLoss_SkipsProduct_WhenCurrentPriceIsZero` | Finnhub → `{ CurrentPrice = 0 }` | Empty | -| `PriceLoss_ReturnsAlert_WhenDropExceedsThreshold` | OriginPrice=100, Threshold=0.1; Quote=85 (15% drop > 10%) | 1 alert; `PriceChangePercent=0.15`; `PriceDiff=-15` | -| `PriceLoss_DoesNotAlert_WhenDropBelowThreshold` | OriginPrice=100, Threshold=0.2; Quote=90 (10% < 20%) | Empty | -| `PriceLoss_AlertsMapsAllFields_Correctly` | Above scenario | All 8 fields on `PriceLossResponse` match expected | +### 1.2 SQS processing (native BackgroundService) ---- +`InventoryManagementSystem/InventoryAlert.Worker/Hosting/SqsListenerService.cs` runs a continuous polling loop (gated by `WorkerSettings.IsPollMessage`), delegating to: -### 1.8 `SyncCurrentPricesAsync` +- `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` + - long-polls SQS via `ISqsHelper.ReceiveMessagesAsync` + - runs Redis dedup (`SET NX`) + cooldown logic + - routes to `IIntegrationMessageRouter` -| Test Name | Arrange | Assert | -|-----------|---------|--------| -| `Sync_SkipsProduct_WhenFinnhubReturnsNull` | Product CurrentPrice=50; Finnhub `null` | `CurrentPrice` still 50 | -| `Sync_UpdatesCurrentPrice_WhenValidQuote` | Finnhub → `CurrentPrice=75` | Product entity mutated to 75 before `UpdateRangeAsync` | -| `Sync_CallsUpdateRangeAsync_InsideTransaction` | same | `UpdateRangeAsync` called once inside transaction | +### 1.2.1 DLQ + retry behavior (what happens today when a message fails?) ---- +This clarifies the **actual runtime behavior** when the Worker polls SQS and message handling fails. -## 2. `ProductsControllerTests.cs` +**SQS-side retry/DLQ mechanics (in general)** -**SUT**: `ProductsController` | **Layer**: Web (pure unit, no HTTP pipeline) +- Each time a message is received but **not deleted**, SQS will make it visible again after the **queue `VisibilityTimeout`**. +- SQS tracks a delivery counter (`ApproximateReceiveCount`). +- If the main queue is configured with a **RedrivePolicy** (DLQ + `maxReceiveCount`), then once the counter exceeds that value, SQS will move the message to the **DLQ** and it will no longer be delivered to consumers from the main queue. -### Mocks -```csharp -Mock _service = new(); -_sut = new ProductsController(_service.Object); -``` +Local/dev evidence (Moto init script): -### 2.1 `GetProducts` -| Test | Assert | -|------|--------| -| `GetProducts_Returns200_WithList` | `OkObjectResult` with 2 items | +- `InventoryManagementSystem/SolutionFolder/moto-init/init-all.sh` creates: + - `event-queue` with `VisibilityTimeout=30s` and `RedrivePolicy.maxReceiveCount=3` + - `inventory-event-dlq` as the DLQ target -### 2.2 `GetProductById` -| Test | Assert | -|------|--------| -| `GetById_Returns200_WhenFound` | `OkObjectResult` | -| `GetById_Returns404_WhenNotFound` | `NotFoundResult` | +**Worker-side behavior (current code)** -### 2.3 `CreateProduct` -| Test | Assert | -|------|--------| -| `Create_Returns201CreatedAtAction` | `CreatedAtActionResult`; ActionName=""GetProductById""; RouteValues[""id""]=5 | +- Polling: `SqsHelper.ReceiveMessagesAsync` long-polls (`WaitTimeSeconds=20`) and requests system attributes including `ApproximateReceiveCount`. + - File: `InventoryManagementSystem/InventoryAlert.Worker/Utilities/SqsHelper.cs` +- Delete-on-success: `ProcessQueueJob.ProcessBatchAsync` deletes the message **only when** `DispatchInternalAsync(...)` returns `success=true`. + - File: `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` +- On handler exception, `DispatchInternalAsync(...)` returns `false` → message is **not deleted** → SQS will retry after `VisibilityTimeout`. + - This is the intended “retry by redelivery” mechanism. -### 2.4 `UpdateProduct` -| Test | Assert | -|------|--------| -| `Update_Returns200_WhenSuccessful` | `OkObjectResult` | -| `Update_Propagates_KeyNotFoundException` | Exception propagates unswallowed | +**Important caveat: current Redis dedup logic effectively cancels retries after the first failure** -### 2.5 `UpdateStockCount` -| Test | Assert | -|------|--------| -| `UpdateStock_Returns404_WhenProductNotFound` | `NotFoundResult`; `UpdateProductAsync` never called | -| `UpdateStock_CallsUpdate_WithNewStockCount` | `UpdateProductAsync` called with `StockCount==10`; other fields from existing product preserved | -| `UpdateStock_Returns200_WhenSuccessful` | `OkObjectResult` | +In `DispatchInternalAsync(...)` the Worker sets a Redis “processed” key **before** executing the router/handler: -### 2.6 `DeleteProduct` -| Test | Assert | -|------|--------| -| `Delete_Returns204_WhenDeleted` | `NoContentResult` | -| `Delete_Returns404_WhenNotFound` | `NotFoundResult` | +- `dedupKey = msg:processed:{envelope.MessageId}` +- It is written with TTL 30 minutes using `SET NX`. -### 2.7 `BulkInsertProducts` -| Test | Assert | -|------|--------| -| `BulkInsert_Returns204_Always` | `NoContentResult` | +If handling then throws: -### 2.8 `GetPriceLossAlerts` -| Test | Assert | -|------|--------| -| `PriceAlerts_Returns200_WithAlerts` | `OkObjectResult` with 2 items | +- The method returns `false` (so SQS will redeliver), +- but on redelivery the dedup key already exists, so the Worker treats the message as a duplicate and returns `true` (ACK), which deletes it from the main queue. ---- +Net effect (today): -## 3. `GenericRepositoryTests.cs` +- “Retry” happens at most once (a redelivery), but the Worker will usually **ACK the redelivery without re-processing**, so the message is effectively **dropped** after the first failure. +- Because the message gets deleted on that redelivery, it may never reach the DLQ even if the queue has a redrive policy. -**SUT**: `GenericRepository` | **Layer**: Infrastructure -**Requires**: `Microsoft.EntityFrameworkCore.InMemory` +**Additional caveat: manual receive-count cutoff is inconsistent with DLQ** -```csharp -AppDbContext CreateContext() => - new(new DbContextOptionsBuilder() - .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); -``` +`ProcessQueueJob` contains a hard-coded cutoff: -| Test | Assert | -|------|--------| -| `AddAsync_PersistsEntity_AndReturnsIt` | Entity in DB; returned entity matches values | -| `GetByIdAsync_ReturnsEntity_WhenExists` | Correct product returned | -| `GetByIdAsync_ReturnsNull_WhenNotExists` | `null` | -| `GetAllAsync_ReturnsAllEntities` | 3 items returned | -| `UpdateAsync_MutatesEntity` | DB reflects new Name after SaveChanges | -| `DeleteAsync_RemovesEntity` | Entity gone after SaveChanges | -| `AddRangeAsync_AddsAllEntities` | 3 entities persisted | +- if `ApproximateReceiveCount > 5` it logs a warning and returns `true` (ACK/delete). ---- +This is not aligned with the dev queue redrive policy (`maxReceiveCount=3`), and if the queue has a DLQ configured, deleting the message at high receive count prevents SQS from redriving it to DLQ (message is removed instead). -## 4. `ProductFixtures.cs` — Shared Builders +**What to expect operationally** -```csharp -public static class ProductFixtures -{ - public static Product BuildProduct( - int id = 1, string name = ""Test"", string ticker = ""TST"", - decimal originPrice = 100m, decimal currentPrice = 90m, - double threshold = 0.2, int stock = 10) => new() - { - Id = id, Name = name, TickerSymbol = ticker, - OriginPrice = originPrice, CurrentPrice = currentPrice, - PriceAlertThreshold = threshold, StockCount = stock - }; +- If a message fails due to a transient downstream error, you currently may not get automatic retries; it can be lost due to Redis dedup behavior. +- DLQ will only reliably capture poison messages if the Worker allows them to be retried/redriven (i.e., does not delete them early). - public static ProductRequest BuildRequest( - string name = ""Test"", string ticker = ""TST"", - decimal originPrice = 100m, decimal currentPrice = 90m, - double threshold = 0.2, int stock = 10) => new() - { - Name = name, TickerSymbol = ticker, - OriginPrice = originPrice, CurrentPrice = currentPrice, - PriceAlertThreshold = threshold, StockCount = stock - }; +**Recommended target behavior (so retries + DLQ are meaningful)** - public static FinnhubQuoteResponse BuildQuote(decimal currentPrice = 90m) => - new() { CurrentPrice = currentPrice }; -} -``` +- Let SQS manage retries: + - On failure: do **not** delete the message. + - On success: delete the message. + - Configure `VisibilityTimeout` and `RedrivePolicy.maxReceiveCount` to match desired retry cadence. +- Move “processed/dedup” markers to **after** successful processing, or store a separate “in-flight” key with a short TTL that doesn’t suppress redelivery attempts. + - Rule of thumb: never let dedup turn a failure into a successful ACK. +- Avoid manual “receiveCount cutoff → ACK” unless you explicitly persist the failed payload somewhere (DynamoDB / DB / blob) before deleting it. + - If you want a manual cutoff, prefer: on cutoff → emit a “dead-lettered” event / persist diagnostics → then delete. +- Decide (and document) the retry policy knobs as configuration: + - `MaxReceiveCount` (DLQ threshold) + - `VisibilityTimeoutSeconds` + - `BackoffStrategy` (if using `ChangeMessageVisibility` to slow down hot-failing messages) ---- +**DLQ operations (today)** -## 5. NuGet Packages to Add +- The Worker polls only the main queue (`event-queue`). Messages in the DLQ (`inventory-event-dlq`) will sit until a human/tool inspects or redrives them. +- In local dev (Moto), you can inspect DLQ messages with AWS CLI (same endpoint used in `moto-init`): -```xml - - - +```bash +aws sqs receive-message --queue-url ""$(aws sqs get-queue-url --queue-name inventory-event-dlq --endpoint-url http://moto:5000 --query 'QueueUrl' --output text)"" --endpoint-url http://moto:5000 ``` -> Already present: `Moq`, `xunit`, `Microsoft.AspNetCore.Mvc.Testing`, `coverlet.collector` +- Retrying a DLQ message typically means “redrive” back to the source queue (AWS console has a Redrive UI) or manually `SendMessage` back to `event-queue` after you’ve fixed the root cause. ---- +### 1.3 Unused / not wired (needs decision) -## 6. Implementation Priority +Found in code but not referenced: -| Priority | Test Class | Reason | -|----------|-----------|--------| -| 🔴 P0 | `ProductServiceTests` | Core business logic; highest risk area | -| 🟠 P1 | `ProductsControllerTests` | HTTP contract; catches routing & binding issues | -| 🟡 P2 | `GenericRepositoryTests` | EF Core integration safety net | +- `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SqsScheduledPollerJob.cs` (Hangfire-style single-shot poller) +- `InventoryManagementSystem/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs` (Hangfire failure/retry logging filter) ---- +Recommendation: pick one supported polling strategy (native BackgroundService OR Hangfire poller) and wire/remove the other to reduce confusion. -## 7. Coverage Targets +Also present but unused today: -| Layer | Line Coverage | -|-------|--------------| -| Application/Services | ≥ 90% | -| Web/Controllers | ≥ 85% | -| Infrastructure/Repositories | ≥ 80% | -| Infrastructure/Workers | Integration test scope — out of this plan |",282,cf83050ca0b6acae1337f171d1fb1c14,doc\archive\unit_test_plan.md,0,361,"test, assert, entity, name, product, returns, null, repo",1775670503.9293694,1,xunit igenericrepository stock price unit test stock data access arrange act assert efcore googl inventory verify notification commit fluentassertions httpput returns async iactionresult moq hosted service price drop appdbcontext savechanges atomicity iproductrepository threshold entity framework aapl productscontroller sku rollback application service quote backgroundservice mock setup business logic market data savechangesasync times once periodictimer asnotracking finnhubpricesyncworker symbol unitofwork loss httppost iunitofwork item external api productservice httpget msft stock ticker dbset executetransactionasync iproductservice dbcontext,# Unit Test Plan — InventoryAlert.Api | Unit Test Plan — InventoryAlert.Api > Stack: xUnit · Moq · FluentAssertions (add -doc,"# Hackathon Challenge: The Perfect API +- `InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs` +- `InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskProcessor.cs` -**Theme:** Design, build, and deploy the ""perfect"" REST API based on industry best practices. +These implement a C# internal work queue (`System.Threading.Channels`) pattern, but there is currently no producer calling `QueueBackgroundWorkItemAsync`, so SQS processing is **not** using the internal queue. -**Duration:** 1 Day +--- -**Technology Stack:** C# with ASP.NET Core Web API +## 2) Event Flow: Known Mismatches / Risks -### **Overview** +### 2.1 Message contract mismatch: `EventEnvelope` vs raw payload -Welcome, developers! Your challenge today is not just to build a functional API, but to build a *well-designed* one. We're moving beyond complex business logic to focus purely on the **technical principles** that make APIs scalable, maintainable, and a pleasure to use. +`ProcessQueueJob` deserializes `message.Body` as `EventEnvelope`: -The provided diagram on REST API Design is your guide and your rulebook. The team that best implements the core principles and features shown in the diagram will be the winner. +- `InventoryManagementSystem/InventoryAlert.Domain/Events/EventEnvelope.cs` +- `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs` -### **The Challenge** +But `IntegrationMessageRouter` currently: -To sharpen the focus on technical implementation over business logic, this challenge is centered around a **single entity**. You still have two options to choose from: +- expects `message.MessageAttributes[""MessageType""]` +- deserializes `message.Body` directly into handler payload models -1. **Greenfield Project (Build from Scratch):** - - Build a **URL Shortener API**. - - The core resource is a ""shortened URL"" which has an original URL, a generated short code, a creation date, and a click count. - - Your goal is to design the API endpoints for creating, retrieving, listing, and deleting these URLs from the ground up, following REST principles. Think about how to handle the redirect logic for a short code. -2. **Brownfield Project (Refactor an Existing App):** - - We will provide you with a sample .NET project for a simple ""To-Do List"" API (with just one ""Todo"" entity) that is poorly designed and non-RESTful. - - Your task is to refactor this ""legacy"" API, correct its flaws, and implement proper RESTful design patterns. You will need to fix endpoint naming, use HTTP methods correctly, implement proper status codes, and add essential features. +File: `InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs` -### **Judging Criteria & Scoring** +Risk: -Your project will be judged based on how many concepts from the REST API Design diagram you successfully implement. +- routing can fail even when SQS contains valid `EventEnvelope` bodies. -**Core Principles (Max 40 points):** +### 2.2 SQS message attributes are not requested in the poller -- **Uniform Interface (15 pts):** Are your resources clearly identified? Are your endpoints resource-based (e.g., `/api/urls/{id}`)? Are you using self-descriptive messages (e.g., correct JSON media types and HTTP status codes)? -- **Stateless (10 pts):** Does each request from the client contain all the information needed to understand and process it? The server should not store any client context between requests. -- **Client-Server (10 pts):** Is there a clear separation of concerns between the UI (client) and the data storage (server)? -- **Cacheable (5 pts):** Have you implemented caching headers (like `ETag` or `Cache-Control`) on appropriate GET endpoints? +`InventoryManagementSystem/InventoryAlert.Worker/Utilities/SqsHelper.cs` requests system attributes only: -**Methods & Endpoints (Max 20 points):** +- `MessageSystemAttributeNames = [""ApproximateReceiveCount"", ""SentTimestamp""]` +- does not request `MessageAttributeNames` -- **Correct HTTP Method Usage (20 pts):** - - `GET`: Retrieve resources. - - `POST`: Create new resources. - - `PUT`: Replace an existing resource entirely. - - `PATCH`: Partially update an existing resource. - - `DELETE`: Remove a resource. - - Are your methods idempotent where they should be (GET, PUT, DELETE)? +Risk: -**Connectedness & Advanced Features (Max 40 points):** +- attribute-based routing won’t work reliably even if attributes exist. -- **Pagination (10 pts):** For endpoints that return a list of resources, have you implemented paging (e.g., using `?page=1&pageSize=10`)? -- **Filtering & Ordering (10 pts):** Can clients filter or sort the results (e.g., `?clicks=0&sortBy=created_desc`)? -- **Versioning (5 pts):** How are you handling API versioning (e.g., `/api/v1/urls`)? -- **Security & Auth (5 pts):** Have you implemented basic security measures? This could be API Key authentication, JWT, or another simple auth mechanism. -- **HATEOAS (Hypermedia) (5 pts):** Do your resource representations include links to related actions or resources? (This is a key principle for a ""perfect"" API). -- **Input Validation (5 pts):** Are you validating incoming data and returning clear `400 Bad Request` errors? +### 2.3 CorrelationId propagation is intended, but fragile -**Bonus (Up to 10 extra points):** +Strengths: -- **Monitoring/Logging:** Basic logging implemented. -- **Documentation:** A simple `README.md` or a generated Swagger/OpenAPI page that is clean and easy to understand. -- **Containerization:** The application is fully runnable via a Dockerfile. +- API stamps `X-Correlation-Id` (`CorrelationIdMiddleware`) +- Worker pushes `CorrelationId` into log scope when it has an envelope (`ProcessQueueJob`) -### **Getting Started** +Risk: -1. Form your teams. -2. Choose your path: Greenfield or Brownfield. -3. Clone the starter repository (if provided for the brownfield option). -4. Design your resource models and API endpoints. **Plan before you code!** -5. Start building! Use the `dotnet new webapi` template to get going quickly. -6. Commit your code regularly. -7. Prepare a short (5-minute) demo for the judges. +- publishing must reliably stamp `EventEnvelope.CorrelationId` (API `EventService` currently doesn’t). -Good luck, and may the best API win!",73,16aed27a12944f551ffc88c2424a06d7,doc\archive\Untitled-1.md,0,362,"your, resource, design, endpoints, build, from, resources, challenge",1759516766.1091347,1,appdbcontext dbset data access igenericrepository asnotracking iproductrepository postgres efcore entity framework postgresql dbcontext compose dockerfile container,"# Hackathon Challenge: The Perfect API | Hackathon Challenge: The Perfect API Theme: Design, build, and deploy the ""perfe" -doc,"# Project Wiki Implementation Plan +--- -This plan outlines the structure and content for a centralized Wiki/Documentation repository designed to onboarding new developers, provide clarity for users, and optimize context for AI coding agents. +## 3) Enhancement Plan (Recommended) -## 1. Goal -Create a single source of truth that defines the technical and functional landscape of the **InventoryAlert** ecosystem. +### Chosen direction (per preference): Option C — SQS retries + DLQ, with Hangfire DLQ reprocessor ---- +Primary goal: -## 2. Wiki Structure (The ""Knowledge Map"") +- Let **SQS** handle automatic retries and DLQ routing (visibility timeout + redrive policy). +- Use **Hangfire Dashboard** to manage *manual recovery* by running a **DLQ reprocessor/redrive job** you can retry from the UI. -### 📂 01. Tech Stack & Environment -- **Backend**: .NET 10, C# 12, Entity Framework Core 10, Npgsql. -- **Frontend**: Next.js 15, TypeScript, Tailwind CSS (v4), React Server Components. -- **Infrastructure**: PostgreSQL, Seq (Logging), Hangfire (Scheduler), SNS/SQS (Event Bus), Docker. -- **Tools**: VS Code/Visual Studio, BM25 Search (Agent), GitHub Actions. +What this gives you: -### 🏛️ 02. Architecture (The ""Blueprints"") -- **Conceptual Model**: Domain-Driven Design (DDD) + Clean Architecture. -- **Layering**: - - **Web (Api)**: Controllers, Middleware, Auth. - - **Application**: Use Cases, Services, DTOs, Mappings. - - **Domain**: Entities, Interfaces, Exceptions, Constants. - - **Infrastructure**: Repositories, DB Context, External Clients (Finnhub). - - **Worker**: Background processors, Event consumers. +- Automatic retries remain “queue-native”. +- Operators get a reliable “button” in Hangfire to re-run recovery tasks (redrive/replay batches from DLQ after a fix). -### 💾 03. Data Model (The ""Schema"") -- **Core Entities**: `User`, `Product`, `WatchlistItem`, `AlertRule`, `PriceHistory`. -- **Database**: PostgreSQL schema definitions and relationship maps. -- **Worker Data**: DynamoDB/Local cache entities for price/news tracking. +### P0 — Make event handling deterministic (one contract, one router) -### 🔄 04. Execution Flows (The ""Sequences"") -- **Authentication**: JWT issues, Token Storage, Protected Routes. -- **Alert Lifecycle**: - 1. Rule defined in UI. - 2. Event triggered (Manual or Timer). - 3. Worker processes Price/News. - 4. Evaluates rule conditions. - 5. Dispatches alert (Telegram/Log). -- **Price Sync**: Scheduled tasks vs. Manual triggers. +Goal: -### ⚙️ 05. Background Jobs (The ""Engine"") -- **Hangfire Dashboard**: How to monitor internal scheduled tasks. -- **Scheduled Workers**: `FinnhubPricesSyncWorker`, `MarketStatusWorker`. -- **Queue System**: SQS message processing patterns. +- SQS body is always `EventEnvelope` JSON +- Worker routes by `envelope.EventType` +- Worker deserializes `envelope.Payload` +- message attributes are optional (debug / filtering), not required for correctness -### 🛠️ 06. Developer Guide (The ""Onboarding"") -- **Local Setup**: `docker compose up`, `dotnet run`, `npm dev`. -- **Coding Standards**: SOLID, Primary Constructors, Async/Await rules. -- **Testing**: xUnit, Moq, Integration test patterns. +### P0 — Ensure correlation is end-to-end (search by one id) -### 🤖 07. AI Agent Optimization (The ""Context"") -- **Knowledge items (KIs)**: Repository-specific patterns (e.g., Transaction Capture Pattern). -- **Workflows**: `feature-flow`, `add-entity`, `db-migration` instructions. -- **Corpus Mapping**: How to search effectively using BM25. +Goal: searching Seq by `CorrelationId` shows: ---- +1) API request +2) publish log +3) Worker consumption +4) handler logs -## 3. Implementation Phases +### P1 — Improve job operability (Hangfire) -| Phase | Content focus | Output | -| :--- | :--- | :--- | -| **Phase 1** | **Foundation** | Architecture, Tech Stack, Local Setup. | -| **Phase 2** | **Technical Core** | Data Model, Controllers, Repositories. | -| **Phase 3** | **Dynamic Flows** | Alert Flow, Worker Jobs, Event Bus. | -| **Phase 4** | **AI Layer** | Knowledge Items, Workflow documentation. | +Goal: ---- +- Wire `HangfireJobLoggingFilter` globally so failures/retries are logged consistently. +- Standardize job logs (`JobName`, `ElapsedMs`, `Succeeded`, `ItemsProcessed`, `CorrelationId` when event-triggered). -## 4. Maintenance Strategy -- **Doc-as-Code**: Keep all markdown files in `docs/wiki/` within the main repository. -- **Sync Routine**: Update the wiki as part of the `feature-flow` cleanup.",72,0e3d1bd474a65b920c064e59ad5aa7fa,doc\archive\wiki_project_plan.md,0,363,"wiki, phase, event, worker, repository, context, knowledge, core",1775670503.9378276,1,productservice periodictimer quote database update market data sku data access container domain driven design commit dbcontext inventory fluentassertions threshold arrange act assert httpput unitofwork savechanges stock dockerfile productscontroller iproductrepository iactionresult httpget httppost postgresql item external api loss igenericrepository hosted service unit test atomicity notification efcore migration postgres application layer domain entity rollback appdbcontext finnhubpricesyncworker stock price efcore business logic asnotracking schema change infrastructure iproductservice application service add-migration backgroundservice dbset entity framework price drop compose xunit,# Project Wiki Implementation Plan | Project Wiki Implementation Plan This plan outlines the structure and content fo -doc,"# InventoryAlert.Worker — Detailed Implementation Architecture +Add (Option C core): -This diagram details the specific files and methods involved in the background processing ecosystem. +- Introduce a **DLQ reprocessor** Hangfire job (design described below) to: + - inspect DLQ, + - republish/redrive messages back to the main queue, + - record what was replayed (ids + counts), + - and surface failures in Hangfire so the Dashboard “Retry” button is meaningful. -### 1. High-Detail Flow Diagram +### P1 — Make DLQ actually capture failures (don’t ACK failures accidentally) -```mermaid -graph TD - subgraph Host [""Host Layer""] - PRG[Program.cs] --> |Register| NSW[NativeSqsWorker.cs] - PRG --> |Register| QHS[QueuedHostedService.cs] - PRG --> |Register| JSS[JobSchedulerService.cs] - end +Goal: if a message keeps failing, it should naturally reach DLQ; if it succeeds, ACK/delete it. - subgraph NativeFlow [""Path B: Native SQS (Real-time)""] - NSW --> |ExecuteAsync| PQJ[ProcessQueueJob.cs] - PQJ --> |ExecuteAsync Loop| SHP[SqsHelper.cs] - SHP --> |ReceiveMessagesAsync| SQS((Amazon SQS)) - PQJ --> |ProcessBatchAsync| DISP[SqsDispatcher.cs] - end +Key changes required (because current behavior can drop messages before DLQ): - subgraph HangfireFlow [""Path A: Hangfire (Scheduled)""] - JSS --> |StartAsync| RJG[IRecurringJobManager] - RJG --> |AddOrUpdate| HFDB[(Hangfire Storage)] - HFDB --> |Trigger| PSJ[PollSqsJob.cs] - PSJ --> |ExecuteAsync| SHP - PSJ --> |ProcessBatchAsync| DISP - end +- Ensure “dedup/processed” markers never convert a failure into a successful ACK. + - Today Redis `msg:processed:{MessageId}` is written before processing and can cause the first redelivery to be ACK’d as a “duplicate”. +- Remove/align the manual cutoff that ACKs messages by `ApproximateReceiveCount`. + - The queue redrive policy already controls the cutoff (`maxReceiveCount`). + - If you keep a manual cutoff, treat it as “move to DLQ / persist diagnostics”, not “delete silently”. - subgraph CoreLogic [""Core Processing Engine""] - DISP --> |DispatchAsync| DDP[Redis: Atomic Dedup] - DDP --> |Unique| CLD[Price Alert Cooldown] - CLD --> |Allow| PROC[MessageProcessor.cs] - PROC --> |ProcessMessageAsync| HAND[Integration Handlers] - HAND --> |HandleAsync| RES[(DynamoDB / DB)] - end +### P1 — Make concurrency & rate limits configurable - subgraph Handlers [""Integration Handlers""] - HAND --- NH[NewsHandler.cs] - HAND --- PH[PriceAlertHandler.cs] - HAND --- SLH[StockLowHandler.cs] - end +Goal: - subgraph InMemFlow [""Path C: In-Memory Task Queue""] - QHS --> |ExecuteAsync| BTQ[IBackgroundTaskQueue] - BTQ --> |DequeueAsync| WORK[Func Task] - WORK --> |Invoke| LOG[(Audit Logs / Sync)] - end +- Move hard-coded `MaxDegreeOfParallelism = 5` into config (`WorkerSettings`). +- Define backoff for Finnhub 429/5xx. +- Avoid logging large payloads by default (log excerpt + ids). - style Host fill:#f5f5f5,stroke:#333 - style NativeFlow fill:#fff0f5,stroke:#db7093,stroke-width:2px - style HangfireFlow fill:#e6f3ff,stroke:#4682b4,stroke-width:2px - style CoreLogic fill:#f0fff0,stroke:#2e8b57,stroke-width:2px - style MemoryQueue fill:#ffffff,stroke:#666,stroke-dasharray: 5 5 -``` +### P2 — Clarify supported polling strategy -### 2. SQS Dispatch Sequence +Goal: + +- Decide between native `SqsListenerService` vs `SqsScheduledPollerJob`. +- Document the chosen strategy and remove ambiguity. + +--- + +## 4) Golden Path (Target) ```mermaid sequenceDiagram - participant SQS as Amazon SQS - participant Job as Job / Poller - participant Help as SqsHelper - participant Disp as SqsDispatcher - participant Redis as Redis / Cache - participant Proc as MessageProcessor - participant Final as IntegrationHandler + participant UI as UI + participant API as InventoryAlert.Api + participant SNS as SNS Topic + participant SQS as SQS Queue + participant DLQ as DLQ + participant W as InventoryAlert.Worker + participant H as Handler/Job + participant HF as Hangfire (DLQ Reprocessor) - Job->>Help: ReceiveMessagesAsync(queueUrl) - Help->>SQS: SDK: ReceiveMessageAsync - SQS-->>Help: List - Help-->>Job: List - - Job->>Disp: ProcessBatchAsync(messages) - loop Each Message in Batch - Disp->>Disp: TryDeserializeEnvelope - - alt Deserialize Success - Disp->>Redis: Atomic Dedup (StringSetAsync) - alt Is Unique - opt EventType == MarketPriceAlert - Disp->>Redis: Cooldown Check (IsSupressedAsync) - end - - alt Not Supressed - Disp->>Proc: ProcessMessageAsync(message) - Proc->>Final: HandleAsync(payload) - Final-->>Proc: Complete - Proc-->>Disp: Handled - Disp->>Redis: Set Key Expiration (48h) - Disp->>SQS: DeleteMessageAsync (on success) - end - end - else Bad JSON - Disp-->>SQS: DeleteMessageAsync (Ack & Drop) - end + UI->>API: POST /api/v1/events (command) + API->>API: Stamp CorrelationId (X-Correlation-Id) + API->>SNS: Publish EventEnvelope { EventType, Payload, CorrelationId, MessageId } + SNS-->>SQS: Fanout delivery + W->>SQS: Long poll + W->>W: Deserialize EventEnvelope + W->>W: Dedup/lock + scope CorrelationId + W->>H: Route by EventType (deserialize Payload) + H-->>W: Logs with CorrelationId + + alt Handler fails repeatedly + W-->>SQS: No delete (retry via redelivery) + SQS-->>DLQ: After maxReceiveCount -> move to DLQ + HF->>DLQ: Poll / read batch + HF->>SQS: Republish or redrive back to main queue + HF-->>HF: If job fails -> Hangfire dashboard retry end ``` -### Component & Method Registry +--- -| File Name | Method | Purpose | -| :--- | :--- | :--- | -| **NativeSqsWorker.cs** | `ExecuteAsync` | Initiates the native polling implementation during app startup. | -| **ProcessQueueJob.cs** | `ExecuteAsync` | Runs an infinite `while(!ct.IsCancellationRequested)` loop for SQS. | -| **SqsHelper.cs** | `ReceiveMessagesAsync` | Low-level AWS SDK call to fetch messages from an SQS URL. | -| **SqsDispatcher.cs** | `Batch / Dispatch` | Orchestrates batch processing, de-duplication, and cooldown logic. | -| **MessageProcessor.cs** | `ProcessMessageAsync`| Logic for routing a raw SQS body to a typed C# event handler. | -| **JobSchedulerService.cs**| `StartAsync` | One-time registration of recurring Hangfire jobs into persistent storage. | -| **QueuedHostedService.cs** | `ExecuteAsync` | Continuous consumer of the internal `IBackgroundTaskQueue`. | +## 4.1 Option C — DLQ reprocessor job (recommended spec) -> [!IMPORTANT] -> **Path B (Native)** is the most efficient for production as it utilizes ""Long Polling"" (`WaitTimeSeconds=20`), which stays connected to AWS until a message is available, significantly reducing SDK overhead compared to the Hangfire trigger.",113,93ba2f9aa758cddbdd10d485e3d33cc5,doc\archive\worker_flow_diagram.md,0,364,"executeasync, implementation, diagram, processing, dispatch, method, native, polling",1775805608.0369725,1,asnotracking loss notification business logic hosted service appdbcontext finnhubpricesyncworker productservice item threshold dbcontext efcore entity framework backgroundservice stock application service periodictimer sku inventory price drop iproductservice,# InventoryAlert.Worker — Detailed Implementation Architecture | InventoryAlert.Worker — Detailed Implementation Architecture This diagram detail +This is the missing piece that makes “retry via Hangfire Dashboard” practical without forcing Hangfire to own the main SQS consumption loop. + +### What the job does + +Hangfire job example names: + +- `dlq-reprocess` (recurring) — periodically scans DLQ and replays safe messages +- `dlq-redrive-once` (manual) — one-off job to replay `N` messages when an operator clicks “Enqueue” + +Operational responsibilities: + +- Pull a bounded batch from DLQ (e.g., `max=10..50`). +- For each message: + - validate it’s an `EventEnvelope` and extract `MessageId`, `EventType`, `CorrelationId` + - optionally check a “replay allowlist” (which event types are safe to replay) + - republish back to the main queue (or publish back to SNS depending on your desired fanout semantics) + - write an audit log entry (Seq + optional DB/Dynamo row) with replay metadata + - delete from DLQ only after successful republish (or keep in DLQ and mark “attempted”) + +### What “Retry” means in Hangfire + +- If the DLQ reprocessor job fails (AWS outage, invalid payloads, permission issue), Hangfire marks the job as failed. +- An operator can click “Retry” in Hangfire Dashboard to rerun the recovery job. +- This is a **job-level retry** (re-run the recovery operation), not a direct per-message retry button inside Hangfire. If you need per-message selection, add parameters (eventType filter, messageId list, max batch size) and expose them via a small admin endpoint or a dashboard command pattern. + +### Recommended guardrails + +- Don’t create replay storms: + - cap batch size per run + - introduce a replay delay/backoff + - record replay attempts per message id to prevent infinite loops +- Preserve traceability: + - keep original `CorrelationId` + - emit a new `ReplayId` / `ReprocessAttemptId` for recovery runs + + +## 5) Wiki doc drift notes (for later cleanup) + +Wiki docs currently contain both current and legacy naming/flow descriptions (job naming, routing assumptions). Recommend keeping Wiki pages “how to use” oriented and referencing this `doc/` review for deeper refactor plans.",337,af2cebc4f95126d5c1d8ee9aa64a32bf,doc\archive\worker_jobs_and_event_flow_review.md,0,382,"worker, message, hangfire, queue, inventorymanagementsystem, retry, inventoryalert, event",1779851803.7578456,10,efcore entity framework notification price drop hosted service market data finnhubpricesyncworker threshold backgroundservice asnotracking external api productservice periodictimer dbcontext appdbcontext stock price business logic loss iproductservice quote application service,# Worker Jobs & Event Flow (Review + Enhancements) | Worker Jobs & Event Flow (Review + Enhancements) This document contains review f doc,"# .NET CLI Quick Reference This guide provides the essential commands to build, manage, and run the **Automated Inventory Alert System** project, including solution and test project setup. @@ -17873,11 +19906,11 @@ This guide provides the essential commands to build, manage, and run the **Autom ## 🏗️ 1. Project Initialization (Solution & API) Create the solution and a new Web API project with Controllers: -```bash",8,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,365,"project, solution, quick, reference, guide, provides, essential, commands",1776074395.6112125,1,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,"# .NET CLI Quick Reference | .NET CLI Quick Reference This guide provides the essential commands to build, ma" +```bash",8,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,383,"project, solution, quick, reference, guide, provides, essential, commands",1776074395.6112125,1,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,"# .NET CLI Quick Reference | .NET CLI Quick Reference This guide provides the essential commands to build, ma" doc,"# Create the Solution -dotnet new sln -n InventoryManagementSystem",11,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,366,"create, solution, dotnet, inventorymanagementsystem",1776074395.6112125,9,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Create the Solution | Create the Solution dotnet new sln -n InventoryManagementSystem +dotnet new sln -n InventoryManagementSystem",11,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,384,"create, solution, dotnet, inventorymanagementsystem",1776074395.6112125,9,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Create the Solution | Create the Solution dotnet new sln -n InventoryManagementSystem doc,"# Create the API Project -dotnet new webapi -n InventoryAlert.Api -o InventoryAlert.Api --use-controllers --no-https",14,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,367,"inventoryalert, create, project, dotnet, webapi, controllers, https",1776074395.6112125,12,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Create the API Project | Create the API Project dotnet new webapi -n InventoryAlert.Api -o InventoryAlert +dotnet new webapi -n InventoryAlert.Api -o InventoryAlert.Api --use-controllers --no-https",14,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,385,"inventoryalert, create, project, dotnet, webapi, controllers, https",1776074395.6112125,12,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Create the API Project | Create the API Project dotnet new webapi -n InventoryAlert.Api -o InventoryAlert doc,"# Add API Project to Solution dotnet sln add InventoryAlert.Api/InventoryAlert.Api.csproj ``` @@ -17885,13 +19918,13 @@ dotnet sln add InventoryAlert.Api/InventoryAlert.Api.csproj ## 🧪 2. Unit Testing Setup Add a separate test project and link it to the API: -```bash",22,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,368,"inventoryalert, project, solution, dotnet, csproj, bash",1776074395.6112125,15,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Add API Project to Solution | Add API Project to Solution dotnet sln add InventoryAlert.Api/InventoryAlert.Api +```bash",22,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,386,"inventoryalert, project, solution, dotnet, csproj, bash",1776074395.6112125,15,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Add API Project to Solution | Add API Project to Solution dotnet sln add InventoryAlert.Api/InventoryAlert.Api doc,"# Create the xUnit Test Project -dotnet new xunit -n InventoryAlert.Tests -o InventoryAlert.Tests",25,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,369,"xunit, inventoryalert, tests, create, test, project, dotnet",1776074395.6112125,23,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Create the xUnit Test Project | Create the xUnit Test Project dotnet new xunit -n InventoryAlert.Tests -o Invent +dotnet new xunit -n InventoryAlert.Tests -o InventoryAlert.Tests",25,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,387,"xunit, inventoryalert, tests, create, test, project, dotnet",1776074395.6112125,23,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Create the xUnit Test Project | Create the xUnit Test Project dotnet new xunit -n InventoryAlert.Tests -o Invent doc,"# Add Test Project to Solution -dotnet sln add InventoryAlert.Tests/InventoryAlert.Tests.csproj",28,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,370,"inventoryalert, tests, test, project, solution, dotnet, csproj",1776074395.6112125,26,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Add Test Project to Solution | Add Test Project to Solution dotnet sln add InventoryAlert.Tests/InventoryAlert. +dotnet sln add InventoryAlert.Tests/InventoryAlert.Tests.csproj",28,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,388,"inventoryalert, tests, test, project, solution, dotnet, csproj",1776074395.6112125,26,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Add Test Project to Solution | Add Test Project to Solution dotnet sln add InventoryAlert.Tests/InventoryAlert. doc,"# Reference the API project from the Test Project -dotnet add InventoryAlert.Tests/InventoryAlert.Tests.csproj reference InventoryAlert.Api/InventoryAlert.Api.csproj",31,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,371,"inventoryalert, reference, project, tests, csproj, from, test, dotnet",1776074395.6112125,29,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Reference the API project from the Test Project | Reference the API project from the Test Project dotnet add InventoryAlert.Tests/ +dotnet add InventoryAlert.Tests/InventoryAlert.Tests.csproj reference InventoryAlert.Api/InventoryAlert.Api.csproj",31,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,389,"inventoryalert, reference, project, tests, csproj, from, test, dotnet",1776074395.6112125,29,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Reference the API project from the Test Project | Reference the API project from the Test Project dotnet add InventoryAlert.Tests/ doc,"# Add Testing Packages (Moq, Mvc.Testing) dotnet add InventoryAlert.Tests/InventoryAlert.Tests.csproj package Moq dotnet add InventoryAlert.Tests/InventoryAlert.Tests.csproj package Microsoft.AspNetCore.Mvc.Testing @@ -17900,15 +19933,15 @@ dotnet add InventoryAlert.Tests/InventoryAlert.Tests.csproj package Microsoft.As ## 📦 3. Dependency Management (Core Packages) Add the required NuGet packages to the API project: -```bash",40,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,372,"inventoryalert, tests, testing, dotnet, csproj, package, packages, microsoft",1776074395.6112125,32,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,"# Add Testing Packages (Moq, Mvc.Testing) | Add Testing Packages (Moq, Mvc.Testing) dotnet add InventoryAlert.Tests/Inventor" +```bash",40,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,390,"inventoryalert, tests, testing, dotnet, csproj, package, packages, microsoft",1776074395.6112125,32,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,"# Add Testing Packages (Moq, Mvc.Testing) | Add Testing Packages (Moq, Mvc.Testing) dotnet add InventoryAlert.Tests/Inventor" doc,"# Navigate to the API project directory -cd InventoryAlert.Api",43,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,373,"navigate, project, directory, inventoryalert",1776074395.6112125,41,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Navigate to the API project directory | Navigate to the API project directory cd InventoryAlert.Api +cd InventoryAlert.Api",43,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,391,"navigate, project, directory, inventoryalert",1776074395.6112125,41,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Navigate to the API project directory | Navigate to the API project directory cd InventoryAlert.Api doc,"# Core PostgreSQL & EF Core Design dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL -dotnet add package Microsoft.EntityFrameworkCore.Design",47,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,374,"core, postgresql, design, dotnet, package, entityframeworkcore, npgsql, microsoft",1776074395.6112125,44,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Core PostgreSQL & EF Core Design | Core PostgreSQL & EF Core Design dotnet add package Npgsql.EntityFrameworkCore.P +dotnet add package Microsoft.EntityFrameworkCore.Design",47,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,392,"core, postgresql, design, dotnet, package, entityframeworkcore, npgsql, microsoft",1776074395.6112125,44,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Core PostgreSQL & EF Core Design | Core PostgreSQL & EF Core Design dotnet add package Npgsql.EntityFrameworkCore.P doc,"# Hangfire for Job Management dotnet add package Hangfire.AspNetCore -dotnet add package Hangfire.PostgreSql",51,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,375,"hangfire, dotnet, package, management, aspnetcore, postgresql",1776074395.6112125,48,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Hangfire for Job Management | Hangfire for Job Management dotnet add package Hangfire.AspNetCore dotnet add pa +dotnet add package Hangfire.PostgreSql",51,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,393,"hangfire, dotnet, package, management, aspnetcore, postgresql",1776074395.6112125,48,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Hangfire for Job Management | Hangfire for Job Management dotnet add package Hangfire.AspNetCore dotnet add pa doc,"# Motor for SNS/SQS (If applicable) dotnet add package Motor.Extensions.Hosting.CloudEvents //TODO: LATER ``` @@ -17916,7 +19949,7 @@ dotnet add package Motor.Extensions.Hosting.CloudEvents //TODO: LATER ## 🗄️ 4. Database Migrations (EF Core) Note: Run these from the project root using `--project`: -```bash",59,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,376,"motor, applicable, dotnet, package, extensions, hosting, cloudevents, todo",1776074395.6112125,52,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Motor for SNS/SQS (If applicable) | Motor for SNS/SQS (If applicable) dotnet add package Motor.Extensions.Hosting.Cl +```bash",59,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,394,"motor, applicable, dotnet, package, extensions, hosting, cloudevents, todo",1776074395.6112125,52,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Motor for SNS/SQS (If applicable) | Motor for SNS/SQS (If applicable) dotnet add package Motor.Extensions.Hosting.Cl doc,"# Create a migration dotnet ef migrations add test --project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api --context InventoryDbContext @@ -17928,11 +19961,11 @@ dotnet ef database update --project InventoryAlert.Infrastructure --startup-proj ## 🛠️ 5. Build, Run, and Test Core development commands: -```bash",71,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,377,"project, inventoryalert, dotnet, infrastructure, startup, context, inventorydbcontext, migrations",1776074395.6112125,60,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Create a migration | Create a migration dotnet ef migrations add test --project InventoryAlert.Infras +```bash",71,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,395,"project, inventoryalert, dotnet, infrastructure, startup, context, inventorydbcontext, migrations",1776074395.6112125,60,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Create a migration | Create a migration dotnet ef migrations add test --project InventoryAlert.Infras doc,"# Build the entire solution -dotnet build",74,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,378,"build, entire, solution, dotnet",1776074395.6112125,72,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Build the entire solution | Build the entire solution dotnet build +dotnet build",74,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,396,"build, entire, solution, dotnet",1776074395.6112125,72,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Build the entire solution | Build the entire solution dotnet build doc,"# Run all tests -dotnet test",77,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,379,"tests, dotnet, test",1776074395.6112125,75,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Run all tests | Run all tests dotnet test +dotnet test",77,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,397,"tests, dotnet, test",1776074395.6112125,75,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Run all tests | Run all tests dotnet test doc,"# Run with Hot Reload (API only) dotnet watch run --project InventoryAlert.Api/InventoryAlert.Api.csproj ``` @@ -17950,7 +19983,7 @@ dotnet list package Build for production: ```bash dotnet publish InventoryAlert.Api/InventoryAlert.Api.csproj -c Release -o ./publish -```",95,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,380,"dotnet, inventoryalert, csproj, bash, publish, reload, only, watch",1776074395.6112125,78,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Run with Hot Reload (API only) | Run with Hot Reload (API only) dotnet watch run --project InventoryAlert.Api/Inv +```",95,32367c933230b518b24f5b7471080675,doc\archive\commands\dotnet-commands.md,0,398,"dotnet, inventoryalert, csproj, bash, publish, reload, only, watch",1776074395.6112125,78,httppost stock item entity framework threshold productscontroller unit test xunit dbcontext database update fluentassertions httpget httpput arrange act assert asnotracking sku notification price drop loss efcore iactionresult inventory efcore migration add-migration appdbcontext schema change,# Run with Hot Reload (API only) | Run with Hot Reload (API only) dotnet watch run --project InventoryAlert.Api/Inv doc,"# 🐳 Docker + Messaging Implementation Plan > Combined from `DOCKER_PLAN.md` and ROADMAP tasks P0-1 and P6-20. @@ -17980,14 +20013,14 @@ Create at `InventoryManagementSystem/.dockerignore`: Create at `InventoryManagementSystem/Dockerfile`: -```dockerfile",30,dce42a0904d286781e6bc0b6422870e9,doc\archive\docker\DOCKER_MESSAGING_PLAN.md,0,381,"step, docker, dockerfile, from, dockerignore, create, inventorymanagementsystem, build",1775670503.9263184,1,hosted service entity framework backgroundservice loss stock msft application service googl business logic efcore migration compose finnhubpricesyncworker container aapl arrange act assert price drop market data inventory schema change efcore appdbcontext symbol stock ticker iproductservice asnotracking dbcontext threshold notification stock price database update fluentassertions periodictimer dockerfile productservice unit test postgresql external api item xunit postgres sku quote add-migration,# 🐳 Docker + Messaging Implementation Plan | 🐳 Docker + Messaging Implementation Plan > Combined from DOCKER_PLAN.md and ROAD +```dockerfile",30,cce5eafc5b36457fe17d29dc68c25640,doc\archive\docker\DOCKER_MESSAGING_PLAN.md,0,399,"step, docker, dockerfile, from, dockerignore, create, inventorymanagementsystem, build",1779851803.9193945,1,asnotracking entity framework dockerfile notification external api symbol hosted service efcore efcore migration inventory fluentassertions periodictimer item sku arrange act assert compose postgres aapl market data appdbcontext quote add-migration business logic postgresql msft stock price stock ticker productservice loss stock xunit container dbcontext unit test application service backgroundservice schema change googl database update threshold iproductservice finnhubpricesyncworker price drop,# 🐳 Docker + Messaging Implementation Plan | 🐳 Docker + Messaging Implementation Plan > Combined from DOCKER_PLAN.md and ROAD doc,"# Stage 1: Build FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY . . RUN dotnet restore ""InventoryAlert.Api/InventoryAlert.Api.csproj"" RUN dotnet publish ""InventoryAlert.Api/InventoryAlert.Api.csproj"" \ - -c Release -o /app/publish",38,dce42a0904d286781e6bc0b6422870e9,doc\archive\docker\DOCKER_MESSAGING_PLAN.md,0,382,"inventoryalert, dotnet, build, csproj, publish, stage, from, microsoft",1775670503.9263184,31,hosted service entity framework backgroundservice loss stock msft application service googl business logic efcore migration compose finnhubpricesyncworker container aapl arrange act assert price drop market data inventory schema change efcore appdbcontext symbol stock ticker iproductservice asnotracking dbcontext threshold notification stock price database update fluentassertions periodictimer dockerfile productservice unit test postgresql external api item xunit postgres sku quote add-migration,# Stage 1: Build | Stage 1: Build FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY + -c Release -o /app/publish",38,cce5eafc5b36457fe17d29dc68c25640,doc\archive\docker\DOCKER_MESSAGING_PLAN.md,0,400,"inventoryalert, dotnet, build, csproj, publish, stage, from, microsoft",1779851803.9193945,31,asnotracking entity framework dockerfile notification external api symbol hosted service efcore efcore migration inventory fluentassertions periodictimer item sku arrange act assert compose postgres aapl market data appdbcontext quote add-migration business logic postgresql msft stock price stock ticker productservice loss stock xunit container dbcontext unit test application service backgroundservice schema change googl database update threshold iproductservice finnhubpricesyncworker price drop,# Stage 1: Build | Stage 1: Build FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY doc,"# Stage 2: Runtime (minimal image) FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final @@ -18128,13 +20161,13 @@ using (var scope = app.Services.CreateScope()) ### Decision: Hangfire vs BackgroundService -| Feature | `BackgroundService` (Current) | Hangfire | -|---|---|---| -| Dashboard UI | ❌ None | ✅ `/hangfire` | -| Retry on failure | ❌ Manual | ✅ Built-in | -| Job history / logs | ❌ Just console logs | ✅ Persistent DB | -| Recurring schedule | ⚠️ PeriodicTimer | ✅ Cron expressions | -| Complexity | ✅ Simple | ⚠️ Needs DB table | +| Feature | `BackgroundService` (Current) | Hangfire | +| ------------------ | ----------------------------- | ------------------ | +| Dashboard UI | ❌ None | ✅ `/hangfire` | +| Retry on failure | ❌ Manual | ✅ Built-in | +| Job history / logs | ❌ Just console logs | ✅ Persistent DB | +| Recurring schedule | ⚠️ PeriodicTimer | ✅ Cron expressions | +| Complexity | ✅ Simple | ⚠️ Needs DB table | **Recommendation:** Keep `BackgroundService` for now. Add Hangfire only when you need the Dashboard or retry management. @@ -18268,7 +20301,7 @@ For local development, use **Moto Server** to emulate AWS SNS/SQS: --- -> **Start with Docker first** — it will make all future testing (including messaging) consistent across machines.",319,dce42a0904d286781e6bc0b6422870e9,doc\archive\docker\DOCKER_MESSAGING_PLAN.md,0,383,"product, ialertnotifier, csharp, scope, cancellationtoken, public, notifyasync, dotnet",1775670503.9263184,39,hosted service entity framework backgroundservice loss stock msft application service googl business logic efcore migration compose finnhubpricesyncworker container aapl arrange act assert price drop market data inventory schema change efcore appdbcontext symbol stock ticker iproductservice asnotracking dbcontext threshold notification stock price database update fluentassertions periodictimer dockerfile productservice unit test postgresql external api item xunit postgres sku quote add-migration,# Stage 2: Runtime (minimal image) | Stage 2: Runtime (minimal image) FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS fi +> **Start with Docker first** — it will make all future testing (including messaging) consistent across machines.",319,cce5eafc5b36457fe17d29dc68c25640,doc\archive\docker\DOCKER_MESSAGING_PLAN.md,0,401,"product, ialertnotifier, csharp, scope, cancellationtoken, public, notifyasync, dotnet",1779851803.9193945,39,asnotracking entity framework dockerfile notification external api symbol hosted service efcore efcore migration inventory fluentassertions periodictimer item sku arrange act assert compose postgres aapl market data appdbcontext quote add-migration business logic postgresql msft stock price stock ticker productservice loss stock xunit container dbcontext unit test application service backgroundservice schema change googl database update threshold iproductservice finnhubpricesyncworker price drop,# Stage 2: Runtime (minimal image) | Stage 2: Runtime (minimal image) FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS fi doc,"# Dockerization & Desktop Environment Plan This document outlines the strategy for containerizing the **Automated Inventory Alert System** to ensure consistent environments across Development, Test, and Production. @@ -18319,7 +20352,7 @@ A single command (`docker-compose up`) should spin up the entire ecosystem. 1. **Non-Root User:** Run the API as a low-privileged user inside the container. 2. **Secret Management:** Do NOT hardcode passwords in `docker-compose.yml`. Use environment variables or `.env` files (ignored by git). -3. **Healtchecks:** Add health checks to the database to ensure the API only starts after the DB is ready.",51,5845cfea662d12d468ac90c3ebd19447,doc\archive\docker\DOCKER_PLAN.md,0,384,"step, docker, container, build, compose, done, environment, dockerfile",1775670503.9263184,1,compose postgres fluentassertions postgresql container business logic xunit dockerfile arrange act assert price drop productservice notification inventory iproductservice threshold sku stock loss item unit test application service,# Dockerization & Desktop Environment Plan | Dockerization & Desktop Environment Plan This document outlines the strategy for +3. **Healtchecks:** Add health checks to the database to ensure the API only starts after the DB is ready.",51,5845cfea662d12d468ac90c3ebd19447,doc\archive\docker\DOCKER_PLAN.md,0,402,"step, docker, container, build, compose, done, environment, dockerfile",1775670503.9263184,1,compose postgres fluentassertions postgresql container business logic xunit dockerfile arrange act assert price drop productservice notification inventory iproductservice threshold sku stock loss item unit test application service,# Dockerization & Desktop Environment Plan | Dockerization & Desktop Environment Plan This document outlines the strategy for doc,"# 🆓 Finnhub Free-Tier Endpoints This document lists all the endpoints available on the Finnhub Free/Personal tier (excluding ""Premium"" and ""Enterprise"" labels). @@ -18377,7 +20410,7 @@ This document lists all the endpoints available on the Finnhub Free/Personal tie - **Rate Limit:** 60 API calls per minute. - **Global Limit:** 30 API calls per second (system-wide). -- **History:** Generally limited (e.g., 1 year for news, 4 quarters for earnings).",58,6979d7ae3a4868847a9069c6e58b1c63,doc\archive\finnhub\FINNHUB_FREE_ENDPOINTS.md,0,385,"stock, market, news, forex, crypto, symbols, list, earnings",1775670503.9273663,1,rollback fluentassertions arrange act assert commit unitofwork atomicity quote stock price savechanges unit test xunit market data external api,# 🆓 Finnhub Free-Tier Endpoints | 🆓 Finnhub Free-Tier Endpoints This document lists all the endpoints available on +- **History:** Generally limited (e.g., 1 year for news, 4 quarters for earnings).",58,6979d7ae3a4868847a9069c6e58b1c63,doc\archive\finnhub\FINNHUB_FREE_ENDPOINTS.md,0,403,"stock, market, news, forex, crypto, symbols, list, earnings",1775670503.9273663,1,rollback fluentassertions arrange act assert commit unitofwork atomicity quote stock price savechanges unit test xunit market data external api,# 🆓 Finnhub Free-Tier Endpoints | 🆓 Finnhub Free-Tier Endpoints This document lists all the endpoints available on doc,"# 🛠️ Finnhub Integration Implementation Checklist Follow these steps to complete the automated pricing and alert system. @@ -18431,7 +20464,7 @@ Follow these steps to complete the automated pricing and alert system. ## 🧪 Testing Tips 1. **Mock Tickers:** Seed a product with `TickerSymbol = ""AAPL""` and a low `OriginalCost` to trigger the ""High Value"" logic. -2. **Rate Limits:** Finnhub free tier is 60 calls/minute. If you have many products, add a small `Task.Delay` between API calls.",54,cef7b5a0f4ac1c0a24b3a2bfad268eaf,doc\archive\finnhub\FINNHUB_IMPLEMENTATION_TASKS.md,0,386,"phase, tickersymbol, logic, finnhub, alert, product, update, create",1775670503.928365,1,stock price symbol mock setup external api efcore migration stock ticker aapl application service hosted service asnotracking moq entity framework arrange act assert stock market data database update appdbcontext finnhubpricesyncworker fluentassertions inventory loss xunit savechangesasync periodictimer sku msft googl returns async productservice efcore executetransactionasync times once unit test quote threshold add-migration iunitofwork backgroundservice iproductservice item price drop schema change business logic notification verify dbcontext,# 🛠️ Finnhub Integration Implementation Checklist | 🛠️ Finnhub Integration Implementation Checklist Follow these steps to complete t +2. **Rate Limits:** Finnhub free tier is 60 calls/minute. If you have many products, add a small `Task.Delay` between API calls.",54,cef7b5a0f4ac1c0a24b3a2bfad268eaf,doc\archive\finnhub\FINNHUB_IMPLEMENTATION_TASKS.md,0,404,"phase, tickersymbol, logic, finnhub, alert, product, update, create",1775670503.928365,1,stock price symbol mock setup external api efcore migration stock ticker aapl application service hosted service asnotracking moq entity framework arrange act assert stock market data database update appdbcontext finnhubpricesyncworker fluentassertions inventory loss xunit savechangesasync periodictimer sku msft googl returns async productservice efcore executetransactionasync times once unit test quote threshold add-migration iunitofwork backgroundservice iproductservice item price drop schema change business logic notification verify dbcontext,# 🛠️ Finnhub Integration Implementation Checklist | 🛠️ Finnhub Integration Implementation Checklist Follow these steps to complete t doc,"# 01 — Application Redefinition > **SystemName:** Market Pulse (working title) > **Previous scope:** InventoryAlert — price breach alerts only @@ -18624,7 +20657,7 @@ App (Serilog) - **Log Enrichment**: - Use Serilog `LogContext.PushProperty` to attach `JobId` or `Symbol` to every log line in the worker handlers. - Implement a `DiagnosticEventListener` for EF Core to log slow queries (>500ms) as Warnings. -- **Mapping**: Standardize on `Direct Mapping` for entities -> events to avoid AutoMapper complexity in high-throughput worker loops.",193,f4b3f5cb8b2800c22d9bb095f8942e66,doc\archive\plan\01_APPLICATION_REDEFINITION.md,0,387,"symbol, price, news, alert, market, stock, event, dynamodb",1775670503.9303658,1,business logic efcore market data threshold notification xunit fluentassertions loss asnotracking finnhubpricesyncworker price drop dockerfile item inventory stock price unit test arrange act assert compose postgres container backgroundservice sku quote iproductservice appdbcontext postgresql application service periodictimer stock external api productservice hosted service dbcontext entity framework,# 01 — Application Redefinition | 01 — Application Redefinition > SystemName: Market Pulse (working title) > Previ +- **Mapping**: Standardize on `Direct Mapping` for entities -> events to avoid AutoMapper complexity in high-throughput worker loops.",193,f4b3f5cb8b2800c22d9bb095f8942e66,doc\archive\plan\01_APPLICATION_REDEFINITION.md,0,405,"symbol, price, news, alert, market, stock, event, dynamodb",1775670503.9303658,1,business logic efcore market data threshold notification xunit fluentassertions loss asnotracking finnhubpricesyncworker price drop dockerfile item inventory stock price unit test arrange act assert compose postgres container backgroundservice sku quote iproductservice appdbcontext postgresql application service periodictimer stock external api productservice hosted service dbcontext entity framework,# 01 — Application Redefinition | 01 — Application Redefinition > SystemName: Market Pulse (working title) > Previ doc,"# 02 — API Endpoint Plan --- @@ -18849,7 +20882,7 @@ CREATE TABLE ""Watchlists"" ( UNIQUE (""UserId"", ""Symbol"") ); CREATE INDEX idx_watchlists_user ON ""Watchlists"" (""UserId""); -```",225,95aee9414fe122dcdace7cbefaff7abf,doc\archive\plan\02_API_ENDPOINT_PLAN.md,0,388,"symbol, source, returns, crypto, market, finnhub, redis, exchange",1775670503.9303658,1,fluentassertions sku loss msft business logic efcore dbcontext iproductservice stock productservice xunit unit test application service appdbcontext stock ticker item googl notification entity framework inventory stock price symbol threshold external api quote aapl market data asnotracking price drop arrange act assert,# 02 — API Endpoint Plan | 02 — API Endpoint Plan --- 1 +```",225,95aee9414fe122dcdace7cbefaff7abf,doc\archive\plan\02_API_ENDPOINT_PLAN.md,0,406,"symbol, source, returns, crypto, market, finnhub, redis, exchange",1775670503.9303658,1,fluentassertions sku loss msft business logic efcore dbcontext iproductservice stock productservice xunit unit test application service appdbcontext stock ticker item googl notification entity framework inventory stock price symbol threshold external api quote aapl market data asnotracking price drop arrange act assert,# 02 — API Endpoint Plan | 02 — API Endpoint Plan --- 1 doc,"# 03 — DynamoDB Table Design All DynamoDB tables use **on-demand billing** in development (Moto) and production. @@ -18957,7 +20990,7 @@ TTL is enabled on every table — the attribute is always `Ttl` (Unix epoch seco Add to `init-all.sh`: -```bash",108,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,389,"number, string, table, attribute, news, inventory, purpose, type",1775670503.9324596,1,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# 03 — DynamoDB Table Design | 03 — DynamoDB Table Design All DynamoDB tables use on-demand billing in developm +```bash",108,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,407,"number, string, table, attribute, news, inventory, purpose, type",1775670503.9324596,1,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# 03 — DynamoDB Table Design | 03 — DynamoDB Table Design All DynamoDB tables use on-demand billing in developm doc,"# inventory-market-news aws dynamodb create-table \ --table-name inventory-market-news \ @@ -18975,7 +21008,7 @@ aws dynamodb update-time-to-live \ --table-name inventory-market-news \ --time-to-live-specification ""Enabled=true,AttributeName=Ttl"" \ --endpoint-url ""$ENDPOINT_URL"" \ - --region ""$AWS_DEFAULT_REGION""",127,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,390,"attributename, inventory, market, news, table, dynamodb, name, category",1775670503.9324596,109,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# inventory-market-news | inventory-market-news aws dynamodb create-table \ --table-name inventory-marke + --region ""$AWS_DEFAULT_REGION""",127,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,408,"attributename, inventory, market, news, table, dynamodb, name, category",1775670503.9324596,109,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# inventory-market-news | inventory-market-news aws dynamodb create-table \ --table-name inventory-marke doc,"# inventory-price-history aws dynamodb create-table \ --table-name inventory-price-history \ @@ -18993,7 +21026,7 @@ aws dynamodb update-time-to-live \ --table-name inventory-price-history \ --time-to-live-specification ""Enabled=true,AttributeName=Ttl"" \ --endpoint-url ""$ENDPOINT_URL"" \ - --region ""$AWS_DEFAULT_REGION""",146,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,391,"attributename, inventory, price, history, table, dynamodb, name, tickersymbol",1775670503.9324596,128,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# inventory-price-history | inventory-price-history aws dynamodb create-table \ --table-name inventory-pri + --region ""$AWS_DEFAULT_REGION""",146,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,409,"attributename, inventory, price, history, table, dynamodb, name, tickersymbol",1775670503.9324596,128,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# inventory-price-history | inventory-price-history aws dynamodb create-table \ --table-name inventory-pri doc,"# inventory-recommendations aws dynamodb create-table \ --table-name inventory-recommendations \ @@ -19011,7 +21044,7 @@ aws dynamodb update-time-to-live \ --table-name inventory-recommendations \ --time-to-live-specification ""Enabled=true,AttributeName=Ttl"" \ --endpoint-url ""$ENDPOINT_URL"" \ - --region ""$AWS_DEFAULT_REGION""",165,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,392,"attributename, inventory, recommendations, table, dynamodb, name, symbol, attributetype",1775670503.9324596,147,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# inventory-recommendations | inventory-recommendations aws dynamodb create-table \ --table-name inventory-r + --region ""$AWS_DEFAULT_REGION""",165,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,410,"attributename, inventory, recommendations, table, dynamodb, name, symbol, attributetype",1775670503.9324596,147,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# inventory-recommendations | inventory-recommendations aws dynamodb create-table \ --table-name inventory-r doc,"# inventory-earnings aws dynamodb create-table \ --table-name inventory-earnings \ @@ -19030,7 +21063,7 @@ aws dynamodb update-time-to-live \ --time-to-live-specification ""Enabled=true,AttributeName=Ttl"" \ --endpoint-url ""$ENDPOINT_URL"" \ --region ""$AWS_DEFAULT_REGION"" -```",184,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,393,"attributename, inventory, earnings, table, dynamodb, name, symbol, attributetype",1775670503.9324596,166,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# inventory-earnings | inventory-earnings aws dynamodb create-table \ --table-name inventory-earnings +```",184,a98ea7e9cec257c69867ec240d45ab64,doc\archive\plan\03_DYNAMODB_TABLE_DESIGN.md,0,411,"attributename, inventory, earnings, table, dynamodb, name, symbol, attributetype",1775670503.9324596,166,stock price arrange act assert unit test stock ticker aapl entity framework msft dbcontext inventory sku googl efcore external api market data fluentassertions appdbcontext stock asnotracking quote item xunit symbol,# inventory-earnings | inventory-earnings aws dynamodb create-table \ --table-name inventory-earnings doc,"# 04 — Jobs, Workers & Telegram Bot Plan --- @@ -19223,7 +21256,7 @@ RecurringJob.AddOrUpdate(""earnings-cal"",x => x.ExecuteAsy RecurringJob.AddOrUpdate(""profile-sync"", x => x.ExecuteAsync(CancellationToken.None), ""0 2 * * 0""); RecurringJob.AddOrUpdate(""symbol-crawl"", x => x.ExecuteAsync(CancellationToken.None), ""0 2 * * *""); RecurringJob.AddOrUpdate(""poll-sqs"", x => x.ExecuteAsync(CancellationToken.None), ""*/1 * * * *""); -```",193,47c4aa5200001989aeb81294055f836e,doc\archive\plan\04_JOBS_WORKERS_TELEGRAM.md,0,394,"inventory, stock, symbol, news, dynamodb, earnings, telegram, price",1775670503.9324596,1,data access stock price asnotracking external api finnhubpricesyncworker igenericrepository dbcontext iproductrepository threshold hosted service quote loss efcore notification application service entity framework dbset market data periodictimer backgroundservice iproductservice price drop productservice appdbcontext business logic,"# 04 — Jobs, Workers & Telegram Bot Plan | 04 — Jobs, Workers & Telegram Bot Plan --- 1" +```",193,47c4aa5200001989aeb81294055f836e,doc\archive\plan\04_JOBS_WORKERS_TELEGRAM.md,0,412,"inventory, stock, symbol, news, dynamodb, earnings, telegram, price",1775670503.9324596,1,data access stock price asnotracking external api finnhubpricesyncworker igenericrepository dbcontext iproductrepository threshold hosted service quote loss efcore notification application service entity framework dbset market data periodictimer backgroundservice iproductservice price drop productservice appdbcontext business logic,"# 04 — Jobs, Workers & Telegram Bot Plan | 04 — Jobs, Workers & Telegram Bot Plan --- 1" doc,"# 05 — UI Plan (Next.js) --- @@ -19345,7 +21378,7 @@ Option B (preferred for prices): ## 6. Docker Service -```yaml",122,014896eae60b2376768bfdada36363f8,doc\archive\plan\05_UI_PLAN.md,0,395,"market, symbol, status, price, news, react, query, rule",1775670503.9339724,1,finnhubpricesyncworker aapl postgresql msft symbol periodictimer productservice fluentassertions container application service loss efcore iproductservice threshold dbcontext arrange act assert compose notification appdbcontext stock ticker backgroundservice unit test business logic googl xunit entity framework asnotracking price drop hosted service dockerfile postgres,# 05 — UI Plan (Next.js) | 05 — UI Plan (Next.js) --- 1 +```yaml",122,014896eae60b2376768bfdada36363f8,doc\archive\plan\05_UI_PLAN.md,0,413,"market, symbol, status, price, news, react, query, rule",1775670503.9339724,1,finnhubpricesyncworker aapl postgresql msft symbol periodictimer productservice fluentassertions container application service loss efcore iproductservice threshold dbcontext arrange act assert compose notification appdbcontext stock ticker backgroundservice unit test business logic googl xunit entity framework asnotracking price drop hosted service dockerfile postgres,# 05 — UI Plan (Next.js) | 05 — UI Plan (Next.js) --- 1 doc,"# docker-compose additions ui: build: @@ -19358,109 +21391,120 @@ ui: - NEXTAUTH_URL=http://localhost:3000 depends_on: - api -```",135,014896eae60b2376768bfdada36363f8,doc\archive\plan\05_UI_PLAN.md,0,396,"http, localhost, docker, compose, additions, build, context, inventoryalert",1775670503.9339724,123,finnhubpricesyncworker aapl postgresql msft symbol periodictimer productservice fluentassertions container application service loss efcore iproductservice threshold dbcontext arrange act assert compose notification appdbcontext stock ticker backgroundservice unit test business logic googl xunit entity framework asnotracking price drop hosted service dockerfile postgres,# docker-compose additions | docker-compose additions ui: build: context: ./InventoryAlert.UI ports: -code,,37,ae9cfcaf5a13981eb8a028fe03668db5,InventoryManagementSystem\.vs\InventoryManagementSystem\v17\DocumentLayout.backup.json,0,397,v17/DocumentLayout.backup.json,1775192535.7046554,1,stock threshold item price drop inventory notification loss sku,[MOD] v17/DocumentLayout.backup.json -code,,54,b914e93ed736e568add78f6d5b76baa9,InventoryManagementSystem\.vs\InventoryManagementSystem\v17\DocumentLayout.json,0,398,v17/DocumentLayout.json,1775192647.9730933,1,inventory item sku price drop stock notification loss threshold,[MOD] v17/DocumentLayout.json -code,,12,9b7791b1639e6664089ab15c675f32e9,InventoryManagementSystem\.vs\InventoryManagementSystem\v18\DocumentLayout.backup.json,0,399,v18/DocumentLayout.backup.json,1776279862.7909582,1,,[MOD] v18/DocumentLayout.backup.json -code,,12,9b7791b1639e6664089ab15c675f32e9,InventoryManagementSystem\.vs\InventoryManagementSystem\v18\DocumentLayout.json,0,400,v18/DocumentLayout.json,1776162156.339451,1,,[MOD] v18/DocumentLayout.json -code,,27,57367df713567d4461e67390da6507c8,InventoryManagementSystem\InventoryAlert.Api\appsettings.Development.json,0,401,InventoryAlert.Api/appsettings.Development.json,1776152660.5062368,1,dbcontext appdbcontext stock price efcore threshold quote asnotracking external api loss market data notification entity framework price drop,[MOD] InventoryAlert.Api/appsettings.Development.json -code,,27,02d45ad1dc0e4dcd76c8be0ccb2d001c,InventoryManagementSystem\InventoryAlert.Api\appsettings.Docker.json,0,402,InventoryAlert.Api/appsettings.Docker.json,1777114699.7929828,1,external api entity framework notification stock price quote efcore dbcontext asnotracking loss appdbcontext threshold market data price drop,[MOD] InventoryAlert.Api/appsettings.Docker.json -code,,28,72988ff23c934e3817a3f19596af1ec3,InventoryManagementSystem\InventoryAlert.Api\appsettings.Example.json,0,403,InventoryAlert.Api/appsettings.Example.json,1777190432.4457185,1,postgresql container asnotracking compose efcore postgres dbcontext notification appdbcontext loss external api dockerfile entity framework quote stock price threshold price drop market data,[MOD] InventoryAlert.Api/appsettings.Example.json -code,,27,5329bf770a0b5ec2c5b28243f61d6377,InventoryManagementSystem\InventoryAlert.Api\appsettings.json,0,404,InventoryAlert.Api/appsettings.json,1776152666.6315463,1,external api loss appdbcontext entity framework dbcontext threshold stock price asnotracking efcore market data price drop quote notification,[MOD] InventoryAlert.Api/appsettings.json -code,,27,57367df713567d4461e67390da6507c8,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\appsettings.Development.json,0,405,net10.0/appsettings.Development.json,1776152660.5062368,1,loss price drop quote stock price threshold dbcontext asnotracking market data entity framework notification appdbcontext efcore external api,[MOD] net10.0/appsettings.Development.json -code,,27,02d45ad1dc0e4dcd76c8be0ccb2d001c,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\appsettings.Docker.json,0,406,net10.0/appsettings.Docker.json,1777114699.7929828,1,external api threshold efcore entity framework loss asnotracking notification appdbcontext market data quote price drop stock price dbcontext,[MOD] net10.0/appsettings.Docker.json -code,,28,72988ff23c934e3817a3f19596af1ec3,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\appsettings.Example.json,0,407,net10.0/appsettings.Example.json,1777190432.4457185,1,postgres loss dbcontext container market data quote entity framework efcore appdbcontext notification threshold external api price drop stock price dockerfile asnotracking compose postgresql,[MOD] net10.0/appsettings.Example.json -code,,27,5329bf770a0b5ec2c5b28243f61d6377,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\appsettings.json,0,408,net10.0/appsettings.json,1776152666.6315463,1,external api price drop entity framework asnotracking dbcontext loss threshold quote appdbcontext stock price notification market data efcore,[MOD] net10.0/appsettings.json -code,,1781,869a0d34545367fdc29df517b815cc3e,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\InventoryAlert.Api.deps.json,0,409,net10.0/InventoryAlert.Api.deps.json,1777190540.2914839,1,asnotracking iproductservice loss threshold business logic efcore notification productservice entity framework dbcontext application service price drop appdbcontext,[MOD] net10.0/InventoryAlert.Api.deps.json -code,,20,37595336dae30b037bd95e5047b95825,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\InventoryAlert.Api.runtimeconfig.json,0,410,net10.0/InventoryAlert.Api.runtimeconfig.json,1775367661.9960494,1,entity framework asnotracking appdbcontext efcore dbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,411,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1776140330.4713986,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json -code,,1,acbe4a57a0230c6e9b12318544965c2f,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,412,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1776908467.097591,1,threshold price drop loss notification,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json -code,,171,6a002d69baf7b85bfe11c404487f1905,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\BuildHost-netcore\Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.deps.json,0,413,BuildHost-netcore/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.deps.json,1763421306.0,1,productservice efcore entity framework appdbcontext application service dbcontext business logic asnotracking iproductservice,[MOD] BuildHost-netcore/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.deps.json -code,,14,4a59cbd5a00293f28ad2649fdda570f9,InventoryManagementSystem\InventoryAlert.Api\bin\Debug\net10.0\BuildHost-netcore\Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.runtimeconfig.json,0,414,BuildHost-netcore/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.runtimeconfig.json,1763421306.0,1,asnotracking efcore appdbcontext dbcontext entity framework,[MOD] BuildHost-netcore/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.runtimeconfig.json -code,,27,57367df713567d4461e67390da6507c8,InventoryManagementSystem\InventoryAlert.Api\bin\Release\net10.0\appsettings.Development.json,0,415,net10.0/appsettings.Development.json,1776152660.5062368,1,loss dbcontext notification efcore stock price price drop threshold quote entity framework appdbcontext asnotracking market data external api,[MOD] net10.0/appsettings.Development.json -code,,27,5329bf770a0b5ec2c5b28243f61d6377,InventoryManagementSystem\InventoryAlert.Api\bin\Release\net10.0\appsettings.Docker.json,0,416,net10.0/appsettings.Docker.json,1776152427.4607298,1,market data stock price asnotracking price drop dbcontext appdbcontext threshold notification loss entity framework efcore external api quote,[MOD] net10.0/appsettings.Docker.json -code,,28,3b1239472906a13429a1c76f242c5c0a,InventoryManagementSystem\InventoryAlert.Api\bin\Release\net10.0\appsettings.Example.json,0,417,net10.0/appsettings.Example.json,1776152663.8011956,1,container dbcontext price drop stock price entity framework loss compose notification dockerfile quote appdbcontext postgres external api postgresql threshold market data efcore asnotracking,[MOD] net10.0/appsettings.Example.json -code,,27,5329bf770a0b5ec2c5b28243f61d6377,InventoryManagementSystem\InventoryAlert.Api\bin\Release\net10.0\appsettings.json,0,418,net10.0/appsettings.json,1776152666.6315463,1,loss price drop entity framework notification appdbcontext efcore threshold stock price asnotracking external api market data dbcontext quote,[MOD] net10.0/appsettings.json -code,,1713,322fbe3f71679c335ba0563804aa7b61,InventoryManagementSystem\InventoryAlert.Api\bin\Release\net10.0\InventoryAlert.Api.deps.json,0,419,net10.0/InventoryAlert.Api.deps.json,1776317847.379226,1,notification entity framework threshold productservice efcore business logic application service dbcontext price drop appdbcontext loss iproductservice asnotracking,[MOD] net10.0/InventoryAlert.Api.deps.json -code,,21,d60cf9618363ac73f5894cceaffc545e,InventoryManagementSystem\InventoryAlert.Api\bin\Release\net10.0\InventoryAlert.Api.runtimeconfig.json,0,420,net10.0/InventoryAlert.Api.runtimeconfig.json,1776317847.4107525,1,entity framework asnotracking dbcontext efcore appdbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.Api\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,421,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1776317847.2301905,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json -code,,1769,704d3b0ef8b8bc876f15829eddf347bb,InventoryManagementSystem\InventoryAlert.Api\obj\InventoryAlert.Api.csproj.nuget.dgspec.json,0,422,obj/InventoryAlert.Api.csproj.nuget.dgspec.json,1777190308.8057697,1,application service threshold arrange act assert business logic productservice iproductservice efcore loss asnotracking notification appdbcontext dbcontext entity framework price drop xunit fluentassertions unit test,[MOD] obj/InventoryAlert.Api.csproj.nuget.dgspec.json -code,,5462,e5cd19af979f23a31b491445ca2945e9,InventoryManagementSystem\InventoryAlert.Api\obj\project.assets.json,0,423,obj/project.assets.json,1777190308.7962513,1,productservice loss arrange act assert efcore unit test threshold application service fluentassertions iproductservice entity framework dbcontext appdbcontext asnotracking business logic notification xunit price drop,[MOD] obj/project.assets.json -code,,1,13427eccf2b7257140bf8a41203d3f25,InventoryManagementSystem\InventoryAlert.Api\obj\project.packagespec.json,0,424,obj/project.packagespec.json,1777190305.260757,1,asnotracking unit test appdbcontext notification business logic efcore dbcontext application service arrange act assert productservice threshold price drop xunit iproductservice entity framework fluentassertions loss,[MOD] obj/project.packagespec.json -code,,1,9781dd6d356826d311887c1e4bd62b4f,InventoryManagementSystem\InventoryAlert.Api\obj\Debug\net10.0\InventoryAlert.Api.sourcelink.json,0,425,net10.0/InventoryAlert.Api.sourcelink.json,1777190539.3473327,1,entity framework efcore dbcontext appdbcontext asnotracking,[MOD] net10.0/InventoryAlert.Api.sourcelink.json -code,,1,f253aa211b66624d3c74b40af57bad11,InventoryManagementSystem\InventoryAlert.Api\obj\Debug\net10.0\rjsmcshtml.dswa.cache.json,0,426,net10.0/rjsmcshtml.dswa.cache.json,1777190539.8792353,1,,[MOD] net10.0/rjsmcshtml.dswa.cache.json -code,,1,6fbe43d8317a18a9900914aae494033f,InventoryManagementSystem\InventoryAlert.Api\obj\Debug\net10.0\rjsmrazor.dswa.cache.json,0,427,net10.0/rjsmrazor.dswa.cache.json,1777190539.8755379,1,,[MOD] net10.0/rjsmrazor.dswa.cache.json -code,,1,8334caeee9543a468d48ed3186ec4af5,InventoryManagementSystem\InventoryAlert.Api\obj\Debug\net10.0\rpswa.dswa.cache.json,0,428,net10.0/rpswa.dswa.cache.json,1777190539.1332502,1,,[MOD] net10.0/rpswa.dswa.cache.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.Api\obj\Debug\net10.0\staticwebassets.build.endpoints.json,0,429,net10.0/staticwebassets.build.endpoints.json,1776140330.4713986,1,,[MOD] net10.0/staticwebassets.build.endpoints.json -code,,1,b32fc32ecdc8bca647441788aa881551,InventoryManagementSystem\InventoryAlert.Api\obj\Debug\net10.0\staticwebassets.build.json,0,430,net10.0/staticwebassets.build.json,1776908467.0577464,1,notification dbcontext entity framework appdbcontext price drop loss asnotracking efcore threshold,[MOD] net10.0/staticwebassets.build.json -code,,1,acbe4a57a0230c6e9b12318544965c2f,InventoryManagementSystem\InventoryAlert.Api\obj\Debug\net10.0\staticwebassets.development.json,0,431,net10.0/staticwebassets.development.json,1776908467.097591,1,price drop threshold loss notification,[MOD] net10.0/staticwebassets.development.json -code,,1,b4bc405b4c07cf3b59a86a282bac2314,InventoryManagementSystem\InventoryAlert.Api\obj\Release\net10.0\InventoryAlert.Api.sourcelink.json,0,432,net10.0/InventoryAlert.Api.sourcelink.json,1776517504.546077,1,,[MOD] net10.0/InventoryAlert.Api.sourcelink.json -code,,1,04d756c08a499ba41f226b9132c17bdc,InventoryManagementSystem\InventoryAlert.Api\obj\Release\net10.0\rjsmcshtml.dswa.cache.json,0,433,net10.0/rjsmcshtml.dswa.cache.json,1776517508.9601493,1,,[MOD] net10.0/rjsmcshtml.dswa.cache.json -code,,1,e483c4dc411d5851c1d78beb1a1b8bd6,InventoryManagementSystem\InventoryAlert.Api\obj\Release\net10.0\rjsmrazor.dswa.cache.json,0,434,net10.0/rjsmrazor.dswa.cache.json,1776517508.95615,1,,[MOD] net10.0/rjsmrazor.dswa.cache.json -code,,1,75285d83c407e034046a7147010e9d9c,InventoryManagementSystem\InventoryAlert.Api\obj\Release\net10.0\rpswa.dswa.cache.json,0,435,net10.0/rpswa.dswa.cache.json,1776398166.400314,1,,[MOD] net10.0/rpswa.dswa.cache.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.Api\obj\Release\net10.0\staticwebassets.build.endpoints.json,0,436,net10.0/staticwebassets.build.endpoints.json,1776317847.2301905,1,,[MOD] net10.0/staticwebassets.build.endpoints.json -code,,1,33100d0122c790e23e46d17c325991ce,InventoryManagementSystem\InventoryAlert.Api\obj\Release\net10.0\staticwebassets.build.json,0,437,net10.0/staticwebassets.build.json,1776317847.2245739,1,notification loss efcore price drop asnotracking threshold appdbcontext dbcontext entity framework,[MOD] net10.0/staticwebassets.build.json -code,,14,251c880b08d1d0344b8a79bdc2d8f6b6,InventoryManagementSystem\InventoryAlert.Api\Properties\launchSettings.json,0,438,Properties/launchSettings.json,1775162587.1512287,1,,[MOD] Properties/launchSettings.json -code,,33,4d6bffd1f43d0997afb15365806311b3,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\appsettings.Development.json,0,439,net10.0/appsettings.Development.json,1776152647.4113853,1,loss price drop appdbcontext quote external api market data threshold entity framework stock price dbcontext asnotracking notification efcore,[MOD] net10.0/appsettings.Development.json -code,,33,474375f23ee2d8392f7d049b4faf29dc,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\appsettings.Docker.json,0,440,net10.0/appsettings.Docker.json,1776743201.9369025,1,entity framework threshold market data efcore stock price external api quote dbcontext appdbcontext loss price drop notification asnotracking,[MOD] net10.0/appsettings.Docker.json -code,,34,5e9035733850c9a99aba36de69e8b5bc,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\appsettings.Example.json,0,441,net10.0/appsettings.Example.json,1776152650.2331953,1,compose postgres postgresql efcore container entity framework stock price loss appdbcontext external api asnotracking dbcontext market data notification dockerfile quote price drop threshold,[MOD] net10.0/appsettings.Example.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\appsettings.json,0,442,net10.0/appsettings.json,1776152652.9040236,1,market data threshold asnotracking price drop quote external api notification appdbcontext stock price entity framework efcore loss dbcontext,[MOD] net10.0/appsettings.json -code,,1781,869a0d34545367fdc29df517b815cc3e,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Api.deps.json,0,443,net10.0/InventoryAlert.Api.deps.json,1777110113.4583828,1,appdbcontext price drop iproductservice asnotracking productservice threshold entity framework notification efcore application service business logic dbcontext loss,[MOD] net10.0/InventoryAlert.Api.deps.json -code,,20,37595336dae30b037bd95e5047b95825,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Api.runtimeconfig.json,0,444,net10.0/InventoryAlert.Api.runtimeconfig.json,1775367661.9960494,1,dbcontext efcore entity framework appdbcontext asnotracking,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,445,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1776140330.4713986,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json -code,,1,acbe4a57a0230c6e9b12318544965c2f,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,446,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1776908467.097591,1,price drop threshold loss notification,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json -code,,1759,fbcbe53067d5a9be934149246f1b5125,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.ArchitectureTests.deps.json,0,447,net10.0/InventoryAlert.ArchitectureTests.deps.json,1777113423.3734236,1,entity framework unit test xunit efcore fluentassertions dbcontext arrange act assert finnhubpricesyncworker business logic asnotracking periodictimer threshold notification appdbcontext application service iproductservice price drop loss hosted service productservice backgroundservice,[MOD] net10.0/InventoryAlert.ArchitectureTests.deps.json -code,,20,5f3a2d98fc24aa854c5b9344a7a4d157,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.ArchitectureTests.runtimeconfig.json,0,448,net10.0/InventoryAlert.ArchitectureTests.runtimeconfig.json,1775367799.9543755,1,asnotracking appdbcontext xunit entity framework unit test fluentassertions arrange act assert efcore dbcontext,[MOD] net10.0/InventoryAlert.ArchitectureTests.runtimeconfig.json -code,,1484,2715841f88b7f187dd9c768d43ae51d9,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Worker.deps.json,0,449,net10.0/InventoryAlert.Worker.deps.json,1777110113.2623515,1,finnhubpricesyncworker productservice entity framework appdbcontext notification business logic dbcontext threshold application service efcore price drop hosted service backgroundservice asnotracking loss periodictimer iproductservice,[MOD] net10.0/InventoryAlert.Worker.deps.json -code,,20,37595336dae30b037bd95e5047b95825,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,450,net10.0/InventoryAlert.Worker.runtimeconfig.json,1775574216.5947363,1,dbcontext efcore entity framework appdbcontext asnotracking,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,451,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1775574216.407298,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json -code,,33,4d6bffd1f43d0997afb15365806311b3,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\appsettings.Development.json,0,452,net10.0/appsettings.Development.json,1776152647.4113853,1,efcore market data entity framework price drop dbcontext appdbcontext stock price quote asnotracking loss external api notification threshold,[MOD] net10.0/appsettings.Development.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\appsettings.Docker.json,0,453,net10.0/appsettings.Docker.json,1776152585.5173597,1,external api appdbcontext loss asnotracking threshold stock price price drop entity framework market data dbcontext notification quote efcore,[MOD] net10.0/appsettings.Docker.json -code,,34,5e9035733850c9a99aba36de69e8b5bc,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\appsettings.Example.json,0,454,net10.0/appsettings.Example.json,1776152650.2331953,1,external api market data postgres dbcontext notification loss compose quote price drop postgresql efcore asnotracking threshold stock price appdbcontext dockerfile entity framework container,[MOD] net10.0/appsettings.Example.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\appsettings.json,0,455,net10.0/appsettings.json,1776152652.9040236,1,market data stock price asnotracking price drop dbcontext appdbcontext threshold notification loss entity framework efcore external api quote,[MOD] net10.0/appsettings.json -code,,1713,322fbe3f71679c335ba0563804aa7b61,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Api.deps.json,0,456,net10.0/InventoryAlert.Api.deps.json,1776317847.379226,1,productservice application service threshold notification business logic entity framework asnotracking dbcontext price drop iproductservice loss efcore appdbcontext,[MOD] net10.0/InventoryAlert.Api.deps.json -code,,21,d60cf9618363ac73f5894cceaffc545e,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Api.runtimeconfig.json,0,457,net10.0/InventoryAlert.Api.runtimeconfig.json,1776317847.4107525,1,appdbcontext efcore entity framework dbcontext asnotracking,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,458,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1776317847.2301905,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json -code,,1690,52cc95c27cc50de640f2fd4ca35ebf84,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.ArchitectureTests.deps.json,0,459,net10.0/InventoryAlert.ArchitectureTests.deps.json,1776398168.9059117,1,periodictimer application service xunit efcore asnotracking loss arrange act assert productservice hosted service finnhubpricesyncworker appdbcontext notification price drop entity framework iproductservice unit test dbcontext backgroundservice fluentassertions business logic threshold,[MOD] net10.0/InventoryAlert.ArchitectureTests.deps.json -code,,21,11a2057f7e08545a87eae55a47ccbe16,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.ArchitectureTests.runtimeconfig.json,0,460,net10.0/InventoryAlert.ArchitectureTests.runtimeconfig.json,1776317849.344718,1,xunit fluentassertions arrange act assert appdbcontext dbcontext entity framework unit test asnotracking efcore,[MOD] net10.0/InventoryAlert.ArchitectureTests.runtimeconfig.json -code,,1415,0dc0c89c73e769db23b190b6e65c008b,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Worker.deps.json,0,461,net10.0/InventoryAlert.Worker.deps.json,1776398168.1515255,1,productservice price drop notification asnotracking loss iproductservice periodictimer threshold dbcontext backgroundservice entity framework efcore application service finnhubpricesyncworker hosted service appdbcontext business logic,[MOD] net10.0/InventoryAlert.Worker.deps.json -code,,21,d60cf9618363ac73f5894cceaffc545e,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,462,net10.0/InventoryAlert.Worker.runtimeconfig.json,1776315560.6109736,1,asnotracking efcore appdbcontext entity framework dbcontext,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,463,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1776315560.4012246,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json -code,,2823,b9475ea1303a98279c928ae6b0a66cde,InventoryManagementSystem\InventoryAlert.ArchitectureTests\obj\InventoryAlert.ArchitectureTests.csproj.nuget.dgspec.json,0,464,obj/InventoryAlert.ArchitectureTests.csproj.nuget.dgspec.json,1777190308.7987552,1,efcore iproductservice xunit dbcontext productservice threshold application service fluentassertions finnhubpricesyncworker arrange act assert backgroundservice asnotracking unit test loss periodictimer entity framework business logic notification appdbcontext price drop hosted service,[MOD] obj/InventoryAlert.ArchitectureTests.csproj.nuget.dgspec.json -code,,5684,934f9b84da425b3190e8628da8b04ef9,InventoryManagementSystem\InventoryAlert.ArchitectureTests\obj\project.assets.json,0,465,obj/project.assets.json,1777190308.7837257,1,dbcontext periodictimer iproductservice threshold backgroundservice fluentassertions notification arrange act assert hosted service entity framework application service xunit unit test appdbcontext business logic finnhubpricesyncworker price drop efcore productservice asnotracking loss,[MOD] obj/project.assets.json -code,,1,dbb6ee572192f95af169324cf4bb9c45,InventoryManagementSystem\InventoryAlert.ArchitectureTests\obj\project.packagespec.json,0,466,obj/project.packagespec.json,1777190305.8346598,1,finnhubpricesyncworker appdbcontext business logic backgroundservice periodictimer fluentassertions arrange act assert xunit efcore unit test productservice dbcontext threshold hosted service loss iproductservice entity framework notification application service price drop asnotracking,[MOD] obj/project.packagespec.json -code,,1,0df8c99f250429caebe480676825bd92,InventoryManagementSystem\InventoryAlert.ArchitectureTests\obj\Debug\net10.0\InventoryAlert.ArchitectureTests.sourcelink.json,0,467,net10.0/InventoryAlert.ArchitectureTests.sourcelink.json,1777113422.8586767,1,,[MOD] net10.0/InventoryAlert.ArchitectureTests.sourcelink.json -code,,1,b4bc405b4c07cf3b59a86a282bac2314,InventoryManagementSystem\InventoryAlert.ArchitectureTests\obj\Release\net10.0\InventoryAlert.ArchitectureTests.sourcelink.json,0,468,net10.0/InventoryAlert.ArchitectureTests.sourcelink.json,1776517509.7508361,1,,[MOD] net10.0/InventoryAlert.ArchitectureTests.sourcelink.json -code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,InventoryManagementSystem\InventoryAlert.Domain\bin\Debug\net10.0\InventoryAlert.Domain.deps.json,0,469,net10.0/InventoryAlert.Domain.deps.json,1776140328.931098,1,loss entity framework application service business logic productservice efcore dbcontext price drop appdbcontext asnotracking notification iproductservice threshold,[MOD] net10.0/InventoryAlert.Domain.deps.json -code,,13,5e2fec3a44baa37dd9b51c63a09513c6,InventoryManagementSystem\InventoryAlert.Domain\bin\Debug\net10.0\InventoryAlert.Domain.runtimeconfig.json,0,470,net10.0/InventoryAlert.Domain.runtimeconfig.json,1776140328.9679196,1,entity framework asnotracking dbcontext appdbcontext efcore,[MOD] net10.0/InventoryAlert.Domain.runtimeconfig.json -code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,InventoryManagementSystem\InventoryAlert.Domain\bin\Release\net10.0\InventoryAlert.Domain.deps.json,0,471,net10.0/InventoryAlert.Domain.deps.json,1776315555.4422834,1,business logic loss entity framework iproductservice dbcontext price drop productservice asnotracking efcore appdbcontext application service threshold notification,[MOD] net10.0/InventoryAlert.Domain.deps.json -code,,14,65e54446b7c5017d0110c783eff5a0a7,InventoryManagementSystem\InventoryAlert.Domain\bin\Release\net10.0\InventoryAlert.Domain.runtimeconfig.json,0,472,net10.0/InventoryAlert.Domain.runtimeconfig.json,1776315555.5014768,1,appdbcontext entity framework dbcontext asnotracking efcore,[MOD] net10.0/InventoryAlert.Domain.runtimeconfig.json -code,,481,66586429795b69647fd88967acc56a25,InventoryManagementSystem\InventoryAlert.Domain\obj\InventoryAlert.Domain.csproj.nuget.dgspec.json,0,473,obj/InventoryAlert.Domain.csproj.nuget.dgspec.json,1777190308.7952511,1,asnotracking iproductservice loss fluentassertions arrange act assert threshold business logic efcore xunit notification productservice entity framework unit test dbcontext application service price drop appdbcontext,[MOD] obj/InventoryAlert.Domain.csproj.nuget.dgspec.json -code,,3941,fd393b7da1aca1f9cac1ec1c7e80c106,InventoryManagementSystem\InventoryAlert.Domain\obj\project.assets.json,0,474,obj/project.assets.json,1777190306.4503043,1,dbcontext loss application service iproductservice unit test efcore appdbcontext fluentassertions xunit arrange act assert threshold notification productservice business logic asnotracking entity framework price drop,[MOD] obj/project.assets.json -code,,1,bb8b685edcbc45f6a9c0542912923abd,InventoryManagementSystem\InventoryAlert.Domain\obj\project.packagespec.json,0,475,obj/project.packagespec.json,1777190304.628418,1,threshold iproductservice price drop arrange act assert unit test entity framework efcore appdbcontext asnotracking application service loss notification xunit business logic dbcontext productservice fluentassertions,[MOD] obj/project.packagespec.json -code,,1,9781dd6d356826d311887c1e4bd62b4f,InventoryManagementSystem\InventoryAlert.Domain\obj\Debug\net10.0\InventoryAlert.Domain.sourcelink.json,0,476,net10.0/InventoryAlert.Domain.sourcelink.json,1777190537.8435922,1,dbcontext entity framework appdbcontext asnotracking efcore,[MOD] net10.0/InventoryAlert.Domain.sourcelink.json -code,,1,b4bc405b4c07cf3b59a86a282bac2314,InventoryManagementSystem\InventoryAlert.Domain\obj\Release\net10.0\InventoryAlert.Domain.sourcelink.json,0,477,net10.0/InventoryAlert.Domain.sourcelink.json,1776517496.9715123,1,,[MOD] net10.0/InventoryAlert.Domain.sourcelink.json -code,,1191,a9c6f57a68b1e527485fff47c0323fdf,InventoryManagementSystem\InventoryAlert.E2ETests\bin\Debug\net10.0\InventoryAlert.E2ETests.deps.json,0,478,net10.0/InventoryAlert.E2ETests.deps.json,1777190553.579349,1,xunit threshold productservice appdbcontext price drop application service asnotracking iproductservice unit test dbcontext loss business logic arrange act assert fluentassertions entity framework efcore notification,[MOD] net10.0/InventoryAlert.E2ETests.deps.json -code,,14,0e71cccfa0816f7f0e9c53a23c96a205,InventoryManagementSystem\InventoryAlert.E2ETests\bin\Debug\net10.0\InventoryAlert.E2ETests.runtimeconfig.json,0,479,net10.0/InventoryAlert.E2ETests.runtimeconfig.json,1776142797.1150572,1,fluentassertions unit test dbcontext arrange act assert xunit entity framework appdbcontext asnotracking efcore,[MOD] net10.0/InventoryAlert.E2ETests.runtimeconfig.json -code,,1086,9b8152bc09e96ced690f2e5dc43f143e,InventoryManagementSystem\InventoryAlert.E2ETests\bin\Release\net10.0\InventoryAlert.E2ETests.deps.json,0,480,net10.0/InventoryAlert.E2ETests.deps.json,1776315557.9949725,1,efcore business logic arrange act assert price drop entity framework dbcontext iproductservice xunit unit test appdbcontext asnotracking loss fluentassertions productservice notification threshold application service,[MOD] net10.0/InventoryAlert.E2ETests.deps.json -code,,15,5f7047d258573e95125f9cc3ab6529c4,InventoryManagementSystem\InventoryAlert.E2ETests\bin\Release\net10.0\InventoryAlert.E2ETests.runtimeconfig.json,0,481,net10.0/InventoryAlert.E2ETests.runtimeconfig.json,1776315558.0472548,1,asnotracking dbcontext appdbcontext unit test arrange act assert entity framework efcore xunit fluentassertions,[MOD] net10.0/InventoryAlert.E2ETests.runtimeconfig.json -code,,916,1555908b4c730038de0d0aa0be6b7ca7,InventoryManagementSystem\InventoryAlert.E2ETests\obj\InventoryAlert.E2ETests.csproj.nuget.dgspec.json,0,482,obj/InventoryAlert.E2ETests.csproj.nuget.dgspec.json,1777190308.7962513,1,productservice business logic fluentassertions asnotracking unit test efcore dbcontext xunit notification appdbcontext loss arrange act assert entity framework application service iproductservice threshold price drop,[MOD] obj/InventoryAlert.E2ETests.csproj.nuget.dgspec.json -code,,3204,b57c9c1153e8c6b13d48d152dda5c369,InventoryManagementSystem\InventoryAlert.E2ETests\obj\project.assets.json,0,483,obj/project.assets.json,1777190308.782726,1,loss arrange act assert dbcontext application service iproductservice entity framework efcore business logic appdbcontext notification threshold price drop productservice xunit fluentassertions asnotracking unit test,[MOD] obj/project.assets.json -code,,1,b83a570ce4ee119c34e0ab2f0897f90f,InventoryManagementSystem\InventoryAlert.E2ETests\obj\project.packagespec.json,0,484,obj/project.packagespec.json,1777190305.1036024,1,iproductservice efcore fluentassertions dbcontext price drop arrange act assert loss entity framework business logic productservice threshold asnotracking unit test notification appdbcontext application service xunit,[MOD] obj/project.packagespec.json -code,,1,9781dd6d356826d311887c1e4bd62b4f,InventoryManagementSystem\InventoryAlert.E2ETests\obj\Debug\net10.0\InventoryAlert.E2ETests.sourcelink.json,0,485,net10.0/InventoryAlert.E2ETests.sourcelink.json,1777190553.2607858,1,entity framework dbcontext efcore asnotracking appdbcontext,[MOD] net10.0/InventoryAlert.E2ETests.sourcelink.json -code,,1,b4bc405b4c07cf3b59a86a282bac2314,InventoryManagementSystem\InventoryAlert.E2ETests\obj\Release\net10.0\InventoryAlert.E2ETests.sourcelink.json,0,486,net10.0/InventoryAlert.E2ETests.sourcelink.json,1776517502.7643807,1,,[MOD] net10.0/InventoryAlert.E2ETests.sourcelink.json -code,,1014,eff730251f234ef689c3bb655ec153c0,InventoryManagementSystem\InventoryAlert.Infrastructure\bin\Debug\net10.0\InventoryAlert.Infrastructure.deps.json,0,487,net10.0/InventoryAlert.Infrastructure.deps.json,1776140329.4235134,1,threshold appdbcontext loss asnotracking iproductservice price drop business logic entity framework notification productservice application service efcore dbcontext,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json -code,,19,7b716426e1deaae021de466b00b9f803,InventoryManagementSystem\InventoryAlert.Infrastructure\bin\Debug\net10.0\InventoryAlert.Infrastructure.runtimeconfig.json,0,488,net10.0/InventoryAlert.Infrastructure.runtimeconfig.json,1776140329.4280994,1,appdbcontext asnotracking dbcontext efcore entity framework,[MOD] net10.0/InventoryAlert.Infrastructure.runtimeconfig.json -code,,171,6a002d69baf7b85bfe11c404487f1905,InventoryManagementSystem\InventoryAlert.Infrastructure\bin\Debug\net10.0\BuildHost-netcore\Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.deps.json,0,489,BuildHost-netcore/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.deps.json,1763421306.0,1,business logic iproductservice dbcontext productservice asnotracking entity framework application service appdbcontext efcore,[MOD] BuildHost-netcore/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.deps.json -code,,14,4a59cbd5a00293f28ad2649fdda570f9,InventoryManagementSystem\InventoryAlert.Infrastructure\bin\Debug\net10.0\BuildHost-netcore\Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.runtimeconfig.json,0,490,BuildHost-netcore/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.runtimeconfig.json,1763421306.0,1,efcore dbcontext asnotracking entity framework appdbcontext,[MOD] BuildHost-netcore/Microsoft.CodeAnalysis.Workspaces.MSBuild.BuildHost.runtimeconfig.json -code,,1014,eff730251f234ef689c3bb655ec153c0,InventoryManagementSystem\InventoryAlert.Infrastructure\bin\Release\net10.0\InventoryAlert.Infrastructure.deps.json,0,491,net10.0/InventoryAlert.Infrastructure.deps.json,1776315557.0782773,1,efcore application service price drop iproductservice threshold dbcontext productservice notification appdbcontext loss asnotracking business logic entity framework,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json -code,,20,83d85af07448d5b73e11a316a264aa5c,InventoryManagementSystem\InventoryAlert.Infrastructure\bin\Release\net10.0\InventoryAlert.Infrastructure.runtimeconfig.json,0,492,net10.0/InventoryAlert.Infrastructure.runtimeconfig.json,1776315557.125782,1,entity framework efcore dbcontext appdbcontext asnotracking,[MOD] net10.0/InventoryAlert.Infrastructure.runtimeconfig.json -code,,1096,470b7ae3129bf3464cb17bba6f3198ef,InventoryManagementSystem\InventoryAlert.Infrastructure\obj\InventoryAlert.Infrastructure.csproj.nuget.dgspec.json,0,493,obj/InventoryAlert.Infrastructure.csproj.nuget.dgspec.json,1777190308.8037696,1,productservice loss arrange act assert efcore unit test threshold application service fluentassertions iproductservice entity framework dbcontext appdbcontext asnotracking business logic notification xunit price drop,[MOD] obj/InventoryAlert.Infrastructure.csproj.nuget.dgspec.json -code,,3554,61aa0f471d67474b2b888f6165ba7194,InventoryManagementSystem\InventoryAlert.Infrastructure\obj\project.assets.json,0,494,obj/project.assets.json,1777190308.7942498,1,xunit threshold productservice appdbcontext price drop application service asnotracking iproductservice unit test dbcontext loss business logic arrange act assert fluentassertions entity framework efcore notification,[MOD] obj/project.assets.json -code,,1,4aaaf41cea95cada1d65147e423621c4,InventoryManagementSystem\InventoryAlert.Infrastructure\obj\project.packagespec.json,0,495,obj/project.packagespec.json,1777190305.0247352,1,asnotracking unit test appdbcontext notification business logic efcore dbcontext application service arrange act assert productservice threshold price drop xunit iproductservice entity framework fluentassertions loss,[MOD] obj/project.packagespec.json -code,,1,9781dd6d356826d311887c1e4bd62b4f,InventoryManagementSystem\InventoryAlert.Infrastructure\obj\Debug\net10.0\InventoryAlert.Infrastructure.sourcelink.json,0,496,net10.0/InventoryAlert.Infrastructure.sourcelink.json,1777190538.5097587,1,dbcontext entity framework efcore asnotracking appdbcontext,[MOD] net10.0/InventoryAlert.Infrastructure.sourcelink.json -code,,1,b4bc405b4c07cf3b59a86a282bac2314,InventoryManagementSystem\InventoryAlert.Infrastructure\obj\Release\net10.0\InventoryAlert.Infrastructure.sourcelink.json,0,497,net10.0/InventoryAlert.Infrastructure.sourcelink.json,1776517502.763385,1,,[MOD] net10.0/InventoryAlert.Infrastructure.sourcelink.json -code,,14,329d29c031280e0b91b8a7b63145ce47,InventoryManagementSystem\InventoryAlert.IntegrationTests\appsettings.test.json,0,498,InventoryAlert.IntegrationTests/appsettings.test.json,1777098229.7782145,1,unit test verify mock setup moq xunit fluentassertions arrange act assert returns async times once,[MOD] InventoryAlert.IntegrationTests/appsettings.test.json +```",135,014896eae60b2376768bfdada36363f8,doc\archive\plan\05_UI_PLAN.md,0,414,"http, localhost, docker, compose, additions, build, context, inventoryalert",1775670503.9339724,123,finnhubpricesyncworker aapl postgresql msft symbol periodictimer productservice fluentassertions container application service loss efcore iproductservice threshold dbcontext arrange act assert compose notification appdbcontext stock ticker backgroundservice unit test business logic googl xunit entity framework asnotracking price drop hosted service dockerfile postgres,# docker-compose additions | docker-compose additions ui: build: context: ./InventoryAlert.UI ports: +code,,31,524eb0bb84017bf7db38382c181633f0,src\InventoryAlert.Api\appsettings.Example.json,0,415,InventoryAlert.Api/appsettings.Example.json,1779814416.2734604,1,container postgresql efcore market data entity framework threshold quote notification dbcontext compose postgres asnotracking dockerfile external api price drop loss stock price appdbcontext,[MOD] InventoryAlert.Api/appsettings.Example.json +code,,31,524eb0bb84017bf7db38382c181633f0,src\InventoryAlert.Api\appsettings.json,0,416,InventoryAlert.Api/appsettings.json,1779814416.2734604,1,dockerfile entity framework external api container dbcontext market data postgresql appdbcontext price drop postgres efcore compose asnotracking stock price quote loss notification threshold,[MOD] InventoryAlert.Api/appsettings.json +code,,31,524eb0bb84017bf7db38382c181633f0,src\InventoryAlert.Api\bin\Debug\net10.0\appsettings.Example.json,0,417,net10.0/appsettings.Example.json,1779814416.2734604,1,external api market data container price drop dockerfile appdbcontext asnotracking postgres stock price threshold loss postgresql compose efcore dbcontext entity framework notification quote,[MOD] net10.0/appsettings.Example.json +code,,31,524eb0bb84017bf7db38382c181633f0,src\InventoryAlert.Api\bin\Debug\net10.0\appsettings.json,0,418,net10.0/appsettings.json,1779814416.2734604,1,container stock price compose market data postgres dockerfile postgresql price drop entity framework efcore asnotracking dbcontext appdbcontext external api quote threshold notification loss,[MOD] net10.0/appsettings.json +code,,1785,ace06dcdfed963a769231bf7d3d17433,src\InventoryAlert.Api\bin\Debug\net10.0\InventoryAlert.Api.deps.json,0,419,net10.0/InventoryAlert.Api.deps.json,1779852474.218987,1,business logic application service productservice price drop appdbcontext asnotracking loss efcore entity framework notification threshold iproductservice dbcontext,[MOD] net10.0/InventoryAlert.Api.deps.json +code,,20,37595336dae30b037bd95e5047b95825,src\InventoryAlert.Api\bin\Debug\net10.0\InventoryAlert.Api.runtimeconfig.json,0,420,net10.0/InventoryAlert.Api.runtimeconfig.json,1779852474.3064263,1,entity framework efcore asnotracking appdbcontext dbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\InventoryAlert.Api\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,421,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1779852473.9235973,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json +code,,1,764ba22cde656c91f3e05ba4bc7bbcee,src\InventoryAlert.Api\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,422,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1779852473.959113,1,notification threshold loss price drop,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json +code,,31,524eb0bb84017bf7db38382c181633f0,src\InventoryAlert.Api\bin\Release\net10.0\appsettings.Example.json,0,423,net10.0/appsettings.Example.json,1779814416.2734604,1,external api stock price price drop asnotracking quote postgresql notification threshold market data dockerfile loss appdbcontext dbcontext container efcore entity framework postgres compose,[MOD] net10.0/appsettings.Example.json +code,,1785,ace06dcdfed963a769231bf7d3d17433,src\InventoryAlert.Api\bin\Release\net10.0\InventoryAlert.Api.deps.json,0,424,net10.0/InventoryAlert.Api.deps.json,1779815055.0786984,1,iproductservice efcore application service business logic entity framework loss threshold dbcontext appdbcontext asnotracking notification price drop productservice,[MOD] net10.0/InventoryAlert.Api.deps.json +code,,21,d60cf9618363ac73f5894cceaffc545e,src\InventoryAlert.Api\bin\Release\net10.0\InventoryAlert.Api.runtimeconfig.json,0,425,net10.0/InventoryAlert.Api.runtimeconfig.json,1779815055.1578588,1,appdbcontext efcore entity framework asnotracking dbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\InventoryAlert.Api\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,426,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1779815054.8447104,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json +code,,1,e6adbf2622be6f462ec396db3b4d5b74,src\InventoryAlert.Api\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,427,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1779815054.8755307,1,price drop notification loss threshold,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json +code,,1807,992dd75d265e5983762ee81e1e628fd2,src\InventoryAlert.Api\obj\InventoryAlert.Api.csproj.nuget.dgspec.json,0,428,obj/InventoryAlert.Api.csproj.nuget.dgspec.json,1779852466.4085908,1,postgresql threshold productservice container mock setup business logic compose verify arrange act assert fluentassertions price drop moq returns async dockerfile dbcontext postgres iproductservice unit test times once loss entity framework notification asnotracking efcore application service appdbcontext xunit,[MOD] obj/InventoryAlert.Api.csproj.nuget.dgspec.json +code,,5463,372e45ff35af9efd2b6d1aa4a3b0d7b4,src\InventoryAlert.Api\obj\project.assets.json,0,429,obj/project.assets.json,1779852466.3991332,1,unit test productservice price drop appdbcontext threshold verify business logic loss application service efcore entity framework moq mock setup iproductservice notification fluentassertions arrange act assert times once dockerfile dbcontext postgres postgresql asnotracking xunit returns async compose container,[MOD] obj/project.assets.json +code,,1,8217d947075d2b465ea0d7e8ae6c5734,src\InventoryAlert.Api\obj\project.packagespec.json,0,430,obj/project.packagespec.json,1779852070.1198926,1,iproductservice appdbcontext times once container verify returns async productservice dbcontext entity framework application service notification postgresql loss efcore mock setup business logic unit test xunit dockerfile postgres fluentassertions threshold moq price drop arrange act assert asnotracking compose,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\InventoryAlert.Api\obj\Debug\net10.0\InventoryAlert.Api.sourcelink.json,0,431,net10.0/InventoryAlert.Api.sourcelink.json,1779852471.827245,1,asnotracking efcore appdbcontext entity framework dbcontext,[MOD] net10.0/InventoryAlert.Api.sourcelink.json +code,,1,7dea31a84b371b58322ae362a24ddbc1,src\InventoryAlert.Api\obj\Debug\net10.0\rjimswa.dswa.cache.json,0,432,net10.0/rjimswa.dswa.cache.json,1779852473.763646,1,,[MOD] net10.0/rjimswa.dswa.cache.json +code,,1,fd34639b75e1b2173449a7e944ca126d,src\InventoryAlert.Api\obj\Debug\net10.0\rjsmcshtml.dswa.cache.json,0,433,net10.0/rjsmcshtml.dswa.cache.json,1779853359.0105672,1,,[MOD] net10.0/rjsmcshtml.dswa.cache.json +code,,1,5bf34707115131ff707e6cc91425ef87,src\InventoryAlert.Api\obj\Debug\net10.0\rjsmrazor.dswa.cache.json,0,434,net10.0/rjsmrazor.dswa.cache.json,1779853359.0064375,1,,[MOD] net10.0/rjsmrazor.dswa.cache.json +code,,1,93deea0c2b1d9bb3e71da83dfab478ad,src\InventoryAlert.Api\obj\Debug\net10.0\rpswa.dswa.cache.json,0,435,net10.0/rpswa.dswa.cache.json,1779853358.8398378,1,price drop threshold notification loss,[MOD] net10.0/rpswa.dswa.cache.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\InventoryAlert.Api\obj\Debug\net10.0\staticwebassets.build.endpoints.json,0,436,net10.0/staticwebassets.build.endpoints.json,1779852473.9235973,1,,[MOD] net10.0/staticwebassets.build.endpoints.json +code,,1,17078b08abfd8d73947ea4f0646a9536,src\InventoryAlert.Api\obj\Debug\net10.0\staticwebassets.build.json,0,437,net10.0/staticwebassets.build.json,1779852473.9067118,1,efcore threshold notification dbcontext entity framework price drop loss asnotracking appdbcontext,[MOD] net10.0/staticwebassets.build.json +code,,1,764ba22cde656c91f3e05ba4bc7bbcee,src\InventoryAlert.Api\obj\Debug\net10.0\staticwebassets.development.json,0,438,net10.0/staticwebassets.development.json,1779852473.959113,1,notification threshold loss price drop,[MOD] net10.0/staticwebassets.development.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\InventoryAlert.Api\obj\Release\net10.0\InventoryAlert.Api.sourcelink.json,0,439,net10.0/InventoryAlert.Api.sourcelink.json,1779815051.57949,1,,[MOD] net10.0/InventoryAlert.Api.sourcelink.json +code,,1,7e624a148eaecf5c2b6ceaaf3e5768f0,src\InventoryAlert.Api\obj\Release\net10.0\rjimswa.dswa.cache.json,0,440,net10.0/rjimswa.dswa.cache.json,1779815054.6112003,1,,[MOD] net10.0/rjimswa.dswa.cache.json +code,,1,b84df256cb8903d3b1915c28b911d7e4,src\InventoryAlert.Api\obj\Release\net10.0\rjsmcshtml.dswa.cache.json,0,441,net10.0/rjsmcshtml.dswa.cache.json,1779815054.6249537,1,appdbcontext dbcontext asnotracking efcore entity framework,[MOD] net10.0/rjsmcshtml.dswa.cache.json +code,,1,2f1f62dd94cc4ed3b687993e59c4078f,src\InventoryAlert.Api\obj\Release\net10.0\rjsmrazor.dswa.cache.json,0,442,net10.0/rjsmrazor.dswa.cache.json,1779815054.6212788,1,entity framework dbcontext efcore asnotracking appdbcontext,[MOD] net10.0/rjsmrazor.dswa.cache.json +code,,1,3f9323e5fd2574dd3a281e2c6624aabc,src\InventoryAlert.Api\obj\Release\net10.0\rpswa.dswa.cache.json,0,443,net10.0/rpswa.dswa.cache.json,1779815051.0406187,1,notification threshold price drop loss,[MOD] net10.0/rpswa.dswa.cache.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\InventoryAlert.Api\obj\Release\net10.0\staticwebassets.build.endpoints.json,0,444,net10.0/staticwebassets.build.endpoints.json,1779815054.8447104,1,,[MOD] net10.0/staticwebassets.build.endpoints.json +code,,1,17cd3b4662f3d9650278496d54a7dce2,src\InventoryAlert.Api\obj\Release\net10.0\staticwebassets.build.json,0,445,net10.0/staticwebassets.build.json,1779815054.8249316,1,entity framework threshold notification loss efcore appdbcontext asnotracking dbcontext price drop,[MOD] net10.0/staticwebassets.build.json +code,,1,e6adbf2622be6f462ec396db3b4d5b74,src\InventoryAlert.Api\obj\Release\net10.0\staticwebassets.development.json,0,446,net10.0/staticwebassets.development.json,1779815054.8755307,1,loss notification threshold price drop,[MOD] net10.0/staticwebassets.development.json +code,,14,251c880b08d1d0344b8a79bdc2d8f6b6,src\InventoryAlert.Api\Properties\launchSettings.json,0,447,Properties/launchSettings.json,1779814416.2687397,1,,[MOD] Properties/launchSettings.json +code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,src\InventoryAlert.Domain\bin\Debug\net10.0\InventoryAlert.Domain.deps.json,0,448,net10.0/InventoryAlert.Domain.deps.json,1779852469.346435,1,efcore application service threshold notification business logic dbcontext iproductservice productservice entity framework price drop loss asnotracking appdbcontext,[MOD] net10.0/InventoryAlert.Domain.deps.json +code,,13,5e2fec3a44baa37dd9b51c63a09513c6,src\InventoryAlert.Domain\bin\Debug\net10.0\InventoryAlert.Domain.runtimeconfig.json,0,449,net10.0/InventoryAlert.Domain.runtimeconfig.json,1779852469.428257,1,entity framework efcore asnotracking appdbcontext dbcontext,[MOD] net10.0/InventoryAlert.Domain.runtimeconfig.json +code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,src\InventoryAlert.Domain\bin\Release\net10.0\InventoryAlert.Domain.deps.json,0,450,net10.0/InventoryAlert.Domain.deps.json,1779815048.8279152,1,entity framework iproductservice dbcontext appdbcontext business logic productservice price drop efcore asnotracking application service loss notification threshold,[MOD] net10.0/InventoryAlert.Domain.deps.json +code,,14,65e54446b7c5017d0110c783eff5a0a7,src\InventoryAlert.Domain\bin\Release\net10.0\InventoryAlert.Domain.runtimeconfig.json,0,451,net10.0/InventoryAlert.Domain.runtimeconfig.json,1779815048.917932,1,asnotracking entity framework dbcontext appdbcontext efcore,[MOD] net10.0/InventoryAlert.Domain.runtimeconfig.json +code,,487,a3646588e562c77f30898634dc070da8,src\InventoryAlert.Domain\obj\InventoryAlert.Domain.csproj.nuget.dgspec.json,0,452,obj/InventoryAlert.Domain.csproj.nuget.dgspec.json,1779852466.4043698,1,entity framework threshold efcore fluentassertions iproductservice xunit appdbcontext mock setup returns async dbcontext container price drop verify dockerfile notification productservice times once loss moq unit test arrange act assert postgresql compose application service postgres asnotracking business logic,[MOD] obj/InventoryAlert.Domain.csproj.nuget.dgspec.json +code,,3947,bc2197771b8b7519cbd868b96240ffb9,src\InventoryAlert.Domain\obj\project.assets.json,0,453,obj/project.assets.json,1779852437.3739333,1,notification asnotracking verify loss postgres times once mock setup unit test iproductservice entity framework productservice postgresql appdbcontext returns async efcore container business logic dockerfile threshold application service compose arrange act assert fluentassertions price drop xunit dbcontext moq,[MOD] obj/project.assets.json +code,,1,6615811e269d492d86e7412774dfa4bb,src\InventoryAlert.Domain\obj\project.packagespec.json,0,454,obj/project.packagespec.json,1779852069.8844283,1,efcore mock setup entity framework moq notification times once compose price drop returns async verify threshold unit test dockerfile asnotracking productservice fluentassertions dbcontext appdbcontext container postgresql postgres business logic loss xunit iproductservice arrange act assert application service,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\InventoryAlert.Domain\obj\Debug\net10.0\InventoryAlert.Domain.sourcelink.json,0,455,net10.0/InventoryAlert.Domain.sourcelink.json,1779852466.5571823,1,asnotracking dbcontext efcore appdbcontext entity framework,[MOD] net10.0/InventoryAlert.Domain.sourcelink.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\InventoryAlert.Domain\obj\Release\net10.0\InventoryAlert.Domain.sourcelink.json,0,456,net10.0/InventoryAlert.Domain.sourcelink.json,1779815043.777892,1,,[MOD] net10.0/InventoryAlert.Domain.sourcelink.json +code,,1204,cb0b59a46f14c231584e0f3eae18a84d,src\InventoryAlert.Infrastructure\bin\Debug\net10.0\InventoryAlert.Infrastructure.deps.json,0,457,net10.0/InventoryAlert.Infrastructure.deps.json,1779852470.849428,1,price drop application service asnotracking notification threshold productservice business logic loss appdbcontext iproductservice efcore entity framework dbcontext,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json +code,,19,7b716426e1deaae021de466b00b9f803,src\InventoryAlert.Infrastructure\bin\Debug\net10.0\InventoryAlert.Infrastructure.runtimeconfig.json,0,458,net10.0/InventoryAlert.Infrastructure.runtimeconfig.json,1779852470.9642072,1,asnotracking efcore appdbcontext dbcontext entity framework,[MOD] net10.0/InventoryAlert.Infrastructure.runtimeconfig.json +code,,1204,cb0b59a46f14c231584e0f3eae18a84d,src\InventoryAlert.Infrastructure\bin\Release\net10.0\InventoryAlert.Infrastructure.deps.json,0,459,net10.0/InventoryAlert.Infrastructure.deps.json,1779815050.7656255,1,loss appdbcontext efcore productservice business logic entity framework asnotracking threshold dbcontext notification application service iproductservice price drop,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json +code,,20,83d85af07448d5b73e11a316a264aa5c,src\InventoryAlert.Infrastructure\bin\Release\net10.0\InventoryAlert.Infrastructure.runtimeconfig.json,0,460,net10.0/InventoryAlert.Infrastructure.runtimeconfig.json,1779815050.8202472,1,asnotracking efcore appdbcontext entity framework dbcontext,[MOD] net10.0/InventoryAlert.Infrastructure.runtimeconfig.json +code,,1128,2d7885b1778636da9328d1f68f141ac0,src\InventoryAlert.Infrastructure\obj\InventoryAlert.Infrastructure.csproj.nuget.dgspec.json,0,461,obj/InventoryAlert.Infrastructure.csproj.nuget.dgspec.json,1779852466.4080687,1,notification compose returns async dbcontext productservice iproductservice price drop mock setup moq times once threshold arrange act assert entity framework xunit postgresql business logic unit test container asnotracking efcore appdbcontext verify fluentassertions application service postgres dockerfile loss,[MOD] obj/InventoryAlert.Infrastructure.csproj.nuget.dgspec.json +code,,3977,92bf71adc8ede55aef4b9bfae5ff36ca,src\InventoryAlert.Infrastructure\obj\project.assets.json,0,462,obj/project.assets.json,1779852466.3936245,1,iproductservice appdbcontext times once container verify returns async productservice dbcontext entity framework application service notification postgresql loss efcore mock setup business logic unit test xunit dockerfile postgres fluentassertions threshold moq price drop arrange act assert asnotracking compose,[MOD] obj/project.assets.json +code,,1,a414ded21d758ad9d04eab74cbf97453,src\InventoryAlert.Infrastructure\obj\project.packagespec.json,0,463,obj/project.packagespec.json,1779852070.0066042,1,efcore mock setup entity framework moq notification times once compose price drop returns async verify threshold unit test dockerfile asnotracking productservice fluentassertions dbcontext appdbcontext container postgresql postgres business logic loss xunit iproductservice arrange act assert application service,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\InventoryAlert.Infrastructure\obj\Debug\net10.0\InventoryAlert.Infrastructure.sourcelink.json,0,464,net10.0/InventoryAlert.Infrastructure.sourcelink.json,1779852469.5972724,1,appdbcontext asnotracking efcore entity framework dbcontext,[MOD] net10.0/InventoryAlert.Infrastructure.sourcelink.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\InventoryAlert.Infrastructure\obj\Release\net10.0\InventoryAlert.Infrastructure.sourcelink.json,0,465,net10.0/InventoryAlert.Infrastructure.sourcelink.json,1779815049.5787792,1,,[MOD] net10.0/InventoryAlert.Infrastructure.sourcelink.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\InventoryAlert.Worker\appsettings.Example.json,0,466,InventoryAlert.Worker/appsettings.Example.json,1779814416.3795497,1,compose efcore notification entity framework market data postgres asnotracking finnhubpricesyncworker quote threshold loss container postgresql hosted service backgroundservice external api periodictimer dockerfile stock price price drop dbcontext appdbcontext,[MOD] InventoryAlert.Worker/appsettings.Example.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\InventoryAlert.Worker\appsettings.json,0,467,InventoryAlert.Worker/appsettings.json,1779814416.3795497,1,entity framework notification loss efcore hosted service price drop finnhubpricesyncworker container postgresql stock price market data appdbcontext periodictimer dockerfile dbcontext external api compose quote threshold backgroundservice asnotracking postgres,[MOD] InventoryAlert.Worker/appsettings.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\InventoryAlert.Worker\bin\Debug\net10.0\appsettings.Example.json,0,468,net10.0/appsettings.Example.json,1779814416.3795497,1,hosted service market data postgresql asnotracking periodictimer entity framework container efcore backgroundservice quote stock price notification dbcontext finnhubpricesyncworker compose postgres external api price drop appdbcontext loss dockerfile threshold,[MOD] net10.0/appsettings.Example.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\InventoryAlert.Worker\bin\Debug\net10.0\appsettings.json,0,469,net10.0/appsettings.json,1779814416.3795497,1,notification asnotracking loss postgres periodictimer finnhubpricesyncworker entity framework postgresql market data appdbcontext efcore container backgroundservice quote dockerfile threshold compose price drop stock price dbcontext external api hosted service,[MOD] net10.0/appsettings.json +code,,1488,bbe0769f603dfb81733a7b52d5e43f76,src\InventoryAlert.Worker\bin\Debug\net10.0\InventoryAlert.Worker.deps.json,0,470,net10.0/InventoryAlert.Worker.deps.json,1779852473.908222,1,price drop appdbcontext business logic asnotracking backgroundservice periodictimer finnhubpricesyncworker loss threshold hosted service application service iproductservice productservice efcore dbcontext entity framework notification,[MOD] net10.0/InventoryAlert.Worker.deps.json +code,,20,37595336dae30b037bd95e5047b95825,src\InventoryAlert.Worker\bin\Debug\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,471,net10.0/InventoryAlert.Worker.runtimeconfig.json,1779852474.0111957,1,asnotracking entity framework dbcontext appdbcontext efcore,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json +code,,1,f44ca44dd881261586b84442f2201257,src\InventoryAlert.Worker\bin\Debug\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,472,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1779852473.689481,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\InventoryAlert.Worker\bin\Release\net10.0\appsettings.Example.json,0,473,net10.0/appsettings.Example.json,1779814416.3795497,1,efcore entity framework notification compose price drop hosted service market data finnhubpricesyncworker threshold backgroundservice asnotracking dockerfile external api periodictimer dbcontext appdbcontext container postgresql postgres stock price loss quote,[MOD] net10.0/appsettings.Example.json +code,,1488,bbe0769f603dfb81733a7b52d5e43f76,src\InventoryAlert.Worker\bin\Release\net10.0\InventoryAlert.Worker.deps.json,0,474,net10.0/InventoryAlert.Worker.deps.json,1779815054.685102,1,finnhubpricesyncworker business logic iproductservice entity framework application service threshold notification loss efcore productservice appdbcontext asnotracking backgroundservice hosted service periodictimer dbcontext price drop,[MOD] net10.0/InventoryAlert.Worker.deps.json +code,,21,d60cf9618363ac73f5894cceaffc545e,src\InventoryAlert.Worker\bin\Release\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,475,net10.0/InventoryAlert.Worker.runtimeconfig.json,1779815054.7921462,1,appdbcontext dbcontext asnotracking efcore entity framework,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json +code,,1,f44ca44dd881261586b84442f2201257,src\InventoryAlert.Worker\bin\Release\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,476,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1779815054.3388731,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json +code,,1757,965eda2e636b7c3550d8e1670db42b51,src\InventoryAlert.Worker\obj\InventoryAlert.Worker.csproj.nuget.dgspec.json,0,477,obj/InventoryAlert.Worker.csproj.nuget.dgspec.json,1779852466.4080687,1,postgresql times once fluentassertions finnhubpricesyncworker xunit container iproductservice efcore unit test dbcontext productservice price drop hosted service compose periodictimer moq postgres entity framework threshold application service mock setup appdbcontext asnotracking business logic backgroundservice verify returns async notification arrange act assert dockerfile loss,[MOD] obj/InventoryAlert.Worker.csproj.nuget.dgspec.json +code,,4546,b2d3796b41aab006b9cbc9a53f55c84f,src\InventoryAlert.Worker\obj\project.assets.json,0,478,obj/project.assets.json,1779852466.3946185,1,hosted service application service postgresql asnotracking periodictimer times once entity framework container productservice xunit efcore backgroundservice notification dbcontext finnhubpricesyncworker verify business logic returns async fluentassertions mock setup compose arrange act assert postgres price drop appdbcontext loss unit test dockerfile threshold iproductservice moq,[MOD] obj/project.assets.json +code,,1,8e70a2013c755662101986942328fe2b,src\InventoryAlert.Worker\obj\project.packagespec.json,0,479,obj/project.packagespec.json,1779852070.1757035,1,notification asnotracking verify loss postgres periodictimer times once mock setup unit test finnhubpricesyncworker iproductservice entity framework productservice postgresql appdbcontext returns async efcore container backgroundservice business logic dockerfile threshold application service compose arrange act assert fluentassertions price drop xunit dbcontext moq hosted service,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\InventoryAlert.Worker\obj\Debug\net10.0\InventoryAlert.Worker.sourcelink.json,0,480,net10.0/InventoryAlert.Worker.sourcelink.json,1779852471.388923,1,efcore dbcontext entity framework asnotracking appdbcontext,[MOD] net10.0/InventoryAlert.Worker.sourcelink.json +code,,1,163140e11b00a50363df942dc5c36791,src\InventoryAlert.Worker\obj\Debug\net10.0\rjsmcshtml.dswa.cache.json,0,481,net10.0/rjsmcshtml.dswa.cache.json,1779853358.9924874,1,asnotracking entity framework dbcontext domain entity infrastructure domain driven design appdbcontext application layer efcore,[MOD] net10.0/rjsmcshtml.dswa.cache.json +code,,1,166afa0f926568e00cd2643c83d7e309,src\InventoryAlert.Worker\obj\Debug\net10.0\rjsmrazor.dswa.cache.json,0,482,net10.0/rjsmrazor.dswa.cache.json,1779853358.990983,1,entity framework dbcontext efcore application layer domain entity appdbcontext domain driven design asnotracking infrastructure,[MOD] net10.0/rjsmrazor.dswa.cache.json +code,,1,76be052ee6498931745be8b1ef0eebf8,src\InventoryAlert.Worker\obj\Debug\net10.0\rpswa.dswa.cache.json,0,483,net10.0/rpswa.dswa.cache.json,1779853358.8428116,1,,[MOD] net10.0/rpswa.dswa.cache.json +code,,1,f44ca44dd881261586b84442f2201257,src\InventoryAlert.Worker\obj\Debug\net10.0\staticwebassets.build.endpoints.json,0,484,net10.0/staticwebassets.build.endpoints.json,1779852473.689481,1,,[MOD] net10.0/staticwebassets.build.endpoints.json +code,,1,6155a156ae4b5c7a22d70b19468ea2f9,src\InventoryAlert.Worker\obj\Debug\net10.0\staticwebassets.build.json,0,485,net10.0/staticwebassets.build.json,1779852473.677951,1,loss appdbcontext efcore backgroundservice hosted service periodictimer entity framework asnotracking finnhubpricesyncworker threshold dbcontext notification price drop,[MOD] net10.0/staticwebassets.build.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\InventoryAlert.Worker\obj\Release\net10.0\InventoryAlert.Worker.sourcelink.json,0,486,net10.0/InventoryAlert.Worker.sourcelink.json,1779815051.1105301,1,,[MOD] net10.0/InventoryAlert.Worker.sourcelink.json +code,,1,1cf70aef6bc8ffb78284118145c391a0,src\InventoryAlert.Worker\obj\Release\net10.0\rjsmcshtml.dswa.cache.json,0,487,net10.0/rjsmcshtml.dswa.cache.json,1779815054.173619,1,,[MOD] net10.0/rjsmcshtml.dswa.cache.json +code,,1,cbd73f4a56f802708f0cdfbcb0100d02,src\InventoryAlert.Worker\obj\Release\net10.0\rjsmrazor.dswa.cache.json,0,488,net10.0/rjsmrazor.dswa.cache.json,1779815054.16978,1,,[MOD] net10.0/rjsmrazor.dswa.cache.json +code,,1,90fc0d487a214b647862afa7d978eee2,src\InventoryAlert.Worker\obj\Release\net10.0\rpswa.dswa.cache.json,0,489,net10.0/rpswa.dswa.cache.json,1779815050.963398,1,,[MOD] net10.0/rpswa.dswa.cache.json +code,,1,f44ca44dd881261586b84442f2201257,src\InventoryAlert.Worker\obj\Release\net10.0\staticwebassets.build.endpoints.json,0,490,net10.0/staticwebassets.build.endpoints.json,1779815054.3388731,1,,[MOD] net10.0/staticwebassets.build.endpoints.json +code,,1,6155a156ae4b5c7a22d70b19468ea2f9,src\InventoryAlert.Worker\obj\Release\net10.0\staticwebassets.build.json,0,491,net10.0/staticwebassets.build.json,1779815054.3257694,1,entity framework threshold notification asnotracking efcore appdbcontext periodictimer backgroundservice price drop loss hosted service dbcontext finnhubpricesyncworker,[MOD] net10.0/staticwebassets.build.json +code,,12,f5fda86557b5826bd2813eb658c10141,src\InventoryAlert.Worker\Properties\launchSettings.json,0,492,Properties/launchSettings.json,1779814416.3758423,1,hosted service price drop backgroundservice finnhubpricesyncworker periodictimer threshold notification loss,[MOD] Properties/launchSettings.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\appsettings.Example.json,0,493,net10.0/appsettings.Example.json,1779814416.3795497,1,entity framework threshold efcore finnhubpricesyncworker stock price periodictimer quote appdbcontext dbcontext hosted service container price drop dockerfile notification loss external api postgresql market data compose postgres asnotracking backgroundservice,[MOD] net10.0/appsettings.Example.json +code,,1785,ace06dcdfed963a769231bf7d3d17433,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Api.deps.json,0,494,net10.0/InventoryAlert.Api.deps.json,1779852474.218987,1,productservice business logic dbcontext entity framework application service asnotracking notification iproductservice appdbcontext loss threshold efcore price drop,[MOD] net10.0/InventoryAlert.Api.deps.json +code,,20,37595336dae30b037bd95e5047b95825,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Api.runtimeconfig.json,0,495,net10.0/InventoryAlert.Api.runtimeconfig.json,1779852474.3064263,1,asnotracking efcore appdbcontext entity framework dbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,496,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1779852473.9235973,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json +code,,1,764ba22cde656c91f3e05ba4bc7bbcee,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,497,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1779852473.959113,1,loss notification threshold price drop,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json +code,,1763,73f69f12216f085cd979769745a7fed7,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.ArchitectureTests.deps.json,0,498,net10.0/InventoryAlert.ArchitectureTests.deps.json,1779852475.4965074,1,entity framework notification loss efcore hosted service unit test price drop finnhubpricesyncworker business logic iproductservice productservice appdbcontext periodictimer dbcontext fluentassertions application service arrange act assert threshold backgroundservice asnotracking xunit,[MOD] net10.0/InventoryAlert.ArchitectureTests.deps.json +code,,20,5f3a2d98fc24aa854c5b9344a7a4d157,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.ArchitectureTests.runtimeconfig.json,0,499,net10.0/InventoryAlert.ArchitectureTests.runtimeconfig.json,1779852475.5847888,1,entity framework efcore asnotracking xunit unit test dbcontext appdbcontext fluentassertions arrange act assert,[MOD] net10.0/InventoryAlert.ArchitectureTests.runtimeconfig.json +code,,1488,bbe0769f603dfb81733a7b52d5e43f76,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Worker.deps.json,0,500,net10.0/InventoryAlert.Worker.deps.json,1779852473.908222,1,hosted service business logic application service productservice price drop appdbcontext asnotracking loss efcore periodictimer backgroundservice finnhubpricesyncworker entity framework notification threshold iproductservice dbcontext,[MOD] net10.0/InventoryAlert.Worker.deps.json +code,,20,37595336dae30b037bd95e5047b95825,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,501,net10.0/InventoryAlert.Worker.runtimeconfig.json,1779852474.0111957,1,asnotracking entity framework dbcontext appdbcontext efcore,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json +code,,1,f44ca44dd881261586b84442f2201257,src\test\InventoryAlert.ArchitectureTests\bin\Debug\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,502,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1779852473.689481,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\appsettings.Example.json,0,503,net10.0/appsettings.Example.json,1779814416.3795497,1,entity framework threshold efcore finnhubpricesyncworker stock price periodictimer quote appdbcontext dbcontext hosted service container price drop dockerfile notification loss external api postgresql market data compose postgres asnotracking backgroundservice,[MOD] net10.0/appsettings.Example.json +code,,1785,ace06dcdfed963a769231bf7d3d17433,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Api.deps.json,0,504,net10.0/InventoryAlert.Api.deps.json,1779815055.0786984,1,asnotracking productservice price drop notification loss business logic efcore appdbcontext application service threshold iproductservice entity framework dbcontext,[MOD] net10.0/InventoryAlert.Api.deps.json +code,,21,d60cf9618363ac73f5894cceaffc545e,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Api.runtimeconfig.json,0,505,net10.0/InventoryAlert.Api.runtimeconfig.json,1779815055.1578588,1,entity framework efcore asnotracking appdbcontext dbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,506,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1779815054.8447104,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json +code,,1,e6adbf2622be6f462ec396db3b4d5b74,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,507,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1779815054.8755307,1,price drop threshold loss notification,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json +code,,1763,73f69f12216f085cd979769745a7fed7,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.ArchitectureTests.deps.json,0,508,net10.0/InventoryAlert.ArchitectureTests.deps.json,1779815056.449929,1,price drop appdbcontext arrange act assert application service asnotracking periodictimer hosted service xunit productservice business logic finnhubpricesyncworker backgroundservice iproductservice unit test fluentassertions entity framework notification loss threshold efcore dbcontext,[MOD] net10.0/InventoryAlert.ArchitectureTests.deps.json +code,,21,11a2057f7e08545a87eae55a47ccbe16,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.ArchitectureTests.runtimeconfig.json,0,509,net10.0/InventoryAlert.ArchitectureTests.runtimeconfig.json,1779815056.5272791,1,entity framework fluentassertions arrange act assert efcore appdbcontext asnotracking xunit unit test dbcontext,[MOD] net10.0/InventoryAlert.ArchitectureTests.runtimeconfig.json +code,,1488,bbe0769f603dfb81733a7b52d5e43f76,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Worker.deps.json,0,510,net10.0/InventoryAlert.Worker.deps.json,1779815054.685102,1,finnhubpricesyncworker entity framework iproductservice dbcontext appdbcontext business logic productservice price drop efcore hosted service asnotracking application service backgroundservice periodictimer loss notification threshold,[MOD] net10.0/InventoryAlert.Worker.deps.json +code,,21,d60cf9618363ac73f5894cceaffc545e,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,511,net10.0/InventoryAlert.Worker.runtimeconfig.json,1779815054.7921462,1,appdbcontext dbcontext asnotracking efcore entity framework,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json +code,,1,f44ca44dd881261586b84442f2201257,src\test\InventoryAlert.ArchitectureTests\bin\Release\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,512,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1779815054.3388731,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json +code,,2873,8e7ff294354eeb80953a46f787686afd,src\test\InventoryAlert.ArchitectureTests\obj\InventoryAlert.ArchitectureTests.csproj.nuget.dgspec.json,0,513,obj/InventoryAlert.ArchitectureTests.csproj.nuget.dgspec.json,1779852466.4069126,1,asnotracking entity framework dockerfile notification hosted service efcore fluentassertions periodictimer times once arrange act assert compose postgres appdbcontext moq business logic postgresql productservice loss xunit returns async container mock setup dbcontext unit test application service backgroundservice verify threshold iproductservice finnhubpricesyncworker price drop,[MOD] obj/InventoryAlert.ArchitectureTests.csproj.nuget.dgspec.json +code,,5678,339e0b64e8667842154e75d3591886c3,src\test\InventoryAlert.ArchitectureTests\obj\project.assets.json,0,514,obj/project.assets.json,1779852466.3926091,1,postgresql threshold productservice container mock setup business logic compose verify arrange act assert fluentassertions price drop moq returns async dockerfile dbcontext postgres finnhubpricesyncworker iproductservice unit test periodictimer times once loss hosted service entity framework notification asnotracking efcore application service appdbcontext backgroundservice xunit,[MOD] obj/project.assets.json +code,,1,b37f96f2d22e648b6f5c4bb95e85c6c3,src\test\InventoryAlert.ArchitectureTests\obj\project.packagespec.json,0,515,obj/project.packagespec.json,1779852403.7204163,1,loss arrange act assert postgresql appdbcontext productservice postgres finnhubpricesyncworker fluentassertions dbcontext backgroundservice hosted service periodictimer entity framework application service dockerfile price drop moq business logic times once asnotracking threshold compose notification returns async efcore xunit container mock setup verify unit test iproductservice,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\test\InventoryAlert.ArchitectureTests\obj\Debug\net10.0\InventoryAlert.ArchitectureTests.sourcelink.json,0,516,net10.0/InventoryAlert.ArchitectureTests.sourcelink.json,1779852474.781735,1,entity framework dbcontext efcore asnotracking appdbcontext,[MOD] net10.0/InventoryAlert.ArchitectureTests.sourcelink.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\test\InventoryAlert.ArchitectureTests\obj\Release\net10.0\InventoryAlert.ArchitectureTests.sourcelink.json,0,517,net10.0/InventoryAlert.ArchitectureTests.sourcelink.json,1779815055.7666128,1,,[MOD] net10.0/InventoryAlert.ArchitectureTests.sourcelink.json +code,,1192,9a9cad09b63e93e58b18f149578880cb,src\test\InventoryAlert.E2ETests\bin\Debug\net10.0\InventoryAlert.E2ETests.deps.json,0,518,net10.0/InventoryAlert.E2ETests.deps.json,1779852470.841201,1,iproductservice efcore application service business logic fluentassertions entity framework loss xunit threshold unit test dbcontext appdbcontext asnotracking notification arrange act assert price drop productservice,[MOD] net10.0/InventoryAlert.E2ETests.deps.json +code,,14,0e71cccfa0816f7f0e9c53a23c96a205,src\test\InventoryAlert.E2ETests\bin\Debug\net10.0\InventoryAlert.E2ETests.runtimeconfig.json,0,519,net10.0/InventoryAlert.E2ETests.runtimeconfig.json,1779852470.938166,1,asnotracking fluentassertions arrange act assert appdbcontext xunit unit test efcore entity framework dbcontext,[MOD] net10.0/InventoryAlert.E2ETests.runtimeconfig.json +code,,1192,9a9cad09b63e93e58b18f149578880cb,src\test\InventoryAlert.E2ETests\bin\Release\net10.0\InventoryAlert.E2ETests.deps.json,0,520,net10.0/InventoryAlert.E2ETests.deps.json,1779815050.7708027,1,business logic notification asnotracking fluentassertions loss price drop threshold appdbcontext unit test efcore application service iproductservice xunit dbcontext entity framework productservice arrange act assert,[MOD] net10.0/InventoryAlert.E2ETests.deps.json +code,,15,5f7047d258573e95125f9cc3ab6529c4,src\test\InventoryAlert.E2ETests\bin\Release\net10.0\InventoryAlert.E2ETests.runtimeconfig.json,0,521,net10.0/InventoryAlert.E2ETests.runtimeconfig.json,1779815050.830553,1,unit test appdbcontext dbcontext asnotracking efcore xunit fluentassertions entity framework arrange act assert,[MOD] net10.0/InventoryAlert.E2ETests.runtimeconfig.json +code,,933,3a994695e4a0477b5deaccbc5a0d38da,src\test\InventoryAlert.E2ETests\obj\InventoryAlert.E2ETests.csproj.nuget.dgspec.json,0,522,obj/InventoryAlert.E2ETests.csproj.nuget.dgspec.json,1779852466.4069126,1,postgresql business logic postgres moq iproductservice entity framework loss fluentassertions application service mock setup dbcontext compose returns async xunit productservice times once container efcore verify notification dockerfile price drop unit test appdbcontext threshold arrange act assert asnotracking,[MOD] obj/InventoryAlert.E2ETests.csproj.nuget.dgspec.json +code,,3216,471aa56020a29d70ce55b8efca75760e,src\test\InventoryAlert.E2ETests\obj\project.assets.json,0,523,obj/project.assets.json,1779852466.3895667,1,entity framework threshold efcore fluentassertions iproductservice xunit appdbcontext mock setup returns async dbcontext container price drop verify dockerfile notification productservice times once loss moq unit test arrange act assert postgresql compose application service postgres asnotracking business logic,[MOD] obj/project.assets.json +code,,1,720866dd97a0219529ce56ca8d97afd4,src\test\InventoryAlert.E2ETests\obj\project.packagespec.json,0,524,obj/project.packagespec.json,1779852408.047456,1,loss arrange act assert postgresql appdbcontext productservice postgres fluentassertions dbcontext entity framework application service dockerfile price drop moq business logic times once asnotracking threshold compose notification returns async efcore xunit container mock setup verify unit test iproductservice,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\test\InventoryAlert.E2ETests\obj\Debug\net10.0\InventoryAlert.E2ETests.sourcelink.json,0,525,net10.0/InventoryAlert.E2ETests.sourcelink.json,1779852469.6458607,1,asnotracking dbcontext efcore appdbcontext entity framework,[MOD] net10.0/InventoryAlert.E2ETests.sourcelink.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\test\InventoryAlert.E2ETests\obj\Release\net10.0\InventoryAlert.E2ETests.sourcelink.json,0,526,net10.0/InventoryAlert.E2ETests.sourcelink.json,1779815049.5690334,1,,[MOD] net10.0/InventoryAlert.E2ETests.sourcelink.json +code,,33,9b5dea32c79876c723aef63bd81f478a,src\test\InventoryAlert.IntegrationTests\appsettings.test.json,0,527,InventoryAlert.IntegrationTests/appsettings.test.json,1779814416.3505743,1,appdbcontext times once verify returns async dbcontext entity framework external api market data notification loss efcore mock setup unit test xunit quote fluentassertions threshold moq price drop stock price arrange act assert asnotracking,[MOD] InventoryAlert.IntegrationTests/appsettings.test.json doc,"# Integration Testing Framework: Implementation Guide This guide provides a step-by-step blueprint for building a professional-grade integration testing framework for the **InventoryAlert.Api** and **InventoryAlert.Worker**. @@ -19626,129 +21670,301 @@ InventoryAlert.IntegrationTests/ --- > [!IMPORTANT] -> **Data Seed Note**: Do not rely on production seed data. Every test should ""Arrange"" its own data or use a minimal `TestSeeder` to ensure predictable outcomes.",166,fd6f15ad1e2295da23429174ddd50fa8,InventoryManagementSystem\InventoryAlert.IntegrationTests\INTEGRATION_TEST_PLAN.md,0,499,"test, step, testing, inventoryalert, testcontainers, class, dotnet, project",1776073560.0211427,1,postgresql stock price stock ticker msft asnotracking mock setup xunit external api commit unitofwork postgres finnhubpricesyncworker container savechanges rollback inventory dbcontext googl fluentassertions aapl verify unit test threshold hosted service compose symbol moq item quote loss add-migration efcore stock notification application service arrange act assert schema change entity framework sku database update returns async market data atomicity periodictimer backgroundservice iproductservice price drop times once productservice appdbcontext dockerfile efcore migration business logic,# Integration Testing Framework: Implementation Guide | Integration Testing Framework: Implementation Guide This guide provides a step-b -code,,33,4d6bffd1f43d0997afb15365806311b3,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\appsettings.Development.json,0,500,net10.0/appsettings.Development.json,1776152647.4113853,1,external api entity framework notification stock price quote efcore dbcontext asnotracking loss appdbcontext threshold market data price drop,[MOD] net10.0/appsettings.Development.json -code,,40,72721ed03133bc70c1c477050ca0cd49,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\appsettings.Docker.json,0,501,net10.0/appsettings.Docker.json,1777114850.0531414,1,external api efcore dbcontext market data price drop loss stock price entity framework threshold quote asnotracking notification appdbcontext,[MOD] net10.0/appsettings.Docker.json -code,,34,f30503f11ca8f3574148588cc789c353,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\appsettings.Example.json,0,502,net10.0/appsettings.Example.json,1777190443.277019,1,entity framework threshold market data efcore stock price external api quote postgresql dbcontext appdbcontext loss container price drop dockerfile postgres compose notification asnotracking,[MOD] net10.0/appsettings.Example.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\appsettings.json,0,503,net10.0/appsettings.json,1776152652.9040236,1,asnotracking loss threshold efcore quote stock price external api notification entity framework dbcontext market data price drop appdbcontext,[MOD] net10.0/appsettings.json -code,,14,329d29c031280e0b91b8a7b63145ce47,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\appsettings.test.json,0,504,net10.0/appsettings.test.json,1777098229.7782145,1,arrange act assert returns async moq mock setup times once xunit verify fluentassertions unit test,[MOD] net10.0/appsettings.test.json -code,,1781,869a0d34545367fdc29df517b815cc3e,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Api.deps.json,0,505,net10.0/InventoryAlert.Api.deps.json,1777190540.2914839,1,notification productservice dbcontext entity framework appdbcontext price drop loss asnotracking business logic efcore threshold iproductservice application service,[MOD] net10.0/InventoryAlert.Api.deps.json -code,,20,37595336dae30b037bd95e5047b95825,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Api.runtimeconfig.json,0,506,net10.0/InventoryAlert.Api.runtimeconfig.json,1775367661.9960494,1,efcore dbcontext appdbcontext asnotracking entity framework,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,507,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1776140330.4713986,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json -code,,1,acbe4a57a0230c6e9b12318544965c2f,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,508,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1776908467.097591,1,loss price drop notification threshold,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json -code,,1853,8c1306b42c8cabe742f84e71c5caeb69,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.IntegrationTests.deps.json,0,509,net10.0/InventoryAlert.IntegrationTests.deps.json,1777190547.4360583,1,price drop entity framework efcore notification arrange act assert finnhubpricesyncworker appdbcontext business logic application service postgres loss container dockerfile periodictimer compose iproductservice dbcontext xunit unit test asnotracking fluentassertions postgresql backgroundservice hosted service productservice threshold,[MOD] net10.0/InventoryAlert.IntegrationTests.deps.json -code,,20,5f3a2d98fc24aa854c5b9344a7a4d157,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.IntegrationTests.runtimeconfig.json,0,510,net10.0/InventoryAlert.IntegrationTests.runtimeconfig.json,1775367663.1248598,1,arrange act assert asnotracking unit test xunit efcore dbcontext appdbcontext entity framework fluentassertions,[MOD] net10.0/InventoryAlert.IntegrationTests.runtimeconfig.json -code,,1484,2715841f88b7f187dd9c768d43ae51d9,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Worker.deps.json,0,511,net10.0/InventoryAlert.Worker.deps.json,1777190539.783416,1,finnhubpricesyncworker productservice entity framework appdbcontext notification business logic dbcontext threshold application service efcore price drop hosted service backgroundservice asnotracking loss periodictimer iproductservice,[MOD] net10.0/InventoryAlert.Worker.deps.json -code,,20,37595336dae30b037bd95e5047b95825,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,512,net10.0/InventoryAlert.Worker.runtimeconfig.json,1777190539.7875724,1,appdbcontext asnotracking efcore entity framework dbcontext,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,513,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1776176577.985349,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json -code,,27,57367df713567d4461e67390da6507c8,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\appsettings.Development.json,0,514,net10.0/appsettings.Development.json,1776152660.5062368,1,loss dbcontext notification efcore stock price price drop threshold quote entity framework appdbcontext asnotracking market data external api,[MOD] net10.0/appsettings.Development.json -code,,27,5329bf770a0b5ec2c5b28243f61d6377,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\appsettings.Docker.json,0,515,net10.0/appsettings.Docker.json,1776152427.4607298,1,notification entity framework threshold stock price quote market data efcore dbcontext price drop external api appdbcontext loss asnotracking,[MOD] net10.0/appsettings.Docker.json -code,,28,3b1239472906a13429a1c76f242c5c0a,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\appsettings.Example.json,0,516,net10.0/appsettings.Example.json,1776152663.8011956,1,loss dockerfile price drop entity framework notification compose postgres postgresql appdbcontext efcore threshold stock price asnotracking external api market data dbcontext quote container,[MOD] net10.0/appsettings.Example.json -code,,27,5329bf770a0b5ec2c5b28243f61d6377,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\appsettings.json,0,517,net10.0/appsettings.json,1776152666.6315463,1,loss price drop entity framework notification appdbcontext efcore threshold stock price asnotracking external api market data dbcontext quote,[MOD] net10.0/appsettings.json -code,,1713,322fbe3f71679c335ba0563804aa7b61,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Api.deps.json,0,518,net10.0/InventoryAlert.Api.deps.json,1776317847.379226,1,efcore application service price drop iproductservice threshold dbcontext productservice notification appdbcontext loss asnotracking business logic entity framework,[MOD] net10.0/InventoryAlert.Api.deps.json -code,,21,d60cf9618363ac73f5894cceaffc545e,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Api.runtimeconfig.json,0,519,net10.0/InventoryAlert.Api.runtimeconfig.json,1776317847.4107525,1,efcore entity framework dbcontext appdbcontext asnotracking,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,520,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1776317847.2301905,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json -code,,1715,18d7c8b6e87ba4fcea7d364bbfc5623a,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.IntegrationTests.deps.json,0,521,net10.0/InventoryAlert.IntegrationTests.deps.json,1776317850.135573,1,notification arrange act assert fluentassertions price drop dbcontext postgresql container business logic unit test entity framework efcore xunit postgres threshold compose productservice dockerfile application service appdbcontext loss iproductservice asnotracking,[MOD] net10.0/InventoryAlert.IntegrationTests.deps.json -code,,21,11a2057f7e08545a87eae55a47ccbe16,InventoryManagementSystem\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.IntegrationTests.runtimeconfig.json,0,522,net10.0/InventoryAlert.IntegrationTests.runtimeconfig.json,1776317850.18185,1,dbcontext unit test fluentassertions efcore arrange act assert entity framework appdbcontext xunit asnotracking,[MOD] net10.0/InventoryAlert.IntegrationTests.runtimeconfig.json -code,,2843,89264e2dd8b13192cf1c06500dc2a827,InventoryManagementSystem\InventoryAlert.IntegrationTests\obj\InventoryAlert.IntegrationTests.csproj.nuget.dgspec.json,0,523,obj/InventoryAlert.IntegrationTests.csproj.nuget.dgspec.json,1777190308.7972503,1,dbcontext periodictimer iproductservice threshold backgroundservice fluentassertions notification arrange act assert hosted service entity framework application service xunit unit test appdbcontext business logic finnhubpricesyncworker price drop efcore productservice asnotracking loss,[MOD] obj/InventoryAlert.IntegrationTests.csproj.nuget.dgspec.json -code,,5909,79d80d04956570ae9bfe98ca2f33a1c0,InventoryManagementSystem\InventoryAlert.IntegrationTests\obj\project.assets.json,0,524,obj/project.assets.json,1777190308.7837257,1,notification asnotracking business logic postgresql application service xunit price drop arrange act assert periodictimer backgroundservice iproductservice compose productservice loss fluentassertions postgres finnhubpricesyncworker dbcontext unit test entity framework appdbcontext container efcore threshold dockerfile hosted service,[MOD] obj/project.assets.json -code,,1,e1c58c3254715160a2883d4d44e6ea91,InventoryManagementSystem\InventoryAlert.IntegrationTests\obj\project.packagespec.json,0,525,obj/project.packagespec.json,1777190305.6718078,1,appdbcontext iproductservice asnotracking productservice entity framework unit test hosted service loss xunit notification dbcontext price drop periodictimer arrange act assert finnhubpricesyncworker backgroundservice efcore fluentassertions application service business logic threshold,[MOD] obj/project.packagespec.json -code,,1,9781dd6d356826d311887c1e4bd62b4f,InventoryManagementSystem\InventoryAlert.IntegrationTests\obj\Debug\net10.0\InventoryAlert.IntegrationTests.sourcelink.json,0,526,net10.0/InventoryAlert.IntegrationTests.sourcelink.json,1777190547.093944,1,appdbcontext efcore dbcontext asnotracking entity framework,[MOD] net10.0/InventoryAlert.IntegrationTests.sourcelink.json -code,,1,b4bc405b4c07cf3b59a86a282bac2314,InventoryManagementSystem\InventoryAlert.IntegrationTests\obj\Release\net10.0\InventoryAlert.IntegrationTests.sourcelink.json,0,527,net10.0/InventoryAlert.IntegrationTests.sourcelink.json,1776517509.6770372,1,,[MOD] net10.0/InventoryAlert.IntegrationTests.sourcelink.json -code,,18,6f1b5171dca185426cce3bfb84627eab,InventoryManagementSystem\InventoryAlert.IntegrationTests\Wiremock\mappings\check-wiremock.json,0,528,mappings/check-wiremock.json,1777190302.5346582,1,mock setup returns async times once verify moq,[MOD] mappings/check-wiremock.json -code,,34,f9beb08cee7c8f5e1e52f603f01b0e96,InventoryManagementSystem\InventoryAlert.IntegrationTests\Wiremock\mappings\get-profile.json,0,529,mappings/get-profile.json,1777190302.54211,1,quote external api aapl symbol googl msft market data stock price stock ticker,[MOD] mappings/get-profile.json -code,,30,c981563ebf6ebf4b12105efe419f3a4f,InventoryManagementSystem\InventoryAlert.IntegrationTests\Wiremock\mappings\get-quote.json,0,530,mappings/get-quote.json,1777190302.546761,1,,[MOD] mappings/get-quote.json -code,,718,ffcd40667082383b6f0962b242cf767d,InventoryManagementSystem\InventoryAlert.Sample\bin\Debug\net10.0\InventoryAlert.Sample.deps.json,0,531,net10.0/InventoryAlert.Sample.deps.json,1776140330.0011876,1,price drop application service entity framework asnotracking dbcontext loss threshold iproductservice productservice appdbcontext notification business logic efcore,[MOD] net10.0/InventoryAlert.Sample.deps.json -code,,13,5e2fec3a44baa37dd9b51c63a09513c6,InventoryManagementSystem\InventoryAlert.Sample\bin\Debug\net10.0\InventoryAlert.Sample.runtimeconfig.json,0,532,net10.0/InventoryAlert.Sample.runtimeconfig.json,1775561754.1899705,1,asnotracking appdbcontext dbcontext entity framework efcore,[MOD] net10.0/InventoryAlert.Sample.runtimeconfig.json -code,,718,ffcd40667082383b6f0962b242cf767d,InventoryManagementSystem\InventoryAlert.Sample\bin\Release\net10.0\InventoryAlert.Sample.deps.json,0,533,net10.0/InventoryAlert.Sample.deps.json,1776315556.6864054,1,loss dbcontext notification productservice iproductservice efcore price drop application service threshold entity framework appdbcontext business logic asnotracking,[MOD] net10.0/InventoryAlert.Sample.deps.json -code,,14,65e54446b7c5017d0110c783eff5a0a7,InventoryManagementSystem\InventoryAlert.Sample\bin\Release\net10.0\InventoryAlert.Sample.runtimeconfig.json,0,534,net10.0/InventoryAlert.Sample.runtimeconfig.json,1776315556.7362208,1,efcore asnotracking appdbcontext dbcontext entity framework,[MOD] net10.0/InventoryAlert.Sample.runtimeconfig.json -code,,896,2c60c638448e9748cc4b582b6e0c38be,InventoryManagementSystem\InventoryAlert.Sample\obj\InventoryAlert.Sample.csproj.nuget.dgspec.json,0,535,obj/InventoryAlert.Sample.csproj.nuget.dgspec.json,1777190308.8092766,1,entity framework threshold application service efcore productservice dbcontext fluentassertions appdbcontext iproductservice loss business logic arrange act assert unit test price drop xunit asnotracking notification,[MOD] obj/InventoryAlert.Sample.csproj.nuget.dgspec.json -code,,2153,68c4b21e7ca008bf175b38c76616ff8e,InventoryManagementSystem\InventoryAlert.Sample\obj\project.assets.json,0,536,obj/project.assets.json,1777190308.7837257,1,asnotracking iproductservice loss fluentassertions arrange act assert threshold business logic efcore xunit notification productservice entity framework unit test dbcontext application service price drop appdbcontext,[MOD] obj/project.assets.json -code,,1,9872ddfbae401198dcba19389eb45f38,InventoryManagementSystem\InventoryAlert.Sample\obj\project.packagespec.json,0,537,obj/project.packagespec.json,1777190304.869259,1,xunit threshold productservice appdbcontext price drop application service asnotracking iproductservice unit test dbcontext loss business logic arrange act assert fluentassertions entity framework efcore notification,[MOD] obj/project.packagespec.json -code,,1,0df8c99f250429caebe480676825bd92,InventoryManagementSystem\InventoryAlert.Sample\obj\Debug\net10.0\InventoryAlert.Sample.sourcelink.json,0,538,net10.0/InventoryAlert.Sample.sourcelink.json,1777113419.2044995,1,,[MOD] net10.0/InventoryAlert.Sample.sourcelink.json -code,,1,6617e48d3582564c683c0b60e4d95c57,InventoryManagementSystem\InventoryAlert.Sample\obj\Release\net10.0\InventoryAlert.Sample.sourcelink.json,0,539,net10.0/InventoryAlert.Sample.sourcelink.json,1776315555.8231874,1,,[MOD] net10.0/InventoryAlert.Sample.sourcelink.json -code,,23,cd9d5cdb6ca1d9be49fecd5c887df1f9,InventoryManagementSystem\InventoryAlert.UnitTests\appsettings.json,0,540,InventoryAlert.UnitTests/appsettings.json,1776070839.3994565,1,dbcontext fluentassertions unit test returns async times once asnotracking efcore entity framework arrange act assert verify appdbcontext mock setup xunit moq,[MOD] InventoryAlert.UnitTests/appsettings.json -code,,33,4d6bffd1f43d0997afb15365806311b3,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\appsettings.Development.json,0,541,net10.0/appsettings.Development.json,1776152647.4113853,1,loss dbcontext stock price notification external api quote threshold entity framework asnotracking efcore appdbcontext price drop market data,[MOD] net10.0/appsettings.Development.json -code,,40,72721ed03133bc70c1c477050ca0cd49,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\appsettings.Docker.json,0,542,net10.0/appsettings.Docker.json,1777114850.0531414,1,market data price drop dbcontext entity framework efcore stock price asnotracking notification quote loss appdbcontext external api threshold,[MOD] net10.0/appsettings.Docker.json -code,,34,f30503f11ca8f3574148588cc789c353,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\appsettings.Example.json,0,543,net10.0/appsettings.Example.json,1777190443.277019,1,market data threshold quote stock price price drop efcore postgres external api dockerfile container appdbcontext notification loss entity framework compose dbcontext asnotracking postgresql,[MOD] net10.0/appsettings.Example.json -code,,23,cd9d5cdb6ca1d9be49fecd5c887df1f9,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\appsettings.json,0,544,net10.0/appsettings.json,1776070839.3994565,1,times once unit test verify asnotracking moq xunit dbcontext entity framework mock setup arrange act assert returns async appdbcontext efcore fluentassertions,[MOD] net10.0/appsettings.json -code,,1781,869a0d34545367fdc29df517b815cc3e,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Api.deps.json,0,545,net10.0/InventoryAlert.Api.deps.json,1777190540.2914839,1,productservice loss efcore asnotracking threshold application service entity framework iproductservice dbcontext appdbcontext business logic notification price drop,[MOD] net10.0/InventoryAlert.Api.deps.json -code,,20,37595336dae30b037bd95e5047b95825,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Api.runtimeconfig.json,0,546,net10.0/InventoryAlert.Api.runtimeconfig.json,1775359505.844858,1,asnotracking efcore appdbcontext dbcontext entity framework,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,547,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1776140330.4713986,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json -code,,1,acbe4a57a0230c6e9b12318544965c2f,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,548,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1776908467.097591,1,threshold price drop loss notification,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json -code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Domain.deps.json,0,549,net10.0/InventoryAlert.Domain.deps.json,1776140328.931098,1,price drop application service entity framework asnotracking dbcontext loss threshold iproductservice productservice appdbcontext notification business logic efcore,[MOD] net10.0/InventoryAlert.Domain.deps.json -code,,1014,eff730251f234ef689c3bb655ec153c0,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Infrastructure.deps.json,0,550,net10.0/InventoryAlert.Infrastructure.deps.json,1776140329.4235134,1,loss efcore notification iproductservice price drop application service asnotracking productservice entity framework dbcontext appdbcontext threshold business logic,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json -code,,6409,140fcc3bc7695f37a10484e0768facfa,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.UnitTests.deps.json,0,551,net10.0/InventoryAlert.UnitTests.deps.json,1777190541.3237271,1,fluentassertions commit rollback dbcontext unitofwork arrange act assert threshold price drop productservice asnotracking unit test efcore notification appdbcontext periodictimer entity framework savechanges application service iproductservice hosted service finnhubpricesyncworker atomicity backgroundservice business logic xunit loss,[MOD] net10.0/InventoryAlert.UnitTests.deps.json -code,,20,5f3a2d98fc24aa854c5b9344a7a4d157,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.UnitTests.runtimeconfig.json,0,552,net10.0/InventoryAlert.UnitTests.runtimeconfig.json,1775367800.2892444,1,arrange act assert asnotracking unit test xunit efcore dbcontext appdbcontext entity framework fluentassertions,[MOD] net10.0/InventoryAlert.UnitTests.runtimeconfig.json -code,,1484,2715841f88b7f187dd9c768d43ae51d9,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Worker.deps.json,0,553,net10.0/InventoryAlert.Worker.deps.json,1777190539.783416,1,entity framework threshold application service efcore hosted service productservice dbcontext backgroundservice appdbcontext periodictimer iproductservice loss business logic price drop asnotracking finnhubpricesyncworker notification,[MOD] net10.0/InventoryAlert.Worker.deps.json -code,,20,37595336dae30b037bd95e5047b95825,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,554,net10.0/InventoryAlert.Worker.runtimeconfig.json,1775574216.5947363,1,asnotracking appdbcontext entity framework dbcontext efcore,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,555,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1775574216.407298,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json -code,,6,a32582e70f6535899ff94c94beb7990c,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Debug\net10.0\MvcTestingAppManifest.json,0,556,net10.0/MvcTestingAppManifest.json,1776162249.7550468,1,periodictimer finnhubpricesyncworker threshold loss hosted service backgroundservice notification price drop,[MOD] net10.0/MvcTestingAppManifest.json -code,,33,4d6bffd1f43d0997afb15365806311b3,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\appsettings.Development.json,0,557,net10.0/appsettings.Development.json,1776152647.4113853,1,external api appdbcontext loss asnotracking threshold stock price price drop entity framework market data dbcontext notification quote efcore,[MOD] net10.0/appsettings.Development.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\appsettings.Docker.json,0,558,net10.0/appsettings.Docker.json,1776152585.5173597,1,external api market data notification loss efcore quote price drop asnotracking threshold stock price appdbcontext dbcontext entity framework,[MOD] net10.0/appsettings.Docker.json -code,,34,5e9035733850c9a99aba36de69e8b5bc,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\appsettings.Example.json,0,559,net10.0/appsettings.Example.json,1776152650.2331953,1,efcore dockerfile compose market data entity framework price drop dbcontext appdbcontext stock price quote postgres asnotracking loss container external api notification postgresql threshold,[MOD] net10.0/appsettings.Example.json -code,,23,cd9d5cdb6ca1d9be49fecd5c887df1f9,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\appsettings.json,0,560,net10.0/appsettings.json,1776070839.3994565,1,times once returns async mock setup xunit asnotracking verify efcore moq unit test appdbcontext fluentassertions entity framework arrange act assert dbcontext,[MOD] net10.0/appsettings.json -code,,1713,322fbe3f71679c335ba0563804aa7b61,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Api.deps.json,0,561,net10.0/InventoryAlert.Api.deps.json,1776317847.379226,1,loss dbcontext notification productservice iproductservice efcore price drop application service threshold entity framework appdbcontext business logic asnotracking,[MOD] net10.0/InventoryAlert.Api.deps.json -code,,21,d60cf9618363ac73f5894cceaffc545e,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Api.runtimeconfig.json,0,562,net10.0/InventoryAlert.Api.runtimeconfig.json,1776317847.4107525,1,appdbcontext efcore entity framework dbcontext asnotracking,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,563,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1776317847.2301905,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json -code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Domain.deps.json,0,564,net10.0/InventoryAlert.Domain.deps.json,1776315555.4422834,1,efcore application service price drop iproductservice threshold dbcontext productservice notification appdbcontext loss asnotracking business logic entity framework,[MOD] net10.0/InventoryAlert.Domain.deps.json -code,,1014,eff730251f234ef689c3bb655ec153c0,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Infrastructure.deps.json,0,565,net10.0/InventoryAlert.Infrastructure.deps.json,1776315557.0782773,1,dbcontext price drop appdbcontext entity framework loss notification productservice application service business logic threshold efcore asnotracking iproductservice,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json -code,,6377,f5bc950d13addc2d57678dc12cd6d00c,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.UnitTests.deps.json,0,566,net10.0/InventoryAlert.UnitTests.deps.json,1776517562.4424899,1,unitofwork efcore iproductservice xunit dbcontext commit productservice atomicity threshold application service fluentassertions finnhubpricesyncworker arrange act assert backgroundservice asnotracking unit test loss periodictimer entity framework business logic notification rollback appdbcontext savechanges price drop hosted service,[MOD] net10.0/InventoryAlert.UnitTests.deps.json -code,,21,11a2057f7e08545a87eae55a47ccbe16,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.UnitTests.runtimeconfig.json,0,567,net10.0/InventoryAlert.UnitTests.runtimeconfig.json,1776317849.5110548,1,arrange act assert fluentassertions unit test xunit efcore asnotracking appdbcontext dbcontext entity framework,[MOD] net10.0/InventoryAlert.UnitTests.runtimeconfig.json -code,,1415,0dc0c89c73e769db23b190b6e65c008b,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Worker.deps.json,0,568,net10.0/InventoryAlert.Worker.deps.json,1776517509.2326386,1,application service threshold backgroundservice business logic productservice iproductservice efcore loss asnotracking notification appdbcontext periodictimer entity framework price drop finnhubpricesyncworker hosted service dbcontext,[MOD] net10.0/InventoryAlert.Worker.deps.json -code,,21,d60cf9618363ac73f5894cceaffc545e,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,569,net10.0/InventoryAlert.Worker.runtimeconfig.json,1776315560.6109736,1,efcore entity framework dbcontext appdbcontext asnotracking,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,570,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1776315560.4012246,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json -code,,6,a32582e70f6535899ff94c94beb7990c,InventoryManagementSystem\InventoryAlert.UnitTests\bin\Release\net10.0\MvcTestingAppManifest.json,0,571,net10.0/MvcTestingAppManifest.json,1776317847.698741,1,notification threshold hosted service periodictimer backgroundservice price drop loss finnhubpricesyncworker,[MOD] net10.0/MvcTestingAppManifest.json -code,,2851,9ed6df42e17c7a87b45649c062351b2d,InventoryManagementSystem\InventoryAlert.UnitTests\obj\InventoryAlert.UnitTests.csproj.nuget.dgspec.json,0,572,obj/InventoryAlert.UnitTests.csproj.nuget.dgspec.json,1777190308.7987552,1,iproductservice business logic productservice appdbcontext arrange act assert threshold backgroundservice fluentassertions finnhubpricesyncworker dbcontext application service periodictimer efcore xunit hosted service unit test price drop asnotracking loss notification entity framework,[MOD] obj/InventoryAlert.UnitTests.csproj.nuget.dgspec.json -code,,6366,5e7874a284a03dd5caaa9de6d9c53483,InventoryManagementSystem\InventoryAlert.UnitTests\obj\project.assets.json,0,573,obj/project.assets.json,1777190308.7837257,1,entity framework unit test xunit efcore fluentassertions dbcontext arrange act assert finnhubpricesyncworker business logic asnotracking periodictimer threshold notification appdbcontext application service iproductservice price drop loss hosted service productservice backgroundservice,[MOD] obj/project.assets.json -code,,1,90f21815d76c70668c3754cb75dde84f,InventoryManagementSystem\InventoryAlert.UnitTests\obj\project.packagespec.json,0,574,obj/project.packagespec.json,1777190306.0278842,1,appdbcontext iproductservice asnotracking productservice entity framework unit test hosted service loss xunit notification dbcontext price drop periodictimer arrange act assert finnhubpricesyncworker backgroundservice efcore fluentassertions application service business logic threshold,[MOD] obj/project.packagespec.json -code,,1,9781dd6d356826d311887c1e4bd62b4f,InventoryManagementSystem\InventoryAlert.UnitTests\obj\Debug\net10.0\InventoryAlert.UnitTests.sourcelink.json,0,575,net10.0/InventoryAlert.UnitTests.sourcelink.json,1777190540.5921621,1,dbcontext appdbcontext entity framework asnotracking efcore,[MOD] net10.0/InventoryAlert.UnitTests.sourcelink.json -code,,6,a32582e70f6535899ff94c94beb7990c,InventoryManagementSystem\InventoryAlert.UnitTests\obj\Debug\net10.0\MvcTestingAppManifest.json,0,576,net10.0/MvcTestingAppManifest.json,1776162249.7550468,1,finnhubpricesyncworker hosted service backgroundservice loss periodictimer threshold notification price drop,[MOD] net10.0/MvcTestingAppManifest.json -code,,1,b4bc405b4c07cf3b59a86a282bac2314,InventoryManagementSystem\InventoryAlert.UnitTests\obj\Release\net10.0\InventoryAlert.UnitTests.sourcelink.json,0,577,net10.0/InventoryAlert.UnitTests.sourcelink.json,1776517509.872894,1,,[MOD] net10.0/InventoryAlert.UnitTests.sourcelink.json -code,,6,a32582e70f6535899ff94c94beb7990c,InventoryManagementSystem\InventoryAlert.UnitTests\obj\Release\net10.0\MvcTestingAppManifest.json,0,578,net10.0/MvcTestingAppManifest.json,1776317847.698741,1,threshold loss finnhubpricesyncworker hosted service notification backgroundservice price drop periodictimer,[MOD] net10.0/MvcTestingAppManifest.json -code,,33,4d6bffd1f43d0997afb15365806311b3,InventoryManagementSystem\InventoryAlert.Worker\appsettings.Development.json,0,579,InventoryAlert.Worker/appsettings.Development.json,1776152647.4113853,1,market data price drop quote dbcontext efcore loss entity framework threshold stock price external api asnotracking notification appdbcontext,[MOD] InventoryAlert.Worker/appsettings.Development.json -code,,40,72721ed03133bc70c1c477050ca0cd49,InventoryManagementSystem\InventoryAlert.Worker\appsettings.Docker.json,0,580,InventoryAlert.Worker/appsettings.Docker.json,1777114850.0531414,1,efcore threshold external api notification stock price loss dbcontext entity framework asnotracking appdbcontext market data price drop quote,[MOD] InventoryAlert.Worker/appsettings.Docker.json -code,,34,f30503f11ca8f3574148588cc789c353,InventoryManagementSystem\InventoryAlert.Worker\appsettings.Example.json,0,581,InventoryAlert.Worker/appsettings.Example.json,1777190443.277019,1,stock price dbcontext price drop external api entity framework postgresql efcore container threshold appdbcontext quote postgres notification dockerfile asnotracking compose market data loss,[MOD] InventoryAlert.Worker/appsettings.Example.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.Worker\appsettings.json,0,582,InventoryAlert.Worker/appsettings.json,1776152652.9040236,1,dbcontext quote external api asnotracking efcore market data notification loss entity framework threshold appdbcontext price drop stock price,[MOD] InventoryAlert.Worker/appsettings.json -code,,33,4d6bffd1f43d0997afb15365806311b3,InventoryManagementSystem\InventoryAlert.Worker\bin\Debug\net10.0\appsettings.Development.json,0,583,net10.0/appsettings.Development.json,1776152647.4113853,1,loss entity framework stock price quote external api efcore notification price drop appdbcontext market data asnotracking threshold dbcontext,[MOD] net10.0/appsettings.Development.json -code,,40,72721ed03133bc70c1c477050ca0cd49,InventoryManagementSystem\InventoryAlert.Worker\bin\Debug\net10.0\appsettings.Docker.json,0,584,net10.0/appsettings.Docker.json,1777114850.0531414,1,dbcontext loss external api efcore appdbcontext stock price threshold quote notification market data asnotracking entity framework price drop,[MOD] net10.0/appsettings.Docker.json -code,,34,f30503f11ca8f3574148588cc789c353,InventoryManagementSystem\InventoryAlert.Worker\bin\Debug\net10.0\appsettings.Example.json,0,585,net10.0/appsettings.Example.json,1777190443.277019,1,notification dbcontext external api market data stock price compose entity framework price drop loss container appdbcontext asnotracking efcore threshold postgresql postgres dockerfile quote,[MOD] net10.0/appsettings.Example.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.Worker\bin\Debug\net10.0\appsettings.json,0,586,net10.0/appsettings.json,1776152652.9040236,1,market data price drop quote dbcontext efcore loss entity framework threshold stock price external api asnotracking notification appdbcontext,[MOD] net10.0/appsettings.json -code,,1484,2715841f88b7f187dd9c768d43ae51d9,InventoryManagementSystem\InventoryAlert.Worker\bin\Debug\net10.0\InventoryAlert.Worker.deps.json,0,587,net10.0/InventoryAlert.Worker.deps.json,1777190539.783416,1,application service threshold backgroundservice business logic productservice iproductservice efcore loss asnotracking notification appdbcontext periodictimer entity framework price drop finnhubpricesyncworker hosted service dbcontext,[MOD] net10.0/InventoryAlert.Worker.deps.json -code,,20,37595336dae30b037bd95e5047b95825,InventoryManagementSystem\InventoryAlert.Worker\bin\Debug\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,588,net10.0/InventoryAlert.Worker.runtimeconfig.json,1775574216.5947363,1,entity framework dbcontext asnotracking appdbcontext efcore,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.Worker\bin\Debug\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,589,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1775574216.407298,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json -code,,33,4d6bffd1f43d0997afb15365806311b3,InventoryManagementSystem\InventoryAlert.Worker\bin\Release\net10.0\appsettings.Development.json,0,590,net10.0/appsettings.Development.json,1776152647.4113853,1,dbcontext notification appdbcontext threshold loss entity framework external api price drop market data asnotracking quote efcore stock price,[MOD] net10.0/appsettings.Development.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.Worker\bin\Release\net10.0\appsettings.Docker.json,0,591,net10.0/appsettings.Docker.json,1776152585.5173597,1,notification entity framework threshold stock price quote market data efcore dbcontext price drop external api appdbcontext loss asnotracking,[MOD] net10.0/appsettings.Docker.json -code,,34,5e9035733850c9a99aba36de69e8b5bc,InventoryManagementSystem\InventoryAlert.Worker\bin\Release\net10.0\appsettings.Example.json,0,592,net10.0/appsettings.Example.json,1776152650.2331953,1,efcore dockerfile compose market data entity framework price drop dbcontext appdbcontext stock price quote postgres asnotracking loss container external api notification postgresql threshold,[MOD] net10.0/appsettings.Example.json -code,,33,263ef85512ed78d9b5ed5fc539294849,InventoryManagementSystem\InventoryAlert.Worker\bin\Release\net10.0\appsettings.json,0,593,net10.0/appsettings.json,1776152652.9040236,1,stock price loss entity framework dbcontext price drop asnotracking quote market data efcore appdbcontext external api threshold notification,[MOD] net10.0/appsettings.json -code,,1415,0dc0c89c73e769db23b190b6e65c008b,InventoryManagementSystem\InventoryAlert.Worker\bin\Release\net10.0\InventoryAlert.Worker.deps.json,0,594,net10.0/InventoryAlert.Worker.deps.json,1776398168.1515255,1,finnhubpricesyncworker entity framework periodictimer productservice efcore application service price drop dbcontext asnotracking backgroundservice hosted service threshold notification appdbcontext iproductservice loss business logic,[MOD] net10.0/InventoryAlert.Worker.deps.json -code,,21,d60cf9618363ac73f5894cceaffc545e,InventoryManagementSystem\InventoryAlert.Worker\bin\Release\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,595,net10.0/InventoryAlert.Worker.runtimeconfig.json,1776315560.6109736,1,entity framework efcore dbcontext appdbcontext asnotracking,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.Worker\bin\Release\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,596,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1776315560.4012246,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json -code,,1719,2986df935e326ae9dba5070b72941813,InventoryManagementSystem\InventoryAlert.Worker\obj\InventoryAlert.Worker.csproj.nuget.dgspec.json,0,597,obj/InventoryAlert.Worker.csproj.nuget.dgspec.json,1777190308.808769,1,dbcontext periodictimer iproductservice threshold backgroundservice fluentassertions notification arrange act assert hosted service entity framework application service xunit unit test appdbcontext business logic finnhubpricesyncworker price drop efcore productservice asnotracking loss,[MOD] obj/InventoryAlert.Worker.csproj.nuget.dgspec.json -code,,4545,e9e5c8bbab58a61fc7743fc9fc9240b4,InventoryManagementSystem\InventoryAlert.Worker\obj\project.assets.json,0,598,obj/project.assets.json,1777190308.8007617,1,efcore productservice asnotracking threshold backgroundservice dbcontext xunit unit test periodictimer iproductservice business logic price drop finnhubpricesyncworker application service fluentassertions arrange act assert notification loss hosted service entity framework appdbcontext,[MOD] obj/project.assets.json -code,,1,c362abcc699f66840fa410f094b3b8d6,InventoryManagementSystem\InventoryAlert.Worker\obj\project.packagespec.json,0,599,obj/project.packagespec.json,1777190305.4334364,1,entity framework unit test xunit efcore fluentassertions dbcontext arrange act assert finnhubpricesyncworker business logic asnotracking periodictimer threshold notification appdbcontext application service iproductservice price drop loss hosted service productservice backgroundservice,[MOD] obj/project.packagespec.json -code,,1,9781dd6d356826d311887c1e4bd62b4f,InventoryManagementSystem\InventoryAlert.Worker\obj\Debug\net10.0\InventoryAlert.Worker.sourcelink.json,0,600,net10.0/InventoryAlert.Worker.sourcelink.json,1777190539.3272612,1,efcore asnotracking dbcontext appdbcontext entity framework,[MOD] net10.0/InventoryAlert.Worker.sourcelink.json -code,,1,ea5b26db32a3724a7ec7efde3bb193e9,InventoryManagementSystem\InventoryAlert.Worker\obj\Debug\net10.0\rjsmcshtml.dswa.cache.json,0,601,net10.0/rjsmcshtml.dswa.cache.json,1777190539.6752498,1,entity framework appdbcontext dbcontext efcore asnotracking,[MOD] net10.0/rjsmcshtml.dswa.cache.json -code,,1,6f20b48d33b10ff344e2a21c3fe12378,InventoryManagementSystem\InventoryAlert.Worker\obj\Debug\net10.0\rjsmrazor.dswa.cache.json,0,602,net10.0/rjsmrazor.dswa.cache.json,1777190539.6707387,1,dbcontext appdbcontext asnotracking entity framework efcore,[MOD] net10.0/rjsmrazor.dswa.cache.json -code,,1,b2046e225ca90cb037bd86640b5133df,InventoryManagementSystem\InventoryAlert.Worker\obj\Debug\net10.0\rpswa.dswa.cache.json,0,603,net10.0/rpswa.dswa.cache.json,1777190539.03054,1,,[MOD] net10.0/rpswa.dswa.cache.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.Worker\obj\Debug\net10.0\staticwebassets.build.endpoints.json,0,604,net10.0/staticwebassets.build.endpoints.json,1775574216.407298,1,,[MOD] net10.0/staticwebassets.build.endpoints.json -code,,1,6155a156ae4b5c7a22d70b19468ea2f9,InventoryManagementSystem\InventoryAlert.Worker\obj\Debug\net10.0\staticwebassets.build.json,0,605,net10.0/staticwebassets.build.json,1775574216.401221,1,finnhubpricesyncworker periodictimer threshold backgroundservice price drop appdbcontext efcore entity framework dbcontext notification loss asnotracking hosted service,[MOD] net10.0/staticwebassets.build.json -code,,1,b4bc405b4c07cf3b59a86a282bac2314,InventoryManagementSystem\InventoryAlert.Worker\obj\Release\net10.0\InventoryAlert.Worker.sourcelink.json,0,606,net10.0/InventoryAlert.Worker.sourcelink.json,1776517504.5140243,1,,[MOD] net10.0/InventoryAlert.Worker.sourcelink.json -code,,1,64814b1ec6423930a6223c560a67957c,InventoryManagementSystem\InventoryAlert.Worker\obj\Release\net10.0\rjsmcshtml.dswa.cache.json,0,607,net10.0/rjsmcshtml.dswa.cache.json,1776517508.9571507,1,,[MOD] net10.0/rjsmcshtml.dswa.cache.json -code,,1,7c643f3b961301fce37b8e85e29df878,InventoryManagementSystem\InventoryAlert.Worker\obj\Release\net10.0\rjsmrazor.dswa.cache.json,0,608,net10.0/rjsmrazor.dswa.cache.json,1776517508.9531496,1,entity framework dbcontext efcore asnotracking appdbcontext,[MOD] net10.0/rjsmrazor.dswa.cache.json -code,,1,bc534b5c44c8b07235b9637f67ce369b,InventoryManagementSystem\InventoryAlert.Worker\obj\Release\net10.0\rpswa.dswa.cache.json,0,609,net10.0/rpswa.dswa.cache.json,1776398166.4013216,1,,[MOD] net10.0/rpswa.dswa.cache.json -code,,1,f44ca44dd881261586b84442f2201257,InventoryManagementSystem\InventoryAlert.Worker\obj\Release\net10.0\staticwebassets.build.endpoints.json,0,610,net10.0/staticwebassets.build.endpoints.json,1776315560.4012246,1,,[MOD] net10.0/staticwebassets.build.endpoints.json -code,,1,6155a156ae4b5c7a22d70b19468ea2f9,InventoryManagementSystem\InventoryAlert.Worker\obj\Release\net10.0\staticwebassets.build.json,0,611,net10.0/staticwebassets.build.json,1776315560.3904145,1,hosted service appdbcontext loss asnotracking backgroundservice threshold finnhubpricesyncworker price drop entity framework dbcontext notification efcore periodictimer,[MOD] net10.0/staticwebassets.build.json -code,,12,f5fda86557b5826bd2813eb658c10141,InventoryManagementSystem\InventoryAlert.Worker\Properties\launchSettings.json,0,612,Properties/launchSettings.json,1775287096.7608154,1,periodictimer notification hosted service finnhubpricesyncworker loss threshold backgroundservice price drop,[MOD] Properties/launchSettings.json +> **Data Seed Note**: Do not rely on production seed data. Every test should ""Arrange"" its own data or use a minimal `TestSeeder` to ensure predictable outcomes.",166,a3df3e6e3cbb92463d0ebb3d099b6962,src\test\InventoryAlert.IntegrationTests\INTEGRATION_TEST_PLAN.md,0,528,"test, step, testing, inventoryalert, testcontainers, class, dotnet, project",1779814416.3372493,1,database update compose returns async schema change efcore unit test verify mock setup arrange act assert add-migration googl notification sku savechanges entity framework market data stock ticker postgres asnotracking efcore migration unitofwork finnhubpricesyncworker quote threshold loss business logic times once container atomicity symbol postgresql hosted service commit application service rollback backgroundservice external api iproductservice stock aapl msft dockerfile periodictimer inventory stock price price drop xunit moq dbcontext appdbcontext fluentassertions productservice item,# Integration Testing Framework: Implementation Guide | Integration Testing Framework: Implementation Guide This guide provides a step-b +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\appsettings.Example.json,0,529,net10.0/appsettings.Example.json,1779814416.3795497,1,threshold loss appdbcontext compose external api periodictimer quote postgresql efcore entity framework postgres stock price market data dockerfile container finnhubpricesyncworker backgroundservice hosted service price drop asnotracking notification dbcontext,[MOD] net10.0/appsettings.Example.json +code,,31,524eb0bb84017bf7db38382c181633f0,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\appsettings.json,0,530,net10.0/appsettings.json,1779814416.2734604,1,postgres efcore stock price entity framework market data container asnotracking loss appdbcontext threshold compose postgresql dbcontext external api dockerfile notification quote price drop,[MOD] net10.0/appsettings.json +code,,33,9b5dea32c79876c723aef63bd81f478a,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\appsettings.test.json,0,531,net10.0/appsettings.test.json,1779814416.3505743,1,threshold mock setup stock price verify arrange act assert fluentassertions price drop moq returns async dbcontext unit test quote times once loss entity framework notification asnotracking efcore appdbcontext external api market data xunit,[MOD] net10.0/appsettings.test.json +code,,1785,ace06dcdfed963a769231bf7d3d17433,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Api.deps.json,0,532,net10.0/InventoryAlert.Api.deps.json,1779852474.218987,1,business logic iproductservice entity framework application service threshold notification loss efcore productservice appdbcontext asnotracking dbcontext price drop,[MOD] net10.0/InventoryAlert.Api.deps.json +code,,20,37595336dae30b037bd95e5047b95825,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Api.runtimeconfig.json,0,533,net10.0/InventoryAlert.Api.runtimeconfig.json,1779852474.3064263,1,appdbcontext efcore entity framework asnotracking dbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,534,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1779852473.9235973,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json +code,,1,764ba22cde656c91f3e05ba4bc7bbcee,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,535,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1779852473.959113,1,loss notification threshold price drop,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json +code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Domain.deps.json,0,536,net10.0/InventoryAlert.Domain.deps.json,1779852469.346435,1,threshold application service asnotracking iproductservice notification efcore productservice dbcontext appdbcontext price drop business logic loss entity framework,[MOD] net10.0/InventoryAlert.Domain.deps.json +code,,1204,cb0b59a46f14c231584e0f3eae18a84d,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Infrastructure.deps.json,0,537,net10.0/InventoryAlert.Infrastructure.deps.json,1779852470.849428,1,productservice business logic dbcontext entity framework application service asnotracking notification iproductservice appdbcontext loss threshold efcore price drop,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json +code,,8968,a728fc0d9f098071ab538f9d48971ca9,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.IntegrationTests.deps.json,0,538,net10.0/InventoryAlert.IntegrationTests.deps.json,1779852476.9513147,1,entity framework threshold infrastructure efcore finnhubpricesyncworker fluentassertions iproductservice domain driven design periodictimer xunit appdbcontext unitofwork mock setup rollback returns async dbcontext hosted service container price drop verify dockerfile savechanges notification productservice times once loss moq backgroundservice unit test application layer arrange act assert postgresql compose commit application service domain entity postgres asnotracking business logic atomicity,[MOD] net10.0/InventoryAlert.IntegrationTests.deps.json +code,,20,5f3a2d98fc24aa854c5b9344a7a4d157,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.IntegrationTests.runtimeconfig.json,0,539,net10.0/InventoryAlert.IntegrationTests.runtimeconfig.json,1779852477.0236187,1,fluentassertions xunit appdbcontext asnotracking efcore unit test entity framework arrange act assert dbcontext,[MOD] net10.0/InventoryAlert.IntegrationTests.runtimeconfig.json +code,,1488,bbe0769f603dfb81733a7b52d5e43f76,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Worker.deps.json,0,540,net10.0/InventoryAlert.Worker.deps.json,1779852473.908222,1,finnhubpricesyncworker entity framework iproductservice dbcontext appdbcontext business logic productservice price drop efcore hosted service asnotracking application service backgroundservice periodictimer loss notification threshold,[MOD] net10.0/InventoryAlert.Worker.deps.json +code,,20,37595336dae30b037bd95e5047b95825,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,541,net10.0/InventoryAlert.Worker.runtimeconfig.json,1779852474.0111957,1,asnotracking efcore appdbcontext entity framework dbcontext,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json +code,,1,f44ca44dd881261586b84442f2201257,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,542,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1779852473.689481,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json +code,,6,e15b7bab85d1b5f11797ca764363b8b6,src\test\InventoryAlert.IntegrationTests\bin\Debug\net10.0\MvcTestingAppManifest.json,0,543,net10.0/MvcTestingAppManifest.json,1779853359.269076,1,hosted service price drop backgroundservice finnhubpricesyncworker periodictimer threshold notification loss,[MOD] net10.0/MvcTestingAppManifest.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\appsettings.Example.json,0,544,net10.0/appsettings.Example.json,1779814416.3795497,1,dbcontext container external api stock price backgroundservice hosted service finnhubpricesyncworker price drop dockerfile quote threshold asnotracking market data loss postgresql postgres compose efcore notification periodictimer appdbcontext entity framework,[MOD] net10.0/appsettings.Example.json +code,,31,524eb0bb84017bf7db38382c181633f0,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\appsettings.json,0,545,net10.0/appsettings.json,1779814416.2734604,1,external api stock price price drop asnotracking quote postgresql notification threshold market data dockerfile loss appdbcontext dbcontext container efcore entity framework postgres compose,[MOD] net10.0/appsettings.json +code,,33,9b5dea32c79876c723aef63bd81f478a,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\appsettings.test.json,0,546,net10.0/appsettings.test.json,1779814416.3505743,1,unit test external api price drop appdbcontext threshold verify loss efcore quote entity framework moq mock setup stock price notification fluentassertions arrange act assert times once dbcontext asnotracking xunit market data returns async,[MOD] net10.0/appsettings.test.json +code,,1785,ace06dcdfed963a769231bf7d3d17433,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Api.deps.json,0,547,net10.0/InventoryAlert.Api.deps.json,1779815055.0786984,1,loss appdbcontext efcore productservice business logic entity framework asnotracking threshold dbcontext notification application service iproductservice price drop,[MOD] net10.0/InventoryAlert.Api.deps.json +code,,21,d60cf9618363ac73f5894cceaffc545e,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Api.runtimeconfig.json,0,548,net10.0/InventoryAlert.Api.runtimeconfig.json,1779815055.1578588,1,entity framework asnotracking efcore appdbcontext dbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,549,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1779815054.8447104,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json +code,,1,e6adbf2622be6f462ec396db3b4d5b74,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,550,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1779815054.8755307,1,notification price drop threshold loss,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json +code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Domain.deps.json,0,551,net10.0/InventoryAlert.Domain.deps.json,1779815048.8279152,1,business logic application service productservice price drop appdbcontext asnotracking loss efcore entity framework notification threshold iproductservice dbcontext,[MOD] net10.0/InventoryAlert.Domain.deps.json +code,,1204,cb0b59a46f14c231584e0f3eae18a84d,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Infrastructure.deps.json,0,552,net10.0/InventoryAlert.Infrastructure.deps.json,1779815050.7656255,1,iproductservice efcore application service business logic entity framework loss threshold dbcontext appdbcontext asnotracking notification price drop productservice,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json +code,,8968,409f89ad4c0185c59012cae139a51457,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.IntegrationTests.deps.json,0,553,net10.0/InventoryAlert.IntegrationTests.deps.json,1779815058.4720733,1,fluentassertions commit asnotracking business logic mock setup appdbcontext times once domain driven design postgresql price drop finnhubpricesyncworker unitofwork unit test threshold entity framework atomicity compose infrastructure container productservice arrange act assert notification application service postgres savechanges verify dockerfile hosted service domain entity loss efcore xunit backgroundservice application layer returns async rollback iproductservice moq periodictimer dbcontext,[MOD] net10.0/InventoryAlert.IntegrationTests.deps.json +code,,21,11a2057f7e08545a87eae55a47ccbe16,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.IntegrationTests.runtimeconfig.json,0,554,net10.0/InventoryAlert.IntegrationTests.runtimeconfig.json,1779815058.539826,1,entity framework efcore asnotracking xunit unit test dbcontext appdbcontext fluentassertions arrange act assert,[MOD] net10.0/InventoryAlert.IntegrationTests.runtimeconfig.json +code,,1488,bbe0769f603dfb81733a7b52d5e43f76,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Worker.deps.json,0,555,net10.0/InventoryAlert.Worker.deps.json,1779815054.685102,1,entity framework dbcontext threshold hosted service efcore finnhubpricesyncworker backgroundservice application service iproductservice notification productservice price drop loss periodictimer asnotracking business logic appdbcontext,[MOD] net10.0/InventoryAlert.Worker.deps.json +code,,21,d60cf9618363ac73f5894cceaffc545e,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,556,net10.0/InventoryAlert.Worker.runtimeconfig.json,1779815054.7921462,1,asnotracking appdbcontext efcore dbcontext entity framework,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json +code,,1,f44ca44dd881261586b84442f2201257,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,557,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1779815054.3388731,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json +code,,6,7b48306a747fe6e90ebb00e01a0c08f4,src\test\InventoryAlert.IntegrationTests\bin\Release\net10.0\MvcTestingAppManifest.json,0,558,net10.0/MvcTestingAppManifest.json,1779815055.545804,1,periodictimer hosted service backgroundservice notification finnhubpricesyncworker threshold price drop loss,[MOD] net10.0/MvcTestingAppManifest.json +code,,2936,67734bc399dec693f0a11879bc282afb,src\test\InventoryAlert.IntegrationTests\obj\InventoryAlert.IntegrationTests.csproj.nuget.dgspec.json,0,559,obj/InventoryAlert.IntegrationTests.csproj.nuget.dgspec.json,1779852466.411099,1,price drop mock setup appdbcontext arrange act assert application service verify container dockerfile asnotracking periodictimer postgres postgresql hosted service xunit compose productservice moq returns async business logic times once backgroundservice finnhubpricesyncworker iproductservice unit test fluentassertions entity framework notification loss threshold efcore dbcontext,[MOD] obj/InventoryAlert.IntegrationTests.csproj.nuget.dgspec.json +code,,11296,2e5e13863d9cc930af857206ae11cbac,src\test\InventoryAlert.IntegrationTests\obj\project.assets.json,0,560,obj/project.assets.json,1779852466.3991332,1,threshold moq loss arrange act assert iproductservice domain driven design appdbcontext compose periodictimer postgresql fluentassertions application layer business logic returns async verify unit test mock setup efcore entity framework postgres infrastructure application service times once productservice dockerfile domain entity container finnhubpricesyncworker backgroundservice hosted service price drop asnotracking notification xunit dbcontext,[MOD] obj/project.assets.json +code,,1,e72d0610ac52b5cf1a985dbb76a038e5,src\test\InventoryAlert.IntegrationTests\obj\project.packagespec.json,0,561,obj/project.packagespec.json,1779852420.0584507,1,postgresql threshold productservice container mock setup business logic compose verify arrange act assert fluentassertions price drop moq returns async dockerfile dbcontext postgres finnhubpricesyncworker iproductservice unit test periodictimer times once loss hosted service entity framework notification asnotracking efcore application service appdbcontext backgroundservice xunit,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\test\InventoryAlert.IntegrationTests\obj\Debug\net10.0\InventoryAlert.IntegrationTests.sourcelink.json,0,562,net10.0/InventoryAlert.IntegrationTests.sourcelink.json,1779852474.7048664,1,appdbcontext dbcontext asnotracking efcore entity framework,[MOD] net10.0/InventoryAlert.IntegrationTests.sourcelink.json +code,,6,e15b7bab85d1b5f11797ca764363b8b6,src\test\InventoryAlert.IntegrationTests\obj\Debug\net10.0\MvcTestingAppManifest.json,0,563,net10.0/MvcTestingAppManifest.json,1779853359.269076,1,hosted service price drop backgroundservice finnhubpricesyncworker periodictimer threshold notification loss,[MOD] net10.0/MvcTestingAppManifest.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\test\InventoryAlert.IntegrationTests\obj\Release\net10.0\InventoryAlert.IntegrationTests.sourcelink.json,0,564,net10.0/InventoryAlert.IntegrationTests.sourcelink.json,1779815056.014794,1,,[MOD] net10.0/InventoryAlert.IntegrationTests.sourcelink.json +code,,6,7b48306a747fe6e90ebb00e01a0c08f4,src\test\InventoryAlert.IntegrationTests\obj\Release\net10.0\MvcTestingAppManifest.json,0,565,net10.0/MvcTestingAppManifest.json,1779815055.545804,1,notification loss price drop periodictimer threshold finnhubpricesyncworker backgroundservice hosted service,[MOD] net10.0/MvcTestingAppManifest.json +code,,18,6f1b5171dca185426cce3bfb84627eab,src\test\InventoryAlert.IntegrationTests\Wiremock\mappings\check-wiremock.json,0,566,mappings/check-wiremock.json,1779814416.3480587,1,returns async mock setup moq times once verify,[MOD] mappings/check-wiremock.json +code,,16,dc6fe1e5686d24e115bea7028eb68a7d,src\test\InventoryAlert.IntegrationTests\Wiremock\mappings\company_news.json,0,567,mappings/company_news.json,1779814416.348566,1,,[MOD] mappings/company_news.json +code,,34,f9beb08cee7c8f5e1e52f603f01b0e96,src\test\InventoryAlert.IntegrationTests\Wiremock\mappings\get-profile.json,0,568,mappings/get-profile.json,1779814416.348566,1,symbol msft external api stock ticker stock price quote market data aapl googl,[MOD] mappings/get-profile.json +code,,30,f079ec3e3482a3d543faaba61e9a51e6,src\test\InventoryAlert.IntegrationTests\Wiremock\mappings\get-quote.json,0,569,mappings/get-quote.json,1779814416.3495753,1,,[MOD] mappings/get-quote.json +code,,16,307d111fddfe56f132e1c51be8ae0cff,src\test\InventoryAlert.IntegrationTests\Wiremock\mappings\market_news.json,0,570,mappings/market_news.json,1779814416.3495753,1,,[MOD] mappings/market_news.json +code,,13,ce1ffb178962523c18e5ea450717497f,src\test\InventoryAlert.IntegrationTests\Wiremock\mappings\ping.json,0,571,mappings/ping.json,1779814416.3495753,1,,[MOD] mappings/ping.json +code,,718,ffcd40667082383b6f0962b242cf767d,src\test\InventoryAlert.Sample\bin\Debug\net10.0\InventoryAlert.Sample.deps.json,0,572,net10.0/InventoryAlert.Sample.deps.json,1779852470.5757928,1,business logic iproductservice entity framework application service threshold notification loss efcore productservice appdbcontext asnotracking dbcontext price drop,[MOD] net10.0/InventoryAlert.Sample.deps.json +code,,13,5e2fec3a44baa37dd9b51c63a09513c6,src\test\InventoryAlert.Sample\bin\Debug\net10.0\InventoryAlert.Sample.runtimeconfig.json,0,573,net10.0/InventoryAlert.Sample.runtimeconfig.json,1779852470.6986418,1,dbcontext entity framework asnotracking appdbcontext efcore,[MOD] net10.0/InventoryAlert.Sample.runtimeconfig.json +code,,718,ffcd40667082383b6f0962b242cf767d,src\test\InventoryAlert.Sample\bin\Release\net10.0\InventoryAlert.Sample.deps.json,0,574,net10.0/InventoryAlert.Sample.deps.json,1779815051.0130446,1,threshold application service asnotracking iproductservice notification efcore productservice dbcontext appdbcontext price drop business logic loss entity framework,[MOD] net10.0/InventoryAlert.Sample.deps.json +code,,14,65e54446b7c5017d0110c783eff5a0a7,src\test\InventoryAlert.Sample\bin\Release\net10.0\InventoryAlert.Sample.runtimeconfig.json,0,575,net10.0/InventoryAlert.Sample.runtimeconfig.json,1779815051.0719917,1,appdbcontext asnotracking efcore entity framework dbcontext,[MOD] net10.0/InventoryAlert.Sample.runtimeconfig.json +code,,908,ce8229ff3548f0389a951980c210ce9b,src\test\InventoryAlert.Sample\obj\InventoryAlert.Sample.csproj.nuget.dgspec.json,0,576,obj/InventoryAlert.Sample.csproj.nuget.dgspec.json,1779852466.4055192,1,dbcontext container price drop unit test xunit dockerfile moq arrange act assert returns async application service asnotracking loss times once productservice mock setup postgresql postgres compose verify iproductservice business logic efcore appdbcontext fluentassertions notification threshold entity framework,[MOD] obj/InventoryAlert.Sample.csproj.nuget.dgspec.json +code,,2159,c66c4a2ef8d9045a351660c75a72149f,src\test\InventoryAlert.Sample\obj\project.assets.json,0,577,obj/project.assets.json,1779852466.3895667,1,unit test productservice price drop appdbcontext threshold verify business logic loss application service efcore entity framework moq mock setup iproductservice notification fluentassertions arrange act assert times once dockerfile dbcontext postgres postgresql asnotracking xunit returns async compose container,[MOD] obj/project.assets.json +code,,1,8f10a4275715eac73db6f905f5264dcf,src\test\InventoryAlert.Sample\obj\project.packagespec.json,0,578,obj/project.packagespec.json,1779852426.9117937,1,dockerfile entity framework iproductservice mock setup price drop threshold returns async xunit container postgresql times once application service fluentassertions appdbcontext verify dbcontext productservice unit test efcore asnotracking arrange act assert business logic postgres compose moq loss notification,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\test\InventoryAlert.Sample\obj\Debug\net10.0\InventoryAlert.Sample.sourcelink.json,0,579,net10.0/InventoryAlert.Sample.sourcelink.json,1779852469.5400133,1,entity framework asnotracking efcore appdbcontext dbcontext,[MOD] net10.0/InventoryAlert.Sample.sourcelink.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\test\InventoryAlert.Sample\obj\Release\net10.0\InventoryAlert.Sample.sourcelink.json,0,580,net10.0/InventoryAlert.Sample.sourcelink.json,1779815049.5690334,1,,[MOD] net10.0/InventoryAlert.Sample.sourcelink.json +code,,23,062c332904c0ce2104c029fbaa9e0ba2,src\test\InventoryAlert.UnitTests\appsettings.json,0,581,InventoryAlert.UnitTests/appsettings.json,1779814416.3660524,1,entity framework returns async efcore asnotracking xunit unit test verify mock setup moq dbcontext fluentassertions arrange act assert appdbcontext times once,[MOD] InventoryAlert.UnitTests/appsettings.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\appsettings.Example.json,0,582,net10.0/appsettings.Example.json,1779814416.3795497,1,postgresql finnhubpricesyncworker postgres entity framework loss market data dbcontext compose stock price container efcore notification hosted service dockerfile external api price drop appdbcontext periodictimer threshold quote backgroundservice asnotracking,[MOD] net10.0/appsettings.Example.json +code,,23,062c332904c0ce2104c029fbaa9e0ba2,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\appsettings.json,0,583,net10.0/appsettings.json,1779814416.3660524,1,efcore returns async mock setup fluentassertions entity framework moq verify unit test dbcontext appdbcontext asnotracking arrange act assert times once xunit,[MOD] net10.0/appsettings.json +code,,1785,ace06dcdfed963a769231bf7d3d17433,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Api.deps.json,0,584,net10.0/InventoryAlert.Api.deps.json,1779852474.218987,1,entity framework dbcontext threshold efcore application service iproductservice notification productservice price drop loss asnotracking business logic appdbcontext,[MOD] net10.0/InventoryAlert.Api.deps.json +code,,20,37595336dae30b037bd95e5047b95825,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Api.runtimeconfig.json,0,585,net10.0/InventoryAlert.Api.runtimeconfig.json,1779852474.3064263,1,dbcontext entity framework asnotracking appdbcontext efcore,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,586,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1779852473.9235973,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json +code,,1,764ba22cde656c91f3e05ba4bc7bbcee,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,587,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1779852473.959113,1,loss threshold notification price drop,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json +code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Domain.deps.json,0,588,net10.0/InventoryAlert.Domain.deps.json,1779852469.346435,1,entity framework iproductservice dbcontext appdbcontext business logic productservice price drop efcore asnotracking application service loss notification threshold,[MOD] net10.0/InventoryAlert.Domain.deps.json +code,,1204,cb0b59a46f14c231584e0f3eae18a84d,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Infrastructure.deps.json,0,589,net10.0/InventoryAlert.Infrastructure.deps.json,1779852470.849428,1,asnotracking notification application service threshold productservice iproductservice dbcontext efcore appdbcontext price drop business logic entity framework loss,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json +code,,6412,780d4de32e288031ad6ebfd38fdefcbf,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.UnitTests.deps.json,0,590,net10.0/InventoryAlert.UnitTests.deps.json,1779852476.3533206,1,efcore unit test arrange act assert notification savechanges entity framework asnotracking unitofwork finnhubpricesyncworker threshold loss business logic atomicity hosted service commit application service rollback backgroundservice iproductservice periodictimer price drop xunit dbcontext appdbcontext fluentassertions productservice,[MOD] net10.0/InventoryAlert.UnitTests.deps.json +code,,20,5f3a2d98fc24aa854c5b9344a7a4d157,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.UnitTests.runtimeconfig.json,0,591,net10.0/InventoryAlert.UnitTests.runtimeconfig.json,1779852476.4341264,1,asnotracking fluentassertions arrange act assert appdbcontext xunit unit test efcore entity framework dbcontext,[MOD] net10.0/InventoryAlert.UnitTests.runtimeconfig.json +code,,1488,bbe0769f603dfb81733a7b52d5e43f76,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Worker.deps.json,0,592,net10.0/InventoryAlert.Worker.deps.json,1779852473.908222,1,loss appdbcontext efcore productservice backgroundservice hosted service business logic periodictimer entity framework asnotracking finnhubpricesyncworker threshold dbcontext notification application service iproductservice price drop,[MOD] net10.0/InventoryAlert.Worker.deps.json +code,,20,37595336dae30b037bd95e5047b95825,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,593,net10.0/InventoryAlert.Worker.runtimeconfig.json,1779852474.0111957,1,efcore entity framework dbcontext appdbcontext asnotracking,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json +code,,1,f44ca44dd881261586b84442f2201257,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,594,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1779852473.689481,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json +code,,6,e15b7bab85d1b5f11797ca764363b8b6,src\test\InventoryAlert.UnitTests\bin\Debug\net10.0\MvcTestingAppManifest.json,0,595,net10.0/MvcTestingAppManifest.json,1779852474.54477,1,periodictimer finnhubpricesyncworker threshold notification hosted service backgroundservice price drop loss,[MOD] net10.0/MvcTestingAppManifest.json +code,,37,bbfa87bac6ead82480acd5e2e0098195,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\appsettings.Example.json,0,596,net10.0/appsettings.Example.json,1779814416.3795497,1,notification asnotracking loss postgres periodictimer finnhubpricesyncworker entity framework postgresql market data appdbcontext efcore container backgroundservice quote dockerfile threshold compose price drop stock price dbcontext external api hosted service,[MOD] net10.0/appsettings.Example.json +code,,23,062c332904c0ce2104c029fbaa9e0ba2,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\appsettings.json,0,597,net10.0/appsettings.json,1779814416.3660524,1,arrange act assert unit test xunit returns async entity framework mock setup dbcontext asnotracking appdbcontext fluentassertions efcore moq times once verify,[MOD] net10.0/appsettings.json +code,,1785,ace06dcdfed963a769231bf7d3d17433,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Api.deps.json,0,598,net10.0/InventoryAlert.Api.deps.json,1779815055.0786984,1,iproductservice threshold productservice entity framework notification asnotracking efcore application service appdbcontext price drop loss dbcontext business logic,[MOD] net10.0/InventoryAlert.Api.deps.json +code,,21,d60cf9618363ac73f5894cceaffc545e,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Api.runtimeconfig.json,0,599,net10.0/InventoryAlert.Api.runtimeconfig.json,1779815055.1578588,1,appdbcontext asnotracking efcore entity framework dbcontext,[MOD] net10.0/InventoryAlert.Api.runtimeconfig.json +code,,1,ab33b3739aa9adef3c653178051f0778,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.endpoints.json,0,600,net10.0/InventoryAlert.Api.staticwebassets.endpoints.json,1779815054.8447104,1,,[MOD] net10.0/InventoryAlert.Api.staticwebassets.endpoints.json +code,,1,e6adbf2622be6f462ec396db3b4d5b74,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Api.staticwebassets.runtime.json,0,601,net10.0/InventoryAlert.Api.staticwebassets.runtime.json,1779815054.8755307,1,notification loss threshold price drop,[MOD] net10.0/InventoryAlert.Api.staticwebassets.runtime.json +code,,1167,5dcc2ba4270b945f88fe750d2866dbcf,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Domain.deps.json,0,602,net10.0/InventoryAlert.Domain.deps.json,1779815048.8279152,1,iproductservice efcore application service business logic entity framework loss threshold dbcontext appdbcontext asnotracking notification price drop productservice,[MOD] net10.0/InventoryAlert.Domain.deps.json +code,,1204,cb0b59a46f14c231584e0f3eae18a84d,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Infrastructure.deps.json,0,603,net10.0/InventoryAlert.Infrastructure.deps.json,1779815050.7656255,1,price drop appdbcontext threshold dbcontext asnotracking business logic loss application service efcore iproductservice notification entity framework productservice,[MOD] net10.0/InventoryAlert.Infrastructure.deps.json +code,,6412,9788c2cd5512198e9c9ca7d2eb60d9de,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.UnitTests.deps.json,0,604,net10.0/InventoryAlert.UnitTests.deps.json,1779815057.2573195,1,fluentassertions finnhubpricesyncworker xunit iproductservice efcore unit test dbcontext productservice price drop hosted service commit unitofwork atomicity periodictimer entity framework savechanges threshold application service appdbcontext asnotracking business logic backgroundservice notification arrange act assert rollback loss,[MOD] net10.0/InventoryAlert.UnitTests.deps.json +code,,21,11a2057f7e08545a87eae55a47ccbe16,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.UnitTests.runtimeconfig.json,0,605,net10.0/InventoryAlert.UnitTests.runtimeconfig.json,1779815057.3553205,1,efcore arrange act assert dbcontext xunit entity framework asnotracking unit test fluentassertions appdbcontext,[MOD] net10.0/InventoryAlert.UnitTests.runtimeconfig.json +code,,1488,bbe0769f603dfb81733a7b52d5e43f76,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Worker.deps.json,0,606,net10.0/InventoryAlert.Worker.deps.json,1779815054.685102,1,productservice business logic dbcontext entity framework periodictimer finnhubpricesyncworker backgroundservice application service hosted service asnotracking notification iproductservice appdbcontext loss threshold efcore price drop,[MOD] net10.0/InventoryAlert.Worker.deps.json +code,,21,d60cf9618363ac73f5894cceaffc545e,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Worker.runtimeconfig.json,0,607,net10.0/InventoryAlert.Worker.runtimeconfig.json,1779815054.7921462,1,entity framework efcore asnotracking appdbcontext dbcontext,[MOD] net10.0/InventoryAlert.Worker.runtimeconfig.json +code,,1,f44ca44dd881261586b84442f2201257,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\InventoryAlert.Worker.staticwebassets.endpoints.json,0,608,net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json,1779815054.3388731,1,,[MOD] net10.0/InventoryAlert.Worker.staticwebassets.endpoints.json +code,,6,7b48306a747fe6e90ebb00e01a0c08f4,src\test\InventoryAlert.UnitTests\bin\Release\net10.0\MvcTestingAppManifest.json,0,609,net10.0/MvcTestingAppManifest.json,1779815055.4423797,1,price drop periodictimer notification hosted service threshold loss finnhubpricesyncworker backgroundservice,[MOD] net10.0/MvcTestingAppManifest.json +code,,2901,6f659c61a506d6d6a5df9b0eeaabc688,src\test\InventoryAlert.UnitTests\obj\InventoryAlert.UnitTests.csproj.nuget.dgspec.json,0,610,obj/InventoryAlert.UnitTests.csproj.nuget.dgspec.json,1779852466.4085908,1,hosted service application service postgresql asnotracking periodictimer times once entity framework container productservice xunit efcore backgroundservice notification dbcontext finnhubpricesyncworker verify business logic returns async fluentassertions mock setup compose arrange act assert postgres price drop appdbcontext loss unit test dockerfile threshold iproductservice moq,[MOD] obj/InventoryAlert.UnitTests.csproj.nuget.dgspec.json +code,,6366,de7b5b19b7ab90396b49b2ef243cfb17,src\test\InventoryAlert.UnitTests\obj\project.assets.json,0,611,obj/project.assets.json,1779852466.3926091,1,entity framework mock setup notification loss efcore hosted service unit test price drop finnhubpricesyncworker business logic container moq verify postgresql postgres iproductservice productservice appdbcontext returns async periodictimer dockerfile dbcontext compose fluentassertions application service times once threshold arrange act assert backgroundservice asnotracking xunit,[MOD] obj/project.assets.json +code,,1,4227b3e7348017c816c5401d7521693b,src\test\InventoryAlert.UnitTests\obj\project.packagespec.json,0,612,obj/project.packagespec.json,1779852437.158456,1,backgroundservice notification compose returns async dbcontext productservice iproductservice price drop mock setup moq times once threshold arrange act assert entity framework xunit postgresql business logic unit test periodictimer hosted service container asnotracking efcore appdbcontext verify fluentassertions finnhubpricesyncworker application service postgres dockerfile loss,[MOD] obj/project.packagespec.json +code,,1,33cf78544497afb0836831abc3bcb58b,src\test\InventoryAlert.UnitTests\obj\Debug\net10.0\InventoryAlert.UnitTests.sourcelink.json,0,613,net10.0/InventoryAlert.UnitTests.sourcelink.json,1779852474.787866,1,efcore dbcontext entity framework asnotracking appdbcontext,[MOD] net10.0/InventoryAlert.UnitTests.sourcelink.json +code,,6,e15b7bab85d1b5f11797ca764363b8b6,src\test\InventoryAlert.UnitTests\obj\Debug\net10.0\MvcTestingAppManifest.json,0,614,net10.0/MvcTestingAppManifest.json,1779852474.54477,1,hosted service threshold finnhubpricesyncworker notification price drop loss periodictimer backgroundservice,[MOD] net10.0/MvcTestingAppManifest.json +code,,1,837e67bc2162b1f1aff1a7067aab411a,src\test\InventoryAlert.UnitTests\obj\Release\net10.0\InventoryAlert.UnitTests.sourcelink.json,0,615,net10.0/InventoryAlert.UnitTests.sourcelink.json,1779815055.7671342,1,,[MOD] net10.0/InventoryAlert.UnitTests.sourcelink.json +code,,6,7b48306a747fe6e90ebb00e01a0c08f4,src\test\InventoryAlert.UnitTests\obj\Release\net10.0\MvcTestingAppManifest.json,0,616,net10.0/MvcTestingAppManifest.json,1779815055.4423797,1,finnhubpricesyncworker price drop hosted service backgroundservice periodictimer loss notification threshold,[MOD] net10.0/MvcTestingAppManifest.json +code,,12,026d84133164917a1ecdc98f2d4ed9da,src\ui\InventoryAlert.UI\next.config.ts,0,617,InventoryAlert.UI/next.config,1779814416.2044578,1,entity framework efcore asnotracking appdbcontext dbcontext,[MOD] InventoryAlert.UI/next.config +code,,13,026d84133164917a1ecdc98f2d4ed9da,src\ui\InventoryAlert.UI\next.config.ts,0,618,InventoryAlert.UI/next.config,1779814416.2044578,13,entity framework efcore asnotracking appdbcontext dbcontext,[FUNC] InventoryAlert.UI/next.config/default nextConfig; +code,,7888,8882ddf0f9c107a85043c8426352d2f5,src\ui\InventoryAlert.UI\package-lock.json,0,619,InventoryAlert.UI/package-lock.json,1779814416.205458,1,notification asnotracking verify loss times once mock setup httpget unit test iproductservice httppost entity framework domain driven design productservice appdbcontext domain entity infrastructure httpput returns async efcore business logic iactionresult threshold application service arrange act assert productscontroller fluentassertions price drop application layer xunit dbcontext moq,[MOD] InventoryAlert.UI/package-lock.json +code,,34,b284e70ebbd986d0a0644a254dc3aba9,src\ui\InventoryAlert.UI\package.json,0,620,InventoryAlert.UI/package.json,1779814416.205966,1,price drop fluentassertions notification threshold loss arrange act assert xunit unit test,[MOD] InventoryAlert.UI/package.json +doc,"This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev",8,9162add00befbcdb432430f405c4ad8d,src\ui\InventoryAlert.UI\README.md,0,621,"next, https, nextjs, create, project, bootstrapped, docs, reference",1779814416.2034502,1,efcore appdbcontext igenericrepository dbcontext data access dbset entity framework asnotracking iproductrepository,README.md | This is a [Next.js](https://nextjs.org) project bootstrapped with [create-next-a +doc,"# or +yarn dev",10,9162add00befbcdb432430f405c4ad8d,src\ui\InventoryAlert.UI\README.md,0,622,yarn,1779814416.2034502,9,efcore appdbcontext igenericrepository dbcontext data access dbset entity framework asnotracking iproductrepository,# or | or yarn dev +doc,"# or +pnpm dev",12,9162add00befbcdb432430f405c4ad8d,src\ui\InventoryAlert.UI\README.md,0,623,pnpm,1779814416.2034502,11,efcore appdbcontext igenericrepository dbcontext data access dbset entity framework asnotracking iproductrepository,# or | or pnpm dev +doc,"# or +bun dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. + +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.",36,9162add00befbcdb432430f405c4ad8d,src\ui\InventoryAlert.UI\README.md,0,624,"next, https, vercel, your, learn, nextjs, page, font",1779814416.2034502,13,efcore appdbcontext igenericrepository dbcontext data access dbset entity framework asnotracking iproductrepository,# or | or bun dev Open [http://localhost:3000](http://localhost:3000) with your browser +code,,42,c65d60f70b09a8e2b72ef41857a167c0,src\ui\InventoryAlert.UI\tsconfig.json,0,625,InventoryAlert.UI/tsconfig.json,1779814416.227826,1,,[MOD] InventoryAlert.UI/tsconfig.json +code,,4,e11718c6b73e618de10eebdd55c8f8e2,src\ui\InventoryAlert.UI\vitest.config.ts,0,626,InventoryAlert.UI/vitest.config,1779814416.227826,1,fluentassertions unit test asnotracking dbcontext arrange act assert efcore appdbcontext entity framework xunit,[MOD] InventoryAlert.UI/vitest.config +code,,14,e11718c6b73e618de10eebdd55c8f8e2,src\ui\InventoryAlert.UI\vitest.config.ts,0,627,InventoryAlert.UI/vitest.config,1779814416.227826,5,fluentassertions unit test asnotracking dbcontext arrange act assert efcore appdbcontext entity framework xunit,[FUNC] InventoryAlert.UI/vitest.config/default defineConfig +code,,1,21ce0057e7da4e80995decfd6cc827f1,src\ui\InventoryAlert.UI\vitest.setup.ts,0,628,InventoryAlert.UI/vitest.setup,1779814416.227826,1,fluentassertions arrange act assert xunit unit test,[MOD] InventoryAlert.UI/vitest.setup +code,,11,540935b83f86f5e361ab150c170d7d31,src\ui\InventoryAlert.UI\src\app\layout.tsx,0,629,app/layoutx,1779814416.2123659,1,entity framework dbcontext threshold container postgresql efcore compose notification price drop loss postgres asnotracking appdbcontext dockerfile,[MOD] app/layoutx +code,,16,540935b83f86f5e361ab150c170d7d31,src\ui\InventoryAlert.UI\src\app\layout.tsx,0,630,app/layoutx,1779814416.2123659,12,entity framework dbcontext threshold container postgresql efcore compose notification price drop loss postgres asnotracking appdbcontext dockerfile,[FUNC] app/layoutx/const metadata: Metadata = { +code,,56,540935b83f86f5e361ab150c170d7d31,src\ui\InventoryAlert.UI\src\app\layout.tsx,0,631,app/layoutx,1779814416.2123659,17,entity framework dbcontext threshold container postgresql efcore compose notification price drop loss postgres asnotracking appdbcontext dockerfile,[FUNC] app/layoutx/default function RootLayout +code,,11,8aaa6cbd9070aedb3bd45b6128731b55,src\ui\InventoryAlert.UI\src\app\page.tsx,0,632,app/pagex,1779814416.2138817,1,price drop asnotracking notification threshold loss appdbcontext efcore entity framework dbcontext,[MOD] app/pagex +code,,19,8aaa6cbd9070aedb3bd45b6128731b55,src\ui\InventoryAlert.UI\src\app\page.tsx,0,633,app/pagex,1779814416.2138817,12,price drop asnotracking notification threshold loss appdbcontext efcore entity framework dbcontext,[FUNC] app/pagex/interface WatchlistItem { +code,,27,8aaa6cbd9070aedb3bd45b6128731b55,src\ui\InventoryAlert.UI\src\app\page.tsx,0,634,app/pagex,1779814416.2138817,20,price drop asnotracking notification threshold loss appdbcontext efcore entity framework dbcontext,[FUNC] app/pagex/interface NewsItem { +code,,324,8aaa6cbd9070aedb3bd45b6128731b55,src\ui\InventoryAlert.UI\src\app\page.tsx,0,635,app/pagex,1779814416.2138817,28,price drop asnotracking notification threshold loss appdbcontext efcore entity framework dbcontext,[FUNC] app/pagex/default function Dashboard +code,,2,26c357972013ed373b4a09504a7e838f,src\ui\InventoryAlert.UI\src\app\(auth)\login\page.tsx,0,636,login/pagex,1779814416.209157,1,appdbcontext efcore entity framework asnotracking dbcontext,[MOD] login/pagex +code,,9,26c357972013ed373b4a09504a7e838f,src\ui\InventoryAlert.UI\src\app\(auth)\login\page.tsx,0,637,login/pagex,1779814416.209157,3,appdbcontext efcore entity framework asnotracking dbcontext,[FUNC] login/pagex/const dynamic = 'force-dynamic' +code,,108,26c357972013ed373b4a09504a7e838f,src\ui\InventoryAlert.UI\src\app\(auth)\login\page.tsx,0,638,login/pagex,1779814416.209157,10,appdbcontext efcore entity framework asnotracking dbcontext,[FUNC] login/pagex/function LoginForm +code,,115,26c357972013ed373b4a09504a7e838f,src\ui\InventoryAlert.UI\src\app\(auth)\login\page.tsx,0,639,login/pagex,1779814416.209157,109,appdbcontext efcore entity framework asnotracking dbcontext,[FUNC] login/pagex/default function LoginPage +code,,7,6fa83482d7987a95e4e3a98cb74f21cd,src\ui\InventoryAlert.UI\src\app\(auth)\register\page.tsx,0,640,register/pagex,1779814416.209157,1,asnotracking price drop notification loss efcore appdbcontext threshold entity framework dbcontext,[MOD] register/pagex +code,,121,6fa83482d7987a95e4e3a98cb74f21cd,src\ui\InventoryAlert.UI\src\app\(auth)\register\page.tsx,0,641,register/pagex,1779814416.209157,8,asnotracking price drop notification loss efcore appdbcontext threshold entity framework dbcontext,[FUNC] register/pagex/default function RegisterPage +code,,5,70cc9fd66940e9b99baaef83cd636186,src\ui\InventoryAlert.UI\src\app\admin\health\page.tsx,0,642,health/pagex,1779814416.2101552,1,efcore stock price hosted service entity framework market data periodictimer appdbcontext dbcontext finnhubpricesyncworker backgroundservice external api asnotracking quote,[MOD] health/pagex +code,,12,70cc9fd66940e9b99baaef83cd636186,src\ui\InventoryAlert.UI\src\app\admin\health\page.tsx,0,643,health/pagex,1779814416.2101552,6,efcore stock price hosted service entity framework market data periodictimer appdbcontext dbcontext finnhubpricesyncworker backgroundservice external api asnotracking quote,[FUNC] health/pagex/interface HealthCheckEntry { +code,,18,70cc9fd66940e9b99baaef83cd636186,src\ui\InventoryAlert.UI\src\app\admin\health\page.tsx,0,644,health/pagex,1779814416.2101552,13,efcore stock price hosted service entity framework market data periodictimer appdbcontext dbcontext finnhubpricesyncworker backgroundservice external api asnotracking quote,[FUNC] health/pagex/interface HealthResponse { +code,,167,70cc9fd66940e9b99baaef83cd636186,src\ui\InventoryAlert.UI\src\app\admin\health\page.tsx,0,645,health/pagex,1779814416.2101552,19,efcore stock price hosted service entity framework market data periodictimer appdbcontext dbcontext finnhubpricesyncworker backgroundservice external api asnotracking quote,[FUNC] health/pagex/default function AdminHealth +code,,6,07dcefb8ecf5bb2749edaafc8dd713f8,src\ui\InventoryAlert.UI\src\app\alerts\page.tsx,0,646,alerts/pagex,1779814416.210763,1,msft loss stock ticker dbcontext efcore googl appdbcontext notification symbol threshold asnotracking aapl price drop entity framework,[MOD] alerts/pagex +code,,34,07dcefb8ecf5bb2749edaafc8dd713f8,src\ui\InventoryAlert.UI\src\app\alerts\page.tsx,0,647,alerts/pagex,1779814416.210763,7,msft loss stock ticker dbcontext efcore googl appdbcontext notification symbol threshold asnotracking aapl price drop entity framework,[FUNC] alerts/pagex/interface AlertRule { +code,,48,07dcefb8ecf5bb2749edaafc8dd713f8,src\ui\InventoryAlert.UI\src\app\alerts\page.tsx,0,648,alerts/pagex,1779814416.210763,35,msft loss stock ticker dbcontext efcore googl appdbcontext notification symbol threshold asnotracking aapl price drop entity framework,[FUNC] alerts/pagex/interface AlertFormState { +code,,355,07dcefb8ecf5bb2749edaafc8dd713f8,src\ui\InventoryAlert.UI\src\app\alerts\page.tsx,0,649,alerts/pagex,1779814416.210763,49,msft loss stock ticker dbcontext efcore googl appdbcontext notification symbol threshold asnotracking aapl price drop entity framework,[FUNC] alerts/pagex/default function AlertsManager +code,,7,1a9dc8ade2ee254f602f9f7495eb1605,src\ui\InventoryAlert.UI\src\app\market\page.tsx,0,650,market/pagex,1779814416.2133749,1,efcore threshold notification dbcontext entity framework price drop loss asnotracking appdbcontext,[MOD] market/pagex +code,,18,1a9dc8ade2ee254f602f9f7495eb1605,src\ui\InventoryAlert.UI\src\app\market\page.tsx,0,651,market/pagex,1779814416.2133749,8,efcore threshold notification dbcontext entity framework price drop loss asnotracking appdbcontext,[FUNC] market/pagex/interface MarketNews { +code,,26,1a9dc8ade2ee254f602f9f7495eb1605,src\ui\InventoryAlert.UI\src\app\market\page.tsx,0,652,market/pagex,1779814416.2133749,19,efcore threshold notification dbcontext entity framework price drop loss asnotracking appdbcontext,[FUNC] market/pagex/interface MarketStatus { +code,,35,1a9dc8ade2ee254f602f9f7495eb1605,src\ui\InventoryAlert.UI\src\app\market\page.tsx,0,653,market/pagex,1779814416.2133749,27,efcore threshold notification dbcontext entity framework price drop loss asnotracking appdbcontext,[FUNC] market/pagex/interface EarningsCalendar { +code,,39,1a9dc8ade2ee254f602f9f7495eb1605,src\ui\InventoryAlert.UI\src\app\market\page.tsx,0,654,market/pagex,1779814416.2133749,36,efcore threshold notification dbcontext entity framework price drop loss asnotracking appdbcontext,[FUNC] market/pagex/function formatDateParam +code,,369,1a9dc8ade2ee254f602f9f7495eb1605,src\ui\InventoryAlert.UI\src\app\market\page.tsx,0,655,market/pagex,1779814416.2133749,40,efcore threshold notification dbcontext entity framework price drop loss asnotracking appdbcontext,[FUNC] market/pagex/default function MarketOverview +code,,24,39e6788e1dad82b9e5ee32ac601a8a21,src\ui\InventoryAlert.UI\src\app\notifications\page.tsx,0,656,notifications/pagex,1779814416.2138817,1,aapl arrange act assert threshold msft unit test entity framework notification asnotracking efcore appdbcontext symbol fluentassertions stock ticker price drop loss googl dbcontext xunit,[MOD] notifications/pagex +code,,34,39e6788e1dad82b9e5ee32ac601a8a21,src\ui\InventoryAlert.UI\src\app\notifications\page.tsx,0,657,notifications/pagex,1779814416.2138817,25,aapl arrange act assert threshold msft unit test entity framework notification asnotracking efcore appdbcontext symbol fluentassertions stock ticker price drop loss googl dbcontext xunit,[FUNC] notifications/pagex/interface Notification { +code,,257,39e6788e1dad82b9e5ee32ac601a8a21,src\ui\InventoryAlert.UI\src\app\notifications\page.tsx,0,658,notifications/pagex,1779814416.2138817,35,aapl arrange act assert threshold msft unit test entity framework notification asnotracking efcore appdbcontext symbol fluentassertions stock ticker price drop loss googl dbcontext xunit,[FUNC] notifications/pagex/default function NotificationsPage +code,,11,67911d9384d271c3e7f09524bf70ec9b,src\ui\InventoryAlert.UI\src\app\portfolio\page.tsx,0,659,portfolio/pagex,1779814416.2154064,1,asnotracking entity framework dbcontext appdbcontext efcore,[MOD] portfolio/pagex +code,,27,67911d9384d271c3e7f09524bf70ec9b,src\ui\InventoryAlert.UI\src\app\portfolio\page.tsx,0,660,portfolio/pagex,1779814416.2154064,12,asnotracking entity framework dbcontext appdbcontext efcore,[FUNC] portfolio/pagex/interface PortfolioPosition { +code,,234,67911d9384d271c3e7f09524bf70ec9b,src\ui\InventoryAlert.UI\src\app\portfolio\page.tsx,0,661,portfolio/pagex,1779814416.2154064,28,asnotracking entity framework dbcontext appdbcontext efcore,[FUNC] portfolio/pagex/default function PortfolioPage +code,,8,10ae764bff6cffe766470aae9d4cd7b6,src\ui\InventoryAlert.UI\src\app\stocks\page.tsx,0,662,stocks/pagex,1779814416.2154064,1,dbcontext entity framework msft googl symbol aapl asnotracking appdbcontext stock ticker efcore,[MOD] stocks/pagex +code,,20,10ae764bff6cffe766470aae9d4cd7b6,src\ui\InventoryAlert.UI\src\app\stocks\page.tsx,0,663,stocks/pagex,1779814416.2154064,9,dbcontext entity framework msft googl symbol aapl asnotracking appdbcontext stock ticker efcore,[FUNC] stocks/pagex/interface StockListing { +code,,27,10ae764bff6cffe766470aae9d4cd7b6,src\ui\InventoryAlert.UI\src\app\stocks\page.tsx,0,664,stocks/pagex,1779814416.2154064,21,dbcontext entity framework msft googl symbol aapl asnotracking appdbcontext stock ticker efcore,[FUNC] stocks/pagex/interface SymbolSearchResult { +code,,214,10ae764bff6cffe766470aae9d4cd7b6,src\ui\InventoryAlert.UI\src\app\stocks\page.tsx,0,665,stocks/pagex,1779814416.2154064,28,dbcontext entity framework msft googl symbol aapl asnotracking appdbcontext stock ticker efcore,[FUNC] stocks/pagex/default function StockCatalog +code,,11,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,666,[symbol]/pagex,1779814416.2154064,1,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[MOD] [symbol]/pagex +code,,23,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,667,[symbol]/pagex,1779814416.2154064,12,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/interface StockQuote { +code,,36,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,668,[symbol]/pagex,1779814416.2154064,24,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/interface StockProfile { +code,,48,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,669,[symbol]/pagex,1779814416.2154064,37,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/interface StockMetrics { +code,,56,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,670,[symbol]/pagex,1779814416.2154064,49,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/interface EarningsSurprise { +code,,65,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,671,[symbol]/pagex,1779814416.2154064,57,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/interface RecommendationTrend { +code,,74,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,672,[symbol]/pagex,1779814416.2154064,66,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/interface InsiderTransaction { +code,,85,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,673,[symbol]/pagex,1779814416.2154064,75,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/interface NewsItem { +code,,93,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,674,[symbol]/pagex,1779814416.2154064,86,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/interface PeersResponse { +code,,661,4701eeccaae66cb107be4637adb6e041,src\ui\InventoryAlert.UI\src\app\stocks\[symbol]\page.tsx,0,675,[symbol]/pagex,1779814416.2154064,94,xunit arrange act assert commit entity framework fluentassertions dbcontext appdbcontext unit test price drop efcore savechanges asnotracking atomicity loss rollback notification threshold unitofwork,[FUNC] [symbol]/pagex/default function StockDetailPage +code,,11,f6b313f158bd789f3cd2fc505018aa09,src\ui\InventoryAlert.UI\src\app\watchlist\page.tsx,0,676,watchlist/pagex,1779814416.2169342,1,asnotracking dbcontext efcore appdbcontext entity framework,[MOD] watchlist/pagex +code,,19,f6b313f158bd789f3cd2fc505018aa09,src\ui\InventoryAlert.UI\src\app\watchlist\page.tsx,0,677,watchlist/pagex,1779814416.2169342,12,asnotracking dbcontext efcore appdbcontext entity framework,[FUNC] watchlist/pagex/interface WatchlistItem { +code,,156,f6b313f158bd789f3cd2fc505018aa09,src\ui\InventoryAlert.UI\src\app\watchlist\page.tsx,0,678,watchlist/pagex,1779814416.2169342,20,asnotracking dbcontext efcore appdbcontext entity framework,[FUNC] watchlist/pagex/default function WatchlistPage +code,,5,119225681e87370cb660f777afd373a7,src\ui\InventoryAlert.UI\src\components\AddSymbolModal.tsx,0,679,InventoryAlert.UI/AddSymbolModalx,1779814416.2179434,1,entity framework symbol stock ticker efcore asnotracking msft dbcontext appdbcontext aapl googl,[MOD] InventoryAlert.UI/AddSymbolModalx +code,,11,119225681e87370cb660f777afd373a7,src\ui\InventoryAlert.UI\src\components\AddSymbolModal.tsx,0,680,InventoryAlert.UI/AddSymbolModalx,1779814416.2179434,6,entity framework symbol stock ticker efcore asnotracking msft dbcontext appdbcontext aapl googl,[FUNC] InventoryAlert.UI/AddSymbolModalx/interface AddSymbolModalProps { +code,,100,119225681e87370cb660f777afd373a7,src\ui\InventoryAlert.UI\src\components\AddSymbolModal.tsx,0,681,InventoryAlert.UI/AddSymbolModalx,1779814416.2179434,12,entity framework symbol stock ticker efcore asnotracking msft dbcontext appdbcontext aapl googl,[FUNC] InventoryAlert.UI/AddSymbolModalx/function AddSymbolModal +code,,2,73318118b7373a63e816bdf752d91b94,src\ui\InventoryAlert.UI\src\components\ConfirmDialog.tsx,0,682,InventoryAlert.UI/ConfirmDialogx,1779814416.2179434,1,,[MOD] InventoryAlert.UI/ConfirmDialogx +code,,13,73318118b7373a63e816bdf752d91b94,src\ui\InventoryAlert.UI\src\components\ConfirmDialog.tsx,0,683,InventoryAlert.UI/ConfirmDialogx,1779814416.2179434,3,,[FUNC] InventoryAlert.UI/ConfirmDialogx/interface ConfirmDialogProps { +code,,58,73318118b7373a63e816bdf752d91b94,src\ui\InventoryAlert.UI\src\components\ConfirmDialog.tsx,0,684,InventoryAlert.UI/ConfirmDialogx,1779814416.2179434,14,,[FUNC] InventoryAlert.UI/ConfirmDialogx/function ConfirmDialog +code,,6,475e8f5708eaa80250792b66f9676a67,src\ui\InventoryAlert.UI\src\components\GlobalSearch.tsx,0,685,InventoryAlert.UI/GlobalSearchx,1779814416.2184627,1,asnotracking dbcontext efcore entity framework appdbcontext,[MOD] InventoryAlert.UI/GlobalSearchx +code,,11,475e8f5708eaa80250792b66f9676a67,src\ui\InventoryAlert.UI\src\components\GlobalSearch.tsx,0,686,InventoryAlert.UI/GlobalSearchx,1779814416.2184627,7,asnotracking dbcontext efcore entity framework appdbcontext,[FUNC] InventoryAlert.UI/GlobalSearchx/interface GlobalSearchProps { +code,,181,475e8f5708eaa80250792b66f9676a67,src\ui\InventoryAlert.UI\src\components\GlobalSearch.tsx,0,687,InventoryAlert.UI/GlobalSearchx,1779814416.2184627,12,asnotracking dbcontext efcore entity framework appdbcontext,[FUNC] InventoryAlert.UI/GlobalSearchx/function GlobalSearch +code,,47,1a9e50a699e98560b0d935990c8f5996,src\ui\InventoryAlert.UI\src\components\MarketStatusBanner.test.tsx,0,688,InventoryAlert.UI/MarketStatusBanner.testx,1779814416.2184627,1,entity framework moq unit test appdbcontext times once mock setup dbcontext verify asnotracking efcore xunit fluentassertions returns async arrange act assert,[MOD] InventoryAlert.UI/MarketStatusBanner.testx +code,,5,1344122ab5bba6e2a07d8f004216540b,src\ui\InventoryAlert.UI\src\components\MarketStatusBanner.tsx,0,689,InventoryAlert.UI/MarketStatusBannerx,1779814416.2184627,1,entity framework dbcontext appdbcontext efcore asnotracking,[MOD] InventoryAlert.UI/MarketStatusBannerx +code,,40,1344122ab5bba6e2a07d8f004216540b,src\ui\InventoryAlert.UI\src\components\MarketStatusBanner.tsx,0,690,InventoryAlert.UI/MarketStatusBannerx,1779814416.2184627,6,entity framework dbcontext appdbcontext efcore asnotracking,[FUNC] InventoryAlert.UI/MarketStatusBannerx/function MarketStatusBanner +code,,16,9a3e199622919c7cc96c2b17a6898d38,src\ui\InventoryAlert.UI\src\components\Navbar.tsx,0,691,InventoryAlert.UI/Navbarx,1779814416.2199922,1,entity framework threshold notification loss efcore appdbcontext asnotracking dbcontext price drop,[MOD] InventoryAlert.UI/Navbarx +code,,20,9a3e199622919c7cc96c2b17a6898d38,src\ui\InventoryAlert.UI\src\components\Navbar.tsx,0,692,InventoryAlert.UI/Navbarx,1779814416.2199922,17,entity framework threshold notification loss efcore appdbcontext asnotracking dbcontext price drop,[FUNC] InventoryAlert.UI/Navbarx/interface NavbarProps { +code,,168,9a3e199622919c7cc96c2b17a6898d38,src\ui\InventoryAlert.UI\src\components\Navbar.tsx,0,693,InventoryAlert.UI/Navbarx,1779814416.2199922,21,entity framework threshold notification loss efcore appdbcontext asnotracking dbcontext price drop,[FUNC] InventoryAlert.UI/Navbarx/default function Navbar +code,,6,973be9acc996bde509edab35f86d36a4,src\ui\InventoryAlert.UI\src\components\NavbarWrapper.tsx,0,694,InventoryAlert.UI/NavbarWrapperx,1779814416.2205794,1,appdbcontext efcore entity framework asnotracking dbcontext,[MOD] InventoryAlert.UI/NavbarWrapperx +code,,28,973be9acc996bde509edab35f86d36a4,src\ui\InventoryAlert.UI\src\components\NavbarWrapper.tsx,0,695,InventoryAlert.UI/NavbarWrapperx,1779814416.2205794,7,appdbcontext efcore entity framework asnotracking dbcontext,[FUNC] InventoryAlert.UI/NavbarWrapperx/default function NavbarWrapper +code,,74,80710e68dc69bfe731bf1f68b7cfac20,src\ui\InventoryAlert.UI\src\components\NotificationBell.test.tsx,0,696,InventoryAlert.UI/NotificationBell.testx,1779814416.2205794,1,fluentassertions asnotracking arrange act assert efcore mock setup xunit appdbcontext returns async unit test verify entity framework times once moq dbcontext,[MOD] InventoryAlert.UI/NotificationBell.testx +code,,6,6f52029815fe10240619a58d1ce975fd,src\ui\InventoryAlert.UI\src\components\NotificationBell.tsx,0,697,InventoryAlert.UI/NotificationBellx,1779814416.2211556,1,efcore entity framework dbcontext appdbcontext asnotracking,[MOD] InventoryAlert.UI/NotificationBellx +code,,30,6f52029815fe10240619a58d1ce975fd,src\ui\InventoryAlert.UI\src\components\NotificationBell.tsx,0,698,InventoryAlert.UI/NotificationBellx,1779814416.2211556,7,efcore entity framework dbcontext appdbcontext asnotracking,[FUNC] InventoryAlert.UI/NotificationBellx/default function NotificationBell +code,,6,210adad1e6e461065af8c176deee5a33,src\ui\InventoryAlert.UI\src\components\NotificationProvider.tsx,0,699,InventoryAlert.UI/NotificationProviderx,1779814416.2211556,1,notification msft asnotracking loss price drop threshold appdbcontext googl efcore aapl dbcontext entity framework stock ticker symbol,[MOD] InventoryAlert.UI/NotificationProviderx +code,,16,210adad1e6e461065af8c176deee5a33,src\ui\InventoryAlert.UI\src\components\NotificationProvider.tsx,0,700,InventoryAlert.UI/NotificationProviderx,1779814416.2211556,7,notification msft asnotracking loss price drop threshold appdbcontext googl efcore aapl dbcontext entity framework stock ticker symbol,[FUNC] InventoryAlert.UI/NotificationProviderx/interface Notification { +code,,27,210adad1e6e461065af8c176deee5a33,src\ui\InventoryAlert.UI\src\components\NotificationProvider.tsx,0,701,InventoryAlert.UI/NotificationProviderx,1779814416.2211556,17,notification msft asnotracking loss price drop threshold appdbcontext googl efcore aapl dbcontext entity framework stock ticker symbol,[FUNC] InventoryAlert.UI/NotificationProviderx/interface NotificationContextType { +code,,125,210adad1e6e461065af8c176deee5a33,src\ui\InventoryAlert.UI\src\components\NotificationProvider.tsx,0,702,InventoryAlert.UI/NotificationProviderx,1779814416.2211556,28,notification msft asnotracking loss price drop threshold appdbcontext googl efcore aapl dbcontext entity framework stock ticker symbol,[FUNC] InventoryAlert.UI/NotificationProviderx/const NotificationProvider = +code,,132,210adad1e6e461065af8c176deee5a33,src\ui\InventoryAlert.UI\src\components\NotificationProvider.tsx,0,703,InventoryAlert.UI/NotificationProviderx,1779814416.2211556,126,notification msft asnotracking loss price drop threshold appdbcontext googl efcore aapl dbcontext entity framework stock ticker symbol,[FUNC] InventoryAlert.UI/NotificationProviderx/const useNotifications = +code,,5,4501cbb88be86a2045d46aa0239a8b48,src\ui\InventoryAlert.UI\src\components\PriceAlertModal.tsx,0,704,InventoryAlert.UI/PriceAlertModalx,1779814416.2221656,1,msft loss stock ticker dbcontext efcore googl appdbcontext notification symbol threshold asnotracking aapl price drop entity framework,[MOD] InventoryAlert.UI/PriceAlertModalx +code,,12,4501cbb88be86a2045d46aa0239a8b48,src\ui\InventoryAlert.UI\src\components\PriceAlertModal.tsx,0,705,InventoryAlert.UI/PriceAlertModalx,1779814416.2221656,6,msft loss stock ticker dbcontext efcore googl appdbcontext notification symbol threshold asnotracking aapl price drop entity framework,[FUNC] InventoryAlert.UI/PriceAlertModalx/interface PriceAlertModalProps { +code,,135,4501cbb88be86a2045d46aa0239a8b48,src\ui\InventoryAlert.UI\src\components\PriceAlertModal.tsx,0,706,InventoryAlert.UI/PriceAlertModalx,1779814416.2221656,13,msft loss stock ticker dbcontext efcore googl appdbcontext notification symbol threshold asnotracking aapl price drop entity framework,[FUNC] InventoryAlert.UI/PriceAlertModalx/function PriceAlertModal +code,,10,42e9018a80863fb507a4b927e5eb220b,src\ui\InventoryAlert.UI\src\components\ThemeProvider.tsx,0,707,InventoryAlert.UI/ThemeProviderx,1779814416.2221656,1,efcore dbcontext entity framework asnotracking appdbcontext,[MOD] InventoryAlert.UI/ThemeProviderx +code,,12,42e9018a80863fb507a4b927e5eb220b,src\ui\InventoryAlert.UI\src\components\ThemeProvider.tsx,0,708,InventoryAlert.UI/ThemeProviderx,1779814416.2221656,11,efcore dbcontext entity framework asnotracking appdbcontext,[FUNC] InventoryAlert.UI/ThemeProviderx/const useTheme = +code,,38,42e9018a80863fb507a4b927e5eb220b,src\ui\InventoryAlert.UI\src\components\ThemeProvider.tsx,0,709,InventoryAlert.UI/ThemeProviderx,1779814416.2221656,13,efcore dbcontext entity framework asnotracking appdbcontext,[FUNC] InventoryAlert.UI/ThemeProviderx/default function ThemeProvider +code,,4,0dcdfae7d0f949f14379e2012a204108,src\ui\InventoryAlert.UI\src\components\Toast.tsx,0,710,InventoryAlert.UI/Toastx,1779814416.2221656,1,appdbcontext asnotracking efcore entity framework dbcontext,[MOD] InventoryAlert.UI/Toastx +code,,6,0dcdfae7d0f949f14379e2012a204108,src\ui\InventoryAlert.UI\src\components\Toast.tsx,0,711,InventoryAlert.UI/Toastx,1779814416.2221656,5,appdbcontext asnotracking efcore entity framework dbcontext,[FUNC] InventoryAlert.UI/Toastx/type ToastType = 'success' | 'error' | 'info' +code,,13,0dcdfae7d0f949f14379e2012a204108,src\ui\InventoryAlert.UI\src\components\Toast.tsx,0,712,InventoryAlert.UI/Toastx,1779814416.2221656,7,appdbcontext asnotracking efcore entity framework dbcontext,[FUNC] InventoryAlert.UI/Toastx/interface ToastProps { +code,,54,0dcdfae7d0f949f14379e2012a204108,src\ui\InventoryAlert.UI\src\components\Toast.tsx,0,713,InventoryAlert.UI/Toastx,1779814416.2221656,14,appdbcontext asnotracking efcore entity framework dbcontext,[FUNC] InventoryAlert.UI/Toastx/function Toast +code,,5,f43005130820b096ad56ad688f9c5d75,src\ui\InventoryAlert.UI\src\components\TradeModal.tsx,0,714,InventoryAlert.UI/TradeModalx,1779814416.2221656,1,aapl msft entity framework asnotracking efcore appdbcontext symbol stock ticker googl dbcontext,[MOD] InventoryAlert.UI/TradeModalx +code,,12,f43005130820b096ad56ad688f9c5d75,src\ui\InventoryAlert.UI\src\components\TradeModal.tsx,0,715,InventoryAlert.UI/TradeModalx,1779814416.2221656,6,aapl msft entity framework asnotracking efcore appdbcontext symbol stock ticker googl dbcontext,[FUNC] InventoryAlert.UI/TradeModalx/interface TradeModalProps { +code,,229,f43005130820b096ad56ad688f9c5d75,src\ui\InventoryAlert.UI\src\components\TradeModal.tsx,0,716,InventoryAlert.UI/TradeModalx,1779814416.2221656,13,aapl msft entity framework asnotracking efcore appdbcontext symbol stock ticker googl dbcontext,[FUNC] InventoryAlert.UI/TradeModalx/function TradeModal +code,,9,ed6b8328e648955925777cc8f027effc,src\ui\InventoryAlert.UI\src\components\UserNav.tsx,0,717,InventoryAlert.UI/UserNavx,1779814416.2232177,1,asnotracking entity framework dbcontext appdbcontext efcore,[MOD] InventoryAlert.UI/UserNavx +code,,75,ed6b8328e648955925777cc8f027effc,src\ui\InventoryAlert.UI\src\components\UserNav.tsx,0,718,InventoryAlert.UI/UserNavx,1779814416.2232177,10,asnotracking entity framework dbcontext appdbcontext efcore,[FUNC] InventoryAlert.UI/UserNavx/default function UserNav +code,,4,256c88b80ea91d62d5967a6f8b907723,src\ui\InventoryAlert.UI\src\components\ui\Pagination.tsx,0,719,ui/Paginationx,1779814416.224313,1,dbcontext entity framework asnotracking appdbcontext efcore,[MOD] ui/Paginationx +code,,12,256c88b80ea91d62d5967a6f8b907723,src\ui\InventoryAlert.UI\src\components\ui\Pagination.tsx,0,720,ui/Paginationx,1779814416.224313,5,dbcontext entity framework asnotracking appdbcontext efcore,[FUNC] ui/Paginationx/interface PaginationProps { +code,,157,256c88b80ea91d62d5967a6f8b907723,src\ui\InventoryAlert.UI\src\components\ui\Pagination.tsx,0,721,ui/Paginationx,1779814416.224313,13,dbcontext entity framework asnotracking appdbcontext efcore,[FUNC] ui/Paginationx/default function Pagination +code,,7,353ade3b3ead2bb49223e9badca804c8,src\ui\InventoryAlert.UI\src\hooks\useSignalR.ts,0,722,InventoryAlert.UI/useSignalR,1779814416.224313,1,asnotracking efcore appdbcontext dbcontext entity framework,[MOD] InventoryAlert.UI/useSignalR +code,,80,353ade3b3ead2bb49223e9badca804c8,src\ui\InventoryAlert.UI\src\hooks\useSignalR.ts,0,723,InventoryAlert.UI/useSignalR,1779814416.224313,8,asnotracking efcore appdbcontext dbcontext entity framework,[FUNC] InventoryAlert.UI/useSignalR/const useSignalR = +code,,120,8ecfe79703117c3893b38b6f9833b88e,src\ui\InventoryAlert.UI\src\lib\api.refresh.test.ts,0,724,lib/api.refresh.test,1779814416.2253218,1,verify fluentassertions unit test times once asnotracking returns async dbcontext arrange act assert efcore xunit appdbcontext entity framework mock setup moq,[MOD] lib/api.refresh.test +code,,51,52e9670cc12a8840fc4bad5950612efb,src\ui\InventoryAlert.UI\src\lib\api.test.ts,0,725,lib/api.test,1779814416.2253218,1,entity framework returns async efcore asnotracking xunit unit test verify mock setup moq dbcontext fluentassertions arrange act assert appdbcontext times once,[MOD] lib/api.test +code,,5,292479087af466e14767b5497df20767,src\ui\InventoryAlert.UI\src\lib\api.ts,0,726,lib/api,1779814416.2263198,1,entity framework dbcontext efcore asnotracking appdbcontext,[MOD] lib/api +code,,19,292479087af466e14767b5497df20767,src\ui\InventoryAlert.UI\src\lib\api.ts,0,727,lib/api,1779814416.2263198,6,entity framework dbcontext efcore asnotracking appdbcontext,[FUNC] lib/api/ApiError extends Error { +code,,41,292479087af466e14767b5497df20767,src\ui\InventoryAlert.UI\src\lib\api.ts,0,728,lib/api,1779814416.2263198,20,entity framework dbcontext efcore asnotracking appdbcontext,[FUNC] lib/api/async function tryRefreshToken +code,,111,292479087af466e14767b5497df20767,src\ui\InventoryAlert.UI\src\lib\api.ts,0,729,lib/api,1779814416.2263198,42,entity framework dbcontext efcore asnotracking appdbcontext,[FUNC] lib/api/async function fetchApi +code,,6,ade7567d93c4a95ac7fab704783d035b,src\ui\InventoryAlert.UI\src\lib\error-utils.ts,0,730,lib/error-utils,1779814416.2273192,1,entity framework dbcontext efcore appdbcontext asnotracking,[FUNC] lib/error-utils/interface ApiErrorDetail { +code,,16,ade7567d93c4a95ac7fab704783d035b,src\ui\InventoryAlert.UI\src\lib\error-utils.ts,0,731,lib/error-utils,1779814416.2273192,7,entity framework dbcontext efcore appdbcontext asnotracking,[FUNC] lib/error-utils/interface ErrorResponse { +code,,35,ade7567d93c4a95ac7fab704783d035b,src\ui\InventoryAlert.UI\src\lib\error-utils.ts,0,732,lib/error-utils,1779814416.2273192,17,entity framework dbcontext efcore appdbcontext asnotracking,[FUNC] lib/error-utils/function getErrorMessage +code,,38,ade7567d93c4a95ac7fab704783d035b,src\ui\InventoryAlert.UI\src\lib\error-utils.ts,0,733,lib/error-utils,1779814416.2273192,36,entity framework dbcontext efcore appdbcontext asnotracking,[FUNC] lib/error-utils/function getCorrelationId +code,,68,7ece2c54faad1a5535b5cc2e3daa6539,src\ui\InventoryAlert.Wiki\docusaurus.config.ts,0,734,InventoryAlert.Wiki/docusaurus.config,1779814416.244776,1,price drop asnotracking data access schema change notification database update threshold efcore migration add-migration loss appdbcontext iproductrepository dbset igenericrepository efcore entity framework dbcontext,[MOD] InventoryAlert.Wiki/docusaurus.config +code,,69,7ece2c54faad1a5535b5cc2e3daa6539,src\ui\InventoryAlert.Wiki\docusaurus.config.ts,0,735,InventoryAlert.Wiki/docusaurus.config,1779814416.244776,69,price drop asnotracking data access schema change notification database update threshold efcore migration add-migration loss appdbcontext iproductrepository dbset igenericrepository efcore entity framework dbcontext,[FUNC] InventoryAlert.Wiki/docusaurus.config/default config; +code,,27533,151ed43a77c6bc52e44ca15291bfaf3e,src\ui\InventoryAlert.Wiki\package-lock.json,0,736,InventoryAlert.Wiki/package-lock.json,1779814416.2488022,1,unit test productservice price drop appdbcontext threshold business logic loss application service efcore entity framework periodictimer domain entity infrastructure finnhubpricesyncworker iproductservice notification fluentassertions arrange act assert backgroundservice application layer dockerfile dbcontext postgres postgresql asnotracking hosted service xunit domain driven design compose container,[MOD] InventoryAlert.Wiki/package-lock.json +code,,57,7baf891744ff81d115495d9396b9c39c,src\ui\InventoryAlert.Wiki\package.json,0,737,InventoryAlert.Wiki/package.json,1779814416.2488022,1,loss item price drop entity framework inventory threshold notification stock efcore dbcontext appdbcontext asnotracking sku,[MOD] InventoryAlert.Wiki/package.json +doc,"# Website + +This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator. + +## Installation + +```bash +yarn +``` + +## Local Development + +```bash +yarn start +``` + +This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. + +## Build + +```bash +yarn build +``` + +This command generates static content into the `build` directory and can be served using any static contents hosting service. + +## Deployment + +Using SSH: + +```bash +USE_SSH=true yarn deploy +``` + +Not using SSH: + +```bash +GIT_USER= yarn deploy +``` + +If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.",41,1536ac7e129e5d3f986a60aab57e7c98,src\ui\InventoryAlert.Wiki\README.md,0,738,"using, website, static, command, build, docusaurus, local, development",1779814416.2288346,1,asnotracking productservice business logic efcore appdbcontext application service entity framework iproductservice dbcontext,"# Website | Website This website is built using [Docusaurus](https://docusaurus.io/), a mode" +code,,32,a2325ff0c6556ddd958682361b20c609,src\ui\InventoryAlert.Wiki\sidebars.ts,0,739,InventoryAlert.Wiki/sidebars,1779814416.2488022,1,entity framework efcore asnotracking appdbcontext dbcontext,[MOD] InventoryAlert.Wiki/sidebars +code,,33,a2325ff0c6556ddd958682361b20c609,src\ui\InventoryAlert.Wiki\sidebars.ts,0,740,InventoryAlert.Wiki/sidebars,1779814416.2488022,33,entity framework efcore asnotracking appdbcontext dbcontext,[FUNC] InventoryAlert.Wiki/sidebars/default sidebars; +code,,12,c201517c02cefaf0cf6be4212ab6f672,src\ui\InventoryAlert.Wiki\tsconfig.json,0,741,InventoryAlert.Wiki/tsconfig.json,1779814416.2555375,1,,[MOD] InventoryAlert.Wiki/tsconfig.json doc,"--- slug: / sidebar_position: 1 ----",5,be095eca413ce8f675381b4a52e02d8a,InventoryAlert.Wiki\docs\index.md,0,613,slug,1776910223.993899,1,unitofwork market data threshold stock price price drop asnotracking external api hosted service business logic finnhubpricesyncworker productservice schema change compose item sku application service dbcontext fluentassertions efcore migration iproductservice quote postgres dockerfile savechanges backgroundservice notification loss xunit periodictimer postgresql rollback stock database update inventory arrange act assert add-migration appdbcontext atomicity efcore container entity framework unit test commit,index.md | --- slug: / sidebar_position: 1 --- +---",5,b3165b88a0c219bee8ac6ce99739c8cd,src\ui\InventoryAlert.Wiki\docs\index.md,0,742,slug,1779814416.244776,1,atomicity efcore rollback entity framework commit inventory notification item database update sku price drop compose efcore migration hosted service market data unitofwork savechanges finnhubpricesyncworker threshold unit test backgroundservice dockerfile asnotracking external api productservice fluentassertions periodictimer add-migration schema change dbcontext appdbcontext container postgresql postgres stock price business logic stock loss xunit iproductservice arrange act assert quote application service,index.md | --- slug: / sidebar_position: 1 --- doc,"# 🚀 InventoryAlert Documentation (v1) Welcome to the **InventoryAlert** System Wiki — the single source of truth for architecture, operational runbooks, and API contracts. -InventoryAlert is a real-time stock portfolio and alerting ecosystem built on **.NET 10** and **Next.js 15**. It tracks global stock prices via Finnhub, evaluates user-defined Alert Rules, and delivers in-app notifications when thresholds are crossed. +InventoryAlert is a real-time stock portfolio and alerting ecosystem built on **.NET 10** and **Next.js 15 (App Router)**. It tracks global stock prices via Finnhub, evaluates user-defined Alert Rules, and delivers in-app notifications when thresholds are crossed. > **v2 Note**: The system has been fully refactored from an inventory-management domain to a finance-domain vocabulary. `Product` → `StockListing`, `StockTransaction` → `Trade`, Telegram → In-App Notifications. @@ -19783,7 +21999,7 @@ How the system talks to the outside world and background workloads. - **[Internal API Reference](./05-api-services/internal-api.md)** — All v1 endpoints: Auth, Portfolio, Stocks, Market, Watchlist, AlertRules, Notifications, Events. - **[Event Handling](./05-api-services/event-handling.md)** — SQS topology, event type strings, deduplication pattern. - **[External Integrations](./05-api-services/external-integrations.md)** — Finnhub, SQS, DynamoDB, Redis integration details. -- **[Background Workers](./06-background-jobs/workers.md)** — All 10 Hangfire jobs with cron schedules and Finnhub endpoints. +- **[Background Workers](./06-background-jobs/workers.md)** — All 8 background jobs (7 recurring + 1 continuous) with cron schedules and Finnhub endpoints. - **[Hangfire Monitoring](./06-background-jobs/hangfire-monitoring.md)** — Dashboard guide, job catalog, failure impact. ### 🛠️ Developer Guide @@ -19792,7 +22008,9 @@ Everything you need to run, build, and maintain the platform. - **[Getting Started](./07-dev-maintenance/getting-started.md)** — Docker commands, seed credentials, service URLs. - **[.NET CLI Reference](./07-dev-maintenance/dotnet-commands.md)** — Migrations, test commands, publish guide. -- **[Testing & Standards](./07-dev-maintenance/testing-and-standards.md)** — xUnit patterns, C# 12 rules, E2E base setup. +- **[Testing & Standards](./07-dev-maintenance/testing-and-standards.md)** — C# 12 rules, primary constructors, and common patterns. +- **[Test Structure & App Quality](./07-dev-maintenance/test-strategy.md)** — Test project architecture, CI/CD gates, and runtime observability. +- **[Integration Testing Tiers](./07-dev-maintenance/integration-testing-tiers.md)** — Deep dive into White-box, Black-box, and Whole-Flow tests. - **[Operational Runbook](./07-dev-maintenance/operational-runbook.md)** — Troubleshooting guide, DB queries, common debug scenarios. - **[AI Agent Workflows](./07-dev-maintenance/ai-agent-workflows.md)** — Slash commands, transaction capture patterns, file placement rules. @@ -19803,7 +22021,7 @@ Everything you need to run, build, and maintain the platform. --- -> 💡 **Tip**: Use the sidebar search to instantly jump to specific API paths, entity names, or architecture diagrams.",65,be095eca413ce8f675381b4a52e02d8a,InventoryAlert.Wiki\docs\index.md,0,614,"architecture, rules, system, flows, data, execution, maintenance, finnhub",1776910223.993899,6,unitofwork market data threshold stock price price drop asnotracking external api hosted service business logic finnhubpricesyncworker productservice schema change compose item sku application service dbcontext fluentassertions efcore migration iproductservice quote postgres dockerfile savechanges backgroundservice notification loss xunit periodictimer postgresql rollback stock database update inventory arrange act assert add-migration appdbcontext atomicity efcore container entity framework unit test commit,# 🚀 InventoryAlert Documentation (v1) | 🚀 InventoryAlert Documentation (v1) Welcome to the InventoryAlert System Wiki — +> 💡 **Tip**: Use the sidebar search to instantly jump to specific API paths, entity names, or architecture diagrams.",67,b3165b88a0c219bee8ac6ce99739c8cd,src\ui\InventoryAlert.Wiki\docs\index.md,0,743,"architecture, maintenance, rules, system, flows, data, execution, background",1779814416.244776,6,atomicity efcore rollback entity framework commit inventory notification item database update sku price drop compose efcore migration hosted service market data unitofwork savechanges finnhubpricesyncworker threshold unit test backgroundservice dockerfile asnotracking external api productservice fluentassertions periodictimer add-migration schema change dbcontext appdbcontext container postgresql postgres stock price business logic stock loss xunit iproductservice arrange act assert quote application service,# 🚀 InventoryAlert Documentation (v1) | 🚀 InventoryAlert Documentation (v1) Welcome to the InventoryAlert System Wiki — doc,"# InventoryAlert — Introduction > A real-time stock portfolio and alert system built on .NET 10 + Next.js 15. @@ -19867,7 +22085,7 @@ Users who maintain a portfolio of stock positions need to know immediately when - [Architecture Overview →](../02-architecture-techstack/architecture-overview) - [Data Model →](../03-data-model/data-model) - [API Reference →](../05-api-services/internal-api) -- [Background Workers →](../06-background-jobs/workers)",64,080799dd7febb11f4110cb40180b4b10,InventoryAlert.Wiki\docs\00-overview\introduction.md,0,615,"user, market, stock, portfolio, global, finnhub, every, data",1776144911.24338,1,backgroundservice efcore entity framework business logic msft hosted service symbol unitofwork stock price stock ticker asnotracking notification atomicity price drop appdbcontext savechanges threshold rollback commit iproductservice productservice googl periodictimer application service external api dbcontext market data quote finnhubpricesyncworker loss aapl,# InventoryAlert — Introduction | InventoryAlert — Introduction > A real-time stock portfolio and alert system bui +- [Background Workers →](../06-background-jobs/workers)",64,dbe785d02c28d854c797b3723fb1191f,src\ui\InventoryAlert.Wiki\docs\00-overview\introduction.md,0,744,"user, market, stock, portfolio, global, finnhub, every, data",1779814416.2298334,1,notification atomicity msft asnotracking loss periodictimer googl finnhubpricesyncworker iproductservice aapl entity framework productservice market data savechanges appdbcontext rollback efcore backgroundservice quote unitofwork stock ticker business logic threshold application service symbol price drop commit stock price dbcontext external api hosted service,# InventoryAlert — Introduction | InventoryAlert — Introduction > A real-time stock portfolio and alert system bui doc,"# Architecture Overview ## System Context @@ -19946,7 +22164,7 @@ To improve maintainability and reduce project-reference overhead, the solution u | `inventory-cache` | redis:7.2-alpine | `6379` | Redis | | `inventory-seq` | datalust/seq | `5341` | Structured log viewer | | `inventory-moto` | motoserver/moto | `5000` | DynamoDB + SQS emulator | -| `inventory-ui` | Custom Next.js | `3000` | Frontend |",79,22f7beccce923739906018f2a5dac28c,InventoryAlert.Wiki\docs\02-architecture-techstack\architecture-overview.md,0,616,"inventory, layer, redis, services, structured, moto, docker, system",1776144961.2239573,1,application service compose iproductservice market data backgroundservice stock price productscontroller dockerfile data access returns async iproductrepository loss container threshold postgres igenericrepository dbset efcore quote periodictimer business logic asnotracking notification httpget httpput entity framework moq price drop hosted service iactionresult times once finnhubpricesyncworker external api verify mock setup appdbcontext productservice dbcontext postgresql httppost,# Architecture Overview | Architecture Overview System Context InventoryAlert is a real-time stock alerti +| `inventory-ui` | Custom Next.js | `3000` | Frontend |",79,92eaa657623c7dd030ecceee59877bab,src\ui\InventoryAlert.Wiki\docs\02-architecture-techstack\architecture-overview.md,0,745,"inventory, layer, redis, services, structured, moto, docker, system",1779814416.2308342,1,dbcontext container external api stock price backgroundservice hosted service finnhubpricesyncworker price drop iactionresult dockerfile moq quote returns async application service productscontroller asnotracking httpput igenericrepository data access market data loss times once httpget productservice mock setup postgresql postgres iproductservice verify compose iproductrepository business logic efcore appdbcontext dbset notification periodictimer threshold entity framework httppost,# Architecture Overview | Architecture Overview System Context InventoryAlert is a real-time stock alerti doc,"# Domain, Structure & DDD ## Lean Vertical Slice Architecture @@ -19955,16 +22173,16 @@ InventoryAlert uses a **Lean Vertical Slice** approach. Business logic is co-loc ## Project Structure -| Project | Responsibility | Key Namespaces | -|---|---|---| -| **InventoryAlert.Domain** | Pure entities, repository interfaces, DTOs, events, enums, and validators. Zero external dependencies. | `Domain.Entities`, `Domain.Interfaces`, `Domain.DTOs`, `Domain.Events`, `Domain.Validators` | -| **InventoryAlert.Infrastructure** | EF Core (PostgreSQL), DynamoDB, FinnhubClient, SQS queue, Redis, and UnitOfWork. | `Infrastructure.Persistence`, `Infrastructure.External`, `Infrastructure.Messaging` | -| **InventoryAlert.Api** | Thin REST controllers, service layer, FluentValidation, middleware, JWT auth, DI root. | `Api.Controllers`, `Api.Services`, `Api.Configuration`, `Api.Middleware` | -| **InventoryAlert.Worker** | Hangfire jobs, SQS listener, SQS event handlers. | `Worker.ScheduledJobs`, `Worker.IntegrationEvents` | -| **InventoryAlert.UnitTests** | xUnit + Moq + FluentAssertions. Covers all services, repositories. | - | -| **InventoryAlert.IntegrationTests** | EF Core InMemory repository tests. | - | -| **InventoryAlert.E2ETests** | Full HTTP roundtrip via RestSharp against running Docker stack. | - | -| **InventoryAlert.ArchitectureTests** | NetArchTest: Domain must have zero imports from Infrastructure/Api/Worker. | - | +| Project | Responsibility | Key Namespaces | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | +| **InventoryAlert.Domain** | Pure entities, repository interfaces, DTOs, events, enums, and validators. Zero external dependencies. | `Domain.Entities`, `Domain.Interfaces`, `Domain.DTOs`, `Domain.Events`, `Domain.Validators` | +| **InventoryAlert.Infrastructure** | EF Core (PostgreSQL), DynamoDB, FinnhubClient, SQS queue, Redis, and UnitOfWork. | `Infrastructure.Persistence`, `Infrastructure.External`, `Infrastructure.Messaging` | +| **InventoryAlert.Api** | Thin REST controllers, service layer, FluentValidation, middleware, JWT auth, DI root. | `Api.Controllers`, `Api.Services`, `Api.Configuration`, `Api.Middleware` | +| **InventoryAlert.Worker** | Hangfire jobs, SQS listener, SQS event handlers. | `Worker.ScheduledJobs`, `Worker.IntegrationEvents` | +| **InventoryAlert.UnitTests** | xUnit + Moq + FluentAssertions. Covers all services, repositories. | - | +| **InventoryAlert.IntegrationTests** | EF Core InMemory repository tests. | - | +| **InventoryAlert.E2ETests** | Full HTTP roundtrip via RestSharp against running Docker stack. | - | +| **InventoryAlert.ArchitectureTests** | NetArchTest: Domain must have zero imports from Infrastructure/Api/Worker. | - | ### Dependency Direction @@ -20103,17 +22321,14 @@ InventoryManagementSystem/ │ │ ├── SyncEarningsJob.cs │ │ ├── SyncRecommendationsJob.cs │ │ ├── SyncInsidersJob.cs -│ │ ├── CompanyNewsJob.cs -│ │ ├── MarketNewsJob.cs +│ │ ├── NewsSyncJob.cs │ │ ├── CleanupPriceHistoryJob.cs │ │ ├── ProcessQueueJob.cs -│ │ └── SqsScheduledPollerJob.cs │ └── IntegrationEvents/ │ ├── Routing/IntegrationMessageRouter.cs │ └── Handlers/ -│ ├── PriceAlertHandler.cs +│ ├── MarketPriceAlertHandler.cs │ ├── LowHoldingsHandler.cs -│ ├── CompanyNewsHandler.cs │ └── DefaultHandler.cs │ ├── InventoryAlert.UnitTests/ @@ -20126,21 +22341,21 @@ InventoryManagementSystem/ ## Placement Decision Reference -| Type | Belongs In | -|---|---| -| Entity class | `Domain/Entities/` | -| Repository interface | `Domain/Interfaces/` | -| Service interface (shared) | `Domain/Interfaces/` | -| Request/Response DTO | `Domain/DTOs/` | -| FluentValidation validator | `Domain/Validators/` | -| SQS event payload | `Domain/Events/Payloads/` | -| EF Core configuration | `Infrastructure/Persistence/Configurations/` | -| Repository implementation | `Infrastructure/Persistence/Repositories/` | -| Caching / Messaging impl | `Infrastructure/Caching/` or `Infrastructure/Messaging/` | -| Controller | `Api/Controllers/` | -| API-level service | `Api/Services/` | -| Scheduled job | `Worker/ScheduledJobs/` | -| SQS event handler | `Worker/IntegrationEvents/Handlers/` |",194,3c0f7f42fb214fe43ce5ce51ce9138d6,InventoryAlert.Wiki\docs\02-architecture-techstack\domain-and-structure.md,0,617,"domain, inventoryalert, infrastructure, worker, repository, interfaces, structure, layer",1776145195.6124675,1,asnotracking quote add-migration finnhubpricesyncworker threshold appdbcontext stock price productservice data access iproductservice stock ticker schema change container periodictimer aapl httppost iactionresult postgresql executetransactionasync efcore migration item unitofwork dockerfile rollback application layer httpput domain entity inventory savechanges compose igenericrepository hosted service productscontroller stock googl xunit dbcontext msft loss atomicity fluentassertions sku savechangesasync entity framework domain driven design symbol unit test market data external api arrange act assert efcore backgroundservice price drop iproductrepository postgres commit notification dbset iunitofwork business logic infrastructure application service database update httpget,"# Domain, Structure & DDD | Domain, Structure & DDD Lean Vertical Slice Architecture InventoryAlert uses a " +| Type | Belongs In | +| -------------------------- | -------------------------------------------------------- | +| Entity class | `Domain/Entities/` | +| Repository interface | `Domain/Interfaces/` | +| Service interface (shared) | `Domain/Interfaces/` | +| Request/Response DTO | `Domain/DTOs/` | +| FluentValidation validator | `Domain/Validators/` | +| SQS event payload | `Domain/Events/Payloads/` | +| EF Core configuration | `Infrastructure/Persistence/Configurations/` | +| Repository implementation | `Infrastructure/Persistence/Repositories/` | +| Caching / Messaging impl | `Infrastructure/Caching/` or `Infrastructure/Messaging/` | +| Controller | `Api/Controllers/` | +| API-level service | `Api/Services/` | +| Scheduled job | `Worker/ScheduledJobs/` | +| SQS event handler | `Worker/IntegrationEvents/Handlers/` |",191,2722ac828bf1445971463fe39d6144e9,src\ui\InventoryAlert.Wiki\docs\02-architecture-techstack\domain-and-structure.md,0,746,"domain, inventoryalert, infrastructure, worker, repository, interfaces, structure, layer",1779851803.7211235,1,postgresql stock rollback finnhubpricesyncworker googl business logic domain driven design postgres productscontroller iproductservice item entity framework loss executetransactionasync asnotracking fluentassertions iproductrepository stock ticker market data application service iunitofwork domain entity application layer httpget dbcontext compose iactionresult atomicity xunit productservice add-migration commit sku database update infrastructure container efcore httpput efcore migration notification savechanges msft data access symbol hosted service dockerfile external api price drop unitofwork unit test appdbcontext httppost periodictimer aapl threshold arrange act assert quote igenericrepository dbset backgroundservice schema change inventory stock price savechangesasync,"# Domain, Structure & DDD | Domain, Structure & DDD Lean Vertical Slice Architecture InventoryAlert uses a " doc,"# Microservice Component Interactions > How the individual project components communicate at runtime. @@ -20189,24 +22404,20 @@ sequenceDiagram participant Cache as Redis participant Finnhub as Finnhub API participant DB as PostgreSQL - participant SQS as Amazon SQS + participant Redis as Redis Backplane - HF->>Job: Trigger (every 15 minutes) + HF->>Job: Trigger (cron from WorkerSettings.Schedules.SyncPrices) Job->>DB: SELECT DISTINCT TickerSymbols FROM StockListing loop For each symbol - Job->>Cache: GET quote:{symbol} - alt Cache MISS - Job->>Finnhub: GET /quote?symbol={symbol} - Job->>Cache: SET quote:{symbol} TTL=30s - end + Job->>Finnhub: GET /quote?symbol={symbol} Job->>DB: INSERT PriceHistory Job->>DB: SELECT active AlertRules WHERE TickerSymbol loop For each AlertRule alt Condition breached AND cooldown not active Job->>DB: INSERT Notification - Job->>Cache: SET cooldown:alert:{symbol} TTL=24h - Job->>SQS: Publish inventoryalert.pricing.price-drop.v1 + Job->>Cache: SET inventoryalert:alerts:cooldown:v1:{userId}:{ruleId} TTL=24h + Job->>Redis: SignalR push (IAlertNotifier) end end end @@ -20219,13 +22430,12 @@ sequenceDiagram ```mermaid flowchart LR - API[""InventoryAlert.Api""] -->|Publish| SQS[""SQS: inventory-events""] - HF[""Hangfire Scheduler""] -->|Trigger| Worker[""InventoryAlert.Worker""] - Worker -->|Publish| SQS + API[""InventoryAlert.Api""] -->|Publish| SNS[""SNS Topic""] + SNS -->|Fan-out| SQS[""SQS: inventory-events""] SQS -->|Consume| Router[""IntegrationMessageRouter""] - Router -->|price-drop.v1| PriceHandler[""PriceAlertHandler""] + Router -->|price-drop.v1| PriceHandler[""MarketPriceAlertHandler""] Router -->|stock-low.v1| HoldingsHandler[""LowHoldingsHandler""] - Router -->|news.headline.v1| NewsHandler[""CompanyNewsHandler""] + Router -->|news.sync-requested.v1| NewsHandler[""Enqueue NewsSyncJob""] Router -->|Unknown| DefaultHandler[""DefaultHandler: Log + ACK""] PriceHandler --> DB[(""PostgreSQL"")] NewsHandler --> DDB[(""DynamoDB"")] @@ -20242,111 +22452,51 @@ The `InventoryAlert.Worker` runs as a **separate Docker container**. It communic 3. **SQS** — consumes events published by the API, publishes events for handlers. 4. **SignalR Backplane (Redis)** — pushes real-time notifications from Worker to API-connected clients. -There are **no direct HTTP calls** between the API and Worker containers.",102,c7b5900eba97a13dc77df2ad2bc4d26b,InventoryAlert.Wiki\docs\02-architecture-techstack\microservice-components.md,0,618,"worker, flow, inventoryalert, shared, reads, writes, redis, keys",1777190302.4257703,1,external api postgresql googl commit iproductservice atomicity rollback dockerfile backgroundservice efcore symbol application service business logic compose unitofwork entity framework loss asnotracking container finnhubpricesyncworker postgres appdbcontext periodictimer hosted service price drop quote productservice aapl savechanges threshold msft dbcontext market data stock price stock ticker notification,# Microservice Component Interactions | Microservice Component Interactions > How the individual project components comm +There are **no direct HTTP calls** between the API and Worker containers.",97,56482dc849d799c847a0b43d3ed0a205,src\ui\InventoryAlert.Wiki\docs\02-architecture-techstack\microservice-components.md,0,747,"worker, flow, inventoryalert, shared, reads, writes, redis, keys",1779814416.2313404,1,external api market data unitofwork googl price drop commit appdbcontext stock price application service stock ticker container dockerfile asnotracking periodictimer postgres postgresql hosted service compose productservice business logic finnhubpricesyncworker backgroundservice symbol savechanges iproductservice atomicity rollback entity framework notification quote msft threshold loss efcore aapl dbcontext,# Microservice Component Interactions | Microservice Component Interactions > How the individual project components comm doc,"# Caching Strategy -> How InventoryAlert uses Redis to reduce external API calls, prevent duplicate processing, and enforce per-symbol cooldowns. - -## Cache Layers - -| Layer | Technology | Scope | -|---|---|---| -| **Quote Cache** | Redis (`StringGetAsync` / `StringSetAsync`) | Shared across all API and Worker instances | -| **Dedup Cache** | Redis (`StringSetAsync` NX) | SQS message deduplication | -| **Alert Cooldown** | Redis (`KeyExistsAsync`) | Per-symbol, 24h cooldown window | -| **Rate Limit Guard** | Redis (sliding window counter) | Finnhub call cap (55 rpm) | - ---- - -## What Is Cached and Why - -### 1. Stock Price Quotes (Redis, 30s TTL) +Last updated: **2026-05-01** -**Key**: `quote:{symbol}` +> How InventoryAlert uses Redis to reduce external API calls, provide idempotency for SQS processing, and enforce alert cooldowns. -**Why**: Finnhub enforces strict rate limits (~60 req/min on free tier). When `SyncPricesJob` processes 50+ tickers, without caching each ticker would hit Finnhub on every run. With the 30-second cache, rapid successive requests (e.g., from UI + Worker simultaneously) serve from Redis. +## Cache use-cases -```csharp -// StockDataService.cs -var cacheKey = $""quote:{symbol}""; -var cached = await _cache.StringGetAsync(cacheKey); -if (cached.HasValue) - return JsonSerializer.Deserialize((string)cached!, _json); - -var q = await _finnhub.GetQuoteAsync(symbol, ct); -await _cache.StringSetAsync(cacheKey, JsonSerializer.Serialize(res, _json), TimeSpan.FromSeconds(30)); -``` - -### 2. SQS Message Deduplication (Redis, 30min TTL) - -**Key**: `dedup:sqs:{messageId}` - -**Why**: `ProcessQueueJob` uses Redis atomic `SET NX` to guarantee each SQS message is processed exactly once, even if SQS delivers it multiple times (at-least-once delivery guarantee). - -```csharp -// ProcessQueueJob.cs -var dedupKey = $""dedup:sqs:{envelope.MessageId}""; -if (!await _redisDb.StringSetAsync(dedupKey, ""1"", TimeSpan.FromMinutes(30), When.NotExists)) - return; // Already processed — skip -``` - -### 3. Alert Cooldown (Redis, 24h TTL) - -**Key**: `cooldown:alert:{symbol}` - -**Why**: Prevents the same symbol's price breach from flooding users with repeated notifications within a short window. `PriceAlertHandler` checks this key before writing a `Notification` row. - -```csharp -// PriceAlertHandler.cs -var alertKey = $""cooldown:alert:{payload.Symbol}""; -if (await _redisDb.KeyExistsAsync(alertKey)) - return; // Suppressed within 24h window - -await _redisDb.StringSetAsync(alertKey, ""1"", TimeSpan.FromHours(24)); -``` - -### 4. Finnhub Rate Limit Guard (Redis, rolling 60s window) - -**Key**: `finnhub:ratelimit` - -**Why**: Free-tier Finnhub allows 60 requests/minute. The guard cap is set at **55 rpm** to leave a buffer. Any worker that exceeds this count skips the Finnhub call and uses local data instead. +| Use-case | Where | Key pattern | TTL | Notes | +|---|---|---|---|---| +| Quote cache | API (`StockDataService`) | `quote:{symbol}` | 30s | Reduces Finnhub calls for hot symbols | +| Metrics cache | API (`StockDataService`) | `metrics:{symbol}` | 1h | Caches DB-sourced metrics response | +| Symbol search cache | API (`StockDataService`) | `search:{query}` | 4h | Caches Finnhub search results | +| SQS idempotency | Worker (`ProcessQueueJob`) | `msg:processed:{messageId}` | 24h | Written only after successful processing | +| Alert cooldown | Infra (`AlertRuleEvaluator`) | `inventoryalert:alerts:cooldown:v1:{userId}:{ruleId}` | 24h | Suppresses repeated notifications for the same rule | ---- - -## Cache Key Reference - -| Key Pattern | TTL | Purpose | -|---|---|---| -| `quote:{symbol}` | **30 seconds** | Cached stock quote from Finnhub | -| `dedup:sqs:{messageId}` | 30 minutes | SQS message idempotency guard | -| `cooldown:alert:{symbol}` | 24 hours | Suppress repeated price alerts | -| `finnhub:ratelimit` | Rolling 60s | Sliding window counter — cap at 55 rpm | -| `search:{query}` | 4 hours | Search result cache | -| `peers:{symbol}` | 24 hours | Cached peer list | -| `metrics:{symbol}` | 1 hour | Cached basic financials | +## Notes and caveats ---- +- The Worker currently relies on **bounded concurrency** (`WorkerSettings.MaxDegreeOfParallelism`) rather than a strict rate limiter for Finnhub. +- Cooldown is **per-user + per-rule**, not per-symbol. +- Some namespaces exist in `CacheKeys` (`InventoryAlert.Domain.Constants.CacheKeys`) but are not yet consistently used by all services (API quote/metrics/search still use simple keys).",22,aaddc15a5de528a0f2a7e7947d586905,src\ui\InventoryAlert.Wiki\docs\03-data-model\caching-strategy.md,0,748,"cache, symbol, metrics, search, inventoryalert, quote, stockdataservice, finnhub",1779814416.2318559,1,iproductservice threshold productservice notification periodictimer application service quote stock price backgroundservice price drop loss external api market data hosted service business logic finnhubpricesyncworker,# Caching Strategy | Caching Strategy Last updated: 2026-05-01 > How InventoryAlert uses Redis to red +doc,"# Data Model -## Why Not Cache in Memory? +Last updated: **2026-05-01** -The API and Worker run as **separate Docker containers**. In-process `IMemoryCache` is not shared between processes. Redis ensures a consistent cache that all containers in the stack see simultaneously.",87,1d1d83ca9addd5800cdeb91069bbe5ab,InventoryAlert.Wiki\docs\03-data-model\caching-strategy.md,0,619,"redis, symbol, finnhub, cache, cooldown, window, quote, worker",1776145010.722802,1,market data application service external api notification finnhubpricesyncworker postgres entity framework efcore dbcontext price drop quote backgroundservice dockerfile aapl periodictimer productservice iproductservice threshold asnotracking business logic msft stock price symbol hosted service stock ticker compose postgresql appdbcontext googl container loss,"# Caching Strategy | Caching Strategy > How InventoryAlert uses Redis to reduce external API calls, p" -doc,"# Data Model +This page documents the current persisted data model used by InventoryAlert. It reflects the EF Core Postgres entities + the DynamoDB news read-models in the repository as of the date above. -## Entity Relationship Diagram +## Entity Relationship Diagram (conceptual) ```mermaid erDiagram User ||--o{ WatchlistItem : watches User ||--o{ AlertRule : configures User ||--o{ Trade : executes + User ||--o{ Notification : receives - StockListing ||--o{ PriceHistory : records + StockListing ||--o{ PriceHistory : ""symbol-indexed (no enforced FK)"" StockListing ||--o{ WatchlistItem : ""tracked via Symbol"" StockListing ||--o{ Trade : ""referenced via Symbol"" StockListing ||--o| StockMetric : ""has cached metrics"" StockListing ||--o{ EarningsSurprise : has StockListing ||--o{ RecommendationTrend : has StockListing ||--o{ InsiderTransaction : has + AlertRule ||--o{ Notification : ""optional link"" User { Guid Id PK @@ -20398,7 +22548,7 @@ erDiagram } PriceHistory { long Id PK - string TickerSymbol FK + string TickerSymbol decimal Price decimal High decimal Low @@ -20451,8 +22601,8 @@ erDiagram Notification { Guid Id PK Guid UserId FK - Guid AlertRuleId FK - string TickerSymbol FK + Guid AlertRuleId + string TickerSymbol string Message NotificationType Type NotificationSeverity Severity @@ -20461,6 +22611,19 @@ erDiagram } ``` +### Nullability notes (implementation detail) + +The ER diagram above is conceptual; the actual EF Core model contains nullable fields (C# `?`) in several places: + +- `StockListing`: `Exchange`, `Currency`, `Country`, `Industry`, `MarketCap`, `Ipo`, `WebUrl`, `Logo`, `LastProfileSync` +- `PriceHistory`: `High`, `Low`, `Open`, `PrevClose` +- `StockMetric`: most metric columns are nullable (e.g., `PeRatio`, `DividendYield`, `Week52High`, …) +- `EarningsSurprise`: `ActualEps`, `EstimateEps`, `SurprisePercent`, `ReportDate` +- `InsiderTransaction`: `Name`, `Share`, `Value`, `TransactionDate`, `FilingDate`, `TransactionCode` +- `Trade`: `Notes` +- `AlertRule`: `LastTriggeredAt` +- `Notification`: `AlertRuleId`, `TickerSymbol` (both nullable for system notifications) + --- ## High-Performance Normalized Model @@ -20493,14 +22656,38 @@ Stored per-user. Fully isolated. | `WatchlistItem` | Minimal join table linking a User to a TickerSymbol. | | `Notification` | System and alert messages securely scoped to the user, synced with a UI bell-badge feed. | -### 3. Historical Archives (Amazon DynamoDB — `CompanyNews`, `MarketNews`) +#### Postgres tables (EF Core / migrations) + +If you are comparing against the running database, use these as the source of truth for the current schema: + +- `Users` (PK: `Id`, unique: `Username`) +- `watchlist_items` (composite PK: `(UserId, TickerSymbol)`) +- `alert_rules` (PK: `Id`, index: `(TickerSymbol, IsActive)`) +- `trades` (PK: `Id`, index: `(UserId, TickerSymbol, TradedAt)`) +- `notifications` (PK: `Id`, index: `(UserId, IsRead, CreatedAt)`, FK `AlertRuleId` is nullable) + +**Trade table shape (current migration)** + +- Columns: `Id`, `UserId`, `TickerSymbol`, `Type`, `Quantity`, `UnitPrice`, `TradedAt`, `Notes` (nullable) +- FKs: + - `UserId` → `Users.Id` (`CASCADE`) + - `TickerSymbol` → `stock_listings.TickerSymbol` (`RESTRICT`) + +If your database “doesn’t have” the `trades` table (or is missing columns), it usually means migrations were not applied to that environment. In this repo, the `trades` table is created by the migration `20260414042036_RefactorToFinanceV2`. + +### 3. Historical Archives (Amazon DynamoDB — News Read Models) Used for high-volume, unstructured market data that is never deleted. -| Table | PK | SK | Responsibility | +| DynamoDB Table | PK (Hash) | SK (Range) | Responsibility | |---|---|---|---| -| `MarketNews` | `CATEGORY#` | `TS#` | General financial events covering forex/crypto/markets | -| `CompanyNews` | `SYMBOL#` | `TS#` | Ticker-specific press releases and articles | +| `inventoryalert-market-news` | `PK=""CATEGORY#""` | `SK=""TS#""` | General financial news feed by category | +| `inventoryalert-company-news` | `PK=""SYMBOL#""` | `SK=""TS#""` | Ticker-specific articles and press releases | + +Notes: + +- The persisted key attribute names are `PK` and `SK` (not `Category`/`Symbol`). +- `Symbol`/`Category` fields are kept as denormalized attributes for querying/display. --- @@ -20542,20 +22729,24 @@ public enum NotificationSeverity ## Alert Evaluation Logic (Fan-Out) -InventoryAlert **v3** uses a high-performance **Hybrid Pipeline**: +Alert evaluation is driven by: + +- **Scheduled price sync**: `SyncPricesJob` (Hangfire recurring job) fetches quotes, writes `PriceHistory`, evaluates active rules, persists `Notification`, then pushes via SignalR. +- **Event-driven handlers**: e.g. `MarketPriceAlertHandler` evaluates rules for a specific symbol/price payload; `LowHoldingsHandler` persists and pushes a holdings alert. + +The shared evaluator (`IAlertRuleEvaluator`) provides the rule logic plus Redis deduplication/cooldown. ```mermaid flowchart TD - A[""Trigger: Scheduled (15m) or Event (Trade/Price)""] --> B[""Identify Ticker and User Context""] - B --> C[""Load Active Rules from PostgreSQL""] - C --> D[""Evaluate via Shared IAlertRuleEvaluator""] - D --> E{Breach Identified?} - E -- Yes --> F{Redis Cooldown active?} - F -- No --> G[""1. Insert Notification (w/ Type & Severity)""] - G --> H[""2. SET Redis Cooldown (Rule-specific)""] - G --> I[""3. SignalR Push (Instant UI Sync)""] - H & I --> J{TriggerOnce?} - J -- Yes --> K[""Disable AlertRule""] + A[""Trigger: SyncPricesJob or integration event""] --> B[""Load active rules (Postgres)""] + B --> C[""Evaluate via IAlertRuleEvaluator""] + C --> D{Breached?} + D -- No --> Z[""Stop""] + D -- Yes --> E[""Persist Notification (Postgres)""] + E --> F[""Set Redis cooldown key (24h)""] + E --> G[""SignalR push via IAlertNotifier (Redis backplane)""] + F & G --> H{TriggerOnce?} + H -- Yes --> I[""Deactivate AlertRule""] ``` ### Business Rules @@ -20563,17 +22754,17 @@ flowchart TD | Rule | Detail | |---|---| | **TriggerOnce** | If `Rule.TriggerOnce` is true, the rule is automatically disabled (`IsActive = false`) after firing. | -| **Deduplication** | Managed via Redis keys: `alert:cooldown:{userId}:{ruleId}` to prevent notification spam. | -| **Real-time Delivery** | Every notification is pushed via **SignalR** using the **Redis Backplane**. | -| **Cascade Behavior** | Deleting a position deletes owned trades and alerts. **Does not** delete the global `StockListing`. | -| **Notification Feed** | Instead of just sending alerts, breaches generate `Notification` rows to populate the web UI hub. |",237,f182879e30d8abd134ac46ec24e0bead,InventoryAlert.Wiki\docs\03-data-model\data-model.md,0,620,"data, user, notification, market, model, entity, high, global",1777190302.4287517,1,dbcontext threshold notification asnotracking savechanges rollback stock price aapl msft unitofwork commit entity framework price drop googl symbol atomicity loss external api appdbcontext stock ticker quote market data efcore,# Data Model | Data Model Entity Relationship Diagram mermaid erDiagram User ||--o{ Watchl +| **Deduplication** | Managed via Redis cooldown keys (example: `inventoryalert:alerts:cooldown:v1:{userId}:{ruleId}`) to prevent notification spam. | +| **Real-time Delivery** | Notifications are pushed via **SignalR**. Worker and API communicate via Redis backplane (channel prefix `InventoryAlert_SignalR`). | +| **Position Removal** | Removing a position deletes the user's watchlist item + trades; it is blocked if there are active alert rules for the symbol. Global `StockListing` is never deleted by user actions. | +| **Notification Feed** | Instead of just sending alerts, breaches generate `Notification` rows to populate the web UI hub. |",284,81dde60f54cf3f7146fdf3b7eca0c73d,src\ui\InventoryAlert.Wiki\docs\03-data-model\data-model.md,0,749,"tickersymbol, user, data, notification, symbol, userid, model, inventoryalert",1779814416.2318559,1,asnotracking entity framework notification external api symbol rollback hosted service unitofwork efcore efcore migration commit periodictimer iproductrepository aapl market data atomicity appdbcontext quote add-migration dbset msft data access igenericrepository savechanges stock price stock ticker loss dbcontext backgroundservice schema change googl database update threshold finnhubpricesyncworker price drop,# Data Model | Data Model Last updated: 2026-05-01 This page documents the current persisted da doc,"# Alert Dispatch Flow > How the system evaluates alert rules and delivers real-time in-app notifications. ## Overview -Alert dispatch in InventoryAlert **v3** uses a **hybrid evaluation pipeline** combining scheduled and event-driven triggers. Both paths utilize a shared `IAlertRuleEvaluator` to ensure consistent business logic. Delivery is now handled via **SignalR** with a **Redis Backplane** for instant UI reactivity. +Alert dispatch uses a **hybrid evaluation pipeline** combining scheduled and event-driven triggers. Both paths use a shared `IAlertRuleEvaluator` for consistent business logic, and delivery is handled via **SignalR** with a **Redis backplane** for instant UI reactivity. --- @@ -20581,9 +22772,9 @@ Alert dispatch in InventoryAlert **v3** uses a **hybrid evaluation pipeline** co The system ensures alert rules are checked whenever relevant data changes. -1. **Scheduled Path (`SyncPricesJob`)**: Runs every 15 minutes. Performs a global scan of all active stock listings and evaluates all associated rules. -2. **Event Path (`MarketPriceAlertHandler`)**: Triggered immediately by price update events from SQS. -3. **Holdings Path (`LowHoldingsHandler`)**: Triggered immediately when a trade is recorded. +1. **Scheduled Path (`SyncPricesJob`)**: Runs on a cron schedule (config: `WorkerSettings.Schedules.SyncPrices`). Scans symbols, fetches quotes, evaluates rules, persists notifications, and pushes via SignalR. +2. **Event Path (`MarketPriceAlertHandler`)**: Triggered by SQS events (EventType: `inventoryalert.pricing.price-drop.v1`) for a specific symbol + price. +3. **Holdings Path (`LowHoldingsHandler`)**: Triggered by SQS events (EventType: `inventoryalert.inventory.stock-low.v1`) when a user’s holdings drop below a threshold. ### Shared Evaluator Logic (`IAlertRuleEvaluator`) @@ -20598,9 +22789,9 @@ flowchart TD H & I & J --> K{Breached?} K -- Yes --> L{Redis Cooldown active?} - L -- Yes --> M[Skip — alert:cooldown:{userId}:{ruleId} exists] + L -- Yes --> M[Skip — inventoryalert:alerts:cooldown:v1:{userId}:{ruleId} exists] L -- No --> N[1. INSERT Notification row] - N --> O[2. SET alert:cooldown:{userId}:{ruleId} TTL=1h+] + N --> O[2. SET inventoryalert:alerts:cooldown:v1:{userId}:{ruleId} TTL=24h] O --> P[3. Push via SignalR HubContext] P --> Q{TriggerOnce?} Q -- Yes --> R[UPDATE AlertRule SET IsActive = false] @@ -20611,7 +22802,7 @@ flowchart TD ## Real-Time Delivery (SignalR) -InventoryAlert v3 replaces legacy polling with an instant push architecture: +SignalR provides an instant push architecture: 1. **Hub Host**: `InventoryAlert.Api` hosts the `NotificationHub` at `/hubs/notifications`. 2. **The Signal**: When the Worker (producer) identifies a breach, it calls `NotifyAsync` on the `IAlertNotifier`. @@ -20621,6 +22812,15 @@ InventoryAlert v3 replaces legacy polling with 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: @@ -20636,12 +22836,9 @@ Notifications are now categorized for better UX: ## Deduplication & Cooldown To prevent ""Alert Storms,"" the system enforces a cooldown gate: -- **Key Pattern**: `alert:cooldown:{userId}:{ruleId}` -- **Standard TTL**: - - Price Alerts: 1 Hour - - Holdings Alerts: 6 Hours - - News Alerts: 24 Hours -- **Global SQS Dedup**: `dedup:sqs:{messageId}` (30 min TTL) prevents duplicate processing of the same message across worker nodes.",75,6ed3c56d1fb2b37202f6be42f8e1cc7f,InventoryAlert.Wiki\docs\04-execution-flows\alert-dispatch.md,0,621,"alert, system, rules, real, time, notifications, inventoryalert, event",1777190302.430713,1,notification price drop loss periodictimer backgroundservice threshold finnhubpricesyncworker hosted service,# Alert Dispatch Flow | Alert Dispatch Flow > How the system evaluates alert rules and delivers real-tim +- **Key Pattern**: `inventoryalert:alerts:cooldown:v1:{userId}:{ruleId}` +- **Standard TTL**: 24 hours (set by the shared `IAlertRuleEvaluator`) +- **SQS message idempotency**: `msg:processed:{messageId}` (24h TTL) prevents processing the same SQS message multiple times in the native polling worker.",81,9bdbde68d2e19f7b2d41c345796968cc,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\alert-dispatch.md,0,750,"alert, signalr, system, notifications, inventoryalert, worker, message, rules",1779814416.2328637,1,arrange act assert unit test xunit periodictimer finnhubpricesyncworker backgroundservice fluentassertions notification loss threshold hosted service price drop,# Alert Dispatch Flow | Alert Dispatch Flow > How the system evaluates alert rules and delivers real-tim doc,"# Alert Rule Creation (Symbol Auto-Resolve) Alert rules no longer require a “pre-discovered” symbol in the local catalog. When a user creates an alert rule, the API will: @@ -20660,7 +22857,7 @@ This removes the previous coupling where users had to visit a symbol page (or ot ## Notes - The stored `TickerSymbol` is normalized to uppercase. -- If the symbol cannot be resolved, the request fails (see API error response).",20,46e89b7851b5904d87d7130230791a39,InventoryAlert.Wiki\docs\04-execution-flows\alert-rule-creation.md,0,622,"symbol, alert, rule, creation, resolve, local, catalog, uppercase",1776910223.9878542,1,msft threshold symbol application service entity framework stock ticker efcore aapl productservice dbcontext appdbcontext iproductservice loss business logic googl price drop asnotracking notification,# Alert Rule Creation (Symbol Auto-Resolve) | Alert Rule Creation (Symbol Auto-Resolve) Alert rules no longer require a “pre-d +- If the symbol cannot be resolved, the request fails (see API error response).",20,46e89b7851b5904d87d7130230791a39,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\alert-rule-creation.md,0,751,"symbol, alert, rule, creation, resolve, local, catalog, uppercase",1779814416.2328637,1,msft threshold application service entity framework asnotracking googl stock ticker notification iproductservice efcore productservice dbcontext appdbcontext price drop business logic aapl loss symbol,# Alert Rule Creation (Symbol Auto-Resolve) | Alert Rule Creation (Symbol Auto-Resolve) Alert rules no longer require a “pre-d doc,"# Business Logic & Rules (v1) This document outlines the core domain logic governing the InventoryAlert.Api system. @@ -20671,7 +22868,7 @@ This document outlines the core domain logic governing the InventoryAlert.Api sy ### 1.1 Price Alerts -Evaluated during the **price sync loop** inside `SyncPricesJob` (every 15 min). Loads all active `AlertRule` rows for each ticker, compares against the latest quote. +Evaluated during the **price sync loop** inside `SyncPricesJob` (cron-configured via `WorkerSettings.Schedules.SyncPrices`). Loads active `AlertRule` rows for each ticker and compares against the latest quote. | Condition | Evaluation | |---|---| @@ -20683,7 +22880,7 @@ On breach: - An unread `Notification` row is written for the owning user. - `rule.LastTriggeredAt` is updated. - If `rule.TriggerOnce = true`, the rule is deactivated (`IsActive = false`). -- Redis cooldown key `cooldown:alert:{symbol}` is set (24h TTL) to prevent alert storms. +- A Redis cooldown key `inventoryalert:alerts:cooldown:v1:{userId}:{ruleId}` is set (24h TTL) to prevent alert storms. ### 1.2 Portfolio Cost-Basis Alerts (`PercentDropFromCost`) @@ -20696,7 +22893,7 @@ Evaluates an individual user's specific unrealized loss exposure. ### 1.3 Low Holdings Alert (`LowHoldingsCount`) -Triggered synchronously by `LowHoldingsHandler` when a trade is executed — not on the 15-minute cycle. +Triggered by `LowHoldingsHandler` via an integration event (`inventoryalert.inventory.stock-low.v1`) — not by the scheduled price sync cycle. - **Formula**: `SUM(Quantity WHERE Type = Buy) - SUM(Quantity WHERE Type = Sell) < rule.TargetValue` - **Guard**: The service guards against net holdings going negative (oversell) — rejects the trade with `422 Unprocessable`. @@ -20758,16 +22955,17 @@ When `DELETE /portfolio/positions/{symbol}` is called: ## 5. Market Intelligence Sync Schedule -| Data | Job | Frequency | Finnhub Endpoint | +Schedules are configurable via `WorkerSettings.Schedules.*`. + +| Data | Job | Schedule setting | Finnhub Endpoint | |---|---|---|---| -| Price quotes | `SyncPricesJob` | Every 15 min | `/quote` | -| Basic Financials | `SyncMetricsJob` | Daily 06:00 UTC | `/stock/metric` | -| Earnings Surprises | `SyncEarningsJob` | Daily 07:00 UTC | `/stock/earnings` | -| Analyst Recommendations | `SyncRecommendationsJob` | Weekly (Monday) | `/stock/recommendation` | -| Insider Transactions | `SyncInsidersJob` | Daily 08:00 UTC | `/stock/insider-transactions` | -| Company News | `CompanyNewsJob` | Every 6h | `/company-news` | -| Market News | `MarketNewsJob` | Every 2h | `/news` | -| Price History Cleanup | `CleanupPriceHistoryJob` | Daily 00:00 UTC | — (DB delete) | +| Price quotes | `SyncPricesJob` | `Schedules.SyncPrices` | `/quote` | +| Basic Financials | `SyncMetricsJob` | `Schedules.SyncMetrics` | `/stock/metric` | +| Earnings Surprises | `SyncEarningsJob` | `Schedules.SyncEarnings` | `/stock/earnings` | +| Analyst Recommendations | `SyncRecommendationsJob` | `Schedules.SyncRecommendations` | `/stock/recommendation` | +| Insider Transactions | `SyncInsidersJob` | `Schedules.SyncInsiders` | `/stock/insider-transactions` | +| Market + Company News | `NewsSyncJob` | `Schedules.MarketNews` | `/news` + `/company-news` | +| Price History Cleanup | `CleanupPriceHistoryJob` | `Schedules.CleanupPrices` | — (DB delete) | --- @@ -20781,7 +22979,7 @@ Applied at the Web layer only. The Application layer trusts pre-validated inputs | `RegisterRequest` | Username `Matches(^[a-zA-Z0-9_]+$)`, Password min 1 uppercase + 1 digit + 1 special char | | `CreatePositionRequest` | TickerSymbol `Matches(^[A-Z0-9.]+$)`, Quantity `> 0`, UnitPrice `> 0 && < 1_000_000`, TradedAt `<= UtcNow` | | `TradeRequest` | Type must be valid enum; Quantity `> 0`; UnitPrice `> 0` (except Dividend/Split) | -| `AlertRuleRequest` | PercentDropFromCost: TargetValue `0.01–100`; LowHoldingsCount: whole number only |",121,3429fc767b6abb56f194ece737c44f64,InventoryAlert.Wiki\docs\04-execution-flows\business-logic.md,0,623,"rule, user, symbol, every, targetvalue, trade, type, delete",1776910223.9890504,1,unitofwork atomicity application service symbol unit test msft business logic dbset rollback productservice appdbcontext price drop stock price fluentassertions aapl notification xunit data access savechanges quote market data asnotracking igenericrepository commit arrange act assert stock ticker googl iproductrepository threshold iproductservice dbcontext loss entity framework efcore external api,# Business Logic & Rules (v1) | Business Logic & Rules (v1) This document outlines the core domain logic governi +| `AlertRuleRequest` | PercentDropFromCost: TargetValue `0.01–100`; LowHoldingsCount: whole number only |",122,2fa5b927cdf295648dbfbdc52960562a,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\business-logic.md,0,752,"rule, schedules, user, symbol, targetvalue, type, delete, price",1779814416.2343721,1,iproductrepository backgroundservice unitofwork notification dbcontext productservice stock ticker iproductservice quote rollback price drop atomicity commit savechanges googl data access dbset threshold arrange act assert entity framework external api xunit business logic unit test periodictimer symbol hosted service asnotracking igenericrepository efcore appdbcontext stock price aapl msft fluentassertions finnhubpricesyncworker application service market data loss,# Business Logic & Rules (v1) | Business Logic & Rules (v1) This document outlines the core domain logic governi doc,"# CQRS Event Flow (Async Commands) > How the system processes ""Commands"" from the UI using decoupling via SQS and Hangfire. @@ -20829,17 +23027,253 @@ This is sent to the `EventsController` (`POST /api/v1/events`). ### 2. Event Publishing (API) The API wraps this command in an `EventEnvelope` (adding telemetry like `CorrelationId` and `MessageId`) and publishes it directly to SQS. It immediately returns `HTTP 202 Accepted`. -### 3. Queue Processing (Worker) -The native continuous poller (`ProcessQueueJob`) reads the queue. Assuming it passes Redis deduplication guarantees, it passes the Event to the `IntegrationMessageRouter`. +### 3. Queue Processing (Worker) +The native continuous poller (`ProcessQueueJob`) reads the queue. Assuming it passes Redis deduplication guarantees, it passes the Event to the `IntegrationMessageRouter`. + +### 4. Background Handler Execution (Worker) +The router detects `SyncMarketNewsRequested` and enqueues `SyncMarketNewsHandler` via Hangfire. +The handler queries `IFinnhubClient`, maps the raw data, and writes the batch to DynamoDB. The UI will pick up this fresh data naturally on its next React-Query polling cycle.",53,769896efcf0c90e5af511b67994c9c79,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\cqrs-event-flow.md,0,753,"event, commands, from, market, news, worker, command, cqrs",1779814416.235048,1,stock price market data hosted service httppost price drop iactionresult backgroundservice httpget external api finnhubpricesyncworker productscontroller periodictimer quote httpput threshold notification loss,"# CQRS Event Flow (Async Commands) | CQRS Event Flow (Async Commands) > How the system processes ""Commands"" from the " +doc,"# 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 + 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. |",41,2336bd949b8a4798ac0a2cda01992266,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\earnings-sync-flow.md,0,754,"earnings, surprise, data, actual, estimate, reported, postgresql, synchronization",1779814416.235048,1,external api googl market data aapl stock price msft quote stock ticker symbol,# Earnings Surprise Synchronization Flow | Earnings Surprise Synchronization Flow > Orchestration pipeline for fetching his +doc,"# 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. |",70,c67db2d964a720bf5176fa1361bae820,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\error-handling-flow.md,0,755,"error, response, mapping, failures, business, friendly, status, diagnostic",1779814416.235048,1,commit entity framework iproductservice productscontroller iactionresult price drop threshold unitofwork httpget application service appdbcontext dbcontext httpput productservice httppost efcore atomicity asnotracking business logic savechanges loss rollback notification,# Error Handling & Standardized Response Flow | Error Handling & Standardized Response Flow > Global pipeline for intercepting f +doc,"# 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 + 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 + 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. |",48,5086c253557a458796621f0f2ccf4089,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\news-sync-flow.md,0,756,"news, dynamodb, company, market, symbol, specific, category, unix",1779814416.236056,1,external api stock price symbol periodictimer quote msft hosted service market data googl aapl stock ticker finnhubpricesyncworker backgroundservice,# News Synchronization Flow | News Synchronization Flow > Orchestration pipeline for fetching global market ne +doc,"# 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 -### 4. Background Handler Execution (Worker) -The router detects `SyncMarketNewsRequested` and enqueues `SyncMarketNewsHandler` via Hangfire. -The handler queries `IFinnhubClient`, maps the raw data, and writes the batch to DynamoDB. The UI will pick up this fresh data naturally on its next React-Query polling cycle.",53,658bf8da3829bbe62df246a47a289214,InventoryAlert.Wiki\docs\04-execution-flows\cqrs-event-flow.md,0,624,"event, commands, from, market, news, worker, command, cqrs",1776151046.7621593,1,backgroundservice iactionresult market data external api price drop periodictimer httppost notification loss hosted service quote threshold httpput productscontroller httpget stock price finnhubpricesyncworker,"# CQRS Event Flow (Async Commands) | CQRS Event Flow (Async Commands) > How the system processes ""Commands"" from the " +| 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. |",77,c13f2b7fb85332ff86164ceabef20818,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\portfolio-management-flow.md,0,757,"total, cost, trade, real, time, performance, return, portfolio",1779814416.236056,1,commit asnotracking business logic efcore migration httppost appdbcontext productscontroller price drop unitofwork iactionresult threshold entity framework atomicity database update productservice notification application service savechanges add-migration httpput httpget loss efcore schema change rollback iproductservice dbcontext,"# Portfolio Management Flow | Portfolio Management Flow > Orchestration for user-specific portfolios, trade hi" doc,"# Price Sync Flow > Orchestration pipeline for global market synchronization, alert evaluation, and in-app notification delivery. -## Sequence (v3 Architecture - Optimized) +## Sequence (current architecture) ```mermaid sequenceDiagram @@ -20847,14 +23281,13 @@ sequenceDiagram participant Job as SyncPricesJob participant Finnhub as Finnhub API participant DB as PostgreSQL - participant Redis as Redis Cache - participant SQS as Amazon SQS + participant Redis as Redis HF->>Job: Trigger (Scheduled) Job->>DB: SELECT TickerSymbols FROM StockListing Note over Job,Finnhub: Part 1: Parallel Quote Sync - loop Parallel.ForEachAsync (concurrency=5) + loop Parallel.ForEachAsync (concurrency = WorkerSettings.MaxDegreeOfParallelism) Job->>Finnhub: GET /quote?symbol={symbol} Finnhub-->>Job: { currentPrice, ... } Job->>Job: Collect into Bag @@ -20865,13 +23298,6 @@ sequenceDiagram Job->>DB: SELECT AlertRules WHERE TickerSymbol IN (processedSymbols) loop For each symbol processed loop For each rule - alt Condition == PercentDropFromCost - Note over Job: Check TradeBasisCache - alt Cache Miss - Job->>DB: SELECT Trades WHERE UserId/Symbol - Job->>Job: Compute + Cache Basis - end - end alt Rule is breached Job->>Job: Collect into List alt TriggerOnce = true @@ -20884,7 +23310,7 @@ sequenceDiagram Note over Job,DB: Part 3: Bulk Dispatch Job->>DB: AddRangeAsync(Notifications) loop For each notification - Job->>SQS: Publish PriceAlert Event + Job->>Redis: SignalR backplane push (IAlertNotifier) end Job->>DB: SaveChangesAsync (Single Transaction) ``` @@ -20910,36 +23336,30 @@ sequenceDiagram | **Parallel I/O** | `SyncPricesJob` uses `Parallel.ForEachAsync` to fetch quotes, significantly reducing latency. | | **Bulk Persistence** | Uses `AddRangeAsync` for PriceHistories and Notifications to minimize EF Core overhead. | | **N+1 Avoidance** | Fetches all relevant `AlertRules` in a single query using `GetBySymbolsAsync`. | -| **Trade Memoization** | Caches (User, Symbol) cost basis calculations to avoid redundant trade history lookups. | -| **In-App Notification** | Alert breaches write to the `Notification` table — UI badge updates instantly. | +| **Evaluator + Cooldown** | `IAlertRuleEvaluator` applies rule logic and enforces a Redis cooldown key to prevent alert storms. | +| **In-App Notification** | Alert breaches write to the `Notification` table, then are pushed via SignalR (`IAlertNotifier`). | | **Single Transaction** | All state changes (history, notifications, rule updates) are saved in one unit of work. | | **TriggerOnce** | If `rule.TriggerOnce = true`, rule is disabled automatically after first breach. | | **User Isolation** | `LowHoldingsCount` and `PercentDropFromCost` always filter by `(UserId, TickerSymbol)`. | --- -## SQS Event Payload +## Relationship to SQS (integration events) -The `inventoryalert.pricing.price-drop.v1` event published by `SyncPricesJob` follows the `EventEnvelope` pattern: - -```json -{ - ""eventType"": ""inventoryalert.pricing.price-drop.v1"", - ""correlationId"": ""..."", - ""payload"": { - ""symbol"": ""TSLA"" - } -} -``` +SQS is used for event-driven evaluation paths that are separate from the scheduled `SyncPricesJob`: -`PriceAlertHandler` in the Worker consumes this and performs a secondary evaluation to confirm the breach is still valid before triggering any additional side-effects (e.g., third-party relay).",98,39031db225d2efca79430eb132fc9089,InventoryAlert.Wiki\docs\04-execution-flows\price-sync-flow.md,0,625,"rule, targetvalue, currentprice, alert, evaluation, notification, quote, price",1777190302.4332247,1,stock ticker efcore savechanges appdbcontext googl entity framework aapl symbol dbcontext commit periodictimer finnhubpricesyncworker hosted service threshold backgroundservice notification msft market data price drop unitofwork external api rollback loss asnotracking quote stock price atomicity,"# Price Sync Flow | Price Sync Flow > Orchestration pipeline for global market synchronization, aler" +- The API can publish an `EventEnvelope` to SQS (see `POST /api/v1/events`). +- The Worker polls SQS continuously (`ProcessQueueJob`) and routes known event types: + - `inventoryalert.pricing.price-drop.v1` → `MarketPriceAlertHandler` + - `inventoryalert.inventory.stock-low.v1` → `LowHoldingsHandler` + - `inventoryalert.news.sync-requested.v1` → enqueue `NewsSyncJob`",84,954f99aef56bb825e1308649ef8d4baa,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\price-sync-flow.md,0,758,"rule, targetvalue, alert, currentprice, evaluation, notification, logic, quote",1779814416.236056,1,loss appdbcontext symbol finnhubpricesyncworker rollback quote dbcontext market data backgroundservice hosted service periodictimer msft entity framework stock ticker price drop aapl asnotracking googl threshold external api notification savechanges efcore commit atomicity stock price unitofwork,"# Price Sync Flow | Price Sync Flow > Orchestration pipeline for global market synchronization, aler" doc,"# User Authentication Flow > How users register, log in, refresh tokens, and access protected resources. ## JWT Token Lifecycle -Access token TTL = **15 minutes**. Refresh token TTL = **7 days** (stored as `httpOnly; Secure; SameSite=Strict` cookie). +Access token TTL defaults to **60 minutes** (config: `Jwt:ExpiryMinutes`). Refresh token TTL defaults to **7 days** (config: `Jwt:RefreshExpiryDays`). Refresh token is stored as an `httpOnly` cookie; `Secure` is enabled only on HTTPS, and `SameSite` is `None` for HTTPS/localhost (otherwise `Lax`). ```mermaid sequenceDiagram @@ -20969,7 +23389,7 @@ sequenceDiagram participant UI as Next.js UI participant API as InventoryAlert.Api - Note over UI: Access token expired (15 min) + Note over UI: Access token expired UI->>API: POST /api/v1/auth/refresh Note over UI,API: Refresh token read from httpOnly cookie (no body) API->>API: Validate refresh token (JWT signature + claims) @@ -21021,8 +23441,8 @@ sequenceDiagram | `sub` | User ID (Guid) — used by all services to scope data access | | `name` | Username — displayed in UI | | `role` | `User` or `Admin` — controls endpoint authorization | -| `exp` | Token expiry — 15 minutes from issuance | -| `iss` / `aud` | Validated on every request to prevent token reuse | +| `exp` | Token expiry — controlled by `Jwt:ExpiryMinutes` (default 60 minutes) | +| `iss` / `aud` | Validated on every request when configured (`Jwt:Issuer`, `Jwt:Audience`) | --- @@ -21030,31 +23450,109 @@ sequenceDiagram | Endpoint | Required | |---|---| -| `POST /auth/login`, `POST /auth/register`, `POST /auth/refresh` | `[Public]` — no token needed | +| `POST /api/v1/auth/login`, `POST /api/v1/auth/register`, `POST /api/v1/auth/refresh` | `[Public]` — no token needed | | All other endpoints | `[Authorize]` — valid JWT required | -| `POST /stocks/sync`, `GET/POST /events/*` | `[Authorize(Roles = ""Admin"")]` | -| `GET /market/status` | `[AllowAnonymous]` — explicitly public | +| `POST /api/v1/stocks/sync`, `GET/POST /api/v1/events/*` | `[Authorize(Roles = ""Admin"")]` | +| `GET /api/v1/market/status` | `[AllowAnonymous]` — explicitly public | --- ## Security Considerations -- Passwords are hashed with **BCrypt** (default work factor 11). +- Passwords are hashed with **BCrypt**. - Access token delivered in JSON body; **refresh token in `httpOnly` cookie** — not accessible to JavaScript. -- Refresh tokens are **single-use** (rotated on each refresh call). -- All sensitive config (`Jwt:Key`, `Database:ConnectionString`, `Finnhub:ApiKey`) lives in `appsettings.*.json` which is **gitignored**. Only `appsettings.Example.json` is committed. -- Login endpoint is **429 rate-limited** to prevent brute-force attacks.",111,281dee7273dce7e79ff0ad60aea712e9,InventoryAlert.Wiki\docs\04-execution-flows\user-authentication.md,0,626,"token, refresh, post, access, user, flow, endpoint, auth",1776145237.747694,1,asnotracking notification price drop loss productservice threshold business logic market data efcore stock price entity framework dbcontext iproductservice appdbcontext quote application service external api,"# User Authentication Flow | User Authentication Flow > How users register, log in, refresh tokens, and acces" +- Refresh tokens are **rotated** on each refresh call (revocation/deny-list can be added if strict single-use is required). +- All sensitive config (`Jwt:Key`, `Database:ConnectionString`, `Finnhub:ApiKey`) lives in `appsettings.*.json` which is **gitignored**. Only `appsettings.Example.json` is committed.",110,7884a63aba9ca35c4088eea4892598ac,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\user-authentication.md,0,759,"token, refresh, post, access, user, flow, config, required",1779814416.237056,1,stock price external api market data iproductservice business logic quote entity framework application service threshold notification loss efcore productservice appdbcontext asnotracking dbcontext price drop,"# User Authentication Flow | User Authentication Flow > How users register, log in, refresh tokens, and acces" +doc,"# 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. |",76,219aecc4e301bdda8d9e7bc314651162,src\ui\InventoryAlert.Wiki\docs\04-execution-flows\watchlist-management-flow.md,0,760,"watchlist, flow, user, first, resolution, finnhub, symbols, system",1779814416.237056,1,msft fluentassertions unit test iproductservice external api productservice httpget arrange act assert asnotracking httpput market data stock price symbol httppost googl dbcontext stock ticker quote appdbcontext business logic entity framework productscontroller efcore application service iactionresult aapl xunit,"# Watchlist Management Flow | Watchlist Management Flow > Orchestration for user-specific stock watchlists, in" doc,"# Event Handling -> How domain events are published, routed, and consumed across the system via Amazon SQS. +> How integration events are published, routed, and consumed across the system via SNS → SQS. ## Event Architecture -The system uses a **direct SQS messaging** pattern. Events flow through a single `inventory-events` queue. +The system uses **SNS fan-out to SQS**: + +- `InventoryAlert.Api` publishes an `EventEnvelope` to an SNS topic. +- The topic fans out to a subscribed SQS queue consumed by `InventoryAlert.Worker`. | Queue | Direction | Purpose | |---|---|---| -| `inventory-events` | API/Worker → Worker | Domain signals (alert triggers, news requests) | +| `inventory-events` | API → Worker | Integration events (alert triggers, news sync requests, test events) | --- @@ -21062,9 +23560,11 @@ The system uses a **direct SQS messaging** pattern. Events flow through a single | Event Type String | Publisher | Consumer | Description | |---|---|---|---| -| `inventoryalert.pricing.price-drop.v1` | `SyncPricesJob` | `PriceAlertHandler` | Fired when a price alert rule is breached | -| `inventoryalert.inventory.stock-low.v1` | Portfolio trade commits | `LowHoldingsHandler` | Fired when share count drops below `LowHoldingsCount` threshold | -| `inventoryalert.news.headline.v1` | `CompanyNewsJob` | `CompanyNewsHandler` | Forces immediate company news sync to DynamoDB | +| `inventoryalert.pricing.price-drop.v1` | Admin API (`POST /api/v1/events`) | `MarketPriceAlertHandler` | Evaluate rules for a specific symbol + price payload | +| `inventoryalert.inventory.stock-low.v1` | (Planned) API emits on trade/position updates | `LowHoldingsHandler` | Low-holdings alert for a specific user + symbol | +| `inventoryalert.news.sync-requested.v1` | Admin API / UI command | enqueue `NewsSyncJob` | Run consolidated market + company news sync | +| `inventoryalert.news.company-sync-requested.v1` | (Reserved) | (Not routed) | Reserved for per-ticker news sync requests | +| `inventoryalert.test.failure.v1` | Tests/E2E | throws (for retry/DLQ testing) | Poison-message simulation | > Retrieve the full list at runtime via `GET /api/v1/events/types`. @@ -21080,7 +23580,7 @@ All events are wrapped in a standard `EventEnvelope`: ""source"": ""InventoryAlert.Worker"", ""messageId"": ""550e8400-e29b-41d4-a716-446655440000"", ""correlationId"": ""req-abc-123"", - ""payload"": ""{\""Symbol\"": \""TSLA\""}"", + ""payload"": ""{\""symbol\"":\""TSLA\"",\""newPrice\"":123.45}"", ""timestamp"": ""2026-04-13T10:00:00Z"" } ``` @@ -21106,9 +23606,9 @@ Incoming SQS messages are routed by `EventType` to the appropriate handler: ```mermaid flowchart TD SQS[SQS Message received] --> Router[IntegrationMessageRouter] - Router -->|price-drop.v1| H1[PriceAlertHandler] + Router -->|price-drop.v1| H1[MarketPriceAlertHandler] Router -->|stock-low.v1| H2[LowHoldingsHandler] - Router -->|news.headline.v1| H3[CompanyNewsHandler] + Router -->|news.sync-requested.v1| H3[Enqueue NewsSyncJob] Router -->|Unknown| H4[DefaultHandler: Log + ACK] ``` @@ -21116,44 +23616,36 @@ flowchart TD ## Processing Guarantee: Exactly-Once via Redis -`ProcessQueueJob` uses Redis `SET NX` deduplication before routing: +`ProcessQueueJob` uses a Redis marker key to avoid re-processing the same SQS message id. The key is written **only after successful handling**, so failures still retry naturally via SQS redelivery: ```csharp -var dedupKey = $""dedup:sqs:{envelope.MessageId}""; -if (!await _redisDb.StringSetAsync(dedupKey, ""1"", TimeSpan.FromMinutes(30), When.NotExists)) - return; // Already processed — skip silently +var dedupKey = $""msg:processed:{message.MessageId}""; +if (await _redisDb.KeyExistsAsync(dedupKey)) + return; // Already processed — skip + +// After successful processing: +await _redisDb.StringSetAsync(dedupKey, ""1"", TimeSpan.FromHours(24)); ``` --- -## Alert Cooldown (24h per symbol) +## Alert Cooldown (24h per rule) -`PriceAlertHandler` uses a Redis cooldown key to prevent repeated alerts within 24 hours for the same symbol — regardless of how many users have alerts for that symbol: +`IAlertRuleEvaluator` uses a Redis cooldown key to prevent repeated alerts within 24 hours for the same user+rule: ```csharp -var alertKey = $""cooldown:alert:{payload.Symbol}""; -if (await _redisDb.KeyExistsAsync(alertKey)) - return; // Suppressed +var cooldownKey = CacheKeys.AlertCooldown(rule.UserId, rule.Id); +if (await _redis.KeyExistsAsync(cooldownKey, ct)) + return (false, string.Empty); -await _redisDb.StringSetAsync(alertKey, ""1"", TimeSpan.FromHours(24)); -// Create Notification rows per user... +await _redis.TryAcquireBestEffortLockAsync(cooldownKey, ""1"", TimeSpan.FromHours(24), ct); ``` --- ## Dead Letter Queue (DLQ) -When `ApproximateReceiveCount > 5`, the message is considered a poison pill and acknowledged to unblock the queue: - -```csharp -if (receiveCount > 5) -{ - _logger.LogWarning(""[SqsWorker] Message {Id} exceeded retry limit. Dropping."", message.MessageId); - return; // ACK to remove from main queue, ejects to DLQ -} -``` - -DLQ messages can be replayed via the AWS Console or Hangfire dashboard. +DLQ behavior is handled by AWS redrive policy: messages are deleted only on success. After the configured max receives, AWS moves the message to the DLQ automatically. --- @@ -21164,12 +23656,12 @@ POST /api/v1/events Authorization: Bearer { - ""eventType"": ""inventoryalert.news.headline.v1"", - ""payload"": { ""Symbol"": ""AAPL"" } + ""eventType"": ""inventoryalert.pricing.price-drop.v1"", + ""payload"": { ""symbol"": ""AAPL"", ""newPrice"": 172.50 } } ``` -Returns `202 Accepted: { ""Status"": ""Queued"" }`.",126,6b25820d83dadedb787fd1a8baf66a0d,InventoryAlert.Wiki\docs\05-api-services\event-handling.md,0,627,"events, event, queue, uses, inventory, alert, news, inventoryalert",1776145217.4504955,1,finnhubpricesyncworker entity framework periodictimer efcore price drop dbcontext asnotracking backgroundservice hosted service threshold notification appdbcontext loss,"# Event Handling | Event Handling > How domain events are published, routed, and consumed across th" +Returns `202 Accepted: { ""Status"": ""Queued"" }`.",123,6451a5eb83fa4958bb0a032dc17957f3,src\ui\InventoryAlert.Wiki\docs\05-api-services\event-handling.md,0,761,"events, inventoryalert, news, sync, message, event, routed, uses",1779814416.237948,1,efcore entity framework notification price drop symbol hosted service finnhubpricesyncworker threshold unit test backgroundservice asnotracking msft stock ticker fluentassertions periodictimer dbcontext appdbcontext aapl googl loss arrange act assert xunit,"# Event Handling | Event Handling > How integration events are published, routed, and consumed acro" doc,"# External Service Integrations > How InventoryAlert communicates with third-party APIs and external services. @@ -21189,8 +23681,8 @@ doc,"# External Service Integrations | `GET /api/v1/quote` | `GET /stocks/{symbol}/quote` | `StockDataService` | | `GET /api/v1/stock/profile2` | `GET /stocks/{symbol}/profile` | `StockDataService` | | `GET /api/v1/stock/market-status` | `GET /market/status` | `StockDataService` | -| `GET /api/v1/news` | `GET /market/news` | `StockDataService` | -| `GET /api/v1/company-news` | `GET /stocks/{symbol}/news` | `CompanyNewsJob` | +| `GET /api/v1/news` | `GET /market/news` | `NewsSyncJob` (sync) + `StockDataService` (read) | +| `GET /api/v1/company-news` | `GET /stocks/{symbol}/news` | `NewsSyncJob` (sync) + `StockDataService` (read) | | `GET /api/v1/search` | `GET /stocks/search` | Discovery flow | | `GET /api/v1/stock/metric` | `GET /stocks/{symbol}/financials` | `SyncMetricsJob` | | `GET /api/v1/stock/earnings` | `GET /stocks/{symbol}/earnings` | `SyncEarningsJob` | @@ -21280,16 +23772,15 @@ var messages = await _sqsHelper.ReceiveMessagesAsync(queueUrl, maxMessages: 10, ## Redis -- **Purpose**: Quote caching, SQS deduplication, alert cooldown, Finnhub rate limiting +- **Purpose**: Quote caching, SQS idempotency markers, alert cooldown - **Local**: `localhost:6379` (Docker: `inventory-cache`) - **Namespaces**: | Key | TTL | Purpose | |---|---|---| | `quote:{symbol}` | 30s | Cached Finnhub quote | -| `dedup:sqs:{messageId}` | 30 min | SQS exactly-once guard | -| `cooldown:alert:{symbol}` | 24h | Prevent alert storms | -| `finnhub:ratelimit` | Rolling 60s | Rate limit counter (cap 55 rpm) |",120,dae7a3675ad53fa6ce5b1585e2c716e3,InventoryAlert.Wiki\docs\05-api-services\external-integrations.md,0,628,"symbol, news, stock, stocks, market, finnhub, quote, stockdataservice",1776145350.6661835,1,googl iproductservice quote aapl dbcontext hosted service asnotracking symbol price drop postgresql savechanges efcore stock price atomicity notification postgres commit finnhubpricesyncworker container rollback loss business logic compose periodictimer unitofwork stock ticker market data productservice backgroundservice external api dockerfile appdbcontext threshold entity framework msft application service,# External Service Integrations | External Service Integrations > How InventoryAlert communicates with third-party +| `msg:processed:{messageId}` | 24h | SQS idempotency marker (written after successful processing) | +| `inventoryalert:alerts:cooldown:v1:{userId}:{ruleId}` | 24h | Alert cooldown gate (per user + rule) |",119,1c2cd08b2650f04ce451ca0555865d7a,src\ui\InventoryAlert.Wiki\docs\05-api-services\external-integrations.md,0,762,"symbol, news, stock, stocks, stockdataservice, market, quote, inventoryalert",1779814416.2384791,1,notification atomicity msft asnotracking loss postgres periodictimer googl finnhubpricesyncworker iproductservice aapl entity framework productservice postgresql market data savechanges appdbcontext rollback efcore container backgroundservice quote unitofwork stock ticker business logic dockerfile threshold application service compose symbol price drop commit stock price dbcontext external api hosted service,# External Service Integrations | External Service Integrations > How InventoryAlert communicates with third-party doc,"# Internal API Reference (v1) > Core REST endpoints exposed by `InventoryAlert.Api`. All routes are prefixed with `/api/v1` unless otherwise noted. JWT Bearer Token required unless marked `[Public]`. @@ -21302,10 +23793,10 @@ Authentication via secure JWTs and `httpOnly` Refresh Token cookies. | Method | Endpoint | Auth | Description | |---|---|---|---| -| POST | `/login` | `[Public]` | Authenticate and receive `AuthResponse` + Refresh token via Cookie. 429 rate-limited. | +| POST | `/login` | `[Public]` | Authenticate and receive `AuthResponse` + Refresh token via Cookie. | | POST | `/register` | `[Public]` | Create a new user account. | | POST | `/refresh` | `[Public]` | Exchange a valid `httpOnly` refresh token for a new access JWT. | -| POST | `/logout` | JWT | Revoke the current refresh token server-side. Clears cookie. | +| POST | `/logout` | JWT | Clears the refresh token cookie (server-side revocation hook reserved for future). | ### POST `/login` — Response @@ -21316,7 +23807,7 @@ Authentication via secure JWTs and `httpOnly` Refresh Token cookies. } ``` -> Access token TTL = **15 minutes**. Refresh token TTL = **7 days**, delivered as `httpOnly; Secure; SameSite=Strict` cookie. +> Access token TTL defaults to **60 minutes** (config: `Jwt:ExpiryMinutes`). Refresh token TTL defaults to **7 days** (config: `Jwt:RefreshExpiryDays`). Refresh token is delivered as an `httpOnly` cookie; `Secure` is enabled only on HTTPS, and `SameSite` is `None` for HTTPS/localhost (otherwise `Lax`). --- @@ -21359,6 +23850,25 @@ Personal position management. All data scoped strictly to the authenticated user --- +### POST `/{symbol}/trades` — Request + +Records an immutable `Trade` row for the authenticated user and returns the updated position snapshot. + +```json +{ + ""type"": ""Buy"", + ""quantity"": 10, + ""unitPrice"": 172.5, + ""notes"": ""Optional note (max 500 chars)"" +} +``` + +Validation notes: + +- `notes` is optional and limited to **500 characters**. +- `unitPrice` must be `>= 0` (dividend/split can be `0`). +- For `Sell`, the API rejects oversell attempts when `netHoldings < quantity`. + ## Stocks (Market Intelligence) — `/api/v1/stocks` Global market intelligence hub. Extensively cached locally to bypass strict external rate limits. @@ -21427,9 +23937,9 @@ Configure dynamic evaluation triggers executed globally by background workers. |---|---|---| | GET | `/` | List all alert rules for the authenticated user. | | POST | `/` | Create a new alert rule (symbol is auto-resolved if missing from catalog). | -| PUT | `/{ruleId}` | Full replacement of an existing rule. | -| PATCH | `/{ruleId}/toggle` | Enable or disable without modifying rule parameters. | -| DELETE | `/{ruleId}` | Permanently remove an alert rule. | +| PUT | `/{id}` | Full replacement of an existing rule (`id` is a GUID). | +| PATCH | `/{id}/toggle` | Enable or disable without modifying rule parameters (`id` is a GUID). | +| DELETE | `/{id}` | Permanently remove an alert rule (`id` is a GUID). | ### Alert Conditions @@ -21449,11 +23959,12 @@ In-app notification delivery. UI polls every 30 seconds. | Method | Endpoint | Description | |---|---|---| -| GET | `/` | Chronological notification feed. Pass `?OnlyUnread=true` for focused rendering. | +| POST | `/test-signalr?message=...` | Dev helper: pushes a test notification via SignalR to the current user. | +| GET | `/` | Chronological notification feed. Pass `?onlyUnread=true` for focused rendering. | | GET | `/unread-count` | Returns `int` for navbar bell badge. | -| PATCH | `/{id}/read` | Mark one notification as acknowledged. | +| PATCH | `/{id}/read` | Mark one notification as acknowledged (204 No Content). | | PATCH | `/read-all` | Batch acknowledge all notifications. | -| DELETE | `/{id}` | Permanently dismiss a notification. | +| DELETE | `/{id}` | Permanently dismiss a notification (204 No Content). | --- @@ -21478,7 +23989,6 @@ Internal event publishing for SQS integration. | `Unauthorized` | 401 | Missing or invalid JWT. | | `Forbidden` | 403 | Authenticated but lacks ownership of resource. | | `UnprocessableEntity` | 422 | Semantic error (e.g., negative quantity, bad ticker). | -| `TooManyRequests` | 429 | Rate limit exceeded (login endpoint). | | `Internal` | 500 | Unhandled server error. | ### Standard Error Body @@ -21492,14 +24002,16 @@ Internal event publishing for SQS integration. ""Quantity"": [""Quantity must be greater than 0.""] } } -```",203,c681fdb585ab63d2073a4a121dec46b3,InventoryAlert.Wiki\docs\05-api-services\internal-api.md,0,629,"symbol, post, user, endpoint, description, positions, method, position",1776910223.9900517,1,atomicity commit dbcontext hosted service arrange act assert finnhubpricesyncworker threshold xunit msft backgroundservice price drop external api loss unit test googl periodictimer appdbcontext savechanges aapl fluentassertions entity framework rollback symbol stock price notification quote asnotracking market data efcore stock ticker unitofwork,# Internal API Reference (v1) | Internal API Reference (v1) > Core REST endpoints exposed by InventoryAlert.Api +```",222,f1254d9c033c4aed1481047ee8f829cb,src\ui\InventoryAlert.Wiki\docs\05-api-services\internal-api.md,0,763,"symbol, post, user, description, position, positions, token, method",1779814416.2384791,1,rollback dbcontext backgroundservice external api stock price hosted service finnhubpricesyncworker price drop unit test xunit msft savechanges quote arrange act assert symbol asnotracking aapl atomicity market data unitofwork loss googl commit stock ticker efcore appdbcontext fluentassertions notification periodictimer threshold entity framework,# Internal API Reference (v1) | Internal API Reference (v1) > Core REST endpoints exposed by InventoryAlert.Api doc,"# Hangfire Monitoring > How to use the Hangfire Dashboard to inspect and manage background jobs. ## Accessing the Dashboard -Navigate to `http://localhost:8080/hangfire` (requires **Admin** role JWT). +Navigate to `http://localhost:8081/hangfire` (Docker Compose maps Worker `8080` → host `8081`). + +Authorization note: the Worker dashboard uses a development-friendly authorization filter (`DevDashboardAuthorizationFilter`). It is not driven by JWT. ## Dashboard Sections @@ -21513,17 +24025,17 @@ Navigate to `http://localhost:8080/hangfire` (requires **Admin** role JWT). ## Scheduled Jobs Visible in Dashboard -| Job Name | Cron | Failure Impact | +Recurring jobs are registered by `JobSchedulerService` and use schedules from `WorkerSettings.Schedules.*`. + +| Recurring Job Id | Schedule setting | Failure impact | |---|---|---| -| `SyncPricesJob` | `*/15 * * * *` | No price update; no alert evaluation for that cycle | -| `SyncMetricsJob` | `0 6 * * *` | Stale `StockMetric` data (P/E, EPS, margins) | -| `SyncEarningsJob` | `0 7 * * *` | Stale `EarningsSurprise` data | -| `SyncRecommendationsJob` | `0 8 * * 1` | Stale analyst consensus | -| `SyncInsidersJob` | `0 8 * * *` | Stale insider transaction data | -| `CompanyNewsJob` | `0 */6 * * *` | Missing company news for that window | -| `MarketNewsJob` | `0 */2 * * *` | Missing general market news | -| `CleanupPriceHistoryJob` | `@daily` | `PriceHistory` table grows unbounded | -| `ProcessQueueJob` | Continuous | SQS events back up until next `SqsScheduledPollerJob` runs | +| `sync-prices` | `Schedules.SyncPrices` | No price update; no scheduled alert evaluation for that cycle | +| `sync-metrics` | `Schedules.SyncMetrics` | Stale `StockMetric` data | +| `sync-earnings` | `Schedules.SyncEarnings` | Stale `EarningsSurprise` data | +| `sync-recommendations` | `Schedules.SyncRecommendations` | Stale analyst consensus | +| `sync-insiders` | `Schedules.SyncInsiders` | Stale insider transaction data | +| `news-sync` | `Schedules.MarketNews` | Stale market/company news snapshots in DynamoDB | +| `cleanup-prices` | `Schedules.CleanupPrices` | `PriceHistory` grows unbounded | ## Retrying a Failed Job @@ -21535,14 +24047,12 @@ Navigate to `http://localhost:8080/hangfire` (requires **Admin** role JWT). From Hangfire Dashboard: 1. Go to **Recurring Jobs** -2. Find `SyncPricesJob` +2. Find `sync-prices` 3. Click **Trigger Now** -Or via the API: -```bash -POST http://localhost:8080/api/v1/stocks/sync -Authorization: Bearer -```",50,5ff415bea27300679dfa248269e9b573,InventoryAlert.Wiki\docs\06-background-jobs\hangfire-monitoring.md,0,630,"jobs, dashboard, hangfire, failed, stale, data, click, recurring",1776145471.6139846,1,commit price drop notification asnotracking unitofwork loss periodictimer threshold dbcontext backgroundservice atomicity rollback entity framework efcore finnhubpricesyncworker hosted service appdbcontext savechanges,# Hangfire Monitoring | Hangfire Monitoring > How to use the Hangfire Dashboard to inspect and manage ba +Or via the API endpoint (placeholder): + +- `POST /api/v1/stocks/sync` currently returns `202 Accepted` but does not enqueue a Hangfire job.",50,692bb2fb19516a3854f74abd5289cd81,src\ui\InventoryAlert.Wiki\docs\06-background-jobs\hangfire-monitoring.md,0,764,"jobs, schedules, sync, dashboard, hangfire, stale, failed, recurring",1779814416.2394872,1,unitofwork price drop commit appdbcontext application service container dockerfile asnotracking periodictimer postgres postgresql hosted service compose productservice business logic finnhubpricesyncworker backgroundservice savechanges iproductservice atomicity rollback entity framework notification threshold loss efcore dbcontext,# Hangfire Monitoring | Hangfire Monitoring > How to use the Hangfire Dashboard to inspect and manage ba doc,"# Worker Engine ## Architecture: Hybrid Hangfire + SQS Strategy @@ -21579,22 +24089,26 @@ graph TD Running inside `InventoryAlert.Worker`, driven by Hangfire cron schedules. -| Job | Cron Schedule | Finnhub Endpoint | Key Duty | +Schedules are configurable via `WorkerSettings.Schedules.*` (with sensible defaults in code and environment overrides via `appsettings*.json`). + +InventoryAlert uses a total of **8 background jobs** (7 recurring via Hangfire + 1 continuous SQS listener). + +| Job | Schedule setting | Finnhub Endpoint | Key duty | |---|---|---|---| -| **SyncPricesJob** | `*/15 * * * *` | `/quote` | Parallel fetch → updates `PriceHistory` → Batch evaluates `AlertRule` → writes `Notification` → SignalR Push | -| **SyncMetricsJob** | `0 6 * * *` | `/stock/metric` | Updates `StockMetric` table for all active symbols | -| **SyncEarningsJob** | `0 7 * * *` | `/stock/earnings` | Refreshes `EarningsSurprise` rows for watchlisted symbols | -| **SyncRecommendationsJob** | `0 8 * * 1` | `/stock/recommendation` | Refreshes `RecommendationTrend` for portfolio + watchlist symbols | -| **SyncInsidersJob** | `0 8 * * *` | `/stock/insider-transactions` | Pulls last 100 insider transactions for actively-watched symbols | -| **NewsSyncJob** | `0 */2 * * *` | `/news` & `/company-news` | **Consolidated:** Syncs global market categories AND symbol-specific news in parallel. | -| **CleanupPriceHistoryJob** | `@daily` | — | Deletes `PriceHistory` rows older than 1 year (batched, `LIMIT 10000`) | -| **ProcessQueueJob** | Continuous | — | SQS consumer with Redis-based idempotency (30-min window) | +| **SyncPricesJob** | `Schedules.SyncPrices` | `/quote` | Parallel fetch → insert `PriceHistory` → batch evaluate `AlertRule` → insert `Notification` → SignalR push | +| **SyncMetricsJob** | `Schedules.SyncMetrics` | `/stock/metric` | Refresh cached `StockMetric` rows | +| **SyncEarningsJob** | `Schedules.SyncEarnings` | `/stock/earnings` | Refresh `EarningsSurprise` rows | +| **SyncRecommendationsJob** | `Schedules.SyncRecommendations` | `/stock/recommendation` | Refresh `RecommendationTrend` rows | +| **SyncInsidersJob** | `Schedules.SyncInsiders` | `/stock/insider-transactions` | Refresh `InsiderTransaction` rows | +| **NewsSyncJob** | `Schedules.MarketNews` | `/news` & `/company-news` | Consolidated market + company news sync (DynamoDB read-model) | +| **CleanupPriceHistoryJob** | `Schedules.CleanupPrices` | — | Deletes `PriceHistory` rows older than 1 year | +| **ProcessQueueJob** | Continuous | — | Native SQS poller + router + idempotency | --- ## The Optimized Evaluation Pipeline: `SyncPricesJob` -The v3 architecture features high-concurrency and batch-resolution logic: +The current architecture uses high-concurrency quote fetching and batch rule evaluation: ```text 1. Collect active TickerSymbols from StockListing. @@ -21604,10 +24118,9 @@ The v3 architecture features high-concurrency and batch-resolution logic: 3. PART 2 (Batch Alert Check): - Fetch all active AlertRules for processed symbols in ONE query. - Evaluate breach conditions (direct comparison or cost-basis math). - - Use TradeBasisCache to memoize heavy User+Symbol cost calculations. 4. PART 3 (Real-time Notification): - Batch insert Notification records. - - For each breach: Push via IHubContext (SignalR Redis Backplane). + - For each breach: Push via `IAlertNotifier` (SignalR via Redis backplane). 5. COMMIT: Single SaveChangesAsync call for all history, notifications, and rule updates. ``` @@ -21621,15 +24134,18 @@ The v3 architecture features high-concurrency and batch-resolution logic: ## Event Handlers (SQS Topology) -Located in `IntegrationEvents/Handlers`. Operating under CQRS Command-Query principles. +Located in `IntegrationEvents/Handlers`, invoked by `IntegrationMessageRouter` after messages are pulled from SQS by `ProcessQueueJob`. | Handler | SQS Event Type | Role | |---|---|---| -| **MarketPriceAlertHandler** | `inventoryalert.pricing.price-drop.v1` | Price fetch → cache update → `PriceHistory` insert → full `AlertRule` evaluate for symbol | -| **LowHoldingsHandler** | `inventoryalert.inventory.stock-low.v1` | Queries `Trade` ledger by `(UserId, TickerSymbol)` → checks `AlertRule[LowHoldingsCount]` | -| **CompanyNewsAlertHandler** | `inventoryalert.news.headline.v1` | Immediate sync of ticker news → DynamoDB `CompanyNews` | -| **NewsSyncJob** (via Router) | `inventoryalert.news.sync-requested.v1` | On-demand UI command to refresh global news feed | -| **DefaultHandler** | `*` (unmatched) | Log + acknowledge. Prevents poison-message queue blockage. | +| **MarketPriceAlertHandler** | `inventoryalert.pricing.price-drop.v1` | Evaluate rules for a specific symbol + price payload and push notifications | +| **LowHoldingsHandler** | `inventoryalert.inventory.stock-low.v1` | Persist + push a holdings notification for a specific user + symbol | +| **NewsSyncJob** (via Router) | `inventoryalert.news.sync-requested.v1` | Enqueue the consolidated news sync job | +| **DefaultHandler** | `*` (unmatched) | Log + acknowledge (prevents poison-message blockage) | + +Notes: + +- `inventoryalert.news.company-sync-requested.v1` is defined in `EventTypes`, but is not currently routed by `IntegrationMessageRouter`. --- @@ -21639,7 +24155,7 @@ The worker is equipped with health check endpoints exposed via HTTP (port `8080` - **Liveness & Readiness**: `GET /health` - **Dependency Checks**: Verified connectivity to PostgreSQL on startup. -- **Docker Integration**: Configured with `interval: 10s` and `retries: 5` to ensure background services stay responsive.",97,a9bdf4297f5160834246be3a461a3779,InventoryAlert.Wiki\docs\06-background-jobs\workers.md,0,631,"news, worker, inventoryalert, stock, price, sync, redis, symbols",1777190302.4357338,1,market data price drop entity framework stock ticker efcore notification data access finnhubpricesyncworker atomicity appdbcontext googl business logic igenericrepository application service postgres loss iproductrepository dbset commit dockerfile container periodictimer compose iproductservice dbcontext asnotracking quote postgresql external api msft savechanges unitofwork stock price symbol rollback aapl backgroundservice hosted service productservice threshold,# Worker Engine | Worker Engine Architecture: Hybrid Hangfire + SQS Strategy The background worke +- **Docker Integration**: Configured with `interval: 10s` and `retries: 5` to ensure background services stay responsive.",103,3956bd95715d379a55d07eea3dcd70d9,src\ui\InventoryAlert.Wiki\docs\06-background-jobs\workers.md,0,765,"schedules, news, worker, sync, inventoryalert, refresh, stock, rows",1779814416.2394872,1,postgresql rollback finnhubpricesyncworker googl business logic postgres iproductservice entity framework loss asnotracking iproductrepository stock ticker market data application service dbcontext compose atomicity productservice commit container efcore notification savechanges msft data access symbol hosted service dockerfile external api price drop unitofwork appdbcontext periodictimer aapl threshold quote igenericrepository dbset backgroundservice stock price,# Worker Engine | Worker Engine Architecture: Hybrid Hangfire + SQS Strategy The background worke doc,"# AI Agent Workflows > Catalog of repository-specific patterns and available agent slash commands. @@ -21738,20 +24254,20 @@ var listings = await _db.StockListings | New controller | `Api/Controllers/` | | New API service | `Api/Services/` | | New scheduled job | `Worker/ScheduledJobs/` | -| New SQS handler | `Worker/IntegrationEvents/Handlers/` |",99,dea271d8e88f1f749650923d4c62caa1,InventoryAlert.Wiki\docs\07-dev-maintenance\ai-agent-workflows.md,0,632,"domain, entity, repository, worker, feature, code, infrastructure, agent",1776145448.7007246,1,iactionresult backgroundservice efcore entity framework fluentassertions business logic database update msft hosted service symbol savechangesasync productscontroller unitofwork schema change executetransactionasync stock price arrange act assert stock ticker igenericrepository asnotracking atomicity appdbcontext savechanges rollback efcore migration iproductrepository commit iproductservice productservice add-migration unit test googl iunitofwork periodictimer application service data access xunit dbset external api httpput httppost dbcontext market data httpget quote finnhubpricesyncworker aapl,# AI Agent Workflows | AI Agent Workflows > Catalog of repository-specific patterns and available agent +| New SQS handler | `Worker/IntegrationEvents/Handlers/` |",99,bd26536132175dbe043c7e0c5829119d,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\ai-agent-workflows.md,0,766,"domain, entity, repository, worker, feature, code, infrastructure, agent",1779814416.2394872,1,productservice httppost executetransactionasync stock price igenericrepository efcore migration business logic arrange act assert data access productscontroller fluentassertions httpget stock ticker iunitofwork googl atomicity savechanges dbcontext iproductrepository finnhubpricesyncworker commit iproductservice unit test dbset periodictimer quote symbol rollback hosted service add-migration unitofwork aapl msft entity framework database update efcore application service appdbcontext asnotracking httpput backgroundservice iactionresult schema change external api market data savechangesasync xunit,# AI Agent Workflows | AI Agent Workflows > Catalog of repository-specific patterns and available agent doc,"# .NET CLI Reference Detailed guide for managing the .NET projects within the InventoryAlert system. ## 1. Solution Commands -```bash",7,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,633,"reference, detailed, guide, managing, projects, within, inventoryalert, system",1776145405.019363,1,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# .NET CLI Reference | .NET CLI Reference Detailed guide for managing the .NET projects within the Inve +```bash",7,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,767,"reference, detailed, guide, managing, projects, within, inventoryalert, system",1779851803.688814,1,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# .NET CLI Reference | .NET CLI Reference Detailed guide for managing the .NET projects within the Inve doc,"# Build entire solution -dotnet build",10,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,634,"build, entire, solution, dotnet",1776145405.019363,8,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Build entire solution | Build entire solution dotnet build +dotnet build",10,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,768,"build, entire, solution, dotnet",1779851803.688814,8,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Build entire solution | Build entire solution dotnet build doc,"# Run clean -dotnet clean",13,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,635,"clean, dotnet",1776145405.019363,11,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Run clean | Run clean dotnet clean +dotnet clean",13,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,769,"clean, dotnet",1779851803.688814,11,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Run clean | Run clean dotnet clean doc,"# Run with Hot Reload (API only) -dotnet watch run --project InventoryAlert.Api/InventoryAlert.Api.csproj",16,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,636,"inventoryalert, reload, only, dotnet, watch, project, csproj",1776145405.019363,14,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Run with Hot Reload (API only) | Run with Hot Reload (API only) dotnet watch run --project InventoryAlert.Api/Inv +dotnet watch run --project InventoryAlert.Api/InventoryAlert.Api.csproj",16,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,770,"inventoryalert, reload, only, dotnet, watch, project, csproj",1779851803.688814,14,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Run with Hot Reload (API only) | Run with Hot Reload (API only) dotnet watch run --project InventoryAlert.Api/Inv doc,"# List all outdated packages dotnet list package --outdated ``` @@ -21762,19 +24278,19 @@ dotnet list package --outdated > Run from `InventoryManagementSystem/` directory. -```bash",27,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,637,"list, outdated, packages, dotnet, package, bash",1776145405.019363,17,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# List all outdated packages | List all outdated packages dotnet list package --outdated --- 2 +```bash",27,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,771,"list, outdated, packages, dotnet, package, bash",1779851803.688814,17,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# List all outdated packages | List all outdated packages dotnet list package --outdated --- 2 doc,"# Create a migration dotnet ef migrations add \ --project InventoryAlert.Api \ - --startup-project InventoryAlert.Api",32,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,638,"project, inventoryalert, create, migration, dotnet, migrations, migrationname, startup",1776145405.019363,28,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Create a migration | Create a migration dotnet ef migrations add \ --project Invent + --startup-project InventoryAlert.Api",32,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,772,"project, inventoryalert, create, migration, dotnet, migrations, migrationname, startup",1779851803.688814,28,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Create a migration | Create a migration dotnet ef migrations add \ --project Invent doc,"# Remove last migration (before applying) dotnet ef migrations remove \ --project InventoryAlert.Api \ - --startup-project InventoryAlert.Api",37,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,639,"remove, project, inventoryalert, last, migration, before, applying, dotnet",1776145405.019363,33,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Remove last migration (before applying) | Remove last migration (before applying) dotnet ef migrations remove \ --projec + --startup-project InventoryAlert.Api",37,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,773,"remove, project, inventoryalert, last, migration, before, applying, dotnet",1779851803.688814,33,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Remove last migration (before applying) | Remove last migration (before applying) dotnet ef migrations remove \ --projec doc,"# Apply migrations dotnet ef database update \ --project InventoryAlert.Api \ - --startup-project InventoryAlert.Api",42,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,640,"project, inventoryalert, apply, migrations, dotnet, database, update, startup",1776145405.019363,38,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Apply migrations | Apply migrations dotnet ef database update \ --project InventoryAlert.Api \ + --startup-project InventoryAlert.Api",42,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,774,"project, inventoryalert, apply, migrations, dotnet, database, update, startup",1779851803.688814,38,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Apply migrations | Apply migrations dotnet ef database update \ --project InventoryAlert.Api \ doc,"# List all migrations dotnet ef migrations list \ --project InventoryAlert.Api \ @@ -21799,40 +24315,51 @@ Examples: ## 3. Test Commands -```bash",67,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,641,"list, migrations, project, inventoryalert, dotnet, startup, verb, entity",1776145405.019363,43,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# List all migrations | List all migrations dotnet ef migrations list \ --project InventoryAlert.Api \ +```bash",67,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,775,"list, migrations, project, inventoryalert, dotnet, startup, verb, entity",1779851803.688814,43,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# List all migrations | List all migrations dotnet ef migrations list \ --project InventoryAlert.Api \ doc,"# Run all tests -dotnet test",70,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,642,"tests, dotnet, test",1776145405.019363,68,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Run all tests | Run all tests dotnet test +dotnet test",70,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,776,"tests, dotnet, test",1779851803.688814,68,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Run all tests | Run all tests dotnet test doc,"# Run with verbose output -dotnet test --logger ""console;verbosity=detailed""",73,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,643,"verbose, output, dotnet, test, logger, console, verbosity, detailed",1776145405.019363,71,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,"# Run with verbose output | Run with verbose output dotnet test --logger ""console;verbosity=detailed""" +dotnet test --logger ""console;verbosity=detailed""",73,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,777,"verbose, output, dotnet, test, logger, console, verbosity, detailed",1779851803.688814,71,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,"# Run with verbose output | Run with verbose output dotnet test --logger ""console;verbosity=detailed""" doc,"# Run specific project dotnet test InventoryAlert.UnitTests/ -dotnet test InventoryAlert.IntegrationTests/",77,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,644,"dotnet, test, inventoryalert, specific, project, unittests, integrationtests",1776145405.019363,74,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Run specific project | Run specific project dotnet test InventoryAlert.UnitTests/ dotnet test Inventory +dotnet test InventoryAlert.IntegrationTests/",77,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,778,"dotnet, test, inventoryalert, specific, project, unittests, integrationtests",1779851803.688814,74,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Run specific project | Run specific project dotnet test InventoryAlert.UnitTests/ dotnet test Inventory doc,"# Run with coverage (requires coverlet) -dotnet test --collect:""XPlat Code Coverage""",80,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,645,"coverage, requires, coverlet, dotnet, test, collect, xplat, code",1776145405.019363,78,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,"# Run with coverage (requires coverlet) | Run with coverage (requires coverlet) dotnet test --collect:""XPlat Code Coverage" +dotnet test --collect:""XPlat Code Coverage""",80,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,779,"coverage, requires, coverlet, dotnet, test, collect, xplat, code",1779851803.688814,78,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,"# Run with coverage (requires coverlet) | Run with coverage (requires coverlet) dotnet test --collect:""XPlat Code Coverage" doc,"# Filter by test class -dotnet test --filter ""ClassName=PortfolioServiceTests""",83,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,646,"filter, test, class, dotnet, classname, portfolioservicetests",1776145405.019363,81,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,"# Filter by test class | Filter by test class dotnet test --filter ""ClassName=PortfolioServiceTests""" +dotnet test --filter ""ClassName=PortfolioServiceTests""",83,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,780,"filter, test, class, dotnet, classname, portfolioservicetests",1779851803.688814,81,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,"# Filter by test class | Filter by test class dotnet test --filter ""ClassName=PortfolioServiceTests""" doc,"# Filter by test project type dotnet test --filter ""FullyQualifiedName~UnitTests"" dotnet test --filter ""FullyQualifiedName~E2ETests"" ``` +### Code Coverage Script + +A pre-configured batch script is available at the root of the repository to generate line-coverage metrics and an HTML report. + +```powershell",93,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,781,"filter, test, dotnet, fullyqualifiedname, project, type, unittests, powershell",1779851803.688814,84,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,"# Filter by test project type | Filter by test project type dotnet test --filter ""FullyQualifiedName~UnitTests"" " +doc,"# From the repository root +./code-coverage.bat +``` + +> **Requirements**: The script will automatically attempt to install `dotnet-reportgenerator-globaltool` and `coverlet.console` globally if they are not already present. + > ⚠️ **E2E tests** require the full Docker stack running: `docker compose up --build` --- ## 4. Package Management -```bash",95,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,647,"filter, test, dotnet, fullyqualifiedname, project, type, unittests, bash",1776145405.019363,84,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,"# Filter by test project type | Filter by test project type dotnet test --filter ""FullyQualifiedName~UnitTests"" " +```bash",106,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,782,"from, repository, root, code, coverage, bash",1779851803.688814,94,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# From the repository root | From the repository root ./code-coverage.bat > Requirements: The script will aut doc,"# Add a package to a specific project dotnet add InventoryAlert.Api/ package dotnet add InventoryAlert.Domain/ package -dotnet add InventoryAlert.Infrastructure/ package ",100,fab1a764b8fe249391f7ba13740ba2a4,InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,648,"package, dotnet, inventoryalert, packagename, specific, project, domain, infrastructure",1776145405.019363,96,dbcontext periodictimer inventory item postgresql commit xunit efcore iproductservice postgres appdbcontext compose productservice container fluentassertions dockerfile schema change threshold business logic notification add-migration sku backgroundservice atomicity savechanges efcore migration unit test database update hosted service loss arrange act assert application service stock finnhubpricesyncworker price drop asnotracking unitofwork entity framework rollback,# Add a package to a specific project | Add a package to a specific project dotnet add InventoryAlert.Api/ package ",111,d4ac9f096d01e8291bce90bdfdfa03a1,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\dotnet-commands.md,0,783,"package, dotnet, inventoryalert, packagename, specific, project, domain, infrastructure",1779851803.688814,107,postgresql fluentassertions igenericrepository iproductrepository finnhubpricesyncworker xunit container database update iproductservice sku unit test efcore dbcontext price drop inventory productservice hosted service commit add-migration unitofwork atomicity compose periodictimer postgres savechanges entity framework item threshold data access application service efcore migration dbset schema change appdbcontext asnotracking business logic backgroundservice notification stock arrange act assert rollback loss dockerfile,# Add a package to a specific project | Add a package to a specific project dotnet add InventoryAlert.Api/ package sh # Open a shell inside a container ```bash dotnet build -dotnet run --project InventoryAlert.Api",57,35612df4f8a8d14dd6eadecdd7195aed,InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,659,"docker, compose, build, logs, container, bash, rebuild, start",1776145107.1730213,12,asnotracking add-migration finnhubpricesyncworker threshold appdbcontext productservice iproductservice container schema change periodictimer postgresql efcore migration item dockerfile inventory compose hosted service stock xunit dbcontext loss fluentassertions sku entity framework unit test efcore backgroundservice arrange act assert price drop postgres notification business logic application service database update,# From the InventoryManagementSystem/ directory: | From the InventoryManagementSystem/ directory: docker compose up --build | Servi +dotnet run --project InventoryAlert.Api",57,4920540ad8cb72e9cfbbe8f56fc6a338,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,794,"docker, compose, build, logs, container, bash, rebuild, start",1779851803.6948419,12,database update efcore migration iproductservice appdbcontext item stock container productservice dbcontext entity framework application service inventory notification add-migration postgresql loss efcore business logic unit test xunit periodictimer finnhubpricesyncworker dockerfile postgres fluentassertions threshold sku price drop arrange act assert backgroundservice asnotracking schema change compose hosted service,# From the InventoryManagementSystem/ directory: | From the InventoryManagementSystem/ directory: docker compose up --build | Servi doc,"# EF Core Migrations (run from InventoryManagementSystem/) dotnet ef migrations add \ --project InventoryAlert.Api \ @@ -21932,13 +24459,13 @@ dotnet ef database update \ ### Running Tests -```bash",70,35612df4f8a8d14dd6eadecdd7195aed,InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,660,"project, inventoryalert, migrations, dotnet, startup, core, from, inventorymanagementsystem",1776145107.1730213,58,asnotracking add-migration finnhubpricesyncworker threshold appdbcontext productservice iproductservice container schema change periodictimer postgresql efcore migration item dockerfile inventory compose hosted service stock xunit dbcontext loss fluentassertions sku entity framework unit test efcore backgroundservice arrange act assert price drop postgres notification business logic application service database update,# EF Core Migrations (run from InventoryManagementSystem/) | EF Core Migrations (run from InventoryManagementSystem/) dotnet ef migrations ad +```bash",70,4920540ad8cb72e9cfbbe8f56fc6a338,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,795,"project, inventoryalert, migrations, dotnet, startup, core, from, inventorymanagementsystem",1779851803.6948419,58,database update efcore migration iproductservice appdbcontext item stock container productservice dbcontext entity framework application service inventory notification add-migration postgresql loss efcore business logic unit test xunit periodictimer finnhubpricesyncworker dockerfile postgres fluentassertions threshold sku price drop arrange act assert backgroundservice asnotracking schema change compose hosted service,# EF Core Migrations (run from InventoryManagementSystem/) | EF Core Migrations (run from InventoryManagementSystem/) dotnet ef migrations ad doc,"# All tests -dotnet test",73,35612df4f8a8d14dd6eadecdd7195aed,InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,661,"tests, dotnet, test",1776145107.1730213,71,asnotracking add-migration finnhubpricesyncworker threshold appdbcontext productservice iproductservice container schema change periodictimer postgresql efcore migration item dockerfile inventory compose hosted service stock xunit dbcontext loss fluentassertions sku entity framework unit test efcore backgroundservice arrange act assert price drop postgres notification business logic application service database update,# All tests | All tests dotnet test +dotnet test",73,4920540ad8cb72e9cfbbe8f56fc6a338,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,796,"tests, dotnet, test",1779851803.6948419,71,database update efcore migration iproductservice appdbcontext item stock container productservice dbcontext entity framework application service inventory notification add-migration postgresql loss efcore business logic unit test xunit periodictimer finnhubpricesyncworker dockerfile postgres fluentassertions threshold sku price drop arrange act assert backgroundservice asnotracking schema change compose hosted service,# All tests | All tests dotnet test doc,"# Unit tests only -dotnet test --filter ""FullyQualifiedName~InventoryAlert.UnitTests""",76,35612df4f8a8d14dd6eadecdd7195aed,InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,662,"unit, tests, only, dotnet, test, filter, fullyqualifiedname, inventoryalert",1776145107.1730213,74,asnotracking add-migration finnhubpricesyncworker threshold appdbcontext productservice iproductservice container schema change periodictimer postgresql efcore migration item dockerfile inventory compose hosted service stock xunit dbcontext loss fluentassertions sku entity framework unit test efcore backgroundservice arrange act assert price drop postgres notification business logic application service database update,"# Unit tests only | Unit tests only dotnet test --filter ""FullyQualifiedName~InventoryAlert.UnitTest" +dotnet test --filter ""FullyQualifiedName~InventoryAlert.UnitTests""",76,4920540ad8cb72e9cfbbe8f56fc6a338,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,797,"unit, tests, only, dotnet, test, filter, fullyqualifiedname, inventoryalert",1779851803.6948419,74,database update efcore migration iproductservice appdbcontext item stock container productservice dbcontext entity framework application service inventory notification add-migration postgresql loss efcore business logic unit test xunit periodictimer finnhubpricesyncworker dockerfile postgres fluentassertions threshold sku price drop arrange act assert backgroundservice asnotracking schema change compose hosted service,"# Unit tests only | Unit tests only dotnet test --filter ""FullyQualifiedName~InventoryAlert.UnitTest" doc,"# E2E tests (requires running Docker stack) -dotnet test --filter ""FullyQualifiedName~InventoryAlert.E2ETests""",79,35612df4f8a8d14dd6eadecdd7195aed,InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,663,"tests, requires, running, docker, stack, dotnet, test, filter",1776145107.1730213,77,asnotracking add-migration finnhubpricesyncworker threshold appdbcontext productservice iproductservice container schema change periodictimer postgresql efcore migration item dockerfile inventory compose hosted service stock xunit dbcontext loss fluentassertions sku entity framework unit test efcore backgroundservice arrange act assert price drop postgres notification business logic application service database update,"# E2E tests (requires running Docker stack) | E2E tests (requires running Docker stack) dotnet test --filter ""FullyQualifiedNa" +dotnet test --filter ""FullyQualifiedName~InventoryAlert.E2ETests""",79,4920540ad8cb72e9cfbbe8f56fc6a338,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,798,"tests, requires, running, docker, stack, dotnet, test, filter",1779851803.6948419,77,database update efcore migration iproductservice appdbcontext item stock container productservice dbcontext entity framework application service inventory notification add-migration postgresql loss efcore business logic unit test xunit periodictimer finnhubpricesyncworker dockerfile postgres fluentassertions threshold sku price drop arrange act assert backgroundservice asnotracking schema change compose hosted service,"# E2E tests (requires running Docker stack) | E2E tests (requires running Docker stack) dotnet test --filter ""FullyQualifiedNa" doc,"# Integration tests dotnet test --filter ""FullyQualifiedName~InventoryAlert.IntegrationTests"" ``` @@ -21967,21 +24494,99 @@ npm run deploy # Deploy to GitHub Pages docker compose down -v docker compose build --no-cache docker compose up -```",108,35612df4f8a8d14dd6eadecdd7195aed,InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,664,"build, inventoryalert, bash, docker, compose, server, http, localhost",1776145107.1730213,80,asnotracking add-migration finnhubpricesyncworker threshold appdbcontext productservice iproductservice container schema change periodictimer postgresql efcore migration item dockerfile inventory compose hosted service stock xunit dbcontext loss fluentassertions sku entity framework unit test efcore backgroundservice arrange act assert price drop postgres notification business logic application service database update,"# Integration tests | Integration tests dotnet test --filter ""FullyQualifiedName~InventoryAlert.Integr" +```",108,4920540ad8cb72e9cfbbe8f56fc6a338,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\getting-started.md,0,799,"build, inventoryalert, bash, docker, compose, server, http, localhost",1779851803.6948419,80,database update efcore migration iproductservice appdbcontext item stock container productservice dbcontext entity framework application service inventory notification add-migration postgresql loss efcore business logic unit test xunit periodictimer finnhubpricesyncworker dockerfile postgres fluentassertions threshold sku price drop arrange act assert backgroundservice asnotracking schema change compose hosted service,"# Integration tests | Integration tests dotnet test --filter ""FullyQualifiedName~InventoryAlert.Integr" +doc,"# 🧪 Integration Testing Tiers + +InventoryAlert uses a **Three-Tier** architecture within the `InventoryAlert.IntegrationTests` project to balance testing speed with system realism. + +--- + +## 🏗️ Technical Foundation + +All tiers share a unified infrastructure: +- **`TestFixture`**: Manages the lifecycle of Postgres, WireMock, and the Docker Log Reader. +- **`SetupDI.cs`**: Reuses production code (Composition Root) to build the test dependency graph. +- **`Respawn`**: Automatically truncates the database between every test run. +- **`Sequential Execution`**: Enforced via `[Collection(""IntegrationTests"")]` to prevent data collisions. + +--- + +## 🥈 Tier 1: White-box Handler Tests +**Goal:** Verify complex business logic using the real database but mocked external services. + +- **How it works:** Resolves concrete services (e.g., `PortfolioService`) or SQS handlers (e.g., `MarketPriceAlertHandler`) directly from the test `IServiceProvider`. +- **Validation:** + - Direct database assertions using `IUnitOfWork`. + - In-memory log assertions using `TestLoggerProvider` (avoids container scraping). +- **Tooling:** Production DI graph + Moq for third-party mocks. +- **Best For:** Price math, rule evaluation logic, and trade ledger updates. + +--- + +## 🥉 Tier 2: Log-Aware API Tests +**Goal:** Verify the HTTP surface, middleware, and request-response lifecycle. + +- **How it works:** Sends real HTTP requests to the running `inventory-api` container via `RestClient`. +- **Validation:** + - HTTP Status Codes and JSON payloads. + - **Log Correlation**: Scrapes container logs for the specific `X-Correlation-Id` returned in the response. Proves that internal ""invisible"" side-effects occurred. +- **Tooling:** `RestSharp` + `DockerLogReader`. +- **Best For:** Authentication, route parameters, and status code correctness. + +--- + +## 🥇 Tier 3: Whole-Flow Orchestration +**Goal:** Prove absolute application quality by verifying cross-project orchestration. + +- **How it works:** Initiates an action via the API and waits for a side-effect in a different part of the system after background processing. +- **Scenario Example**: + 1. `POST /api/v1/events` (via API). + 2. Event travels through **SQS**. + 3. **Worker** consumes event and processes business logic. + 4. **Worker** updates the database. + 5. Test polls `GET /api/v1/notifications` (via API) to confirm the user sees the result. +- **Tooling:** `WaitHelper` for polling + `WireMock` Admin API for seeding external quotes. +- **Best For:** Proving that the API and Worker projects are correctly integrated via the event bus. + +--- + +## 🛠️ Developer Patterns + +### 1. Mocking External Services (WireMock) +Use the `WireMock` instance in the fixture to define behavior for Finnhub: + +```csharp +Fixture.WireMock + .Given(Request.Create().WithPath(""/quote"").WithParam(""symbol"", ""AAPL"")) + .RespondWith(Response.Create().WithStatusCode(200).WithBody(""{\""c\"": 150}"")); +``` + +### 2. Asserting Internal Logs (Tier 1) +```csharp +AssertLog(""Dispatched real-time notification""); +``` + +### 3. Waiting for Async Results (Tier 3) +```csharp +await WaitHelper.WaitForConditionAsync(async () => { + var res = await Client.GetAsync(""/api/v1/notifications""); + return res.Content.Contains(""AAPL Alert""); +}, timeoutSeconds: 30); +```",78,813f56480e918ce0a38698a0645d4fec,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\integration-testing-tiers.md,0,800,"tier, wiremock, test, database, goal, logic, using, external",1779814416.2415717,1,compose returns async efcore unit test savechangesasync mock setup verify arrange act assert notification sku entity framework market data postgres asnotracking finnhubpricesyncworker quote threshold loss business logic times once container iunitofwork postgresql hosted service application service backgroundservice external api iproductservice stock executetransactionasync periodictimer dockerfile inventory stock price price drop xunit moq dbcontext appdbcontext fluentassertions productservice item,# 🧪 Integration Testing Tiers | 🧪 Integration Testing Tiers InventoryAlert uses a Three-Tier architecture within doc,"# Operational Runbook > Step-by-step troubleshooting guide for common operational issues. ## Service URLs -| Service | URL | Notes | -|---|---|---| -| API (Swagger) | http://localhost:8080/swagger | REST API + interactive docs | -| UI | http://localhost:3000 | Next.js frontend | -| Hangfire | http://localhost:8080/hangfire | Admin only — job dashboard | -| Seq Logs | http://localhost:5341 | Structured log viewer | -| PostgreSQL | localhost:5433 | `psql -h localhost -p 5433 -U postgres` | -| DynamoDB/SQS | localhost:5000 | Moto (local AWS emulator) | +| Service | URL | Notes | +| ------------- | ------------------------------ | --------------------------------------- | +| API (Swagger) | http://localhost:8080/swagger | REST API + interactive docs | +| UI | http://localhost:3000 | Next.js frontend | +| Hangfire | http://localhost:8080/hangfire | Admin only — job dashboard | +| Seq Logs | http://localhost:5341 | Structured log viewer | +| PostgreSQL | localhost:5433 | `psql -h localhost -p 5433 -U postgres` | +| DynamoDB/SQS | localhost:5000 | Moto (local AWS emulator) | --- @@ -22009,9 +24614,9 @@ docker exec -it inventory-worker sh # Enter the Worker container shell ## Verify Database Tables -```bash",42,936c69a9a221a8986db8b236f8b5af33,InventoryAlert.Wiki\docs\07-dev-maintenance\operational-runbook.md,0,665,"localhost, http, service, filter, operational, step, swagger, hangfire",1776145260.2184885,1,stock ticker compose productscontroller efcore migration httpget periodictimer application service finnhubpricesyncworker loss schema change asnotracking add-migration googl database update symbol dbcontext httpput aapl entity framework msft notification appdbcontext external api postgresql market data backgroundservice container iactionresult efcore dockerfile hosted service productservice quote business logic price drop stock price iproductservice httppost postgres threshold,# Operational Runbook | Operational Runbook > Step-by-step troubleshooting guide for common operational +```bash",42,a3e7988e9f52b7aa740a412923fc1445,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\operational-runbook.md,0,801,"localhost, http, service, filter, operational, step, swagger, hangfire",1779851803.680223,1,asnotracking entity framework dockerfile httpget notification external api symbol hosted service efcore iactionresult efcore migration httpput periodictimer httppost compose postgres aapl market data appdbcontext finnhubpricesyncworker quote add-migration business logic postgresql msft stock price stock ticker productservice loss container dbcontext application service backgroundservice schema change googl database update threshold iproductservice productscontroller price drop,# Operational Runbook | Operational Runbook > Step-by-step troubleshooting guide for common operational doc,"# Connect to PostgreSQL inside Docker -docker exec -it inventory-db psql -U postgres -d inventoryalert",45,936c69a9a221a8986db8b236f8b5af33,InventoryAlert.Wiki\docs\07-dev-maintenance\operational-runbook.md,0,666,"docker, connect, postgresql, inside, exec, inventory, psql, postgres",1776145260.2184885,43,stock ticker compose productscontroller efcore migration httpget periodictimer application service finnhubpricesyncworker loss schema change asnotracking add-migration googl database update symbol dbcontext httpput aapl entity framework msft notification appdbcontext external api postgresql market data backgroundservice container iactionresult efcore dockerfile hosted service productservice quote business logic price drop stock price iproductservice httppost postgres threshold,# Connect to PostgreSQL inside Docker | Connect to PostgreSQL inside Docker docker exec -it inventory-db psql -U postgre +docker exec -it inventory-db psql -U postgres -d inventoryalert",45,a3e7988e9f52b7aa740a412923fc1445,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\operational-runbook.md,0,802,"docker, connect, postgresql, inside, exec, inventory, psql, postgres",1779851803.680223,43,asnotracking entity framework dockerfile httpget notification external api symbol hosted service efcore iactionresult efcore migration httpput periodictimer httppost compose postgres aapl market data appdbcontext finnhubpricesyncworker quote add-migration business logic postgresql msft stock price stock ticker productservice loss container dbcontext application service backgroundservice schema change googl database update threshold iproductservice productscontroller price drop,# Connect to PostgreSQL inside Docker | Connect to PostgreSQL inside Docker docker exec -it inventory-db psql -U postgre doc,"# Useful queries SELECT * FROM stock_listings ORDER BY id DESC LIMIT 20; SELECT * FROM alert_rules WHERE is_active = true; @@ -22046,7 +24651,7 @@ FROM trades GROUP BY ticker_symbol; ## Apply EF Core Migrations -```bash",80,936c69a9a221a8986db8b236f8b5af33,InventoryAlert.Wiki\docs\07-dev-maintenance\operational-runbook.md,0,667,"select, from, where, order, desc, limit, quantity, filter",1776145260.2184885,46,stock ticker compose productscontroller efcore migration httpget periodictimer application service finnhubpricesyncworker loss schema change asnotracking add-migration googl database update symbol dbcontext httpput aapl entity framework msft notification appdbcontext external api postgresql market data backgroundservice container iactionresult efcore dockerfile hosted service productservice quote business logic price drop stock price iproductservice httppost postgres threshold,# Useful queries | Useful queries SELECT FROM stock_listings ORDER BY id DESC LIMIT 20; SELECT FR +```bash",80,a3e7988e9f52b7aa740a412923fc1445,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\operational-runbook.md,0,803,"select, from, where, order, desc, limit, quantity, filter",1779851803.680223,46,asnotracking entity framework dockerfile httpget notification external api symbol hosted service efcore iactionresult efcore migration httpput periodictimer httppost compose postgres aapl market data appdbcontext finnhubpricesyncworker quote add-migration business logic postgresql msft stock price stock ticker productservice loss container dbcontext application service backgroundservice schema change googl database update threshold iproductservice productscontroller price drop,# Useful queries | Useful queries SELECT FROM stock_listings ORDER BY id DESC LIMIT 20; SELECT FR doc,"# From InventoryManagementSystem/ directory dotnet ef migrations add \ --project InventoryAlert.Api \ @@ -22076,93 +24681,79 @@ curl -X POST http://localhost:8080/api/v1/stocks/sync \ -H ""Authorization: Bearer "" ``` -Returns `202 Accepted` and enqueues a Hangfire job visible at `/hangfire`.",110,936c69a9a221a8986db8b236f8b5af33,InventoryAlert.Wiki\docs\07-dev-maintenance\operational-runbook.md,0,668,"project, inventoryalert, docker, compose, dotnet, startup, bash, hangfire",1776145260.2184885,81,stock ticker compose productscontroller efcore migration httpget periodictimer application service finnhubpricesyncworker loss schema change asnotracking add-migration googl database update symbol dbcontext httpput aapl entity framework msft notification appdbcontext external api postgresql market data backgroundservice container iactionresult efcore dockerfile hosted service productservice quote business logic price drop stock price iproductservice httppost postgres threshold,# From InventoryManagementSystem/ directory | From InventoryManagementSystem/ directory dotnet ef migrations add u.ExecuteTransactionAsync( - It.IsAny>(), - It.IsAny())) - .Returns, CancellationToken>((action, _) => action()); -``` +--- -### Verify Trade Ledger Calls +## 📈 Measuring Quality: Code Coverage -```csharp -_tradeRepoMock.Verify(r => r.AddAsync(It.Is(t => - t.TickerSymbol == ""AAPL"" && - t.Quantity == 10 && - t.Type == TradeType.Buy && - t.UserId == expectedUserId), - It.IsAny()), - Times.Once); -``` +We use **Coverlet** and **ReportGenerator** to visualize coverage. +- **Script:** Run `./code-coverage.bat` from the root. +- **Target:** **80%+ coverage** in the `Domain` and `Application` layers. -### E2E Test Base Setup +--- -```csharp -// BaseE2ETest.cs — all E2E tests inherit this -protected async Task EnsureAuthenticatedAsync() -{ - var request = new RestRequest(""api/auth/login"", Method.Post); - request.AddJsonBody(new LoginRequest(""admin"", ""password"")); - var response = await Client.ExecuteAsync(request); - JwtToken = response.Data!.AccessToken; -} -``` +## ⚙️ Automated Quality Gates (CI/CD) -### Event Flow Testing (CQRS) -For endpoints that trigger background processes (like `POST /api/v1/events`), E2E testing ensures: -1. The API responds correctly with `202 Accepted`. -2. The infrastructure successfully routed the payload. E2E tests can verify side-effects by waiting a small delay and verifying the final state via a GET request to the read-store. +Every Pull Request is blocked until the following passes: +1. **Build & Lint:** Next.js and .NET 10 compilation. +2. **Architecture Check:** Runs `NetArchTest` rules. +3. **Unit Tests:** Executes isolated logic tests. +4. **Integration Suite:** Spins up the full Docker stack and executes all 3 Tiers of integration tests to prove ""Whole-Flow"" stability. -> ⚠️ **E2E tests require the Docker stack to be running** (`docker compose up --build`). +--- -### Integration Test Database Naming +## 🩺 Runtime Quality (Observability) -```csharp -// Use unique DB name per test class to prevent state bleed -var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(Guid.NewGuid().ToString()) - .Options; -``` +- **Structured Logging (Seq):** Trace single user actions across projects via `CorrelationId`. +- **Health Checks (`/health`):** Active probes for Postgres, Redis, and SQS connectivity. +- **DLQ isolation:** Poison messages are moved to `inventory-event-dlq` to prevent worker crash loops.",66,771c13e14e28a200256716e2e39de5b9,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\test-strategy.md,0,805,"quality, tests, testing, integration, logic, tier, verify, coverage",1779814416.24258,1,backgroundservice notification compose sku returns async dbcontext productservice iproductservice quote price drop httpput mock setup moq times once threshold arrange act assert inventory iactionresult entity framework external api xunit postgresql business logic unit test periodictimer hosted service container httppost asnotracking httpget stock item efcore appdbcontext stock price verify fluentassertions finnhubpricesyncworker application service productscontroller postgres market data dockerfile loss,# 🛡️ Test Structure & Application Quality | 🛡️ Test Structure & Application Quality Quality in InventoryAlert is enforced th +doc,"# Coding Standards & Patterns + +This page focuses on the technical standards and recurring patterns for .NET 10 development in InventoryAlert. + +For a high-level overview of how to test the system, see the **[Test Structure & App Quality](./test-strategy.md)**. +For technical details on the three integration tiers, see **[Integration Testing Tiers](./integration-testing-tiers.md)**. --- @@ -22180,18 +24771,17 @@ var options = new DbContextOptionsBuilder() | **`AsNoTracking()`** | Required on all read-only EF Core queries | | **FluentValidation** | Applied at Web layer only; controllers must not contain inline `if` validation | -## Transaction Capture Pattern +--- -```csharp -// ❌ BAD — blank entity returned if lambda throws -StockListing updated = new(); -await _unitOfWork.ExecuteTransactionAsync(async () => { - updated = await _repo.UpdateAsync(entity); -}, ct); -return MapToResponse(updated); // may map a blank StockListing! +## Common Patterns + +### Transaction Capture Pattern +Ensure results are captured *inside* the transaction block to avoid returning stale or blank entities. + +```csharp // ✅ GOOD — result assigned inside the lambda -PortfolioPositionResponse result = null!; // null-forgiving acceptable here: assigned before read +PortfolioPositionResponse result = null!; await _unitOfWork.ExecuteTransactionAsync(async () => { var updated = await _repo.UpdateAsync(entity); result = MapToResponse(updated); @@ -22199,22 +24789,35 @@ await _unitOfWork.ExecuteTransactionAsync(async () => { return result; ``` -## Git Commit Convention +### Async Polling Helper (Tests) -``` -(): +Used in E2E tests to wait for background worker side-effects. -Types: feat | fix | test | refactor | chore | docs -Scope: domain | application | infrastructure | web | tests +```csharp +await WaitHelper.WaitForConditionAsync(async () => { + var res = await Client.GetAsync(""/api/v1/notifications""); + return res.IsSuccessStatusCode; +}, timeoutSeconds: 15); ``` -Examples: -``` -feat(application): add BulkImport to PortfolioService -fix(infrastructure): remove async keyword from GenericRepository.UpdateAsync -test(application): add E2E coverage for AlertRulesController -refactor(web): extract trade recording to PortfolioService -```",138,40a4e419231b2a9446fb03b9cc78b9df,InventoryAlert.Wiki\docs\07-dev-maintenance\testing-and-standards.md,0,669,"test, testing, tests, inventoryalert, stack, core, docker, must",1776151063.4574015,1,market data application service verify iactionresult external api notification rollback moq fluentassertions commit httppost httpput postgres entity framework efcore dbcontext savechangesasync savechanges iunitofwork price drop quote igenericrepository iproductrepository returns async times once productscontroller mock setup aapl dockerfile productservice iproductservice threshold data access asnotracking business logic msft stock price dbset symbol stock ticker unitofwork httpget atomicity compose postgresql xunit unit test appdbcontext googl executetransactionasync container loss arrange act assert,# Testing & Coding Standards | Testing & Coding Standards Testing Stack - xUnit — Test runner - Moq — Mocking +--- + +## Git Commit Convention + +Follow the standard `type(scope): message` format. + +| Type | Description | +|---|---| +| `feat` | New feature | +| `fix` | Bug fix | +| `test` | Adding or updating tests | +| `refactor` | Code change that neither fixes a bug nor adds a feature | +| `docs` | Documentation only changes | +| `chore` | Maintenance tasks | + +**Scopes**: `domain`, `infra`, `api`, `worker`, `ui`, `tests`. + +*Example: `feat(api): add position bulk import`*",70,c705bfe5ea062e31ee2c359fe629de7a,src\ui\InventoryAlert.Wiki\docs\07-dev-maintenance\testing-and-standards.md,0,806,"test, async, tests, standards, patterns, integration, tiers, only",1779814416.2431607,1,entity framework threshold efcore finnhubpricesyncworker fluentassertions periodictimer xunit appdbcontext unitofwork rollback dbcontext hosted service httppost iactionresult savechangesasync price drop productscontroller savechanges notification loss unit test arrange act assert httpget commit iunitofwork asnotracking executetransactionasync backgroundservice httpput atomicity,# Coding Standards & Patterns | Coding Standards & Patterns This page focuses on the technical standards and rec doc,"# Feature Breakdown > Catalog of all user-facing features in the InventoryAlert UI (v1). @@ -22223,7 +24826,7 @@ doc,"# Feature Breakdown | Feature | Route | Auth | Description | |---|---|---|---| -| **Login** | `/login` | Public | JWT authentication form. 429 rate-limited. | +| **Login** | `/login` | Public | JWT authentication form. | | **Register** | `/register` | Public | New account creation with username + email + password. | | **Dashboard** | `/dashboard` | ✅ | Overview: portfolio summary, watchlist strip, market status, top news, alert badges. | | **Portfolio** | `/portfolio` | ✅ | Paginated position list with search + filter. Cost basis, return %, market value. | @@ -22257,11 +24860,11 @@ flowchart LR ```mermaid flowchart LR A[SyncPricesJob detects breach] --> B[INSERT Notification row] - B --> C[UI polls GET /notifications/unread-count every 30s] + B --> C[UI polls GET /api/v1/notifications/unread-count every 30s] C --> D{Count > 0?} D -- Yes --> E[Bell badge shows red count] E --> F[User opens notification panel] - F --> G[PATCH /notifications/read-all] + F --> G[PATCH /api/v1/notifications/read-all] G --> H[Bell clears] ``` @@ -22288,7 +24891,7 @@ When a user removes a position (`DELETE /api/v1/portfolio/positions/{symbol}`): | User's `WatchlistItem` for symbol | ✅ Deleted | | User's `AlertRule` rows for symbol | ⛔ Blocked (user must delete active rules first — 409) | | Global `StockListing` | ❌ Not touched | -| Global `PriceHistory` | ❌ Not touched |",74,d1dcf5c6e50438629b2d29e7cb692919,InventoryAlert.Wiki\docs\08-frontend-ui\feature-breakdown.md,0,670,"user, symbol, portfolio, alert, search, watchlist, market, position",1776910223.991383,1,msft notification aapl market data threshold symbol quote price drop googl stock price external api loss stock ticker,# Feature Breakdown | Feature Breakdown > Catalog of all user-facing features in the InventoryAlert UI +| Global `PriceHistory` | ❌ Not touched |",74,f953530972e475b2bc22c48e3ae1862d,src\ui\InventoryAlert.Wiki\docs\08-frontend-ui\feature-breakdown.md,0,807,"user, symbol, portfolio, alert, search, watchlist, market, position",1779814416.2437706,1,external api stock price price drop symbol quote notification msft threshold market data googl loss aapl stock ticker,# Feature Breakdown | Feature Breakdown > Catalog of all user-facing features in the InventoryAlert UI doc,"# Frontend Architecture > How the Next.js 15 UI application is structured, fetches data, and manages state against the v2 API. @@ -22302,7 +24905,7 @@ InventoryAlert.UI/ │ │ ├── (auth)/ │ │ │ ├── login/ ← JWT authentication form │ │ │ └── register/ ← New account creation -│ │ ├── dashboard/ ← Portfolio summary, watchlist strip, market status, news +│ │ ├── page.tsx ← Dashboard: Portfolio summary, watchlist strip, market status, news (Route: /) │ │ ├── portfolio/ ← Paginated position list with trade history │ │ │ └── [symbol]/ ← Position detail: chart, trades, alerts │ │ ├── stocks/ ← Global StockListing catalog (browse + search) @@ -22310,6 +24913,8 @@ InventoryAlert.UI/ │ │ ├── watchlist/ ← Live watchlist with quick-add │ │ ├── alerts/ ← Alert rule CRUD with toggle │ │ ├── market/ ← Exchange status, news feed, earnings calendar, IPO calendar +│ │ ├── admin/ ← Admin only pages +│ │ │ └── health/ ← Real-time system health dashboard │ │ └── layout.tsx ← Root layout with Navbar, Sidebar, MarketStatusBanner │ ├── components/ ← Reusable UI components │ ├── hooks/ ← Custom React hooks (useQuote, useNotifications) @@ -22322,7 +24927,7 @@ InventoryAlert.UI/ | Page | Route | Key API Calls | |---|---|---| -| Dashboard | `/dashboard` | `GET /portfolio/positions`, `GET /watchlist/`, `GET /market/status`, `GET /market/news` | +| Dashboard | `/` | `GET /portfolio/positions`, `GET /watchlist/`, `GET /market/status`, `GET /market/news` | | Portfolio | `/portfolio` | `GET /portfolio/positions` (paged), `GET /portfolio/alerts` | | Position Detail | `/portfolio/[symbol]` | `GET /portfolio/positions/{symbol}`, `GET /stocks/{symbol}/quote`, `GET /alertrules/` | | Stock Catalog | `/stocks` | `GET /stocks/` (paged), `GET /stocks/search` | @@ -22330,6 +24935,7 @@ InventoryAlert.UI/ | Watchlist | `/watchlist` | `GET /watchlist/`, `POST /watchlist/{symbol}`, `DELETE /watchlist/{symbol}` | | Alerts | `/alerts` | `GET /alertrules/`, `POST /alertrules/`, `PUT /alertrules/{id}`, `PATCH /alertrules/{id}/toggle` | | Market | `/market` | `GET /market/status`, `/news`, `/calendar/earnings`, `/calendar/ipo`, `/holiday` | +| Admin Health | `/admin/health` | `GET /health` (via proxy or direct) | --- @@ -22392,80 +24998,302 @@ InventoryAlert.UI/ ## Auth Flow in UI -The JWT access token is delivered via JSON body (stored in React Query state). The `httpOnly` refresh token cookie is set server-side by the API on login. The `middleware.ts` file protects all routes under `/dashboard`, `/portfolio`, `/watchlist`, `/stocks`, `/alerts`, and `/market` — redirecting unauthenticated users to `/login`.",104,61da72117caa4a4fe5d6c144e4ef7706,InventoryAlert.Wiki\docs\08-frontend-ui\ui-architecture.md,0,671,"symbol, portfolio, stocks, market, watchlist, alertrules, post, positions",1776910223.9928923,1,efcore threshold external api notification stock price loss dbcontext entity framework asnotracking appdbcontext market data price drop quote,"# Frontend Architecture | Frontend Architecture > How the Next.js 15 UI application is structured, fetches" -doc,"# InventoryAlert — Modern Financial Inventory Ecosystem - -InventoryAlert is a high-performance inventory management and stock monitoring system built with **.NET 10 (Clean Architecture)** and **Next.js 15**. It provides real-time stock price tracking, automated alert evaluation via AWS SQS, and a premium developer experience through a centralized Wiki and Scalar API documentation. +The JWT access token is delivered via JSON body (stored in React Query state). The `httpOnly` refresh token cookie is set server-side by the API on login. The `middleware.ts` file protects all routes under `/dashboard`, `/portfolio`, `/watchlist`, `/stocks`, `/alerts`, and `/market` — redirecting unauthenticated users to `/login`.",107,ff22774684a8c5294ec1986ab51a6d8c,src\ui\InventoryAlert.Wiki\docs\08-frontend-ui\ui-architecture.md,0,808,"symbol, portfolio, stocks, market, watchlist, alertrules, post, positions",1779814416.2437706,1,entity framework external api dbcontext appdbcontext market data price drop efcore asnotracking stock price quote loss notification threshold,"# Frontend Architecture | Frontend Architecture > How the Next.js 15 UI application is structured, fetches" +code,,45,0fa94973d0a34debd2260c50cbd9afb1,src\ui\InventoryAlert.Wiki\src\components\HomepageFeatures\index.tsx,0,809,HomepageFeatures/indexx,1779814416.2498028,1,asnotracking price drop notification loss efcore appdbcontext finnhubpricesyncworker backgroundservice external api threshold entity framework hosted service stock price market data periodictimer quote dbcontext,[MOD] HomepageFeatures/indexx +code,,59,0fa94973d0a34debd2260c50cbd9afb1,src\ui\InventoryAlert.Wiki\src\components\HomepageFeatures\index.tsx,0,810,HomepageFeatures/indexx,1779814416.2498028,46,asnotracking price drop notification loss efcore appdbcontext finnhubpricesyncworker backgroundservice external api threshold entity framework hosted service stock price market data periodictimer quote dbcontext,[FUNC] HomepageFeatures/indexx/function Feature +code,,72,0fa94973d0a34debd2260c50cbd9afb1,src\ui\InventoryAlert.Wiki\src\components\HomepageFeatures\index.tsx,0,811,HomepageFeatures/indexx,1779814416.2498028,60,asnotracking price drop notification loss efcore appdbcontext finnhubpricesyncworker backgroundservice external api threshold entity framework hosted service stock price market data periodictimer quote dbcontext,[FUNC] HomepageFeatures/indexx/default function HomepageFeatures +doc,"# InventoryAlert — Inventory & Stock Alerting System ---- +InventoryAlert is a full-stack inventory management and stock monitoring system built with **.NET 10** and **Next.js 15**. It tracks stock prices via Finnhub, evaluates user-defined rules, and delivers in-app notifications (SignalR), with documentation published via Docusaurus and GitHub Actions. -## 🏗 Architecture Overview +## Repository layout -The system is designed with strict **Domain-Driven Design (DDD)** principles and distributed observer patterns: +- `InventoryManagementSystem/` — .NET solution (`InventoryManagementSystem.sln`) +- `InventoryAlert.UI/` — Next.js UI +- `InventoryAlert.Wiki/` — Docusaurus docs site (source in `InventoryAlert.Wiki/docs/`) +- `doc/` — internal engineering docs and audits -- **Api (.NET 10)**: High-throughput REST interface with JWT security and Scalar documentation. -- **Worker (.NET 10)**: Background engine handling Hangfire schedulers and AWS SQS consumers for price alerts. -- **Contracts**: Shared library for entities, common exceptions, and bus events to ensure zero circular dependencies. -- **UI (Next.js 15)**: OLED-themed dashboard using Tailwind CSS v4 and Nextra for the system Wiki. -- **Infrastructure**: Powered by **PostgreSQL** (Relational), **Redis** (Cache/Hangfire), and **Seq** (Structured Logging). +## Quick start (development) ---- +Prereqs: Docker, .NET 10 SDK, Node.js 20. -## 🚀 Quick Start (Development) +### 1) Infrastructure (Docker) -### 1. Infrastructure (One-Click Docker) -Spin up the database, cache, AWS emulator (LocalStack), and logging server: -```powershell",23,15405f6ed35b8b5637da15f108697bf3,README.md,0,672,"system, inventoryalert, inventory, high, stock, architecture, next, price",1775670096.6278808,1,hosted service entity framework backgroundservice loss infrastructure savechanges application service domain entity domain driven design business logic compose finnhubpricesyncworker rollback commit container price drop atomicity efcore appdbcontext iproductservice asnotracking dbcontext threshold notification application layer unitofwork dockerfile periodictimer productservice postgresql postgres,# InventoryAlert — Modern Financial Inventory Ecosystem | InventoryAlert — Modern Financial Inventory Ecosystem InventoryAlert is a high-p -doc,"# Navigate to solution folder +```powershell cd InventoryManagementSystem docker compose up -d db redis moto moto-init seq ``` -### 2. Backend (API & Worker) -Run the core services from the root folder: -```powershell",31,15405f6ed35b8b5637da15f108697bf3,README.md,0,673,"moto, navigate, solution, folder, inventorymanagementsystem, docker, compose, redis",1775670096.6278808,24,hosted service entity framework backgroundservice loss infrastructure savechanges application service domain entity domain driven design business logic compose finnhubpricesyncworker rollback commit container price drop atomicity efcore appdbcontext iproductservice asnotracking dbcontext threshold notification application layer unitofwork dockerfile periodictimer productservice postgresql postgres,# Navigate to solution folder | Navigate to solution folder cd InventoryManagementSystem docker compose up -d db -doc,"# Run API -dotnet run --project InventoryManagementSystem/InventoryAlert.Api",34,15405f6ed35b8b5637da15f108697bf3,README.md,0,674,"dotnet, project, inventorymanagementsystem, inventoryalert",1775670096.6278808,32,hosted service entity framework backgroundservice loss infrastructure savechanges application service domain entity domain driven design business logic compose finnhubpricesyncworker rollback commit container price drop atomicity efcore appdbcontext iproductservice asnotracking dbcontext threshold notification application layer unitofwork dockerfile periodictimer productservice postgresql postgres,# Run API | Run API dotnet run --project InventoryManagementSystem/InventoryAlert.Api -doc,"# Run Worker +### 2) Backend (API + Worker) + +```powershell +dotnet run --project InventoryManagementSystem/InventoryAlert.Api dotnet run --project InventoryManagementSystem/InventoryAlert.Worker ``` -- **API Health**: `http://localhost:5294/health` -- **Interactive API Docs (Scalar)**: `http://localhost:5294/scalar/v1` -### 3. Frontend (UI & Wiki) +- API health: `http://localhost:5294/health` +- Swagger UI: `http://localhost:5294/swagger` +- Scalar API reference: `http://localhost:5294/scalar/v1` + +### 3) Frontend (UI) + ```powershell cd InventoryAlert.UI npm install npm run dev ``` -- **Dashboard**: `http://localhost:3000` -- **Project Wiki**: `http://localhost:3000/docs` + +- UI: `http://localhost:3000` + +### 4) Documentation (Docusaurus) + +```powershell +cd InventoryAlert.Wiki +npm ci +npm run start +``` + +- Wiki site: `http://localhost:3001` + +## Documentation publishing + +- GitHub Pages (Docusaurus): `.github/workflows/deploy-wiki.yml` +- GitHub Wiki sync (markdown export): `.github/workflows/sync-github-wiki.yml` + +## Observability + +- Seq: `http://localhost:5341` + +## Tech stack (actual) + +- Backend: C# 12, .NET 10, EF Core, Hangfire, FluentValidation, SignalR, Scalar + Swagger +- Frontend: React 19, Next.js 15 +- Infra: PostgreSQL, Redis, Moto (AWS emulator), Seq + +## Docs rule + +If you change a domain entity, endpoint, or execution flow, update the matching page under `InventoryAlert.Wiki/docs/` (and keep `doc/` references in sync when applicable).",71,0045da2fee96d2f8a75fea56b3378702,README.md,0,812,"wiki, inventoryalert, github, http, localhost, docs, docusaurus, stock",1779851803.6592581,1,loss postgresql appdbcontext postgres finnhubpricesyncworker quote data access dbcontext market data backgroundservice iproductrepository hosted service periodictimer entity framework dockerfile price drop asnotracking threshold external api compose notification efcore dbset container igenericrepository stock price,# InventoryAlert — Inventory & Stock Alerting System | InventoryAlert — Inventory & Stock Alerting System InventoryAlert is a full-stac +doc,"# Refactoring Suggestions for InventoryAlert + +Last reviewed: **2026-04-30** + +This document is a prioritized set of refactoring suggestions to improve maintainability, testability, and runtime performance for: + +- `InventoryManagementSystem/InventoryAlert.Api` +- `InventoryManagementSystem/InventoryAlert.Worker` + +It is based on the current source code shape (not generic advice). Where possible, each recommendation includes concrete targets (files/classes), a suggested approach, and “done” criteria. + +## Quick prioritization + +If you only do a few things, do these first: + +1. Fix the **N+1 + sequential IO** in `PortfolioService.GetPositionsPagedAsync` (largest user-facing latency win). +2. Extract a small **Redis cache helper** (biggest maintainability win in `StockDataService`). +3. Introduce a consistent **application error contract** (reduce “mystery 500s” and improve client UX). + +## Current observations (ground truth) + +- `StockDataService` mixes **Finnhub calls + Redis caching + Postgres UoW + Dynamo news repos + symbol discovery**. (`InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs`) +- `PortfolioService.GetPositionsPagedAsync` loops and calls `GetPositionBySymbolAsync` per symbol, which performs multiple queries and an external quote call per item. (`InventoryManagementSystem/InventoryAlert.Api/Services/PortfolioService.cs`) +- `SyncPricesJob` already has some decoupling via `IAlertRuleEvaluator` + `IAlertNotifier`, but still runs a “fetch → evaluate → persist → notify” pipeline inside one job. (`InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs`) +- `IUnitOfWork` aggregates many repositories, increasing coupling across modules. (`InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IUnitOfWork.cs`) +- The `.Result` mentioned previously in `StockDataService` is **not** a sync wait; it is a property access (`raw?.Result`) from Finnhub’s search response DTO. (`InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs`) + +--- + +## 1) Architectural improvements + +### 1.1 Decompose `StockDataService` (SRP boundary) + +**Target** +- `InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs` +- Consumers: controllers + services using `IStockDataService` (e.g., `StocksController`, `MarketController`, `PortfolioService`, `WatchlistService`, `AlertRuleService`) + +**Problem** +- The service owns too many axes of change (cache policy, Finnhub API mapping, local DB discovery, Dynamo news read models). +- This makes unit tests coarse-grained and encourages copy/paste caching patterns. + +**Suggested split (incremental, low-risk)** +- Keep `IStockDataService` for now, but internally delegate to smaller components so you can migrate consumers later: + - `ISymbolDiscoveryService` (DB lookup + Finnhub profile + persist listing) + - `IQuoteService` (quote cache + Finnhub quote) + - `IMarketCalendarService` (holidays, earnings/IPO calendars) + - `INewsReadService` (market + company news via Dynamo repos) + - `IIntelligenceReadService` (metrics/earnings/recommendations/insiders sourced from Postgres repos) + +**Definition of done** +- `StockDataService` becomes a thin facade that composes smaller services (or is removed entirely in favor of those interfaces). +- Each component can be unit-tested with a single external dependency mocked (Finnhub OR Redis OR UoW). + +**Notes** +- Avoid a “big bang rename”. Introduce delegates first, then gradually update controllers/services to depend on the smaller interfaces. + +### 1.2 Modularize `IUnitOfWork` (reduce coupling) + +**Target** +- `InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IUnitOfWork.cs` + +**Problem** +- One interface contains repositories for unrelated concerns (portfolio, market intelligence, notifications, etc.). +- This increases the blast radius: a service that needs `Trades` accidentally “sees” `Insiders`, `Recommendations`, etc. + +**Options (choose one)** + +**Option A — Split UoW by domain slice (recommended if you want strict boundaries)** +- `IPortfolioUnitOfWork`: Trades, WatchlistItems, StockListings (maybe), AlertRules (maybe) +- `IMarketIntelligenceUnitOfWork`: StockListings, Metrics, Earnings, Recommendations, Insiders, PriceHistories +- `INotificationUnitOfWork`: Notifications, AlertRules (read) + +**Option B — Keep UoW, but narrow injection** +- Prefer injecting repositories directly into services unless a transaction is required. +- Reserve UoW injection for transactional operations only. + +**Definition of done** +- New services do not inject the full `IUnitOfWork` by default. +- Transaction usage becomes explicit and localized. + +### 1.3 Strengthen the `SyncPricesJob` pipeline boundaries (already partially done) + +**Target** +- `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs` + +**What’s already good** +- Fetch is parallelized with `MaxDegreeOfParallelism`. +- Alert logic is delegated via `IAlertRuleEvaluator`. +- Delivery is delegated via `IAlertNotifier`. + +**Remaining issues** +- Notifications are sent inline after DB operations; transient SignalR issues can slow the job. +- Persist and notify are tightly coupled; you can’t easily retry notification delivery independently. + +**Suggested enhancement (incremental)** +- Persist notifications first, then publish delivery asynchronously: + - Option A: enqueue a Hangfire background job per notification (or per batch) to call `_notifier.NotifyAsync`. + - Option B: implement an Outbox table / delivery status and a separate delivery worker. + +**Definition of done** +- Price sync succeeds even if SignalR delivery is temporarily failing. +- Notification delivery has dedicated retries/observability. --- -## 📚 Documentation & Observability +## 2) Performance optimizations + +### 2.1 Fix the N+1 + sequential IO in `PortfolioService.GetPositionsPagedAsync` + +**Target** +- `InventoryManagementSystem/InventoryAlert.Api/Services/PortfolioService.cs` + +**Problem** +- `GetPositionsPagedAsync` loops `pagedItems` and calls `GetPositionBySymbolAsync` sequentially. +- Each call can trigger: + - Trades fetch (`GetByUserAndSymbolAsync`) + - Watchlist check (`GetByUserAndSymbolAsync`) when no trades exist + - Listing fetch (`FindBySymbolAsync`) + - Quote fetch (`IStockDataService.GetQuoteAsync`) which may hit Finnhub + +**Suggested approach (two-step, safe)** +1. **Batch DB reads** for the paged symbols: + - Trades for all symbols for user (single query) + - Listings for all symbols (single query) + - Watchlist items already loaded can be reused +2. **Batch quote reads**: + - Add `GetQuotesAsync(IEnumerable)` to `IStockDataService` (or a new quote service) that returns a dictionary. + - Internally: use Redis multi-get + controlled Finnhub fan-out. + +**Definition of done** +- `GetPositionsPagedAsync` performs O(1) DB round-trips per page (not per item). +- Quotes are fetched with bounded concurrency and cached consistently. + +### 2.2 Extract and standardize caching policy (reduce duplication + mistakes) + +**Target** +- `InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs` + +**Problem** +- Cache read/deserialize/fallback/write is repeated across multiple methods with minor variations. + +**Suggested approach** +- Introduce a small helper, e.g. `ICacheStore` or `RedisCacheClient` with: + - `GetOrSetAsync(key, ttl, factory)` + - consistent JSON options (`JsonOptions.Default`) + - optional “negative cache” for missing symbols (avoid hammering Finnhub on unknown tickers) + +**Definition of done** +- Cache logic becomes one-liners; TTLs are declared next to the method behavior, not repeated mechanics. + +### 2.3 Finnhub rate limiting + resilience -### System Wiki -The built-in Wiki provides deep-dives into: -- **Execution Flows**: Authentication and Alert evaluation sequences. -- **Database Model**: ERD and persistence strategy. -- **AI Agent Guide**: Protocol for coding assistants (Transaction patterns, async rules). +**Target** +- `InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs` +- `InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs` -### Monitoring (Seq) -All internal messages and errors are streamed to **Seq** for real-time observability. -- **URL**: `http://localhost:5341` -- **Tracing**: Every request includes a `CorrelationId` that propagates from the API through SNS/SQS to the Worker. +**Current state** +- Worker uses `MaxDegreeOfParallelism` to reduce pressure, but that isn’t an actual rate limiter. + +**Suggested approach** +- Implement a shared rate limiter around Finnhub calls: + - Token bucket / fixed window limiter (per API key), shared per process. + - Add retry/backoff for transient 429/5xx via Polly. + +**Definition of done** +- Large symbol catalog does not cause sustained 429s and does not stall the worker. --- -## 🛠 Tech Stack -- **Backend**: C# 12, .NET 10, EF Core, Hangfire, MediatR, FluentValidation. -- **Frontend**: React 19, Next.js 15 (App Router), Tailwind CSS v4, Lucide Icons, Nextra. -- **Observability**: Serilog, Seq, OpenTelemetry. -- **Cloud/Infra**: PostgreSQL, Redis, AWS SNS/SQS (LocalStack/Moto). +## 3) Clean code & maintainability + +### 3.1 Standardize business-rule errors (avoid `InvalidOperationException` for user-facing issues) + +**Targets** +- `InventoryManagementSystem/InventoryAlert.Api/Services/PortfolioService.cs` (uses `InvalidOperationException` for expected domain rules) +- `InventoryManagementSystem/InventoryAlert.Api/Services/AuthService.cs` (uses `UserFriendlyException` with error codes) + +**Problem** +- Mixing exception types makes it hard to guarantee consistent HTTP responses and error bodies. + +**Suggested approach** +- Define a small set of app exceptions (or a Result type) that map to a stable API error contract: + - `NotFound`, `Conflict`, `Validation`, `Unauthorized`, `Forbidden`, `UnprocessableEntity` +- Update service layer to throw those exceptions for expected conditions; reserve `InvalidOperationException` for programmer errors. + +**Definition of done** +- API clients can reliably parse `errorCode` / `userFriendlyMessage` and render consistent UX. + +### 3.2 Centralize cache keys and TTLs + +**Target** +- `InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs` (keys like `quote:{symbol}`, `metrics:{symbol}`, `search:{query}`) + +**Suggested approach** +- Create `CacheKeys` (and optionally `CacheTtls`) in Domain or Api constants: + - `CacheKeys.Quote(symbol)` + - `CacheKeys.Metrics(symbol)` + - `CacheKeys.SymbolSearch(query)` + +**Definition of done** +- No “magic key strings” remain in business services. + +### 3.3 Encapsulate portfolio calculations + +**Target** +- `InventoryManagementSystem/InventoryAlert.Api/Services/PortfolioService.cs` (net holdings, avg price, returns) + +**Suggested approach** +- Extract calculation logic to: + - a domain service `IPortfolioCalculator`, or + - a pure helper in Domain layer (so it’s testable without DB/IO) + +**Definition of done** +- Portfolio math has dedicated unit tests and no longer mixes with DB/HTTP/cache concerns. --- -## 📜 Maintenance Flow -Changes affecting the core architecture should follow the **Boy Scout Rule for Docs**: If you update a domain entity or a business flow, always update the corresponding entry in the [Project Wiki](./InventoryAlert.UI/src/pages/docs).",76,15405f6ed35b8b5637da15f108697bf3,README.md,0,675,"wiki, worker, project, inventoryalert, http, localhost, docs, observability",1775670096.6278808,35,hosted service entity framework backgroundservice loss infrastructure savechanges application service domain entity domain driven design business logic compose finnhubpricesyncworker rollback commit container price drop atomicity efcore appdbcontext iproductservice asnotracking dbcontext threshold notification application layer unitofwork dockerfile periodictimer productservice postgresql postgres,# Run Worker | Run Worker dotnet run --project InventoryManagementSystem/InventoryAlert.Worker -code,,30,d846e3d2e9fa39e539bfd9b68c5a549d,skills-lock.json,0,676,skills-lock.json,1775284654.147763,1,asnotracking entity framework appdbcontext efcore dbcontext,[MOD] skills-lock.json +## Proposed “refactor milestones” (optional) + +1. **Performance pass (1–2 days)**: Batch reads in `PortfolioService` + add quote batching. +2. **Maintainability pass (1–2 days)**: Cache helper + centralized keys/TTLs. +3. **Reliability pass (2–4 days)**: Finnhub rate limiter + SyncPrices pipeline hardening. +4. **Architecture pass (ongoing)**: Decompose `StockDataService` + narrow `IUnitOfWork` usage.",223,765c358f49eaf6f71e27ae2ff2bd7b27,REFACTORING_SUGGESTIONS.md,0,813,"inventoryalert, inventorymanagementsystem, services, stockdataservice, finnhub, done, suggested, portfolioservice",1779851803.6592581,1,entity framework httpget mock setup notification loss efcore hosted service unit test symbol atomicity price drop savechanges business logic finnhubpricesyncworker executetransactionasync moq aapl verify unitofwork httpput rollback productscontroller stock price market data savechangesasync iproductservice xunit iunitofwork productservice appdbcontext returns async iactionresult periodictimer commit googl dbcontext external api quote fluentassertions application service times once threshold arrange act assert backgroundservice asnotracking msft stock ticker httppost,# Refactoring Suggestions for InventoryAlert | Refactoring Suggestions for InventoryAlert Last reviewed: 2026-04-30 This docume +code,,30,0c4ecfa5bd6863b8816c802106af51a9,skills-lock.json,0,814,skills-lock.json,1779814416.4053197,1,entity framework dbcontext appdbcontext efcore asnotracking,[MOD] skills-lock.json diff --git a/.agents/skills/db-migration/SKILL.md b/.agents/skills/db-migration/SKILL.md index 28d8031..616be9e 100644 --- a/.agents/skills/db-migration/SKILL.md +++ b/.agents/skills/db-migration/SKILL.md @@ -33,9 +33,9 @@ tags: [workflow, migration, efcore, database, postgresql, inventoryalert] ## Prerequisites - `dotnet-ef` installed: `dotnet tool install -g dotnet-ef` -- PostgreSQL running: `docker-compose up postgres -d` +- PostgreSQL running: `docker compose up db -d` - `appsettings.Development.json` has valid `Database.DefaultConnection` -- Working directory: solution root `InventoryManagementSystem/` +- Working directory: `src/` --- @@ -63,7 +63,7 @@ dotnet ef migrations add AddNotificationDetails --project InventoryAlert.Infrast ### 3. Review the generated migration -Open `InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/_.cs`: +Open `src/InventoryAlert.Infrastructure/Migrations/_.cs`: - `Up()` — adds/changes exactly what you intended - `Down()` — correctly reverses it @@ -108,7 +108,7 @@ dotnet ef migrations remove --project InventoryAlert.Infrastructure --startup-pr | Error | Fix | |-------|-----| -| `No DbContext was found` | Run from `InventoryManagementSystem/`, use `--project InventoryAlert.Api` | +| `No DbContext was found` | Run from `src/`, use `--project InventoryAlert.Infrastructure --startup-project InventoryAlert.Api` | | `Connection refused` | `docker-compose up postgres -d` | | `Pending model changes` | Run `dotnet ef migrations add` to capture drift | | `MSB4066 Include attribute` | Fix nested `` in `.csproj` | diff --git a/.agents/skills/run-tests/SKILL.md b/.agents/skills/run-tests/SKILL.md index 085b322..a7a8ace 100644 --- a/.agents/skills/run-tests/SKILL.md +++ b/.agents/skills/run-tests/SKILL.md @@ -32,7 +32,7 @@ tags: [workflow, tests, xunit, coverage, inventoryalert] ## Prerequisites -- `InventoryManagementSystem/` as working directory +- Root directory as working directory - Packages: `xunit`, `Moq`, `FluentAssertions`, `EF InMemory` (all in `.csproj`) --- @@ -49,29 +49,29 @@ dotnet build --no-restore ### 2. Run all tests ```bash -dotnet test InventoryManagementSystem --no-build --verbosity normal +dotnet test src/InventoryManagementSystem.sln --no-build --verbosity normal ``` ### 3. Run by test class ```bash -dotnet test InventoryManagementSystem --no-build --filter "FullyQualifiedName~PortfolioServiceTests" -dotnet test InventoryManagementSystem --no-build --filter "FullyQualifiedName~StockDataServiceTests" -dotnet test InventoryManagementSystem --no-build --filter "FullyQualifiedName~AlertRuleServiceTests" -dotnet test InventoryManagementSystem --no-build --filter "FullyQualifiedName~WatchlistControllerTests" -dotnet test InventoryManagementSystem --no-build --filter "FullyQualifiedName~GenericRepositoryTests" +dotnet test src/InventoryManagementSystem.sln --no-build --filter "FullyQualifiedName~PortfolioServiceTests" +dotnet test src/InventoryManagementSystem.sln --no-build --filter "FullyQualifiedName~StockDataServiceTests" +dotnet test src/InventoryManagementSystem.sln --no-build --filter "FullyQualifiedName~AlertRuleServiceTests" +dotnet test src/InventoryManagementSystem.sln --no-build --filter "FullyQualifiedName~WatchlistControllerTests" +dotnet test src/InventoryManagementSystem.sln --no-build --filter "FullyQualifiedName~GenericRepositoryTests" ``` ### 4. Run by method name ```bash -dotnet test InventoryManagementSystem --no-build --filter "FullyQualifiedName~GetQuote_ReturnsCachedResult_WhenAvailable" +dotnet test src/InventoryManagementSystem.sln --no-build --filter "FullyQualifiedName~GetQuote_ReturnsCachedResult_WhenAvailable" ``` ### 5. Run with coverage (HTML report) ```bash -dotnet test InventoryManagementSystem --no-build --collect:"XPlat Code Coverage" --results-directory ./TestResults +dotnet test src/InventoryManagementSystem.sln --no-build --collect:"XPlat Code Coverage" --results-directory ./TestResults dotnet tool install -g dotnet-reportgenerator-globaltool reportgenerator -reports:"./TestResults/**/coverage.cobertura.xml" -targetdir:"./TestResults/CoverageReport" -reporttypes:Html start ./TestResults/CoverageReport/index.html diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..4ee2439 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,25 @@ +version: 2 +updates: + # NuGet dependencies + - package-ecosystem: "nuget" + directory: "/src" + schedule: + interval: "weekly" + + # UI Project NPM dependencies + - package-ecosystem: "npm" + directory: "/src/ui/InventoryAlert.UI" + schedule: + interval: "weekly" + + # Wiki Project NPM dependencies + - package-ecosystem: "npm" + directory: "/src/ui/InventoryAlert.Wiki" + schedule: + interval: "weekly" + + # GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 942b289..3f0ba82 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,17 +20,17 @@ jobs: dotnet-version: '10.0.x' - name: Restore dependencies (.NET) - run: dotnet restore InventoryManagementSystem/InventoryManagementSystem.sln + run: dotnet restore src/InventoryManagementSystem.sln - name: Build (.NET) - run: dotnet build InventoryManagementSystem/InventoryManagementSystem.sln --no-restore --configuration Release + run: dotnet build src/InventoryManagementSystem.sln --no-restore --configuration Release - name: Architecture Test - run: dotnet test InventoryManagementSystem/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj --no-restore --no-build --configuration Release --verbosity normal + run: dotnet test src/test/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj --no-restore --no-build --configuration Release --verbosity normal - name: Unit Test & Coverage run: | - dotnet test InventoryManagementSystem/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj \ + dotnet test src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj \ --no-restore --no-build --configuration Release \ --verbosity normal \ --collect:"XPlat Code Coverage" \ @@ -60,32 +60,32 @@ jobs: with: node-version: '20' cache: 'npm' - cache-dependency-path: InventoryAlert.UI/package-lock.json + cache-dependency-path: src/ui/InventoryAlert.UI/package-lock.json - name: Install UI dependencies run: npm ci - working-directory: InventoryAlert.UI + working-directory: src/ui/InventoryAlert.UI - name: UI Lint run: npm run lint - working-directory: InventoryAlert.UI + working-directory: src/ui/InventoryAlert.UI - name: UI Test run: npm run test - working-directory: InventoryAlert.UI + working-directory: src/ui/InventoryAlert.UI # ── Docker Integration & E2E Tests ────────────────────────────────────────────── - name: Seed Configuration Files (CI) run: | cp InventoryAlert.Api/appsettings.Example.json InventoryAlert.Api/appsettings.json cp InventoryAlert.Worker/appsettings.Example.json InventoryAlert.Worker/appsettings.json - working-directory: InventoryManagementSystem + working-directory: src - name: Start Docker Stack id: start-docker run: | docker compose up -d --build || (echo "Docker Compose failed to start" && docker ps -a && docker compose logs api && docker compose logs db && exit 1) - working-directory: InventoryManagementSystem + working-directory: src - name: Wait for Services Health (API & Worker) run: | @@ -107,24 +107,23 @@ jobs: docker compose logs worker exit 1 shell: bash - working-directory: InventoryManagementSystem + working-directory: src - 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 --filter Category=Api + cp src/test/InventoryAlert.IntegrationTests/appsettings.test.json appsettings.test.json + dotnet test src/test/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 + cp src/test/InventoryAlert.IntegrationTests/appsettings.test.json appsettings.test.json + dotnet test src/test/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 - working-directory: InventoryManagementSystem + run: dotnet test src/test/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj --no-restore --configuration Release --verbosity normal - name: Docker Cleanup if: always() run: docker compose down -v --rmi local - working-directory: InventoryManagementSystem + working-directory: src diff --git a/.github/workflows/deploy-wiki.yml b/.github/workflows/deploy-wiki.yml index ca3a3eb..f004e2c 100644 --- a/.github/workflows/deploy-wiki.yml +++ b/.github/workflows/deploy-wiki.yml @@ -4,12 +4,12 @@ on: push: branches: [ "main" ] paths: - - 'InventoryAlert.Wiki/**' + - 'src/ui/InventoryAlert.Wiki/**' - '.github/workflows/deploy-wiki.yml' pull_request: branches: [ "main" ] paths: - - 'InventoryAlert.Wiki/**' + - 'src/ui/InventoryAlert.Wiki/**' - '.github/workflows/deploy-wiki.yml' workflow_dispatch: @@ -28,26 +28,26 @@ jobs: with: node-version: '20' cache: 'npm' - cache-dependency-path: InventoryAlert.Wiki/package-lock.json + cache-dependency-path: src/ui/InventoryAlert.Wiki/package-lock.json - name: Install dependencies run: npm ci - working-directory: InventoryAlert.Wiki + working-directory: src/ui/InventoryAlert.Wiki - name: Build Docusaurus run: npm run build - working-directory: InventoryAlert.Wiki + working-directory: src/ui/InventoryAlert.Wiki # This prevents GitHub from running Jekyll on the 'gh-pages' branch - name: Create .nojekyll - run: touch InventoryAlert.Wiki/build/.nojekyll + run: touch src/ui/InventoryAlert.Wiki/build/.nojekyll - name: Deploy to GitHub Pages if: github.event_name != 'pull_request' uses: peaceiris/actions-gh-pages@v4 with: github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./InventoryAlert.Wiki/build + publish_dir: ./src/ui/InventoryAlert.Wiki/build force_orphan: true user_name: 'github-actions[bot]' user_email: 'github-actions[bot]@users.noreply.github.com' diff --git a/.github/workflows/sync-github-wiki.yml b/.github/workflows/sync-github-wiki.yml index a092147..34844b3 100644 --- a/.github/workflows/sync-github-wiki.yml +++ b/.github/workflows/sync-github-wiki.yml @@ -7,13 +7,13 @@ on: - "refactor/**" - "feature/**" paths: - - "InventoryAlert.Wiki/docs/**" + - "src/ui/InventoryAlert.Wiki/docs/**" - ".github/workflows/sync-github-wiki.yml" pull_request: branches: [ "main" ] paths: - - "InventoryAlert.Wiki/docs/**" + - "src/ui/InventoryAlert.Wiki/docs/**" workflow_dispatch: @@ -56,7 +56,7 @@ jobs: git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" git add . - git commit -m "Sync wiki from InventoryAlert.Wiki/docs" + git commit -m "Sync wiki from src/ui/InventoryAlert.Wiki/docs" git push else echo "No changes to commit." diff --git a/code-coverage.bat b/code-coverage.bat index 7578364..de5220e 100644 --- a/code-coverage.bat +++ b/code-coverage.bat @@ -3,7 +3,7 @@ REM ======================== REM Set Tools & Paths REM ======================== SET "dotnet=dotnet" -SET "testproject=./InventoryManagementSystem/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj" +SET "testproject=./src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj" SET "coveragedir=./coverage/" echo [info] Ensuring tools are installed... diff --git a/coverage/html/InventoryAlert.Api_ApiLoggingMiddleware.html b/coverage/html/InventoryAlert.Api_ApiLoggingMiddleware.html new file mode 100644 index 0000000..f31ed56 --- /dev/null +++ b/coverage/html/InventoryAlert.Api_ApiLoggingMiddleware.html @@ -0,0 +1,283 @@ + + + + + + + +InventoryAlert.Api.Middleware.ApiLoggingMiddleware - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Api.Middleware.ApiLoggingMiddleware
Assembly:InventoryAlert.Api
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Api\Middleware\ApiLoggingMiddleware.cs
+
+
+
+
+
+
+
Line coverage
+
+
92%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:76
Uncovered lines:6
Coverable lines:82
Total lines:140
Line coverage:92.6%
+
+
+
+
+
Branch coverage
+
+
67%
+
+ + + + + + + + + + + + + +
Covered branches:31
Total branches:46
Branch coverage:67.3%
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%22100%
InvokeAsync()66.66%66100%
LogMinimal(...)62.5%88100%
LogFull(...)91.66%1212100%
TryParseJson(...)100%22100%
ToObject(...)20%201053.84%
ReadStreamAsync()100%66100%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Api\Middleware\ApiLoggingMiddleware.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using System.Diagnostics;
 2using System.Security.Claims;
 3using System.Text;
 4using System.Text.Json;
 5using InventoryAlert.Domain.Configuration;
 6using InventoryAlert.Infrastructure.Utilities;
 7
 8namespace InventoryAlert.Api.Middleware;
 9
 10/// <summary>
 11/// Unified logging middleware that captures:
 12/// 1. Request &amp; Response bodies (if JSON)
 13/// 2. Execution time (ElapsedMs)
 14/// 3. User &amp; Correlation context
 15/// All in a single structured Seq event.
 16/// </summary>
 917public class ApiLoggingMiddleware(ILogger<ApiLoggingMiddleware> logger, AppSettings settings) : IMiddleware
 18{
 919    private readonly bool _enableBodyLogging = settings.Api?.EnableBodyLogging ?? true;
 20    private const int MaxBodyLength = 4096;
 21
 22    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
 823    {
 824        var stopwatch = Stopwatch.StartNew();
 825        var isApi = context.Request.Path.StartsWithSegments("/api");
 26
 27        // If not API or logging disabled, just capture performance
 828        if (!isApi || !_enableBodyLogging)
 129        {
 130            await next(context);
 131            stopwatch.Stop();
 132            LogMinimal(context, stopwatch.Elapsed.TotalMilliseconds);
 133            return;
 34        }
 35
 36        // 1. Capture Request Body
 737        context.Request.EnableBuffering();
 738        var requestBodyText = await ReadStreamAsync(context.Request.Body);
 739        context.Request.Body.Position = 0;
 40
 41        // 2. Wrap Response Body Stream
 742        var originalBodyStream = context.Response.Body;
 743        using var responseBodyWrapper = new MemoryStream();
 744        context.Response.Body = responseBodyWrapper;
 45
 46        try
 747        {
 748            await next(context);
 749        }
 50        finally
 751        {
 752            stopwatch.Stop();
 53
 54            // 3. Read Response Body
 755            responseBodyWrapper.Position = 0;
 756            var responseBodyText = await ReadStreamAsync(responseBodyWrapper);
 57
 58            // 4. Restore original stream
 759            responseBodyWrapper.Position = 0;
 760            await responseBodyWrapper.CopyToAsync(originalBodyStream);
 761            context.Response.Body = originalBodyStream;
 62
 63            // 5. Unified Log
 764            LogFull(context, stopwatch.Elapsed.TotalMilliseconds, requestBodyText, responseBodyText);
 765        }
 866    }
 67
 68    private void LogMinimal(HttpContext context, double elapsedMs)
 169    {
 170        var statusCode = context.Response.StatusCode;
 171        var userId = context.User?.FindFirstValue(ClaimTypes.NameIdentifier) ?? "Anonymous";
 72
 173        var level = statusCode >= 500 ? LogLevel.Error : (elapsedMs > 500 ? LogLevel.Warning : LogLevel.Information);
 74
 175        logger.Log(level,
 176            LoggingConfiguration.Templates.ApiRequestMinimal,
 177            context.Request.Method, context.Request.Path, statusCode, elapsedMs, userId);
 178    }
 79
 80    private void LogFull(HttpContext context, double elapsedMs, string reqBody, string resBody)
 781    {
 782        var statusCode = context.Response.StatusCode;
 783        var userId = context.User?.FindFirstValue(ClaimTypes.NameIdentifier) ?? "Anonymous";
 84
 785        var level = statusCode >= 500 ? LogLevel.Error : (elapsedMs > 500 ? LogLevel.Warning : LogLevel.Information);
 86
 87        // We pass the parsed objects directly to Serilog.
 88        // By using Dictionary<string, object>, Serilog destructures correctly for Seq.
 789        logger.Log(level,
 790            LoggingConfiguration.Templates.ApiRequest,
 791            context.Request.Method,
 792            context.Request.Path,
 793            statusCode,
 794            elapsedMs,
 795            userId,
 796            TryParseJson(reqBody) ?? "N/A",
 797            TryParseJson(resBody) ?? "N/A");
 798    }
 99
 100    private static object? TryParseJson(string text)
 14101    {
 24102        if (string.IsNullOrWhiteSpace(text)) return null;
 103        try
 4104        {
 4105            using var doc = JsonDocument.Parse(text);
 2106            return ToObject(doc.RootElement);
 107        }
 2108        catch
 2109        {
 2110            return text;
 111        }
 14112    }
 113
 114    private static object? ToObject(JsonElement element)
 4115    {
 4116        return element.ValueKind switch
 4117        {
 6118            JsonValueKind.Object => element.EnumerateObject().ToDictionary(p => p.Name, p => ToObject(p.Value)),
 0119            JsonValueKind.Array => element.EnumerateArray().Select(ToObject).ToList(),
 2120            JsonValueKind.String => element.GetString(),
 0121            JsonValueKind.Number => element.TryGetInt64(out long l) ? l : element.GetDouble(),
 0122            JsonValueKind.True => true,
 0123            JsonValueKind.False => false,
 0124            JsonValueKind.Null => null,
 0125            _ => element.GetRawText()
 4126        };
 4127    }
 128
 129    private static async Task<string> ReadStreamAsync(Stream stream)
 14130    {
 24131        if (stream.Length == 0) return string.Empty;
 4132        using var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true);
 4133        var body = await reader.ReadToEndAsync();
 134
 5135        if (body.Length > MaxBodyLength) body = body[..MaxBodyLength] + "... [TRUNCATED]";
 5136        if (body.Contains("password", StringComparison.OrdinalIgnoreCase)) return "[REDACTED]";
 137
 3138        return body;
 14139    }
 140}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Api_HttpContextExtensions.html b/coverage/html/InventoryAlert.Api_HttpContextExtensions.html new file mode 100644 index 0000000..9807003 --- /dev/null +++ b/coverage/html/InventoryAlert.Api_HttpContextExtensions.html @@ -0,0 +1,142 @@ + + + + + + + +InventoryAlert.Api.Extensions.HttpContextExtensions - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Api.Extensions.HttpContextExtensions
Assembly:InventoryAlert.Api
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Api\Extensions\HttpContextExtensions.cs
+
+
+
+
+
+
+
Line coverage
+
+
100%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:3
Uncovered lines:0
Coverable lines:3
Total lines:11
Line coverage:100%
+
+
+
+
+
Branch coverage
+
+
75%
+
+ + + + + + + + + + + + + +
Covered branches:3
Total branches:4
Branch coverage:75%
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
GetCorrelationId(...)75%44100%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Api\Extensions\HttpContextExtensions.cs

+
+ + + + + + + + + + + + + + + +
#LineLine coverage
 1namespace InventoryAlert.Api.Extensions;
 2
 3public static class HttpContextExtensions
 4{
 5    private const string CorrelationIdHeader = "X-Correlation-Id";
 6
 7    public static string GetCorrelationId(this HttpContext context)
 88    {
 89        return context.Items[CorrelationIdHeader]?.ToString() ?? "N/A";
 810    }
 11}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Domain_AuthTokenPair.html b/coverage/html/InventoryAlert.Domain_AuthTokenPair.html new file mode 100644 index 0000000..d4b39cc --- /dev/null +++ b/coverage/html/InventoryAlert.Domain_AuthTokenPair.html @@ -0,0 +1,161 @@ + + + + + + + +InventoryAlert.Domain.DTOs.AuthTokenPair - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Domain.DTOs.AuthTokenPair
Assembly:InventoryAlert.Domain
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Domain\DTOs\AuthDTOs.cs
+
+
+
+
+
+
+
Line coverage
+
+
100%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:4
Uncovered lines:0
Coverable lines:4
Total lines:24
Line coverage:100%
+
+
+
+
+
Branch coverage
+
+
N/A
+
+ + + + + + + + + + + + + +
Covered branches:0
Total branches:0
Branch coverage:N/A
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_Auth()100%11100%
get_RefreshToken()100%11100%
get_RefreshExpiresAt()100%11100%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Domain\DTOs\AuthDTOs.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1namespace InventoryAlert.Domain.DTOs;
 2
 3public record LoginRequest(string Username, string Password);
 4
 5public record RegisterRequest(string Username, string Password, string Email);
 6
 7public record AuthResponse(
 8    string AccessToken,
 9    DateTime ExpiresAt);
 10
 11/// <summary>
 12/// Internal token pair used to set the httpOnly refresh cookie while keeping API response bodies minimal.
 13/// </summary>
 214public record AuthTokenPair(
 215    AuthResponse Auth,
 216    string RefreshToken,
 417    DateTime RefreshExpiresAt);
 18
 19public record RegistrationResponse(string Message, string Username);
 20
 21/// <summary>
 22/// No body needed; refresh token is read from httpOnly cookie.
 23/// </summary>
 24public record RefreshRequest();
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Infrastructure_AddNotificationDetails.html b/coverage/html/InventoryAlert.Infrastructure_AddNotificationDetails.html new file mode 100644 index 0000000..106961e --- /dev/null +++ b/coverage/html/InventoryAlert.Infrastructure_AddNotificationDetails.html @@ -0,0 +1,740 @@ + + + + + + + +InventoryAlert.Infrastructure.Migrations.AddNotificationDetails - Coverage Report + +
+

< Summary

+ +
+
+
Line coverage
+
+
0%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:0
Uncovered lines:537
Coverable lines:537
Total lines:597
Line coverage:0%
+
+
+
+
+
Branch coverage
+
+
N/A
+
+ + + + + + + + + + + + + +
Covered branches:0
Total branches:0
Branch coverage:N/A
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: Up(...)100%210%
File 1: Down(...)100%210%
File 2: BuildTargetModel(...)100%210%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Migrations\20260426071939_AddNotificationDetails.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using Microsoft.EntityFrameworkCore.Migrations;
 2
 3#nullable disable
 4
 5namespace InventoryAlert.Infrastructure.Migrations;
 6
 7/// <inheritdoc />
 8public partial class AddNotificationDetails : Migration
 9{
 10    /// <inheritdoc />
 11    protected override void Up(MigrationBuilder migrationBuilder)
 012    {
 013        migrationBuilder.AddColumn<int>(
 014            name: "Severity",
 015            table: "notifications",
 016            type: "integer",
 017            nullable: false,
 018            defaultValue: 0);
 19
 020        migrationBuilder.AddColumn<int>(
 021            name: "Type",
 022            table: "notifications",
 023            type: "integer",
 024            nullable: false,
 025            defaultValue: 0);
 026    }
 27
 28    /// <inheritdoc />
 29    protected override void Down(MigrationBuilder migrationBuilder)
 030    {
 031        migrationBuilder.DropColumn(
 032            name: "Severity",
 033            table: "notifications");
 34
 035        migrationBuilder.DropColumn(
 036            name: "Type",
 037            table: "notifications");
 038    }
 39}
+
+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Migrations\20260426071939_AddNotificationDetails.Designer.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1// <auto-generated />
 2using System;
 3using InventoryAlert.Infrastructure.Persistence.Postgres;
 4using Microsoft.EntityFrameworkCore;
 5using Microsoft.EntityFrameworkCore.Infrastructure;
 6using Microsoft.EntityFrameworkCore.Migrations;
 7using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
 8using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
 9
 10#nullable disable
 11
 12namespace InventoryAlert.Infrastructure.Migrations
 13{
 14    [DbContext(typeof(AppDbContext))]
 15    [Migration("20260426071939_AddNotificationDetails")]
 16    partial class AddNotificationDetails
 17    {
 18        /// <inheritdoc />
 19        protected override void BuildTargetModel(ModelBuilder modelBuilder)
 020        {
 21#pragma warning disable 612, 618
 022            modelBuilder
 023                .HasAnnotation("ProductVersion", "10.0.5")
 024                .HasAnnotation("Relational:MaxIdentifierLength", 63);
 25
 026            NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
 27
 028            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.AlertRule", b =>
 029                {
 030                    b.Property<Guid>("Id")
 031                        .ValueGeneratedOnAdd()
 032                        .HasColumnType("uuid");
 033
 034                    b.Property<int>("Condition")
 035                        .HasColumnType("integer");
 036
 037                    b.Property<DateTime>("CreatedAt")
 038                        .HasColumnType("timestamp with time zone");
 039
 040                    b.Property<bool>("IsActive")
 041                        .HasColumnType("boolean");
 042
 043                    b.Property<DateTime?>("LastTriggeredAt")
 044                        .HasColumnType("timestamp with time zone");
 045
 046                    b.Property<decimal>("TargetValue")
 047                        .HasColumnType("numeric");
 048
 049                    b.Property<string>("TickerSymbol")
 050                        .IsRequired()
 051                        .HasMaxLength(10)
 052                        .HasColumnType("character varying(10)");
 053
 054                    b.Property<bool>("TriggerOnce")
 055                        .HasColumnType("boolean");
 056
 057                    b.Property<Guid>("UserId")
 058                        .HasColumnType("uuid");
 059
 060                    b.HasKey("Id");
 061
 062                    b.HasIndex("UserId");
 063
 064                    b.HasIndex("TickerSymbol", "IsActive");
 065
 066                    b.ToTable("alert_rules", (string)null);
 067                });
 68
 069            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.EarningsSurprise", b =>
 070                {
 071                    b.Property<int>("Id")
 072                        .ValueGeneratedOnAdd()
 073                        .HasColumnType("integer");
 074
 075                    NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
 076
 077                    b.Property<double?>("ActualEps")
 078                        .HasColumnType("double precision");
 079
 080                    b.Property<double?>("EstimateEps")
 081                        .HasColumnType("double precision");
 082
 083                    b.Property<DateOnly>("Period")
 084                        .HasColumnType("date");
 085
 086                    b.Property<DateOnly?>("ReportDate")
 087                        .HasColumnType("date");
 088
 089                    b.Property<double?>("SurprisePercent")
 090                        .HasColumnType("double precision");
 091
 092                    b.Property<string>("TickerSymbol")
 093                        .IsRequired()
 094                        .HasMaxLength(10)
 095                        .HasColumnType("character varying(10)");
 096
 097                    b.HasKey("Id");
 098
 099                    b.HasIndex("TickerSymbol", "Period")
 0100                        .IsUnique();
 0101
 0102                    b.ToTable("earnings_surprises", (string)null);
 0103                });
 104
 0105            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.InsiderTransaction", b =>
 0106                {
 0107                    b.Property<int>("Id")
 0108                        .ValueGeneratedOnAdd()
 0109                        .HasColumnType("integer");
 0110
 0111                    NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
 0112
 0113                    b.Property<DateOnly?>("FilingDate")
 0114                        .HasColumnType("date");
 0115
 0116                    b.Property<string>("Name")
 0117                        .HasColumnType("text");
 0118
 0119                    b.Property<long?>("Share")
 0120                        .HasColumnType("bigint");
 0121
 0122                    b.Property<string>("TickerSymbol")
 0123                        .IsRequired()
 0124                        .HasMaxLength(10)
 0125                        .HasColumnType("character varying(10)");
 0126
 0127                    b.Property<string>("TransactionCode")
 0128                        .HasColumnType("text");
 0129
 0130                    b.Property<DateOnly?>("TransactionDate")
 0131                        .HasColumnType("date");
 0132
 0133                    b.Property<decimal?>("Value")
 0134                        .HasColumnType("numeric");
 0135
 0136                    b.HasKey("Id");
 0137
 0138                    b.HasIndex("TickerSymbol", "TransactionDate");
 0139
 0140                    b.ToTable("insider_transactions", (string)null);
 0141                });
 142
 0143            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.Notification", b =>
 0144                {
 0145                    b.Property<Guid>("Id")
 0146                        .ValueGeneratedOnAdd()
 0147                        .HasColumnType("uuid");
 0148
 0149                    b.Property<Guid?>("AlertRuleId")
 0150                        .HasColumnType("uuid");
 0151
 0152                    b.Property<DateTime>("CreatedAt")
 0153                        .HasColumnType("timestamp with time zone");
 0154
 0155                    b.Property<bool>("IsRead")
 0156                        .HasColumnType("boolean");
 0157
 0158                    b.Property<string>("Message")
 0159                        .IsRequired()
 0160                        .HasColumnType("text");
 0161
 0162                    b.Property<int>("Severity")
 0163                        .HasColumnType("integer");
 0164
 0165                    b.Property<string>("TickerSymbol")
 0166                        .HasMaxLength(10)
 0167                        .HasColumnType("character varying(10)");
 0168
 0169                    b.Property<int>("Type")
 0170                        .HasColumnType("integer");
 0171
 0172                    b.Property<Guid>("UserId")
 0173                        .HasColumnType("uuid");
 0174
 0175                    b.HasKey("Id");
 0176
 0177                    b.HasIndex("AlertRuleId");
 0178
 0179                    b.HasIndex("UserId", "IsRead", "CreatedAt");
 0180
 0181                    b.ToTable("notifications", (string)null);
 0182                });
 183
 0184            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.PriceHistory", b =>
 0185                {
 0186                    b.Property<long>("Id")
 0187                        .ValueGeneratedOnAdd()
 0188                        .HasColumnType("bigint");
 0189
 0190                    NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
 0191
 0192                    b.Property<decimal?>("High")
 0193                        .HasColumnType("numeric");
 0194
 0195                    b.Property<decimal?>("Low")
 0196                        .HasColumnType("numeric");
 0197
 0198                    b.Property<decimal?>("Open")
 0199                        .HasColumnType("numeric");
 0200
 0201                    b.Property<decimal?>("PrevClose")
 0202                        .HasColumnType("numeric");
 0203
 0204                    b.Property<decimal>("Price")
 0205                        .HasColumnType("numeric");
 0206
 0207                    b.Property<DateTime>("RecordedAt")
 0208                        .HasColumnType("timestamp with time zone");
 0209
 0210                    b.Property<string>("TickerSymbol")
 0211                        .IsRequired()
 0212                        .HasMaxLength(10)
 0213                        .HasColumnType("character varying(10)");
 0214
 0215                    b.HasKey("Id");
 0216
 0217                    b.HasIndex("TickerSymbol", "RecordedAt");
 0218
 0219                    b.ToTable("price_history", (string)null);
 0220                });
 221
 0222            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.RecommendationTrend", b =>
 0223                {
 0224                    b.Property<int>("Id")
 0225                        .ValueGeneratedOnAdd()
 0226                        .HasColumnType("integer");
 0227
 0228                    NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
 0229
 0230                    b.Property<int>("Buy")
 0231                        .HasColumnType("integer");
 0232
 0233                    b.Property<int>("Hold")
 0234                        .HasColumnType("integer");
 0235
 0236                    b.Property<string>("Period")
 0237                        .IsRequired()
 0238                        .HasColumnType("text");
 0239
 0240                    b.Property<int>("Sell")
 0241                        .HasColumnType("integer");
 0242
 0243                    b.Property<int>("StrongBuy")
 0244                        .HasColumnType("integer");
 0245
 0246                    b.Property<int>("StrongSell")
 0247                        .HasColumnType("integer");
 0248
 0249                    b.Property<DateTime>("SyncedAt")
 0250                        .HasColumnType("timestamp with time zone");
 0251
 0252                    b.Property<string>("TickerSymbol")
 0253                        .IsRequired()
 0254                        .HasMaxLength(10)
 0255                        .HasColumnType("character varying(10)");
 0256
 0257                    b.HasKey("Id");
 0258
 0259                    b.HasIndex("TickerSymbol", "Period")
 0260                        .IsUnique();
 0261
 0262                    b.ToTable("recommendation_trends", (string)null);
 0263                });
 264
 0265            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.StockListing", b =>
 0266                {
 0267                    b.Property<int>("Id")
 0268                        .ValueGeneratedOnAdd()
 0269                        .HasColumnType("integer");
 0270
 0271                    NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
 0272
 0273                    b.Property<string>("Country")
 0274                        .HasMaxLength(10)
 0275                        .HasColumnType("character varying(10)");
 0276
 0277                    b.Property<string>("Currency")
 0278                        .HasMaxLength(10)
 0279                        .HasColumnType("character varying(10)");
 0280
 0281                    b.Property<string>("Exchange")
 0282                        .HasMaxLength(50)
 0283                        .HasColumnType("character varying(50)");
 0284
 0285                    b.Property<string>("Industry")
 0286                        .HasMaxLength(100)
 0287                        .HasColumnType("character varying(100)");
 0288
 0289                    b.Property<DateOnly?>("Ipo")
 0290                        .HasColumnType("date");
 0291
 0292                    b.Property<DateTime?>("LastProfileSync")
 0293                        .HasColumnType("timestamp with time zone");
 0294
 0295                    b.Property<string>("Logo")
 0296                        .HasMaxLength(1000)
 0297                        .HasColumnType("character varying(1000)");
 0298
 0299                    b.Property<decimal?>("MarketCap")
 0300                        .HasColumnType("numeric");
 0301
 0302                    b.Property<string>("Name")
 0303                        .IsRequired()
 0304                        .HasMaxLength(200)
 0305                        .HasColumnType("character varying(200)");
 0306
 0307                    b.Property<string>("TickerSymbol")
 0308                        .IsRequired()
 0309                        .HasMaxLength(10)
 0310                        .HasColumnType("character varying(10)");
 0311
 0312                    b.Property<string>("WebUrl")
 0313                        .HasMaxLength(1000)
 0314                        .HasColumnType("character varying(1000)");
 0315
 0316                    b.HasKey("Id");
 0317
 0318                    b.HasIndex("TickerSymbol")
 0319                        .IsUnique();
 0320
 0321                    b.ToTable("stock_listings", (string)null);
 0322                });
 323
 0324            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.StockMetric", b =>
 0325                {
 0326                    b.Property<string>("TickerSymbol")
 0327                        .HasMaxLength(10)
 0328                        .HasColumnType("character varying(10)");
 0329
 0330                    b.Property<double?>("DividendYield")
 0331                        .HasColumnType("double precision");
 0332
 0333                    b.Property<double?>("EpsBasicTtm")
 0334                        .HasColumnType("double precision");
 0335
 0336                    b.Property<DateTime>("LastSyncedAt")
 0337                        .HasColumnType("timestamp with time zone");
 0338
 0339                    b.Property<double?>("MarginNet")
 0340                        .HasColumnType("double precision");
 0341
 0342                    b.Property<double?>("PbRatio")
 0343                        .HasColumnType("double precision");
 0344
 0345                    b.Property<double?>("PeRatio")
 0346                        .HasColumnType("double precision");
 0347
 0348                    b.Property<double?>("RevenueGrowthTtm")
 0349                        .HasColumnType("double precision");
 0350
 0351                    b.Property<decimal?>("Week52High")
 0352                        .HasColumnType("numeric");
 0353
 0354                    b.Property<decimal?>("Week52Low")
 0355                        .HasColumnType("numeric");
 0356
 0357                    b.HasKey("TickerSymbol");
 0358
 0359                    b.ToTable("stock_metrics", (string)null);
 0360                });
 361
 0362            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.Trade", b =>
 0363                {
 0364                    b.Property<Guid>("Id")
 0365                        .ValueGeneratedOnAdd()
 0366                        .HasColumnType("uuid");
 0367
 0368                    b.Property<string>("Notes")
 0369                        .HasColumnType("text");
 0370
 0371                    b.Property<decimal>("Quantity")
 0372                        .HasColumnType("numeric");
 0373
 0374                    b.Property<string>("TickerSymbol")
 0375                        .IsRequired()
 0376                        .HasMaxLength(10)
 0377                        .HasColumnType("character varying(10)");
 0378
 0379                    b.Property<DateTime>("TradedAt")
 0380                        .HasColumnType("timestamp with time zone");
 0381
 0382                    b.Property<int>("Type")
 0383                        .HasColumnType("integer");
 0384
 0385                    b.Property<decimal>("UnitPrice")
 0386                        .HasColumnType("numeric");
 0387
 0388                    b.Property<Guid>("UserId")
 0389                        .HasColumnType("uuid");
 0390
 0391                    b.HasKey("Id");
 0392
 0393                    b.HasIndex("TickerSymbol");
 0394
 0395                    b.HasIndex("UserId", "TickerSymbol", "TradedAt");
 0396
 0397                    b.ToTable("trades", (string)null);
 0398                });
 399
 0400            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.User", b =>
 0401                {
 0402                    b.Property<Guid>("Id")
 0403                        .ValueGeneratedOnAdd()
 0404                        .HasColumnType("uuid");
 0405
 0406                    b.Property<DateTime>("CreatedAt")
 0407                        .HasColumnType("timestamp with time zone");
 0408
 0409                    b.Property<string>("Email")
 0410                        .IsRequired()
 0411                        .HasMaxLength(128)
 0412                        .HasColumnType("character varying(128)");
 0413
 0414                    b.Property<string>("PasswordHash")
 0415                        .IsRequired()
 0416                        .HasColumnType("text");
 0417
 0418                    b.Property<string>("Role")
 0419                        .IsRequired()
 0420                        .HasColumnType("text");
 0421
 0422                    b.Property<string>("Username")
 0423                        .IsRequired()
 0424                        .HasMaxLength(64)
 0425                        .HasColumnType("character varying(64)");
 0426
 0427                    b.HasKey("Id");
 0428
 0429                    b.HasIndex("Username")
 0430                        .IsUnique();
 0431
 0432                    b.ToTable("Users", (string)null);
 0433                });
 434
 0435            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.WatchlistItem", b =>
 0436                {
 0437                    b.Property<Guid>("UserId")
 0438                        .HasColumnType("uuid");
 0439
 0440                    b.Property<string>("TickerSymbol")
 0441                        .HasMaxLength(10)
 0442                        .HasColumnType("character varying(10)");
 0443
 0444                    b.Property<DateTime>("CreatedAt")
 0445                        .HasColumnType("timestamp with time zone");
 0446
 0447                    b.HasKey("UserId", "TickerSymbol");
 0448
 0449                    b.HasIndex("TickerSymbol");
 0450
 0451                    b.ToTable("watchlist_items", (string)null);
 0452                });
 453
 0454            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.AlertRule", b =>
 0455                {
 0456                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.StockListing", null)
 0457                        .WithMany()
 0458                        .HasForeignKey("TickerSymbol")
 0459                        .HasPrincipalKey("TickerSymbol")
 0460                        .OnDelete(DeleteBehavior.Cascade)
 0461                        .IsRequired();
 0462
 0463                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.User", null)
 0464                        .WithMany()
 0465                        .HasForeignKey("UserId")
 0466                        .OnDelete(DeleteBehavior.Cascade)
 0467                        .IsRequired();
 0468                });
 469
 0470            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.EarningsSurprise", b =>
 0471                {
 0472                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.StockListing", null)
 0473                        .WithMany()
 0474                        .HasForeignKey("TickerSymbol")
 0475                        .HasPrincipalKey("TickerSymbol")
 0476                        .OnDelete(DeleteBehavior.Cascade)
 0477                        .IsRequired();
 0478                });
 479
 0480            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.InsiderTransaction", b =>
 0481                {
 0482                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.StockListing", null)
 0483                        .WithMany()
 0484                        .HasForeignKey("TickerSymbol")
 0485                        .HasPrincipalKey("TickerSymbol")
 0486                        .OnDelete(DeleteBehavior.Cascade)
 0487                        .IsRequired();
 0488                });
 489
 0490            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.Notification", b =>
 0491                {
 0492                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.AlertRule", null)
 0493                        .WithMany()
 0494                        .HasForeignKey("AlertRuleId")
 0495                        .OnDelete(DeleteBehavior.SetNull);
 0496
 0497                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.User", null)
 0498                        .WithMany()
 0499                        .HasForeignKey("UserId")
 0500                        .OnDelete(DeleteBehavior.Cascade)
 0501                        .IsRequired();
 0502                });
 503
 0504            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.RecommendationTrend", b =>
 0505                {
 0506                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.StockListing", null)
 0507                        .WithMany()
 0508                        .HasForeignKey("TickerSymbol")
 0509                        .HasPrincipalKey("TickerSymbol")
 0510                        .OnDelete(DeleteBehavior.Cascade)
 0511                        .IsRequired();
 0512                });
 513
 0514            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.StockMetric", b =>
 0515                {
 0516                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.StockListing", null)
 0517                        .WithOne()
 0518                        .HasForeignKey("InventoryAlert.Domain.Entities.Postgres.StockMetric", "TickerSymbol")
 0519                        .HasPrincipalKey("InventoryAlert.Domain.Entities.Postgres.StockListing", "TickerSymbol")
 0520                        .OnDelete(DeleteBehavior.Cascade)
 0521                        .IsRequired();
 0522                });
 523
 0524            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.Trade", b =>
 0525                {
 0526                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.StockListing", null)
 0527                        .WithMany()
 0528                        .HasForeignKey("TickerSymbol")
 0529                        .HasPrincipalKey("TickerSymbol")
 0530                        .OnDelete(DeleteBehavior.Restrict)
 0531                        .IsRequired();
 0532
 0533                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.User", null)
 0534                        .WithMany()
 0535                        .HasForeignKey("UserId")
 0536                        .OnDelete(DeleteBehavior.Cascade)
 0537                        .IsRequired();
 0538                });
 539
 0540            modelBuilder.Entity("InventoryAlert.Domain.Entities.Postgres.WatchlistItem", b =>
 0541                {
 0542                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.StockListing", null)
 0543                        .WithMany()
 0544                        .HasForeignKey("TickerSymbol")
 0545                        .HasPrincipalKey("TickerSymbol")
 0546                        .OnDelete(DeleteBehavior.Cascade)
 0547                        .IsRequired();
 0548
 0549                    b.HasOne("InventoryAlert.Domain.Entities.Postgres.User", null)
 0550                        .WithMany()
 0551                        .HasForeignKey("UserId")
 0552                        .OnDelete(DeleteBehavior.Cascade)
 0553                        .IsRequired();
 0554                });
 555#pragma warning restore 612, 618
 0556        }
 557    }
 558}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Infrastructure_AlertRuleEvaluator.html b/coverage/html/InventoryAlert.Infrastructure_AlertRuleEvaluator.html new file mode 100644 index 0000000..73d1bd2 --- /dev/null +++ b/coverage/html/InventoryAlert.Infrastructure_AlertRuleEvaluator.html @@ -0,0 +1,230 @@ + + + + + + + +InventoryAlert.Infrastructure.Utilities.AlertRuleEvaluator - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Infrastructure.Utilities.AlertRuleEvaluator
Assembly:InventoryAlert.Infrastructure
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Utilities\AlertRuleEvaluator.cs
+
+
+
+
+
+
+
Line coverage
+
+
74%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:47
Uncovered lines:16
Coverable lines:63
Total lines:95
Line coverage:74.6%
+
+
+
+
+
Branch coverage
+
+
76%
+
+ + + + + + + + + + + + + +
Covered branches:16
Total branches:21
Branch coverage:76.1%
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
EvaluateAsync()78.94%261972.72%
GetAverageCostAsync()50%2255.55%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Utilities\AlertRuleEvaluator.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using InventoryAlert.Domain.Constants;
 2using InventoryAlert.Domain.Entities.Postgres;
 3using InventoryAlert.Domain.Interfaces;
 4using Microsoft.Extensions.Logging;
 5
 6namespace InventoryAlert.Infrastructure.Utilities;
 7
 38public class AlertRuleEvaluator(
 39    IUnitOfWork unitOfWork,
 310    IRedisHelper redis,
 311    ILogger<AlertRuleEvaluator> logger) : IAlertRuleEvaluator
 12{
 313    private readonly IUnitOfWork _unitOfWork = unitOfWork;
 314    private readonly IRedisHelper _redis = redis;
 315    private readonly ILogger<AlertRuleEvaluator> _logger = logger;
 16
 17    public async Task<(bool IsBreached, string Message)> EvaluateAsync(AlertRule rule, decimal currentPrice, Cancellatio
 318    {
 19        // 1. Check Cooldown/Deduplication
 320        var cooldownKey = CacheKeys.AlertCooldown(rule.UserId, rule.Id);
 321        if (await _redis.KeyExistsAsync(cooldownKey, ct))
 122        {
 123            return (false, string.Empty);
 24        }
 25
 226        bool isBreached = false;
 227        string message = string.Empty;
 28
 229        switch (rule.Condition)
 30        {
 31            case AlertCondition.PriceAbove:
 132                if (currentPrice > rule.TargetValue)
 133                {
 134                    isBreached = true;
 135                    message = $"{rule.TickerSymbol} price {currentPrice:C} is above your target {rule.TargetValue:C}";
 136                }
 137                break;
 38
 39            case AlertCondition.PriceBelow:
 040                if (currentPrice < rule.TargetValue)
 041                {
 042                    isBreached = true;
 043                    message = $"{rule.TickerSymbol} price {currentPrice:C} is below your target {rule.TargetValue:C}";
 044                }
 045                break;
 46
 47            case AlertCondition.PriceTargetReached:
 048                if (Math.Abs(currentPrice - rule.TargetValue) < 0.01m)
 049                {
 050                    isBreached = true;
 051                    message = $"{rule.TickerSymbol} price reached your target {rule.TargetValue:C}";
 052                }
 053                break;
 54
 55            case AlertCondition.PercentDropFromCost:
 156                var avgCost = await GetAverageCostAsync(rule.UserId, rule.TickerSymbol, ct);
 157                if (avgCost > 0)
 158                {
 159                    var drop = (avgCost - currentPrice) / avgCost * 100;
 160                    if (drop >= rule.TargetValue)
 161                    {
 162                        isBreached = true;
 163                        message = $"{rule.TickerSymbol} has dropped {drop:F2}% from your cost basis of {avgCost:C}";
 164                    }
 165                }
 166                break;
 67        }
 68
 269        if (isBreached)
 270        {
 71            // Set cooldown to prevent alert storm (e.g., 24 hours)
 272            await _redis.TryAcquireBestEffortLockAsync(cooldownKey, "1", TimeSpan.FromHours(24), ct);
 273            _logger.LogInformation("[Evaluator] Rule {RuleId} breached for user {UserId}", rule.Id, rule.UserId);
 274        }
 75
 276        return (isBreached, message);
 377    }
 78
 79    private async Task<decimal> GetAverageCostAsync(Guid userId, string symbol, CancellationToken ct)
 180    {
 81        try
 182        {
 183            var trades = await _unitOfWork.Trades.GetByUserAndSymbolAsync(userId, symbol, ct);
 284            var buys = trades.Where(t => t.Type == TradeType.Buy).ToList();
 285            var totalCost = buys.Sum(t => t.Quantity * t.UnitPrice);
 286            var totalQty = buys.Sum(t => t.Quantity);
 187            return totalQty > 0 ? totalCost / totalQty : 0;
 88        }
 089        catch (Exception ex)
 090        {
 091            _logger.LogError(ex, "Failed to calculate average cost for User {UserId} Symbol {Symbol}", userId, symbol);
 092            return 0;
 93        }
 194    }
 95}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Infrastructure_CorrelationIdEnricher.html b/coverage/html/InventoryAlert.Infrastructure_CorrelationIdEnricher.html new file mode 100644 index 0000000..810cf68 --- /dev/null +++ b/coverage/html/InventoryAlert.Infrastructure_CorrelationIdEnricher.html @@ -0,0 +1,165 @@ + + + + + + + +InventoryAlert.Infrastructure.Utilities.CorrelationIdEnricher - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Infrastructure.Utilities.CorrelationIdEnricher
Assembly:InventoryAlert.Infrastructure
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Utilities\CorrelationIdEnricher.cs
+
+
+
+
+
+
+
Line coverage
+
+
0%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:0
Uncovered lines:14
Coverable lines:14
Total lines:32
Line coverage:0%
+
+
+
+
+
Branch coverage
+
+
0%
+
+ + + + + + + + + + + + + +
Covered branches:0
Total branches:6
Branch coverage:0%
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
Enrich(...)0%4260%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Utilities\CorrelationIdEnricher.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using InventoryAlert.Domain.Interfaces;
 2using Serilog.Core;
 3using Serilog.Events;
 4
 5namespace InventoryAlert.Infrastructure.Utilities;
 6
 7/// <summary>
 8/// Serilog enricher that uses ICorrelationProvider to attach the current CorrelationId to every log entry.
 9/// This ensures logs in both API (via Middleware) and Worker (via AsyncLocal) are traceable in Seq and Console.
 10/// </summary>
 011public class CorrelationIdEnricher(ICorrelationProvider correlationProvider) : ILogEventEnricher
 12{
 013    private readonly ICorrelationProvider _correlationProvider = correlationProvider;
 14
 15    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
 016    {
 17        // 1. If property already exists and has a real value, don't overwrite it.
 18        // This allows ILogger.BeginScope or LogContext.PushProperty to take precedence.
 019        if (logEvent.Properties.TryGetValue("CorrelationId", out var existing))
 020        {
 021            var value = existing.ToString().Trim('\"');
 022            if (!string.IsNullOrEmpty(value) && value != "N/A")
 023            {
 024                return;
 25            }
 026        }
 27
 028        var correlationId = _correlationProvider.GetCorrelationId();
 029        var property = propertyFactory.CreateProperty("CorrelationId", correlationId);
 030        logEvent.AddOrUpdateProperty(property);
 031    }
 32}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Infrastructure_LoggingConfiguration.html b/coverage/html/InventoryAlert.Infrastructure_LoggingConfiguration.html new file mode 100644 index 0000000..c74c4d6 --- /dev/null +++ b/coverage/html/InventoryAlert.Infrastructure_LoggingConfiguration.html @@ -0,0 +1,183 @@ + + + + + + + +InventoryAlert.Infrastructure.Utilities.LoggingConfiguration - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Infrastructure.Utilities.LoggingConfiguration
Assembly:InventoryAlert.Infrastructure
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Utilities\LoggingConfiguration.cs
+
+
+
+
+
+
+
Line coverage
+
+
0%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:0
Uncovered lines:23
Coverable lines:23
Total lines:50
Line coverage:0%
+
+
+
+
+
Branch coverage
+
+
0%
+
+ + + + + + + + + + + + + +
Covered branches:0
Total branches:4
Branch coverage:0%
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
ApplyBaseConfiguration(...)0%2040%
AddCorrelationEnricher(...)100%210%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Utilities\LoggingConfiguration.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using InventoryAlert.Domain.Configuration;
 2using Microsoft.Extensions.DependencyInjection;
 3using Serilog;
 4using Serilog.Events;
 5
 6namespace InventoryAlert.Infrastructure.Utilities;
 7
 8public static class LoggingConfiguration
 9{
 10    public const string ConsoleOutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {CorrelationId} {SourceContext}: {Mes
 11    public const string FileOutputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {CorrelationId} {SourceCo
 12
 13    // Standardized Log Message Templates
 14    public static class Templates
 15    {
 16        public const string ApiRequest = "HTTP {Method} {Path} responded {StatusCode} in {ElapsedMs:F3}ms | User: {UserI
 17        public const string ApiRequestMinimal = "HTTP {Method} {Path} responded {StatusCode} in {ElapsedMs:F3}ms | User:
 18        public const string JobStarted = "handler.started: Job {JobName} execution started.";
 19        public const string JobCompleted = "handler.completed: Job {JobName} execution finished. Succeeded={Succeeded} |
 20        public const string UnhandledException = "An unhandled exception has occurred while executing the request.";
 21    }
 22
 23    public static LoggerConfiguration ApplyBaseConfiguration(this LoggerConfiguration loggerConfiguration, AppSettings s
 024    {
 025        var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
 026                  ?? Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")
 027                  ?? "Production";
 28
 029        return loggerConfiguration
 030            .MinimumLevel.Information()
 031            .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
 032            .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
 033            .MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning)
 034            .MinimumLevel.Override("Hangfire", LogEventLevel.Information)
 035            .Enrich.FromLogContext()
 036            .Enrich.WithProperty("Service", serviceName)
 037            .Enrich.WithProperty("Environment", env)
 038            .WriteTo.Console(outputTemplate: ConsoleOutputTemplate)
 039            .WriteTo.Seq(settings.Seq.ServerUrl)
 040            .WriteTo.File($"logs/{serviceName.ToLower()}-.log",
 041                rollingInterval: RollingInterval.Day,
 042                retainedFileCountLimit: 7,
 043                outputTemplate: FileOutputTemplate);
 044    }
 45
 46    public static void AddCorrelationEnricher(this IServiceCollection services)
 047    {
 048        services.AddSingleton<CorrelationIdEnricher>();
 049    }
 50}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Infrastructure_NotificationAlertNotifier.html b/coverage/html/InventoryAlert.Infrastructure_NotificationAlertNotifier.html new file mode 100644 index 0000000..a1ec781 --- /dev/null +++ b/coverage/html/InventoryAlert.Infrastructure_NotificationAlertNotifier.html @@ -0,0 +1,184 @@ + + + + + + + +InventoryAlert.Infrastructure.Utilities.NotificationAlertNotifier - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Infrastructure.Utilities.NotificationAlertNotifier
Assembly:InventoryAlert.Infrastructure
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Utilities\NotificationAlertNotifier.cs
+
+
+
+
+
+
+
Line coverage
+
+
0%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:0
Uncovered lines:27
Coverable lines:27
Total lines:51
Line coverage:0%
+
+
+
+
+
Branch coverage
+
+
0%
+
+ + + + + + + + + + + + + +
Covered branches:0
Total branches:2
Branch coverage:0%
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
NotifyAsync()0%620%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Utilities\NotificationAlertNotifier.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using InventoryAlert.Domain.DTOs;
 2using InventoryAlert.Domain.Entities.Postgres;
 3using InventoryAlert.Domain.Interfaces;
 4using InventoryAlert.Infrastructure.Hubs;
 5using Microsoft.AspNetCore.SignalR;
 6using Microsoft.Extensions.Logging;
 7
 8namespace InventoryAlert.Infrastructure.Utilities;
 9
 10/// <summary>
 11/// Refactored notifier that pushes real-time alerts via SignalR (Redis Backplane).
 12/// Shared across services via Infrastructure.
 13/// </summary>
 014public class NotificationAlertNotifier(
 015    IHubContext<NotificationHub, INotificationHub> hubContext,
 016    ILogger<NotificationAlertNotifier> logger) : IAlertNotifier
 17{
 018    private readonly IHubContext<NotificationHub, INotificationHub> _hubContext = hubContext;
 019    private readonly ILogger<NotificationAlertNotifier> _logger = logger;
 20
 21    public async Task NotifyAsync(Notification notification, CancellationToken ct)
 022    {
 023        _logger.LogInformation("[AlertNotifier] New internal notification for User {UserId}: {Message}",
 024            notification.UserId, notification.Message);
 25
 26        try
 027        {
 28            // Map to response DTO for consistent client consumption
 029            var dto = new NotificationResponse(
 030                notification.Id,
 031                notification.Message,
 032                notification.TickerSymbol ?? "MARKET",
 033                notification.Type,
 034                notification.Severity,
 035                notification.IsRead,
 036                notification.CreatedAt
 037            );
 38
 39            // Push to specific user via SignalR
 40            // The Redis backplane ensures this reaches the correct Api instance where the user is connected.
 041            await _hubContext.Clients.User(notification.UserId.ToString())
 042                .ReceiveNotification(dto);
 43
 044            _logger.LogInformation("[AlertNotifier] Successfully pushed SignalR alert to User {UserId}", notification.Us
 045        }
 046        catch (Exception ex)
 047        {
 048            _logger.LogError(ex, "[AlertNotifier] Failed to push SignalR notification for User {UserId}", notification.U
 049        }
 050    }
 51}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Infrastructure_NotificationHub.html b/coverage/html/InventoryAlert.Infrastructure_NotificationHub.html new file mode 100644 index 0000000..5d2cf6f --- /dev/null +++ b/coverage/html/InventoryAlert.Infrastructure_NotificationHub.html @@ -0,0 +1,174 @@ + + + + + + + +InventoryAlert.Infrastructure.Hubs.NotificationHub - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Infrastructure.Hubs.NotificationHub
Assembly:InventoryAlert.Infrastructure
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Hubs\NotificationHub.cs
+
+
+
+
+
+
+
Line coverage
+
+
0%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:0
Uncovered lines:15
Coverable lines:15
Total lines:39
Line coverage:0%
+
+
+
+
+
Branch coverage
+
+
N/A
+
+ + + + + + + + + + + + + +
Covered branches:0
Total branches:0
Branch coverage:N/A
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
OnConnectedAsync()100%210%
OnDisconnectedAsync()100%210%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Infrastructure\Hubs\NotificationHub.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using InventoryAlert.Domain.Interfaces;
 2using Microsoft.AspNetCore.Authorization;
 3using Microsoft.AspNetCore.SignalR;
 4using Microsoft.Extensions.Logging;
 5
 6namespace InventoryAlert.Infrastructure.Hubs;
 7
 8/// <summary>
 9/// Secured SignalR hub for real-time user notifications.
 10/// Uses the INotificationHub interface for type-safe client calls.
 11/// Shared in Infrastructure so both Api and Worker can use it with the Redis backplane.
 12/// </summary>
 13[Authorize]
 14public class NotificationHub : Hub<INotificationHub>
 15{
 16    private readonly ILogger<NotificationHub> _logger;
 17
 018    public NotificationHub(ILogger<NotificationHub> logger)
 019    {
 020        _logger = logger;
 021    }
 22
 23    public override async Task OnConnectedAsync()
 024    {
 025        var userId = Context.UserIdentifier;
 026        _logger.LogInformation("User {UserId} connected to NotificationHub (ConnectionId: {ConnectionId})",
 027            userId, Context.ConnectionId);
 28
 029        await base.OnConnectedAsync();
 030    }
 31
 32    public override async Task OnDisconnectedAsync(Exception? exception)
 033    {
 034        var userId = Context.UserIdentifier;
 035        _logger.LogInformation("User {UserId} disconnected from NotificationHub", userId);
 36
 037        await base.OnDisconnectedAsync(exception);
 038    }
 39}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Worker_HealthCheckExtensions.html b/coverage/html/InventoryAlert.Worker_HealthCheckExtensions.html new file mode 100644 index 0000000..ed58400 --- /dev/null +++ b/coverage/html/InventoryAlert.Worker_HealthCheckExtensions.html @@ -0,0 +1,175 @@ + + + + + + + +InventoryAlert.Worker.Extensions.HealthCheckExtensions - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Worker.Extensions.HealthCheckExtensions
Assembly:InventoryAlert.Worker
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Worker\Extensions\HealthCheckExtensions.cs
+
+
+
+
+
+
+
Line coverage
+
+
0%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:0
Uncovered lines:30
Coverable lines:30
Total lines:42
Line coverage:0%
+
+
+
+
+
Branch coverage
+
+
N/A
+
+ + + + + + + + + + + + + +
Covered branches:0
Total branches:0
Branch coverage:N/A
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
SetupHealthCheck(...)100%210%
ConfigureHealthCheck(...)100%210%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Worker\Extensions\HealthCheckExtensions.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using InventoryAlert.Domain.Common.Constants;
 2using InventoryAlert.Domain.Configuration;
 3using Microsoft.AspNetCore.Diagnostics.HealthChecks;
 4
 5namespace InventoryAlert.Worker.Extensions;
 6
 7public static class HealthCheckExtensions
 8{
 9    public static void SetupHealthCheck(this IServiceCollection services, AppSettings configuration)
 010    {
 011        services.AddHealthChecks()
 012            .AddNpgSql(
 013                configuration.Database.DefaultConnection,
 014                name: HealthCheck.DBHealthCheck,
 015                tags: new[] { HealthCheck.InfrastructureCheck, "db", "worker" });
 016    }
 17
 18    public static void ConfigureHealthCheck(this WebApplication app)
 019    {
 020        app.MapHealthChecks("/health", new HealthCheckOptions
 021        {
 022            Predicate = _ => true,
 023            ResponseWriter = async (context, report) =>
 024            {
 025                context.Response.ContentType = "application/json";
 026                var response = new
 027                {
 028                    status = report.Status.ToString(),
 029                    checks = report.Entries.Select(entry => new
 030                    {
 031                        name = entry.Key,
 032                        status = entry.Value.Status.ToString(),
 033                        description = entry.Value.Description,
 034                        duration = entry.Value.Duration
 035                    }),
 036                    totalDuration = report.TotalDuration
 037                };
 038                await context.Response.WriteAsJsonAsync(response);
 039            }
 040        });
 041    }
 42}
+
+
+
+ + \ No newline at end of file diff --git a/coverage/html/InventoryAlert.Worker_NewsSyncJob.html b/coverage/html/InventoryAlert.Worker_NewsSyncJob.html new file mode 100644 index 0000000..53e0b69 --- /dev/null +++ b/coverage/html/InventoryAlert.Worker_NewsSyncJob.html @@ -0,0 +1,266 @@ + + + + + + + +InventoryAlert.Worker.ScheduledJobs.NewsSyncJob - Coverage Report + +
+

< Summary

+
+
+
Information
+
+
+ + + + + + + + + + + + + +
Class:InventoryAlert.Worker.ScheduledJobs.NewsSyncJob
Assembly:InventoryAlert.Worker
File(s):C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Worker\ScheduledJobs\NewsSyncJob.cs
+
+
+
+
+
+
+
Line coverage
+
+
95%
+
+ + + + + + + + + + + + + + + + + + + + + +
Covered lines:89
Uncovered lines:4
Coverable lines:93
Total lines:127
Line coverage:95.6%
+
+
+
+
+
Branch coverage
+
+
85%
+
+ + + + + + + + + + + + + +
Covered branches:24
Total branches:28
Branch coverage:85.7%
+
+
+
+
+
Method coverage
+
+
+

Feature is only available for sponsors

+Upgrade to PRO version +
+
+
+
+

Metrics

+
+ +++++++ + + + + + + + + +
MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
ExecuteAsync()100%1166.66%
SyncMarketNewsInternalAsync()83.33%66100%
SyncCompanyNewsInternalAsync()100%11100%
<SyncCompanyNewsInternalAsync()83.33%1212100%
+
+

File(s)

+

C:\Users\TruongNhon\Desktop\project\InventoryManagementSystem\src\InventoryAlert.Worker\ScheduledJobs\NewsSyncJob.cs

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#LineLine coverage
 1using InventoryAlert.Domain.Entities.Dynamodb;
 2using InventoryAlert.Domain.Interfaces;
 3using InventoryAlert.Worker.Configuration;
 4using InventoryAlert.Worker.Models;
 5
 6namespace InventoryAlert.Worker.ScheduledJobs;
 7
 8/// <summary>
 9/// Consolidated job for fetching both Global Market News and Symbol-Specific Company News.
 10/// </summary>
 211public class NewsSyncJob(
 212    IUnitOfWork unitOfWork,
 213    IFinnhubClient finnhub,
 214    ICompanyNewsDynamoRepository companyNewsRepo,
 215    IMarketNewsDynamoRepository marketNewsRepo,
 216    WorkerSettings settings,
 217    ILogger<NewsSyncJob> logger)
 18{
 219    private readonly IUnitOfWork _unitOfWork = unitOfWork;
 220    private readonly IFinnhubClient _finnhub = finnhub;
 221    private readonly ICompanyNewsDynamoRepository _companyNewsRepo = companyNewsRepo;
 222    private readonly IMarketNewsDynamoRepository _marketNewsRepo = marketNewsRepo;
 223    private readonly WorkerSettings _settings = settings;
 224    private readonly ILogger<NewsSyncJob> _logger = logger;
 25
 26    public async Task<JobResult> ExecuteAsync(CancellationToken ct)
 227    {
 28        try
 229        {
 230            _logger.LogInformation("[NewsSync] Starting consolidated news synchronization...");
 31
 32            // 1. Sync Market News (Global Categories)
 233            int marketArticlesSaved = await SyncMarketNewsInternalAsync(ct);
 34
 35            // 2. Sync Company News (Symbol-Specific)
 236            int companyArticlesSaved = await SyncCompanyNewsInternalAsync(ct);
 37
 238            return new JobResult(JobStatus.Success,
 239                $"Sync complete. Saved {marketArticlesSaved} market articles and {companyArticlesSaved} company articles
 40        }
 041        catch (Exception ex)
 042        {
 043            _logger.LogError(ex, "[NewsSync] Critical failure during consolidated news sync.");
 044            return new JobResult(JobStatus.Failed, "Consolidated news sync failed.", Error: ex);
 45        }
 246    }
 47
 48    private async Task<int> SyncMarketNewsInternalAsync(CancellationToken ct)
 249    {
 250        string[] categories = { "general", "forex", "crypto", "merger" };
 251        int totalSaved = 0;
 52
 2253        foreach (var category in categories)
 854        {
 855            var articles = await _finnhub.GetMarketNewsAsync(category, ct);
 1556            if (articles == null || articles.Count == 0) continue;
 57
 158            var entries = articles
 159                .DistinctBy(a => a.Id)
 260                .Select(a => new MarketNewsDynamoEntry
 261                {
 262                    PK = $"CATEGORY#{category.ToUpperInvariant()}",
 263                    SK = $"TS#{a.Datetime}#ID#{a.Id}",
 264                    Category = category,
 265                    PublishedAt = DateTimeOffset.FromUnixTimeSeconds(a.Datetime).ToString("O"),
 266                    Headline = a.Headline ?? "No Headline",
 267                    Summary = a.Summary ?? string.Empty,
 268                    Source = a.Source ?? "Unknown",
 269                    Url = a.Url ?? string.Empty,
 270                    ImageUrl = a.Image ?? string.Empty,
 271                    NewsId = a.Id,
 272                    SyncedAt = DateTime.UtcNow.ToString("O")
 273                }).ToList();
 74
 175            await _marketNewsRepo.BatchSaveAsync(entries, ct);
 176            totalSaved += entries.Count;
 177        }
 78
 279        return totalSaved;
 280    }
 81
 82    private async Task<int> SyncCompanyNewsInternalAsync(CancellationToken ct)
 283    {
 284        var listings = await _unitOfWork.StockListings.GetAllAsync(ct);
 285        var to = DateTime.UtcNow.ToString("yyyy-MM-dd");
 286        var from = DateTime.UtcNow.AddDays(-1).ToString("yyyy-MM-dd");
 287        int totalSaved = 0;
 88
 89        // Using Parallel fetching for company news to speed up execution for many symbols
 290        var options = new ParallelOptions { MaxDegreeOfParallelism = _settings.MaxDegreeOfParallelism, CancellationToken
 91
 292        await Parallel.ForEachAsync(listings, options, async (listing, token) =>
 393        {
 294            try
 395            {
 396                var articles = await _finnhub.GetCompanyNewsAsync(listing.TickerSymbol, from, to, token);
 297                if (articles.Count == 0) return;
 298
 299                var entries = articles
 2100                    .DistinctBy(a => a.Id)
 4101                    .Select(a => new CompanyNewsDynamoEntry
 4102                    {
 4103                        PK = $"SYMBOL#{listing.TickerSymbol.ToUpperInvariant()}",
 4104                        SK = $"TS#{a.Datetime}#ID#{a.Id}",
 4105                        Symbol = listing.TickerSymbol,
 4106                        Timestamp = a.Datetime,
 4107                        Headline = a.Headline ?? "No Headline",
 4108                        Summary = a.Summary ?? string.Empty,
 4109                        Source = a.Source ?? "Unknown",
 4110                        Url = a.Url ?? string.Empty,
 4111                        ImageUrl = a.Image ?? string.Empty,
 4112                        NewsId = a.Id,
 4113                        SyncedAt = DateTime.UtcNow.ToString("O")
 4114                    }).ToList();
 2115
 2116                await _companyNewsRepo.BatchSaveAsync(entries, token);
 2117                Interlocked.Add(ref totalSaved, entries.Count);
 2118            }
 1119            catch (Exception ex)
 1120            {
 1121                _logger.LogWarning("[NewsSync] Failed to fetch company news for {Symbol}: {Msg}", listing.TickerSymbol, 
 1122            }
 5123        });
 124
 2125        return totalSaved;
 2126    }
 127}
+
+
+
+ + \ No newline at end of file diff --git a/doc/archive/EVENT_DRIVEN_PLAN.md b/doc/archive/EVENT_DRIVEN_PLAN.md index 07e6520..6e6af8e 100644 --- a/doc/archive/EVENT_DRIVEN_PLAN.md +++ b/doc/archive/EVENT_DRIVEN_PLAN.md @@ -101,13 +101,13 @@ All events follow the standard SNS notification format: ### Event Types -| EventType | Trigger | Finnhub Source | -| :--- | :--- | :--- | -| `MarketPriceAlert` | Price drops beyond `PriceAlertThreshold` | `/quote` | -| `StockLowAlert` | `StockCount` drops below `StockAlertThreshold` | Internal DB | -| `EarningsAlert` | A tracked company announces earnings | `/stock/earnings` | -| `InsiderSellAlert` | Insider selling detected above a threshold | `/stock/insider-transactions` | -| `CompanyNewsAlert` | High-impact news published for a tracked stock | `/company-news` | +| EventType | Trigger | Finnhub Source | +| :----------------- | :--------------------------------------------- | :---------------------------- | +| `MarketPriceAlert` | Price drops beyond `PriceAlertThreshold` | `/quote` | +| `StockLowAlert` | `StockCount` drops below `StockAlertThreshold` | Internal DB | +| `EarningsAlert` | A tracked company announces earnings | `/stock/earnings` | +| `InsiderSellAlert` | Insider selling detected above a threshold | `/stock/insider-transactions` | +| `CompanyNewsAlert` | High-impact news published for a tracked stock | `/company-news` | ### New Domain Models @@ -170,12 +170,12 @@ public record CompanyNewsAlertPayload ### New Endpoints -| Method | Route | Purpose | -| :--- | :--- | :--- | -| `POST` | `/api/events` | Receive any generic event and publish to SNS | -| `POST` | `/api/events/market-alert` | Manually trigger a `MarketPriceAlert` event | -| `POST` | `/api/events/news-alert` | Manually trigger a `CompanyNewsAlert` event | -| `GET` | `/api/events/types` | List all supported event types | +| Method | Route | Purpose | +| :----- | :------------------------- | :------------------------------------------- | +| `POST` | `/api/events` | Receive any generic event and publish to SNS | +| `POST` | `/api/events/market-alert` | Manually trigger a `MarketPriceAlert` event | +| `POST` | `/api/events/news-alert` | Manually trigger a `CompanyNewsAlert` event | +| `GET` | `/api/events/types` | List all supported event types | ### New Service: `IEventPublisher` @@ -191,14 +191,14 @@ IEventPublisher Persist all published events to the DB for auditing: -| Column | Type | Notes | -| :--- | :--- | :--- | -| `Id` | `int` | PK | -| `MessageId` | `string` | From SNS | -| `EventType` | `string` | e.g. `MarketPriceAlert` | -| `Payload` | `string` | JSON body | -| `PublishedAt` | `DateTime` | UTC | -| `SourceService` | `string` | e.g. `InventoryAlert.Api` | +| Column | Type | Notes | +| :-------------- | :--------- | :------------------------ | +| `Id` | `int` | PK | +| `MessageId` | `string` | From SNS | +| `EventType` | `string` | e.g. `MarketPriceAlert` | +| `Payload` | `string` | JSON body | +| `PublishedAt` | `DateTime` | UTC | +| `SourceService` | `string` | e.g. `InventoryAlert.Api` | --- @@ -214,13 +214,13 @@ This is a separate **.NET Worker Service** (minimal API or `BackgroundService` h ### Architecture: Hangfire Jobs -| Job Name | Schedule | Responsibility | Finnhub Call | -| :--- | :--- | :--- | :--- | -| `PollSqsJob` | Every 30s | Dequeue messages from SQS and dispatch to handlers | None | -| `SyncPricesJob` | Every 10m | Update `CurrentPrice` for all products | `/quote` | -| `EarningsCheckJob` | Every 6h | Check if tracked symbols have new earnings | `/stock/earnings` | -| `InsiderTxCheckJob` | Every 6h | Check for insider selling on tracked symbols | `/stock/insider-transactions` | -| `NewsCheckJob` | Every 1h | Fetch latest news for tracked symbols | `/company-news` | +| Job Name | Schedule | Responsibility | Finnhub Call | +| :------------------ | :-------- | :------------------------------------------------- | :---------------------------- | +| `PollSqsJob` | Every 30s | Dequeue messages from SQS and dispatch to handlers | None | +| `SyncPricesJob` | Every 10m | Update `CurrentPrice` for all products | `/quote` | +| `EarningsCheckJob` | Every 6h | Check if tracked symbols have new earnings | `/stock/earnings` | +| `InsiderTxCheckJob` | Every 6h | Check for insider selling on tracked symbols | `/stock/insider-transactions` | +| `NewsCheckJob` | Every 1h | Fetch latest news for tracked symbols | `/company-news` | ### SQS Consumer Flow @@ -241,12 +241,12 @@ PollSqsJob runs → ### Redis Caching Strategy -| Key Pattern | Stores | TTL | Populated By | -| :--- | :--- | :--- | :--- | -| `product:quote:{AAPL}` | Latest price quote | 60 seconds | `SyncPricesJob` | -| `alert:history:{AAPL}` | Last alert timestamp | 24 hours | `PollSqsJob` (dedup) | -| `job:last-run:EarningsCheckJob` | Last run timestamp | 10 minutes | Each Job | -| `news:{AAPL}:latest` | Latest news headline | 1 hour | `NewsCheckJob` | +| Key Pattern | Stores | TTL | Populated By | +| :------------------------------ | :------------------- | :--------- | :------------------- | +| `product:quote:{AAPL}` | Latest price quote | 60 seconds | `SyncPricesJob` | +| `alert:history:{AAPL}` | Last alert timestamp | 24 hours | `PollSqsJob` (dedup) | +| `job:last-run:EarningsCheckJob` | Last run timestamp | 10 minutes | Each Job | +| `news:{AAPL}:latest` | Latest news headline | 1 hour | `NewsCheckJob` | --- @@ -300,13 +300,13 @@ Time: 2026-04-04 02:00 UTC ## 🧩 Business Logic Scenarios (Finnhub Free Tier) -| Scenario | Entities Affected | Finnhub Endpoint | Event Published | -| :--- | :--- | :--- | :--- | -| **Price Drop > threshold** | `Product.CurrentPrice` | `/quote` | `MarketPriceAlert` | -| **Earnings miss > 10%** | New `EarningsRecord` entity | `/stock/earnings` | `EarningsAlert` | -| **Insider sells > $1M** | New `InsiderTransaction` entity | `/stock/insider-transactions` | `InsiderSellAlert` | -| **High impact news** | New `NewsRecord` entity | `/company-news` | `CompanyNewsAlert` | -| **Market closes** | Trigger close-of-day sync | `/stock/market-status` | Internal only | +| Scenario | Entities Affected | Finnhub Endpoint | Event Published | +| :------------------------- | :------------------------------ | :---------------------------- | :----------------- | +| **Price Drop > threshold** | `Product.CurrentPrice` | `/quote` | `MarketPriceAlert` | +| **Earnings miss > 10%** | New `EarningsRecord` entity | `/stock/earnings` | `EarningsAlert` | +| **Insider sells > $1M** | New `InsiderTransaction` entity | `/stock/insider-transactions` | `InsiderSellAlert` | +| **High impact news** | New `NewsRecord` entity | `/company-news` | `CompanyNewsAlert` | +| **Market closes** | Trigger close-of-day sync | `/stock/market-status` | Internal only | ### New Entities (Database Changes Required) diff --git a/doc/archive/EVENT_SETUP_COMMANDS.md b/doc/archive/EVENT_SETUP_COMMANDS.md index d7a6157..813ead5 100644 --- a/doc/archive/EVENT_SETUP_COMMANDS.md +++ b/doc/archive/EVENT_SETUP_COMMANDS.md @@ -11,9 +11,9 @@ | :------------------------- | :-------------- | :---------------------------------------------- | | `InventoryAlert.Api` | ASP.NET Web API | ✅ Existing — extended with event endpoints | | `InventoryAlert.Contracts` | Class Library | ✅ Done — shared event schemas + domain entities | -| `InventoryAlert.Worker` | Worker Service | ✅ Done — Hangfire + SQS consumer | -| `InventoryAlert.Sample` | Console App | ✅ Done — sample event publisher | -| `InventoryAlert.Tests` | xUnit Test | ✅ Existing | +| `InventoryAlert.Worker` | Worker Service | ✅ Done — Hangfire + SQS consumer | +| `InventoryAlert.Sample` | Console App | ✅ Done — sample event publisher | +| `InventoryAlert.Tests` | xUnit Test | ✅ Existing | --- diff --git a/doc/archive/MANUAL_TESTING.md b/doc/archive/MANUAL_TESTING.md index 8bf92d6..99afe3e 100644 --- a/doc/archive/MANUAL_TESTING.md +++ b/doc/archive/MANUAL_TESTING.md @@ -21,12 +21,12 @@ last_updated: 2026-04-05 ## 🚀 Pre-Flight: Start & Health Check -| # | Step | Expected | -|---|---|---| -| 1 | Run `docker-compose up --build` | All 5 containers start without error | -| 2 | Check `moto-init` logs | `SQS queue created`, `DynamoDB table created` messages visible | -| 3 | `GET http://localhost:5000/swagger` | Swagger UI loads with all endpoints | -| 4 | Check `logs/inventoryalert.log` exists | Serilog has created the log file | +| # | Step | Expected | +| --- | -------------------------------------- | -------------------------------------------------------------- | +| 1 | Run `docker-compose up --build` | All 5 containers start without error | +| 2 | Check `moto-init` logs | `SQS queue created`, `DynamoDB table created` messages visible | +| 3 | `GET http://localhost:5000/swagger` | Swagger UI loads with all endpoints | +| 4 | Check `logs/inventoryalert.log` exists | Serilog has created the log file | > 🔍 **REVIEW:** There is no `/health` endpoint defined. If the `api` or `worker` container crashes silently, there is no heartbeat to detect it. Consider adding `app.MapHealthChecks("/health")`. @@ -87,18 +87,18 @@ POST /api/products ### TC-PROD-02 — Create Product (Validation Failures) -| Sub-case | Payload Change | Expected | -|---|---|---| -| Empty name | `"name": ""` | ❌ `400` — `"Name is required."` | -| Name too long | `"name": "A" * 257` | ❌ `400` — `"Name must not exceed 256 characters."` | -| Lowercase ticker | `"tickerSymbol": "aapl"` | ❌ `400` — `"TickerSymbol must be 1–16 uppercase letters"` | -| Ticker with numbers | `"tickerSymbol": "AAP1"` | ❌ `400` — regex rejects non-alpha characters | -| `originPrice: 0` | `"originPrice": 0` | ❌ `400` — `"OriginPrice must be greater than 0."` | -| `originPrice: -1` | `"originPrice": -1` | ❌ `400` | -| `currentPrice: -1` | `"currentPrice": -1` | ❌ `400` — `"CurrentPrice must be 0 or greater."` | -| `stockCount: -1` | `"stockCount": -1` | ❌ `400` | -| `priceAlertThreshold: 1.1` | `"priceAlertThreshold": 1.1` | ❌ `400` — `"must be between 0.0 and 1.0"` | -| `priceAlertThreshold: -0.1` | `"priceAlertThreshold": -0.1` | ❌ `400` | +| Sub-case | Payload Change | Expected | +| --------------------------- | ----------------------------- | --------------------------------------------------------- | +| Empty name | `"name": ""` | ❌ `400` — `"Name is required."` | +| Name too long | `"name": "A" * 257` | ❌ `400` — `"Name must not exceed 256 characters."` | +| Lowercase ticker | `"tickerSymbol": "aapl"` | ❌ `400` — `"TickerSymbol must be 1–16 uppercase letters"` | +| Ticker with numbers | `"tickerSymbol": "AAP1"` | ❌ `400` — regex rejects non-alpha characters | +| `originPrice: 0` | `"originPrice": 0` | ❌ `400` — `"OriginPrice must be greater than 0."` | +| `originPrice: -1` | `"originPrice": -1` | ❌ `400` | +| `currentPrice: -1` | `"currentPrice": -1` | ❌ `400` — `"CurrentPrice must be 0 or greater."` | +| `stockCount: -1` | `"stockCount": -1` | ❌ `400` | +| `priceAlertThreshold: 1.1` | `"priceAlertThreshold": 1.1` | ❌ `400` — `"must be between 0.0 and 1.0"` | +| `priceAlertThreshold: -0.1` | `"priceAlertThreshold": -0.1` | ❌ `400` | > 🔍 **REVIEW:** `tickerSymbol` is declared as `string?` (nullable) in `ProductRequest.cs` but the validator treats it as required. Confirm the swagger UI does not allow submitting without it. Check if `null` body field passes validation. @@ -387,16 +387,16 @@ POST /api/products/bulk ## 🔍 Summary: All Items Needing Human Review -| ID | Location | Issue | Priority | -|---|---|---|---| -| A | `AuthController.cs:26-27` | `admin`/`admin123` fallback always active if config missing | 🔴 High | -| B | `appsettings.Docker.json:7` | Real Finnhub API key possibly committed in git history | 🔴 High | -| C | `ProductsController.cs` — `UpdateStockCount` | No validation on negative `stockCount` query param | 🟡 Medium | -| D | `ProductService.cs` — `GetPriceLossAlertsAsync` | `LastAlertSentAt` cooldown is never written — gate always bypassed | 🟡 Medium | -| E | `EventsController.cs` — `PublishEvent` | Unknown event types accepted without validation against `EventTypes.All` | 🟡 Medium | -| F | `ProductService.cs:55` | Cache TTL (10 min) is hardcoded — no config key | 🟢 Low | -| G | No health endpoint | No `/health` or `/ready` probe for Docker orchestration | 🟢 Low | -| H | `ProductRequest.cs:7` | `TickerSymbol` is `string?` (nullable) but validator treats it as required | 🟢 Low | -| I | `TC-BULK-02` / `TC-BULK-03` | Validation behavior for bulk insert edge cases unverified | 🟢 Low | -| J | DLQ monitoring | No alerting on dead-letter queue depth | 🟢 Low | -| K | `MinuteSyncCurrentPrice` | Verify setting is actually wired into Hangfire cron in Worker `Program.cs` | 🟢 Low | +| ID | Location | Issue | Priority | +| --- | ----------------------------------------------- | -------------------------------------------------------------------------- | -------- | +| A | `AuthController.cs:26-27` | `admin`/`admin123` fallback always active if config missing | 🔴 High | +| B | `appsettings.Docker.json:7` | Real Finnhub API key possibly committed in git history | 🔴 High | +| C | `ProductsController.cs` — `UpdateStockCount` | No validation on negative `stockCount` query param | 🟡 Medium | +| D | `ProductService.cs` — `GetPriceLossAlertsAsync` | `LastAlertSentAt` cooldown is never written — gate always bypassed | 🟡 Medium | +| E | `EventsController.cs` — `PublishEvent` | Unknown event types accepted without validation against `EventTypes.All` | 🟡 Medium | +| F | `ProductService.cs:55` | Cache TTL (10 min) is hardcoded — no config key | 🟢 Low | +| G | No health endpoint | No `/health` or `/ready` probe for Docker orchestration | 🟢 Low | +| H | `ProductRequest.cs:7` | `TickerSymbol` is `string?` (nullable) but validator treats it as required | 🟢 Low | +| I | `TC-BULK-02` / `TC-BULK-03` | Validation behavior for bulk insert edge cases unverified | 🟢 Low | +| J | DLQ monitoring | No alerting on dead-letter queue depth | 🟢 Low | +| K | `MinuteSyncCurrentPrice` | Verify setting is actually wired into Hangfire cron in Worker `Program.cs` | 🟢 Low | diff --git a/doc/archive/PROJECT_OVERVIEW.md b/doc/archive/PROJECT_OVERVIEW.md index f134336..f428a83 100644 --- a/doc/archive/PROJECT_OVERVIEW.md +++ b/doc/archive/PROJECT_OVERVIEW.md @@ -16,15 +16,15 @@ last_updated: 2026-04-05 ## 1. Solution Project Map -| Project | SDK | Role | -|---|---|---| -| `InventoryAlert.Api` | `Microsoft.NET.Sdk.Web` | REST API — Controllers, Application Services, Infrastructure | -| `InventoryAlert.Worker` | `Microsoft.NET.Sdk.Web` | Background processor — Hangfire jobs, SQS consumers, Event Handlers | -| `InventoryAlert.Contracts` | `Microsoft.NET.Sdk` | Shared kernel — Entities, Events, Constants. Zero dependencies. | -| `InventoryAlert.Sample` | `Microsoft.NET.Sdk` | Local test publisher — bypasses API to directly push events to SNS | -| `InventoryAlert.UnitTests` | `Microsoft.NET.Sdk` | xUnit + Moq + FluentAssertions unit test suite | -| `InventoryAlert.IntegrationTests` | `Microsoft.NET.Sdk` | Testcontainers.PostgreSql integration tests | -| `InventoryAlert.ArchitectureTests` | `Microsoft.NET.Sdk` | NetArchTest.Rules — automated DDD boundary enforcement | +| Project | SDK | Role | +| ---------------------------------- | ----------------------- | ------------------------------------------------------------------- | +| `InventoryAlert.Api` | `Microsoft.NET.Sdk.Web` | REST API — Controllers, Application Services, Infrastructure | +| `InventoryAlert.Worker` | `Microsoft.NET.Sdk.Web` | Background processor — Hangfire jobs, SQS consumers, Event Handlers | +| `InventoryAlert.Contracts` | `Microsoft.NET.Sdk` | Shared kernel — Entities, Events, Constants. Zero dependencies. | +| `InventoryAlert.Sample` | `Microsoft.NET.Sdk` | Local test publisher — bypasses API to directly push events to SNS | +| `InventoryAlert.UnitTests` | `Microsoft.NET.Sdk` | xUnit + Moq + FluentAssertions unit test suite | +| `InventoryAlert.IntegrationTests` | `Microsoft.NET.Sdk` | Testcontainers.PostgreSql integration tests | +| `InventoryAlert.ArchitectureTests` | `Microsoft.NET.Sdk` | NetArchTest.Rules — automated DDD boundary enforcement | --- @@ -62,13 +62,13 @@ The `Contracts` project has **zero external NuGet dependencies** and is the sing ### Domain Entities -| Class | Key Fields | -|---|---| -| `Product` | `Id`, `Name`, `TickerSymbol`, `OriginPrice`, `CurrentPrice`, `PriceAlertThreshold` (double, e.g. `0.2` = 20%), `StockCount`, `StockAlertThreshold`, `LastAlertSentAt` (nullable DateTime for alert cooldown) | -| `EventLog` | DynamoDB audit record per published event | -| `EarningsRecord` | Persisted EPS data from Finnhub earnings events | -| `NewsRecord` | Persisted company news headline | -| `InsiderTransaction` | Persisted insider sell transaction | +| Class | Key Fields | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Product` | `Id`, `Name`, `TickerSymbol`, `OriginPrice`, `CurrentPrice`, `PriceAlertThreshold` (double, e.g. `0.2` = 20%), `StockCount`, `StockAlertThreshold`, `LastAlertSentAt` (nullable DateTime for alert cooldown) | +| `EventLog` | DynamoDB audit record per published event | +| `EarningsRecord` | Persisted EPS data from Finnhub earnings events | +| `NewsRecord` | Persisted company news headline | +| `InsiderTransaction` | Persisted insider sell transaction | ### Event Pipeline Types @@ -87,13 +87,13 @@ public record EventEnvelope **`EventTypes` static class** — canonical reverse-DNS event names: -| Constant | Value | -|---|---| -| `MarketPriceAlert` | `inventoryalert.pricing.price-drop.v1` | -| `StockLowAlert` | `inventoryalert.inventory.stock-low.v1` | -| `EarningsAlert` | `inventoryalert.fundamentals.earnings.v1` | +| Constant | Value | +| ------------------ | --------------------------------------------- | +| `MarketPriceAlert` | `inventoryalert.pricing.price-drop.v1` | +| `StockLowAlert` | `inventoryalert.inventory.stock-low.v1` | +| `EarningsAlert` | `inventoryalert.fundamentals.earnings.v1` | | `InsiderSellAlert` | `inventoryalert.fundamentals.insider-sell.v1` | -| `CompanyNewsAlert` | `inventoryalert.news.headline.v1` | +| `CompanyNewsAlert` | `inventoryalert.news.headline.v1` | --- @@ -111,13 +111,13 @@ public record EventEnvelope 2. Each message body is deserialized into `EventEnvelope`. 3. An internal **Dictionary Dispatcher** reads `EventType` and invokes the corresponding `IEventHandler`: -| EventType | Handler | Action | -|---|---|---| -| `MarketPriceAlert` | `PriceAlertHandler` | Logs a structured `🚨 PRICE DROP ALERT` warning; Telegram plug-in point | -| `EarningsAlert` | `EarningsHandler` | Persists `EarningsRecord` to PostgreSQL via `WorkerDbContext` | -| `CompanyNewsAlert` | `NewsHandler` | Persists `NewsRecord` to PostgreSQL | -| `InsiderSellAlert` | `InsiderHandler` | Persists `InsiderTransaction` to PostgreSQL | -| *(unknown)* | `UnknownEventHandler` | Logs and discards gracefully — no crash | +| EventType | Handler | Action | +| ------------------ | --------------------- | ---------------------------------------------------------------------- | +| `MarketPriceAlert` | `PriceAlertHandler` | Logs a structured `🚨 PRICE DROP ALERT` warning; Telegram plug-in point | +| `EarningsAlert` | `EarningsHandler` | Persists `EarningsRecord` to PostgreSQL via `WorkerDbContext` | +| `CompanyNewsAlert` | `NewsHandler` | Persists `NewsRecord` to PostgreSQL | +| `InsiderSellAlert` | `InsiderHandler` | Persists `InsiderTransaction` to PostgreSQL | +| *(unknown)* | `UnknownEventHandler` | Logs and discards gracefully — no crash | 4. **Dead-Letter Queue**: After `ApproximateReceiveCount` exceeds 3, SQS automaticaly routes to `inventory-event-dlq`. @@ -125,12 +125,12 @@ public record EventEnvelope ## 5. Storage Layer -| Store | Purpose | Access Pattern | -|---|---|---| +| Store | Purpose | Access Pattern | +| ---------------------------------- | --------------------------------------------------------------- | -------------------------------------------------------------- | | **PostgreSQL** (Npgsql EF Core 10) | `Product`, `EarningsRecord`, `NewsRecord`, `InsiderTransaction` | `IProductRepository` → `GenericRepository` → `AppDbContext` | -| **AWS DynamoDB** | `EventLog` audit trail (append-only, TTL-expiring) | `DynamoEventLogRepository`, accessed via `IEventService` | -| **IMemoryCache** (ASP.NET) | `Product` single-item cache (`Product_{id}`, 10 min TTL) | `ProductService.GetProductByIdAsync` — cache-aside pattern | -| **Hangfire** | Job scheduling metadata | Stored in PostgreSQL (`WorkerDbContext`) | +| **AWS DynamoDB** | `EventLog` audit trail (append-only, TTL-expiring) | `DynamoEventLogRepository`, accessed via `IEventService` | +| **IMemoryCache** (ASP.NET) | `Product` single-item cache (`Product_{id}`, 10 min TTL) | `ProductService.GetProductByIdAsync` — cache-aside pattern | +| **Hangfire** | Job scheduling metadata | Stored in PostgreSQL (`WorkerDbContext`) | ### Transaction Pattern (`ExecuteTransactionAsync`) All writes use the project-mandated capture pattern: @@ -177,12 +177,12 @@ All Docker files are linked as **Solution Items** in `InventoryManagementSystem. ## 8. Testing Strategy -| Suite | Count | Tools | -|---|---|---| -| `InventoryAlert.UnitTests` | 66 tests | xUnit, Moq, FluentAssertions, EF InMemory | -| `InventoryAlert.IntegrationTests` | 5 tests | Testcontainers.PostgreSql | -| `InventoryAlert.ArchitectureTests` | 9 tests | NetArchTest.Rules | -| **Total** | **80 tests, 0 failures** | | +| Suite | Count | Tools | +| ---------------------------------- | ------------------------ | ----------------------------------------- | +| `InventoryAlert.UnitTests` | 66 tests | xUnit, Moq, FluentAssertions, EF InMemory | +| `InventoryAlert.IntegrationTests` | 5 tests | Testcontainers.PostgreSql | +| `InventoryAlert.ArchitectureTests` | 9 tests | NetArchTest.Rules | +| **Total** | **80 tests, 0 failures** | | Key unit test rules: - `ExecuteTransactionAsync` mocks **must** invoke the delegate: `.Returns, CancellationToken>((action, _) => action())` diff --git a/doc/archive/SETUP_COMMANDS.md b/doc/archive/SETUP_COMMANDS.md index e46f479..a93171f 100644 --- a/doc/archive/SETUP_COMMANDS.md +++ b/doc/archive/SETUP_COMMANDS.md @@ -7,13 +7,13 @@ ## 📁 Final Project Names -| Project | Type | Purpose | -| :--- | :--- | :--- | -| `InventoryAlert.Api` | ASP.NET Web API | ✅ Existing — extended with event endpoints | -| `InventoryAlert.Contracts` | Class Library | ✅ Done — shared event schemas + domain entities | -| `InventoryAlert.Worker` | Worker Service | ✅ Done — Hangfire + SQS consumer | -| `InventoryAlert.Sample` | Console App | ✅ Done — sample event publisher | -| `InventoryAlert.Tests` | xUnit Test | ✅ Existing | +| Project | Type | Purpose | +| :------------------------- | :-------------- | :---------------------------------------------- | +| `InventoryAlert.Api` | ASP.NET Web API | ✅ Existing — extended with event endpoints | +| `InventoryAlert.Contracts` | Class Library | ✅ Done — shared event schemas + domain entities | +| `InventoryAlert.Worker` | Worker Service | ✅ Done — Hangfire + SQS consumer | +| `InventoryAlert.Sample` | Console App | ✅ Done — sample event publisher | +| `InventoryAlert.Tests` | xUnit Test | ✅ Existing | --- @@ -184,11 +184,11 @@ Automatically creates SNS/SQS resources on first Docker boot: - **Script:** `SolutionFolder/moto-init/init-sqs.sh` - **Runs via:** `moto-init` service in docker-compose (one-shot, exits when done) -| Resource | Type | Notes | -| :--- | :--- | :--- | +| Resource | Type | Notes | +| :-------------------- | :----------- | :--------------------------------- | | `inventory-event-dlq` | SQS Standard | Dead Letter Queue (max 3 receives) | -| `event-queue` | SQS Standard | Main queue — DLQ redrive wired | -| `inventory-events` | SNS Topic | Auto-subscribed to `event-queue` | +| `event-queue` | SQS Standard | Main queue — DLQ redrive wired | +| `inventory-events` | SNS Topic | Auto-subscribed to `event-queue` | > Script is **idempotent** — checks before creating, safe to re-run. diff --git a/doc/archive/docker/DOCKER_MESSAGING_PLAN.md b/doc/archive/docker/DOCKER_MESSAGING_PLAN.md index 47d4a51..2b2d6eb 100644 --- a/doc/archive/docker/DOCKER_MESSAGING_PLAN.md +++ b/doc/archive/docker/DOCKER_MESSAGING_PLAN.md @@ -176,13 +176,13 @@ using (var scope = app.Services.CreateScope()) ### Decision: Hangfire vs BackgroundService -| Feature | `BackgroundService` (Current) | Hangfire | -|---|---|---| -| Dashboard UI | ❌ None | ✅ `/hangfire` | -| Retry on failure | ❌ Manual | ✅ Built-in | -| Job history / logs | ❌ Just console logs | ✅ Persistent DB | -| Recurring schedule | ⚠️ PeriodicTimer | ✅ Cron expressions | -| Complexity | ✅ Simple | ⚠️ Needs DB table | +| Feature | `BackgroundService` (Current) | Hangfire | +| ------------------ | ----------------------------- | ------------------ | +| Dashboard UI | ❌ None | ✅ `/hangfire` | +| Retry on failure | ❌ Manual | ✅ Built-in | +| Job history / logs | ❌ Just console logs | ✅ Persistent DB | +| Recurring schedule | ⚠️ PeriodicTimer | ✅ Cron expressions | +| Complexity | ✅ Simple | ⚠️ Needs DB table | **Recommendation:** Keep `BackgroundService` for now. Add Hangfire only when you need the Dashboard or retry management. diff --git a/doc/archive/error_handling_and_response_standard.md b/doc/archive/error_handling_and_response_standard.md index cf478e6..e610ae4 100644 --- a/doc/archive/error_handling_and_response_standard.md +++ b/doc/archive/error_handling_and_response_standard.md @@ -162,15 +162,15 @@ This aligns with many .NET clients and tooling, but is a bigger change and may n This table is a suggested baseline: -| HTTP | Code | When | -|---:|---|---| -| 400 | `InventoryAlert.BAD_REQUEST` | invalid input shape, parsing, validation failures | -| 401 | `InventoryAlert.UNAUTHORIZED` | missing/invalid auth, invalid refresh token | -| 403 | `InventoryAlert.FORBIDDEN` | authenticated but lacks permission | -| 404 | `InventoryAlert.NOT_FOUND` | resource id not found (rule id, notification id, etc.) | -| 409 | `InventoryAlert.CONFLICT` | version conflict / uniqueness / state conflict | -| 422 | `InventoryAlert.UNPROCESSABLE_ENTITY` | business-rule violation when input is syntactically valid | -| 500 | `InventoryAlert.INTERNAL_ERROR` (or `GENERAL_ERROR`) | unexpected server failures | +| HTTP | Code | When | +| ---: | ---------------------------------------------------- | --------------------------------------------------------- | +| 400 | `InventoryAlert.BAD_REQUEST` | invalid input shape, parsing, validation failures | +| 401 | `InventoryAlert.UNAUTHORIZED` | missing/invalid auth, invalid refresh token | +| 403 | `InventoryAlert.FORBIDDEN` | authenticated but lacks permission | +| 404 | `InventoryAlert.NOT_FOUND` | resource id not found (rule id, notification id, etc.) | +| 409 | `InventoryAlert.CONFLICT` | version conflict / uniqueness / state conflict | +| 422 | `InventoryAlert.UNPROCESSABLE_ENTITY` | business-rule violation when input is syntactically valid | +| 500 | `InventoryAlert.INTERNAL_ERROR` (or `GENERAL_ERROR`) | unexpected server failures | Recommendation: diff --git a/doc/archive/naming_and_structure_audit.md b/doc/archive/naming_and_structure_audit.md index ee55cb2..e39a6b8 100644 --- a/doc/archive/naming_and_structure_audit.md +++ b/doc/archive/naming_and_structure_audit.md @@ -68,13 +68,13 @@ This document evaluates whether repository naming and file locations match the c ## Current Repository Top-Level Layout -| Path | Purpose | Notes | -|---|---|---| -| `.agents/` | Agent workflows/skills/scripts | BM25 tooling lives in `.agents/scripts/core/`. | -| `doc/` | Working internal documentation | Should use YAML frontmatter (see `/doc` skill standard). | -| `InventoryManagementSystem/` | .NET solution root | Contains `InventoryManagementSystem.sln` and all `.csproj`. | -| `InventoryAlert.UI/` | Next.js UI | Frontend app; has its own `package.json`. | -| `InventoryAlert.Wiki/` | Docusaurus documentation site | Built output in `InventoryAlert.Wiki/build` (should remain gitignored). | +| Path | Purpose | Notes | +| ---------------------------- | ------------------------------ | ----------------------------------------------------------------------- | +| `.agents/` | Agent workflows/skills/scripts | BM25 tooling lives in `.agents/scripts/core/`. | +| `doc/` | Working internal documentation | Should use YAML frontmatter (see `/doc` skill standard). | +| `InventoryManagementSystem/` | .NET solution root | Contains `InventoryManagementSystem.sln` and all `.csproj`. | +| `InventoryAlert.UI/` | Next.js UI | Frontend app; has its own `package.json`. | +| `InventoryAlert.Wiki/` | Docusaurus documentation site | Built output in `InventoryAlert.Wiki/build` (should remain gitignored). | ## .NET Solution Structure (`InventoryManagementSystem/`) @@ -98,10 +98,10 @@ This document evaluates whether repository naming and file locations match the c ## Frontend App Structure (`InventoryAlert.UI/`) -| Path | Purpose | -|---|---| -| `InventoryAlert.UI/src/` | Next.js app code | -| `InventoryAlert.UI/public/` | Static assets | +| Path | Purpose | +| -------------------------------- | --------------------- | +| `InventoryAlert.UI/src/` | Next.js app code | +| `InventoryAlert.UI/public/` | Static assets | | `InventoryAlert.UI/package.json` | Frontend scripts/deps | **Naming convention check** @@ -110,11 +110,11 @@ This document evaluates whether repository naming and file locations match the c ## Wiki Site Structure (`InventoryAlert.Wiki/`) -| Path | Purpose | -|---|---| -| `InventoryAlert.Wiki/docs/` | Docusaurus docs source (what we should edit) | -| `InventoryAlert.Wiki/sidebars.ts` | Autogenerated sidebar config | -| `InventoryAlert.Wiki/build/` | Generated static site output | +| Path | Purpose | +| --------------------------------- | -------------------------------------------- | +| `InventoryAlert.Wiki/docs/` | Docusaurus docs source (what we should edit) | +| `InventoryAlert.Wiki/sidebars.ts` | Autogenerated sidebar config | +| `InventoryAlert.Wiki/build/` | Generated static site output | **Naming convention check** - `docs/` subfolders use ordered prefixes like `04-execution-flows`: OK for navigation. diff --git a/scripts/export-wiki.mjs b/scripts/export-wiki.mjs index 067477e..4ad2812 100644 --- a/scripts/export-wiki.mjs +++ b/scripts/export-wiki.mjs @@ -5,7 +5,7 @@ import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); -const sourceDir = path.resolve(__dirname, '../InventoryAlert.Wiki/docs'); +const sourceDir = path.resolve(__dirname, '../src/ui/InventoryAlert.Wiki/docs'); const targetDir = path.resolve(__dirname, '../artifacts/wiki-export'); function processFile(filePath, rootSourceDir, outDir) { diff --git a/InventoryManagementSystem/.dockerignore b/src/.dockerignore similarity index 100% rename from InventoryManagementSystem/.dockerignore rename to src/.dockerignore diff --git a/InventoryManagementSystem/Directory.Packages.props b/src/Directory.Packages.props similarity index 100% rename from InventoryManagementSystem/Directory.Packages.props rename to src/Directory.Packages.props diff --git a/InventoryManagementSystem/InventoryAlert.Api/Configuration/ApiSettings.cs b/src/InventoryAlert.Api/Configuration/ApiSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Configuration/ApiSettings.cs rename to src/InventoryAlert.Api/Configuration/ApiSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Controllers/AlertRulesController.cs b/src/InventoryAlert.Api/Controllers/AlertRulesController.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Controllers/AlertRulesController.cs rename to src/InventoryAlert.Api/Controllers/AlertRulesController.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Controllers/AuthController.cs b/src/InventoryAlert.Api/Controllers/AuthController.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Controllers/AuthController.cs rename to src/InventoryAlert.Api/Controllers/AuthController.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Controllers/EventsController.cs b/src/InventoryAlert.Api/Controllers/EventsController.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Controllers/EventsController.cs rename to src/InventoryAlert.Api/Controllers/EventsController.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Controllers/MarketController.cs b/src/InventoryAlert.Api/Controllers/MarketController.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Controllers/MarketController.cs rename to src/InventoryAlert.Api/Controllers/MarketController.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Controllers/NotificationsController.cs b/src/InventoryAlert.Api/Controllers/NotificationsController.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Controllers/NotificationsController.cs rename to src/InventoryAlert.Api/Controllers/NotificationsController.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Controllers/PortfolioController.cs b/src/InventoryAlert.Api/Controllers/PortfolioController.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Controllers/PortfolioController.cs rename to src/InventoryAlert.Api/Controllers/PortfolioController.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Controllers/StocksController.cs b/src/InventoryAlert.Api/Controllers/StocksController.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Controllers/StocksController.cs rename to src/InventoryAlert.Api/Controllers/StocksController.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Controllers/WatchlistController.cs b/src/InventoryAlert.Api/Controllers/WatchlistController.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Controllers/WatchlistController.cs rename to src/InventoryAlert.Api/Controllers/WatchlistController.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Dockerfile b/src/InventoryAlert.Api/Dockerfile similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Dockerfile rename to src/InventoryAlert.Api/Dockerfile diff --git a/InventoryManagementSystem/InventoryAlert.Api/Extensions/CompressionExtension.cs b/src/InventoryAlert.Api/Extensions/CompressionExtension.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Extensions/CompressionExtension.cs rename to src/InventoryAlert.Api/Extensions/CompressionExtension.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Extensions/HealthCheckExtensions.cs b/src/InventoryAlert.Api/Extensions/HealthCheckExtensions.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Extensions/HealthCheckExtensions.cs rename to src/InventoryAlert.Api/Extensions/HealthCheckExtensions.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Extensions/HttpContextExtensions.cs b/src/InventoryAlert.Api/Extensions/HttpContextExtensions.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Extensions/HttpContextExtensions.cs rename to src/InventoryAlert.Api/Extensions/HttpContextExtensions.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Extensions/MvcExtension.cs b/src/InventoryAlert.Api/Extensions/MvcExtension.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Extensions/MvcExtension.cs rename to src/InventoryAlert.Api/Extensions/MvcExtension.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Extensions/SwaggerExtension.cs b/src/InventoryAlert.Api/Extensions/SwaggerExtension.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Extensions/SwaggerExtension.cs rename to src/InventoryAlert.Api/Extensions/SwaggerExtension.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Filters/SwaggerFilters.cs b/src/InventoryAlert.Api/Filters/SwaggerFilters.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Filters/SwaggerFilters.cs rename to src/InventoryAlert.Api/Filters/SwaggerFilters.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Filters/ValidateModelFilter.cs b/src/InventoryAlert.Api/Filters/ValidateModelFilter.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Filters/ValidateModelFilter.cs rename to src/InventoryAlert.Api/Filters/ValidateModelFilter.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/InventoryAlert.Api.csproj b/src/InventoryAlert.Api/InventoryAlert.Api.csproj similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/InventoryAlert.Api.csproj rename to src/InventoryAlert.Api/InventoryAlert.Api.csproj diff --git a/InventoryManagementSystem/InventoryAlert.Api/InventoryAlert.Api.http b/src/InventoryAlert.Api/InventoryAlert.Api.http similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/InventoryAlert.Api.http rename to src/InventoryAlert.Api/InventoryAlert.Api.http diff --git a/InventoryManagementSystem/InventoryAlert.Api/Middleware/ApiLoggingMiddleware.cs b/src/InventoryAlert.Api/Middleware/ApiLoggingMiddleware.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Middleware/ApiLoggingMiddleware.cs rename to src/InventoryAlert.Api/Middleware/ApiLoggingMiddleware.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Middleware/CorrelationIdMiddleware.cs b/src/InventoryAlert.Api/Middleware/CorrelationIdMiddleware.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Middleware/CorrelationIdMiddleware.cs rename to src/InventoryAlert.Api/Middleware/CorrelationIdMiddleware.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs b/src/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs rename to src/InventoryAlert.Api/Middleware/GlobalExceptionMiddleware.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Models/Error.cs b/src/InventoryAlert.Api/Models/Error.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Models/Error.cs rename to src/InventoryAlert.Api/Models/Error.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Program.cs b/src/InventoryAlert.Api/Program.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Program.cs rename to src/InventoryAlert.Api/Program.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Properties/launchSettings.json b/src/InventoryAlert.Api/Properties/launchSettings.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Properties/launchSettings.json rename to src/InventoryAlert.Api/Properties/launchSettings.json diff --git a/InventoryManagementSystem/InventoryAlert.Api/ServiceExtensions/HttpClientServiceExtensions.cs b/src/InventoryAlert.Api/ServiceExtensions/HttpClientServiceExtensions.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/ServiceExtensions/HttpClientServiceExtensions.cs rename to src/InventoryAlert.Api/ServiceExtensions/HttpClientServiceExtensions.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/ServiceExtensions/InfrastructureServiceExtensions.cs b/src/InventoryAlert.Api/ServiceExtensions/InfrastructureServiceExtensions.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/ServiceExtensions/InfrastructureServiceExtensions.cs rename to src/InventoryAlert.Api/ServiceExtensions/InfrastructureServiceExtensions.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs b/src/InventoryAlert.Api/Services/AlertRuleService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Services/AlertRuleService.cs rename to src/InventoryAlert.Api/Services/AlertRuleService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Services/AuthService.cs b/src/InventoryAlert.Api/Services/AuthService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Services/AuthService.cs rename to src/InventoryAlert.Api/Services/AuthService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs b/src/InventoryAlert.Api/Services/EventService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Services/EventService.cs rename to src/InventoryAlert.Api/Services/EventService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Services/NotificationService.cs b/src/InventoryAlert.Api/Services/NotificationService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Services/NotificationService.cs rename to src/InventoryAlert.Api/Services/NotificationService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Services/PortfolioService.cs b/src/InventoryAlert.Api/Services/PortfolioService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Services/PortfolioService.cs rename to src/InventoryAlert.Api/Services/PortfolioService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs b/src/InventoryAlert.Api/Services/StockDataService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Services/StockDataService.cs rename to src/InventoryAlert.Api/Services/StockDataService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Services/WatchlistService.cs b/src/InventoryAlert.Api/Services/WatchlistService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Services/WatchlistService.cs rename to src/InventoryAlert.Api/Services/WatchlistService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Utilities/JsonConverters.cs b/src/InventoryAlert.Api/Utilities/JsonConverters.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Utilities/JsonConverters.cs rename to src/InventoryAlert.Api/Utilities/JsonConverters.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/Validations/ValidatorInterceptor.cs b/src/InventoryAlert.Api/Validations/ValidatorInterceptor.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/Validations/ValidatorInterceptor.cs rename to src/InventoryAlert.Api/Validations/ValidatorInterceptor.cs diff --git a/InventoryManagementSystem/InventoryAlert.Api/appsettings.Example.json b/src/InventoryAlert.Api/appsettings.Example.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/appsettings.Example.json rename to src/InventoryAlert.Api/appsettings.Example.json diff --git a/src/InventoryAlert.Api/appsettings.json b/src/InventoryAlert.Api/appsettings.json new file mode 100644 index 0000000..126b21c --- /dev/null +++ b/src/InventoryAlert.Api/appsettings.json @@ -0,0 +1,31 @@ +{ + "Aws": { + "EndpointUrl": "http://moto:5000", + "SqsDlqUrl": "http://moto:5000/123456789012/inventory-event-dlq", + "SqsQueueUrl": "http://moto:5000/123456789012/event-queue", + "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:inventory-events" + }, + "Database": { + "DefaultConnection": "Host=db;Database=inventory_alert_db;Username=postgres;Password=postgres" // docker + // "DefaultConnection": "Host=localhost;Port=5433;Database=inventory_alert_db;Username=postgres;Password=postgres" // local + }, + "Finnhub": { + "ApiBaseUrl": "https://finnhub.io/api/v1", + "ApiKey": "[YOUR_FINNHUB_KEY]", + "SyncIntervalMinutes": 30 + }, + "Jwt": { + "Audience": "InventoryAlert.Web", + "Issuer": "InventoryAlert.Api", + "Key": "InventoryAlert_Secure_Development_32_Char_Key" + }, + "Redis": { + "ConnectionString": "redis:6379" + }, + "Seq": { + "ServerUrl": "http://seq:5341" + }, + "Api": { + "EnableBodyLogging": true + } +} \ No newline at end of file diff --git a/InventoryManagementSystem/InventoryAlert.Api/wwwroot/.gitkeep b/src/InventoryAlert.Api/wwwroot/.gitkeep similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Api/wwwroot/.gitkeep rename to src/InventoryAlert.Api/wwwroot/.gitkeep diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Common/Constants/Constants.cs b/src/InventoryAlert.Domain/Common/Constants/Constants.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Common/Constants/Constants.cs rename to src/InventoryAlert.Domain/Common/Constants/Constants.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Common/Constants/NotificationConstants.cs b/src/InventoryAlert.Domain/Common/Constants/NotificationConstants.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Common/Constants/NotificationConstants.cs rename to src/InventoryAlert.Domain/Common/Constants/NotificationConstants.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Common/Exceptions/NotFoundException.cs b/src/InventoryAlert.Domain/Common/Exceptions/NotFoundException.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Common/Exceptions/NotFoundException.cs rename to src/InventoryAlert.Domain/Common/Exceptions/NotFoundException.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Common/Exceptions/UserFriendlyException.cs b/src/InventoryAlert.Domain/Common/Exceptions/UserFriendlyException.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Common/Exceptions/UserFriendlyException.cs rename to src/InventoryAlert.Domain/Common/Exceptions/UserFriendlyException.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Common/Exceptions/ValidationException.cs b/src/InventoryAlert.Domain/Common/Exceptions/ValidationException.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Common/Exceptions/ValidationException.cs rename to src/InventoryAlert.Domain/Common/Exceptions/ValidationException.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Configuration/AppSettings.cs b/src/InventoryAlert.Domain/Configuration/AppSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Configuration/AppSettings.cs rename to src/InventoryAlert.Domain/Configuration/AppSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Configuration/JsonOptions.cs b/src/InventoryAlert.Domain/Configuration/JsonOptions.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Configuration/JsonOptions.cs rename to src/InventoryAlert.Domain/Configuration/JsonOptions.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Configuration/RedisSettings.cs b/src/InventoryAlert.Domain/Configuration/RedisSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Configuration/RedisSettings.cs rename to src/InventoryAlert.Domain/Configuration/RedisSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Configuration/SharedAwsSettings.cs b/src/InventoryAlert.Domain/Configuration/SharedAwsSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Configuration/SharedAwsSettings.cs rename to src/InventoryAlert.Domain/Configuration/SharedAwsSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Configuration/SharedDatabaseSettings.cs b/src/InventoryAlert.Domain/Configuration/SharedDatabaseSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Configuration/SharedDatabaseSettings.cs rename to src/InventoryAlert.Domain/Configuration/SharedDatabaseSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Configuration/SharedFinnhubSettings.cs b/src/InventoryAlert.Domain/Configuration/SharedFinnhubSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Configuration/SharedFinnhubSettings.cs rename to src/InventoryAlert.Domain/Configuration/SharedFinnhubSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Configuration/SharedSeqSettings.cs b/src/InventoryAlert.Domain/Configuration/SharedSeqSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Configuration/SharedSeqSettings.cs rename to src/InventoryAlert.Domain/Configuration/SharedSeqSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Constants/AlertConstants.cs b/src/InventoryAlert.Domain/Constants/AlertConstants.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Constants/AlertConstants.cs rename to src/InventoryAlert.Domain/Constants/AlertConstants.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/AlertRuleDTOs.cs b/src/InventoryAlert.Domain/DTOs/AlertRuleDTOs.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/AlertRuleDTOs.cs rename to src/InventoryAlert.Domain/DTOs/AlertRuleDTOs.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/AuthDTOs.cs b/src/InventoryAlert.Domain/DTOs/AuthDTOs.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/AuthDTOs.cs rename to src/InventoryAlert.Domain/DTOs/AuthDTOs.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/CalendarDTOs.cs b/src/InventoryAlert.Domain/DTOs/CalendarDTOs.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/CalendarDTOs.cs rename to src/InventoryAlert.Domain/DTOs/CalendarDTOs.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/EventDTOs.cs b/src/InventoryAlert.Domain/DTOs/EventDTOs.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/EventDTOs.cs rename to src/InventoryAlert.Domain/DTOs/EventDTOs.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/MarketDTOs.cs b/src/InventoryAlert.Domain/DTOs/MarketDTOs.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/MarketDTOs.cs rename to src/InventoryAlert.Domain/DTOs/MarketDTOs.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/NotificationDTOs.cs b/src/InventoryAlert.Domain/DTOs/NotificationDTOs.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/NotificationDTOs.cs rename to src/InventoryAlert.Domain/DTOs/NotificationDTOs.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/PagedResult.cs b/src/InventoryAlert.Domain/DTOs/PagedResult.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/PagedResult.cs rename to src/InventoryAlert.Domain/DTOs/PagedResult.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/PaginationParams.cs b/src/InventoryAlert.Domain/DTOs/PaginationParams.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/PaginationParams.cs rename to src/InventoryAlert.Domain/DTOs/PaginationParams.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/PortfolioDTOs.cs b/src/InventoryAlert.Domain/DTOs/PortfolioDTOs.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/PortfolioDTOs.cs rename to src/InventoryAlert.Domain/DTOs/PortfolioDTOs.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/DTOs/StockDTOs.cs b/src/InventoryAlert.Domain/DTOs/StockDTOs.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/DTOs/StockDTOs.cs rename to src/InventoryAlert.Domain/DTOs/StockDTOs.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Dynamodb/CompanyNewsDynamoEntry.cs b/src/InventoryAlert.Domain/Entities/Dynamodb/CompanyNewsDynamoEntry.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Dynamodb/CompanyNewsDynamoEntry.cs rename to src/InventoryAlert.Domain/Entities/Dynamodb/CompanyNewsDynamoEntry.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Dynamodb/MarketNewsDynamoEntry.cs b/src/InventoryAlert.Domain/Entities/Dynamodb/MarketNewsDynamoEntry.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Dynamodb/MarketNewsDynamoEntry.cs rename to src/InventoryAlert.Domain/Entities/Dynamodb/MarketNewsDynamoEntry.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs b/src/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs rename to src/InventoryAlert.Domain/Entities/Postgres/AlertRule.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/EarningsSurprise.cs b/src/InventoryAlert.Domain/Entities/Postgres/EarningsSurprise.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/EarningsSurprise.cs rename to src/InventoryAlert.Domain/Entities/Postgres/EarningsSurprise.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/InsiderTransaction.cs b/src/InventoryAlert.Domain/Entities/Postgres/InsiderTransaction.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/InsiderTransaction.cs rename to src/InventoryAlert.Domain/Entities/Postgres/InsiderTransaction.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/Notification.cs b/src/InventoryAlert.Domain/Entities/Postgres/Notification.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/Notification.cs rename to src/InventoryAlert.Domain/Entities/Postgres/Notification.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/PriceHistory.cs b/src/InventoryAlert.Domain/Entities/Postgres/PriceHistory.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/PriceHistory.cs rename to src/InventoryAlert.Domain/Entities/Postgres/PriceHistory.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/RecommendationTrend.cs b/src/InventoryAlert.Domain/Entities/Postgres/RecommendationTrend.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/RecommendationTrend.cs rename to src/InventoryAlert.Domain/Entities/Postgres/RecommendationTrend.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/StockListing.cs b/src/InventoryAlert.Domain/Entities/Postgres/StockListing.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/StockListing.cs rename to src/InventoryAlert.Domain/Entities/Postgres/StockListing.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/StockMetric.cs b/src/InventoryAlert.Domain/Entities/Postgres/StockMetric.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/StockMetric.cs rename to src/InventoryAlert.Domain/Entities/Postgres/StockMetric.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/Trade.cs b/src/InventoryAlert.Domain/Entities/Postgres/Trade.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/Trade.cs rename to src/InventoryAlert.Domain/Entities/Postgres/Trade.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/User.cs b/src/InventoryAlert.Domain/Entities/Postgres/User.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/User.cs rename to src/InventoryAlert.Domain/Entities/Postgres/User.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/WatchlistItem.cs b/src/InventoryAlert.Domain/Entities/Postgres/WatchlistItem.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Entities/Postgres/WatchlistItem.cs rename to src/InventoryAlert.Domain/Entities/Postgres/WatchlistItem.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Events/EventEnvelope.cs b/src/InventoryAlert.Domain/Events/EventEnvelope.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Events/EventEnvelope.cs rename to src/InventoryAlert.Domain/Events/EventEnvelope.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Events/EventTypes.cs b/src/InventoryAlert.Domain/Events/EventTypes.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Events/EventTypes.cs rename to src/InventoryAlert.Domain/Events/EventTypes.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/CompanyNewsAlertPayload.cs b/src/InventoryAlert.Domain/Events/Payloads/CompanyNewsAlertPayload.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/CompanyNewsAlertPayload.cs rename to src/InventoryAlert.Domain/Events/Payloads/CompanyNewsAlertPayload.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/LowHoldingsAlertPayload.cs b/src/InventoryAlert.Domain/Events/Payloads/LowHoldingsAlertPayload.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/LowHoldingsAlertPayload.cs rename to src/InventoryAlert.Domain/Events/Payloads/LowHoldingsAlertPayload.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/MarketNewsPayload.cs b/src/InventoryAlert.Domain/Events/Payloads/MarketNewsPayload.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/MarketNewsPayload.cs rename to src/InventoryAlert.Domain/Events/Payloads/MarketNewsPayload.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/MarketPriceAlertPayload.cs b/src/InventoryAlert.Domain/Events/Payloads/MarketPriceAlertPayload.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/MarketPriceAlertPayload.cs rename to src/InventoryAlert.Domain/Events/Payloads/MarketPriceAlertPayload.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/SyncCompanyNewsPayload.cs b/src/InventoryAlert.Domain/Events/Payloads/SyncCompanyNewsPayload.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Events/Payloads/SyncCompanyNewsPayload.cs rename to src/InventoryAlert.Domain/Events/Payloads/SyncCompanyNewsPayload.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/External/Finnhub/FinnhubModels.cs b/src/InventoryAlert.Domain/External/Finnhub/FinnhubModels.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/External/Finnhub/FinnhubModels.cs rename to src/InventoryAlert.Domain/External/Finnhub/FinnhubModels.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAlertNotifier.cs b/src/InventoryAlert.Domain/Interfaces/IAlertNotifier.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAlertNotifier.cs rename to src/InventoryAlert.Domain/Interfaces/IAlertNotifier.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAlertRuleEvaluator.cs b/src/InventoryAlert.Domain/Interfaces/IAlertRuleEvaluator.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAlertRuleEvaluator.cs rename to src/InventoryAlert.Domain/Interfaces/IAlertRuleEvaluator.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAlertRuleRepository.cs b/src/InventoryAlert.Domain/Interfaces/IAlertRuleRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAlertRuleRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IAlertRuleRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAlertRuleService.cs b/src/InventoryAlert.Domain/Interfaces/IAlertRuleService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAlertRuleService.cs rename to src/InventoryAlert.Domain/Interfaces/IAlertRuleService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAuthService.cs b/src/InventoryAlert.Domain/Interfaces/IAuthService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IAuthService.cs rename to src/InventoryAlert.Domain/Interfaces/IAuthService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/ICompanyNewsDynamoRepository.cs b/src/InventoryAlert.Domain/Interfaces/ICompanyNewsDynamoRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/ICompanyNewsDynamoRepository.cs rename to src/InventoryAlert.Domain/Interfaces/ICompanyNewsDynamoRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/ICorrelationProvider.cs b/src/InventoryAlert.Domain/Interfaces/ICorrelationProvider.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/ICorrelationProvider.cs rename to src/InventoryAlert.Domain/Interfaces/ICorrelationProvider.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IDynamoDbGenericRepository.cs b/src/InventoryAlert.Domain/Interfaces/IDynamoDbGenericRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IDynamoDbGenericRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IDynamoDbGenericRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IEarningsSurpriseRepository.cs b/src/InventoryAlert.Domain/Interfaces/IEarningsSurpriseRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IEarningsSurpriseRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IEarningsSurpriseRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IEventPublisher.cs b/src/InventoryAlert.Domain/Interfaces/IEventPublisher.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IEventPublisher.cs rename to src/InventoryAlert.Domain/Interfaces/IEventPublisher.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IEventService.cs b/src/InventoryAlert.Domain/Interfaces/IEventService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IEventService.cs rename to src/InventoryAlert.Domain/Interfaces/IEventService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IFinnhubClient.cs b/src/InventoryAlert.Domain/Interfaces/IFinnhubClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IFinnhubClient.cs rename to src/InventoryAlert.Domain/Interfaces/IFinnhubClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IGenericRepository.cs b/src/InventoryAlert.Domain/Interfaces/IGenericRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IGenericRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IGenericRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IInsiderTransactionRepository.cs b/src/InventoryAlert.Domain/Interfaces/IInsiderTransactionRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IInsiderTransactionRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IInsiderTransactionRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IMarketNewsDynamoRepository.cs b/src/InventoryAlert.Domain/Interfaces/IMarketNewsDynamoRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IMarketNewsDynamoRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IMarketNewsDynamoRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/INotificationHub.cs b/src/InventoryAlert.Domain/Interfaces/INotificationHub.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/INotificationHub.cs rename to src/InventoryAlert.Domain/Interfaces/INotificationHub.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/INotificationRepository.cs b/src/InventoryAlert.Domain/Interfaces/INotificationRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/INotificationRepository.cs rename to src/InventoryAlert.Domain/Interfaces/INotificationRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/INotificationService.cs b/src/InventoryAlert.Domain/Interfaces/INotificationService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/INotificationService.cs rename to src/InventoryAlert.Domain/Interfaces/INotificationService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IPortfolioService.cs b/src/InventoryAlert.Domain/Interfaces/IPortfolioService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IPortfolioService.cs rename to src/InventoryAlert.Domain/Interfaces/IPortfolioService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IPriceHistoryRepository.cs b/src/InventoryAlert.Domain/Interfaces/IPriceHistoryRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IPriceHistoryRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IPriceHistoryRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IQueueService.cs b/src/InventoryAlert.Domain/Interfaces/IQueueService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IQueueService.cs rename to src/InventoryAlert.Domain/Interfaces/IQueueService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IRecommendationTrendRepository.cs b/src/InventoryAlert.Domain/Interfaces/IRecommendationTrendRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IRecommendationTrendRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IRecommendationTrendRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IRedisHelper.cs b/src/InventoryAlert.Domain/Interfaces/IRedisHelper.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IRedisHelper.cs rename to src/InventoryAlert.Domain/Interfaces/IRedisHelper.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IStockDataService.cs b/src/InventoryAlert.Domain/Interfaces/IStockDataService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IStockDataService.cs rename to src/InventoryAlert.Domain/Interfaces/IStockDataService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IStockListingRepository.cs b/src/InventoryAlert.Domain/Interfaces/IStockListingRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IStockListingRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IStockListingRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IStockMetricRepository.cs b/src/InventoryAlert.Domain/Interfaces/IStockMetricRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IStockMetricRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IStockMetricRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/ITradeRepository.cs b/src/InventoryAlert.Domain/Interfaces/ITradeRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/ITradeRepository.cs rename to src/InventoryAlert.Domain/Interfaces/ITradeRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IUnitOfWork.cs b/src/InventoryAlert.Domain/Interfaces/IUnitOfWork.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IUnitOfWork.cs rename to src/InventoryAlert.Domain/Interfaces/IUnitOfWork.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IUserRepository.cs b/src/InventoryAlert.Domain/Interfaces/IUserRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IUserRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IUserRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IWatchlistItemRepository.cs b/src/InventoryAlert.Domain/Interfaces/IWatchlistItemRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IWatchlistItemRepository.cs rename to src/InventoryAlert.Domain/Interfaces/IWatchlistItemRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IWatchlistService.cs b/src/InventoryAlert.Domain/Interfaces/IWatchlistService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Interfaces/IWatchlistService.cs rename to src/InventoryAlert.Domain/Interfaces/IWatchlistService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/InventoryAlert.Domain.csproj b/src/InventoryAlert.Domain/InventoryAlert.Domain.csproj similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/InventoryAlert.Domain.csproj rename to src/InventoryAlert.Domain/InventoryAlert.Domain.csproj diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Validators/AlertRuleRequestValidator.cs b/src/InventoryAlert.Domain/Validators/AlertRuleRequestValidator.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Validators/AlertRuleRequestValidator.cs rename to src/InventoryAlert.Domain/Validators/AlertRuleRequestValidator.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Validators/AuthValidators.cs b/src/InventoryAlert.Domain/Validators/AuthValidators.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Validators/AuthValidators.cs rename to src/InventoryAlert.Domain/Validators/AuthValidators.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Validators/CreatePositionRequestValidator.cs b/src/InventoryAlert.Domain/Validators/CreatePositionRequestValidator.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Validators/CreatePositionRequestValidator.cs rename to src/InventoryAlert.Domain/Validators/CreatePositionRequestValidator.cs diff --git a/InventoryManagementSystem/InventoryAlert.Domain/Validators/TradeRequestValidator.cs b/src/InventoryAlert.Domain/Validators/TradeRequestValidator.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Domain/Validators/TradeRequestValidator.cs rename to src/InventoryAlert.Domain/Validators/TradeRequestValidator.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Caching/RedisHelper.cs b/src/InventoryAlert.Infrastructure/Caching/RedisHelper.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Caching/RedisHelper.cs rename to src/InventoryAlert.Infrastructure/Caching/RedisHelper.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/DependencyInjection.cs b/src/InventoryAlert.Infrastructure/DependencyInjection.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/DependencyInjection.cs rename to src/InventoryAlert.Infrastructure/DependencyInjection.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/External/Finnhub/FinnhubClient.cs b/src/InventoryAlert.Infrastructure/External/Finnhub/FinnhubClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/External/Finnhub/FinnhubClient.cs rename to src/InventoryAlert.Infrastructure/External/Finnhub/FinnhubClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Hubs/NotificationHub.cs b/src/InventoryAlert.Infrastructure/Hubs/NotificationHub.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Hubs/NotificationHub.cs rename to src/InventoryAlert.Infrastructure/Hubs/NotificationHub.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj b/src/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj rename to src/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs b/src/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs rename to src/InventoryAlert.Infrastructure/Messaging/SnsEventPublisher.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SqsQueueService.cs b/src/InventoryAlert.Infrastructure/Messaging/SqsQueueService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Messaging/SqsQueueService.cs rename to src/InventoryAlert.Infrastructure/Messaging/SqsQueueService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.Designer.cs b/src/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.Designer.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.Designer.cs rename to src/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.Designer.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.cs b/src/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.cs rename to src/InventoryAlert.Infrastructure/Migrations/20260414042036_RefactorToFinanceV2.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.Designer.cs b/src/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.Designer.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.Designer.cs rename to src/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.Designer.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.cs b/src/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.cs rename to src/InventoryAlert.Infrastructure/Migrations/20260426071939_AddNotificationDetails.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/InventoryAlert.Infrastructure/Migrations/AppDbContextModelSnapshot.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Migrations/AppDbContextModelSnapshot.cs rename to src/InventoryAlert.Infrastructure/Migrations/AppDbContextModelSnapshot.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/CompanyNewsDynamoRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/CompanyNewsDynamoRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/CompanyNewsDynamoRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/CompanyNewsDynamoRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDBContextBuilder.cs b/src/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDBContextBuilder.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDBContextBuilder.cs rename to src/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDBContextBuilder.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDbGenericRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDbGenericRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDbGenericRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/DynamoDbGenericRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/MarketNewsDynamoRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/MarketNewsDynamoRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/MarketNewsDynamoRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/DynamoDb/Repositories/MarketNewsDynamoRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContext.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContext.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContext.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContext.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContextFactory.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContextFactory.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContextFactory.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/AppDbContextFactory.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/AlertRuleConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/AlertRuleConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/AlertRuleConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/AlertRuleConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/EarningsSurpriseConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/EarningsSurpriseConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/EarningsSurpriseConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/EarningsSurpriseConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/InsiderTransactionConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/InsiderTransactionConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/InsiderTransactionConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/InsiderTransactionConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/NotificationConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/NotificationConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/NotificationConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/NotificationConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/PriceHistoryConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/PriceHistoryConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/PriceHistoryConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/PriceHistoryConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/RecommendationTrendConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/RecommendationTrendConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/RecommendationTrendConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/RecommendationTrendConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockListingConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockListingConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockListingConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockListingConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockMetricConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockMetricConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockMetricConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/StockMetricConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/TradeConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/TradeConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/TradeConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/TradeConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/UserConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/UserConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/UserConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/UserConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/WatchlistItemConfiguration.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/WatchlistItemConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/WatchlistItemConfiguration.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Configurations/WatchlistItemConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/DatabaseSeeder.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/DatabaseSeeder.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/DatabaseSeeder.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/DatabaseSeeder.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/AlertRuleRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/AlertRuleRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/AlertRuleRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/AlertRuleRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/EarningsSurpriseRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/EarningsSurpriseRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/EarningsSurpriseRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/EarningsSurpriseRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/GenericRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/GenericRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/GenericRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/GenericRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/InsiderTransactionRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/InsiderTransactionRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/InsiderTransactionRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/InsiderTransactionRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/NotificationRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/NotificationRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/NotificationRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/NotificationRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/PriceHistoryRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/PriceHistoryRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/PriceHistoryRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/PriceHistoryRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/RecommendationTrendRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/RecommendationTrendRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/RecommendationTrendRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/RecommendationTrendRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockListingRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockListingRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockListingRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockListingRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockMetricRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockMetricRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockMetricRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/StockMetricRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/TradeRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/TradeRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/TradeRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/TradeRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UnitOfWork.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UnitOfWork.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UnitOfWork.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UnitOfWork.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UserRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UserRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UserRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/UserRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/WatchlistItemRepository.cs b/src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/WatchlistItemRepository.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/WatchlistItemRepository.cs rename to src/InventoryAlert.Infrastructure/Persistence/Postgres/Repositories/WatchlistItemRepository.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/AlertRuleEvaluator.cs b/src/InventoryAlert.Infrastructure/Utilities/AlertRuleEvaluator.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/AlertRuleEvaluator.cs rename to src/InventoryAlert.Infrastructure/Utilities/AlertRuleEvaluator.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationIdEnricher.cs b/src/InventoryAlert.Infrastructure/Utilities/CorrelationIdEnricher.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationIdEnricher.cs rename to src/InventoryAlert.Infrastructure/Utilities/CorrelationIdEnricher.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs b/src/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs rename to src/InventoryAlert.Infrastructure/Utilities/CorrelationProvider.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/LoggingConfiguration.cs b/src/InventoryAlert.Infrastructure/Utilities/LoggingConfiguration.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/LoggingConfiguration.cs rename to src/InventoryAlert.Infrastructure/Utilities/LoggingConfiguration.cs diff --git a/InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/NotificationAlertNotifier.cs b/src/InventoryAlert.Infrastructure/Utilities/NotificationAlertNotifier.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Infrastructure/Utilities/NotificationAlertNotifier.cs rename to src/InventoryAlert.Infrastructure/Utilities/NotificationAlertNotifier.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Configuration/WorkerSettings.cs b/src/InventoryAlert.Worker/Configuration/WorkerSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Configuration/WorkerSettings.cs rename to src/InventoryAlert.Worker/Configuration/WorkerSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/DevDashboardAuthorizationFilter.cs b/src/InventoryAlert.Worker/DevDashboardAuthorizationFilter.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/DevDashboardAuthorizationFilter.cs rename to src/InventoryAlert.Worker/DevDashboardAuthorizationFilter.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Dockerfile b/src/InventoryAlert.Worker/Dockerfile similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Dockerfile rename to src/InventoryAlert.Worker/Dockerfile diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Extensions/HealthCheckExtensions.cs b/src/InventoryAlert.Worker/Extensions/HealthCheckExtensions.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Extensions/HealthCheckExtensions.cs rename to src/InventoryAlert.Worker/Extensions/HealthCheckExtensions.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs b/src/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs rename to src/InventoryAlert.Worker/Filters/HangfireJobLoggingFilter.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskProcessor.cs b/src/InventoryAlert.Worker/Hosting/BackgroundTaskProcessor.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskProcessor.cs rename to src/InventoryAlert.Worker/Hosting/BackgroundTaskProcessor.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs b/src/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs rename to src/InventoryAlert.Worker/Hosting/BackgroundTaskQueue.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Hosting/JobSchedulerService.cs b/src/InventoryAlert.Worker/Hosting/JobSchedulerService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Hosting/JobSchedulerService.cs rename to src/InventoryAlert.Worker/Hosting/JobSchedulerService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Hosting/SqsListenerService.cs b/src/InventoryAlert.Worker/Hosting/SqsListenerService.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Hosting/SqsListenerService.cs rename to src/InventoryAlert.Worker/Hosting/SqsListenerService.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/DefaultHandler.cs b/src/InventoryAlert.Worker/IntegrationEvents/Handlers/DefaultHandler.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/DefaultHandler.cs rename to src/InventoryAlert.Worker/IntegrationEvents/Handlers/DefaultHandler.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/LowHoldingsHandler.cs b/src/InventoryAlert.Worker/IntegrationEvents/Handlers/LowHoldingsHandler.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/LowHoldingsHandler.cs rename to src/InventoryAlert.Worker/IntegrationEvents/Handlers/LowHoldingsHandler.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/MarketPriceAlertHandler.cs b/src/InventoryAlert.Worker/IntegrationEvents/Handlers/MarketPriceAlertHandler.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Handlers/MarketPriceAlertHandler.cs rename to src/InventoryAlert.Worker/IntegrationEvents/Handlers/MarketPriceAlertHandler.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs b/src/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs rename to src/InventoryAlert.Worker/IntegrationEvents/Routing/IntegrationMessageRouter.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Interfaces/IBackgroundTaskQueue.cs b/src/InventoryAlert.Worker/Interfaces/IBackgroundTaskQueue.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Interfaces/IBackgroundTaskQueue.cs rename to src/InventoryAlert.Worker/Interfaces/IBackgroundTaskQueue.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Interfaces/IHandlerInterfaces.cs b/src/InventoryAlert.Worker/Interfaces/IHandlerInterfaces.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Interfaces/IHandlerInterfaces.cs rename to src/InventoryAlert.Worker/Interfaces/IHandlerInterfaces.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Interfaces/IIntegrationMessageRouter.cs b/src/InventoryAlert.Worker/Interfaces/IIntegrationMessageRouter.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Interfaces/IIntegrationMessageRouter.cs rename to src/InventoryAlert.Worker/Interfaces/IIntegrationMessageRouter.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Interfaces/IProcessQueueJob.cs b/src/InventoryAlert.Worker/Interfaces/IProcessQueueJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Interfaces/IProcessQueueJob.cs rename to src/InventoryAlert.Worker/Interfaces/IProcessQueueJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Interfaces/ISqsHelper.cs b/src/InventoryAlert.Worker/Interfaces/ISqsHelper.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Interfaces/ISqsHelper.cs rename to src/InventoryAlert.Worker/Interfaces/ISqsHelper.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/InventoryAlert.Worker.csproj b/src/InventoryAlert.Worker/InventoryAlert.Worker.csproj similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/InventoryAlert.Worker.csproj rename to src/InventoryAlert.Worker/InventoryAlert.Worker.csproj diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Models/JobResult.cs b/src/InventoryAlert.Worker/Models/JobResult.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Models/JobResult.cs rename to src/InventoryAlert.Worker/Models/JobResult.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Program.cs b/src/InventoryAlert.Worker/Program.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Program.cs rename to src/InventoryAlert.Worker/Program.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Properties/launchSettings.json b/src/InventoryAlert.Worker/Properties/launchSettings.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Properties/launchSettings.json rename to src/InventoryAlert.Worker/Properties/launchSettings.json diff --git a/InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/CleanupPriceHistoryJob.cs b/src/InventoryAlert.Worker/ScheduledJobs/CleanupPriceHistoryJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/CleanupPriceHistoryJob.cs rename to src/InventoryAlert.Worker/ScheduledJobs/CleanupPriceHistoryJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/NewsSyncJob.cs b/src/InventoryAlert.Worker/ScheduledJobs/NewsSyncJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/NewsSyncJob.cs rename to src/InventoryAlert.Worker/ScheduledJobs/NewsSyncJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs b/src/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs rename to src/InventoryAlert.Worker/ScheduledJobs/ProcessQueueJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncEarningsJob.cs b/src/InventoryAlert.Worker/ScheduledJobs/SyncEarningsJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncEarningsJob.cs rename to src/InventoryAlert.Worker/ScheduledJobs/SyncEarningsJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncInsidersJob.cs b/src/InventoryAlert.Worker/ScheduledJobs/SyncInsidersJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncInsidersJob.cs rename to src/InventoryAlert.Worker/ScheduledJobs/SyncInsidersJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncMetricsJob.cs b/src/InventoryAlert.Worker/ScheduledJobs/SyncMetricsJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncMetricsJob.cs rename to src/InventoryAlert.Worker/ScheduledJobs/SyncMetricsJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs b/src/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs rename to src/InventoryAlert.Worker/ScheduledJobs/SyncPricesJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncRecommendationsJob.cs b/src/InventoryAlert.Worker/ScheduledJobs/SyncRecommendationsJob.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/ScheduledJobs/SyncRecommendationsJob.cs rename to src/InventoryAlert.Worker/ScheduledJobs/SyncRecommendationsJob.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/Utilities/SqsHelper.cs b/src/InventoryAlert.Worker/Utilities/SqsHelper.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/Utilities/SqsHelper.cs rename to src/InventoryAlert.Worker/Utilities/SqsHelper.cs diff --git a/InventoryManagementSystem/InventoryAlert.Worker/appsettings.Example.json b/src/InventoryAlert.Worker/appsettings.Example.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Worker/appsettings.Example.json rename to src/InventoryAlert.Worker/appsettings.Example.json diff --git a/src/InventoryAlert.Worker/appsettings.json b/src/InventoryAlert.Worker/appsettings.json new file mode 100644 index 0000000..7b982b7 --- /dev/null +++ b/src/InventoryAlert.Worker/appsettings.json @@ -0,0 +1,37 @@ +{ + "Aws": { + "EndpointUrl": "http://moto:5000", + "SqsDlqUrl": "http://moto:5000/123456789012/inventory-event-dlq", + "SqsQueueUrl": "http://moto:5000/123456789012/event-queue", + "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:inventory-events" + }, + "Database": { + "DefaultConnection": "Host=db;Database=inventory_alert_db;Username=postgres;Password=postgres" // docker + // "DefaultConnection": "Host=localhost;Port=5433;Database=inventory_alert_db;Username=postgres;Password=postgres" // local + }, + "Finnhub": { + "ApiBaseUrl": "https://finnhub.io/api/v1", + "ApiKey": "[YOUR_FINNHUB_KEY]", + "SyncIntervalMinutes": 30 + }, + "IsPollMessage": true, + "Redis": { + "ConnectionString": "redis:6379" + }, + "Schedules": { + "CleanupPrices": "10 2 * * *", + "MarketNews": "5 */2 * * *", + "NewsCheck": "0 */6 * * *", + "SyncEarnings": "35 7 * * *", + "SyncInsiders": "50 8 * * *", + "SyncMetrics": "20 6 * * *", + "SyncPrices": "*/15 * * * *", + "SyncRecommendations": "55 1 * * 1" + }, + "Seq": { + "ServerUrl": "http://seq:5341" // docker + }, + "Worker": { + "EnablePayloadLogging": true + } +} \ No newline at end of file diff --git a/InventoryManagementSystem/InventoryManagementSystem.sln b/src/InventoryManagementSystem.sln similarity index 94% rename from InventoryManagementSystem/InventoryManagementSystem.sln rename to src/InventoryManagementSystem.sln index 24dbeb4..cffa557 100644 --- a/InventoryManagementSystem/InventoryManagementSystem.sln +++ b/src/InventoryManagementSystem.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -9,13 +9,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.Domain", "In EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.Worker", "InventoryAlert.Worker\InventoryAlert.Worker.csproj", "{BE715D9F-CC6A-4931-893E-C0E413ADD3BD}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.Sample", "InventoryAlert.Sample\InventoryAlert.Sample.csproj", "{9A5F9FC6-8F3C-42FF-A04E-F5C9527646DB}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.Sample", "test\InventoryAlert.Sample\InventoryAlert.Sample.csproj", "{9A5F9FC6-8F3C-42FF-A04E-F5C9527646DB}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.UnitTests", "InventoryAlert.UnitTests\InventoryAlert.UnitTests.csproj", "{FFE36D59-CD3A-4C4B-BFFA-E7C7A6955C06}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.UnitTests", "test\InventoryAlert.UnitTests\InventoryAlert.UnitTests.csproj", "{FFE36D59-CD3A-4C4B-BFFA-E7C7A6955C06}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.IntegrationTests", "InventoryAlert.IntegrationTests\InventoryAlert.IntegrationTests.csproj", "{8AEACF55-3718-4F82-B731-305FD8ECAA1F}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.IntegrationTests", "test\InventoryAlert.IntegrationTests\InventoryAlert.IntegrationTests.csproj", "{8AEACF55-3718-4F82-B731-305FD8ECAA1F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.ArchitectureTests", "InventoryAlert.ArchitectureTests\InventoryAlert.ArchitectureTests.csproj", "{51B44AE9-AC73-4B5D-8B25-672C921A704D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.ArchitectureTests", "test\InventoryAlert.ArchitectureTests\InventoryAlert.ArchitectureTests.csproj", "{51B44AE9-AC73-4B5D-8B25-672C921A704D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D0C8D6AE-CF6B-4197-85EE-56E52AA62688}" ProjectSection(SolutionItems) = preProject @@ -29,7 +29,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.Infrastructure", "InventoryAlert.Infrastructure\InventoryAlert.Infrastructure.csproj", "{86727EA4-9945-4FD4-8A93-C31883C5EA5F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.E2ETests", "InventoryAlert.E2ETests\InventoryAlert.E2ETests.csproj", "{5E783740-3A81-4C1A-AB33-617CDED7E7AD}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.E2ETests", "test\InventoryAlert.E2ETests\InventoryAlert.E2ETests.csproj", "{5E783740-3A81-4C1A-AB33-617CDED7E7AD}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/InventoryManagementSystem/SolutionFolder/moto-init/init-all.sh b/src/SolutionFolder/moto-init/init-all.sh similarity index 100% rename from InventoryManagementSystem/SolutionFolder/moto-init/init-all.sh rename to src/SolutionFolder/moto-init/init-all.sh diff --git a/InventoryManagementSystem/docker-compose.yml b/src/docker-compose.yml similarity index 98% rename from InventoryManagementSystem/docker-compose.yml rename to src/docker-compose.yml index 56ac206..773b8e6 100644 --- a/InventoryManagementSystem/docker-compose.yml +++ b/src/docker-compose.yml @@ -157,7 +157,7 @@ services: # ── UI: Next.js Frontend ────────────────────────────── ui: build: - context: ../InventoryAlert.UI + context: ./ui/InventoryAlert.UI args: - NEXT_PUBLIC_API_URL=http://localhost:8080 container_name: inventory-ui @@ -180,7 +180,7 @@ services: ports: - "9091:8080" volumes: - - ./InventoryAlert.IntegrationTests/Wiremock:/home/wiremock + - ./test/InventoryAlert.IntegrationTests/Wiremock:/home/wiremock command: - "--global-response-templating" - "--verbose" diff --git a/InventoryManagementSystem/InventoryAlert.ArchitectureTests/ArchitectureTests.cs b/src/test/InventoryAlert.ArchitectureTests/ArchitectureTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.ArchitectureTests/ArchitectureTests.cs rename to src/test/InventoryAlert.ArchitectureTests/ArchitectureTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj b/src/test/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj similarity index 69% rename from InventoryManagementSystem/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj rename to src/test/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj index 70cde0d..9ee8973 100644 --- a/InventoryManagementSystem/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj +++ b/src/test/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj @@ -20,9 +20,9 @@ - - - + + + diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/Abstractions/BaseE2ETest.cs b/src/test/InventoryAlert.E2ETests/Abstractions/BaseE2ETest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/Abstractions/BaseE2ETest.cs rename to src/test/InventoryAlert.E2ETests/Abstractions/BaseE2ETest.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/AlertRulesE2ETests.cs b/src/test/InventoryAlert.E2ETests/AlertRulesE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/AlertRulesE2ETests.cs rename to src/test/InventoryAlert.E2ETests/AlertRulesE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/AuthE2ETests.cs b/src/test/InventoryAlert.E2ETests/AuthE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/AuthE2ETests.cs rename to src/test/InventoryAlert.E2ETests/AuthE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/EventsE2ETests.cs b/src/test/InventoryAlert.E2ETests/EventsE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/EventsE2ETests.cs rename to src/test/InventoryAlert.E2ETests/EventsE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj b/src/test/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj similarity index 90% rename from InventoryManagementSystem/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj rename to src/test/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj index ab64669..e1a1317 100644 --- a/InventoryManagementSystem/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj +++ b/src/test/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj @@ -20,7 +20,7 @@ - + diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/MarketE2ETests.cs b/src/test/InventoryAlert.E2ETests/MarketE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/MarketE2ETests.cs rename to src/test/InventoryAlert.E2ETests/MarketE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/NotificationE2ETests.cs b/src/test/InventoryAlert.E2ETests/NotificationE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/NotificationE2ETests.cs rename to src/test/InventoryAlert.E2ETests/NotificationE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/PortfolioE2ETests.cs b/src/test/InventoryAlert.E2ETests/PortfolioE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/PortfolioE2ETests.cs rename to src/test/InventoryAlert.E2ETests/PortfolioE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/SignalRNotificationE2ETests.cs b/src/test/InventoryAlert.E2ETests/SignalRNotificationE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/SignalRNotificationE2ETests.cs rename to src/test/InventoryAlert.E2ETests/SignalRNotificationE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/SqsRetryE2ETests.cs b/src/test/InventoryAlert.E2ETests/SqsRetryE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/SqsRetryE2ETests.cs rename to src/test/InventoryAlert.E2ETests/SqsRetryE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/StocksE2ETests.cs b/src/test/InventoryAlert.E2ETests/StocksE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/StocksE2ETests.cs rename to src/test/InventoryAlert.E2ETests/StocksE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/WatchlistE2ETests.cs b/src/test/InventoryAlert.E2ETests/WatchlistE2ETests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/WatchlistE2ETests.cs rename to src/test/InventoryAlert.E2ETests/WatchlistE2ETests.cs diff --git a/InventoryManagementSystem/InventoryAlert.E2ETests/test-e2e.ps1 b/src/test/InventoryAlert.E2ETests/test-e2e.ps1 similarity index 100% rename from InventoryManagementSystem/InventoryAlert.E2ETests/test-e2e.ps1 rename to src/test/InventoryAlert.E2ETests/test-e2e.ps1 diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/BaseClient.cs b/src/test/InventoryAlert.IntegrationTests/Abstractions/BaseClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/BaseClient.cs rename to src/test/InventoryAlert.IntegrationTests/Abstractions/BaseClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/BaseIntegrationTest.cs b/src/test/InventoryAlert.IntegrationTests/Abstractions/BaseIntegrationTest.cs similarity index 79% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/BaseIntegrationTest.cs rename to src/test/InventoryAlert.IntegrationTests/Abstractions/BaseIntegrationTest.cs index c5e037a..63123a2 100644 --- a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/BaseIntegrationTest.cs +++ b/src/test/InventoryAlert.IntegrationTests/Abstractions/BaseIntegrationTest.cs @@ -22,10 +22,15 @@ protected BaseIntegrationTest(TestFixture fixture, ITestOutputHelper output) Fixture = fixture; Output = output; - var baseUrl = Fixture.Configuration["ApiSettings:BaseUrl"] ?? "http://localhost:8080/api/v1"; + // Use the in-process HttpClient from the factory + var httpClient = Fixture.CreateTestClient(); - var options = new RestClientOptions(baseUrl); - Client = new RestClient(options, configureSerialization: s => s.UseSystemTextJson(new JsonSerializerOptions + var options = new RestClientOptions + { + BaseUrl = new Uri(httpClient.BaseAddress!, "api/v1/") + }; + + Client = new RestClient(httpClient, options, configureSerialization: s => s.UseSystemTextJson(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/HandlerTestBase.cs b/src/test/InventoryAlert.IntegrationTests/Abstractions/HandlerTestBase.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/HandlerTestBase.cs rename to src/test/InventoryAlert.IntegrationTests/Abstractions/HandlerTestBase.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/Tier2TestBase.cs b/src/test/InventoryAlert.IntegrationTests/Abstractions/Tier2TestBase.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Abstractions/Tier2TestBase.cs rename to src/test/InventoryAlert.IntegrationTests/Abstractions/Tier2TestBase.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/AlertRuleClient.cs b/src/test/InventoryAlert.IntegrationTests/Clients/AlertRuleClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/AlertRuleClient.cs rename to src/test/InventoryAlert.IntegrationTests/Clients/AlertRuleClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/AuthClient.cs b/src/test/InventoryAlert.IntegrationTests/Clients/AuthClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/AuthClient.cs rename to src/test/InventoryAlert.IntegrationTests/Clients/AuthClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/MarketClient.cs b/src/test/InventoryAlert.IntegrationTests/Clients/MarketClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/MarketClient.cs rename to src/test/InventoryAlert.IntegrationTests/Clients/MarketClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/MockFinnhubClient.cs b/src/test/InventoryAlert.IntegrationTests/Clients/MockFinnhubClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/MockFinnhubClient.cs rename to src/test/InventoryAlert.IntegrationTests/Clients/MockFinnhubClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/StockClient.cs b/src/test/InventoryAlert.IntegrationTests/Clients/StockClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/StockClient.cs rename to src/test/InventoryAlert.IntegrationTests/Clients/StockClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/WatchlistClient.cs b/src/test/InventoryAlert.IntegrationTests/Clients/WatchlistClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/WatchlistClient.cs rename to src/test/InventoryAlert.IntegrationTests/Clients/WatchlistClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/WiremockAdminClient.cs b/src/test/InventoryAlert.IntegrationTests/Clients/WiremockAdminClient.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Clients/WiremockAdminClient.cs rename to src/test/InventoryAlert.IntegrationTests/Clients/WiremockAdminClient.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Config/ApiSettings.cs b/src/test/InventoryAlert.IntegrationTests/Config/ApiSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Config/ApiSettings.cs rename to src/test/InventoryAlert.IntegrationTests/Config/ApiSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Config/AppSettings.cs b/src/test/InventoryAlert.IntegrationTests/Config/AppSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Config/AppSettings.cs rename to src/test/InventoryAlert.IntegrationTests/Config/AppSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Config/TestUser.cs b/src/test/InventoryAlert.IntegrationTests/Config/TestUser.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Config/TestUser.cs rename to src/test/InventoryAlert.IntegrationTests/Config/TestUser.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Config/WiremockSettings.cs b/src/test/InventoryAlert.IntegrationTests/Config/WiremockSettings.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Config/WiremockSettings.cs rename to src/test/InventoryAlert.IntegrationTests/Config/WiremockSettings.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Fixtures/InjectionFixture.cs b/src/test/InventoryAlert.IntegrationTests/Fixtures/InjectionFixture.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Fixtures/InjectionFixture.cs rename to src/test/InventoryAlert.IntegrationTests/Fixtures/InjectionFixture.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Helpers/WaitHelper.cs b/src/test/InventoryAlert.IntegrationTests/Helpers/WaitHelper.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Helpers/WaitHelper.cs rename to src/test/InventoryAlert.IntegrationTests/Helpers/WaitHelper.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/INTEGRATION_TEST_PLAN.md b/src/test/InventoryAlert.IntegrationTests/INTEGRATION_TEST_PLAN.md similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/INTEGRATION_TEST_PLAN.md rename to src/test/InventoryAlert.IntegrationTests/INTEGRATION_TEST_PLAN.md diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/ActionTestConfig.cs b/src/test/InventoryAlert.IntegrationTests/Infrastructure/ActionTestConfig.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/ActionTestConfig.cs rename to src/test/InventoryAlert.IntegrationTests/Infrastructure/ActionTestConfig.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/IntegrationTestCollection.cs b/src/test/InventoryAlert.IntegrationTests/Infrastructure/IntegrationTestCollection.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/IntegrationTestCollection.cs rename to src/test/InventoryAlert.IntegrationTests/Infrastructure/IntegrationTestCollection.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/SeqLogReader.cs b/src/test/InventoryAlert.IntegrationTests/Infrastructure/SeqLogReader.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/SeqLogReader.cs rename to src/test/InventoryAlert.IntegrationTests/Infrastructure/SeqLogReader.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/SetupDI.cs b/src/test/InventoryAlert.IntegrationTests/Infrastructure/SetupDI.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/SetupDI.cs rename to src/test/InventoryAlert.IntegrationTests/Infrastructure/SetupDI.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/TestFixture.cs b/src/test/InventoryAlert.IntegrationTests/Infrastructure/TestFixture.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/TestFixture.cs rename to src/test/InventoryAlert.IntegrationTests/Infrastructure/TestFixture.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/TestLoggerProvider.cs b/src/test/InventoryAlert.IntegrationTests/Infrastructure/TestLoggerProvider.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/TestLoggerProvider.cs rename to src/test/InventoryAlert.IntegrationTests/Infrastructure/TestLoggerProvider.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/WaitHelper.cs b/src/test/InventoryAlert.IntegrationTests/Infrastructure/WaitHelper.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Infrastructure/WaitHelper.cs rename to src/test/InventoryAlert.IntegrationTests/Infrastructure/WaitHelper.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj b/src/test/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj similarity index 69% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj rename to src/test/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj index 9cd8e4a..47a2a68 100644 --- a/InventoryManagementSystem/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj +++ b/src/test/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj @@ -28,10 +28,10 @@ - + PreserveNewest - + PreserveNewest @@ -44,10 +44,10 @@ - - - - + + + + diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Models/Request/WiremockCountGetQuoteRequest.cs b/src/test/InventoryAlert.IntegrationTests/Models/Request/WiremockCountGetQuoteRequest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Models/Request/WiremockCountGetQuoteRequest.cs rename to src/test/InventoryAlert.IntegrationTests/Models/Request/WiremockCountGetQuoteRequest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Models/Response/WiremockCountResponse.cs b/src/test/InventoryAlert.IntegrationTests/Models/Response/WiremockCountResponse.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Models/Response/WiremockCountResponse.cs rename to src/test/InventoryAlert.IntegrationTests/Models/Response/WiremockCountResponse.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/TestUtils/Assertions/AlertRuleAssertion.cs b/src/test/InventoryAlert.IntegrationTests/TestUtils/Assertions/AlertRuleAssertion.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/TestUtils/Assertions/AlertRuleAssertion.cs rename to src/test/InventoryAlert.IntegrationTests/TestUtils/Assertions/AlertRuleAssertion.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/TestUtils/Assertions/WatchlistItemAssertion.cs b/src/test/InventoryAlert.IntegrationTests/TestUtils/Assertions/WatchlistItemAssertion.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/TestUtils/Assertions/WatchlistItemAssertion.cs rename to src/test/InventoryAlert.IntegrationTests/TestUtils/Assertions/WatchlistItemAssertion.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/AlertRuleApiTest.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Api/AlertRuleApiTest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/AlertRuleApiTest.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Api/AlertRuleApiTest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/AuthApiTest.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Api/AuthApiTest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/AuthApiTest.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Api/AuthApiTest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/MarketApiTest.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Api/MarketApiTest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/MarketApiTest.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Api/MarketApiTest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/StockApiTest.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Api/StockApiTest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/StockApiTest.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Api/StockApiTest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/WatchlistApiTest.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Api/WatchlistApiTest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Api/WatchlistApiTest.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Api/WatchlistApiTest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Handlers/LowHoldingsHandlerTests.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Handlers/LowHoldingsHandlerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Handlers/LowHoldingsHandlerTests.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Handlers/LowHoldingsHandlerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Handlers/MarketPriceAlertHandlerTests.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Handlers/MarketPriceAlertHandlerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Handlers/MarketPriceAlertHandlerTests.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Handlers/MarketPriceAlertHandlerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Jobs/WholeFlowTests.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Jobs/WholeFlowTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Jobs/WholeFlowTests.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Jobs/WholeFlowTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Services/PortfolioServiceTests.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Services/PortfolioServiceTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Services/PortfolioServiceTests.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Services/PortfolioServiceTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Smoke/ALertRuleSmokeTest.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Smoke/ALertRuleSmokeTest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Smoke/ALertRuleSmokeTest.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Smoke/ALertRuleSmokeTest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Smoke/AuthSmokeTest.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Smoke/AuthSmokeTest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Smoke/AuthSmokeTest.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Smoke/AuthSmokeTest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Smoke/WatchlistSmokeTest.cs b/src/test/InventoryAlert.IntegrationTests/Tests/Smoke/WatchlistSmokeTest.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/Smoke/WatchlistSmokeTest.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/Smoke/WatchlistSmokeTest.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/SmokeTests.cs b/src/test/InventoryAlert.IntegrationTests/Tests/SmokeTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Tests/SmokeTests.cs rename to src/test/InventoryAlert.IntegrationTests/Tests/SmokeTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/check-wiremock.json b/src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/check-wiremock.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/check-wiremock.json rename to src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/check-wiremock.json diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/company_news.json b/src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/company_news.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/company_news.json rename to src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/company_news.json diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/get-profile.json b/src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/get-profile.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/get-profile.json rename to src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/get-profile.json diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/get-quote.json b/src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/get-quote.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/get-quote.json rename to src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/get-quote.json diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/market_news.json b/src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/market_news.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/market_news.json rename to src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/market_news.json diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/ping.json b/src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/ping.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/Wiremock/mappings/ping.json rename to src/test/InventoryAlert.IntegrationTests/Wiremock/mappings/ping.json diff --git a/InventoryManagementSystem/InventoryAlert.IntegrationTests/appsettings.test.json b/src/test/InventoryAlert.IntegrationTests/appsettings.test.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.IntegrationTests/appsettings.test.json rename to src/test/InventoryAlert.IntegrationTests/appsettings.test.json diff --git a/InventoryManagementSystem/InventoryAlert.Sample/InventoryAlert.Sample.csproj b/src/test/InventoryAlert.Sample/InventoryAlert.Sample.csproj similarity index 83% rename from InventoryManagementSystem/InventoryAlert.Sample/InventoryAlert.Sample.csproj rename to src/test/InventoryAlert.Sample/InventoryAlert.Sample.csproj index 224f2ed..d86de5c 100644 --- a/InventoryManagementSystem/InventoryAlert.Sample/InventoryAlert.Sample.csproj +++ b/src/test/InventoryAlert.Sample/InventoryAlert.Sample.csproj @@ -1,7 +1,7 @@ - + diff --git a/InventoryManagementSystem/InventoryAlert.Sample/Program.cs b/src/test/InventoryAlert.Sample/Program.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.Sample/Program.cs rename to src/test/InventoryAlert.Sample/Program.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/AlertRuleServiceTests.cs b/src/test/InventoryAlert.UnitTests/Application/Services/AlertRuleServiceTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/AlertRuleServiceTests.cs rename to src/test/InventoryAlert.UnitTests/Application/Services/AlertRuleServiceTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/ConfigurationTests.cs b/src/test/InventoryAlert.UnitTests/Application/Services/ConfigurationTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/ConfigurationTests.cs rename to src/test/InventoryAlert.UnitTests/Application/Services/ConfigurationTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/NotificationServiceTests.cs b/src/test/InventoryAlert.UnitTests/Application/Services/NotificationServiceTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/NotificationServiceTests.cs rename to src/test/InventoryAlert.UnitTests/Application/Services/NotificationServiceTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/PortfolioServiceTests.cs b/src/test/InventoryAlert.UnitTests/Application/Services/PortfolioServiceTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/PortfolioServiceTests.cs rename to src/test/InventoryAlert.UnitTests/Application/Services/PortfolioServiceTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/StockDataServiceTests.cs b/src/test/InventoryAlert.UnitTests/Application/Services/StockDataServiceTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/StockDataServiceTests.cs rename to src/test/InventoryAlert.UnitTests/Application/Services/StockDataServiceTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/WatchlistServiceTests.cs b/src/test/InventoryAlert.UnitTests/Application/Services/WatchlistServiceTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Application/Services/WatchlistServiceTests.cs rename to src/test/InventoryAlert.UnitTests/Application/Services/WatchlistServiceTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Application/Validations/AuthValidatorsTests.cs b/src/test/InventoryAlert.UnitTests/Application/Validations/AuthValidatorsTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Application/Validations/AuthValidatorsTests.cs rename to src/test/InventoryAlert.UnitTests/Application/Validations/AuthValidatorsTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Fixtures/InjectionFixture.cs b/src/test/InventoryAlert.UnitTests/Fixtures/InjectionFixture.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Fixtures/InjectionFixture.cs rename to src/test/InventoryAlert.UnitTests/Fixtures/InjectionFixture.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Helpers/PaginatedListFixtures.cs b/src/test/InventoryAlert.UnitTests/Helpers/PaginatedListFixtures.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Helpers/PaginatedListFixtures.cs rename to src/test/InventoryAlert.UnitTests/Helpers/PaginatedListFixtures.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/External/FinnhubClientTests.cs b/src/test/InventoryAlert.UnitTests/Infrastructure/External/FinnhubClientTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/External/FinnhubClientTests.cs rename to src/test/InventoryAlert.UnitTests/Infrastructure/External/FinnhubClientTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/Messaging/SnsEventPublisherTests.cs b/src/test/InventoryAlert.UnitTests/Infrastructure/Messaging/SnsEventPublisherTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/Messaging/SnsEventPublisherTests.cs rename to src/test/InventoryAlert.UnitTests/Infrastructure/Messaging/SnsEventPublisherTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/GenericRepositoryTests.cs b/src/test/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/GenericRepositoryTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/GenericRepositoryTests.cs rename to src/test/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/GenericRepositoryTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/UnitOfWorkTests.cs b/src/test/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/UnitOfWorkTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/UnitOfWorkTests.cs rename to src/test/InventoryAlert.UnitTests/Infrastructure/Persistence/Repositories/UnitOfWorkTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/Utilities/AlertRuleEvaluatorTests.cs b/src/test/InventoryAlert.UnitTests/Infrastructure/Utilities/AlertRuleEvaluatorTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Infrastructure/Utilities/AlertRuleEvaluatorTests.cs rename to src/test/InventoryAlert.UnitTests/Infrastructure/Utilities/AlertRuleEvaluatorTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj b/src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj similarity index 72% rename from InventoryManagementSystem/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj rename to src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj index 30d7df8..a0cfbc3 100644 --- a/InventoryManagementSystem/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj +++ b/src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj @@ -27,10 +27,10 @@ - - - - + + + + diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/AlertRulesControllerTests.cs b/src/test/InventoryAlert.UnitTests/Web/Controllers/AlertRulesControllerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/AlertRulesControllerTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Controllers/AlertRulesControllerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/AuthControllerTests.cs b/src/test/InventoryAlert.UnitTests/Web/Controllers/AuthControllerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/AuthControllerTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Controllers/AuthControllerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/EventsControllerTests.cs b/src/test/InventoryAlert.UnitTests/Web/Controllers/EventsControllerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/EventsControllerTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Controllers/EventsControllerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/NotificationsControllerTests.cs b/src/test/InventoryAlert.UnitTests/Web/Controllers/NotificationsControllerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/NotificationsControllerTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Controllers/NotificationsControllerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/PortfolioControllerTests.cs b/src/test/InventoryAlert.UnitTests/Web/Controllers/PortfolioControllerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/PortfolioControllerTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Controllers/PortfolioControllerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/StocksControllerTests.cs b/src/test/InventoryAlert.UnitTests/Web/Controllers/StocksControllerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/StocksControllerTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Controllers/StocksControllerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/WatchlistControllerTests.cs b/src/test/InventoryAlert.UnitTests/Web/Controllers/WatchlistControllerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Controllers/WatchlistControllerTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Controllers/WatchlistControllerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Middleware/ApiLoggingMiddlewareTests.cs b/src/test/InventoryAlert.UnitTests/Web/Middleware/ApiLoggingMiddlewareTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Middleware/ApiLoggingMiddlewareTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Middleware/ApiLoggingMiddlewareTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Middleware/CorrelationIdMiddlewareTests.cs b/src/test/InventoryAlert.UnitTests/Web/Middleware/CorrelationIdMiddlewareTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Middleware/CorrelationIdMiddlewareTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Middleware/CorrelationIdMiddlewareTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Web/Middleware/GlobalExceptionMiddlewareTests.cs b/src/test/InventoryAlert.UnitTests/Web/Middleware/GlobalExceptionMiddlewareTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Web/Middleware/GlobalExceptionMiddlewareTests.cs rename to src/test/InventoryAlert.UnitTests/Web/Middleware/GlobalExceptionMiddlewareTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Worker/Handlers/LowHoldingsHandlerTests.cs b/src/test/InventoryAlert.UnitTests/Worker/Handlers/LowHoldingsHandlerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Worker/Handlers/LowHoldingsHandlerTests.cs rename to src/test/InventoryAlert.UnitTests/Worker/Handlers/LowHoldingsHandlerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Worker/Handlers/MarketPriceAlertHandlerTests.cs b/src/test/InventoryAlert.UnitTests/Worker/Handlers/MarketPriceAlertHandlerTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Worker/Handlers/MarketPriceAlertHandlerTests.cs rename to src/test/InventoryAlert.UnitTests/Worker/Handlers/MarketPriceAlertHandlerTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Worker/MessageProcessorTests.cs b/src/test/InventoryAlert.UnitTests/Worker/MessageProcessorTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Worker/MessageProcessorTests.cs rename to src/test/InventoryAlert.UnitTests/Worker/MessageProcessorTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Worker/ScheduledJobs/NewsSyncJobTests.cs b/src/test/InventoryAlert.UnitTests/Worker/ScheduledJobs/NewsSyncJobTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Worker/ScheduledJobs/NewsSyncJobTests.cs rename to src/test/InventoryAlert.UnitTests/Worker/ScheduledJobs/NewsSyncJobTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Worker/ScheduledJobs/ProcessQueueJobTests.cs b/src/test/InventoryAlert.UnitTests/Worker/ScheduledJobs/ProcessQueueJobTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Worker/ScheduledJobs/ProcessQueueJobTests.cs rename to src/test/InventoryAlert.UnitTests/Worker/ScheduledJobs/ProcessQueueJobTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/Worker/ScheduledJobs/SyncPricesJobTests.cs b/src/test/InventoryAlert.UnitTests/Worker/ScheduledJobs/SyncPricesJobTests.cs similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/Worker/ScheduledJobs/SyncPricesJobTests.cs rename to src/test/InventoryAlert.UnitTests/Worker/ScheduledJobs/SyncPricesJobTests.cs diff --git a/InventoryManagementSystem/InventoryAlert.UnitTests/appsettings.json b/src/test/InventoryAlert.UnitTests/appsettings.json similarity index 100% rename from InventoryManagementSystem/InventoryAlert.UnitTests/appsettings.json rename to src/test/InventoryAlert.UnitTests/appsettings.json diff --git a/InventoryAlert.UI/.dockerignore b/src/ui/InventoryAlert.UI/.dockerignore similarity index 100% rename from InventoryAlert.UI/.dockerignore rename to src/ui/InventoryAlert.UI/.dockerignore diff --git a/InventoryAlert.UI/.gitignore b/src/ui/InventoryAlert.UI/.gitignore similarity index 100% rename from InventoryAlert.UI/.gitignore rename to src/ui/InventoryAlert.UI/.gitignore diff --git a/InventoryAlert.UI/Dockerfile b/src/ui/InventoryAlert.UI/Dockerfile similarity index 100% rename from InventoryAlert.UI/Dockerfile rename to src/ui/InventoryAlert.UI/Dockerfile diff --git a/InventoryAlert.UI/README.md b/src/ui/InventoryAlert.UI/README.md similarity index 100% rename from InventoryAlert.UI/README.md rename to src/ui/InventoryAlert.UI/README.md diff --git a/InventoryAlert.UI/eslint.config.mjs b/src/ui/InventoryAlert.UI/eslint.config.mjs similarity index 100% rename from InventoryAlert.UI/eslint.config.mjs rename to src/ui/InventoryAlert.UI/eslint.config.mjs diff --git a/InventoryAlert.UI/next.config.ts b/src/ui/InventoryAlert.UI/next.config.ts similarity index 100% rename from InventoryAlert.UI/next.config.ts rename to src/ui/InventoryAlert.UI/next.config.ts diff --git a/InventoryAlert.UI/package-lock.json b/src/ui/InventoryAlert.UI/package-lock.json similarity index 100% rename from InventoryAlert.UI/package-lock.json rename to src/ui/InventoryAlert.UI/package-lock.json diff --git a/InventoryAlert.UI/package.json b/src/ui/InventoryAlert.UI/package.json similarity index 100% rename from InventoryAlert.UI/package.json rename to src/ui/InventoryAlert.UI/package.json diff --git a/InventoryAlert.UI/postcss.config.mjs b/src/ui/InventoryAlert.UI/postcss.config.mjs similarity index 100% rename from InventoryAlert.UI/postcss.config.mjs rename to src/ui/InventoryAlert.UI/postcss.config.mjs diff --git a/InventoryAlert.UI/public/file.svg b/src/ui/InventoryAlert.UI/public/file.svg similarity index 100% rename from InventoryAlert.UI/public/file.svg rename to src/ui/InventoryAlert.UI/public/file.svg diff --git a/InventoryAlert.UI/public/globe.svg b/src/ui/InventoryAlert.UI/public/globe.svg similarity index 100% rename from InventoryAlert.UI/public/globe.svg rename to src/ui/InventoryAlert.UI/public/globe.svg diff --git a/InventoryAlert.UI/public/next.svg b/src/ui/InventoryAlert.UI/public/next.svg similarity index 100% rename from InventoryAlert.UI/public/next.svg rename to src/ui/InventoryAlert.UI/public/next.svg diff --git a/InventoryAlert.UI/public/vercel.svg b/src/ui/InventoryAlert.UI/public/vercel.svg similarity index 100% rename from InventoryAlert.UI/public/vercel.svg rename to src/ui/InventoryAlert.UI/public/vercel.svg diff --git a/InventoryAlert.UI/public/window.svg b/src/ui/InventoryAlert.UI/public/window.svg similarity index 100% rename from InventoryAlert.UI/public/window.svg rename to src/ui/InventoryAlert.UI/public/window.svg diff --git a/InventoryAlert.UI/src/app/(auth)/login/page.tsx b/src/ui/InventoryAlert.UI/src/app/(auth)/login/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/(auth)/login/page.tsx rename to src/ui/InventoryAlert.UI/src/app/(auth)/login/page.tsx diff --git a/InventoryAlert.UI/src/app/(auth)/register/page.tsx b/src/ui/InventoryAlert.UI/src/app/(auth)/register/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/(auth)/register/page.tsx rename to src/ui/InventoryAlert.UI/src/app/(auth)/register/page.tsx diff --git a/InventoryAlert.UI/src/app/admin/health/page.tsx b/src/ui/InventoryAlert.UI/src/app/admin/health/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/admin/health/page.tsx rename to src/ui/InventoryAlert.UI/src/app/admin/health/page.tsx diff --git a/InventoryAlert.UI/src/app/alerts/page.tsx b/src/ui/InventoryAlert.UI/src/app/alerts/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/alerts/page.tsx rename to src/ui/InventoryAlert.UI/src/app/alerts/page.tsx diff --git a/InventoryAlert.UI/src/app/favicon.ico b/src/ui/InventoryAlert.UI/src/app/favicon.ico similarity index 100% rename from InventoryAlert.UI/src/app/favicon.ico rename to src/ui/InventoryAlert.UI/src/app/favicon.ico diff --git a/InventoryAlert.UI/src/app/globals.css b/src/ui/InventoryAlert.UI/src/app/globals.css similarity index 100% rename from InventoryAlert.UI/src/app/globals.css rename to src/ui/InventoryAlert.UI/src/app/globals.css diff --git a/InventoryAlert.UI/src/app/layout.tsx b/src/ui/InventoryAlert.UI/src/app/layout.tsx similarity index 100% rename from InventoryAlert.UI/src/app/layout.tsx rename to src/ui/InventoryAlert.UI/src/app/layout.tsx diff --git a/InventoryAlert.UI/src/app/market/page.tsx b/src/ui/InventoryAlert.UI/src/app/market/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/market/page.tsx rename to src/ui/InventoryAlert.UI/src/app/market/page.tsx diff --git a/InventoryAlert.UI/src/app/notifications/page.tsx b/src/ui/InventoryAlert.UI/src/app/notifications/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/notifications/page.tsx rename to src/ui/InventoryAlert.UI/src/app/notifications/page.tsx diff --git a/InventoryAlert.UI/src/app/page.tsx b/src/ui/InventoryAlert.UI/src/app/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/page.tsx rename to src/ui/InventoryAlert.UI/src/app/page.tsx diff --git a/InventoryAlert.UI/src/app/portfolio/page.tsx b/src/ui/InventoryAlert.UI/src/app/portfolio/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/portfolio/page.tsx rename to src/ui/InventoryAlert.UI/src/app/portfolio/page.tsx diff --git a/InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx b/src/ui/InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx rename to src/ui/InventoryAlert.UI/src/app/stocks/[symbol]/page.tsx diff --git a/InventoryAlert.UI/src/app/stocks/page.tsx b/src/ui/InventoryAlert.UI/src/app/stocks/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/stocks/page.tsx rename to src/ui/InventoryAlert.UI/src/app/stocks/page.tsx diff --git a/InventoryAlert.UI/src/app/watchlist/page.tsx b/src/ui/InventoryAlert.UI/src/app/watchlist/page.tsx similarity index 100% rename from InventoryAlert.UI/src/app/watchlist/page.tsx rename to src/ui/InventoryAlert.UI/src/app/watchlist/page.tsx diff --git a/InventoryAlert.UI/src/components/AddSymbolModal.tsx b/src/ui/InventoryAlert.UI/src/components/AddSymbolModal.tsx similarity index 100% rename from InventoryAlert.UI/src/components/AddSymbolModal.tsx rename to src/ui/InventoryAlert.UI/src/components/AddSymbolModal.tsx diff --git a/InventoryAlert.UI/src/components/ConfirmDialog.tsx b/src/ui/InventoryAlert.UI/src/components/ConfirmDialog.tsx similarity index 100% rename from InventoryAlert.UI/src/components/ConfirmDialog.tsx rename to src/ui/InventoryAlert.UI/src/components/ConfirmDialog.tsx diff --git a/InventoryAlert.UI/src/components/GlobalSearch.tsx b/src/ui/InventoryAlert.UI/src/components/GlobalSearch.tsx similarity index 100% rename from InventoryAlert.UI/src/components/GlobalSearch.tsx rename to src/ui/InventoryAlert.UI/src/components/GlobalSearch.tsx diff --git a/InventoryAlert.UI/src/components/MarketStatusBanner.test.tsx b/src/ui/InventoryAlert.UI/src/components/MarketStatusBanner.test.tsx similarity index 100% rename from InventoryAlert.UI/src/components/MarketStatusBanner.test.tsx rename to src/ui/InventoryAlert.UI/src/components/MarketStatusBanner.test.tsx diff --git a/InventoryAlert.UI/src/components/MarketStatusBanner.tsx b/src/ui/InventoryAlert.UI/src/components/MarketStatusBanner.tsx similarity index 100% rename from InventoryAlert.UI/src/components/MarketStatusBanner.tsx rename to src/ui/InventoryAlert.UI/src/components/MarketStatusBanner.tsx diff --git a/InventoryAlert.UI/src/components/Navbar.tsx b/src/ui/InventoryAlert.UI/src/components/Navbar.tsx similarity index 100% rename from InventoryAlert.UI/src/components/Navbar.tsx rename to src/ui/InventoryAlert.UI/src/components/Navbar.tsx diff --git a/InventoryAlert.UI/src/components/NavbarWrapper.tsx b/src/ui/InventoryAlert.UI/src/components/NavbarWrapper.tsx similarity index 100% rename from InventoryAlert.UI/src/components/NavbarWrapper.tsx rename to src/ui/InventoryAlert.UI/src/components/NavbarWrapper.tsx diff --git a/InventoryAlert.UI/src/components/NotificationBell.test.tsx b/src/ui/InventoryAlert.UI/src/components/NotificationBell.test.tsx similarity index 100% rename from InventoryAlert.UI/src/components/NotificationBell.test.tsx rename to src/ui/InventoryAlert.UI/src/components/NotificationBell.test.tsx diff --git a/InventoryAlert.UI/src/components/NotificationBell.tsx b/src/ui/InventoryAlert.UI/src/components/NotificationBell.tsx similarity index 100% rename from InventoryAlert.UI/src/components/NotificationBell.tsx rename to src/ui/InventoryAlert.UI/src/components/NotificationBell.tsx diff --git a/InventoryAlert.UI/src/components/NotificationProvider.tsx b/src/ui/InventoryAlert.UI/src/components/NotificationProvider.tsx similarity index 100% rename from InventoryAlert.UI/src/components/NotificationProvider.tsx rename to src/ui/InventoryAlert.UI/src/components/NotificationProvider.tsx diff --git a/InventoryAlert.UI/src/components/PriceAlertModal.tsx b/src/ui/InventoryAlert.UI/src/components/PriceAlertModal.tsx similarity index 100% rename from InventoryAlert.UI/src/components/PriceAlertModal.tsx rename to src/ui/InventoryAlert.UI/src/components/PriceAlertModal.tsx diff --git a/InventoryAlert.UI/src/components/ThemeProvider.tsx b/src/ui/InventoryAlert.UI/src/components/ThemeProvider.tsx similarity index 100% rename from InventoryAlert.UI/src/components/ThemeProvider.tsx rename to src/ui/InventoryAlert.UI/src/components/ThemeProvider.tsx diff --git a/InventoryAlert.UI/src/components/Toast.tsx b/src/ui/InventoryAlert.UI/src/components/Toast.tsx similarity index 100% rename from InventoryAlert.UI/src/components/Toast.tsx rename to src/ui/InventoryAlert.UI/src/components/Toast.tsx diff --git a/InventoryAlert.UI/src/components/TradeModal.tsx b/src/ui/InventoryAlert.UI/src/components/TradeModal.tsx similarity index 100% rename from InventoryAlert.UI/src/components/TradeModal.tsx rename to src/ui/InventoryAlert.UI/src/components/TradeModal.tsx diff --git a/InventoryAlert.UI/src/components/UserNav.tsx b/src/ui/InventoryAlert.UI/src/components/UserNav.tsx similarity index 100% rename from InventoryAlert.UI/src/components/UserNav.tsx rename to src/ui/InventoryAlert.UI/src/components/UserNav.tsx diff --git a/InventoryAlert.UI/src/components/ui/Pagination.tsx b/src/ui/InventoryAlert.UI/src/components/ui/Pagination.tsx similarity index 100% rename from InventoryAlert.UI/src/components/ui/Pagination.tsx rename to src/ui/InventoryAlert.UI/src/components/ui/Pagination.tsx diff --git a/InventoryAlert.UI/src/hooks/useSignalR.ts b/src/ui/InventoryAlert.UI/src/hooks/useSignalR.ts similarity index 100% rename from InventoryAlert.UI/src/hooks/useSignalR.ts rename to src/ui/InventoryAlert.UI/src/hooks/useSignalR.ts diff --git a/InventoryAlert.UI/src/lib/api.refresh.test.ts b/src/ui/InventoryAlert.UI/src/lib/api.refresh.test.ts similarity index 100% rename from InventoryAlert.UI/src/lib/api.refresh.test.ts rename to src/ui/InventoryAlert.UI/src/lib/api.refresh.test.ts diff --git a/InventoryAlert.UI/src/lib/api.test.ts b/src/ui/InventoryAlert.UI/src/lib/api.test.ts similarity index 100% rename from InventoryAlert.UI/src/lib/api.test.ts rename to src/ui/InventoryAlert.UI/src/lib/api.test.ts diff --git a/InventoryAlert.UI/src/lib/api.ts b/src/ui/InventoryAlert.UI/src/lib/api.ts similarity index 100% rename from InventoryAlert.UI/src/lib/api.ts rename to src/ui/InventoryAlert.UI/src/lib/api.ts diff --git a/InventoryAlert.UI/src/lib/error-utils.ts b/src/ui/InventoryAlert.UI/src/lib/error-utils.ts similarity index 100% rename from InventoryAlert.UI/src/lib/error-utils.ts rename to src/ui/InventoryAlert.UI/src/lib/error-utils.ts diff --git a/InventoryAlert.UI/tsconfig.json b/src/ui/InventoryAlert.UI/tsconfig.json similarity index 100% rename from InventoryAlert.UI/tsconfig.json rename to src/ui/InventoryAlert.UI/tsconfig.json diff --git a/InventoryAlert.UI/vitest.config.ts b/src/ui/InventoryAlert.UI/vitest.config.ts similarity index 100% rename from InventoryAlert.UI/vitest.config.ts rename to src/ui/InventoryAlert.UI/vitest.config.ts diff --git a/InventoryAlert.UI/vitest.setup.ts b/src/ui/InventoryAlert.UI/vitest.setup.ts similarity index 100% rename from InventoryAlert.UI/vitest.setup.ts rename to src/ui/InventoryAlert.UI/vitest.setup.ts diff --git a/InventoryAlert.Wiki/.gitignore b/src/ui/InventoryAlert.Wiki/.gitignore similarity index 100% rename from InventoryAlert.Wiki/.gitignore rename to src/ui/InventoryAlert.Wiki/.gitignore diff --git a/InventoryAlert.Wiki/README.md b/src/ui/InventoryAlert.Wiki/README.md similarity index 100% rename from InventoryAlert.Wiki/README.md rename to src/ui/InventoryAlert.Wiki/README.md diff --git a/InventoryAlert.Wiki/docs/00-overview/introduction.md b/src/ui/InventoryAlert.Wiki/docs/00-overview/introduction.md similarity index 100% rename from InventoryAlert.Wiki/docs/00-overview/introduction.md rename to src/ui/InventoryAlert.Wiki/docs/00-overview/introduction.md diff --git a/InventoryAlert.Wiki/docs/02-architecture-techstack/architecture-overview.md b/src/ui/InventoryAlert.Wiki/docs/02-architecture-techstack/architecture-overview.md similarity index 100% rename from InventoryAlert.Wiki/docs/02-architecture-techstack/architecture-overview.md rename to src/ui/InventoryAlert.Wiki/docs/02-architecture-techstack/architecture-overview.md diff --git a/InventoryAlert.Wiki/docs/02-architecture-techstack/domain-and-structure.md b/src/ui/InventoryAlert.Wiki/docs/02-architecture-techstack/domain-and-structure.md similarity index 63% rename from InventoryAlert.Wiki/docs/02-architecture-techstack/domain-and-structure.md rename to src/ui/InventoryAlert.Wiki/docs/02-architecture-techstack/domain-and-structure.md index 7a456ae..b21f570 100644 --- a/InventoryAlert.Wiki/docs/02-architecture-techstack/domain-and-structure.md +++ b/src/ui/InventoryAlert.Wiki/docs/02-architecture-techstack/domain-and-structure.md @@ -6,16 +6,16 @@ InventoryAlert uses a **Lean Vertical Slice** approach. Business logic is co-loc ## Project Structure -| Project | Responsibility | Key Namespaces | -|---|---|---| -| **InventoryAlert.Domain** | Pure entities, repository interfaces, DTOs, events, enums, and validators. Zero external dependencies. | `Domain.Entities`, `Domain.Interfaces`, `Domain.DTOs`, `Domain.Events`, `Domain.Validators` | -| **InventoryAlert.Infrastructure** | EF Core (PostgreSQL), DynamoDB, FinnhubClient, SQS queue, Redis, and UnitOfWork. | `Infrastructure.Persistence`, `Infrastructure.External`, `Infrastructure.Messaging` | -| **InventoryAlert.Api** | Thin REST controllers, service layer, FluentValidation, middleware, JWT auth, DI root. | `Api.Controllers`, `Api.Services`, `Api.Configuration`, `Api.Middleware` | -| **InventoryAlert.Worker** | Hangfire jobs, SQS listener, SQS event handlers. | `Worker.ScheduledJobs`, `Worker.IntegrationEvents` | -| **InventoryAlert.UnitTests** | xUnit + Moq + FluentAssertions. Covers all services, repositories. | - | -| **InventoryAlert.IntegrationTests** | EF Core InMemory repository tests. | - | -| **InventoryAlert.E2ETests** | Full HTTP roundtrip via RestSharp against running Docker stack. | - | -| **InventoryAlert.ArchitectureTests** | NetArchTest: Domain must have zero imports from Infrastructure/Api/Worker. | - | +| Project | Responsibility | Key Namespaces | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | +| **InventoryAlert.Domain** | Pure entities, repository interfaces, DTOs, events, enums, and validators. Zero external dependencies. | `Domain.Entities`, `Domain.Interfaces`, `Domain.DTOs`, `Domain.Events`, `Domain.Validators` | +| **InventoryAlert.Infrastructure** | EF Core (PostgreSQL), DynamoDB, FinnhubClient, SQS queue, Redis, and UnitOfWork. | `Infrastructure.Persistence`, `Infrastructure.External`, `Infrastructure.Messaging` | +| **InventoryAlert.Api** | Thin REST controllers, service layer, FluentValidation, middleware, JWT auth, DI root. | `Api.Controllers`, `Api.Services`, `Api.Configuration`, `Api.Middleware` | +| **InventoryAlert.Worker** | Hangfire jobs, SQS listener, SQS event handlers. | `Worker.ScheduledJobs`, `Worker.IntegrationEvents` | +| **InventoryAlert.UnitTests** | xUnit + Moq + FluentAssertions. Covers all services, repositories. | - | +| **InventoryAlert.IntegrationTests** | EF Core InMemory repository tests. | - | +| **InventoryAlert.E2ETests** | Full HTTP roundtrip via RestSharp against running Docker stack. | - | +| **InventoryAlert.ArchitectureTests** | NetArchTest: Domain must have zero imports from Infrastructure/Api/Worker. | - | ### Dependency Direction @@ -174,18 +174,18 @@ InventoryManagementSystem/ ## Placement Decision Reference -| Type | Belongs In | -|---|---| -| Entity class | `Domain/Entities/` | -| Repository interface | `Domain/Interfaces/` | -| Service interface (shared) | `Domain/Interfaces/` | -| Request/Response DTO | `Domain/DTOs/` | -| FluentValidation validator | `Domain/Validators/` | -| SQS event payload | `Domain/Events/Payloads/` | -| EF Core configuration | `Infrastructure/Persistence/Configurations/` | -| Repository implementation | `Infrastructure/Persistence/Repositories/` | -| Caching / Messaging impl | `Infrastructure/Caching/` or `Infrastructure/Messaging/` | -| Controller | `Api/Controllers/` | -| API-level service | `Api/Services/` | -| Scheduled job | `Worker/ScheduledJobs/` | -| SQS event handler | `Worker/IntegrationEvents/Handlers/` | +| Type | Belongs In | +| -------------------------- | -------------------------------------------------------- | +| Entity class | `Domain/Entities/` | +| Repository interface | `Domain/Interfaces/` | +| Service interface (shared) | `Domain/Interfaces/` | +| Request/Response DTO | `Domain/DTOs/` | +| FluentValidation validator | `Domain/Validators/` | +| SQS event payload | `Domain/Events/Payloads/` | +| EF Core configuration | `Infrastructure/Persistence/Configurations/` | +| Repository implementation | `Infrastructure/Persistence/Repositories/` | +| Caching / Messaging impl | `Infrastructure/Caching/` or `Infrastructure/Messaging/` | +| Controller | `Api/Controllers/` | +| API-level service | `Api/Services/` | +| Scheduled job | `Worker/ScheduledJobs/` | +| SQS event handler | `Worker/IntegrationEvents/Handlers/` | diff --git a/InventoryAlert.Wiki/docs/02-architecture-techstack/microservice-components.md b/src/ui/InventoryAlert.Wiki/docs/02-architecture-techstack/microservice-components.md similarity index 100% rename from InventoryAlert.Wiki/docs/02-architecture-techstack/microservice-components.md rename to src/ui/InventoryAlert.Wiki/docs/02-architecture-techstack/microservice-components.md diff --git a/InventoryAlert.Wiki/docs/03-data-model/caching-strategy.md b/src/ui/InventoryAlert.Wiki/docs/03-data-model/caching-strategy.md similarity index 100% rename from InventoryAlert.Wiki/docs/03-data-model/caching-strategy.md rename to src/ui/InventoryAlert.Wiki/docs/03-data-model/caching-strategy.md diff --git a/InventoryAlert.Wiki/docs/03-data-model/data-model.md b/src/ui/InventoryAlert.Wiki/docs/03-data-model/data-model.md similarity index 100% rename from InventoryAlert.Wiki/docs/03-data-model/data-model.md rename to src/ui/InventoryAlert.Wiki/docs/03-data-model/data-model.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/alert-rule-creation.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/alert-rule-creation.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/alert-rule-creation.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/alert-rule-creation.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/business-logic.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/business-logic.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/business-logic.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/business-logic.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/cqrs-event-flow.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/cqrs-event-flow.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/cqrs-event-flow.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/cqrs-event-flow.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/earnings-sync-flow.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/earnings-sync-flow.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/earnings-sync-flow.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/earnings-sync-flow.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/error-handling-flow.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/error-handling-flow.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/error-handling-flow.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/error-handling-flow.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/news-sync-flow.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/news-sync-flow.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/news-sync-flow.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/news-sync-flow.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/portfolio-management-flow.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/portfolio-management-flow.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/portfolio-management-flow.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/portfolio-management-flow.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/price-sync-flow.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/price-sync-flow.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/price-sync-flow.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/price-sync-flow.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/user-authentication.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/user-authentication.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/user-authentication.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/user-authentication.md diff --git a/InventoryAlert.Wiki/docs/04-execution-flows/watchlist-management-flow.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/watchlist-management-flow.md similarity index 100% rename from InventoryAlert.Wiki/docs/04-execution-flows/watchlist-management-flow.md rename to src/ui/InventoryAlert.Wiki/docs/04-execution-flows/watchlist-management-flow.md diff --git a/InventoryAlert.Wiki/docs/05-api-services/event-handling.md b/src/ui/InventoryAlert.Wiki/docs/05-api-services/event-handling.md similarity index 100% rename from InventoryAlert.Wiki/docs/05-api-services/event-handling.md rename to src/ui/InventoryAlert.Wiki/docs/05-api-services/event-handling.md diff --git a/InventoryAlert.Wiki/docs/05-api-services/external-integrations.md b/src/ui/InventoryAlert.Wiki/docs/05-api-services/external-integrations.md similarity index 100% rename from InventoryAlert.Wiki/docs/05-api-services/external-integrations.md rename to src/ui/InventoryAlert.Wiki/docs/05-api-services/external-integrations.md diff --git a/InventoryAlert.Wiki/docs/05-api-services/internal-api.md b/src/ui/InventoryAlert.Wiki/docs/05-api-services/internal-api.md similarity index 100% rename from InventoryAlert.Wiki/docs/05-api-services/internal-api.md rename to src/ui/InventoryAlert.Wiki/docs/05-api-services/internal-api.md diff --git a/InventoryAlert.Wiki/docs/06-background-jobs/hangfire-monitoring.md b/src/ui/InventoryAlert.Wiki/docs/06-background-jobs/hangfire-monitoring.md similarity index 100% rename from InventoryAlert.Wiki/docs/06-background-jobs/hangfire-monitoring.md rename to src/ui/InventoryAlert.Wiki/docs/06-background-jobs/hangfire-monitoring.md diff --git a/InventoryAlert.Wiki/docs/06-background-jobs/workers.md b/src/ui/InventoryAlert.Wiki/docs/06-background-jobs/workers.md similarity index 100% rename from InventoryAlert.Wiki/docs/06-background-jobs/workers.md rename to src/ui/InventoryAlert.Wiki/docs/06-background-jobs/workers.md diff --git a/InventoryAlert.Wiki/docs/07-dev-maintenance/ai-agent-workflows.md b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/ai-agent-workflows.md similarity index 100% rename from InventoryAlert.Wiki/docs/07-dev-maintenance/ai-agent-workflows.md rename to src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/ai-agent-workflows.md diff --git a/InventoryAlert.Wiki/docs/07-dev-maintenance/dotnet-commands.md b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/dotnet-commands.md similarity index 100% rename from InventoryAlert.Wiki/docs/07-dev-maintenance/dotnet-commands.md rename to src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/dotnet-commands.md diff --git a/InventoryAlert.Wiki/docs/07-dev-maintenance/getting-started.md b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/getting-started.md similarity index 71% rename from InventoryAlert.Wiki/docs/07-dev-maintenance/getting-started.md rename to src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/getting-started.md index 2419d2d..0c4d173 100644 --- a/InventoryAlert.Wiki/docs/07-dev-maintenance/getting-started.md +++ b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/getting-started.md @@ -13,23 +13,23 @@ docker compose up --build ``` -| Service | URL | Notes | -|---|---|---| -| API | http://localhost:8080 | Swagger at `/swagger` | -| UI | http://localhost:3000 | Next.js frontend | -| Hangfire Dashboard | http://localhost:8080/hangfire | Admin only | -| Seq Logs | http://localhost:5341 | Structured log viewer | -| PostgreSQL | localhost:**5433** | Internal port 5432 | -| DynamoDB/SQS | localhost:5000 | Moto emulator | -| Redis | localhost:6379 | Cache + dedup | -| Wiki (local) | http://localhost:3001 | Docusaurus dev server | +| Service | URL | Notes | +| ------------------ | ------------------------------ | --------------------- | +| API | http://localhost:8080 | Swagger at `/swagger` | +| UI | http://localhost:3000 | Next.js frontend | +| Hangfire Dashboard | http://localhost:8080/hangfire | Admin only | +| Seq Logs | http://localhost:5341 | Structured log viewer | +| PostgreSQL | localhost:**5433** | Internal port 5432 | +| DynamoDB/SQS | localhost:5000 | Moto emulator | +| Redis | localhost:6379 | Cache + dedup | +| Wiki (local) | http://localhost:3001 | Docusaurus dev server | ## Seed Credentials -| Username | Password | Role | -|---|---|---| -| `admin` | `password` | Admin | -| `user1` | `password` | User | +| Username | Password | Role | +| -------- | ---------- | ----- | +| `admin` | `password` | Admin | +| `user1` | `password` | User | --- diff --git a/InventoryAlert.Wiki/docs/07-dev-maintenance/integration-testing-tiers.md b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/integration-testing-tiers.md similarity index 100% rename from InventoryAlert.Wiki/docs/07-dev-maintenance/integration-testing-tiers.md rename to src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/integration-testing-tiers.md diff --git a/InventoryAlert.Wiki/docs/07-dev-maintenance/operational-runbook.md b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/operational-runbook.md similarity index 80% rename from InventoryAlert.Wiki/docs/07-dev-maintenance/operational-runbook.md rename to src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/operational-runbook.md index 70cc55e..1bdf86b 100644 --- a/InventoryAlert.Wiki/docs/07-dev-maintenance/operational-runbook.md +++ b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/operational-runbook.md @@ -4,14 +4,14 @@ ## Service URLs -| Service | URL | Notes | -|---|---|---| -| API (Swagger) | http://localhost:8080/swagger | REST API + interactive docs | -| UI | http://localhost:3000 | Next.js frontend | -| Hangfire | http://localhost:8080/hangfire | Admin only — job dashboard | -| Seq Logs | http://localhost:5341 | Structured log viewer | -| PostgreSQL | localhost:5433 | `psql -h localhost -p 5433 -U postgres` | -| DynamoDB/SQS | localhost:5000 | Moto (local AWS emulator) | +| Service | URL | Notes | +| ------------- | ------------------------------ | --------------------------------------- | +| API (Swagger) | http://localhost:8080/swagger | REST API + interactive docs | +| UI | http://localhost:3000 | Next.js frontend | +| Hangfire | http://localhost:8080/hangfire | Admin only — job dashboard | +| Seq Logs | http://localhost:5341 | Structured log viewer | +| PostgreSQL | localhost:5433 | `psql -h localhost -p 5433 -U postgres` | +| DynamoDB/SQS | localhost:5000 | Moto (local AWS emulator) | --- diff --git a/InventoryAlert.Wiki/docs/07-dev-maintenance/test-strategy.md b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/test-strategy.md similarity index 100% rename from InventoryAlert.Wiki/docs/07-dev-maintenance/test-strategy.md rename to src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/test-strategy.md diff --git a/InventoryAlert.Wiki/docs/07-dev-maintenance/testing-and-standards.md b/src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/testing-and-standards.md similarity index 100% rename from InventoryAlert.Wiki/docs/07-dev-maintenance/testing-and-standards.md rename to src/ui/InventoryAlert.Wiki/docs/07-dev-maintenance/testing-and-standards.md diff --git a/InventoryAlert.Wiki/docs/08-frontend-ui/feature-breakdown.md b/src/ui/InventoryAlert.Wiki/docs/08-frontend-ui/feature-breakdown.md similarity index 100% rename from InventoryAlert.Wiki/docs/08-frontend-ui/feature-breakdown.md rename to src/ui/InventoryAlert.Wiki/docs/08-frontend-ui/feature-breakdown.md diff --git a/InventoryAlert.Wiki/docs/08-frontend-ui/ui-architecture.md b/src/ui/InventoryAlert.Wiki/docs/08-frontend-ui/ui-architecture.md similarity index 100% rename from InventoryAlert.Wiki/docs/08-frontend-ui/ui-architecture.md rename to src/ui/InventoryAlert.Wiki/docs/08-frontend-ui/ui-architecture.md diff --git a/InventoryAlert.Wiki/docs/index.md b/src/ui/InventoryAlert.Wiki/docs/index.md similarity index 100% rename from InventoryAlert.Wiki/docs/index.md rename to src/ui/InventoryAlert.Wiki/docs/index.md diff --git a/InventoryAlert.Wiki/docusaurus.config.ts b/src/ui/InventoryAlert.Wiki/docusaurus.config.ts similarity index 100% rename from InventoryAlert.Wiki/docusaurus.config.ts rename to src/ui/InventoryAlert.Wiki/docusaurus.config.ts diff --git a/InventoryAlert.Wiki/package-lock.json b/src/ui/InventoryAlert.Wiki/package-lock.json similarity index 100% rename from InventoryAlert.Wiki/package-lock.json rename to src/ui/InventoryAlert.Wiki/package-lock.json diff --git a/InventoryAlert.Wiki/package.json b/src/ui/InventoryAlert.Wiki/package.json similarity index 100% rename from InventoryAlert.Wiki/package.json rename to src/ui/InventoryAlert.Wiki/package.json diff --git a/InventoryAlert.Wiki/sidebars.ts b/src/ui/InventoryAlert.Wiki/sidebars.ts similarity index 100% rename from InventoryAlert.Wiki/sidebars.ts rename to src/ui/InventoryAlert.Wiki/sidebars.ts diff --git a/InventoryAlert.Wiki/src/components/HomepageFeatures/index.tsx b/src/ui/InventoryAlert.Wiki/src/components/HomepageFeatures/index.tsx similarity index 100% rename from InventoryAlert.Wiki/src/components/HomepageFeatures/index.tsx rename to src/ui/InventoryAlert.Wiki/src/components/HomepageFeatures/index.tsx diff --git a/InventoryAlert.Wiki/src/components/HomepageFeatures/styles.module.css b/src/ui/InventoryAlert.Wiki/src/components/HomepageFeatures/styles.module.css similarity index 100% rename from InventoryAlert.Wiki/src/components/HomepageFeatures/styles.module.css rename to src/ui/InventoryAlert.Wiki/src/components/HomepageFeatures/styles.module.css diff --git a/InventoryAlert.Wiki/src/css/custom.css b/src/ui/InventoryAlert.Wiki/src/css/custom.css similarity index 100% rename from InventoryAlert.Wiki/src/css/custom.css rename to src/ui/InventoryAlert.Wiki/src/css/custom.css diff --git a/InventoryAlert.Wiki/static/.nojekyll b/src/ui/InventoryAlert.Wiki/static/.nojekyll similarity index 100% rename from InventoryAlert.Wiki/static/.nojekyll rename to src/ui/InventoryAlert.Wiki/static/.nojekyll diff --git a/InventoryAlert.Wiki/static/img/docusaurus-social-card.jpg b/src/ui/InventoryAlert.Wiki/static/img/docusaurus-social-card.jpg similarity index 100% rename from InventoryAlert.Wiki/static/img/docusaurus-social-card.jpg rename to src/ui/InventoryAlert.Wiki/static/img/docusaurus-social-card.jpg diff --git a/InventoryAlert.Wiki/static/img/docusaurus.png b/src/ui/InventoryAlert.Wiki/static/img/docusaurus.png similarity index 100% rename from InventoryAlert.Wiki/static/img/docusaurus.png rename to src/ui/InventoryAlert.Wiki/static/img/docusaurus.png diff --git a/InventoryAlert.Wiki/static/img/favicon.ico b/src/ui/InventoryAlert.Wiki/static/img/favicon.ico similarity index 100% rename from InventoryAlert.Wiki/static/img/favicon.ico rename to src/ui/InventoryAlert.Wiki/static/img/favicon.ico diff --git a/InventoryAlert.Wiki/static/img/logo.svg b/src/ui/InventoryAlert.Wiki/static/img/logo.svg similarity index 100% rename from InventoryAlert.Wiki/static/img/logo.svg rename to src/ui/InventoryAlert.Wiki/static/img/logo.svg diff --git a/InventoryAlert.Wiki/static/img/undraw_docusaurus_mountain.svg b/src/ui/InventoryAlert.Wiki/static/img/undraw_docusaurus_mountain.svg similarity index 100% rename from InventoryAlert.Wiki/static/img/undraw_docusaurus_mountain.svg rename to src/ui/InventoryAlert.Wiki/static/img/undraw_docusaurus_mountain.svg diff --git a/InventoryAlert.Wiki/static/img/undraw_docusaurus_react.svg b/src/ui/InventoryAlert.Wiki/static/img/undraw_docusaurus_react.svg similarity index 100% rename from InventoryAlert.Wiki/static/img/undraw_docusaurus_react.svg rename to src/ui/InventoryAlert.Wiki/static/img/undraw_docusaurus_react.svg diff --git a/InventoryAlert.Wiki/static/img/undraw_docusaurus_tree.svg b/src/ui/InventoryAlert.Wiki/static/img/undraw_docusaurus_tree.svg similarity index 100% rename from InventoryAlert.Wiki/static/img/undraw_docusaurus_tree.svg rename to src/ui/InventoryAlert.Wiki/static/img/undraw_docusaurus_tree.svg diff --git a/InventoryAlert.Wiki/tsconfig.json b/src/ui/InventoryAlert.Wiki/tsconfig.json similarity index 100% rename from InventoryAlert.Wiki/tsconfig.json rename to src/ui/InventoryAlert.Wiki/tsconfig.json From 10661475bb9228caaffabda1bcb01b37820c1c23 Mon Sep 17 00:00:00 2001 From: nhonvo Date: Wed, 27 May 2026 13:09:19 +0700 Subject: [PATCH 2/4] docs(wiki): fix Mermaid diagram syntax error in alert-dispatch.md --- .../docs/04-execution-flows/alert-dispatch.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md index c823884..accd1c0 100644 --- a/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md +++ b/src/ui/InventoryAlert.Wiki/docs/04-execution-flows/alert-dispatch.md @@ -29,9 +29,9 @@ flowchart TD H & I & J --> K{Breached?} K -- Yes --> L{Redis Cooldown active?} - L -- Yes --> M[Skip — inventoryalert:alerts:cooldown:v1:{userId}:{ruleId} exists] + L -- Yes --> M["Skip — inventoryalert:alerts:cooldown:v1:{userId}:{ruleId} exists"] L -- No --> N[1. INSERT Notification row] - N --> O[2. SET inventoryalert:alerts:cooldown:v1:{userId}:{ruleId} TTL=24h] + N --> O["2. SET inventoryalert:alerts:cooldown:v1:{userId}:{ruleId} TTL=24h"] O --> P[3. Push via SignalR HubContext] P --> Q{TriggerOnce?} Q -- Yes --> R[UPDATE AlertRule SET IsActive = false] From e90b80587a7049ad8e4d3396d2053c18fc58444a Mon Sep 17 00:00:00 2001 From: nhonvo Date: Wed, 27 May 2026 13:41:12 +0700 Subject: [PATCH 3/4] chore(sln): nest test projects inside a solution folder --- src/InventoryManagementSystem.sln | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/InventoryManagementSystem.sln b/src/InventoryManagementSystem.sln index cffa557..878fbed 100644 --- a/src/InventoryManagementSystem.sln +++ b/src/InventoryManagementSystem.sln @@ -31,6 +31,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.Infrastructu EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InventoryAlert.E2ETests", "test\InventoryAlert.E2ETests\InventoryAlert.E2ETests.csproj", "{5E783740-3A81-4C1A-AB33-617CDED7E7AD}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{B9E83740-3A81-4C1A-AB33-617CDED7E7AE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -150,6 +152,13 @@ Global {5E783740-3A81-4C1A-AB33-617CDED7E7AD}.Release|x86.ActiveCfg = Release|Any CPU {5E783740-3A81-4C1A-AB33-617CDED7E7AD}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {9A5F9FC6-8F3C-42FF-A04E-F5C9527646DB} = {B9E83740-3A81-4C1A-AB33-617CDED7E7AE} + {FFE36D59-CD3A-4C4B-BFFA-E7C7A6955C06} = {B9E83740-3A81-4C1A-AB33-617CDED7E7AE} + {8AEACF55-3718-4F82-B731-305FD8ECAA1F} = {B9E83740-3A81-4C1A-AB33-617CDED7E7AE} + {51B44AE9-AC73-4B5D-8B25-672C921A704D} = {B9E83740-3A81-4C1A-AB33-617CDED7E7AE} + {5E783740-3A81-4C1A-AB33-617CDED7E7AD} = {B9E83740-3A81-4C1A-AB33-617CDED7E7AE} + EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection From 94c15388172f081285ff8a3344eb8bfbb84101e3 Mon Sep 17 00:00:00 2001 From: nhonvo Date: Wed, 27 May 2026 15:48:42 +0700 Subject: [PATCH 4/4] fix(csproj): restore missing ProjectReferences deleted in merge --- .../InventoryAlert.Infrastructure.csproj | 4 ++++ .../InventoryAlert.ArchitectureTests.csproj | 2 ++ .../InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj | 3 ++- .../InventoryAlert.IntegrationTests.csproj | 2 ++ .../InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj | 2 ++ 5 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj b/src/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj index 1c2e1b2..dc28223 100644 --- a/src/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj +++ b/src/InventoryAlert.Infrastructure/InventoryAlert.Infrastructure.csproj @@ -1,5 +1,9 @@ + + + + diff --git a/src/test/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj b/src/test/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj index e228a65..9ee8973 100644 --- a/src/test/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj +++ b/src/test/InventoryAlert.ArchitectureTests/InventoryAlert.ArchitectureTests.csproj @@ -21,6 +21,8 @@ + + diff --git a/src/test/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj b/src/test/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj index 620c3c7..e1a1317 100644 --- a/src/test/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj +++ b/src/test/InventoryAlert.E2ETests/InventoryAlert.E2ETests.csproj @@ -20,7 +20,8 @@ - + + diff --git a/src/test/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj b/src/test/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj index 5cbca16..47a2a68 100644 --- a/src/test/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj +++ b/src/test/InventoryAlert.IntegrationTests/InventoryAlert.IntegrationTests.csproj @@ -44,7 +44,9 @@ + + diff --git a/src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj b/src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj index a6dcba1..a0cfbc3 100644 --- a/src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj +++ b/src/test/InventoryAlert.UnitTests/InventoryAlert.UnitTests.csproj @@ -28,6 +28,8 @@ + +

`N>j36s=rBZ} zY@SWSr#7s5ZtpaFffnD_cR=~M|9!=?i2flmWE8|*@ONZD~@v{NFMrMj==S8-^m zGC!k1zj*&kz~++yq-y>l|HYoBzsjAeb(F2%7(Pq^&6&?t^<;U;d|J&!cPT)s1v~W#q?-3?;-Maa1^Fo zXq1|8tN6HOfT3rVzl=Cu89|g$>?H+BAkPCH0Tqb5Rx&xU|Fw+uOa|-9HcND>FiIm6 zDjzHi$~S}yg;^y;J@gORE3v0^WeJdT;^O0m`JBB<9x1ZINc7a$1C?bGYbab6hdU(S zPi93TGnIUm3{x5iFQPgaVZ14A8B=IFVJDA?SHGe`HI3JR8E|2G=8}k_+0c%lko0ka z+@kdW7X|k>6(Q)NVkBxsQH*b8w3nkgQFtx;2-rhFb_1?!&5NfV8qpP7r>uz@EK_QU z5fu^$I75?mW;v}Ifj)!iHWR=cZ(x8Gjg?P*_wu#k^QHNDD@#fkyIe*j>|oYQ;R6Fo z!UHI$Tv(0+Vet54Y3WA!3oVV@3i7vwD9mmti~CKX0p-c}j~a5a=^4t!LVyIlFJBD1 z^V64-_l=T#$kd&9tcT0RcYl>$Cd_+L8*n5&(;#+rXPy(85jlZs1GLd6u!ItV8L{x? zvGuu{_gPHYAC-Yvu4fpQgy2j2nm4|h+oyo z1*0Ova)BYC=_+JUle+@6h#p`YkZqQ6eqowc*9?wmuFoCazLfn5j=)xTxJ_v5QG)?E ziAE_Q47X!DN5II65abVcF8m-$`eYc-LaIf?{z0Z@I1ao4JQK4If}DdxY+i}Jn5)G^ zMH)3Z2rpr#p?VXdk13J%fW?GCj6o`qbim>+Cl%p2#TSl!qk6(s=hK9oQ-Jir{X;ne zULG3MxpFw8VBrswL07SMf!Dz}xK_OQd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