6 Commits

Author SHA1 Message Date
masoodafar-web b42d9e141d feat: Implement file management and authorization features
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 3m9s
- Add RequiresPermissionAttribute for gRPC method access control.
- Create IFileManagementService interface for file upload and management.
- Implement AddProductImageCommand and handler for adding product images.
- Implement CreateNewProductsCommand and handler for creating new products with image uploads.
- Implement DeleteProductsCommand and handler for deleting products and their associations.
- Implement RemoveProductImageCommand and handler for removing product images from galleries.
- Implement UpdateProductsCommand and handler for updating product details and images.
- Create GetProductGalleryQuery and handler for retrieving product galleries.
- Implement PermissionService for role-based access control using JWT claims.
- Implement FileManagementService for handling file uploads and image optimization.
- Define gRPC service and messages for file management in fms.proto.
- Add FluentValidation for request validation in various commands.
- Create PermissionInterceptor for enforcing permissions on gRPC methods.
2026-02-10 22:04:54 +03:30
masoodafar-web f64b6be7da feat: Implement GetMyWeeklyBalances query and handler, enhance ClubMembership service with JWT userId handling 2026-02-08 00:24:59 +03:30
masoodafar-web 9185aa227d feat: Add discount balance and change value to wallet change log
- Added CurrentDiscountBalance and ChangeDiscountValue properties to GetCustomerWalletChangeLogResponseDto.
- Updated userwallet.proto to include current_discount_balance and change_discount_value fields.
- Enhanced CommissionProfile mapping to support GetMyCommissionPayouts requests and responses.
- Implemented GetMyCommissionPayouts query and handler to retrieve user commission payouts.
- Added validation for GetMyCommissionPayouts query.
- Updated UserOrderService to handle user orders, including VAT calculations and wallet transactions.
- Enhanced UserWalletService to include new properties in wallet change log responses.
2026-02-07 22:03:49 +03:30
masoodafar-web b2d676b555 feat: Implement customer profile and referral queries
- Add GetCustomerProfileResponseDto for retrieving customer profile information.
- Create GetCustomerReferralsQuery and GetCustomerReferralsQueryHandler to fetch customer referrals with pagination and filtering options.
- Introduce GetCustomerReferralsResponseDto to structure the response for customer referrals.
- Implement GetCustomerSettingsQuery and GetCustomerSettingsQueryHandler to retrieve user settings.
- Add GetCustomerOrder and GetCustomerOrderQueryHandler for fetching specific customer orders.
- Create GetCustomerOrderHistoryQuery and GetCustomerOrderHistoryQueryHandler to retrieve order history with filtering options.
- Implement GetCustomerOrdersQuery and GetCustomerOrdersQueryHandler for fetching multiple customer orders with filters.
- Add GetCustomerWalletChangeLogQuery and GetCustomerWalletChangeLogQueryHandler for retrieving wallet change logs.
- Implement GetCustomerWithdrawalSettingsQuery and GetCustomerWithdrawalSettingsQueryHandler for fetching withdrawal settings.
- Create GetCustomerWithdrawalsQuery and GetCustomerWithdrawalsQueryHandler to retrieve customer withdrawal requests.
2026-02-05 23:01:50 +03:30
masoodafar-web b41342dcad feat: implement JWT token generation in VerifyOtpTokenCommandHandler and update related configurations 2026-02-03 00:02:04 +03:30
masoodafar-web c3eeb16856 refactor: rename response properties in PackageService for consistency 2026-02-01 22:25:25 +03:30
163 changed files with 7890 additions and 1857 deletions
-179
View File
@@ -1,179 +0,0 @@
# FrontOffice.BFF to CMS Migration Progress
## Migration Overview
مهاجرت سرویس‌های FrontOffice.BFF به CMS Microservice با معماری Clean Architecture و gRPC.
## ✅ Completed Services
### 1. Categories Service
- **Status**: ✅ Complete
- **Proto Definition**: `categories.proto`
- **Service Implementation**: `CategoryService.cs`
- **Methods Migrated**:
- Admin Methods:
- `AddNewCategory` - افزودن دسته‌بندی جدید
- `UpdateCategory` - بروزرسانی دسته‌بندی
- `DeleteCategory` - حذف دسته‌بندی
- `GetCategory` - دریافت یک دسته‌بندی
- `GetAllCategoriesByFilter` - دریافت لیست دسته‌بندی‌ها
- Customer Methods:
- `GetActiveCategoriesForCustomer` - دریافت دسته‌بندی‌های فعال برای مشتری
### 2. City Service
- **Status**: ✅ Complete
- **Proto Definition**: `city.proto`
- **Service Implementation**: `CityService.cs`
- **Methods Migrated**:
- Admin Methods:
- `AddNewCity` - افزودن شهر جدید
- `UpdateCity` - بروزرسانی شهر
- `DeleteCity` - حذف شهر
- `GetCity` - دریافت یک شهر
- `GetAllCitiesByFilter` - دریافت لیست شهرها
- Customer Methods:
- `GetActiveCitiesForCustomer` - دریافت شهرهای فعال برای مشتری
### 3. UserCarts Service
- **Status**: ✅ Complete
- **Proto Definition**: `usercarts.proto`
- **Service Implementation**: `UserCartsService.cs`
- **Methods Migrated**:
- Admin Methods:
- `AddNewUserCart` - افزودن سبد خرید جدید
- `UpdateUserCart` - بروزرسانی سبد خرید
- `DeleteUserCart` - حذف سبد خرید
- `GetUserCart` - دریافت سبد خرید (Admin)
- `GetAllUserCartsByFilter` - دریافت لیست سبدهای خرید
- Customer Methods:
- `AddNewUserCartForCustomer` - افزودن محصول به سبد (Customer)
- `UpdateUserCartForCustomer` - بروزرسانی تعداد محصول در سبد
- `RemoveUserCartForCustomer` - حذف محصول از سبد
- `GetCustomerCart` - دریافت سبد خرید مشتری
## 🛠️ Technical Implementation Details
### gRPC HTTP Annotations
تمام سرویس‌ها با HTTP annotations تعریف شده‌اند:
- Admin endpoints: `/ServiceName` pattern
- Customer endpoints: `/Customer/Action` pattern
### Clean Architecture Structure
```
CMSMicroservice.Domain/ # Core business entities
CMSMicroservice.Application/ # Business logic & CQRS
CMSMicroservice.Infrastructure/ # Data access & external services
CMSMicroservice.WebApi/ # gRPC services & controllers
CMSMicroservice.Protobuf/ # Protocol buffer definitions
```
### Swagger Integration
- Multiple Swagger documents: cms, admin, customer, unified
- gRPC HTTP transcoding enabled
- Custom CSS styling applied
- Conflict resolution implemented
## 🔧 Issues Resolved
### 1. Swagger Conflict Resolution
**Problem**:
```
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException:
Conflicting method/path combination "GET GetUserCart"
```
**Root Cause**:
- دو method با operation ID یکسان: `GetUserCart` و `GetUserCartForCustomer`
- Swagger از method name برای operation ID استفاده می‌کند
**Solutions Attempted**:
1.`CustomOperationIds` - ineffective
2.`ResolveConflictingActions` - incomplete resolution
3.**Method Renaming** - successful
**Final Solution**:
```protobuf
// Before (conflicting):
rpc GetUserCartForCustomer(GetUserCartForCustomerRequest) returns (GetUserCartForCustomerResponse)
// After (resolved):
rpc GetCustomerCart(GetUserCartForCustomerRequest) returns (GetUserCartForCustomerResponse)
```
### 2. Application Layer Dependencies
**Problem**: Build errors در Application layer
**Solution**: پاکسازی dependencies و rebuild پروژه
## 📊 Migration Status Summary
| Service | Proto ✅ | Implementation ✅ | Build ✅ | Swagger ✅ |
|---------|----------|-------------------|----------|------------|
| Categories | ✅ | ✅ | ✅ | ✅ |
| City | ✅ | ✅ | ✅ | ✅ |
| UserCarts | ✅ | ✅ | ✅ | ✅ |
## 🎯 Next Steps
1. **Service Integration Testing** - تست عملکرد سرویس‌های migrate شده
2. **Business Logic Implementation** - پیاده‌سازی منطق کسب‌وکار واقعی
3. **Database Integration** - اتصال به لایه دیتا
4. **Continue Migration** - ادامه migration سایر سرویس‌ها
## 🏗️ Technical Architecture
### gRPC Service Pattern
```csharp
public class ServiceName : ServiceContract.ServiceContractBase
{
private readonly IDispatchRequestToCQRS _dispatcher;
// Customer Methods Section
#region Customer Methods
public override async Task<Response> CustomerMethod(Request request, ServerCallContext context)
{
// Implementation
}
#endregion
// Admin Methods Section
#region Admin Methods
public override async Task<Response> AdminMethod(Request request, ServerCallContext context)
{
// Implementation
}
#endregion
}
```
### Proto File Structure
```protobuf
syntax = "proto3";
import "google/api/annotations.proto";
service ServiceContract {
// ============= Admin Methods =============
rpc AdminMethod(Request) returns (Response) {
option (google.api.http) = {
post: "/AdminEndpoint"
body: "*"
};
};
// ============= Customer Methods =============
rpc CustomerMethod(Request) returns (Response) {
option (google.api.http) = {
get: "/Customer/Endpoint"
};
};
}
```
## 📈 Performance & Quality
- ✅ All services compile successfully
- ✅ Swagger documentation accessible
- ✅ gRPC HTTP transcoding working
- ✅ Clean separation of Admin/Customer concerns
- ✅ Consistent naming conventions applied
---
**Last Updated**: January 30, 2026
**Migration Phase**: Foundation Services Complete
**Next Milestone**: Business Logic Implementation
-190
View File
@@ -1,190 +0,0 @@
# وضعیت Refactoring سیستم انبارداری (Inventory)
**تاریخ:** ۳ ژانویه ۲۰۲۶
**وضعیت:** ✅ تکمیل شده - Build موفق
---
## 📊 وضعیت Build
| پروژه | وضعیت |
|-------|--------|
| CMSMicroservice.Domain | ✅ OK |
| CMSMicroservice.Application | ✅ OK |
| CMSMicroservice.Infrastructure | ✅ OK |
| CMSMicroservice.WebApi | ✅ OK |
---
## ✅ کارهای انجام شده
### 1. حذف Repository Pattern
فایل‌های حذف شده:
- `Application/Common/Interfaces/Repositories/IInventoryItemRepository.cs`
- `Application/Common/Interfaces/Repositories/IStockMovementRepository.cs`
- `Application/Common/Interfaces/Repositories/IWarehouseRepository.cs`
- `Infrastructure/Persistence/Repositories/InventoryItemRepository.cs`
- `Infrastructure/Persistence/Repositories/StockMovementRepository.cs`
- `Infrastructure/Persistence/Repositories/WarehouseRepository.cs`
### 2. حذف Features قدیمی
فولدر حذف شده:
- `Application/Features/` (کل فولدر)
### 3. ایجاد ساختار CQ جدید
#### WarehouseCQ/
```
WarehouseCQ/
├── Commands/
│ ├── CreateWarehouse/
│ ├── UpdateWarehouse/
│ ├── DeleteWarehouse/
│ └── SetDefaultWarehouse/
└── Queries/
├── GetWarehouse/
├── GetAllWarehouses/
└── SearchWarehouses/
```
#### InventoryItemCQ/
```
InventoryItemCQ/
├── Commands/
│ ├── CreateInventoryItem/
│ ├── UpdateInventoryItem/
│ ├── DeleteInventoryItem/
│ ├── UpdateInventoryQuantity/
│ ├── ReserveInventory/
│ ├── ReleaseReservedInventory/
│ ├── ReduceInventory/
│ └── IncreaseInventory/
└── Queries/
├── GetInventoryItem/
├── GetInventoryByProduct/
├── GetAllInventoryItems/
└── GetLowStockItems/
```
#### StockMovementCQ/
```
StockMovementCQ/
├── Commands/
│ └── CreateStockMovement/
└── Queries/
├── GetStockMovements/
└── GetStockMovementsByInventoryItem/
```
### 4. Fix شدن InventoryProfile.cs
- اصلاح enum names: `ProtoProductType.Unspecified` بجای `ProductTypeUnspecified`
- حذف `new Int64Value` - Proto مستقیم `long?` میگیره
- اصلاح expression tree برای `?.` operator
### 5. ساده‌سازی InventoryService.cs
- متدهای اصلی (Warehouse, Query ها) کامل پیاده‌سازی شدن
- متدهای پیچیده که نیاز به lookup دارن فعلاً TODO هستن
---
## ⚠️ متدهای TODO در InventoryService
این متدها نیاز به پیاده‌سازی دارن (وقتی لازم شد):
| متد | دلیل TODO |
|-----|-----------|
| `AddStock` | نیاز به lookup با ProductId/ProductType |
| `AdjustStock` | نیاز به lookup با ProductId/ProductType |
| `ReserveStock` | نیاز به lookup با ProductId/ProductType |
| `ReleaseReservation` | نیاز به lookup با ProductId/ProductType |
| `ConfirmSale` | نیاز به lookup با ProductId/ProductType |
| `ProcessReturn` | نیاز به lookup با ProductId/ProductType |
| `RecordLoss` | نیاز به lookup با ProductId/ProductType |
| `BulkAddStock` | نیاز به loop و lookup |
| `BulkAdjustStock` | نیاز به loop و lookup |
| `GetInventorySummary` | نیاز به Query جدید |
| `GetStockValueReport` | نیاز به Query جدید |
---
## 🎯 درس‌های آموخته شده
1. **همیشه اول Proto رو بررسی کن** - Proto مرجع اصلی API هست
2. **ساختار موجود رو تحلیل کن** - قبل از ساختن فایل جدید، نمونه‌های موجود رو ببین
3. **Mapping از Proto به Command** - نه برعکس!
4. **IApplicationDbContext** - الگوی استاندارد این پروژه برای دسترسی به DB
5. **بدون Repository** - این پروژه از Repository pattern استفاده نمیکنه
6. **Proto enum names** - نام‌ها در C# متفاوت هستن (مثلاً `Unspecified` بجای `PRODUCT_TYPE_UNSPECIFIED`)
7. **Int64Value در Proto** - در C# به `long?` تبدیل میشه، نیازی به `new Int64Value` نیست
---
## 🔄 همگام‌سازی BFF با CMS (۳ ژانویه ۲۰۲۶)
### تغییرات Proto
BackOffice.BFF.Inventory.Protobuf با CMS همگام شد:
| آیتم | قبل | بعد |
|------|-----|-----|
| ProductType enum | `REGULAR`, `DISCOUNT` | `REGULAR_PRODUCT`, `DISCOUNT_PRODUCT` |
| StockMovementType | Sequential (0-9) | Grouped (10, 20, 30, 40, 50) |
| Pagination | `page_index` | `page` |
| Search | `search_term` | `search` |
| Product name | `product_name` | `product_title` |
### فایل‌های آپدیت شده در BFF
**Commands:**
- `AddStock` - حذف Success, Message از Response
- `AdjustStock` - Note→Reason, +ReferenceNumber
- `RecordLoss` - Note→Reason, +ReferenceNumber
- `UpdateInventorySettings` - InventoryItemId→Id
**Queries:**
- `GetAllInventoryItems` - PageIndex→Page, SearchTerm→Search, +ProductPrice
- `GetStockMovements` - PageIndex→Page, +ProductTitle, +Created
- `GetLowStockItems` - حذف Count، استفاده از Page/PageSize
- `GetAllWarehouses` - ActiveOnly→IsActive, +Created, +LastModified
**Mappings:**
- `InventoryProfile.cs` - بازنویسی کامل برای فیلدهای جدید
### وضعیت Build BFF
```
Build succeeded.
0 Warning(s)
0 Error(s)
```
---
## 📊 پوشش API - مقایسه CMS و BFF
| عملیات | CMS | BFF | یادداشت |
|--------|-----|-----|---------|
| GetAllInventoryItems | ✅ | ✅ | همگام |
| GetInventoryItem | ✅ | ✅ | همگام |
| GetLowStockItems | ✅ | ✅ | همگام |
| GetStockMovements | ✅ | ✅ | همگام |
| GetAllWarehouses | ✅ | ✅ | همگام |
| AddStock | ✅ | ✅ | همگام |
| AdjustStock | ✅ | ✅ | همگام |
| RecordLoss | ✅ | ✅ | همگام |
| CreateWarehouse | ✅ | ✅ | همگام |
| UpdateWarehouse | ✅ | ❌ | نیاز به پیاده‌سازی |
| UpdateInventorySettings | ✅ | ✅ | همگام |
| GetInventorySummary | TODO | ❌ | اولویت بالا |
| GetStockValueReport | TODO | ❌ | اولویت بالا |
| ProcessReturn | TODO | ❌ | اولویت متوسط |
---
## 📝 نتیجه‌گیری
**Refactoring با موفقیت تکمیل شد!**
- Application layer با ساختار `*CQ/Commands/[Action]/` سازگار شد
- Repository pattern کاملاً حذف شد
- WebApi layer با Proto سازگار شد
- Build همه پروژه‌ها موفق هست
- **BFF کاملاً با CMS همگام شد (۳ ژانویه ۲۰۲۶)**
+1
View File
@@ -0,0 +1 @@
Docs moved to /totalDoc — see totalDoc/INDEX.md
-490
View File
@@ -1,490 +0,0 @@
# Club Feature Management Services - Implementation Guide
## Overview
Admin services for managing user club features (enable/disable features per user).
## Created Files
### 1. CQRS Layer (Application)
#### Query: GetUserClubFeatures
**Location:** `/CMS/src/CMSMicroservice.Application/ClubFeatureCQ/Queries/GetUserClubFeatures/`
**Files:**
- `GetUserClubFeaturesQuery.cs` - Query definition
- `GetUserClubFeaturesQueryHandler.cs` - Query handler
- `UserClubFeatureDto.cs` - Response DTO
**Purpose:** Get list of all club features for a specific user with their active status.
**Input:**
```csharp
public record GetUserClubFeaturesQuery : IRequest<List<UserClubFeatureDto>>
{
public long UserId { get; init; }
}
```
**Output:**
```csharp
public class UserClubFeatureDto
{
public long Id { get; set; }
public long UserId { get; set; }
public long ClubMembershipId { get; set; }
public long ClubFeatureId { get; set; }
public string FeatureTitle { get; set; }
public string? FeatureDescription { get; set; }
public bool IsActive { get; set; }
public DateTime GrantedAt { get; set; }
public string? Notes { get; set; }
}
```
**Logic:**
- Joins `UserClubFeatures` with `ClubFeature` table
- Filters by `UserId` and `!IsDeleted`
- Returns list of features with their active status
---
#### Command: ToggleUserClubFeature
**Location:** `/CMS/src/CMSMicroservice.Application/ClubFeatureCQ/Commands/ToggleUserClubFeature/`
**Files:**
- `ToggleUserClubFeatureCommand.cs` - Command definition
- `ToggleUserClubFeatureCommandHandler.cs` - Command handler
- `ToggleUserClubFeatureResponse.cs` - Response DTO
**Purpose:** Enable or disable a specific club feature for a user.
**Input:**
```csharp
public record ToggleUserClubFeatureCommand : IRequest<ToggleUserClubFeatureResponse>
{
public long UserId { get; init; }
public long ClubFeatureId { get; init; }
public bool IsActive { get; init; }
}
```
**Output:**
```csharp
public class ToggleUserClubFeatureResponse
{
public bool Success { get; set; }
public string Message { get; set; }
public long? UserClubFeatureId { get; set; }
public bool? IsActive { get; set; }
}
```
**Validations:**
1. ✅ User exists and not deleted
2. ✅ Club feature exists and not deleted
3. ✅ User has this feature assigned (exists in UserClubFeatures)
**Logic:**
- Find `UserClubFeature` record by `UserId` + `ClubFeatureId`
- Update `IsActive` field
- Set `LastModified` timestamp
- Save changes
**Error Messages:**
- "کاربر یافت نشد" - User not found
- "ویژگی باشگاه یافت نشد" - Club feature not found
- "این ویژگی برای کاربر یافت نشد" - User doesn't have this feature
**Success Messages:**
- "ویژگی با موفقیت فعال شد" - Feature activated successfully
- "ویژگی با موفقیت غیرفعال شد" - Feature deactivated successfully
---
### 2. gRPC Layer (Protobuf + WebApi)
#### Proto Definition
**File:** `/CMS/src/CMSMicroservice.Protobuf/Protos/clubmembership.proto`
**Added RPC Methods:**
```protobuf
rpc GetUserClubFeatures(GetUserClubFeaturesRequest) returns (GetUserClubFeaturesResponse){
option (google.api.http) = {
get: "/ClubFeature/GetUserFeatures"
};
};
rpc ToggleUserClubFeature(ToggleUserClubFeatureRequest) returns (ToggleUserClubFeatureResponse){
option (google.api.http) = {
post: "/ClubFeature/ToggleFeature"
body: "*"
};
};
```
**Message Definitions:**
```protobuf
message GetUserClubFeaturesRequest {
int64 user_id = 1;
}
message GetUserClubFeaturesResponse {
repeated UserClubFeatureModel features = 1;
}
message UserClubFeatureModel {
int64 id = 1;
int64 user_id = 2;
int64 club_membership_id = 3;
int64 club_feature_id = 4;
string feature_title = 5;
string feature_description = 6;
bool is_active = 7;
google.protobuf.Timestamp granted_at = 8;
string notes = 9;
}
message ToggleUserClubFeatureRequest {
int64 user_id = 1;
int64 club_feature_id = 2;
bool is_active = 3;
}
message ToggleUserClubFeatureResponse {
bool success = 1;
string message = 2;
google.protobuf.Int64Value user_club_feature_id = 3;
google.protobuf.BoolValue is_active = 4;
}
```
---
#### gRPC Service Implementation
**File:** `/CMS/src/CMSMicroservice.WebApi/Services/ClubMembershipService.cs`
**Added Methods:**
```csharp
public override async Task<GetUserClubFeaturesResponse> GetUserClubFeatures(
GetUserClubFeaturesRequest request,
ServerCallContext context)
{
return await _dispatchRequestToCQRS.Handle<
GetUserClubFeaturesRequest,
GetUserClubFeaturesQuery,
GetUserClubFeaturesResponse>(request, context);
}
public override async Task<Protobuf.Protos.ClubMembership.ToggleUserClubFeatureResponse>
ToggleUserClubFeature(
ToggleUserClubFeatureRequest request,
ServerCallContext context)
{
return await _dispatchRequestToCQRS.Handle<
ToggleUserClubFeatureRequest,
ToggleUserClubFeatureCommand,
Protobuf.Protos.ClubMembership.ToggleUserClubFeatureResponse>(request, context);
}
```
---
#### AutoMapper Profile
**File:** `/CMS/src/CMSMicroservice.WebApi/Common/Mappings/ClubFeatureProfile.cs`
**Mappings:**
1. `GetUserClubFeaturesRequest``GetUserClubFeaturesQuery`
2. `UserClubFeatureDto``UserClubFeatureModel` (Proto)
3. `List<UserClubFeatureDto>``GetUserClubFeaturesResponse`
4. `ToggleUserClubFeatureRequest``ToggleUserClubFeatureCommand`
5. `ToggleUserClubFeatureResponse` (App) → `ToggleUserClubFeatureResponse` (Proto)
**Special Handling:**
- DateTime conversion to `Timestamp` (Protobuf format)
- Null-safe mapping for optional fields
- Fully qualified type names to avoid ambiguity
---
## API Endpoints
### 1. Get User Club Features
**Method:** GET
**Endpoint:** `/ClubFeature/GetUserFeatures`
**Request:**
```json
{
"user_id": 123
}
```
**Response:**
```json
{
"features": [
{
"id": 1,
"user_id": 123,
"club_membership_id": 456,
"club_feature_id": 1,
"feature_title": "دسترسی به فروشگاه تخفیف",
"feature_description": "امکان خرید از فروشگاه تخفیف",
"is_active": true,
"granted_at": "2025-12-09T18:30:00Z",
"notes": "اعطا شده به‌طور خودکار هنگام فعالسازی"
}
]
}
```
---
### 2. Toggle User Club Feature
**Method:** POST
**Endpoint:** `/ClubFeature/ToggleFeature`
**Request:**
```json
{
"user_id": 123,
"club_feature_id": 1,
"is_active": false
}
```
**Response (Success):**
```json
{
"success": true,
"message": "ویژگی با موفقیت غیرفعال شد",
"user_club_feature_id": 1,
"is_active": false
}
```
**Response (Error - User Not Found):**
```json
{
"success": false,
"message": "کاربر یافت نشد"
}
```
**Response (Error - Feature Not Found):**
```json
{
"success": false,
"message": "ویژگی باشگاه یافت نشد"
}
```
**Response (Error - User Doesn't Have Feature):**
```json
{
"success": false,
"message": "این ویژگی برای کاربر یافت نشد"
}
```
---
## Database Schema
### Table: UserClubFeatures
Existing table with newly added `IsActive` field:
```sql
CREATE TABLE [CMS].[UserClubFeatures]
(
[Id] BIGINT IDENTITY(1,1) PRIMARY KEY,
[UserId] BIGINT NOT NULL,
[ClubMembershipId] BIGINT NOT NULL,
[ClubFeatureId] BIGINT NOT NULL,
[GrantedAt] DATETIME2 NOT NULL,
[IsActive] BIT NOT NULL DEFAULT 1, -- ← NEW FIELD
[Notes] NVARCHAR(MAX) NULL,
[Created] DATETIME2 NOT NULL,
[CreatedBy] NVARCHAR(MAX) NULL,
[LastModified] DATETIME2 NULL,
[LastModifiedBy] NVARCHAR(MAX) NULL,
[IsDeleted] BIT NOT NULL DEFAULT 0,
CONSTRAINT FK_UserClubFeatures_Users FOREIGN KEY ([UserId])
REFERENCES [Identity].[Users]([Id]),
CONSTRAINT FK_UserClubFeatures_ClubMembership FOREIGN KEY ([ClubMembershipId])
REFERENCES [CMS].[ClubMembership]([Id]),
CONSTRAINT FK_UserClubFeatures_ClubFeatures FOREIGN KEY ([ClubFeatureId])
REFERENCES [CMS].[ClubFeatures]([Id])
);
```
---
## Usage Examples
### Admin Panel Scenario
#### 1. View User's Club Features
```csharp
// Admin selects user ID: 123
var request = new GetUserClubFeaturesRequest { UserId = 123 };
var response = await client.GetUserClubFeaturesAsync(request);
// Display in grid:
foreach (var feature in response.Features)
{
Console.WriteLine($"Feature: {feature.FeatureTitle}");
Console.WriteLine($"Status: {(feature.IsActive ? "فعال" : "غیرفعال")}");
Console.WriteLine($"Granted: {feature.GrantedAt}");
Console.WriteLine("---");
}
```
**Output:**
```
Feature: دسترسی به فروشگاه تخفیف
Status: فعال
Granted: 2025-12-09 18:30:00
---
Feature: دسترسی به کمیسیون هفتگی
Status: فعال
Granted: 2025-12-09 18:30:00
---
Feature: دسترسی به شارژ شبکه
Status: غیرفعال
Granted: 2025-12-09 18:30:00
---
```
---
#### 2. Disable a Feature
```csharp
// Admin clicks "Disable" on Feature ID: 3
var request = new ToggleUserClubFeatureRequest
{
UserId = 123,
ClubFeatureId = 3,
IsActive = false
};
var response = await client.ToggleUserClubFeatureAsync(request);
if (response.Success)
{
Console.WriteLine(response.Message);
// Output: ویژگی با موفقیت غیرفعال شد
}
```
---
#### 3. Re-enable a Feature
```csharp
// Admin clicks "Enable" on Feature ID: 3
var request = new ToggleUserClubFeatureRequest
{
UserId = 123,
ClubFeatureId = 3,
IsActive = true
};
var response = await client.ToggleUserClubFeatureAsync(request);
if (response.Success)
{
Console.WriteLine(response.Message);
// Output: ویژگی با موفقیت فعال شد
}
```
---
## Testing Checklist
### Unit Tests (Recommended)
- [ ] GetUserClubFeaturesQueryHandler returns correct DTOs
- [ ] ToggleUserClubFeatureCommandHandler validates user exists
- [ ] ToggleUserClubFeatureCommandHandler validates feature exists
- [ ] ToggleUserClubFeatureCommandHandler validates user has feature
- [ ] ToggleUserClubFeatureCommandHandler updates IsActive correctly
- [ ] ToggleUserClubFeatureCommandHandler sets LastModified timestamp
### Integration Tests
- [ ] gRPC GetUserClubFeatures endpoint returns data
- [ ] gRPC ToggleUserClubFeature endpoint updates database
- [ ] AutoMapper mappings work correctly
- [ ] Proto serialization/deserialization works
### Manual Testing
1. **Get Features:**
```bash
grpcurl -d '{"user_id": 123}' \
-plaintext localhost:5000 \
clubmembership.ClubMembershipContract/GetUserClubFeatures
```
2. **Disable Feature:**
```bash
grpcurl -d '{"user_id": 123, "club_feature_id": 1, "is_active": false}' \
-plaintext localhost:5000 \
clubmembership.ClubMembershipContract/ToggleUserClubFeature
```
3. **Verify in Database:**
```sql
SELECT Id, UserId, ClubFeatureId, IsActive, LastModified
FROM CMS.UserClubFeatures
WHERE UserId = 123;
```
---
## Build Status
✅ **All projects build successfully**
- CMSMicroservice.Domain: ✅
- CMSMicroservice.Application: ✅ (0 errors, 274 warnings)
- CMSMicroservice.Protobuf: ✅
- CMSMicroservice.WebApi: ✅ (0 errors, 17 warnings)
---
## Next Steps (Optional Enhancements)
1. **Authorization:**
- Add `[Authorize(Roles = "Admin")]` attribute
- Validate admin permissions before toggling
2. **Audit Logging:**
- Log who changed the feature status
- Track `LastModifiedBy` field
3. **Bulk Operations:**
- Add endpoint to toggle multiple features at once
- Add endpoint to enable/disable all features for a user
4. **History Tracking:**
- Create `UserClubFeatureHistory` table
- Log every status change with timestamp and reason
5. **Notifications:**
- Send notification to user when feature is disabled
- Email/SMS alert for important features
6. **Business Rules:**
- Add validation: prevent disabling critical features
- Add expiration dates for features
- Add feature dependencies (e.g., Feature B requires Feature A)
---
## Summary
✅ Created CQRS Query + Command for club feature management
✅ Created gRPC Proto definitions and services
✅ Created AutoMapper mappings
✅ All builds successful
✅ Ready for deployment and testing
**Total Files Created:** 8
**Total Lines of Code:** ~350
**Build Errors:** 0
**Status:** ✅ Complete and ready for use
@@ -3,14 +3,18 @@ namespace CMSMicroservice.Application.ClubMembershipCQ.Queries.GetClubMembership
public class GetClubMembershipQueryHandler : IRequestHandler<GetClubMembershipQuery, ClubMembershipDto?>
{
private readonly IApplicationDbContext _context;
private readonly ILogger<GetClubMembershipQueryHandler> _logger;
public GetClubMembershipQueryHandler(IApplicationDbContext context)
public GetClubMembershipQueryHandler(IApplicationDbContext context, ILogger<GetClubMembershipQueryHandler> logger)
{
_context = context;
_logger = logger;
}
public async Task<ClubMembershipDto?> Handle(GetClubMembershipQuery request, CancellationToken cancellationToken)
{
_logger.LogInformation("GetClubMembership called for UserId: {UserId}", request.UserId);
var membership = await _context.ClubMemberships
.AsNoTracking()
.Where(x => x.UserId == request.UserId)
@@ -27,6 +31,26 @@ public class GetClubMembershipQueryHandler : IRequestHandler<GetClubMembershipQu
})
.FirstOrDefaultAsync(cancellationToken);
// اگر کاربر عضویت نداره، یک DTO با وضعیت غیرفعال برگردون
if (membership == null)
{
_logger.LogInformation("No membership found for UserId: {UserId}, returning inactive status", request.UserId);
return new ClubMembershipDto
{
Id = 0,
UserId = request.UserId,
IsActive = false,
ActivatedAt = null,
InitialContribution = 0,
TotalEarned = 0,
Created = DateTimeOffset.UtcNow,
LastModified = null
};
}
_logger.LogInformation("Membership found for UserId: {UserId}, IsActive: {IsActive}, Id: {Id}",
request.UserId, membership.IsActive, membership.Id);
return membership;
}
}
@@ -0,0 +1,25 @@
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.CommissionCQ.Queries.GetMyCommissionPayouts;
/// <summary>
/// Query برای دریافت پرداخت‌های کمیسیون کاربر جاری (از JWT)
/// </summary>
public record GetMyCommissionPayoutsQuery : IRequest<GetMyCommissionPayoutsResponseDto>
{
/// <summary>
/// فیلتر وضعیت
/// </summary>
public CommissionPayoutStatus? Status { get; init; }
/// <summary>
/// شماره هفته (اختیاری)
/// </summary>
public long? WeekDefinitionId { get; init; }
/// <summary>
/// Pagination
/// </summary>
public PaginationState? PaginationState { get; init; }
}
@@ -0,0 +1,73 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Extensions;
using CMSMicroservice.Domain.Enums;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.CommissionCQ.Queries.GetMyCommissionPayouts;
public class GetMyCommissionPayoutsQueryHandler : IRequestHandler<GetMyCommissionPayoutsQuery, GetMyCommissionPayoutsResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetMyCommissionPayoutsQueryHandler(
IApplicationDbContext context,
ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetMyCommissionPayoutsResponseDto> Handle(GetMyCommissionPayoutsQuery request, CancellationToken cancellationToken)
{
// دریافت UserId از JWT (فقط برای Customer API)
if (!long.TryParse(_currentUser.UserId, out var userId))
{
throw new UnauthorizedAccessException("User not authenticated");
}
var query = _context.UserCommissionPayouts
.Include(x => x.WeekDefinition)
.Where(x => x.UserId == userId)
.AsNoTracking()
.AsQueryable();
// فیلترها
if (request.Status.HasValue)
{
query = query.Where(x => x.Status == request.Status.Value);
}
if (request.WeekDefinitionId.HasValue)
{
query = query.Where(x => x.WeekDefinitionId == request.WeekDefinitionId.Value);
}
// مرتب‌سازی: جدیدترین اول
query = query.OrderByDescending(x => x.Created);
var meta = await query.GetMetaData(request.PaginationState, cancellationToken);
var models = await query
.PaginatedListAsync(paginationState: request.PaginationState)
.Select(x => new GetMyCommissionPayoutsResponseModel
{
Id = x.Id,
WeekDefinitionId = x.WeekDefinitionId,
WeekDisplayName = x.WeekDefinition != null ? x.WeekDefinition.DisplayName : "",
BalancesEarned = x.BalancesEarned,
TotalAmount = x.TotalAmount,
AmountFormatted = x.TotalAmount.ToString("N0") + " تومان",
Status = x.Status,
CalculatedDate = x.PaidAt ?? (DateTime?)x.Created,
DatePersian = ""
})
.ToListAsync(cancellationToken);
return new GetMyCommissionPayoutsResponseDto
{
MetaData = meta,
Models = models
};
}
}
@@ -0,0 +1,25 @@
using FluentValidation;
namespace CMSMicroservice.Application.CommissionCQ.Queries.GetMyCommissionPayouts;
public class GetMyCommissionPayoutsQueryValidator : AbstractValidator<GetMyCommissionPayoutsQuery>
{
public GetMyCommissionPayoutsQueryValidator()
{
RuleFor(x => x.PaginationState)
.NotNull()
.WithMessage("Pagination state is required");
When(x => x.PaginationState != null, () =>
{
RuleFor(x => x.PaginationState!.PageNumber)
.GreaterThan(0)
.WithMessage("Page number must be greater than 0");
RuleFor(x => x.PaginationState!.PageSize)
.GreaterThan(0)
.LessThanOrEqualTo(100)
.WithMessage("Page size must be between 1 and 100");
});
}
}
@@ -0,0 +1,23 @@
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.CommissionCQ.Queries.GetMyCommissionPayouts;
public class GetMyCommissionPayoutsResponseDto
{
public MetaData? MetaData { get; set; }
public List<GetMyCommissionPayoutsResponseModel> Models { get; set; } = new();
}
public class GetMyCommissionPayoutsResponseModel
{
public long Id { get; set; }
public long WeekDefinitionId { get; set; }
public string WeekDisplayName { get; set; } = string.Empty;
public int BalancesEarned { get; set; }
public long TotalAmount { get; set; }
public string AmountFormatted { get; set; } = string.Empty;
public CommissionPayoutStatus Status { get; set; }
public DateTime? CalculatedDate { get; set; }
public string DatePersian { get; set; } = string.Empty;
}
@@ -0,0 +1,24 @@
using CMSMicroservice.Application.CommissionCQ.Queries.GetUserWeeklyBalances;
namespace CMSMicroservice.Application.CommissionCQ.Queries.GetMyWeeklyBalances;
/// <summary>
/// Query برای دریافت تعادل‌های هفتگی کاربر جاری (از JWT)
/// </summary>
public record GetMyWeeklyBalancesQuery : IRequest<GetUserWeeklyBalancesResponseDto>
{
/// <summary>
/// شناسه تعریف هفته (اختیاری)
/// </summary>
public long? WeekDefinitionId { get; init; }
/// <summary>
/// فقط موارد Expired نشده؟
/// </summary>
public bool OnlyActive { get; init; }
/// <summary>
/// Pagination
/// </summary>
public PaginationState? PaginationState { get; init; }
}
@@ -0,0 +1,47 @@
using CMSMicroservice.Application.CommissionCQ.Queries.GetUserWeeklyBalances;
namespace CMSMicroservice.Application.CommissionCQ.Queries.GetMyWeeklyBalances;
/// <summary>
/// Handler برای دریافت تعادل‌های هفتگی کاربر جاری
/// </summary>
public class GetMyWeeklyBalancesQueryHandler : IRequestHandler<GetMyWeeklyBalancesQuery, GetUserWeeklyBalancesResponseDto>
{
private readonly ICurrentUserService _currentUserService;
private readonly IMediator _mediator;
private readonly ILogger<GetMyWeeklyBalancesQueryHandler> _logger;
public GetMyWeeklyBalancesQueryHandler(
ICurrentUserService currentUserService,
IMediator mediator,
ILogger<GetMyWeeklyBalancesQueryHandler> logger)
{
_currentUserService = currentUserService;
_mediator = mediator;
_logger = logger;
}
public async Task<GetUserWeeklyBalancesResponseDto> Handle(GetMyWeeklyBalancesQuery request, CancellationToken cancellationToken)
{
// دریافت UserId از JWT
if (!long.TryParse(_currentUserService.UserId, out var userId) || userId <= 0)
{
_logger.LogWarning("GetMyWeeklyBalances called without valid user authentication");
throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
}
_logger.LogInformation("GetMyWeeklyBalances for UserId: {UserId}, WeekDefinitionId: {WeekDefinitionId}",
userId, request.WeekDefinitionId);
// فراخوانی GetUserWeeklyBalancesQuery با UserId از JWT
var query = new GetUserWeeklyBalancesQuery
{
UserId = userId,
WeekDefinitionId = request.WeekDefinitionId,
OnlyActive = request.OnlyActive,
PaginationState = request.PaginationState
};
return await _mediator.Send(query, cancellationToken);
}
}
@@ -4,13 +4,16 @@ public class GetUserCommissionPayoutsQueryHandler : IRequestHandler<GetUserCommi
{
private readonly IApplicationDbContext _context;
private readonly IWeekDefinitionRepository _weekDefinitionRepository;
private readonly ICurrentUserService _currentUser;
public GetUserCommissionPayoutsQueryHandler(
IApplicationDbContext context,
IWeekDefinitionRepository weekDefinitionRepository)
IWeekDefinitionRepository weekDefinitionRepository,
ICurrentUserService currentUser)
{
_context = context;
_weekDefinitionRepository = weekDefinitionRepository;
_currentUser = currentUser;
}
public async Task<GetUserCommissionPayoutsResponseDto> Handle(GetUserCommissionPayoutsQuery request, CancellationToken cancellationToken)
@@ -21,10 +24,20 @@ public class GetUserCommissionPayoutsQueryHandler : IRequestHandler<GetUserCommi
.AsNoTracking()
.AsQueryable();
// فیلترها
if (request.UserId.HasValue)
// اگر UserId داده نشده، از CurrentUser بگیر (برای Customer API)
long? userId = request.UserId;
if (!userId.HasValue || userId.Value == 0)
{
query = query.Where(x => x.UserId == request.UserId.Value);
if (long.TryParse(_currentUser.UserId, out var currentUserId))
{
userId = currentUserId;
}
}
// فیلترها
if (userId.HasValue && userId.Value > 0)
{
query = query.Where(x => x.UserId == userId.Value);
}
if (request.Status.HasValue)
@@ -4,13 +4,16 @@ public class GetUserWeeklyBalancesQueryHandler : IRequestHandler<GetUserWeeklyBa
{
private readonly IApplicationDbContext _context;
private readonly IWeekDefinitionRepository _weekDefinitionRepository;
private readonly ICurrentUserService _currentUser;
public GetUserWeeklyBalancesQueryHandler(
IApplicationDbContext context,
IWeekDefinitionRepository weekDefinitionRepository)
IWeekDefinitionRepository weekDefinitionRepository,
ICurrentUserService currentUser)
{
_context = context;
_weekDefinitionRepository = weekDefinitionRepository;
_currentUser = currentUser;
}
public async Task<GetUserWeeklyBalancesResponseDto> Handle(GetUserWeeklyBalancesQuery request, CancellationToken cancellationToken)
@@ -21,10 +24,20 @@ public class GetUserWeeklyBalancesQueryHandler : IRequestHandler<GetUserWeeklyBa
.AsNoTracking()
.AsQueryable();
// فیلترها
if (request.UserId.HasValue)
// اگر UserId داده نشده، از CurrentUser بگیر (برای Customer API)
long? userId = request.UserId;
if (!userId.HasValue || userId.Value == 0)
{
query = query.Where(x => x.UserId == request.UserId.Value);
if (long.TryParse(_currentUser.UserId, out var currentUserId))
{
userId = currentUserId;
}
}
// فیلترها
if (userId.HasValue && userId.Value > 0)
{
query = query.Where(x => x.UserId == userId.Value);
}
// فیلتر بر اساس WeekDefinitionId (روش ترجیحی)
@@ -0,0 +1,17 @@
namespace CMSMicroservice.Application.Common.Authorization;
/// <summary>
/// سرویس بررسی مجوز کاربر بر اساس نقش‌های JWT
/// </summary>
public interface IPermissionService
{
/// <summary>
/// دریافت نقش‌های کاربر فعلی از JWT Claims
/// </summary>
Task<IReadOnlyList<string>> GetUserRolesAsync(CancellationToken cancellationToken);
/// <summary>
/// بررسی اینکه آیا کاربر فعلی مجوز مشخصی دارد
/// </summary>
Task<bool> HasPermissionAsync(string permission, CancellationToken cancellationToken);
}
@@ -0,0 +1,127 @@
namespace CMSMicroservice.Application.Common.Authorization;
/// <summary>
/// ثوابت نام مجوزها — دسته‌بندی شده بر اساس حوزه
/// </summary>
public static class PermissionNames
{
// Dashboard
public const string DashboardView = "dashboard.view";
// Orders
public const string OrdersView = "orders.view";
public const string OrdersCreate = "orders.create";
public const string OrdersUpdate = "orders.update";
public const string OrdersDelete = "orders.delete";
public const string OrdersCancel = "orders.cancel";
public const string OrdersApprove = "orders.approve";
// Products
public const string ProductsView = "products.view";
public const string ProductsCreate = "products.create";
public const string ProductsUpdate = "products.update";
public const string ProductsDelete = "products.delete";
// Users
public const string UsersView = "users.view";
public const string UsersUpdate = "users.update";
public const string UsersDelete = "users.delete";
// Commission
public const string CommissionView = "commission.view";
public const string CommissionApproveWithdrawal = "commission.approve_withdrawal";
// Public Messages
public const string PublicMessagesView = "publicmessages.view";
public const string PublicMessagesCreate = "publicmessages.create";
public const string PublicMessagesUpdate = "publicmessages.update";
public const string PublicMessagesPublish = "publicmessages.publish";
// Manual Payments
public const string ManualPaymentsView = "manualpayments.view";
public const string ManualPaymentsCreate = "manualpayments.create";
public const string ManualPaymentsApprove = "manualpayments.approve";
// Settings
public const string SettingsView = "settings.view";
public const string SettingsUpdate = "settings.update";
public const string SettingsDelete = "settings.delete";
public const string SettingsManageConfiguration = "settings.manage_configuration";
public const string SettingsManageVat = "settings.manage_vat";
// Reports
public const string ReportsView = "reports.view";
}
/// <summary>
/// نام نقش‌ها
/// </summary>
public static class RoleNames
{
public const string SuperAdmin = "Administrator";
public const string Admin = "Admin";
public const string Inspector = "Inspector";
}
/// <summary>
/// تنظیمات نقش→مجوز — ماتریس دسترسی
/// </summary>
public static class RolePermissionConfig
{
private static readonly Dictionary<string, HashSet<string>> RolePermissions = new(StringComparer.OrdinalIgnoreCase)
{
[RoleNames.SuperAdmin] = new(StringComparer.OrdinalIgnoreCase) { "*" }, // Full access
[RoleNames.Admin] = new(StringComparer.OrdinalIgnoreCase)
{
PermissionNames.DashboardView,
PermissionNames.OrdersView,
PermissionNames.OrdersCreate,
PermissionNames.OrdersUpdate,
PermissionNames.OrdersCancel,
PermissionNames.ProductsView,
PermissionNames.ProductsCreate,
PermissionNames.ProductsUpdate,
PermissionNames.ProductsDelete,
PermissionNames.UsersView,
PermissionNames.UsersUpdate,
PermissionNames.CommissionView,
PermissionNames.CommissionApproveWithdrawal,
PermissionNames.PublicMessagesView,
PermissionNames.PublicMessagesCreate,
PermissionNames.PublicMessagesUpdate,
PermissionNames.PublicMessagesPublish,
PermissionNames.ManualPaymentsView,
PermissionNames.ManualPaymentsCreate,
PermissionNames.ReportsView
},
[RoleNames.Inspector] = new(StringComparer.OrdinalIgnoreCase)
{
PermissionNames.DashboardView,
PermissionNames.OrdersView,
PermissionNames.UsersView,
PermissionNames.CommissionView,
PermissionNames.PublicMessagesView,
PermissionNames.ReportsView
}
};
/// <summary>
/// بررسی اینکه آیا نقش مشخصی مجوز خاصی دارد
/// </summary>
public static bool HasPermission(string role, string permission)
{
if (string.IsNullOrWhiteSpace(role) || string.IsNullOrWhiteSpace(permission))
return false;
if (!RolePermissions.TryGetValue(role, out var permissions))
return false;
// Wildcard: SuperAdmin has full access
if (permissions.Contains("*"))
return true;
return permissions.Contains(permission);
}
}
@@ -0,0 +1,15 @@
namespace CMSMicroservice.Application.Common.Authorization;
/// <summary>
/// Attribute برای مشخص کردن مجوز لازم برای دسترسی به یک متد gRPC
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequiresPermissionAttribute : Attribute
{
public RequiresPermissionAttribute(string permission)
{
Permission = permission ?? throw new ArgumentNullException(nameof(permission));
}
public string Permission { get; }
}
@@ -0,0 +1,37 @@
namespace CMSMicroservice.Application.Common.Interfaces;
/// <summary>
/// Service for uploading files to FMS (File Management Service)
/// </summary>
public interface IFileManagementService
{
/// <summary>
/// Uploads a file to FMS and returns the stored file path
/// </summary>
/// <param name="directory">Target directory path (e.g. "Images/Products")</param>
/// <param name="fileBytes">Raw file bytes</param>
/// <param name="mime">MIME type (e.g. "image/jpeg")</param>
/// <param name="fileName">Original file name</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>The stored file path returned by FMS, or null if upload failed</returns>
Task<string?> UploadFileAsync(string directory, byte[] fileBytes, string mime, string? fileName, CancellationToken cancellationToken = default);
/// <summary>
/// Uploads an image to FMS with optimization (resize + compress)
/// Returns both main image path and thumbnail path
/// </summary>
/// <param name="directory">Target directory path (e.g. "Images/Products")</param>
/// <param name="fileBytes">Raw image bytes</param>
/// <param name="mime">MIME type (e.g. "image/jpeg")</param>
/// <param name="fileName">Original file name</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Tuple of (mainImagePath, thumbnailPath), either can be null if upload failed</returns>
Task<(string? MainImagePath, string? ThumbnailPath)> UploadImageWithThumbnailAsync(
string directory, byte[] fileBytes, string mime, string? fileName,
CancellationToken cancellationToken = default);
/// <summary>
/// Deletes a file from FMS by its ID
/// </summary>
Task<bool> DeleteFileAsync(long fileId, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,20 @@
using MediatR;
namespace CMSMicroservice.Application.DiscountShopCQ.Commands.AddToCustomerCart;
/// <summary>
/// Command برای افزودن محصول به سبد خرید کاربر فعلی
/// </summary>
public class AddToCustomerCartCommand : IRequest<AddToCustomerCartCommandResponse>
{
public long ProductId { get; set; }
public int Count { get; set; }
// UserId from ICurrentUserService
}
public class AddToCustomerCartCommandResponse
{
public long Id { get; set; }
public string Message { get; set; } = string.Empty;
public bool Success { get; set; }
}
@@ -0,0 +1,80 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.DiscountShopCQ.Commands.AddToCustomerCart;
public class AddToCustomerCartCommandHandler : IRequestHandler<AddToCustomerCartCommand, AddToCustomerCartCommandResponse>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public AddToCustomerCartCommandHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<AddToCustomerCartCommandResponse> Handle(AddToCustomerCartCommand request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// Check if product exists and is not deleted
var product = await _context.Products
.FirstOrDefaultAsync(p => p.Id == request.ProductId && !p.IsDeleted, cancellationToken);
if (product == null)
{
return new AddToCustomerCartCommandResponse
{
Success = false,
Message = "محصول یافت نشد یا حذف شده است"
};
}
// Check if item already exists in cart
var existingCartItem = await _context.UserCarts
.FirstOrDefaultAsync(uc => uc.UserId == userId && uc.ProductId == request.ProductId, cancellationToken);
if (existingCartItem != null)
{
// Update count
existingCartItem.Count += request.Count;
_context.UserCarts.Update(existingCartItem);
await _context.SaveChangesAsync(cancellationToken);
return new AddToCustomerCartCommandResponse
{
Id = existingCartItem.Id,
Success = true,
Message = "تعداد محصول در سبد خرید به‌روزرسانی شد"
};
}
// Create new cart item
var cartItem = new UserCart
{
UserId = userId,
ProductId = request.ProductId,
Count = request.Count,
Created = DateTime.UtcNow
};
_context.UserCarts.Add(cartItem);
await _context.SaveChangesAsync(cancellationToken);
return new AddToCustomerCartCommandResponse
{
Id = cartItem.Id,
Success = true,
Message = "محصول به سبد خرید اضافه شد"
};
}
}
@@ -0,0 +1,18 @@
using MediatR;
namespace CMSMicroservice.Application.DiscountShopCQ.Commands.RemoveFromCustomerCart;
/// <summary>
/// Command برای حذف محصول از سبد خرید
/// </summary>
public class RemoveFromCustomerCartCommand : IRequest<RemoveFromCustomerCartCommandResponse>
{
public long CartItemId { get; set; }
// UserId from ICurrentUserService
}
public class RemoveFromCustomerCartCommandResponse
{
public string Message { get; set; } = string.Empty;
public bool Success { get; set; }
}
@@ -0,0 +1,49 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.DiscountShopCQ.Commands.RemoveFromCustomerCart;
public class RemoveFromCustomerCartCommandHandler : IRequestHandler<RemoveFromCustomerCartCommand, RemoveFromCustomerCartCommandResponse>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public RemoveFromCustomerCartCommandHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<RemoveFromCustomerCartCommandResponse> Handle(RemoveFromCustomerCartCommand request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// Find and remove cart item
var cartItem = await _context.UserCarts
.FirstOrDefaultAsync(uc => uc.Id == request.CartItemId && uc.UserId == userId, cancellationToken);
if (cartItem == null)
{
return new RemoveFromCustomerCartCommandResponse
{
Success = false,
Message = "آیتم سبد خرید یافت نشد"
};
}
_context.UserCarts.Remove(cartItem);
await _context.SaveChangesAsync(cancellationToken);
return new RemoveFromCustomerCartCommandResponse
{
Success = true,
Message = "آیتم از سبد خرید حذف شد"
};
}
}
@@ -0,0 +1,19 @@
using MediatR;
namespace CMSMicroservice.Application.DiscountShopCQ.Commands.UpdateCustomerCartItem;
/// <summary>
/// Command برای به‌روزرسانی تعداد محصول در سبد خرید
/// </summary>
public class UpdateCustomerCartItemCommand : IRequest<UpdateCustomerCartItemCommandResponse>
{
public long CartItemId { get; set; }
public int Count { get; set; }
// UserId from ICurrentUserService
}
public class UpdateCustomerCartItemCommandResponse
{
public string Message { get; set; } = string.Empty;
public bool Success { get; set; }
}
@@ -0,0 +1,64 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.DiscountShopCQ.Commands.UpdateCustomerCartItem;
public class UpdateCustomerCartItemCommandHandler : IRequestHandler<UpdateCustomerCartItemCommand, UpdateCustomerCartItemCommandResponse>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public UpdateCustomerCartItemCommandHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<UpdateCustomerCartItemCommandResponse> Handle(UpdateCustomerCartItemCommand request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// Find cart item
var cartItem = await _context.UserCarts
.FirstOrDefaultAsync(uc => uc.Id == request.CartItemId && uc.UserId == userId, cancellationToken);
if (cartItem == null)
{
return new UpdateCustomerCartItemCommandResponse
{
Success = false,
Message = "آیتم سبد خرید یافت نشد"
};
}
// Update count
if (request.Count <= 0)
{
// Remove item if count is 0 or negative
_context.UserCarts.Remove(cartItem);
await _context.SaveChangesAsync(cancellationToken);
return new UpdateCustomerCartItemCommandResponse
{
Success = true,
Message = "آیتم از سبد خرید حذف شد"
};
}
cartItem.Count = request.Count;
_context.UserCarts.Update(cartItem);
await _context.SaveChangesAsync(cancellationToken);
return new UpdateCustomerCartItemCommandResponse
{
Success = true,
Message = "تعداد آیتم به‌روزرسانی شد"
};
}
}
@@ -0,0 +1,11 @@
using MediatR;
namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetCustomerCart;
/// <summary>
/// Query برای دریافت سبد خرید کاربر فعلی
/// </summary>
public class GetCustomerCartQuery : IRequest<GetCustomerCartQueryResponse>
{
// UserId from ICurrentUserService
}
@@ -0,0 +1,68 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetCustomerCart;
public class GetCustomerCartQueryHandler : IRequestHandler<GetCustomerCartQuery, GetCustomerCartQueryResponse>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetCustomerCartQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetCustomerCartQueryResponse> Handle(GetCustomerCartQuery request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// Get all cart items for the current user
var cartItems = await _context.UserCarts
.Include(uc => uc.Product)
.Where(uc => uc.UserId == userId)
.ToListAsync(cancellationToken);
var response = new GetCustomerCartQueryResponse
{
TotalItemsCount = cartItems.Sum(c => c.Count),
Message = cartItems.Count > 0 ? "سبد خرید با موفقیت بازیابی شد" : "سبد خرید خالی است"
};
foreach (var item in cartItems)
{
// Use Product.ThumbnailPath directly
var thumbnailPath = item.Product?.ThumbnailPath ?? string.Empty;
var itemPrice = item.Product?.Price ?? 0;
var itemDiscount = item.Product?.Discount ?? 0;
var finalPrice = itemPrice * (100 - itemDiscount) / 100;
var totalItemPrice = finalPrice * item.Count;
response.Items.Add(new CustomerCartItemModel
{
Id = item.Id,
ProductId = item.ProductId,
ProductTitle = item.Product?.Title ?? string.Empty,
ProductShortInformation = item.Product?.ShortInfomation ?? string.Empty, // Typo in DB: ShortInfomation
ProductPrice = itemPrice,
ProductDiscount = itemDiscount,
ProductThumbnailPath = thumbnailPath,
Count = item.Count,
TotalItemPrice = totalItemPrice,
Created = item.Created
});
response.TotalPrice += totalItemPrice;
}
return response;
}
}
@@ -0,0 +1,23 @@
namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetCustomerCart;
public class GetCustomerCartQueryResponse
{
public List<CustomerCartItemModel> Items { get; set; } = new();
public long TotalPrice { get; set; }
public int TotalItemsCount { get; set; }
public string Message { get; set; } = string.Empty;
}
public class CustomerCartItemModel
{
public long Id { get; set; }
public long ProductId { get; set; }
public string ProductTitle { get; set; } = string.Empty;
public string ProductShortInformation { get; set; } = string.Empty;
public long ProductPrice { get; set; }
public int ProductDiscount { get; set; }
public string ProductThumbnailPath { get; set; } = string.Empty;
public int Count { get; set; }
public long TotalItemPrice { get; set; }
public DateTime Created { get; set; }
}
@@ -0,0 +1,15 @@
using CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkTree;
namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetMyNetworkTree;
/// <summary>
/// Query برای دریافت درخت شبکه کاربر جاری (Customer-facing)
/// از ICurrentUserService برای دریافت UserId استفاده می‌کند
/// </summary>
public record GetMyNetworkTreeQuery : IRequest<NetworkTreeDto?>
{
/// <summary>
/// تعداد سطوح (Depth) که می‌خواهیم نمایش دهیم (پیش‌فرض: 3)
/// </summary>
public int MaxDepth { get; init; } = 3;
}
@@ -0,0 +1,40 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkTree;
namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetMyNetworkTree;
/// <summary>
/// Handler برای دریافت درخت شبکه کاربر جاری
/// </summary>
public class GetMyNetworkTreeQueryHandler : IRequestHandler<GetMyNetworkTreeQuery, NetworkTreeDto?>
{
private readonly ICurrentUserService _currentUser;
private readonly ISender _sender;
public GetMyNetworkTreeQueryHandler(
ICurrentUserService currentUser,
ISender sender)
{
_currentUser = currentUser;
_sender = sender;
}
public async Task<NetworkTreeDto?> Handle(GetMyNetworkTreeQuery request, CancellationToken cancellationToken)
{
// دریافت UserId از JWT
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// استفاده از GetNetworkTreeQuery موجود با UserId از JWT
var query = new GetNetworkTreeQuery
{
UserId = userId,
MaxDepth = request.MaxDepth > 0 ? request.MaxDepth : 3
};
return await _sender.Send(query, cancellationToken);
}
}
@@ -0,0 +1,24 @@
namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetMyNetworkTree;
public class GetMyNetworkTreeQueryValidator : AbstractValidator<GetMyNetworkTreeQuery>
{
public GetMyNetworkTreeQueryValidator()
{
RuleFor(x => x.MaxDepth)
.InclusiveBetween(1, 100)
.WithMessage("عمق درخت باید بین 1 تا 100 باشد");
}
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(
ValidationContext<GetMyNetworkTreeQuery>.CreateWithOptions(
(GetMyNetworkTreeQuery)model,
x => x.IncludeProperties(propertyName)));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}
@@ -2,5 +2,8 @@ namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkStat
public class GetNetworkStatisticsQuery : IRequest<GetNetworkStatisticsResponseDto>
{
// No parameters - returns overall statistics
/// <summary>
/// شناسه کاربر برای محاسبه آمار شبکه او - 0 یا null یعنی کاربر جاری
/// </summary>
public long UserId { get; set; }
}
@@ -5,61 +5,79 @@ namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkStat
public class GetNetworkStatisticsQueryHandler : IRequestHandler<GetNetworkStatisticsQuery, GetNetworkStatisticsResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetNetworkStatisticsQueryHandler(IApplicationDbContext context)
public GetNetworkStatisticsQueryHandler(
IApplicationDbContext context,
ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetNetworkStatisticsResponseDto> Handle(GetNetworkStatisticsQuery request, CancellationToken cancellationToken)
{
// Basic statistics - using Users table with NetworkParentId
var totalMembers = await _context.Users
.Where(x => x.NetworkParentId != null)
.CountAsync(cancellationToken);
// Get userId - use current user if not specified or is 0
var userId = request.UserId == 0
? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
: request.UserId;
var activeMembers = await _context.Users
.Where(x => x.NetworkParentId != null)
.CountAsync(cancellationToken);
if (userId == 0)
{
throw new UnauthorizedAccessException("User ID not found");
}
var leftLegCount = await _context.Users
.Where(x => x.LegPosition == NetworkLeg.Left)
.CountAsync(cancellationToken);
// Get all descendants recursively
var allUsers = await _context.Users.ToListAsync(cancellationToken);
var allDescendants = GetAllDescendants(userId, allUsers);
var rightLegCount = await _context.Users
.Where(x => x.LegPosition == NetworkLeg.Right)
.CountAsync(cancellationToken);
// Statistics for the user's network (all descendants)
var totalMembers = allDescendants.Count;
var activeMembers = allDescendants.Count(x => !x.IsDeleted);
// Get direct left and right children
var leftChild = allUsers.FirstOrDefault(x => x.NetworkParentId == userId && x.LegPosition == NetworkLeg.Left);
var rightChild = allUsers.FirstOrDefault(x => x.NetworkParentId == userId && x.LegPosition == NetworkLeg.Right);
// Count all descendants in left and right subtrees
var leftLegCount = leftChild != null ? GetAllDescendants(leftChild.Id, allUsers).Count + 1 : 0; // +1 for leftChild itself
var rightLegCount = rightChild != null ? GetAllDescendants(rightChild.Id, allUsers).Count + 1 : 0; // +1 for rightChild itself
double leftPercentage = totalMembers > 0 ? (leftLegCount / (double)totalMembers) * 100 : 0;
double rightPercentage = totalMembers > 0 ? (rightLegCount / (double)totalMembers) * 100 : 0;
// Calculate depth based on network parent relationships
// For simplicity, we'll estimate average depth as 3-5 levels
double averageDepth = 4.5; // Estimated average
int maxDepth = 10; // Estimated max depth
// Calculate actual depth
int maxDepth = 0;
double totalDepthSum = 0;
var userDepths = new Dictionary<long, int>();
CalculateDepths(userId, allUsers, 0, userDepths, ref maxDepth);
// Level distribution - simplified estimation based on growth pattern
if (allDescendants.Count > 0)
{
totalDepthSum = allDescendants.Sum(d => userDepths.ContainsKey(d.Id) ? userDepths[d.Id] : 0);
}
double averageDepth = allDescendants.Count > 0 ? totalDepthSum / allDescendants.Count : 0;
// Level distribution - calculate from depths
var levelDistribution = new List<LevelDistributionModel>();
if (totalMembers > 0)
if (allDescendants.Count > 0)
{
// Approximate distribution: Level 1 (10%), Level 2 (20%), Level 3 (30%), Level 4 (20%), Level 5+ (20%)
levelDistribution = new List<LevelDistributionModel>
{
new() { Level = 1, Count = (int)(totalMembers * 0.1) },
new() { Level = 2, Count = (int)(totalMembers * 0.2) },
new() { Level = 3, Count = (int)(totalMembers * 0.3) },
new() { Level = 4, Count = (int)(totalMembers * 0.2) },
new() { Level = 5, Count = (int)(totalMembers * 0.15) },
new() { Level = 6, Count = totalMembers - (int)(totalMembers * 0.95) }
};
var levelCounts = allDescendants
.Where(d => userDepths.ContainsKey(d.Id))
.GroupBy(d => userDepths[d.Id])
.OrderBy(g => g.Key)
.Select(g => new LevelDistributionModel { Level = g.Key, Count = g.Count() })
.ToList();
levelDistribution = levelCounts;
}
// Monthly growth (last 6 months) - using Created date
// Monthly growth (last 6 months) - using descendants Created date
var sixMonthsAgo = DateTime.Now.AddMonths(-6);
var monthlyGrowthRaw = await _context.Users
.Where(x => x.NetworkParentId != null && x.Created >= sixMonthsAgo)
var monthlyGrowthRaw = allDescendants
.Where(x => x.Created >= sixMonthsAgo)
.Select(x => new { x.Created.Year, x.Created.Month })
.ToListAsync(cancellationToken);
.ToList();
var monthlyGrowth = monthlyGrowthRaw
.GroupBy(x => new { x.Year, x.Month })
@@ -71,27 +89,34 @@ public class GetNetworkStatisticsQueryHandler : IRequestHandler<GetNetworkStatis
.OrderBy(x => x.Month)
.ToList();
// Top users by total children count
var topUsers = await _context.Users
.Where(x => x.NetworkParentId != null)
// Top users by total descendants count
var userDescendantCounts = new Dictionary<long, int>();
foreach (var user in allDescendants)
{
var descendants = GetAllDescendants(user.Id, allUsers);
userDescendantCounts[user.Id] = descendants.Count;
}
var topUserData = allDescendants
.Where(x => x.Id != userId && userDescendantCounts[x.Id] > 0)
.Select(x => new
{
x.Id,
UserName = (x.FirstName + " " + x.LastName).Trim(),
LeftCount = _context.Users.Count(c => c.NetworkParentId == x.Id && c.LegPosition == NetworkLeg.Left),
RightCount = _context.Users.Count(c => c.NetworkParentId == x.Id && c.LegPosition == NetworkLeg.Right)
DescendantCount = userDescendantCounts[x.Id],
LeftCount = allUsers.Count(c => c.NetworkParentId == x.Id && c.LegPosition == NetworkLeg.Left),
RightCount = allUsers.Count(c => c.NetworkParentId == x.Id && c.LegPosition == NetworkLeg.Right)
})
.Where(x => x.LeftCount + x.RightCount > 0)
.OrderByDescending(x => x.LeftCount + x.RightCount)
.OrderByDescending(x => x.DescendantCount)
.Take(10)
.ToListAsync(cancellationToken);
.ToList();
var topUserModels = topUsers.Select((x, index) => new TopNetworkUserModel
var topUserModels = topUserData.Select((x, index) => new TopNetworkUserModel
{
Rank = index + 1,
UserId = x.Id,
UserName = x.UserName,
TotalChildren = x.LeftCount + x.RightCount,
TotalChildren = x.DescendantCount,
LeftCount = x.LeftCount,
RightCount = x.RightCount
}).ToList();
@@ -111,4 +136,40 @@ public class GetNetworkStatisticsQueryHandler : IRequestHandler<GetNetworkStatis
TopUsers = topUserModels
};
}
/// <summary>
/// Recursively get all descendants of a user
/// </summary>
private List<User> GetAllDescendants(long userId, List<User> allUsers)
{
var descendants = new List<User>();
var directChildren = allUsers.Where(x => x.NetworkParentId == userId).ToList();
foreach (var child in directChildren)
{
descendants.Add(child);
descendants.AddRange(GetAllDescendants(child.Id, allUsers));
}
return descendants;
}
/// <summary>
/// Calculate depth for all descendants recursively
/// </summary>
private void CalculateDepths(long userId, List<User> allUsers, int currentDepth, Dictionary<long, int> depths, ref int maxDepth)
{
var children = allUsers.Where(x => x.NetworkParentId == userId).ToList();
foreach (var child in children)
{
var childDepth = currentDepth + 1;
depths[child.Id] = childDepth;
if (childDepth > maxDepth)
maxDepth = childDepth;
CalculateDepths(child.Id, allUsers, childDepth, depths, ref maxDepth);
}
}
}
@@ -8,21 +8,37 @@ public class GetNetworkTreeQueryHandler : IRequestHandler<GetNetworkTreeQuery, N
{
private readonly IApplicationDbContext _context;
private readonly ILogger<GetNetworkTreeQueryHandler> _logger;
private readonly ICurrentUserService _currentUser;
public GetNetworkTreeQueryHandler(
IApplicationDbContext context,
ILogger<GetNetworkTreeQueryHandler> logger)
ILogger<GetNetworkTreeQueryHandler> logger,
ICurrentUserService currentUser)
{
_context = context;
_logger = logger;
_currentUser = currentUser;
}
public async Task<NetworkTreeDto?> Handle(GetNetworkTreeQuery request, CancellationToken cancellationToken)
{
// Get userId - use current user if UserId is 0
var userId = request.UserId == 0
? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
: request.UserId;
if (userId == 0)
{
throw new UnauthorizedAccessException("User ID not found");
}
// Create a new request with the resolved userId
var resolvedRequest = request with { UserId = userId };
try
{
// دریافت نتایج flat از Stored Procedure
var flatNodes = await ExecuteStoredProcedureAsync(request, cancellationToken);
var flatNodes = await ExecuteStoredProcedureAsync(resolvedRequest, cancellationToken);
if (flatNodes == null || !flatNodes.Any())
{
@@ -57,7 +57,7 @@ public class CreateNewOtpTokenCommandHandler : IRequestHandler<CreateNewOtpToken
};
await _context.OtpTokens.AddAsync(entity, cancellationToken);
entity.AddDomainEvent(new CreateNewOtpTokenEvent(entity));
entity.AddDomainEvent(new CreateNewOtpTokenEvent(entity, code));
await _context.SaveChangesAsync(cancellationToken);
return new CreateNewOtpTokenResponseDto()
{
@@ -1,3 +1,4 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Events;
using Microsoft.Extensions.Logging;
@@ -6,16 +7,29 @@ namespace CMSMicroservice.Application.OtpTokenCQ.EventHandlers;
public class CreateNewOtpTokenEventHandler : INotificationHandler<CreateNewOtpTokenEvent>
{
private readonly ILogger<CreateNewOtpTokenEventHandler> _logger;
private readonly IKavenegarService _kavenegarService;
public CreateNewOtpTokenEventHandler(ILogger<CreateNewOtpTokenEventHandler> logger)
public CreateNewOtpTokenEventHandler(
ILogger<CreateNewOtpTokenEventHandler> logger,
IKavenegarService kavenegarService)
{
_logger = logger;
_kavenegarService = kavenegarService;
}
public Task Handle(CreateNewOtpTokenEvent notification, CancellationToken cancellationToken)
public async Task Handle(CreateNewOtpTokenEvent notification, CancellationToken cancellationToken)
{
_logger.LogInformation("Domain Event: {DomainEvent}", notification.GetType().Name);
_logger.LogInformation("Domain Event: {DomainEvent} for mobile {Mobile}",
notification.GetType().Name, notification.Item.Mobile);
return Task.CompletedTask;
try
{
await _kavenegarService.VerifyLookupAsync(notification.Item.Mobile, notification.PlainCode);
_logger.LogInformation("OTP SMS sent successfully to {Mobile}", notification.Item.Mobile);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send OTP SMS to {Mobile}", notification.Item.Mobile);
}
}
}
@@ -0,0 +1,6 @@
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPackageDetails;
public class GetCustomerPackageDetailsQuery : IRequest<GetCustomerPackageDetailsResponseDto>
{
public long PackageId { get; set; }
}
@@ -0,0 +1,68 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Mapster;
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPackageDetails;
public class GetCustomerPackageDetailsQueryHandler : IRequestHandler<GetCustomerPackageDetailsQuery, GetCustomerPackageDetailsResponseDto>
{
private readonly IApplicationDbContext _context;
public GetCustomerPackageDetailsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetCustomerPackageDetailsResponseDto> Handle(GetCustomerPackageDetailsQuery request, CancellationToken cancellationToken)
{
var package = await _context.Packages
.AsNoTracking()
.Where(x => x.Id == request.PackageId)
.ProjectToType<GetCustomerPackageDetailsResponseDto>()
.FirstOrDefaultAsync(cancellationToken);
if (package == null)
throw new NotFoundException(nameof(Package), request.PackageId);
// Add features based on package (this could be stored in DB in future)
package.Features = new List<PackageFeatureDto>
{
new PackageFeatureDto
{
Title = "درآمد کمیسیون",
Description = "دریافت کمیسیون از فروش محصولات",
Icon = "commission",
IsHighlighted = true
},
new PackageFeatureDto
{
Title = "پشتیبانی 24/7",
Description = "دسترسی به پشتیبانی در تمام ساعات شبانه روز",
Icon = "support",
IsHighlighted = false
},
new PackageFeatureDto
{
Title = "آموزش‌های تخصصی",
Description = "دسترسی به دوره‌های آموزشی و وبینارها",
Icon = "education",
IsHighlighted = true
}
};
// Set purchase requirements
package.Requirements = new PurchaseRequirementsDto
{
RequiresMembership = false,
MinimumWalletBalance = package.Price / 10, // 10% minimum
Restrictions = new List<string>
{
"باید حداقل 18 سال سن داشته باشید",
"تایید هویت الزامی است"
}
};
return package;
}
}
@@ -0,0 +1,27 @@
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPackageDetails;
public class GetCustomerPackageDetailsResponseDto
{
public long Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public long Price { get; set; }
public string ImagePath { get; set; }
public List<PackageFeatureDto> Features { get; set; } = new();
public PurchaseRequirementsDto Requirements { get; set; }
}
public class PackageFeatureDto
{
public string Title { get; set; }
public string Description { get; set; }
public string Icon { get; set; }
public bool IsHighlighted { get; set; }
}
public class PurchaseRequirementsDto
{
public bool RequiresMembership { get; set; }
public long MinimumWalletBalance { get; set; }
public List<string> Restrictions { get; set; } = new();
}
@@ -0,0 +1,7 @@
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPackages;
public class GetCustomerPackagesQuery : IRequest<List<GetCustomerPackagesResponseDto>>
{
public bool IncludeInactive { get; set; }
public int? PackageTypeFilter { get; set; }
}
@@ -0,0 +1,51 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Mapster;
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPackages;
public class GetCustomerPackagesQueryHandler : IRequestHandler<GetCustomerPackagesQuery, List<GetCustomerPackagesResponseDto>>
{
private readonly IApplicationDbContext _context;
public GetCustomerPackagesQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<GetCustomerPackagesResponseDto>> Handle(GetCustomerPackagesQuery request, CancellationToken cancellationToken)
{
var query = _context.Packages
.AsNoTracking()
.AsQueryable();
// Filter by PackageType if specified
if (request.PackageTypeFilter.HasValue)
{
// Note: Package entity doesn't have PackageType enum, so we filter by convention
// Assuming Title or Description contains the package type indicator
// If Package entity needs PackageType field, it should be added to migration
}
// Get all packages (assuming all are available unless marked otherwise)
var packages = await query
.ProjectToType<GetCustomerPackagesResponseDto>()
.ToListAsync(cancellationToken);
// Map additional fields
foreach (var package in packages)
{
package.Name = package.Title;
package.ImageUrl = package.ImagePath;
package.Currency = "IRR";
package.IsAvailable = true;
package.ValidityDays = 365; // Default validity
package.IsPopular = false;
package.ShortDescription = package.Description?.Length > 100
? package.Description.Substring(0, 100) + "..."
: package.Description;
}
return packages;
}
}
@@ -0,0 +1,18 @@
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPackages;
public class GetCustomerPackagesResponseDto
{
public long Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public long Price { get; set; }
public string Currency { get; set; } = "IRR";
public int PackageType { get; set; }
public bool IsAvailable { get; set; } = true;
public string ImageUrl { get; set; }
public string ImagePath { get; set; }
public int ValidityDays { get; set; }
public bool IsPopular { get; set; }
public string ShortDescription { get; set; }
}
@@ -0,0 +1,12 @@
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPurchaseHistory;
public class GetCustomerPurchaseHistoryQuery : IRequest<GetCustomerPurchaseHistoryResponseDto>
{
public long UserId { get; set; }
public PaginationState PaginationState { get; set; }
public int? PackageTypeFilter { get; set; }
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
}
@@ -0,0 +1,90 @@
using CMSMicroservice.Application.Common.Extensions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
using Mapster;
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPurchaseHistory;
public class GetCustomerPurchaseHistoryQueryHandler : IRequestHandler<GetCustomerPurchaseHistoryQuery, GetCustomerPurchaseHistoryResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetCustomerPurchaseHistoryQueryHandler(
IApplicationDbContext context,
ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetCustomerPurchaseHistoryResponseDto> Handle(GetCustomerPurchaseHistoryQuery request, CancellationToken cancellationToken)
{
// Resolve UserId from JWT if not specified
var userId = request.UserId == 0
? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
: request.UserId;
if (userId == 0)
throw new UnauthorizedAccessException("User ID not found");
var query = _context.UserOrders
.AsNoTracking()
.Where(x => x.UserId == userId && x.PackageId != null)
.Include(x => x.Package)
.AsQueryable();
// Apply date filters if specified
if (request.FromDate.HasValue)
query = query.Where(x => x.Created >= request.FromDate.Value);
if (request.ToDate.HasValue)
query = query.Where(x => x.Created <= request.ToDate.Value);
// Apply PackageType filter if needed (Package entity doesn't have Type enum currently)
// This would require Package entity to have a PackageType field
// Order by most recent first
query = query.OrderByDescending(x => x.Created);
// Get metadata
var metaData = await query.GetMetaData(request.PaginationState, cancellationToken);
// Get paginated results
var orders = await query
.PaginatedListAsync(request.PaginationState)
.ToListAsync(cancellationToken);
var purchases = orders.Select(order => new PackagePurchaseHistoryDto
{
Id = order.Id,
PackageId = order.PackageId ?? 0,
PackageName = order.Package?.Title ?? "نامشخص",
Amount = order.Amount,
PackageType = 0, // Default, needs Package.PackageType field
PurchaseDate = order.Created,
ExpiryDate = order.PaymentDate?.AddDays(365), // Assuming 1 year validity
Status = order.PaymentStatus,
StatusMessage = GetStatusMessage(order.PaymentStatus),
ReferenceCode = order.Transaction?.RefId ?? order.Id.ToString()
}).ToList();
return new GetCustomerPurchaseHistoryResponseDto
{
MetaData = metaData,
Purchases = purchases
};
}
private string GetStatusMessage(PaymentStatus status)
{
return status switch
{
PaymentStatus.Pending => "در انتظار پرداخت",
PaymentStatus.Success => "فعال",
PaymentStatus.Reject => "رد شده",
_ => "نامشخص"
};
}
}
@@ -0,0 +1,24 @@
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPurchaseHistory;
public class GetCustomerPurchaseHistoryResponseDto
{
public MetaData MetaData { get; set; }
public List<PackagePurchaseHistoryDto> Purchases { get; set; } = new();
}
public class PackagePurchaseHistoryDto
{
public long Id { get; set; }
public long PackageId { get; set; }
public string PackageName { get; set; }
public long Amount { get; set; }
public int PackageType { get; set; }
public DateTime PurchaseDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public PaymentStatus Status { get; set; }
public string StatusMessage { get; set; }
public string ReferenceCode { get; set; }
}
@@ -0,0 +1,10 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.AddProductImage;
public record AddProductImageCommand : IRequest<AddProductImageResponseDto>
{
public long ProductId { get; init; }
public string Title { get; init; } = string.Empty;
public byte[]? ImageFileBytes { get; init; }
public string? ImageFileMime { get; init; }
public string? ImageFileName { get; init; }
}
@@ -0,0 +1,86 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.ProductsCQ.Commands.AddProductImage;
public class AddProductImageCommandHandler : IRequestHandler<AddProductImageCommand, AddProductImageResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly IFileManagementService _fileManagementService;
private readonly ILogger<AddProductImageCommandHandler> _logger;
public AddProductImageCommandHandler(
IApplicationDbContext context,
IFileManagementService fileManagementService,
ILogger<AddProductImageCommandHandler> logger)
{
_context = context;
_fileManagementService = fileManagementService;
_logger = logger;
}
public async Task<AddProductImageResponseDto> Handle(AddProductImageCommand request,
CancellationToken cancellationToken)
{
// Verify product exists
var productExists = await _context.Products
.AnyAsync(p => p.Id == request.ProductId, cancellationToken);
if (!productExists)
throw new NotFoundException(nameof(Product), request.ProductId);
string imagePath = string.Empty;
string thumbnailPath = string.Empty;
// Upload image to FMS
if (request.ImageFileBytes is { Length: > 0 })
{
try
{
var (mainPath, thumbPath) = await _fileManagementService.UploadImageWithThumbnailAsync(
"Images/Products/Gallery",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
imagePath = mainPath ?? string.Empty;
thumbnailPath = thumbPath ?? string.Empty;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload gallery image to FMS for product {ProductId}", request.ProductId);
}
}
// Create ProductImage entity
var productImage = new ProductImage
{
Title = request.Title,
ImagePath = imagePath,
ImageThumbnailPath = thumbnailPath
};
await _context.ProductImages.AddAsync(productImage, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
// Create ProductGallery join entity
var productGallery = new ProductGallery
{
ProductId = request.ProductId,
ProductImageId = productImage.Id
};
await _context.ProductGalleries.AddAsync(productGallery, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
return new AddProductImageResponseDto
{
ProductGalleryId = productGallery.Id,
ProductImageId = productImage.Id,
Title = productImage.Title,
ImagePath = productImage.ImagePath,
ImageThumbnailPath = productImage.ImageThumbnailPath
};
}
}
@@ -0,0 +1,10 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.AddProductImage;
public class AddProductImageResponseDto
{
public long ProductGalleryId { get; set; }
public long ProductImageId { get; set; }
public string Title { get; set; } = string.Empty;
public string ImagePath { get; set; } = string.Empty;
public string ImageThumbnailPath { get; set; } = string.Empty;
}
@@ -0,0 +1,26 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.CreateNewProducts;
public record CreateNewProductsCommand : IRequest<CreateNewProductsResponseDto>
{
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string ShortInfomation { get; init; } = string.Empty;
public string FullInformation { get; init; } = string.Empty;
public long Price { get; init; }
public int Discount { get; init; }
public int Rate { get; init; }
public string? ImagePath { get; init; }
public string? ThumbnailPath { get; init; }
public int SaleCount { get; init; }
public int ViewCount { get; init; }
public int RemainingCount { get; init; }
public List<long> CategoryIds { get; init; } = new();
// File upload fields (raw bytes from client)
public byte[]? ImageFileBytes { get; init; }
public string? ImageFileMime { get; init; }
public string? ImageFileName { get; init; }
public byte[]? ThumbnailFileBytes { get; init; }
public string? ThumbnailFileMime { get; init; }
public string? ThumbnailFileName { get; init; }
}
@@ -0,0 +1,112 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.ProductsCQ.Commands.CreateNewProducts;
public class CreateNewProductsCommandHandler : IRequestHandler<CreateNewProductsCommand, CreateNewProductsResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly IFileManagementService _fileManagementService;
private readonly ILogger<CreateNewProductsCommandHandler> _logger;
public CreateNewProductsCommandHandler(
IApplicationDbContext context,
IFileManagementService fileManagementService,
ILogger<CreateNewProductsCommandHandler> logger)
{
_context = context;
_fileManagementService = fileManagementService;
_logger = logger;
}
public async Task<CreateNewProductsResponseDto> Handle(CreateNewProductsCommand request,
CancellationToken cancellationToken)
{
var entity = new Product
{
Title = request.Title,
Description = request.Description,
ShortInfomation = request.ShortInfomation,
FullInformation = request.FullInformation,
Price = request.Price,
Discount = request.Discount,
Rate = request.Rate,
ImagePath = request.ImagePath ?? string.Empty,
ThumbnailPath = request.ThumbnailPath ?? string.Empty,
SaleCount = request.SaleCount,
ViewCount = request.ViewCount,
RemainingCount = request.RemainingCount
};
// Handle image upload to FMS if file bytes provided
if (request.ImageFileBytes is { Length: > 0 })
{
try
{
var (mainPath, thumbPath) = await _fileManagementService.UploadImageWithThumbnailAsync(
"Images/Products",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
if (!string.IsNullOrWhiteSpace(mainPath))
entity.ImagePath = mainPath;
if (!string.IsNullOrWhiteSpace(thumbPath))
entity.ThumbnailPath = thumbPath;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload product image to FMS");
}
}
// Handle separate thumbnail upload if provided (and not already set from main image)
if (request.ThumbnailFileBytes is { Length: > 0 } && string.IsNullOrWhiteSpace(entity.ThumbnailPath))
{
try
{
var thumbPath = await _fileManagementService.UploadFileAsync(
"Images/Products/Thumbnails",
request.ThumbnailFileBytes,
request.ThumbnailFileMime ?? "image/jpeg",
request.ThumbnailFileName,
cancellationToken);
if (!string.IsNullOrWhiteSpace(thumbPath))
entity.ThumbnailPath = thumbPath;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload product thumbnail to FMS");
}
}
await _context.Products.AddAsync(entity, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
// Handle category assignments
if (request.CategoryIds is { Count: > 0 })
{
foreach (var categoryId in request.CategoryIds)
{
var categoryExists = await _context.Categories
.AnyAsync(c => c.Id == categoryId, cancellationToken);
if (categoryExists)
{
await _context.ProductCategories.AddAsync(new ProductCategory
{
ProductId = entity.Id,
CategoryId = categoryId
}, cancellationToken);
}
}
await _context.SaveChangesAsync(cancellationToken);
}
return new CreateNewProductsResponseDto { Id = entity.Id };
}
}
@@ -0,0 +1,26 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.CreateNewProducts;
public class CreateNewProductsCommandValidator : AbstractValidator<CreateNewProductsCommand>
{
public CreateNewProductsCommandValidator()
{
RuleFor(model => model.Title)
.NotEmpty().WithMessage("عنوان محصول الزامی است");
RuleFor(model => model.Price)
.GreaterThanOrEqualTo(0).WithMessage("قیمت نمی‌تواند منفی باشد");
RuleFor(model => model.Discount)
.InclusiveBetween(0, 100).WithMessage("تخفیف باید بین 0 تا 100 باشد");
}
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(
ValidationContext<CreateNewProductsCommand>.CreateWithOptions(
(CreateNewProductsCommand)model, x => x.IncludeProperties(propertyName)));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}
@@ -0,0 +1,6 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.CreateNewProducts;
public class CreateNewProductsResponseDto
{
public long Id { get; set; }
}
@@ -0,0 +1,6 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.DeleteProducts;
public record DeleteProductsCommand : IRequest<Unit>
{
public long Id { get; init; }
}
@@ -0,0 +1,38 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
namespace CMSMicroservice.Application.ProductsCQ.Commands.DeleteProducts;
public class DeleteProductsCommandHandler : IRequestHandler<DeleteProductsCommand, Unit>
{
private readonly IApplicationDbContext _context;
public DeleteProductsCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(DeleteProductsCommand request, CancellationToken cancellationToken)
{
var entity = await _context.Products
.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken)
?? throw new NotFoundException(nameof(Product), request.Id);
// Remove category associations
var productCategories = await _context.ProductCategories
.Where(pc => pc.ProductId == entity.Id)
.ToListAsync(cancellationToken);
_context.ProductCategories.RemoveRange(productCategories);
// Remove gallery associations
var productGalleries = await _context.ProductGalleries
.Where(pg => pg.ProductId == entity.Id)
.ToListAsync(cancellationToken);
_context.ProductGalleries.RemoveRange(productGalleries);
_context.Products.Remove(entity);
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,6 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.RemoveProductImage;
public record RemoveProductImageCommand : IRequest<Unit>
{
public long ProductGalleryId { get; init; }
}
@@ -0,0 +1,40 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
namespace CMSMicroservice.Application.ProductsCQ.Commands.RemoveProductImage;
public class RemoveProductImageCommandHandler : IRequestHandler<RemoveProductImageCommand, Unit>
{
private readonly IApplicationDbContext _context;
public RemoveProductImageCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(RemoveProductImageCommand request, CancellationToken cancellationToken)
{
var gallery = await _context.ProductGalleries
.Include(pg => pg.ProductImage)
.FirstOrDefaultAsync(pg => pg.Id == request.ProductGalleryId, cancellationToken)
?? throw new NotFoundException(nameof(ProductGallery), request.ProductGalleryId);
// Remove gallery entry
_context.ProductGalleries.Remove(gallery);
// Remove the product image if it exists and is not referenced by other galleries
if (gallery.ProductImage != null)
{
var otherReferences = await _context.ProductGalleries
.AnyAsync(pg => pg.ProductImageId == gallery.ProductImageId && pg.Id != gallery.Id, cancellationToken);
if (!otherReferences)
{
_context.ProductImages.Remove(gallery.ProductImage);
}
}
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,27 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.UpdateProducts;
public record UpdateProductsCommand : IRequest<Unit>
{
public long Id { get; init; }
public string Title { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string ShortInfomation { get; init; } = string.Empty;
public string FullInformation { get; init; } = string.Empty;
public long Price { get; init; }
public int Discount { get; init; }
public int Rate { get; init; }
public string? ImagePath { get; init; }
public string? ThumbnailPath { get; init; }
public int SaleCount { get; init; }
public int ViewCount { get; init; }
public int RemainingCount { get; init; }
public List<long> CategoryIds { get; init; } = new();
// File upload fields (raw bytes from client)
public byte[]? ImageFileBytes { get; init; }
public string? ImageFileMime { get; init; }
public string? ImageFileName { get; init; }
public byte[]? ThumbnailFileBytes { get; init; }
public string? ThumbnailFileMime { get; init; }
public string? ThumbnailFileName { get; init; }
}
@@ -0,0 +1,127 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.ProductsCQ.Commands.UpdateProducts;
public class UpdateProductsCommandHandler : IRequestHandler<UpdateProductsCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly IFileManagementService _fileManagementService;
private readonly ILogger<UpdateProductsCommandHandler> _logger;
public UpdateProductsCommandHandler(
IApplicationDbContext context,
IFileManagementService fileManagementService,
ILogger<UpdateProductsCommandHandler> logger)
{
_context = context;
_fileManagementService = fileManagementService;
_logger = logger;
}
public async Task<Unit> Handle(UpdateProductsCommand request, CancellationToken cancellationToken)
{
var entity = await _context.Products
.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken)
?? throw new NotFoundException(nameof(Product), request.Id);
// Update basic properties
entity.Title = request.Title;
entity.Description = request.Description;
entity.ShortInfomation = request.ShortInfomation;
entity.FullInformation = request.FullInformation;
entity.Price = request.Price;
entity.Discount = request.Discount;
entity.Rate = request.Rate;
entity.SaleCount = request.SaleCount;
entity.ViewCount = request.ViewCount;
entity.RemainingCount = request.RemainingCount;
// Handle image upload to FMS if new file bytes provided
if (request.ImageFileBytes is { Length: > 0 })
{
try
{
var (mainPath, thumbPath) = await _fileManagementService.UploadImageWithThumbnailAsync(
"Images/Products",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
if (!string.IsNullOrWhiteSpace(mainPath))
entity.ImagePath = mainPath;
if (!string.IsNullOrWhiteSpace(thumbPath))
entity.ThumbnailPath = thumbPath;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload updated product image to FMS for product {ProductId}", request.Id);
}
}
else
{
// If no new file uploaded, keep existing paths or update from request
if (!string.IsNullOrWhiteSpace(request.ImagePath))
entity.ImagePath = request.ImagePath;
if (!string.IsNullOrWhiteSpace(request.ThumbnailPath))
entity.ThumbnailPath = request.ThumbnailPath;
}
// Handle separate thumbnail upload if provided
if (request.ThumbnailFileBytes is { Length: > 0 })
{
try
{
var thumbPath = await _fileManagementService.UploadFileAsync(
"Images/Products/Thumbnails",
request.ThumbnailFileBytes,
request.ThumbnailFileMime ?? "image/jpeg",
request.ThumbnailFileName,
cancellationToken);
if (!string.IsNullOrWhiteSpace(thumbPath))
entity.ThumbnailPath = thumbPath;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to upload updated product thumbnail to FMS for product {ProductId}", request.Id);
}
}
_context.Products.Update(entity);
await _context.SaveChangesAsync(cancellationToken);
// Update category assignments
if (request.CategoryIds != null)
{
// Remove existing categories
var existingCategories = await _context.ProductCategories
.Where(pc => pc.ProductId == entity.Id)
.ToListAsync(cancellationToken);
_context.ProductCategories.RemoveRange(existingCategories);
// Add new categories
foreach (var categoryId in request.CategoryIds)
{
var categoryExists = await _context.Categories
.AnyAsync(c => c.Id == categoryId, cancellationToken);
if (categoryExists)
{
await _context.ProductCategories.AddAsync(new ProductCategory
{
ProductId = entity.Id,
CategoryId = categoryId
}, cancellationToken);
}
}
await _context.SaveChangesAsync(cancellationToken);
}
return Unit.Value;
}
}
@@ -0,0 +1,29 @@
namespace CMSMicroservice.Application.ProductsCQ.Commands.UpdateProducts;
public class UpdateProductsCommandValidator : AbstractValidator<UpdateProductsCommand>
{
public UpdateProductsCommandValidator()
{
RuleFor(model => model.Id)
.NotNull().WithMessage("شناسه محصول الزامی است");
RuleFor(model => model.Title)
.NotEmpty().WithMessage("عنوان محصول الزامی است");
RuleFor(model => model.Price)
.GreaterThanOrEqualTo(0).WithMessage("قیمت نمی‌تواند منفی باشد");
RuleFor(model => model.Discount)
.InclusiveBetween(0, 100).WithMessage("تخفیف باید بین 0 تا 100 باشد");
}
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(
ValidationContext<UpdateProductsCommand>.CreateWithOptions(
(UpdateProductsCommand)model, x => x.IncludeProperties(propertyName)));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}
@@ -1,69 +0,0 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CMSMicroservice.Application.Common.Interfaces;
using Mapster;
using MediatR;
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetAllProductsByFilter;
public class
GetAllProductsByFilterQueryHandler : IRequestHandler<GetAllProductsByFilterQuery, GetAllProductsByFilterResponseDto>
{
private readonly IApplicationDbContext _context;
public GetAllProductsByFilterQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllProductsByFilterResponseDto> Handle(GetAllProductsByFilterQuery request,
CancellationToken cancellationToken)
{
var grpcRequest = new CmsProductsProtos.GetAllProductsByFilterRequest
{
PaginationState = request.PaginationState is { } pagination
? new CmsPaginationState
{
PageNumber = pagination.PageNumber,
PageSize = pagination.PageSize
}
: null,
SortBy = request.SortBy,
Filter = BuildFilter(request.Filter)
};
var result = await _context.Product.GetAllProductsByFilterAsync(grpcRequest,
cancellationToken: cancellationToken);
if (request.Filter?.CategoryId is { } categoryId)
{
var matchingModels = result.Models
.Where(model => model.CategoryIds.Contains(categoryId))
.ToList();
result.Models.Clear();
result.Models.AddRange(matchingModels);
}
return result.Adapt<GetAllProductsByFilterResponseDto>();
}
private static CmsProductsProtos.GetAllProductsByFilterFilter? BuildFilter(GetAllProductsByFilterFilter? filter)
{
if (filter is null)
{
return null;
}
return new CmsProductsProtos.GetAllProductsByFilterFilter
{
Id = filter.Id,
Title = filter.Title,
Description = filter.Description,
ShortInfomation = filter.ShortInfomation,
FullInformation = filter.FullInformation,
Price = filter.Price,
Discount = filter.Discount,
Rate = filter.Rate
};
}
}
@@ -0,0 +1,6 @@
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetCustomerProducts;
public class GetCustomerProductsQuery : IRequest<GetCustomerProductsResponseDto>
{
public long Id { get; set; }
}
@@ -0,0 +1,91 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetCustomerProducts;
public class GetCustomerProductsQueryHandler : IRequestHandler<GetCustomerProductsQuery, GetCustomerProductsResponseDto>
{
private readonly IApplicationDbContext _context;
public GetCustomerProductsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetCustomerProductsResponseDto> Handle(GetCustomerProductsQuery request, CancellationToken cancellationToken)
{
var product = await _context.Products
.AsNoTracking()
.Where(x => x.Id == request.Id)
.Include(x => x.ProductGalleries)
.ThenInclude(pg => pg.ProductImage)
.Include(x => x.ProductCategories)
.ThenInclude(pc => pc.Category)
.FirstOrDefaultAsync(cancellationToken);
if (product == null)
throw new NotFoundException(nameof(Product), request.Id);
var response = new GetCustomerProductsResponseDto
{
Id = product.Id,
Title = product.Title,
Description = product.Description,
ShortInfomation = product.ShortInfomation,
FullInformation = product.FullInformation,
Price = product.Price,
Discount = product.Discount,
Rate = product.Rate,
ImagePath = product.ImagePath,
ThumbnailPath = product.ThumbnailPath,
SaleCount = product.SaleCount,
ViewCount = product.ViewCount,
RemainingCount = product.RemainingCount,
Gallery = product.ProductGalleries?.Select(pg => new ProductGalleryModel
{
ProductGalleryId = pg.Id,
ProductImageId = pg.ProductImageId,
Title = pg.ProductImage?.Title ?? string.Empty,
ImagePath = pg.ProductImage?.ImagePath ?? string.Empty,
ImageThumbnailPath = pg.ProductImage?.ImageThumbnailPath ?? string.Empty
}).ToList() ?? new List<ProductGalleryModel>(),
Categories = product.ProductCategories?.Select(pc => new ProductCategoryModel
{
CategoryId = pc.CategoryId,
Title = pc.Category?.Title ?? string.Empty,
Path = BuildCategoryPath(pc.Category)
}).ToList() ?? new List<ProductCategoryModel>()
};
return response;
}
private List<CategoryNodeModel> BuildCategoryPath(Category? category)
{
var path = new List<CategoryNodeModel>();
while (category != null)
{
path.Insert(0, new CategoryNodeModel
{
Id = category.Id,
Title = category.Title,
ParentId = category.ParentId
});
// Move to parent
if (category.ParentId.HasValue)
{
category = _context.Categories
.AsNoTracking()
.FirstOrDefault(c => c.Id == category.ParentId.Value);
}
else
{
category = null;
}
}
return path;
}
}
@@ -0,0 +1,43 @@
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetCustomerProducts;
public class GetCustomerProductsResponseDto
{
public long Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ShortInfomation { get; set; }
public string FullInformation { get; set; }
public long Price { get; set; }
public int Discount { get; set; }
public int Rate { get; set; }
public string ImagePath { get; set; }
public string ThumbnailPath { get; set; }
public int SaleCount { get; set; }
public int ViewCount { get; set; }
public int RemainingCount { get; set; }
public List<ProductGalleryModel> Gallery { get; set; }
public List<ProductCategoryModel> Categories { get; set; }
}
public class ProductGalleryModel
{
public long ProductGalleryId { get; set; }
public long ProductImageId { get; set; }
public string Title { get; set; }
public string ImagePath { get; set; }
public string ImageThumbnailPath { get; set; }
}
public class ProductCategoryModel
{
public long CategoryId { get; set; }
public string Title { get; set; }
public List<CategoryNodeModel> Path { get; set; }
}
public class CategoryNodeModel
{
public long Id { get; set; }
public string Title { get; set; }
public long? ParentId { get; set; }
}
@@ -0,0 +1,25 @@
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetCustomerProductsByFilter;
public class GetCustomerProductsByFilterQuery : IRequest<GetCustomerProductsByFilterResponseDto>
{
public PaginationState? PaginationState { get; set; }
public string? SortBy { get; set; }
// Filters
public long? Id { get; set; }
public string? Title { get; set; }
public string? Description { get; set; }
public string? ShortInfomation { get; set; }
public string? FullInformation { get; set; }
public long? Price { get; set; }
public int? Discount { get; set; }
public int? Rate { get; set; }
public string? ImagePath { get; set; }
public string? ThumbnailPath { get; set; }
public int? SaleCount { get; set; }
public int? ViewCount { get; set; }
public int? RemainingCount { get; set; }
public List<long>? CategoryIds { get; set; }
}
@@ -0,0 +1,145 @@
using CMSMicroservice.Application.Common.Extensions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Entities;
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetCustomerProductsByFilter;
public class GetCustomerProductsByFilterQueryHandler : IRequestHandler<GetCustomerProductsByFilterQuery, GetCustomerProductsByFilterResponseDto>
{
private readonly IApplicationDbContext _context;
public GetCustomerProductsByFilterQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetCustomerProductsByFilterResponseDto> Handle(GetCustomerProductsByFilterQuery request, CancellationToken cancellationToken)
{
var query = _context.Products
.AsNoTracking()
.Include(x => x.ProductCategories)
.ThenInclude(pc => pc.Category)
.AsQueryable();
// Apply filters
if (request.Id.HasValue)
query = query.Where(x => x.Id == request.Id.Value);
if (!string.IsNullOrEmpty(request.Title))
query = query.Where(x => x.Title.Contains(request.Title));
if (!string.IsNullOrEmpty(request.Description))
query = query.Where(x => x.Description.Contains(request.Description));
if (!string.IsNullOrEmpty(request.ShortInfomation))
query = query.Where(x => x.ShortInfomation.Contains(request.ShortInfomation));
if (!string.IsNullOrEmpty(request.FullInformation))
query = query.Where(x => x.FullInformation.Contains(request.FullInformation));
if (request.Price.HasValue)
query = query.Where(x => x.Price == request.Price.Value);
if (request.Discount.HasValue)
query = query.Where(x => x.Discount == request.Discount.Value);
if (request.Rate.HasValue)
query = query.Where(x => x.Rate == request.Rate.Value);
if (request.SaleCount.HasValue)
query = query.Where(x => x.SaleCount == request.SaleCount.Value);
if (request.ViewCount.HasValue)
query = query.Where(x => x.ViewCount == request.ViewCount.Value);
if (request.RemainingCount.HasValue)
query = query.Where(x => x.RemainingCount == request.RemainingCount.Value);
if (request.CategoryIds != null && request.CategoryIds.Any())
query = query.Where(x => x.ProductCategories.Any(pc => request.CategoryIds.Contains(pc.CategoryId)));
// Apply sorting
if (!string.IsNullOrEmpty(request.SortBy))
query = query.ApplyOrder(request.SortBy);
else
query = query.OrderByDescending(x => x.Created);
// Pagination
var totalCount = await query.CountAsync(cancellationToken);
var paginationState = request.PaginationState ?? new PaginationState { PageNumber = 1, PageSize = 10 };
var products = await query
.Skip((paginationState.PageNumber - 1) * paginationState.PageSize)
.Take(paginationState.PageSize)
.ToListAsync(cancellationToken);
var metaData = new MetaData
{
TotalCount = totalCount,
CurrentPage = paginationState.PageNumber,
PageSize = paginationState.PageSize,
TotalPage = (int)Math.Ceiling((double)totalCount / paginationState.PageSize),
HasPrevious = paginationState.PageNumber > 1,
HasNext = paginationState.PageNumber < (int)Math.Ceiling((double)totalCount / paginationState.PageSize)
};
var models = products.Select(p => new CustomerProductModel
{
Id = p.Id,
Title = p.Title,
Description = p.Description,
ShortInfomation = p.ShortInfomation,
FullInformation = p.FullInformation,
Price = p.Price,
Discount = p.Discount,
Rate = p.Rate,
ImagePath = p.ImagePath,
ThumbnailPath = p.ThumbnailPath,
SaleCount = p.SaleCount,
ViewCount = p.ViewCount,
RemainingCount = p.RemainingCount,
Categories = p.ProductCategories?.Select(pc => new ProductCategoryPathModel
{
CategoryId = pc.CategoryId,
Title = pc.Category?.Title ?? string.Empty,
Path = BuildCategoryPath(pc.Category)
}).ToList() ?? new List<ProductCategoryPathModel>()
}).ToList();
return new GetCustomerProductsByFilterResponseDto
{
MetaData = metaData,
Models = models
};
}
private List<CategoryNodeItemModel> BuildCategoryPath(Category? category)
{
var path = new List<CategoryNodeItemModel>();
while (category != null)
{
path.Insert(0, new CategoryNodeItemModel
{
Id = category.Id,
Title = category.Title,
ParentId = category.ParentId
});
// Move to parent
if (category.ParentId.HasValue)
{
category = _context.Categories
.AsNoTracking()
.FirstOrDefault(c => c.Id == category.ParentId.Value);
}
else
{
category = null;
}
}
return path;
}
}
@@ -0,0 +1,41 @@
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetCustomerProductsByFilter;
public class GetCustomerProductsByFilterResponseDto
{
public MetaData MetaData { get; set; }
public List<CustomerProductModel> Models { get; set; }
}
public class CustomerProductModel
{
public long Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ShortInfomation { get; set; }
public string FullInformation { get; set; }
public long Price { get; set; }
public int Discount { get; set; }
public int Rate { get; set; }
public string ImagePath { get; set; }
public string ThumbnailPath { get; set; }
public int SaleCount { get; set; }
public int ViewCount { get; set; }
public int RemainingCount { get; set; }
public List<ProductCategoryPathModel> Categories { get; set; }
}
public class ProductCategoryPathModel
{
public long CategoryId { get; set; }
public string Title { get; set; }
public List<CategoryNodeItemModel> Path { get; set; }
}
public class CategoryNodeItemModel
{
public long Id { get; set; }
public string Title { get; set; }
public long? ParentId { get; set; }
}
@@ -0,0 +1,6 @@
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetProductGallery;
public class GetProductGalleryQuery : IRequest<GetProductGalleryResponseDto>
{
public long ProductId { get; set; }
}
@@ -0,0 +1,34 @@
using CMSMicroservice.Application.Common.Interfaces;
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetProductGallery;
public class GetProductGalleryQueryHandler : IRequestHandler<GetProductGalleryQuery, GetProductGalleryResponseDto>
{
private readonly IApplicationDbContext _context;
public GetProductGalleryQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetProductGalleryResponseDto> Handle(GetProductGalleryQuery request, CancellationToken cancellationToken)
{
var galleries = await _context.ProductGalleries
.AsNoTracking()
.Where(pg => pg.ProductId == request.ProductId)
.Include(pg => pg.ProductImage)
.ToListAsync(cancellationToken);
return new GetProductGalleryResponseDto
{
Items = galleries.Select(pg => new ProductGalleryItemDto
{
ProductGalleryId = pg.Id,
ProductImageId = pg.ProductImageId,
Title = pg.ProductImage?.Title ?? string.Empty,
ImagePath = pg.ProductImage?.ImagePath ?? string.Empty,
ImageThumbnailPath = pg.ProductImage?.ImageThumbnailPath ?? string.Empty
}).ToList()
};
}
}
@@ -0,0 +1,15 @@
namespace CMSMicroservice.Application.ProductsCQ.Queries.GetProductGallery;
public class GetProductGalleryResponseDto
{
public List<ProductGalleryItemDto> Items { get; set; } = new();
}
public class ProductGalleryItemDto
{
public long ProductGalleryId { get; set; }
public long ProductImageId { get; set; }
public string Title { get; set; } = string.Empty;
public string ImagePath { get; set; } = string.Empty;
public string ImageThumbnailPath { get; set; } = string.Empty;
}
@@ -0,0 +1,8 @@
namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetCustomerTransaction;
public class GetCustomerTransactionQuery : IRequest<GetCustomerTransactionResponseDto>
{
public long? Id { get; set; }
public string Authority { get; set; }
public long UserId { get; set; }
}
@@ -0,0 +1,52 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetCustomerTransaction;
public class GetCustomerTransactionQueryHandler : IRequestHandler<GetCustomerTransactionQuery, GetCustomerTransactionResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetCustomerTransactionQueryHandler(
IApplicationDbContext context,
ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetCustomerTransactionResponseDto> Handle(GetCustomerTransactionQuery request, CancellationToken cancellationToken)
{
// Resolve UserId from JWT if not specified
var userId = request.UserId == 0
? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
: request.UserId;
if (userId == 0)
throw new UnauthorizedAccessException("User ID not found");
// Transaction entity doesn't have UserId, so we need to find it through UserOrders
var transaction = await _context.Transactions
.AsNoTracking()
.Where(x => request.Id.HasValue ? x.Id == request.Id.Value : true)
.Include(x => x.UserOrders)
.Where(x => x.UserOrders.Any(o => o.UserId == userId))
.FirstOrDefaultAsync(cancellationToken);
if (transaction == null)
throw new NotFoundException(nameof(Transaction), request.Id ?? 0);
return new GetCustomerTransactionResponseDto
{
Id = transaction.Id,
Amount = transaction.Amount,
Description = transaction.Description ?? "",
PaymentStatus = transaction.PaymentStatus,
PaymentDate = transaction.PaymentDate,
RefId = transaction.RefId ?? "",
Type = transaction.Type
};
}
}
@@ -0,0 +1,14 @@
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetCustomerTransaction;
public class GetCustomerTransactionResponseDto
{
public long Id { get; set; }
public long Amount { get; set; }
public string Description { get; set; }
public PaymentStatus PaymentStatus { get; set; }
public DateTime? PaymentDate { get; set; }
public string RefId { get; set; }
public TransactionType Type { get; set; }
}
@@ -0,0 +1,16 @@
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetCustomerTransactionsByFilter;
public class GetCustomerTransactionsByFilterQuery : IRequest<GetCustomerTransactionsByFilterResponseDto>
{
public long UserId { get; set; }
public PaginationState PaginationState { get; set; }
public string SortBy { get; set; }
public long? IdFilter { get; set; }
public long? AmountFilter { get; set; }
public string DescriptionFilter { get; set; }
public bool? PaymentStatusFilter { get; set; }
public string RefIdFilter { get; set; }
public int? TypeFilter { get; set; }
}
@@ -0,0 +1,92 @@
using CMSMicroservice.Application.Common.Extensions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetCustomerTransactionsByFilter;
public class GetCustomerTransactionsByFilterQueryHandler : IRequestHandler<GetCustomerTransactionsByFilterQuery, GetCustomerTransactionsByFilterResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetCustomerTransactionsByFilterQueryHandler(
IApplicationDbContext context,
ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetCustomerTransactionsByFilterResponseDto> Handle(GetCustomerTransactionsByFilterQuery request, CancellationToken cancellationToken)
{
// Resolve UserId from JWT if not specified
var userId = request.UserId == 0
? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
: request.UserId;
if (userId == 0)
throw new UnauthorizedAccessException("User ID not found");
// Transaction doesn't have UserId, find through UserOrders
var query = _context.Transactions
.AsNoTracking()
.Include(x => x.UserOrders)
.Where(x => x.UserOrders.Any(o => o.UserId == userId))
.AsQueryable();
// Apply filters
if (request.IdFilter.HasValue)
query = query.Where(x => x.Id == request.IdFilter.Value);
if (request.AmountFilter.HasValue)
query = query.Where(x => x.Amount == request.AmountFilter.Value);
if (!string.IsNullOrEmpty(request.DescriptionFilter))
query = query.Where(x => x.Description.Contains(request.DescriptionFilter));
if (request.PaymentStatusFilter.HasValue)
{
var status = request.PaymentStatusFilter.Value
? Domain.Enums.PaymentStatus.Success
: Domain.Enums.PaymentStatus.Reject;
query = query.Where(x => x.PaymentStatus == status);
}
if (!string.IsNullOrEmpty(request.RefIdFilter))
query = query.Where(x => x.RefId == request.RefIdFilter);
if (request.TypeFilter.HasValue)
query = query.Where(x => (int)x.Type == request.TypeFilter.Value);
// Apply sorting
if (!string.IsNullOrEmpty(request.SortBy))
query = query.ApplyOrder(request.SortBy);
else
query = query.OrderByDescending(x => x.Created);
// Get metadata
var metaData = await query.GetMetaData(request.PaginationState, cancellationToken);
// Get paginated results
var transactions = await query
.PaginatedListAsync(request.PaginationState)
.ToListAsync(cancellationToken);
var models = transactions.Select(t => new CustomerTransactionModel
{
Id = t.Id,
Amount = t.Amount,
Description = t.Description ?? "",
PaymentStatus = t.PaymentStatus,
PaymentDate = t.PaymentDate,
RefId = t.RefId ?? "",
Type = t.Type
}).ToList();
return new GetCustomerTransactionsByFilterResponseDto
{
MetaData = metaData,
Models = models
};
}
}
@@ -0,0 +1,21 @@
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.TransactionsCQ.Queries.GetCustomerTransactionsByFilter;
public class GetCustomerTransactionsByFilterResponseDto
{
public MetaData MetaData { get; set; }
public List<CustomerTransactionModel> Models { get; set; } = new();
}
public class CustomerTransactionModel
{
public long Id { get; set; }
public long Amount { get; set; }
public string Description { get; set; }
public PaymentStatus PaymentStatus { get; set; }
public DateTime? PaymentDate { get; set; }
public string RefId { get; set; }
public TransactionType Type { get; set; }
}
@@ -0,0 +1,22 @@
using MediatR;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.CreateCustomerAddress;
/// <summary>
/// Command برای ایجاد آدرس جدید برای کاربر فعلی
/// </summary>
public class CreateCustomerAddressCommand : IRequest<CreateCustomerAddressCommandResponse>
{
public string Title { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public string PostalCode { get; set; } = string.Empty;
public bool IsDefault { get; set; }
public long CityId { get; set; }
// UserId from ICurrentUserService
}
public class CreateCustomerAddressCommandResponse
{
public long Id { get; set; }
public string Message { get; set; } = string.Empty;
}
@@ -0,0 +1,62 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.CreateCustomerAddress;
public class CreateCustomerAddressCommandHandler : IRequestHandler<CreateCustomerAddressCommand, CreateCustomerAddressCommandResponse>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public CreateCustomerAddressCommandHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<CreateCustomerAddressCommandResponse> Handle(CreateCustomerAddressCommand request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// If this address is set as default, unset other defaults
if (request.IsDefault)
{
var existingDefaults = await _context.UserAddresses
.Where(ua => ua.UserId == userId && ua.IsDefault && !ua.IsDeleted)
.ToListAsync(cancellationToken);
foreach (var addr in existingDefaults)
{
addr.IsDefault = false;
}
}
// Create new address
var address = new UserAddress
{
UserId = userId,
Title = request.Title,
Address = request.Address,
PostalCode = request.PostalCode,
IsDefault = request.IsDefault,
CityId = request.CityId,
Created = DateTime.UtcNow
};
_context.UserAddresses.Add(address);
await _context.SaveChangesAsync(cancellationToken);
return new CreateCustomerAddressCommandResponse
{
Id = address.Id,
Message = "آدرس با موفقیت ایجاد شد"
};
}
}
@@ -0,0 +1,12 @@
using MediatR;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.DeleteCustomerAddress;
/// <summary>
/// Command برای حذف آدرس کاربر فعلی
/// </summary>
public class DeleteCustomerAddressCommand : IRequest<Unit>
{
public long Id { get; set; }
// UserId from ICurrentUserService
}
@@ -0,0 +1,45 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.DeleteCustomerAddress;
public class DeleteCustomerAddressCommandHandler : IRequestHandler<DeleteCustomerAddressCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public DeleteCustomerAddressCommandHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<Unit> Handle(DeleteCustomerAddressCommand request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// Find address and verify ownership
var address = await _context.UserAddresses
.FirstOrDefaultAsync(ua => ua.Id == request.Id && ua.UserId == userId && !ua.IsDeleted, cancellationToken);
if (address == null)
{
throw new Exception("آدرس یافت نشد یا به شما تعلق ندارد");
}
// Soft delete
address.IsDeleted = true;
address.LastModified = DateTime.UtcNow;
_context.UserAddresses.Update(address);
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,12 @@
using MediatR;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.SetCustomerDefaultAddress;
/// <summary>
/// Command برای تنظیم آدرس پیش‌فرض کاربر فعلی
/// </summary>
public class SetCustomerDefaultAddressCommand : IRequest<Unit>
{
public long Id { get; set; }
// UserId from ICurrentUserService
}
@@ -0,0 +1,55 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.SetCustomerDefaultAddress;
public class SetCustomerDefaultAddressCommandHandler : IRequestHandler<SetCustomerDefaultAddressCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public SetCustomerDefaultAddressCommandHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<Unit> Handle(SetCustomerDefaultAddressCommand request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// Find address and verify ownership
var address = await _context.UserAddresses
.FirstOrDefaultAsync(ua => ua.Id == request.Id && ua.UserId == userId && !ua.IsDeleted, cancellationToken);
if (address == null)
{
throw new Exception("آدرس یافت نشد یا به شما تعلق ندارد");
}
// Unset all other defaults for this user
var existingDefaults = await _context.UserAddresses
.Where(ua => ua.UserId == userId && ua.IsDefault && ua.Id != request.Id && !ua.IsDeleted)
.ToListAsync(cancellationToken);
foreach (var addr in existingDefaults)
{
addr.IsDefault = false;
}
// Set this address as default
address.IsDefault = true;
address.LastModified = DateTime.UtcNow;
_context.UserAddresses.Update(address);
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,17 @@
using MediatR;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.UpdateCustomerAddress;
/// <summary>
/// Command برای به‌روزرسانی آدرس کاربر فعلی
/// </summary>
public class UpdateCustomerAddressCommand : IRequest<Unit>
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public string PostalCode { get; set; } = string.Empty;
public bool IsDefault { get; set; }
public long CityId { get; set; }
// UserId from ICurrentUserService
}
@@ -0,0 +1,62 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.UpdateCustomerAddress;
public class UpdateCustomerAddressCommandHandler : IRequestHandler<UpdateCustomerAddressCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public UpdateCustomerAddressCommandHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<Unit> Handle(UpdateCustomerAddressCommand request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// Find address and verify ownership
var address = await _context.UserAddresses
.FirstOrDefaultAsync(ua => ua.Id == request.Id && ua.UserId == userId && !ua.IsDeleted, cancellationToken);
if (address == null)
{
throw new Exception("آدرس یافت نشد یا به شما تعلق ندارد");
}
// If setting as default, unset other defaults
if (request.IsDefault && !address.IsDefault)
{
var existingDefaults = await _context.UserAddresses
.Where(ua => ua.UserId == userId && ua.IsDefault && ua.Id != request.Id && !ua.IsDeleted)
.ToListAsync(cancellationToken);
foreach (var addr in existingDefaults)
{
addr.IsDefault = false;
}
}
// Update address
address.Title = request.Title;
address.Address = request.Address;
address.PostalCode = request.PostalCode;
address.IsDefault = request.IsDefault;
address.CityId = request.CityId;
address.LastModified = DateTime.UtcNow;
_context.UserAddresses.Update(address);
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,11 @@
using MediatR;
namespace CMSMicroservice.Application.UserAddressCQ.Queries.GetCustomerAddresses;
/// <summary>
/// Query برای دریافت لیست آدرس‌های کاربر فعلی
/// </summary>
public class GetCustomerAddressesQuery : IRequest<GetCustomerAddressesQueryResponse>
{
// UserId from ICurrentUserService
}
@@ -0,0 +1,53 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.UserAddressCQ.Queries.GetCustomerAddresses;
public class GetCustomerAddressesQueryHandler : IRequestHandler<GetCustomerAddressesQuery, GetCustomerAddressesQueryResponse>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetCustomerAddressesQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetCustomerAddressesQueryResponse> Handle(GetCustomerAddressesQuery request, CancellationToken cancellationToken)
{
// Extract UserId from JWT token
var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
if (userId == 0)
{
throw new UnauthorizedAccessException("User not authenticated");
}
// Get all addresses for the current user
var addresses = await _context.UserAddresses
.Where(ua => ua.UserId == userId && !ua.IsDeleted)
.OrderByDescending(ua => ua.IsDefault)
.ThenByDescending(ua => ua.Created)
.ToListAsync(cancellationToken);
var response = new GetCustomerAddressesQueryResponse();
foreach (var addr in addresses)
{
response.Addresses.Add(new CustomerAddressModel
{
Id = addr.Id,
Title = addr.Title,
Address = addr.Address,
PostalCode = addr.PostalCode,
IsDefault = addr.IsDefault,
CityId = addr.CityId,
CityName = string.Empty, // Will be populated by FrontOffice from City service
ProvinceName = string.Empty // Will be populated by FrontOffice from City service
});
}
return response;
}
}
@@ -0,0 +1,18 @@
namespace CMSMicroservice.Application.UserAddressCQ.Queries.GetCustomerAddresses;
public class GetCustomerAddressesQueryResponse
{
public List<CustomerAddressModel> Addresses { get; set; } = new();
}
public class CustomerAddressModel
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public string PostalCode { get; set; } = string.Empty;
public bool IsDefault { get; set; }
public long CityId { get; set; }
public string CityName { get; set; } = string.Empty;
public string ProvinceName { get; set; } = string.Empty;
}
@@ -1,5 +1,6 @@
using CMSMicroservice.Application.Common.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using CMSMicroservice.Domain.Entities;
namespace CMSMicroservice.Application.UserCQ.Commands.AcceptContract;
@@ -7,25 +8,38 @@ public class AcceptContractCommandHandler : IRequestHandler<AcceptContractComman
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUserService;
private readonly IHashService _hashService;
private readonly IGenerateJwtToken _generateJwt;
private readonly IConfiguration _cfg;
public AcceptContractCommandHandler(IApplicationDbContext context, ICurrentUserService currentUserService)
public AcceptContractCommandHandler(IApplicationDbContext context, ICurrentUserService currentUserService,
IHashService hashService, IGenerateJwtToken generateJwt, IConfiguration cfg)
{
_context = context;
_currentUserService = currentUserService;
_hashService = hashService;
_generateJwt = generateJwt;
_cfg = cfg;
}
public async Task<AcceptContractResponseDto> Handle(AcceptContractCommand request, CancellationToken cancellationToken)
{
// Verify OTP first
var otpToken = await _context.OtpTokens
.Where(x => x.Mobile == _currentUserService.Username && x.Purpose == "signContract" && !x.IsUsed && x.Code == request.Code)
.OrderByDescending(x => x.Id) // Use Id instead of CreatedAt for now
.Where(x => x.Mobile == _currentUserService.Username && x.Purpose == "signContract" && !x.IsUsed)
.OrderByDescending(x => x.Id)
.FirstOrDefaultAsync(cancellationToken);
if (otpToken == null || !otpToken.IsValid(request.Code))
var secret = _cfg["Otp:Secret"] ?? throw new InvalidOperationException("Otp:Secret not set");
if (otpToken == null || !otpToken.IsValid() || !_hashService.VerifyHmacSha256Hex(request.Code, otpToken.CodeHash, secret))
return new AcceptContractResponseDto { IsSuccess = false, Message = "کد تایید نامعتبر است" };
var user = await _context.Users
.Include(u => u.UserContracts)
.ThenInclude(uc => uc.Contract)
.Include(u => u.UserRoles)
.ThenInclude(ur => ur.Role)
.Include(u => u.ClubMembership)
.Where(x => x.Mobile == _currentUserService.Username)
.FirstOrDefaultAsync(cancellationToken);
@@ -48,12 +62,14 @@ public class AcceptContractCommandHandler : IRequestHandler<AcceptContractComman
await _context.SaveChangesAsync(cancellationToken);
// TODO: Implement JWT token generation
// Generate JWT token with updated contract status
var token = await _generateJwt.GenerateJwtToken(user);
return new AcceptContractResponseDto
{
IsSuccess = true,
Message = "قرارداد با موفقیت تایید شد",
Token = "TODO_IMPLEMENT_JWT_GENERATION"
Token = token
};
}
}
@@ -66,7 +66,7 @@ public class CreateNewOtpTokenCommandHandler : IRequestHandler<CreateNewOtpToken
return new CreateNewOtpTokenResponseDto
{
IsSuccess = true,
Success = true,
Message = "کد تایید با موفقیت ارسال شد",
ExpiresAt = otpToken.ExpiresAt
};
@@ -2,7 +2,7 @@ namespace CMSMicroservice.Application.UserCQ.Commands.CreateNewOtpToken;
public class CreateNewOtpTokenResponseDto
{
//موفق؟
public bool IsSuccess { get; set; }
public bool Success { get; set; }
//پیام
public string Message { get; set; }
//تلاش باقی مانده
@@ -1,43 +1,67 @@
using CMSMicroservice.Application.Common.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace CMSMicroservice.Application.UserCQ.Commands.VerifyOtpToken;
public class VerifyOtpTokenCommandHandler : IRequestHandler<VerifyOtpTokenCommand, VerifyOtpTokenResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly IGenerateJwtToken _generateJwt;
private readonly IHashService _hashService;
private readonly IConfiguration _cfg;
public VerifyOtpTokenCommandHandler(IApplicationDbContext context)
public VerifyOtpTokenCommandHandler(IApplicationDbContext context, IGenerateJwtToken generateJwt,
IHashService hashService, IConfiguration cfg)
{
_context = context;
_generateJwt = generateJwt;
_hashService = hashService;
_cfg = cfg;
}
public async Task<VerifyOtpTokenResponseDto> Handle(VerifyOtpTokenCommand request, CancellationToken cancellationToken)
{
var otpToken = await _context.OtpTokens
.Where(x => x.Mobile == request.Mobile && x.Purpose == request.Purpose && !x.IsUsed)
.OrderByDescending(x => x.Id) // Use Id instead of CreatedAt for now
.OrderByDescending(x => x.Id)
.FirstOrDefaultAsync(cancellationToken);
if (otpToken == null || !otpToken.IsValid(request.Code))
return new VerifyOtpTokenResponseDto { IsSuccess = false, Message = "کد تایید نامعتبر است" };
if (otpToken == null)
return new VerifyOtpTokenResponseDto { Success = false, Message = "کد تایید نامعتبر است" };
// Check expiry and usage
if (otpToken.IsUsed || DateTime.Now > otpToken.ExpiresAt)
return new VerifyOtpTokenResponseDto { Success = false, Message = "کد تایید منقضی شده است" };
// Verify using the same HMAC-SHA256 method used during creation
var secret = _cfg["Otp:Secret"] ?? throw new InvalidOperationException("Otp:Secret not set");
if (!_hashService.VerifyHmacSha256Hex(request.Code, otpToken.CodeHash, secret))
return new VerifyOtpTokenResponseDto { Success = false, Message = "کد تایید نامعتبر است" };
var user = await _context.Users
.Include(u => u.UserContracts)
.ThenInclude(uc => uc.Contract)
.Include(u => u.UserRoles)
.ThenInclude(ur => ur.Role)
.Include(u => u.ClubMembership)
.Where(x => x.Mobile == request.Mobile)
.FirstOrDefaultAsync(cancellationToken);
if (user == null)
return new VerifyOtpTokenResponseDto { IsSuccess = false, Message = "کاربر یافت نشد" };
return new VerifyOtpTokenResponseDto { Success = false, Message = "کاربر یافت نشد" };
// Mark OTP as used
otpToken.IsUsed = true;
await _context.SaveChangesAsync(cancellationToken);
// TODO: Implement JWT token generation
// Generate JWT token
var token = await _generateJwt.GenerateJwtToken(user);
return new VerifyOtpTokenResponseDto
{
IsSuccess = true,
Success = true,
Message = "کد تایید با موفقیت تایید شد",
Token = "TODO_IMPLEMENT_JWT_GENERATION"
Token = token
};
}
}
@@ -2,7 +2,7 @@ namespace CMSMicroservice.Application.UserCQ.Commands.VerifyOtpToken;
public class VerifyOtpTokenResponseDto
{
//موفق؟
public bool IsSuccess { get; set; }
public bool Success { get; set; }
//پیام
public string Message { get; set; }
//توکن
@@ -0,0 +1,6 @@
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerProfile;
public class GetCustomerProfileQuery : IRequest<GetCustomerProfileResponseDto>
{
public long UserId { get; set; }
}
@@ -0,0 +1,77 @@
using CMSMicroservice.Application.Common.Interfaces;
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerProfile;
public class GetCustomerProfileQueryHandler : IRequestHandler<GetCustomerProfileQuery, GetCustomerProfileResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetCustomerProfileQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetCustomerProfileResponseDto> Handle(GetCustomerProfileQuery request, CancellationToken cancellationToken)
{
// Get userId from ICurrentUserService if not provided
var userId = request.UserId == 0
? (long.TryParse(_currentUser.UserId, out var id) ? id : 0)
: request.UserId;
if (userId == 0)
throw new UnauthorizedAccessException("User ID not found in JWT token");
var user = await _context.Users
.AsNoTracking()
.Where(x => x.Id == userId)
.FirstOrDefaultAsync(cancellationToken);
if (user == null)
throw new NotFoundException(nameof(User), userId);
var fullName = $"{user.FirstName} {user.LastName}".Trim();
var profileCompletionPercentage = CalculateProfileCompletion(user);
return new GetCustomerProfileResponseDto
{
Id = user.Id,
FirstName = user.FirstName,
LastName = user.LastName,
Mobile = user.Mobile,
Email = user.Email,
NationalCode = user.NationalCode,
AvatarPath = user.AvatarPath,
ParentId = user.NetworkParentId,
ReferralCode = user.ReferralCode,
IsMobileVerified = user.IsMobileVerified,
MobileVerifiedAt = user.MobileVerifiedAt,
EmailNotifications = user.EmailNotifications,
SmsNotifications = user.SmsNotifications,
PushNotifications = user.PushNotifications,
BirthDate = user.BirthDate,
FullName = fullName,
ProfileCompletionPercentage = profileCompletionPercentage
};
}
private int CalculateProfileCompletion(Domain.Entities.User user)
{
var totalFields = 10;
var completedFields = 0;
if (!string.IsNullOrEmpty(user.FirstName)) completedFields++;
if (!string.IsNullOrEmpty(user.LastName)) completedFields++;
if (!string.IsNullOrEmpty(user.Mobile)) completedFields++;
if (!string.IsNullOrEmpty(user.Email)) completedFields++;
if (!string.IsNullOrEmpty(user.NationalCode)) completedFields++;
if (!string.IsNullOrEmpty(user.AvatarPath)) completedFields++;
if (user.BirthDate.HasValue) completedFields++;
if (user.IsMobileVerified) completedFields++;
if (user.NetworkParentId.HasValue) completedFields++;
if (!string.IsNullOrEmpty(user.ReferralCode)) completedFields++;
return (int)((double)completedFields / totalFields * 100);
}
}
@@ -0,0 +1,22 @@
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerProfile;
public class GetCustomerProfileResponseDto
{
public long Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string Mobile { get; set; }
public string? Email { get; set; }
public string? NationalCode { get; set; }
public string? AvatarPath { get; set; }
public long? ParentId { get; set; }
public string ReferralCode { get; set; }
public bool IsMobileVerified { get; set; }
public DateTime? MobileVerifiedAt { get; set; }
public bool EmailNotifications { get; set; }
public bool SmsNotifications { get; set; }
public bool PushNotifications { get; set; }
public DateTime? BirthDate { get; set; }
public string FullName { get; set; }
public int ProfileCompletionPercentage { get; set; }
}
@@ -0,0 +1,10 @@
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerReferrals;
public class GetCustomerReferralsQuery : IRequest<GetCustomerReferralsResponseDto>
{
public long UserId { get; set; }
public PaginationState? PaginationState { get; set; }
public string? StatusFilter { get; set; } // ACTIVE, INACTIVE, ALL
}
@@ -0,0 +1,114 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerReferrals;
public class GetCustomerReferralsQueryHandler : IRequestHandler<GetCustomerReferralsQuery, GetCustomerReferralsResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetCustomerReferralsQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetCustomerReferralsResponseDto> Handle(GetCustomerReferralsQuery request, CancellationToken cancellationToken)
{
// Get userId from ICurrentUserService if not provided
var userId = request.UserId == 0
? (long.TryParse(_currentUser.UserId, out var id) ? id : 0)
: request.UserId;
if (userId == 0)
throw new UnauthorizedAccessException("User ID not found in JWT token");
// Get referrals (children in network)
var query = _context.Users
.AsNoTracking()
.Where(x => x.NetworkParentId == userId);
// Apply status filter
if (!string.IsNullOrEmpty(request.StatusFilter))
{
if (request.StatusFilter.ToUpper() == "ACTIVE")
query = query.Where(x => x.IsMobileVerified);
else if (request.StatusFilter.ToUpper() == "INACTIVE")
query = query.Where(x => !x.IsMobileVerified);
// ALL - no additional filter
}
query = query.OrderByDescending(x => x.Created);
// Calculate stats
var allReferrals = await _context.Users
.AsNoTracking()
.Where(x => x.NetworkParentId == userId)
.ToListAsync(cancellationToken);
var totalReferrals = allReferrals.Count;
var activeReferrals = allReferrals.Count(x => x.IsMobileVerified);
// Calculate commission for current user
var userWallet = await _context.UserWallets
.AsNoTracking()
.Where(x => x.UserId == userId)
.FirstOrDefaultAsync(cancellationToken);
var totalCommission = userWallet?.NetworkBalance ?? 0;
// Calculate this month's commission from wallet changelog
var startOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
var thisMonthCommission = await _context.UserWalletChangeLogs
.AsNoTracking()
.Include(x => x.Wallet)
.Where(x => x.Wallet.UserId == userId && x.Created >= startOfMonth)
.SumAsync(x => x.ChangeNerworkValue, cancellationToken);
// Pagination
var totalCount = await query.CountAsync(cancellationToken);
var paginationState = request.PaginationState ?? new PaginationState { PageNumber = 1, PageSize = 10 };
var referrals = await query
.Skip((paginationState.PageNumber - 1) * paginationState.PageSize)
.Take(paginationState.PageSize)
.ToListAsync(cancellationToken);
var metaData = new MetaData
{
TotalCount = totalCount,
CurrentPage = paginationState.PageNumber,
PageSize = paginationState.PageSize,
TotalPage = (int)Math.Ceiling((double)totalCount / paginationState.PageSize),
HasPrevious = paginationState.PageNumber > 1,
HasNext = paginationState.PageNumber < (int)Math.Ceiling((double)totalCount / paginationState.PageSize)
};
var referralModels = referrals.Select(r => new CustomerReferralModel
{
Id = r.Id,
FirstName = r.FirstName,
LastName = r.LastName,
Mobile = r.Mobile,
JoinDate = r.Created,
IsActive = r.IsMobileVerified,
StatusMessage = r.IsMobileVerified ? "Active" : "Inactive",
Level = 1, // Direct referral
TotalCommission = 0 // Not tracking per-referral commission
}).ToList();
return new GetCustomerReferralsResponseDto
{
MetaData = metaData,
Referrals = referralModels,
Stats = new CustomerReferralStats
{
TotalReferrals = totalReferrals,
ActiveReferrals = activeReferrals,
TotalCommissionEarned = totalCommission,
ThisMonthCommission = thisMonthCommission
}
};
}
}
@@ -0,0 +1,31 @@
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerReferrals;
public class GetCustomerReferralsResponseDto
{
public MetaData MetaData { get; set; }
public List<CustomerReferralModel> Referrals { get; set; }
public CustomerReferralStats Stats { get; set; }
}
public class CustomerReferralModel
{
public long Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string Mobile { get; set; }
public DateTime JoinDate { get; set; }
public bool IsActive { get; set; }
public string StatusMessage { get; set; }
public int Level { get; set; }
public long TotalCommission { get; set; }
}
public class CustomerReferralStats
{
public int TotalReferrals { get; set; }
public int ActiveReferrals { get; set; }
public long TotalCommissionEarned { get; set; }
public long ThisMonthCommission { get; set; }
}
@@ -0,0 +1,6 @@
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerSettings;
public class GetCustomerSettingsQuery : IRequest<GetCustomerSettingsResponseDto>
{
public long UserId { get; set; }
}
@@ -0,0 +1,45 @@
using CMSMicroservice.Application.Common.Interfaces;
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerSettings;
public class GetCustomerSettingsQueryHandler : IRequestHandler<GetCustomerSettingsQuery, GetCustomerSettingsResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetCustomerSettingsQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetCustomerSettingsResponseDto> Handle(GetCustomerSettingsQuery request, CancellationToken cancellationToken)
{
// Get userId from ICurrentUserService if not provided
var userId = request.UserId == 0
? (long.TryParse(_currentUser.UserId, out var id) ? id : 0)
: request.UserId;
if (userId == 0)
throw new UnauthorizedAccessException("User ID not found in JWT token");
var user = await _context.Users
.AsNoTracking()
.Where(x => x.Id == userId)
.FirstOrDefaultAsync(cancellationToken);
if (user == null)
throw new NotFoundException(nameof(User), userId);
return new GetCustomerSettingsResponseDto
{
EmailNotifications = user.EmailNotifications,
SmsNotifications = user.SmsNotifications,
PushNotifications = user.PushNotifications,
MarketingNotifications = false, // Not in User entity, default to false
PreferredLanguage = "fa", // Default Persian
TimeZone = "Asia/Tehran", // Default Iran timezone
TwoFactorAuthEnabled = false // Not implemented yet
};
}
}
@@ -0,0 +1,12 @@
namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerSettings;
public class GetCustomerSettingsResponseDto
{
public bool EmailNotifications { get; set; }
public bool SmsNotifications { get; set; }
public bool PushNotifications { get; set; }
public bool MarketingNotifications { get; set; }
public string PreferredLanguage { get; set; }
public string TimeZone { get; set; }
public bool TwoFactorAuthEnabled { get; set; }
}
@@ -14,7 +14,7 @@ public class GetJwtTokenQueryHandler : IRequestHandler<GetJwtTokenQuery, GetJwtT
{
var user = await _context.Users
.Include(u => u.UserContracts)
.ThenInclude(u => u.Contract)
.ThenInclude(uc => uc.Contract)
.Include(u => u.UserRoles)
.ThenInclude(ur => ur.Role)
.Include(u => u.ClubMembership)
@@ -2,21 +2,28 @@ namespace CMSMicroservice.Application.UserCQ.Queries.GetUser;
public class GetUserQueryHandler : IRequestHandler<GetUserQuery, GetUserResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
public GetUserQueryHandler(IApplicationDbContext context)
public GetUserQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser)
{
_context = context;
_currentUser = currentUser;
}
public async Task<GetUserResponseDto> Handle(GetUserQuery request,
CancellationToken cancellationToken)
{
// If Id is 0 or not provided, get the current authenticated user's ID
var userId = request.Id == 0
? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
: request.Id;
var response = await _context.Users
.AsNoTracking()
.Where(x => x.Id == request.Id)
.Where(x => x.Id == userId)
.ProjectToType<GetUserResponseDto>()
.FirstOrDefaultAsync(cancellationToken);
return response ?? throw new NotFoundException(nameof(User), request.Id);
return response ?? throw new NotFoundException(nameof(User), userId);
}
}

Some files were not shown because too many files have changed in this diff Show More