Commit Graph

41 Commits

Author SHA1 Message Date
Ho Ngoc Hai
c8a70f8d80 fix(order): include payment_method in order list API response
OrderSummaryDto and ListOrdersByShop Dapper query were missing the
payment_method column, causing the POS history tab to always show
"Chưa thanh toán" (Unpaid) even for completed/paid orders.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 03:25:00 +07:00
Ho Ngoc Hai
9f52c27f56 fix(pos-dashboard): show payment method names instead of order status
GetPosDashboardQuery payment breakdown SQL was grouping by
order_statuses.name (e.g. "Completed") instead of orders.payment_method
(e.g. "cash", "card", "qr", "transfer").

Fix: GROUP BY o.payment_method with COALESCE for empty values.
Frontend: apply MapPaymentMethodLabel() to translate method names
to Vietnamese (Tiền mặt, Thẻ, Mã QR, Chuyển khoản).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 17:08:50 +07:00
Ho Ngoc Hai
ee8f057d67 fix(order): complete order after POS payment instead of stopping at Processing
PayOrderCommandHandler was calling MarkAsPaid() + MarkAsProcessing()
but NOT MarkAsCompleted(), leaving orders stuck at status_id=4
(Processing) instead of 5 (Completed).

For POS direct sales (cash/card/qr/transfer), the full chain is now:
  Validated(2) → Paid(3) → Processing(4) → Completed(5)

All 4 payment methods tested and confirmed:
  - cash: Completed ✓
  - card: Completed ✓
  - qr: Completed ✓
  - transfer: Completed ✓

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 10:34:51 +07:00
Ho Ngoc Hai
a8edfd1597 fix(p2): Wave 3 — fix 4 P2 backend architecture issues (TEC-261)
BACK-I-01: Add CI steps to generate openapi.yaml for all 24 .NET services
- Add .config/dotnet-tools.json with swashbuckle.aspnetcore.cli 7.2.0
- Add scripts/ci/generate-openapi.sh reusable script
- Update all 24 service CI workflows with dotnet tool restore + swagger tofile + artifact upload

BACK-I-02: Add OpenTelemetry Metrics + Prometheus /metrics to _template_dot_net
- Add OTel packages (Extensions.Hosting, Instrumentation.AspNetCore, Runtime, Prometheus)
- Register AddOpenTelemetry().WithMetrics() with ASPNetCore + Runtime instrumentation
- Map MapPrometheusScrapingEndpoint("/metrics") in middleware pipeline

BACK-W-01: Remove IHttpContextAccessor from all 18 handler files in merchant-service-net
- Create MerchantBaseController abstract base with GetCurrentUserId() helper
- Add Guid UserId to 11 Commands and 7 Queries
- Remove IHttpContextAccessor injection from all handlers, use request.UserId instead
- Update 7 controllers to inherit MerchantBaseController and extract userId from JWT claims
- Remove AddHttpContextAccessor() registration from Program.cs

BACK-W-03: Add explicit commandTimeout:5 to all Dapper queries in order-service-net
- 14 files updated: QueryAsync, ExecuteScalarAsync, QueryFirstOrDefaultAsync all get commandTimeout: 5

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-23 10:09:45 +07:00
Ho Ngoc Hai
97b54ebd39 fix(security): fix 5 P1 backend issues — BACK-C-01/03/04, BACK-W-02
BACK-W-02: Replace string-interpolated SET LOCAL SQL with parameterized
set_config() calls in TenantMiddleware across 5 services (order, wallet,
inventory, catalog, fnb-engine). Eliminates SQL injection pattern;
set_config(key, $1, true) is local-to-transaction, same semantics as SET LOCAL.

BACK-C-01: Remove AllowAnyOrigin() from all 26 services. Switch to
WithOrigins() reading AllowedOrigins config array, with dev-only fallback
to localhost. In production, set AllowedOrigins=["https://goodgo.vn",
"https://admin.goodgo.vn"] via environment config.

BACK-C-03: Standardize OrdersController GET /orders/{id} 404 response
from {Message:...} to {success:false, error:{code,message}} per API contract.

BACK-C-04: Add complete ProblemDetails exception mappings to _template_dot_net:
ValidationException -> 400, DomainException -> 422, with TODO comments
for service-specific types (EntityNotFoundException -> 404, etc.).

BACK-C-02: wallet-service and booking-service already have full
IRequestManager idempotency implementation — no changes needed.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-23 09:48:22 +07:00
Ho Ngoc Hai
25f68781ad fix(security): fix 5 P0 security blockers — SEC-C-01 through SEC-C-05
SEC-C-01: Replace Neon PostgreSQL credentials (npg_Ssfy6HKO0cXI) with local
dev connection strings in all 19 appsettings.json files. Production credentials
must be injected via ConnectionStrings__DefaultConnection env var. Add
appsettings.Production.json and appsettings.Staging.json to .gitignore.

SEC-C-02: Add services/goodgo-mcp-server/.env to root .gitignore. Create
.env.example with safe placeholder values documenting required variables.

SEC-C-03: Wrap AddDeveloperSigningCredential() in env check — development only.
Non-development environments must provide X.509 certificate via
IdentityServer:SigningCertificatePath and IdentityServer:SigningCertificatePassword.

SEC-C-04: Remove 4 unauthenticated debug endpoints from StaffController:
GET debug/all, POST debug/seed, POST debug/update-userid, POST debug/update-merchant.
These endpoints allowed privilege escalation and data exfiltration without auth.

SEC-C-05: Removed endpoints containing SQL injection via string interpolation
(lines 307, 367 in StaffController). Also removed [AllowAnonymous] from
GET lookup endpoint — inherits class-level [Authorize].

BREAKING: debug/* endpoints are permanently removed. BFF lookup endpoint now
requires authentication.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-03-23 09:47:07 +07:00
Ho Ngoc Hai
f8606e0447 fix(P0): security hardening + critical bug fixes across 22 services
Wave 1 — 6 parallel agents fixing P0 issues from code audit:

Auth (18 services secured):
- Added JWT Bearer auth + [Authorize] to all unprotected controllers
- Webhook endpoints (Facebook/WhatsApp/Zalo/X) stay [AllowAnonymous]
- Health checks remain public for Docker/K8s probes
- Services: catalog, order, booking, fnb-engine, inventory, social,
  ads-manager, ads-serving, ads-billing, ads-tracking, ads-analytics,
  mkt-facebook, mkt-whatsapp, mkt-x, mkt-zalo, promotion

Template artifacts (4 services):
- mission-service: myservice_db → mission_service
- mkt-facebook: Dockerfile MyService.API → FacebookService.API
- mkt-whatsapp: MyServiceContext.cs → WhatsAppServiceContext.cs
- promotion: UserSecretsId fixed

Critical handler bugs (7 fixes):
- ads-tracking: TrackPixelEventHandler now persists to DB
- ads-tracking: RecordConversion endpoint exposed via controller
- booking: UpdateResource now applies Name + Capacity changes
- ads-manager: ListPendingAds uses correct enum (pending_review)
- mining: BanMiner calls Ban() not Suspend()
- mining: ResetMinerStreak now actually resets streak
- mkt-x: 8 missing repository DI registrations added

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 20:18:09 +07:00
Ho Ngoc Hai
f3779c4ebe docs: add SERVICE_DOCS.md for all 24 microservices from per-service code audit
Each SERVICE_DOCS.md documents: Overview, API Endpoints, Commands, Queries,
Domain Model, Database Schema, Integration Events, Dependencies, Configuration.
Generated by 23 parallel audit agents reading actual source code.

Key corrections from audit:
- inventory-service: 12 commands/6 queries (was listed as scaffold)
- promotion-service: 12 commands/10 queries (was listed as 0)
- mission-service: 4 commands/7 queries (was listed as 0)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 17:54:53 +07:00
Ho Ngoc Hai
dc1ea7c0d2 feat: Phase 2 W7-8 production readiness — QR menu, analytics, E2E tests, observability
- Public QR menu: BFF proxy endpoints (no auth), PosDataService public methods
- Revenue analytics + staff performance: Dapper queries, validators, BFF proxy
- Playwright E2E tests: 8 spec files covering auth, admin, 5 POS verticals, reports
- Observability: Grafana dashboard (HTTP metrics, infra, business), Prometheus alert rules
- Fixes: validator frozen-date bug (Must vs LessThanOrEqualTo), PublicMenuController logging + CancellationToken

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 19:51:37 +07:00
Ho Ngoc Hai
0d03feeffd feat: Phase 2 multi-vertical expansion — Spa appointments, Retail POS, Cafe loyalty
Spa/Beauty (booking-service) — Therapist + Appointment scheduling:
- Therapist aggregate: specialties (text[]), workingHours (jsonb), CRUD
- Appointment: notes field, Pending initial status, MarkNoShow() behavior
- TherapistsController (4 endpoints), 9 FluentValidation validators
- EF config: PostgreSQL native text[] + jsonb column types

Retail POS (catalog + inventory + order) — Barcode, stock, returns:
- Product: barcode/SKU fields, GetProductByBarcodeQuery (lookup endpoint)
- Inventory: bulk stock check, low stock alert threshold (SetReorderLevel)
- Order: return/exchange flow with ProcessReturn(), Returned status (id=8)
- CreateReturnCommand, CreateExchangeCommand (same UnitOfWork)
- 2 domain events: OrderReturnedDomainEvent, OrderExchangedDomainEvent
- 6 new API endpoints across 3 services

Cafe (membership + fnb-engine) — Loyalty stamps + barista queue:
- StampCard aggregate: AddStamp(), ClaimReward(), Reset(), 4 domain events
- Auto-create card on first stamp (friction-free UX)
- StampCardsController (6 endpoints), 4 commands, 2 queries
- BaristaQueueItem: 5-status workflow (Queued→Preparing→Ready→Delivered)
- BaristaController (6 endpoints), 5 commands, 2 queries
- Tenant isolation (shop-level) on both features

ROADMAP: Phase 1 closed out, Phase 2 vertical tasks IN-PROGRESS

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 16:45:43 +07:00
Ho Ngoc Hai
a7a753bf38 feat: EOD reports, security audit (rate limiting + 44 validators), and 30 critical path tests
EOD Reports & Daily Close (order-service + Blazor UI):
- GetEodReportQuery: Dapper query for revenue, orders, payment breakdown, top items, hourly chart
- CloseDayCommand: check pending orders, generate final report
- EodReport.razor: 6 KPI cards, donut/bar charts, top 10 table, close-day dialog
- FluentValidation for both query and command
- BFF proxy endpoints for reports

Security Audit — Rate Limiting:
- Tighten auth-ratelimit from 100 to 10 req/min (brute force protection)
- Add payment-ratelimit (30/min), api-ratelimit (100/min), hub-ratelimit (500/min)
- Apply rate limits to ALL Traefik routers (previously many had none)

Security Audit — Input Sanitization (44 missing validators created):
- iam-service: 14 validators (auth, user, role commands)
- merchant-service: 11 validators (admin, attendance commands)
- wallet-service: 7 validators (wallet, points commands)
- fnb-engine: 7 validators (session, table, ticket, reservation)
- catalog-service: 6 validators (product, category CRUD)
- storage-service: 6 validators (upload, share, quota)
- order-service: 2 validators (complete order/payment)

Critical Path Unit Tests (30 new tests):
- inventory-service: 12 tests (deduction, partial stock, idempotency)
- wallet-service: 14 tests (create payment, process callback, domain events)
- fnb-engine: 8 tests (kitchen-served event handler, inventory client integration)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 16:33:39 +07:00
Ho Ngoc Hai
653322b26c fix: resolve 12 critical/high issues from code review across backend, frontend, and infra
Backend (7 fixes):
- wallet-service: remove conflicting EF Ignore() calls for mapped backing fields
- fnb-engine: remove KitchenTicket short constructor that set productId=orderItemId
- fnb-engine: replace fire-and-forget Task.Run with direct await for inventory deduction
- TenantMiddleware: implement PostgreSQL RLS SET LOCAL in 4 services (wallet, fnb, inventory, catalog)
- order-service: fix SQL injection pattern in TenantMiddleware with Guid.ToString("D")
- order-service: add ValidateShopAccess() authorization check in SignalR PosHub
- 4 services: register IDbConnection (NpgsqlConnection) in DI for RLS middleware

Frontend (3 fixes):
- PosDataService: return Success=false (not true) when PayOrder response parsing fails
- QrPayment: add _disposed guard to prevent timer race condition after component disposal
- BFF OrderController: add [Authorize] attribute to require JWT for all endpoints

Infrastructure (3 fixes):
- docker-compose: upgrade PostgreSQL 15-alpine to 16-alpine per project spec
- init-databases.sh: add 4 missing marketing service databases (mkt_*)
- Traefik routes: add wallet, catalog, booking routers and /api/v1/stock path

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 16:22:08 +07:00
Ho Ngoc Hai
1d12a7980b feat: add order lifecycle integration tests (29 tests) and staging K8s deployment manifests
Testing (P0-7):
- 29 functional tests for order-service API (create/pay/complete/cancel lifecycle)
- CustomWebApplicationFactory with InMemory DB, mocked wallet/SignalR/tenant
- TestAuthHandler for JWT auth in tests
- Full lifecycle tests: cash flow and online payment flow end-to-end

Staging Deployment (P0-8):
- K8s manifests for 8 MVP services + Redis + POS web (namespace, configmap, secrets)
- Traefik Ingress with path-based routing and TLS via cert-manager
- HPA auto-scaling (2-4 replicas, CPU/memory thresholds)
- deploy-staging.sh script with --dry-run and --service flags
- CI/CD: deploy-staging.yml and docker-build.yml with matrix strategy
- Consistent patterns: port 8080, 3 health probes, RollingUpdate

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 13:56:03 +07:00
Ho Ngoc Hai
6061164873 feat: add multi-tenant row-level security across 5 services and 96 FnB engine unit tests
Security (P0-5):
- Implement ITenantProvider + HttpContextTenantProvider per service (order, fnb, inventory, catalog, wallet)
- Add EF Core global query filters for tenant isolation (shop_id/user_id based)
- Add TenantMiddleware setting PostgreSQL session variables for RLS
- Create PostgreSQL RLS policies script (scripts/db/rls-policies.sql)
- Adapter pattern bridges API-layer to Infrastructure-layer (Clean Architecture)
- Bypass mechanisms for admin roles, service-to-service calls, and migrations

Testing (P1-12):
- Add 96 unit tests for fnb-engine (up from 3)
- 57 domain entity tests: Table(18), KitchenTicket(12), Session(8), Reservation(13), Recipe(6)
- 39 command handler tests: CRUD operations, status transitions, validation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 13:40:34 +07:00
Ho Ngoc Hai
8af86e9e89 feat: implement Phase 1 payment gateway, real-time SignalR, kitchen-inventory deduction, and order payment flow
- wallet-service: IPaymentGateway abstraction + VN Pay implementation (HMAC-SHA512, sandbox), Payment aggregate root, PaymentsController with create/callback/query endpoints
- order-service: PosHub SignalR hub with Redis backplane + MessagePack, strongly-typed clients, 3 group types (shop/kds/pos), integrated into Create/Pay/Complete/Cancel order handlers
- fnb-engine + inventory-service: Kitchen→Inventory auto-deduction via domain events, HTTP with Polly retry + circuit breaker, idempotency check, graceful degradation on insufficient stock
- order-service: Enhanced PayOrderCommand with 3 flows (cash/card/online), PaymentPending status, WalletServiceClient, CompleteOrderPaymentCommand for gateway callbacks
- POS frontend: Cash/Card/QR payment components wired to real backend, BFF proxy updated
- infra: Traefik routes for fnb-engine, inventory-service, and SignalR WebSocket hub
- ROADMAP.md: Updated with Phase 1 progress tracking

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 13:28:46 +07:00
Ho Ngoc Hai
fd75da34dc feat: enhance inventory management with new item types, stocktake, wastage, and recipe-based deductions 2026-03-05 22:28:45 +07:00
Ho Ngoc Hai
cfcdbd069d feat(pos): implement order payment flow and update order aggregate status handling. 2026-03-05 08:05:19 +07:00
Ho Ngoc Hai
0901e91673 feat(pos): implement table-based ordering, kitchen ticket workflow, and table floor plan management 2026-03-05 07:53:00 +07:00
Ho Ngoc Hai
802c03995a feat(order-processing): execute order item strategies during order creation and add kitchen ticket API with session management. 2026-03-05 06:19:18 +07:00
Ho Ngoc Hai
629fed8a55 commit 2026-03-05 01:39:40 +07:00
Ho Ngoc Hai
051261accd feat: implement recipe management, inventory operations, voucher integration, and order discounts 2026-03-04 20:05:38 +07:00
Ho Ngoc Hai
7baba14fad refactor(web-client-tpos, order-service): improve API deserialization, update DTO types for Dapper compatibility, and refine API proxying for staff schedules and order cancellations. 2026-03-04 12:53:43 +07:00
Ho Ngoc Hai
2d74f53f0d refactor: update DTO numeric types, refactor EF Core entity configurations to use HasField, and enable JsonDocument change tracking. 2026-03-04 11:44:43 +07:00
Ho Ngoc Hai
89bd8232a8 feat: Implement Blazor lifecycle improvements, enhance navigation with browser history, and update EF Core entity configurations for backing fields 2026-03-04 11:35:41 +07:00
Ho Ngoc Hai
9b44e88a6a feat(order-service): add dashboard and reporting endpoints
- GET /api/v1/orders/dashboard — POS dashboard stats (revenue, orders,
  items sold, popular items, payment breakdown, hourly revenue, recent orders)
- GET /api/v1/reports/revenue — Revenue report grouped by daily/weekly/monthly
- GET /api/v1/reports/top-products — Top selling products by quantity

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 10:36:09 +07:00
Ho Ngoc Hai
751f90c365 feat: Log EF Core migration errors instead of crashing the application at startup across all services. 2026-02-28 01:03:43 +07:00
Ho Ngoc Hai
be86e48de6 feat: automatically apply EF Core database migrations on service startup across all services 2026-02-28 00:51:35 +07:00
Ho Ngoc Hai
f521cc0a91 chore: Remove the web-client application, add a local database initialization script, and update service Dockerfiles. 2026-02-28 00:41:17 +07:00
Cursor Agent
4751929a3e fix: switch JWT Bearer auth from symmetric key to OIDC discovery in 5 microservices
Replace manual SymmetricSecurityKey validation with Authority-based OIDC
discovery so tokens are validated against RSA keys published by the IAM
IdentityServer's discovery endpoint.

Services updated:
- CatalogService.API
- OrderService.API
- InventoryService.API
- FnbEngine.API
- BookingService.API

Co-authored-by: Velik <hongochai10@users.noreply.github.com>
2026-02-26 22:51:57 +00:00
Cursor Agent
c789f964a8 Add JWT Bearer authentication registration to 5 microservice Program.cs files
Add AddAuthentication(JwtBearerDefaults.AuthenticationScheme) and
AddJwtBearer() service registration before CORS configuration in:
- CatalogService.API
- OrderService.API
- InventoryService.API
- FnbEngine.API
- BookingService.API

Also add Microsoft.AspNetCore.Authentication.JwtBearer v10.0.1 NuGet
package reference to each service's .csproj file.

This fixes the runtime error caused by UseAuthentication() being called
without a registered authentication scheme.

Co-authored-by: Velik <hongochai10@users.noreply.github.com>
2026-02-26 22:51:57 +00:00
Cursor Agent
2fcf73b33f Add UseAuthentication and UseAuthorization middleware after UseRouting in 5 microservices
Added app.UseAuthentication() and app.UseAuthorization() after
app.UseRouting() in the middleware pipeline for:
- CatalogService.API
- OrderService.API
- InventoryService.API
- FnbEngine.API
- BookingService.API

Co-authored-by: Velik <hongochai10@users.noreply.github.com>
2026-02-26 22:51:57 +00:00
Cursor Agent
0f828dafb0 test: replace sample tests with service-specific order and ads suites
Co-authored-by: Velik <hongochai10@users.noreply.github.com>
2026-02-23 12:47:21 +00:00
Cursor Agent
9e5b1018b4 feat: implement admin order stats export and mining overview
Co-authored-by: Velik <hongochai10@users.noreply.github.com>
2026-02-23 12:42:55 +00:00
Ho Ngoc Hai
593457a9e3 feat: Implement kitchen ticket and session management in FnbEngine, add booking-related controllers and a generic API response in BookingService, and update Dockerfiles. 2026-01-18 02:56:43 +07:00
Ho Ngoc Hai
83a8db2942 feat: Implement new API endpoints, application logic, and domain repositories across FnbEngine, BookingService, and OrderService, alongside minor infrastructure updates. 2026-01-18 02:51:10 +07:00
Ho Ngoc Hai
f198409e3a refactor: Replace generic 'Sample' aggregate with specific domain models in Ads Tracking and Ads Analytics services, updating infrastructure. 2026-01-18 00:58:51 +07:00
Ho Ngoc Hai
2866aad345 feat: Replace generic sample implementations with concrete Ads Billing and Order service domain logic. 2026-01-18 00:44:53 +07:00
Ho Ngoc Hai
5626c3495b refactor: Update Dockerfiles to use service-specific project names instead of generic 'MyService'. 2026-01-18 00:23:39 +07:00
Ho Ngoc Hai
811ddd1e19 feat: Add functional tests for OrderService and update InventoryService command and idempotency logic. 2026-01-18 00:19:46 +07:00
Ho Ngoc Hai
844e40f818 config: Update local application ports and switch database connection strings to Neon.tech for multiple services. 2026-01-17 23:28:35 +07:00
Ho Ngoc Hai
19c0acfe0f feat: Add new unit tests, domain exceptions, documentation, and various build artifacts across multiple services. 2026-01-17 23:04:15 +07:00