311 Commits

Author SHA1 Message Date
masoodafar-web 436e5d7aca Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 9m50s
2026-08-09 02:33:38 +03:30
masoodafar-web 6a04a6a270 feat(package): enhance pagination logic in GetCustomerPackagePurchaseRollupQueryHandler
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m42s
- Updated pagination handling to allow for exporting all results when PageSize is set to 0.
- Adjusted page size and number calculations to accommodate the new export functionality.
- Improved clarity in pagination logic by distinguishing between export and paginated results.
2026-08-09 00:40:25 +03:30
masoodafar-web 427d2cce1d feat(package): update package purchase methods and enhance Protobuf definitions
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 6m45s
- Changed package purchase method from DirectPurchase to Manual in multiple command handlers to reflect new business logic.
- Added Manual purchase method to PackagePurchaseMethod enum for clarity.
- Introduced new RPC method GetCustomerPackagePurchaseRollup in Protobuf for summarizing customer package purchases.
- Updated UserPackagePurchaseProfile and UserPackagePurchaseService to support new rollup functionality.
- Bumped Protobuf project version to accommodate new features.
2026-08-08 21:59:14 +03:30
masoodafar-web fb9e3d0109 feat(order): refactor order data mapping for improved clarity and structure
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 13m4s
- Updated GetAllDiscountOrdersQueryHandler to enhance order data mapping by using a more structured approach with AdminOrderDto.
- Refactored user full name construction in GetCustomerOrderQueryHandler and GetCustomerOrdersQueryHandler to utilize UserDisplayName for better readability.
- Added necessary using directives for consistency across query handlers.
2026-08-07 18:39:42 +03:30
masoodafar-web 6c90e4caf0 feat(order): enhance order status management and Protobuf definitions
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m46s
- Added AdminNotes handling in UpdateOrderStatusCommandHandler to include delivery descriptions.
- Updated DeliveryStatus enum to include ReadyForOfficePickup.
- Enhanced GetCustomerOrderHistoryQueryHandler and UserOrderService to support new delivery status.
- Updated Protobuf definitions for DeliveryStatus to reflect changes.
- Bumped Protobuf project version to accommodate new features.
2026-08-07 17:25:57 +03:30
masoodafar-web 40da1bd8df feat(order): enhance order details with user contact information and update Protobuf definitions
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m33s
- Added Phone property to UserAddressDto for capturing the user's mobile number.
- Updated GetOrderByIdQueryHandler to include user mobile in order details.
- Enhanced GetCustomerOrderQueryHandler and GetCustomerOrderResponseDto to include PostalCode and UserMobile.
- Modified userorder.proto to add postal_code and user_mobile fields in GetUserOrderResponse.
- Bumped Protobuf project version to reflect the addition of new features.
2026-08-07 15:48:04 +03:30
masoodafar-web 053c5a7c4f Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Failing after 17m27s
2026-08-07 14:38:07 +03:30
masoodafar-web 3810146651 feat(wallet): enforce club membership validation for wallet charge operations
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 19m57s
- Added club membership inclusion in user retrieval for ChargeCreditWallet and VerifyCreditWalletCharge command handlers.
- Implemented validation to ensure users have an active club membership before allowing wallet charges, throwing a BadRequestException if not.
- Updated UserWalletService to handle BadRequestException and return appropriate error messages in responses.
2026-08-06 23:59:36 +03:30
masoodafar-web 82944e11d0 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2026-07-26 00:52:02 +03:30
masoodafar-web ce98efdd68 feat(sorting): implement ApplyOrderWithInStockPriority method for enhanced product sorting
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- Added ApplyOrderWithInStockPriority method to prioritize in-stock products in queries.
- Updated GetDiscountProductsQueryHandler and GetCustomerProductsByFilterQueryHandler to utilize the new sorting method, ensuring in-stock items are listed first followed by user-defined sorting or creation date.
- Improved overall query handling for product availability and sorting logic.
2026-07-26 00:17:44 +03:30
masoodafar-web d232399f43 feat(wallet): add manual credit wallet charge functionality and update Protobuf definitions
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- Introduced ManualCreditWalletCharge enum value to TransactionType for clarity.
- Added AdminManualCreditCharge and GetManualCreditCharges RPC methods in UserWalletService for handling manual credit charges by admin.
- Created corresponding request and response messages for manual credit charge operations in Protobuf.
- Updated Protobuf project version to reflect the addition of new features.
2026-07-25 23:55:08 +03:30
masoodafar-web bb20ad2c4e Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2026-06-30 02:28:32 +03:30
masoodafar-web 246d893b62 feat(discount): add InStock filter to discount product queries and mappings
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- Introduced InStock property to GetDiscountProductsQuery and GetCustomerProductsByFilterQuery for filtering based on product availability.
- Updated query handlers to apply InStock filtering logic in both discount and customer product queries.
- Enhanced mapping configurations to include InStock in the response DTOs.
- Bumped Protobuf project version to reflect the addition of new features.
2026-06-30 00:16:28 +03:30
masoodafar-web 99aab3beff Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Failing after 19m40s
2026-06-26 19:30:03 +03:30
masoodafar-web 728f28f525 fix(config): update FrontOfficeBaseUrl in configuration files
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- Changed FrontOfficeBaseUrl from "https://kbs1.ir" to "https://frontoffice.se.kbs1.ir" in both cms-config.yaml and appsettings.Staging.json for consistency across environments.
2026-06-26 17:49:42 +03:30
masoodafar-web 89af07c122 feat(config): add CMS and Front Office base URLs to configuration files
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- Introduced CmsBaseUrl and FrontOfficeBaseUrl properties in both cms-config.yaml and appsettings.Staging.json for improved service integration.
- Ensured consistency across configuration files for easier management of base URLs.
2026-06-26 17:12:43 +03:30
masoodafar-web 58aeddf004 feat(transactions): enhance transaction filtering and summary capabilities
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- Added new date range filters (CreatedFrom, CreatedTo, PaymentDateFrom, PaymentDateTo) to GetAllTransactionsByFilterQuery for improved transaction querying.
- Updated GetAllTransactionsByFilterQueryHandler to apply new filters and return detailed transaction models.
- Introduced GetTransactionSummary RPC method in Protobuf for summarizing transaction data.
- Enhanced mapping configurations to accommodate new filter properties and response models.
- Bumped Protobuf project version to reflect the addition of new features.
2026-06-26 16:33:20 +03:30
masoodafar-web 6c3fbe43b1 feat(wallet): add credit wallet functionality and update Protobuf definitions
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m49s
- Introduced new CreditWalletCharge enum value to TransactionType for clarity.
- Implemented InitiateCreditCharge and VerifyCreditCharge methods in UserWalletService for handling credit wallet transactions.
- Updated ZarinpalReconciliationJob to support credit wallet payment verification.
- Enhanced Protobuf definitions with new messages and RPC methods for credit wallet operations.
- Bumped Protobuf project version to reflect the addition of new features.
2026-06-26 16:11:18 +03:30
masoodafar-web 7570c39e65 refactor(extensions): improve sorting logic in ApplyOrder method
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 21m1s
- Simplified the default sorting approach by directly returning the ordered source.
- Introduced NormalizeSortBy method to handle dynamic LINQ sorting, accommodating leading '+' and '-' for ascending and descending order respectively.
- Enhanced code clarity and maintainability by reducing unnecessary variable assignments.
2026-06-23 00:11:37 +03:30
masoodafar-web 46ac1d817e refactor(mappings): streamline mapping configurations for user package purchases and payment transactions
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 23m14s
- Updated mapping configurations in UserPackagePurchaseProfile and PaymentTransactionProfile to utilize new Protobuf definitions for improved clarity and consistency.
- Simplified filter mappings and removed redundant mapping methods to enhance maintainability.
- Ensured alignment of all relevant profiles with the latest filter structures and DTOs.
2026-06-22 22:54:25 +03:30
masoodafar-web db20d95b43 refactor(mappings): update filter mappings for club membership and payment transaction profiles
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- Renamed filter types in ClubMembershipCycleHistoryProfile, ClubMembershipCycleProfile, PaymentTransactionProfile, UserPackagePurchaseProfile to improve clarity and consistency.
- Adjusted mapping methods to utilize new filter type aliases for better readability and maintainability.
- Ensured all relevant profiles are aligned with the updated filter structures.
2026-06-22 22:36:33 +03:30
masoodafar-web f8794bbb63 feat(club-membership): enhance club membership history queries and responses
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 17m54s
- Added filtering capabilities to GetClubMembershipHistoryQuery, allowing optional filters for UserId, ClubMembershipId, Action, and date range.
- Updated GetClubMembershipHistoryQueryHandler to utilize the new filter structure.
- Enhanced GetAllClubMembershipsQueryHandler to include LastPackage details in the response.
- Introduced new properties in GetAllClubMembershipsResponseModel for PackageId and PackageName.
- Updated Protobuf definitions to reflect changes in club membership history queries and responses.
- Refactored mapping configurations to accommodate new DTOs and filters.
2026-06-22 22:19:44 +03:30
masoodafar-web 19be5dc9dc Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Failing after 16m51s
2026-06-20 23:45:47 +03:30
masoodafar-web 6395f63ab5 Merge branch 'kub-stage' of https://git.se.kbs1.ir/admin/CMS into kub-stage
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 16m9s
2026-06-20 23:31:31 +03:30
masoodafar-web 758640cce3 feat(wallet): add current discount balance and change discount value to wallet history response DTOs and Protobuf definitions 2026-06-20 23:31:29 +03:30
m-moghaddam 5c1e3cf601 Merge remote-tracking branch 'origin/kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Failing after 19m16s
2026-06-20 17:28:19 +03:30
m-moghaddam 37820ea257 feat(db): add SQL script to fix incorrect bulk credit payouts in user wallet histories
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 19m38s
Introduced a new SQL script to identify and correct erroneous bulk credit entries in user wallet histories. The script allows for a dry run to preview changes before applying fixes, ensuring accurate balance adjustments and removal of incorrect records.
2026-06-20 17:27:23 +03:30
m-moghaddam 5f8e30905d refactor(commission): streamline bulk credit payouts handling by removing unused wallet loading and updating payout history logic
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 17m51s
Removed unnecessary loading of user wallets and adjusted payout history creation to reflect accurate amounts before and after payment. Updated comments for clarity.
2026-06-20 16:11:37 +03:30
masoodafar-web d82b7c28a8 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Failing after 20m50s
2026-06-19 02:37:34 +03:30
masoodafar-web 02b2966e96 fix(cms-deployment): change imagePullPolicy to Always for cms container and clean up unused images during deployment
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 21m47s
2026-06-19 01:56:43 +03:30
masoodafar-web 29fa7ff435 fix(cms-deployment): change imagePullPolicy to IfNotPresent for cms container
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 19m13s
2026-06-14 00:09:43 +03:30
masoodafar-web 3df738e496 Merge branches 'kub-stage' and 'production' of https://git.se.kbs1.ir/admin/CMS into production
Build and Deploy to Production / build-and-deploy (push) Successful in 11m1s
2026-06-08 22:47:48 +03:30
masoodafar-web dba0b63a70 refactor(payment): unify package verify for callback and reconciliation job
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 10m40s
Extract VerifyUserPackagePurchasePaymentCommand with idempotency, DB lock,
and IUserPaymentLock so ZarinpalReconciliationJob cannot double-credit wallets.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 22:44:12 +03:30
masoodafar-web 3a9c3438e6 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 12m7s
Deploy DiscountOrderService build fix.
2026-06-08 02:30:01 +03:30
masoodafar-web 541b0c2ce9 fix(build): add missing System.Linq import in DiscountOrderService
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 14m42s
Fixes CI compile error CS1061 on DbSet.Where; remove duplicate using in UserOrderService.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 02:29:55 +03:30
masoodafar-web 12ebdc9e87 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
Deploy blog slug auto-generation fix to production.
2026-06-08 02:06:50 +03:30
masoodafar-web 121291eeed fix(blog): auto-generate slug when admin leaves it empty
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
Allow optional slug on create/update, generate from title with unique fallback,
so BackOffice can publish posts without manual slug entry.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 02:06:30 +03:30
masoodafar-web 9f1bc2bcdb Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Failing after 15m25s
Deploy payment idempotency fixes and per-user payment locks to production.
2026-06-08 02:00:30 +03:30
masoodafar-web d22eb1617f feat(payment): add per-user in-memory lock for gateway operations
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 9m58s
Introduce IUserPaymentLock to serialize payment initiate and verify flows
per user, preventing concurrent duplicate gateway requests across services.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 01:55:00 +03:30
masoodafar-web f08d3ac78f fix(payment): prevent duplicate wallet credit on package verify
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 11m29s
Add idempotent verify with serializable transaction and wallet-history check
to stop concurrent callback/race from charging the wallet twice.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 01:32:47 +03:30
masoodafar-web 354ba1dd1b Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 8m37s
2026-05-29 19:59:05 +03:30
masoodafar-web 4f2d313d5e fix(UserOrderService): update comment to reflect correct threshold value for Magic Wallet
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m50s
2026-05-29 19:58:36 +03:30
masoodafar-web 034679d915 fix(ZarinpalReconciliationJob): correct typo in logging method for unverified list
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 16m38s
2026-05-21 20:21:21 +03:30
masoodafar-web 3b9958a700 fix(ZarinpalReconciliationJob): correct typo in logging method for unverified list
Build and Deploy to Production / build-and-deploy (push) Successful in 19m55s
2026-05-21 20:20:38 +03:30
masoodafar-web 9c562b12c7 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2026-05-21 20:19:43 +03:30
masoodafar-web 6414e5663a fix(ZarinpalReconciliationJob): log information when unverified list is empty
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-05-21 20:19:32 +03:30
masoodafar-web 3c9957463d Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 14m52s
2026-05-21 19:27:56 +03:30
masoodafar-web 90d4f65de4 chore: add missing using directives for System.Collections.Generic in ZarinpalReconciliationJob and ZarinPalPaymentService files
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 20m42s
2026-05-21 19:27:30 +03:30
masoodafar-web 4df71107a9 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Failing after 12m46s
2026-05-21 18:27:04 +03:30
masoodafar-web bc52240a41 feat(payment): add GetUnverifiedAuthoritiesAsync method to IPaymentGatewayService and ZarinPalPaymentService for payment reconciliation
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 8m7s
- Introduced GetUnverifiedAuthoritiesAsync method to retrieve authorities with unverified payments.
- Implemented ZarinPal-specific logic for fetching unverified authorities from the new endpoint.
- Added background job for Zarinpal payment reconciliation every 30 minutes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-21 18:26:49 +03:30
masoodafar-web a7fc959d3e Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 14m3s
2026-05-18 01:56:29 +03:30
masoodafar-web aac0d4271d feat(wallets): add DiscountBalance to GetAllUserWalletByFilter response; bump proto to 0.0.199
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 15m40s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-18 01:13:56 +03:30
masoodafar-web d96558aa4b Revert "feat(commission): add BulkCreditPayouts — credit wallets for pending payouts"
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
This reverts commit a2d13c72c3.
2026-05-18 00:38:40 +03:30
masoodafar-web da1a2fcf8e feat(commission): add BulkCreditPayouts — credit wallets for pending payouts
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 10m35s
- commission.proto: add BulkCreditPayouts rpc + request/response messages; bump version to 0.0.198
- BulkCreditPayoutsCommand + Handler: load all Pending payouts for given week, credit UserWallet.Balance for each user, create UserWalletHistory + CommissionPayoutHistory records, set Status=Paid + PaidAt
- CommissionService: wire up BulkCreditPayouts gRPC method
- CommissionProfile: add Mapster mappings for request/result ↔ proto types

Previously ProcessUserPayouts created records with Status=Pending but never credited wallets, making CustomerWithdrawBalance unreachable (it requires Status==Paid).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-18 00:38:25 +03:30
masoodafar-web a2d13c72c3 feat(commission): add BulkCreditPayouts — credit wallets for pending payouts
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
- commission.proto: add BulkCreditPayouts rpc + request/response messages; bump version to 0.0.198
- BulkCreditPayoutsCommand + Handler: load all Pending payouts for given week, credit UserWallet.Balance for each user, create UserWalletHistory + CommissionPayoutHistory records, set Status=Paid + PaidAt
- CommissionService: wire up BulkCreditPayouts gRPC method
- CommissionProfile: add Mapster mappings for request/result ↔ proto types

Previously ProcessUserPayouts created records with Status=Pending but never credited wallets, making CustomerWithdrawBalance unreachable (it requires Status==Paid).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-18 00:36:05 +03:30
masoodafar-web 4e8caa6e2c Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 19m44s
2026-05-18 00:12:13 +03:30
masoodafar-web cdd124ac25 fix: rename cancellationToken to ct in ProcessReturnAsync call
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m21s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 22:38:40 +03:30
masoodafar-web 4d7932f335 fix(regular-store): deduct inventory and restore on cancel
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 19m38s
- UserOrderService.SubmitShopBuyOrder: inject IInventoryService; validate
  available stock per item before any financial operation; call ConfirmSaleAsync
  and increment Product.SaleCount after order is persisted.
- CancelOrderByAdminCommandHandler: inject IInventoryService; include
  FactorDetails in query; call ProcessReturnAsync for each item so stock
  is restored when an order is cancelled by admin.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 21:57:48 +03:30
masoodafar-web 18a2299d93 fix: update MagicWallet thresholds for consistency with business logic
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m11s
- Adjust MagicWalletEntryThreshold from 1,000,000 to 100,000
- Update MagicWalletDefaultMaxDeposit from 1,000,000,000 to 100,000,000
- Change MagicWalletDefaultMaxCredit from 2,500,000,000 to 250,000,000
- Modify comments in UserOrderService to reflect updated threshold values
2026-05-14 03:12:45 +03:30
masoodafar-web 37a017998c Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 9m24s
2026-05-14 01:13:03 +03:30
masoodafar-web 6e60ca7c25 chore: bump CMSMicroservice.Protobuf version to 0.0.197
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m42s
2026-05-13 22:21:22 +03:30
masoodafar-web fd8b37a6b1 docs: add note on TLS certificate requirements for cms-tls in Ingress configuration
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m14s
2026-05-13 22:05:26 +03:30
masoodafar-web 683ed370b5 feat: extend discount product gRPC API with sort_by and sale_count
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m11s
- Add sort_by (StringValue) to GetDiscountProductsRequest proto to enable dynamic sorting
- Add sale_count (int32) to DiscountProductDto proto for top-seller exposure
- Update GetDiscountProductsQuery with SortBy property
- Update GetDiscountProductsQueryHandler to use ApplyOrder(SortBy) with fallback to Created desc; project SaleCount in SELECT
- Add SortBy and SaleCount Mapster mappings in DiscountProductProfile
- Bump CMSMicroservice.Protobuf version to 0.0.196

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 19:47:56 +03:30
masoodafar-web 16acb8f3b5 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 7m7s
2026-05-10 21:37:51 +03:30
masoodafar-web 98c2875ae2 feat: simplify UserId handling in GetOrderById method for improved clarity
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m12s
2026-05-10 21:37:30 +03:30
masoodafar-web 34d2354fd4 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 9m37s
2026-05-05 01:54:44 +03:30
masoodafar-web 65db839642 feat: update GetOrderByIdQuery to allow nullable UserId and adjust query handling in GetOrderByIdQueryHandler
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m43s
2026-05-05 01:54:33 +03:30
masoodafar-web f7d6b0e3e7 feat: cast Created field to datetimeoffset in sp_GetUserWeeklyBalances for improved date handling
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m46s
2026-05-05 01:35:07 +03:30
masoodafar-web be2b22c50a Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 10m25s
2026-05-04 23:55:16 +03:30
masoodafar-web b905c308c1 feat: enhance sp_CalculateWeeklyBalances to track package activity and optimize member calculations
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 10m21s
2026-05-04 23:54:13 +03:30
masoodafar-web d09db638cc feat: enhance sp_CalculateWeeklyCommissionPool to include IsDeleted filter and update commission calculations for package-specific pools
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m44s
2026-05-04 18:44:28 +03:30
masoodafar-web 41e7f29a0d feat: add PackageId to CalculateWeeklyCommissionPoolCommand and related logic for package-specific calculations
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m43s
2026-05-04 02:31:26 +03:30
masoodafar-web c4409491c1 feat: update stored procedure to use UserWalletHistories and include PackageId in balance checks
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m19s
2026-05-04 01:28:04 +03:30
masoodafar-web e4279f3d05 Add migration to rename index and create stored procedure for user weekly balances
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m55s
- Added migration to rename index from IX_NetworkWeeklyBalances_PackageId to IX_NetworkWeeklyBalance_PackageId in the NetworkWeeklyBalances table.
- Created stored procedure sp_GetUserWeeklyBalances to retrieve weekly balances with pagination and various filters.
2026-05-04 00:36:31 +03:30
masoodafar-web b260fd56fa Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 10m7s
2026-05-04 00:04:36 +03:30
masoodafar-web c5dd1a2ef5 feat: improve package retrieval logic in AcceptClubMembershipContract and ActivateClubMembership handlers
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m0s
2026-05-03 22:03:47 +03:30
masoodafar-web 1e3ba03c5c Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 8m34s
2026-05-01 00:56:21 +03:30
masoodafar-web eeb837f32e feat: enhance inventory release logic in ExpirePendingOrdersService and InventoryService
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m27s
2026-05-01 00:56:00 +03:30
masoodafar-web ee7d29015f Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2026-05-01 00:47:44 +03:30
masoodafar-web 624ab7ea9f feat: conditionally enable InventoryInitializer service and update appsettings for seed workers
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-05-01 00:47:32 +03:30
masoodafar-web d8a3b49f4d feat: add GetNetworkTree stored procedure for network data retrieval
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-05-01 00:28:25 +03:30
masoodafar-web b053d86006 feat: Add GetNetworkTree stored procedure for binary network retrieval with activation logic
Build and Deploy to Production / build-and-deploy (push) Successful in 8m27s
2026-05-01 00:27:44 +03:30
masoodafar-web 15044c66cb Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2026-05-01 00:15:48 +03:30
masoodafar-web 8518c7b3ec feat: Enhance club membership activation and commission pool validation
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m9s
- Updated AcceptClubMembershipContractCommandHandler to set PackagePurchasedAt to the contract-signing time, ensuring accurate pool charging.
- Modified ActivateClubMembershipCommand to allow specifying a PackageId for forced activation, defaulting to the base package if not provided.
- Improved ActivateClubMembershipCommandHandler to handle new and existing memberships differently regarding pool charging.
- Added validation logic in GetWeeklyCommissionPoolQueryHandler to compare TotalPoolAmount against actual activations.
- Introduced validation fields in WeeklyCommissionPoolDto for tracking discrepancies and expected amounts.
- Updated stored procedures to ensure accurate calculations based on package purchases and to handle empty pools.
- Enhanced protobuf definitions to include validation fields for commission pools and network tree nodes.
- Added mapping for new fields in CommissionProfile and NetworkMembershipProfile.
- Created DiscountProductProfile for mapping discount product requests and responses.
2026-05-01 00:07:05 +03:30
masoodafar-web 0983cdf88f Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 8m56s
2026-04-30 04:27:43 +03:30
masoodafar-web 789aa0b870 fix: update response message for non-existent user during registration process
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m42s
2026-04-30 03:55:03 +03:30
masoodafar-web b4e7902870 fix: update Kavenegar API key in appsettings for staging environment
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m25s
2026-04-30 03:44:38 +03:30
masoodafar-web aa7f77bfec fix: return 'user not found' for login purpose instead of requiring referral code 2026-04-30 03:42:53 +03:30
masoodafar-web a4d04cb7bf fix: update Kavenegar API key in appsettings for staging environment
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m19s
2026-04-30 03:36:10 +03:30
masoodafar-web 85591aec30 fix: update Kavenegar API key in appsettings for staging environment
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m0s
2026-04-30 02:33:54 +03:30
masoodafar-web e93fad3b3d fix: update Kavenegar API key in appsettings for SMS provider
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-04-30 02:31:45 +03:30
masoodafar-web 04e1a83838 feat: enhance OTP verification logic to support master code bypass and improve error handling 2026-04-29 22:58:16 +03:30
masoodafar-web b8120dd1b9 config: add master OTP code to production appsettings 2026-04-29 00:49:55 +03:30
masoodafar-web 7ce5539793 feat: add master OTP bypass for login + referral code field support 2026-04-29 00:49:33 +03:30
masoodafar-web 4a7df2083e feat: add master OTP bypass for login + referral code field support
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 22m37s
2026-04-29 00:49:25 +03:30
masoodafar-web 9a4f1e6401 chore: merge kub-stage into production
Build and Deploy to Production / build-and-deploy (push) Successful in 8m11s
2026-04-28 23:28:44 +03:30
masoodafar-web e77b5f9658 fix(ci): fix proto publish - remove allow-insecure-connections, add CI=true env, use source name
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 16m36s
2026-04-24 04:43:28 +03:30
masoodafar-web b71ddfaf9b chore(proto): bump version to 0.0.193 for per-package commission fields
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 18m4s
2026-04-24 04:18:41 +03:30
masoodafar-web 4d6d77531d feat(commission): add per-package calculation support
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 15m3s
- SP sp_CalculateWeeklyBalances: added @PackageId, @InputMaxBalancesPerLeg, @InputMaxNetworkLevel params; filters by PackageId
- SP sp_CalculateWeeklyCommissionPool: added @PackageId param; all queries filter by PackageId/WeeklyPoolId for isolation
- ICommissionCalculationStrategy: added optional PackageId param to both methods
- StoredProcedureCommissionCalculationStrategy: loops per-package for both Balance and Pool methods; filters by packageId if provided
- OrmCommissionCalculationStrategy: signature updated to match interface
- TriggerWeeklyCalculationCommand: added PackageId optional field
- TriggerWeeklyCalculationCommandHandler: passes PackageId to strategy
- GetWeeklyCommissionPoolQuery: added optional PackageId filter
- GetWeeklyCommissionPoolQueryHandler: filters pool by PackageId if provided
- GetAllWeeklyPoolsQuery/Handler/DTO: added PackageId filter + PackageTitle in response
- Proto commission.proto: added package_id to TriggerWeeklyCalculationRequest, GetWeeklyCommissionPoolRequest, WeeklyCommissionPoolModel, GetWeeklyCommissionPoolResponse, GetAllWeeklyPoolsRequest
- CommissionProfile: added explicit mappings for TriggerWeeklyCalculation, GetWeeklyCommissionPool, GetAllWeeklyPools

Fixes: SP picks wrong pool when multiple packages per week
Fixes: SP ignores PackageId on ForceRecalculate (now uses WeeklyPoolId)
Fixes: Zero-balance pools not fully recorded (now sets TotalBalances=0, ValuePerBalance=0)
2026-04-24 03:43:20 +03:30
masoodafar-web 091a04f3aa Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 24m9s
2026-03-15 03:19:41 +03:30
masoodafar-web a35e2eeb92 fix: add proxy timeout annotations to CMS ingress
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 23m45s
Add nginx.ingress.kubernetes.io/proxy-read-timeout: 3600
and proxy-send-timeout: 3600 to prevent 504 Gateway Timeout
on gRPC-Web requests through the nginx ingress controller.
2026-03-15 03:12:03 +03:30
masoodafar-web 0a66b09e7b ci: retry build - all NuGet packages pushed to Nexus
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 22m48s
2026-03-12 01:14:07 +03:30
masoodafar-web e946c56631 Revert "fix: bypass broken Nexus proxy, use nuget.org directly"
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 20m7s
This reverts commit 370f735cf2.
2026-03-12 00:06:14 +03:30
masoodafar-web 370f735cf2 fix: bypass broken Nexus proxy, use nuget.org directly
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
Nexus nuget-all proxy returns 500. Replace with direct nuget.org
source. Keep foursat-hosted for proto push step only.
2026-03-12 00:03:42 +03:30
masoodafar-web 0e9d0cad2f feat: manual payment package-based + StockMovement constraint fix
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 7m23s
- ManualPayment: add package_id to proto, handler selects package by ID
- ManualPayment: remove manual amount input, use package price
- ManualPayment: validator now checks PackageId instead of Amount
- StockMovement: fix CHECK constraint (store negative qty for decreases)
- StockMovement: Reserved/Released don't change physical Quantity
- Proto NuGet bumped to 0.0.192
2026-03-11 23:44:28 +03:30
masoodafar-web 62a0f8594d fix: Update Kavenegar API key and modify database connection string
Build and Deploy to Production / build-and-deploy (push) Successful in 8m39s
2026-02-28 05:03:38 +03:30
masoodafar-web fb81aff095 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 8m48s
# Conflicts:
#	.gitea/workflows/kub-deploy.yml
#	k8s/staging/cms-deployment.yaml
#	src/CMSMicroservice.Application/DiscountShopCQ/Commands/CompleteOrderPayment/CompleteOrderPaymentCommandHandler.cs
#	src/CMSMicroservice.Application/DiscountShopCQ/Commands/PlaceOrder/PlaceOrderCommandHandler.cs
#	src/CMSMicroservice.Application/WalletCQ/Commands/VerifyDiscountWalletCharge/VerifyDiscountWalletChargeCommandHandler.cs
#	src/CMSMicroservice.Application/WalletCQ/Commands/VerifyMagicWalletCharge/VerifyMagicWalletChargeCommandHandler.cs
#	src/CMSMicroservice.Infrastructure/Services/Payment/ZarinPalPaymentService.cs
#	src/CMSMicroservice.WebApi/Controllers/PaymentCallbackController.cs
#	src/CMSMicroservice.WebApi/appsettings.Production.json
#	src/CMSMicroservice.WebApi/appsettings.Staging.json
#	src/CMSMicroservice.WebApi/appsettings.json
2026-02-28 04:51:57 +03:30
masoodafar-web 1a0bb83c99 feat: Enhance SMS verification with new token handling and update API key
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m45s
2026-02-28 04:01:45 +03:30
masoodafar-web 1e7c17f090 feat: Update payment processing and callback mechanisms
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m22s
- Refactor ActivateClubMembershipCommandHandler to use UserPackagePurchases instead of UserOrders for package activation.
- Modify PlaceOrderCommandHandler to redirect payment callbacks to the front office.
- Update ChargeDiscountWalletCommandHandler and ChargeMagicWalletCommandHandler to direct payment callbacks to the front office.
- Remove PaymentCallbackController and integrate payment verification directly into DiscountOrderService and UserWalletService.
- Add CustomerVerifyDiscountOrderPayment RPC to DiscountOrderService for verifying discount order payments.
- Implement VerifyMagicCharge and VerifyDiscountCharge methods in UserWalletService for wallet charge verifications.
- Update appsettings.json to use local URLs for development.
- Remove appsettings.Development.json as it is no longer needed.
- Comment out history tracking methods in ClubMembershipCycle and Package classes.
- Update PackageService to automatically activate club membership after successful payment verification.
- Adjust UserService to generate JWT tokens with user details.
2026-02-28 03:27:46 +03:30
masoodafar-web 01073084ab security: remove callback URL from user input — read from FrontOfficeBaseUrl config
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m28s
- PackageService: build callback URL from FrontOfficeBaseUrl config instead of request.CallbackUrl
- TransactionsService: same fix — callback URL from config
- Prevents potential open redirect vulnerability (user could send arbitrary URL)

All callback URLs now come from appsettings FrontOfficeBaseUrl or CmsBaseUrl.
2026-02-27 22:20:04 +03:30
masoodafar-web ed2b20a98e fix: wallet callback URL issues
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- PaymentCallbackController: fix redirect paths /magic-wallet → /profile/magic-wallet
- Add appsettings.Development.json with local CmsBaseUrl (localhost:32846) and FrontOfficeBaseUrl (localhost:5268)
- Proto: fix comments ریال → تومان in wallet charge messages

Root cause: CmsBaseUrl in appsettings.json points to stage (cms.se.kbs1.ir),
so when testing locally, ZarinPal callback went to stage CMS instead of local.
Also redirect after verify used wrong FO path (/magic-wallet instead of /profile/magic-wallet).
2026-02-27 22:09:15 +03:30
masoodafar-web 721661af0f fix: pass amount to ZarinPal VerifyPaymentAsync — fix verify failure (amount=0 bug)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m38s
- PackageService.CustomerVerifyPackagePurchase: look up PaymentTransaction.Amount and pass to 3-arg overload
- TransactionsService.CustomerPaymentVerification: same fix
- VerifyDiscountWalletChargeCommandHandler: look up amount from PaymentTransaction
- VerifyPackagePurchaseCommandHandler: fix copy-paste bug (Authority as verificationToken) + add amount
- IPaymentGatewayService: throw NotImplementedException in default 3-arg impl to prevent silent amount=0
- MockPaymentGatewayService & DayaPaymentService: add 3-arg overload for compatibility

Root cause: ZarinPal requires the exact amount in verify request.
The 2-arg overload was sending amount=0 which caused Code=-1 (تأیید تراکنش ناموفق).
2026-02-27 21:17:50 +03:30
masoodafar-web aee7b59fc1 fix: Toman/Rial — system uses Toman everywhere, only ZarinPal gets Rial
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 10m16s
Core change in ZarinPalPaymentService:
- InitiatePaymentAsync: Amount (Toman) × 10 → Rial for gateway
- VerifyPaymentWithAmountAsync: Amount (Toman) × 10 → Rial for verify
- Verify result: gateway Rial ÷ 10 → Toman back to system

Also fixed:
- Package.Price doc: ریال → تومان
- Error messages in 3 handlers: ریال → تومان
- ConfigurationService descriptions: ریال → تومان (7 entries)
- Notification SMS/email: ریال → تومان
- Doc comments in 5 command files: ریال → تومان
- PaymentCallback comments: ریال → تومان

14 files changed across Domain, Application, Infrastructure, WebApi
2026-02-27 21:03:27 +03:30
masoodafar-web 61b7e4f8f2 F2-F7: نوتیفیکیشن‌ها+نام‌پکیج، ستون پکیج در CSV، مقادیر داینامیک کیف‌پول جادویی، ولیدیتور SystemConstants
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m29s
F2: اضافه شدن packageName به SmsTemplates، IUserNotificationService، UserNotificationService
    - DayaLoan، ClubActivated، CommissionDeposited حالا نام پکیج را نشان می‌دهند
F4: اضافه شدن ستون پکیج به CSV خروجی‌ها
    - commission.proto: package_name در WithdrawalRequestModel
    - manualpayment.proto: package_name در ManualPaymentModel
    - کوئری‌هندلرها UserPackagePurchases لوکاپ اضافه شد
F6: مقادیر داینامیک کیف‌پول جادویی از پکیج
    - userwallet.proto: magic_multiplier + magic_max_credit
    - UserWalletService: پاپیولیت فیلدهای جدید + فالبک به SystemConstants
F7: ولیدیتورها از SystemConstants استفاده می‌کنند
    - WalletMaxSafeAmount (10B ریال) به عنوان حصار ایمنی
    - MagicWalletMinCharge، DiscountWalletMinCharge ثابت‌های مرکزی
    - سقف واقعی per-package در هندلرها اعمال می‌شود
Proto: v0.0.189
2026-02-27 08:47:46 +03:30
masoodafar-web e5bc3a952a feat: ClubMembershipCycle IHasHistory + PackageId in WalletHistory (F1)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m33s
- ClubMembershipCycle now implements IHasHistory<ClubMembershipCycleHistory>
  - CreateHistorySnapshot: New* fields from current state, Old* auto-filled by interceptor
  - Parses action string to ClubMembershipCycleAction enum

- Add PackageId to 6 UserWalletHistory creation sites (F1 fix):
  - VerifyPackagePurchaseCommandHandler: balanceLog + discountLog (order.PackageId)
  - CheckAndProcessDayaLoansCommandHandler: mainLog + discountLog (package.Id)
  - CreateManualPaymentCommandHandler: walletLog (package.Id)
  - PackageService.CustomerVerifyPackagePurchase: walletLog (purchase.PackageId)
  - Non-package flows (orders, commissions, manual) correctly keep PackageId=null
2026-02-27 07:07:30 +03:30
masoodafar-web 10d2ca20d1 refactor: rename UserWalletChangeLog→UserWalletHistory, add History interceptor & migration
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m11s
- Rename UserWalletChangeLog to UserWalletHistory across 54+ files (entities, configs, DTOs, commands, queries, protos, services)
- Rename 34 files and 11 directories accordingly
- Rename proto file userwalletchangelog.proto → userwallethistory.proto
- Add IHasHistory<T> generic interface for history auto-tracking
- Implement IHasHistory<PackageHistory> on Package entity
- Add HistoryTrackingSaveChangesInterceptor (reflection-based, auto-fills Old* values from OriginalValues)
- Wire interceptor in DI and ApplicationDbContext
- Add EF migration Q27_HistoryTables_And_RenameWalletHistory:
  * RenameTable UserWalletChangeLogs → UserWalletHistories (preserves data)
  * Rename PK, FK constraints and indexes via sp_rename
  * CreateTable ClubMembershipCycleHistories + PackageHistories
2026-02-27 06:22:15 +03:30
masoodafar-web fdbb91d2e1 feat(Q27): PackageHistory + ClubMembershipCycleHistory entities
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m28s
Q27: History Tables standardization — added missing history entities:
- PackageHistory: tracks price, activation fee, magic settings changes
- ClubMembershipCycleHistory: tracks cycle state transitions
- PackageAction + ClubMembershipCycleAction enums
- EF configurations with proper indexes and FK relationships
- DbSets registered in IApplicationDbContext + ApplicationDbContext
- Navigation properties on Package + ClubMembershipCycle entities
2026-02-27 05:31:21 +03:30
masoodafar-web a1024a3e18 feat(Q24+Q26): balance threshold + SP auto-deploy worker
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m25s
Q24: Magic wallet entry/exit trigger now uses Balance <= 1,000,000 Rials
  instead of Balance == 0 (products have varying prices so exact zero
  is unreachable). Added MagicWalletEntryThreshold to SystemConstants.

Q26: StoredProcedureDeploymentService (IHostedService) auto-deploys
  stored procedures on startup via embedded SQL resources + SHA256
  checksum comparison. Creates [CMS].[__StoredProcedureVersions] table
  automatically. Supports GO batch separators.
2026-02-27 04:22:24 +03:30
masoodafar-web 1ac23667e2 fix: package-based compliance audit — feature DIFF, remove hardcoded fallbacks
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m12s
- ActivateClubMembership: replace GetAllFeatureIds with PackageFeature DIFF (Q20)
- ActivateClubMembership: fix re-activation early return — check current cycle
- AcceptClubMembershipContract: same feature DIFF logic
- VerifyPackagePurchase: remove ?? 2.0m fallback, throw if package null
- PackageService: remove ?? 2.0m fallback for DiscountMultiplier
- UserOrderService: remove ?? 1B fallback for MagicWalletMaxDeposit
- SystemConstants: remove 9 dead [Obsolete] constants (per-package values)
2026-02-27 02:35:41 +03:30
masoodafar-web dcd11351a3 feat(T4.13): add PackageFeature CRUD support
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m41s
- Proto: add feature_ids to Create/Update/Get package messages
- Commands: add FeatureIds to Create/Update commands
- Handlers: sync PackageFeature join entities on create/update
- Queries: include PackageFeatures, map FeatureIds in responses
- Bump NuGet to v0.0.188
2026-02-26 21:59:24 +03:30
masoodafar-web aaaf7fc1ca feat(commission): add per-package filtering to commission & balance queries
- Proto: add package_id filter to 4 request messages, package_id/package_title to 4 response models
- Queries: add PackageId filter to GetUserWeeklyBalances, GetUserCommissionPayouts, GetMyCommissionPayouts, GetMyWeeklyBalances
- Handlers: include Package navigation, filter by PackageId, map PackageId/PackageTitle
- DTOs: add PackageId + PackageTitle to all response models
- Mappings: update CommissionProfile with PackageId/PackageTitle for all admin+customer mappings
- NuGet: bump proto version to 0.0.187
2026-02-26 21:07:59 +03:30
masoodafar-web 7554d7054a Phase 8d: Proto cleanup — delete 4 deprecated RPCs + 8 deprecated messages
- Deleted RPCs: PurchaseGoldenPackage, VerifyGoldenPackagePurchase,
  InitiateBasePackagePayment, VerifyBasePackagePayment
- Deleted messages: PurchaseGoldenPackage{Request,Response},
  VerifyGoldenPackagePurchase{Request,Response},
  InitiateBasePackagePayment{Request,Response},
  VerifyBasePackagePayment{Request,Response}
- Kept: GetUserPackageStatus (still in use)
- NuGet version bump: 0.0.185 → 0.0.186
2026-02-26 18:00:40 +03:30
masoodafar-web ce8e248843 Phase 8b: Bump Protobuf NuGet to v0.0.185 2026-02-26 17:42:59 +03:30
masoodafar-web 8446e0e3b5 Phase 7c: Delete deprecated handlers + clean service/mapping refs
- Delete 4 deprecated CQRS handler folders (12 files):
  - PurchaseGoldenPackage/ (Command, Handler, Validator)
  - VerifyGoldenPackagePurchase/ (Command, Handler, Validator)
  - InitiateBasePackagePayment/ (Command, Handler, Validator)
  - VerifyBasePackagePayment/ (Command, Handler, Validator)
- PackageService.cs: Remove 4 gRPC override methods that dispatched
  to deleted handlers (proto RPCs now auto-throw Unimplemented)
- PackageProfile.cs: Remove all Mapster mappings for deleted types
  (6 mapping blocks + 4 using directives removed)
- Customer* RPCs remain fully functional
- Build: 0 errors
2026-02-26 03:02:17 +03:30
masoodafar-web 161f796cd4 Phase 7b: Embed orderId in callback URL for CustomerPurchasePackage
- CustomerPurchasePackage: append orderId to callback URL before sending to gateway
- Ensures PaymentCallback page receives orderId via query string for verification
2026-02-26 02:34:47 +03:30
masoodafar-web 469d97bb60 Phase 7a: Cosmetic cleanup + delete orphaned PurchasePackage handler
- Delete orphaned PurchasePackageCommand handler (no RPC dispatch, no callers)
- Fix doc-comments: طلایی → پکیج in enums, entities, handlers
- Remove stale 56M inline comments
- Clean SystemConstants deprecated field docs
2026-02-26 02:01:33 +03:30
masoodafar-web d19c569aae Phase 6: Deprecation cleanup + ConfigurationService MagicWallet
- Mark PurchaseGoldenPackage/VerifyGoldenPackagePurchase RPCs as deprecated
- Mark InitiateBasePackagePayment/VerifyBasePackagePayment RPCs as deprecated
- Remove deprecated SystemConstants from GetAllAsDict/GetAllWithDescriptions helpers
- Add MagicWallet per-package values to ConfigurationService (Multiplier, MaxDeposit, MaxCredit)
- All deprecated constants have zero active code usages — safe dead code
2026-02-26 01:10:43 +03:30
masoodafar-web 7176fe44ee Fix SP: cm.PackageId → cm.LastPackageId (match actual DB column name) 2026-02-26 00:59:59 +03:30
masoodafar-web 607f791b65 Phase 5: Per-package commission + golden ref cleanup
- Fix golden/طلایی string refs in user-facing messages (ActivateClubMembership)
- Rename HasPurchasedGoldenPackage → HasPurchasedPackage (DTO, Handler, Proto, Mapping)
- ORM commission: per-user-package calculation via ClubMembership.LastPackageId
  - Build userPackageMap, per-user maxBalancesPerLeg/maxNetworkLevel
  - Carryover keyed by (UserId, PackageId) tuple
- SP commission: loop over packages, pass @PackageId/@InputMaxBalancesPerLeg/@InputMaxNetworkLevel
- sp_CalculateWeeklyBalances: accept 3 new params, filter by PackageId, insert PackageId column
2026-02-26 00:57:20 +03:30
masoodafar-web 0002a5a6f2 Phase 4: Complete Package CRUD DTOs + Legacy Fixes
- CreateNewPackageCommand: Add 12 new Package fields (SortOrder, IsActive, IsBasePackage,
  SupportsDayaPurchase, SupportsDirectPurchase, ActivationFee, DiscountMultiplier,
  MagicWalletMultiplier, MaxBalancesPerLeg, MaxNetworkLevel, MagicWalletMaxDeposit,
  MagicWalletMaxCredit) with sensible defaults
- GetPackageResponseDto: Add 12 new fields (Mapster auto-maps via ProjectToType)
- GetAllPackageByFilterResponseModel: Add 12 new fields (Mapster auto-maps)
- PurchaseGoldenPackage: Replace fragile Title string match ('طلایی'/'golden')
  with proper IsDeleted/IsActive/SupportsDirectPurchase validation
- VerifyPackagePurchase: Replace hardcoded order.Amount*2 with
  package.DiscountMultiplier from DB (fallback 2.0 for null Package)
2026-02-26 00:24:35 +03:30
masoodafar-web ccb938e9ba Phase 3: Package layer overhaul — fix critical bugs + proto enhancement
Proto (package.proto):
- Add 11 new Package fields to Create/Update/Get/GetAll messages
- Add 8 new fields to CustomerPackageModel for frontend

Critical Bug Fixes:
- VerifyGoldenPackagePurchase: Replace hardcoded ×2 with package.DiscountMultiplier from DB

Query Fixes:
- GetAllPackageByFilter: Add IsDeleted filter (was returning soft-deleted packages)
- GetCustomerPackages: Apply IsDeleted+IncludeInactive filters, sort by SortOrder, return new fields
- GetCustomerPackageDetails: Load PackageFeatures from DB (was hardcoded), add IsDeleted filter, return new fields
- GetCustomerPurchaseHistory: Include Transaction (was null → ReferenceCode always empty)

UpdatePackage: Add 12 new fields (SortOrder, IsActive, IsBasePackage, etc.)

Build: 0 errors
2026-02-25 23:50:09 +03:30
masoodafar-web 8e5c7c5205 Phase 2: Replace all deprecated SystemConstants with Package entity reads
- ActivateClubMembership: Load Package, set First/Last fields, PackageId on Cycle+Pool
- AcceptClubMembershipContract: Load Package, set First/Last fields, PackageId on Pool
- CalculateWeeklyBalances: Load base package, use package.MaxBalancesPerLeg/MaxNetworkLevel, set PackageId on NetworkWeeklyBalance
- ProcessUserPayouts: Load base package, use package.MaxNetworkLevel, set PackageId on UserCommissionPayout
- CheckAndProcessDayaLoans: Load base package (IsBasePackage), replace DayaLoanAmount→package.Price, fix hardcoded p.Id==4
- CreateManualPayment: Load base package, replace BasePackageAmount→package.Price, use DiscountMultiplier
- InitiateBasePackagePayment: Remove hardcoded BasePackageId=4, load from IsBasePackage, use package.Price/Id
- VerifyBasePackagePayment: Load Package from order.PackageId, use package.Price+DiscountMultiplier
- ChargeMagicWallet: Load user's package from current cycle, use package.MagicWalletMaxDeposit
- VerifyMagicWalletCharge: Load user's package, use package.MagicWalletMultiplier/MagicWalletMaxDeposit
- OrmCommissionCalculationStrategy: Load base package in both methods, set PackageId on Balance+Payout
- ConfigurationService: Inject IApplicationDbContext, read package values from DB instead of SystemConstants
- UserOrderService: Load user's package for EXIT trigger MagicWalletMaxDeposit check
- UserWalletService: Load user's package for GetMagicWalletStatus display

All 9 deprecated SystemConstants now have ZERO usages outside SystemConstants.cs
Build: 0 errors, 521 warnings (all pre-existing)
2026-02-25 23:25:18 +03:30
masoodafar-web a9cd2fd67a Phase 1.5: EF Migration + Data Seed + Backfill
MIGRATION (AddPackageBasedSystem):
- Adds 11 new columns to Packages table
- Creates PackageFeatures table (Package×ClubFeature junction)
- Adds PackageId FK to: ClubMembershipCycles, WeeklyCommissionPools,
  UserCommissionPayouts, NetworkWeeklyBalances, UserWalletChangeLogs
- Adds First/LastActivationDate, First/LastPackageId to ClubMemberships
- Drops old unique indexes, creates new composite unique indexes:
  (WeekDef,Package), (User,WeekDef,Package)

DATA MIGRATION (embedded in EF migration):
1. Seeds Golden Package (Id=1): Price=56M, ActivationFee=25.2M,
   DiscountMultiplier=2.0, MagicWalletMultiplier=2.5, MaxBalancesPerLeg=300,
   MaxNetworkLevel=15, MagicWalletMaxDeposit=1B, MagicWalletMaxCredit=2.5B
2. Backfills PackageId=1 on all existing commission/network records
3. Backfills ClubMembership First/Last fields from existing ActivatedAt

FIXES:
- ClubMembership First/Last fields now nullable (DateTime?, long?)
  for backward compat with existing records
- UserPackagePurchaseConfiguration: .WithMany() → .WithMany(p => p.Purchases)
  to prevent shadow FK PackageId1

Build: 0 errors, 73 warnings
2026-02-25 22:49:12 +03:30
masoodafar-web ae92ab8697 Phase 1: Package-Based Domain Infrastructure
ENTITIES:
- Package: +11 fields (SortOrder, IsActive, IsBasePackage, SupportsDaya/Direct,
  ActivationFee, DiscountMultiplier, MagicWalletMultiplier, MaxBalancesPerLeg,
  MaxNetworkLevel, MagicWalletMaxDeposit/Credit) + nav props
- PackageFeature: NEW junction entity (Package × ClubFeature) for feature DIFF
- ClubMembership: +4 fields (FirstActivationDate/PackageId, LastActivation/PackageId)
  ActivatedAt kept as [Obsolete] for backward compat
- ClubMembershipCycle: +PackageId FK (tracks which package per cycle)
- WeeklyCommissionPool: +PackageId FK (separate pool per package)
- UserCommissionPayout: +PackageId FK (payout per package)
- NetworkWeeklyBalance: +PackageId FK (balance per package)
- UserWalletChangeLog: +PackageId? FK (optional package tracking)

EF CONFIGS:
- PackageConfiguration: 11 new field configs + indexes
- PackageFeatureConfiguration: NEW (unique PackageId+ClubFeatureId)
- ClubMembershipConfiguration: First/Last Package FKs + LastActivationDate index
- ClubMembershipCycleConfiguration: Package FK
- WeeklyCommissionPoolConfiguration: Package FK + unique(WeekDef,Package)
- UserCommissionPayoutConfiguration: Package FK + unique(User,WeekDef,Package)
- NetworkWeeklyBalanceConfiguration: Package FK + unique(User,WeekDef,Package)
- UserWalletChangeLogConfiguration: Package FK (nullable)

DBCONTEXT:
- DbSet<PackageFeature> added to ApplicationDbContext + IApplicationDbContext

SYSTEMCONSTANTS:
- 9 constants marked [Obsolete] → moved to Package entity
  (ClubMembershipGiftValue, ClubActivationFee, BasePackageAmount, DayaLoanAmount,
   MagicWalletMultiplier, MagicWalletMaxDeposit, MagicWalletMaxCredit,
   CommissionMaxWeeklyBalancesPerLeg, CommissionMaxNetworkLevel)

Build: 0 errors, 610 warnings (40 new = expected Obsolete CS0618)
2026-02-25 22:32:42 +03:30
masoodafar-web fe3edd178d fix(B6): EXIT Magic Mode — reset PackagePurchaseMethod + close current cycle
B6: PackagePurchaseMethod was NOT reset when exiting Magic Mode.
This caused Guards G1-G3 to permanently block re-purchase.

Changes:
- user.PackagePurchaseMethod = None (allows re-purchase via G1-G3)
- currentCycle.IsCurrentCycle = false (ready for new cycle)

Note: membership.IsActive is intentionally preserved (Q19 — contract is one-time).
Features are preserved — DIFF will be applied on next purchase (Q20).
2026-02-25 21:59:30 +03:30
masoodafar-web 13dd0f552f refactor: archive 12 dead gRPC RPCs with [ARCHIVED] markers
Archived RPCs (code preserved, marked obsolete):
- fms.proto: excluded from csproj (CreateNewFileInfo, DeleteFileInfo)
- UserOrderService: GetOrdersByDateRange, CreateNewOrderForCustomer, SubmitOrderForCustomer
- ConfigurationService: DeactivateConfiguration, GetConfigurationHistory
- CityService: UpdateCity, DeleteCity
- HealthService: GetServiceHealth
- CategoryService: GetCategoryByIdForCustomer
- inventory.proto: BulkAdjustStock (no implementation existed)

All archived RPCs wrapped in #region [ARCHIVED] with [Obsolete] attributes.
No code deleted — archive only. Build passes with 0 errors.
2026-02-24 22:53:36 +03:30
masoodafar-web 8b9c317de6 fix: Phase 0 — critical bugs in package purchase handlers
B1: VerifyGoldenPackagePurchase — DiscountBalance was NOT charged (Amount × 2)
    Now charges DiscountBalance same as all other handlers.

B2: VerifyGoldenPackagePurchase — UserPackagePurchase record was NOT created
    Now creates UPP with OrderId and TransactionId.

B3: VerifyPackagePurchase — UserPackagePurchase record was NOT created
    Now creates UPP after wallet charge.

B4: VerifyBasePackagePayment — UserPackagePurchase record was NOT created
    Now creates UPP after wallet change log.

Also: VerifyGolden WalletChangeLog split into 2 logs (Balance + Discount)
      to match the pattern used by VerifyPackagePurchase.
      Transaction description changed from 'پکیج طلایی' to 'پکیج' (generic).

Impact: Only Daya Loan handler was creating UserPackagePurchase before.
        Now all 4 payment paths create it consistently.
2026-02-24 21:52:36 +03:30
masoodafar-web 491b8a0d0f fix: remove double ×10 Rial conversion in ZarinPalPaymentService
Build and Deploy to Production / build-and-deploy (push) Successful in 10m10s
Root cause: FrontOffice already converts Toman→Rial (×10) before sending
to CMS. ZarinPalPaymentService was multiplying by 10 AGAIN, causing
amounts to be 10x too large.

Example: user enters 500K Toman → FO sends 5M Rial → CMS did ×10 → 50M
Rial sent to ZarinPal → showed 5M Toman instead of 500K.

Changes:
- ZarinPalPaymentService.InitiatePaymentAsync: remove ×10 (amount already Rial)
- ZarinPalPaymentService.VerifyPaymentWithAmountAsync: remove ×10 + accept Rial
- ZarinPalPaymentService.VerifyResult.Amount: return Rial (no /10 conversion)
- VerifyMagicWalletChargeCommandHandler: remove /10 before calling Verify
- PaymentCallbackController: update comments (amount is Rial)
- Also includes: improved HTTP error logging for non-200 responses
- Also includes: production URL fix (kbs1→kbs2)
2026-02-24 00:49:47 +03:30
masoodafar-web cbaa20f339 fix: remove double ×10 Rial conversion in ZarinPalPaymentService
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
Root cause: FrontOffice already converts Toman→Rial (×10) before sending
to CMS. ZarinPalPaymentService was multiplying by 10 AGAIN, causing
amounts to be 10x too large.

Example: user enters 500K Toman → FO sends 5M Rial → CMS did ×10 → 50M
Rial sent to ZarinPal → showed 5M Toman instead of 500K.

Changes:
- ZarinPalPaymentService.InitiatePaymentAsync: remove ×10 (amount already Rial)
- ZarinPalPaymentService.VerifyPaymentWithAmountAsync: remove ×10 + accept Rial
- ZarinPalPaymentService.VerifyResult.Amount: return Rial (no /10 conversion)
- VerifyMagicWalletChargeCommandHandler: remove /10 before calling Verify
- PaymentCallbackController: update comments (amount is Rial)
- Also includes: improved HTTP error logging for non-200 responses
- Also includes: production URL fix (kbs1→kbs2)
2026-02-24 00:49:16 +03:30
masoodafar-web be80136ae8 fix: reduce discount order expiry from 30 to 15 minutes
Build and Deploy to Production / build-and-deploy (push) Successful in 9m8s
2026-02-24 00:24:30 +03:30
masoodafar-web 5e9984f0e5 fix: validate discount wallet balance before applying discount in PlaceOrderCommandHandler 2026-02-24 00:24:30 +03:30
masoodafar-web 1d07ae4f71 fix: add missing UserWalletChangeLog for discount shop purchases and discount wallet charge
Bug: when buying from discount shop, DiscountBalance was deducted from DB
but no UserWalletChangeLog was created — making it invisible in wallet history.
Same issue existed for discount wallet top-up (charge).

Fixed in 3 handlers:
- PlaceOrderCommandHandler (fully paid by discount balance path)
- CompleteOrderPaymentCommandHandler (gateway + discount balance path)
- VerifyDiscountWalletChargeCommandHandler (discount wallet charge)
2026-02-24 00:24:30 +03:30
masoodafar-web e206b71186 fix: reduce discount order expiry from 30 to 15 minutes
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-02-24 00:24:02 +03:30
masoodafar-web 775a9bd75d fix: update .gitignore to include environment-specific appsettings files 2026-02-24 00:18:42 +03:30
masoodafar-web 2620a24597 fix: correct production URLs from kbs1 to kbs2 in cms-config
CmsBaseUrl: cms.kbs1.ir → cms.kbs2.ir
FrontOfficeBaseUrl: kbs1.ir → kbs2.ir

This was causing ZarinPal callback to go to staging instead of production,
resulting in 401 errors (-1 unknown error).
2026-02-24 00:18:24 +03:30
masoodafar-web def3b94d89 fix: update appsettings for production environment — adjust URLs and connection strings
Build and Deploy to Production / build-and-deploy (push) Successful in 9m32s
2026-02-23 23:59:41 +03:30
masoodafar-web 0457ef6c7c fix: validate discount wallet balance before applying discount in PlaceOrderCommandHandler
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m36s
2026-02-23 23:06:37 +03:30
masoodafar-web f3ac5ad7df fix: add missing UserWalletChangeLog for discount shop purchases and discount wallet charge
Bug: when buying from discount shop, DiscountBalance was deducted from DB
but no UserWalletChangeLog was created — making it invisible in wallet history.
Same issue existed for discount wallet top-up (charge).

Fixed in 3 handlers:
- PlaceOrderCommandHandler (fully paid by discount balance path)
- CompleteOrderPaymentCommandHandler (gateway + discount balance path)
- VerifyDiscountWalletChargeCommandHandler (discount wallet charge)
2026-02-23 22:59:00 +03:30
masoodafar-web 3ebe0f9f48 chore(production): remove appsettings.Staging.json — config comes from K8s Secret
Build and Deploy to Production / build-and-deploy (push) Successful in 12m5s
DO NOT cherry-pick this commit to kub-stage branch
2026-02-23 22:10:53 +03:30
masoodafar-web e72673c184 chore(staging): remove appsettings.Production.json — config comes from K8s Secret
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m42s
DO NOT cherry-pick this commit to production branch
2026-02-23 22:07:58 +03:30
masoodafar-web f4e24f7449 feat: externalize appsettings to K8s Secret — config persists independently of image rebuilds
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
- Add cms-config.yaml (K8s Secret) for staging and production
- Mount appsettings.{Environment}.json from Secret into /app/
- Update CI/CD pipelines to apply Secret before Deployment
- Remove redundant env vars (Kestrel, FileStorage) — now in config file
2026-02-23 21:58:56 +03:30
masoodafar-web 9288d0640b feat: externalize appsettings to K8s Secret — config persists independently of image rebuilds
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m57s
- Add cms-config.yaml (K8s Secret) for staging and production
- Mount appsettings.{Environment}.json from Secret into /app/
- Update CI/CD pipelines to apply Secret before Deployment
- Remove redundant env vars (Kestrel, FileStorage) — now in config file
2026-02-23 21:58:05 +03:30
masoodafar-web 540a2ce4fc fix: production uses namespace default + remove foursat namespace references
Build and Deploy to Production / build-and-deploy (push) Successful in 8m44s
2026-02-23 21:36:16 +03:30
masoodafar-web de83c31346 fix: production uses namespace default + remove foursat namespace references
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m18s
2026-02-23 21:36:08 +03:30
masoodafar-web e57f01965a fix: staging ASPNETCORE_ENVIRONMENT=Staging, remove secretKeyRef (config in appsettings)
Build and Deploy to Production / build-and-deploy (push) Failing after 8m36s
2026-02-23 21:17:34 +03:30
masoodafar-web f8dc4abd04 fix: staging ASPNETCORE_ENVIRONMENT=Staging, remove secretKeyRef (config in appsettings)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m28s
2026-02-23 21:17:23 +03:30
masoodafar-web f97c4b0812 fix: use local registry 194.5.195.53:30080 instead of git.se.kbs1.ir for image pull
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2026-02-23 20:58:28 +03:30
masoodafar-web 2d6c95e6ee fix: use local registry 194.5.195.53:30080 instead of git.se.kbs1.ir for image pull
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 11m28s
2026-02-23 20:58:16 +03:30
masoodafar-web fd32e15192 fix: production ingress — add cms.kbs2.ir, use ingressClassName instead of annotation
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2026-02-23 20:42:28 +03:30
masoodafar-web e41747afe0 fix: production ingress — add cms.kbs2.ir, use ingressClassName instead of annotation
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 12m6s
2026-02-23 20:41:12 +03:30
masoodafar-web 68da3f45a3 fix: staging uses namespace default, not foursat
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-02-23 20:38:27 +03:30
masoodafar-web 4456e504d4 feat: add PersistentVolume for CMS uploads + apply manifests in CI/CD
Build and Deploy to Production / build-and-deploy (push) Failing after 8m12s
- Add k8s/staging/ and k8s/production/ deployment manifests
- PVC 20Gi for /app/Uploads (file uploads persist across pod restarts)
- FileStorage__UploadPath env var set to /app/Uploads
- Replicas reduced to 1 (ReadWriteOnce PVC)
- Pipelines now: create namespace → apply manifests → restart/update
2026-02-23 20:12:24 +03:30
masoodafar-web 3153fd8a74 feat: add PersistentVolume for CMS uploads + apply manifests in CI/CD
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 12m12s
- Add k8s/staging/ and k8s/production/ deployment manifests
- PVC 20Gi for /app/Uploads (file uploads persist across pod restarts)
- FileStorage__UploadPath env var set to /app/Uploads
- Replicas reduced to 1 (ReadWriteOnce PVC)
- Pipelines now: create namespace → apply manifests → restart/update
2026-02-23 20:11:56 +03:30
masoodafar-web 8cdb197ee7 chore: prevent appsettings.Production.json from merging — keep ours strategy
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m15s
2026-02-23 00:01:56 +03:30
masoodafar-web cec1e74f6c chore: prevent appsettings.Production.json from merging — keep ours strategy
Build and Deploy to Production / build-and-deploy (push) Successful in 10m59s
2026-02-22 23:59:36 +03:30
masoodafar-web dd9ac48474 fix: update CMS and FrontOffice base URLs to reflect new domain
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2026-02-22 23:53:56 +03:30
masoodafar-web 2ca3fd29f9 feat: admin force activation — skip order/wallet checks for BackOffice
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m12s
- Proto: add force_activation field to ActivateClubMembershipRequest
- Command: add ForceActivation property
- Handler: wrap steps 2-5 in ForceActivation guard
  - Skip PackagePurchaseMethod check (set to DirectPurchase if None)
  - Skip wallet balance check
  - Skip Magic wallet mode check
  - Skip UserOrder/Transaction validation
- Proto NuGet bumped to 0.0.184
2026-02-22 23:51:39 +03:30
masoodafar-web eb1b249869 Merge kub-stage into production
Build and Deploy to Production / build-and-deploy (push) Successful in 11m49s
- Resolved appsettings.Production.json conflict (new MerchantId, SeedWorkers)
- Removed duplicate u21 migration (kept 155925 from production)
- All features: Magic Wallet, Discount Wallet, StockMovement fix, FullInformation expansion, Wallet user_name, gateway activation
2026-02-22 22:21:36 +03:30
masoodafar-web b9a72b4589 fix: environment-specific gateway config — staging=sandbox, production=real
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m37s
- appsettings.json/Staging.json: UseSandbox=true (sandbox mode for testing)
- appsettings.Production.json: UseSandbox=false, MerchantId=new production key
- Added SeedWorkers, Kestrel, Seq overrides to Production config
2026-02-22 22:18:51 +03:30
masoodafar-web 5c63dc6e38 feat: activate ZarinPal gateway with production MerchantId
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
- MerchantId: 4225d555-5fa9-4df0-9b61-1ce152cbbba8
- UseSandbox: false (production mode)
2026-02-22 22:12:02 +03:30
masoodafar-web 52f6af2091 feat: add user_name to wallet response + enrich via Users table
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m59s
- userwallet.proto: added string user_name = 5 to GetAllUserWalletByFilterResponseModel
- UserWalletService: enriches response with user names from Users table
- Proto version bumped to 0.0.183
2026-02-22 22:02:54 +03:30
masoodafar-web e3fbd45739 fix: expand DiscountProducts.FullInformation from nvarchar(2000) to nvarchar(max) — HTML content was getting truncated
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m17s
2026-02-22 21:44:03 +03:30
masoodafar-web 0fe4db5e77 fix: StockMovement CHECK constraint violation — store Quantity as negative for reduce operations, pass correct MovementType from RecordLoss
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-02-22 21:38:20 +03:30
masoodafar-web 305b8d3fd8 feat: add MagicWalletCycleSeedService — one-time BackgroundService to seed ClubMembershipCycle for existing active memberships, controlled via appsettings SeedWorkers:MagicWalletCycleSeed:Enabled
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m36s
2026-02-22 21:14:09 +03:30
masoodafar-web df976b7b80 fix: Update project version to 0.0.182
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m5s
2026-02-22 20:48:26 +03:30
masoodafar-web b90aa50fac feat: ChargeDiscountWallet - callback endpoint, gRPC RPC & service implementation
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 10m43s
- Add /api/wallet/verify-discount-charge callback endpoint in PaymentCallbackController
- Add InitiateDiscountCharge RPC + request/response messages in userwallet.proto
- Add InitiateDiscountCharge gRPC service override in UserWalletService
- Add ChargeDiscountWallet using import for handler resolution
2026-02-22 20:22:44 +03:30
masoodafar-web 58d419ced3 feat: Magic Wallet Phase 6 + Daya restriction + purchase cycle count
- ActivateClubMembershipCommandHandler: block activation in Magic mode
- CheckAndProcessDayaLoansCommandHandler: reject Daya after first cycle
- userwallet.proto: add purchase_cycle_count to GetMagicWalletStatusResponse
- UserWalletService: query ClubMembershipCycles count for cycle info
- EF Migration u21: ClubMembershipCycle table + UserWallet Magic fields
2026-02-22 20:04:13 +03:30
masoodafar-web e8e964f9a0 Add migration for UserWallets and ClubMembershipCycles schema updates
- Added columns to UserWallets: MagicActivatedAt, MagicCompletedAt, MagicTotalCredited, MagicTotalDeposited, and WalletMode.
- Created new table ClubMembershipCycles with relevant fields and constraints.
- Established foreign key relationships with Users and ClubMemberships.
- Added indexes for optimized queries on ClubMembershipCycles.
2026-02-22 19:33:56 +03:30
masoodafar-web 9050c00297 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 8m56s
2026-02-21 20:37:55 +03:30
masoodafar-web bdd2c51726 fix: Update project version to 0.0.181 and adjust NuGet package path
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-02-21 20:37:14 +03:30
masoodafar-web 2a569a024f feat: Implement Magic Wallet functionality
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m36s
- Added ClubMembershipCycle entity and DbSet to IApplicationDbContext.
- Updated VAT rate from 9% to 10% in VatCalculator and related areas.
- Introduced Magic Wallet settings in SystemConstants.
- Enhanced UserWallet entity to support Magic Wallet features.
- Updated TransactionType enum to include Magic Wallet transactions.
- Configured UserWallet to handle Magic Wallet properties in ApplicationDbContext.
- Implemented OrmCommissionCalculationStrategy to exclude Magic Wallet users from commission calculations.
- Added Protobuf definitions for Magic Wallet methods and responses.
- Created PaymentCallbackController endpoint for handling Magic Wallet charge callbacks.
- Updated UserOrderService to manage Magic Wallet state transitions.
- Developed UserWalletService to support Magic Wallet operations.
- Created ChargeMagicWalletCommand and its handler for initiating Magic Wallet charges.
- Implemented VerifyMagicWalletChargeCommand and handler for payment verification.
- Added validation for ChargeMagicWalletCommand.
- Established ClubMembershipCycle configuration for EF Core.
- Introduced WalletMode enum to differentiate between Normal and Magic modes.
2026-02-21 19:50:28 +03:30
masoodafar-web 04e8c49fa7 fix: IPG DiscountBalance should be 2× BasePackageAmount (112M not 56M)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m44s
Both VerifyBasePackagePayment and VerifyPackagePurchase handlers were
charging DiscountBalance with 1× amount instead of 2×.
Now consistent with DayaLoan and ManualPayment handlers.

- VerifyBasePackagePaymentCommandHandler: DiscountBalance += BasePackageAmount * 2
- VerifyPackagePurchaseCommandHandler: DiscountBalance += order.Amount * 2
- Change logs updated to reflect correct 2× discount value
2026-02-18 23:12:03 +03:30
masoodafar-web f968a6c005 docs: move README to totalDoc, replace with placeholder
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m50s
2026-02-18 21:44:46 +03:30
masoodafar-web 6048824b33 docs: move README to totalDoc, replace with placeholder 2026-02-18 21:44:39 +03:30
masoodafar-web 62a247f097 merge: kub-stage → production (inventory auto-init + initializer worker)
Build and Deploy to Production / build-and-deploy (push) Successful in 9m2s
2026-02-18 01:01:15 +03:30
masoodafar-web bc710fdb7b feat: auto-create inventory records for new products + migration worker
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m52s
- CreateNewProductsCommandHandler: inject IInventoryService, auto-init
  inventory record with qty=0 when a new regular product is created
  (DiscountProduct handler already had this)
- InventoryInitializerService: one-time BackgroundService that runs on
  startup, finds existing products without InventoryItem records, and
  creates them (migration for legacy products)
- Register InventoryInitializerService in DI
2026-02-18 00:42:41 +03:30
masoodafar-web fd24dcebcd feat: Add SitePageSettings - simplified page management system
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m2s
- New entities: SitePageSettings + SitePageImage (4 fixed pages)
- EF Migration: AddSitePageSettings (SitePageSettings + SitePageImages tables)
- Proto: sitepagesettings.proto with 5 RPCs
- CQRS: GetPageSettings, GetAllPageSettings, SavePageSettings, SavePageImage, DeletePageImage
- gRPC Service: SitePageSettingsService (auto-registered)
- Proto NuGet bumped to 0.0.180
2026-02-17 22:34:29 +03:30
masoodafar-web 89e146bf32 fix: set Kestrel protocol to Http1AndHttp2 in appsettings — prevents 502
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m38s
2026-02-17 02:55:50 +03:30
masoodafar-web af12f996f1 merge: kub-stage into production — fix prod workflow + add CmsBaseUrl/FrontOfficeBaseUrl
Build and Deploy to Production / build-and-deploy (push) Successful in 8m9s
2026-02-17 01:59:28 +03:30
masoodafar-web 27d995faf4 fix: production deployment — appsettings.Production.json + fix K8S_SERVER + set image
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m48s
- appsettings.Production.json: CmsBaseUrl=cms.kbs1.ir, FrontOfficeBaseUrl=kbs1.ir, DB=KBS
- prod-deploy.yml: K8S_SERVER 194.5.195.53 → 45.149.79.127
- prod-deploy.yml: kubectl set image instead of rollout restart
2026-02-17 01:58:07 +03:30
masoodafar-web 3b0d9eadd3 Fix production workflow: use SERVER_PASSWORD, add docker login, use set image for deploy
Build and Deploy to Production / build-and-deploy (push) Successful in 8m17s
2026-02-17 01:23:53 +03:30
masoodafar-web db07838ecb Remove staging workflow files from production branch to prevent cross-deployment 2026-02-17 01:15:50 +03:30
masoodafar-web 167991890c Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 2m43s
Features merged:
- ZarinPal payment gateway (sandbox mode)
- Discount store improvements (100% discount auto-apply)
- VAT breakdown on checkout
- PaymentStatus in order responses (proto v0.0.179)
- ExpirePendingOrdersService (background job for stale orders)
- DeliveryStatus proper mapping + cancel on failed payment
- Inventory management system
- Various bug fixes

Production config preserved:
- DB: 45.149.79.127 / KBS
- CmsBaseUrl: https://cms.kbs1.ir
- FrontOfficeBaseUrl: https://foursat.kbs1.ir
- Payment gateway: sandbox (will show 'درگاه فعال نمیباشد')
- Production workflow unchanged
2026-02-17 00:53:28 +03:30
masoodafar-web ef1716e243 fix: proper DeliveryStatus mapping + cancel delivery on failed payment
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m22s
- Added MapDeliveryStatus() to correctly map Domain→Proto enum values
- Domain Pending(1) was incorrectly cast to Proto PROCESSING(1) instead of PROCESSING
- Set DeliveryStatus=Cancelled when payment fails (CompleteOrderPaymentCommandHandler)
- Set DeliveryStatus=Cancelled when order expires (ExpirePendingOrdersService)
2026-02-17 00:41:48 +03:30
masoodafar-web c2ccd32f39 fix: use DateTime.Now instead of UtcNow in ExpirePendingOrdersService
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m33s
Database stores Created timestamps using DateTime.Now (local time).
Background service was comparing with DateTime.UtcNow causing 3.5 hour offset (Iran timezone).
Orders would only expire after ~4 hours instead of 30 minutes.
2026-02-16 22:52:33 +03:30
masoodafar-web c435319025 feat: add PaymentStatus to discount order proto + expire pending orders background service
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m53s
- Added payment_status field to GetOrderByIdResponse and OrderSummaryDto in proto
- Proto version bumped to 0.0.179
- Added PaymentStatus mapping in DiscountOrderService gRPC responses
- Created ExpirePendingOrdersService: expires pending orders after 30 min, releases inventory
- Registered background service in ConfigureServices
2026-02-16 22:37:58 +03:30
masoodafar-web 18a65de8c7 fix: force 100% discount in PlaceOrder — ignore client DiscountBalanceToUse, always use max
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m51s
2026-02-16 21:52:02 +03:30
masoodafar-web e2e09ac4e8 fix: add CmsBaseUrl/FrontOfficeBaseUrl to appsettings.json for staging callback URLs
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m43s
- Added CmsBaseUrl=https://cms.se.kbs1.ir to appsettings.json
- Added FrontOfficeBaseUrl=https://foursat.se.kbs1.ir to appsettings.json
- Fixed PurchasePackageCommandHandler hardcoded yourdomain.com
- Development keeps localhost values via appsettings.Development.json
2026-02-16 02:31:27 +03:30
masoodafar-web 61a0d68b7c feat: add staging configuration file for environment-specific settings
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-02-16 02:24:22 +03:30
masoodafar-web 1c4beb5f05 chore: bump Protobuf NuGet package version to 0.0.178
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m45s
2026-02-16 01:39:49 +03:30
masoodafar-web 163a0a2f1a fix: discount store DeliveryStatus stays Pending after payment (matches regular store)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m34s
- CompleteOrderPaymentCommandHandler: DeliveryStatus.InTransit → DeliveryStatus.Pending
- PlaceOrderCommandHandler (full discount-balance path): same fix
- Now both stores behave the same: admin must manually update delivery status
- Consistent with regular store flow where order stays Pending after payment
2026-02-16 00:45:55 +03:30
masoodafar-web e77611012b fix: PaymentStatus→PaymentCompleted mapping in DiscountOrderService
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m25s
- GetOrderById and GetUserOrders were using Mapster auto-mapping which
  could not map 'PaymentStatus' (enum: Success=0) to 'payment_completed' (bool)
- Replaced with manual mapping: PaymentStatus == Success → true
- Also maps DeliveryStatus and all other fields correctly
- Fixed FrontOfficeBaseUrl and CmsBaseUrl to use HTTP for local dev
2026-02-16 00:36:29 +03:30
masoodafar-web a39a36e66d feat: add PaymentTransaction table for gateway-level tracking
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m6s
- New PaymentTransaction entity (Domain/Entities/Payment/) with all gateway fields:
  GatewayProvider, MerchantId, Authority, CardPan, CardHash, RefId, VerificationStatusCode, etc.
- New PaymentTransactionConfiguration with indexes on Authority, GatewayProvider, UserId, TransactionId, RefId
- Added DbSet<PaymentTransaction> to IApplicationDbContext and ApplicationDbContext
- Extended PaymentVerificationResult DTO with CardPan, CardHash, VerificationCode
- Updated ZarinPalPaymentService.VerifyPayment to return CardPan/CardHash/VerificationCode
- Updated all 5 payment consumers to create/update PaymentTransaction:
  * PlaceOrderCommandHandler — creates PaymentTransaction after InitiatePayment
  * PaymentCallbackController — updates PaymentTransaction after VerifyPayment
  * ChargeDiscountWalletCommandHandler — creates PaymentTransaction + fixed callback URL
  * VerifyDiscountWalletChargeCommandHandler — updates PaymentTransaction after verify
  * TransactionsService.CustomerPaymentRequest/Verification — create/update PaymentTransaction
  * PackageService.CustomerPurchasePackage/Verify — create/update PaymentTransaction
- Transaction table untouched — PaymentTransaction is a separate table
- Pattern inspired by PYMS: create row before gateway → update after verify
- EF migration: AddPaymentTransactionTable
2026-02-15 23:53:28 +03:30
masoodafar-web 207f53ef80 refactor: remove PYMS microservice, use ZarinPal directly in CMS
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m26s
- Remove PYMSPaymentService.cs and PYMS proto files
- Remove 'pyms' case from DI ConfigureServices
- Remove PYMS config from appsettings
- Switch PaymentProvider to 'zarinpal' (direct integration)
- ZarinPalPaymentService handles sandbox/production, verify, errors
- PYMS deployment/service/ingress removed from K8s
2026-02-15 23:25:20 +03:30
masoodafar-web 2502cbbda2 feat: integrate PYMS payment gateway, add blog/sitepage/image services, local file manager
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 8m44s
Payment Gateway:
- Add PYMSPaymentService: IPaymentGatewayService via gRPC to PYMS microservice
- Add ZarinPalPaymentService: direct ZarinPal integration (backup)
- Register 'pyms' payment provider in DI ConfigureServices
- Add PYMS proto files (pyms_transaction.proto, pyms_public_messages.proto)
- Fix VerifyDiscountWalletCharge: pass 'OK' as status instead of Authority
- Update appsettings: PaymentProvider=pyms, sandbox mode, merchant ID

Blog System:
- Add BlogCategory, BlogPost, BlogPostImage entities and CQRS
- Add proto files and gRPC services for blog management
- Add Mapster profiles for blog responses

Content Management:
- Add SitePage entity and CQRS for static pages
- Add proto and gRPC service for site pages

Image/File Management:
- Add LocalFileManager with disk storage + base64 serving + FMS fallback
- Add ImagePathResolverInterceptor for gRPC responses
- Add ImageResolverService for explicit image resolution
- Add UploadsController for public file serving with FMS fallback
- Add PaymentCallbackController for discount order payment callbacks

Database:
- Add blog and content entity migrations
- Remove ImagePath MaxLength constraints
- Remove old FileManagementService (replaced by LocalFileManager)
2026-02-15 23:01:16 +03:30
masoodafar-web 5a4e4a960d fix: Update production deployment workflow for improved Docker handling and Kubernetes integration
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 7m19s
2026-02-11 00:40:29 +03:30
masoodafar-web dc1e00f514 fix: Disable BuildKit for Docker image build in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 9m15s
2026-02-11 00:19:27 +03:30
masoodafar-web 9d929dc7fb fix: Add network option to Docker run and build commands in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 3m23s
2026-02-11 00:08:02 +03:30
masoodafar-web 9b7d61593b fix: Remove unnecessary security options from Docker container in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 23s
2026-02-10 23:41:56 +03:30
masoodafar-web e3e3e8cec4 fix: Enhance Docker container security options in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 13s
2026-02-10 23:13:07 +03:30
masoodafar-web 2885ff20c0 fix: Streamline Docker registry login process in CI workflow
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 15s
2026-02-10 23:08:51 +03:30
masoodafar-web f2a0b4d211 fix: Update dotnet restore command to use custom NuGet configuration
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 5s
2026-02-10 23:05:45 +03:30
masoodafar-web 6c9f3dd671 fix: Add storage driver option to Docker daemon startup in Kubernetes deployment
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 5s
2026-02-10 23:03:03 +03:30
masoodafar-web d1ca72300d refactor: Remove ICurrentUserService dependency from query handlers and update user ID handling logic
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 8s
2026-02-10 23:01:49 +03:30
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
masoodafar-web 794dd01ac0 feat: update Protobuf definitions and add customer-facing APIs for various services 2026-02-01 22:16:36 +03:30
masoodafar-web 658d076bdf Complete FrontOffice BFF to CMS Migration
- Migrated all 9 services from FrontOffice.BFF to CMS architecture
- Enhanced user.proto with 7 additional Customer API endpoints:
  * UpdateCustomerProfile, GetCustomerProfile
  * ChangeCustomerPassword with validation
  * GetCustomerReferrals with commission stats
  * UploadCustomerAvatar with file validation
  * GetCustomerSettings, UpdateCustomerSettings
- All services now support Customer endpoints with /Customer/ prefix
- Mock implementations with realistic Persian data
- Fixed namespace conflicts and compilation issues
- Comprehensive testing completed for all endpoints
- Services migrated: Categories, City, UserCarts, Products, UserWallet,
  Transaction, UserOrder, Package, User (enhanced)
2026-01-30 08:53:09 +03:30
masoodafar-web 1a425f0d93 chore: Update production workflow to use Nexus registry (no proxy needed)
Build and Deploy to Production / build-and-deploy (push) Failing after 0s
- Changed Dockerfile base images to use 194.5.195.53:32082 (Nexus)
- Updated workflow to use docker-sshpass image from Nexus
- Removed HTTP_PROXY/HTTPS_PROXY dependencies
- Changed deploy method to SSH instead of kubeconfig
- Registry: 194.5.195.53:30080 (Gitea internal)
- K8S Server: 45.149.79.127 (Production)
2026-01-29 22:04:31 +03:30
masoodafar-web 96daf899c7 fix: increase Docker daemon startup timeout to 3 minutes
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 3m12s
2026-01-29 17:13:41 +03:30
masoodafar-web eddc82dfce refactor: use docker-sshpass image (fully offline)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 4m23s
2026-01-29 06:49:26 +03:30
masoodafar-web 0c95b03f0b fix: ensure sshpass is installed only if not present before deployment
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-29 06:05:46 +03:30
masoodafar-web 45c01fc157 refactor: merge two jobs into one pipeline
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-29 06:00:45 +03:30
masoodafar-web 55a775f51c perf: remove unnecessary apt-get install git
Build and Deploy to Kubernetes / publish-packages (push) Successful in 1m1s
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-29 05:57:07 +03:30
masoodafar-web 5b0558ee24 fix: streamline Kubernetes deployment process by removing SSH and adding kubectl installation
Build and Deploy to Kubernetes / publish-packages (push) Successful in 1m13s
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-29 05:54:44 +03:30
masoodafar-web cabf3886de fix: use rollout restart for simpler deployment
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
Build and Deploy to Kubernetes / publish-packages (push) Has been cancelled
2026-01-29 05:53:08 +03:30
masoodafar-web 0baed05fd4 fix: use cached docker:dind from Nexus
Build and Deploy to Kubernetes / publish-packages (push) Successful in 49s
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-29 05:41:09 +03:30
masoodafar-web 7c4c978d3f trigger: re-run pipeline with deploy step
Build and Deploy to Kubernetes / publish-packages (push) Successful in 1m39s
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 10s
2026-01-29 05:20:24 +03:30
masoodafar-web e327eb23ba feat: add kubernetes deployment step via SSH
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
Build and Deploy to Kubernetes / publish-packages (push) Has been cancelled
2026-01-29 05:18:47 +03:30
masoodafar-web 20280cf07f fix: proper restore and disable auto-push in CI
Build and Deploy to Kubernetes / publish-packages (push) Successful in 1m33s
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 1m7s
- Add restore step before build
- Add CI=true env to disable PushToFoursatNuget target
- Add --allow-insecure-connections to csproj push command
- Add Condition to skip push target in CI
2026-01-29 04:59:48 +03:30
masoodafar-web c67caca0ae fix: add --allow-insecure-connections to nuget push
Build and Deploy to Kubernetes / publish-packages (push) Failing after 1m6s
Build and Deploy to Kubernetes / build-and-deploy (push) Has been skipped
2026-01-29 04:56:40 +03:30
masoodafar-web e14a653fa8 feat: add publish-packages job to CI/CD workflow
Build and Deploy to Kubernetes / publish-packages (push) Failing after 1m6s
Build and Deploy to Kubernetes / build-and-deploy (push) Has been skipped
- Auto-detect and pack *Protobuf*.csproj files
- Push to Nexus with --skip-duplicate
- Build job now depends on publish-packages
2026-01-29 04:44:39 +03:30
masoodafar-web 4968878773 Revert: use only Nexus (no fallback)
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 3m29s
2026-01-29 03:44:38 +03:30
masoodafar-web 8ffb53996b Add nuget.org as fallback source
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-29 03:41:15 +03:30
masoodafar-web 1a01fd9057 Remove afrino NuGet sources - use only Nexus
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 4m24s
2026-01-29 03:14:38 +03:30
masoodafar-web 52af1bfaad chore: تنظیم Nexus برای NuGet و Docker offline
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 11m13s
- Dockerfile: استفاده از Nexus Docker (194.5.195.53:32082)
- NuGet.config: استفاده از Nexus NuGet با HTTP و allowInsecureConnections
- workflow: حذف kubectl dependency، اضافه کردن 32082 به insecure-registries
- csproj: تغییر push آدرس به Nexus foursat-nuget-hosted
2026-01-29 02:56:14 +03:30
masoodafar-web 2fd5300c1e fix: Add allowInsecureConnections attribute to Nexus package source in NuGet.config
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-29 02:48:03 +03:30
masoodafar-web c76af47a4c fix: Update Nexus package source URL in NuGet.config
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 45s
2026-01-29 02:46:43 +03:30
masoodafar-web 77be841221 fix: Add NuGet.config for package source configuration and update restore command in Dockerfile
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 1m5s
2026-01-29 02:44:55 +03:30
masoodafar-web 4743b52cae fix: Remove dependency installation step for offline builds in kub-deploy.yml
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 1m4s
2026-01-29 02:41:22 +03:30
masoodafar-web 0b0fa3aa61 fix: Simplify kubectl installation and update deployment messages in kub-deploy.yml
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-29 02:36:21 +03:30
masoodafar-web 839250e132 fix: Update Dockerfile to use internal registry for .NET SDK and ASP.NET images
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 10s
2026-01-29 02:25:38 +03:30
masoodafar-web 8894e72a8e fix: Update kubectl installation to use a fixed version instead of fetching stable version
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 1m9s
2026-01-29 02:20:40 +03:30
masoodafar-web 1c130b14e1 fix: Update Dockerfile to use .NET 9.0 images from internal registry
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 11s
2026-01-29 02:15:45 +03:30
masoodafar-web 793d81f1dd fix: Remove NotEmpty validation for ShortInfomation and FullInformation in discount product validators
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m48s
2026-01-05 01:43:23 +03:30
masoodafar-web f6704eaa99 fix: Implement product lookup in RecordLoss method to accurately reduce inventory on loss
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m50s
2026-01-05 00:58:52 +03:30
masoodafar-web d03fbe0a98 fix: Remove RemainingCount property from CreateDiscountProduct and related commands, initializing inventory with zero
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m56s
2026-01-04 23:51:35 +03:30
masoodafar-web f9c90bb871 fix: Synchronize RemainingCount for Regular and Discount products in inventory commands
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m40s
2026-01-04 23:29:02 +03:30
masoodafar-web 70c4b15a23 fix: Refactor AdjustStock method to streamline inventory updates and improve response structure
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 2m18s
2026-01-04 22:58:25 +03:30
masoodafar-web 5e662b5984 fix: Implement product lookup for AddStock and AdjustStock methods in InventoryService
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-04 22:38:46 +03:30
masoodafar-web 16ba2fa6fb fix: Update sorting and calculation of available quantity in GetLowStockItems query
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m46s
2026-01-04 22:22:42 +03:30
masoodafar-web 389568af2b fix: Reset wallet balance and discount balance to zero in DayaLoan processing
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 2m7s
2026-01-04 21:46:37 +03:30
Admin 98f3036bd0 fix: Remove domain from insecure-registries, use IP only
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 2m8s
2026-01-03 15:15:24 +00:00
masoodafar-web 631646776e u
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
2026-01-03 18:41:39 +03:30
masoodafar-web d8031a0d17 fix: update registry URL in deployment workflows to the correct address
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 5m58s
2026-01-03 17:28:10 +03:30
masoodafar-web ca9b02a902 chore: update Protobuf project version to 0.0.169
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 2m4s
2026-01-03 15:38:33 +03:30
masoodafar-web dde4c68b2f feat: Implement inventory and warehouse management features
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 2m33s
- Add GetLowStockItemsResponseDto and LowStockItemDto for low stock item queries.
- Create CreateStockMovementCommand and its handler for managing stock movements.
- Implement CreateStockMovementCommandValidator for validating stock movement commands.
- Add GetStockMovementsQuery and its handler to retrieve stock movement records.
- Create GetStockMovementsResponseDto and StockMovementListDto for stock movement responses.
- Implement GetStockMovementsByInventoryItemQuery and its handler for fetching movements by inventory item.
- Add CreateWarehouseCommand and its handler for creating new warehouses.
- Implement CreateWarehouseCommandValidator for warehouse creation validation.
- Add DeleteWarehouseCommand and its handler for removing warehouses.
- Implement SetDefaultWarehouseCommand and its handler for setting a default warehouse.
- Create UpdateWarehouseCommand and its handler for updating warehouse details.
- Implement GetAllWarehousesQuery and its handler to retrieve all warehouses.
- Add GetWarehouseQuery and its handler for fetching a specific warehouse by ID.
- Implement SearchWarehousesQuery and its handler for searching warehouses based on criteria.
2026-01-03 11:59:08 +03:30
masoodafar-web 8c3d710253 feat(mappings): expand InventoryProfile with comprehensive CQRS mappings for warehouses and inventory items
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 1m37s
2026-01-03 10:05:47 +03:30
masoodafar-web a81fb39a32 feat(mappings): add InventoryProfile for mapping Inventory entities to Protobuf DTOs
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m41s
2026-01-03 09:02:09 +03:30
masoodafar-web f8731bc7fc feat: register inventory-related repositories and services in ConfigureServices
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m39s
2026-01-03 08:43:22 +03:30
masoodafar-web d3d021c007 feat(migrations): add ImageDocumentId column to ManualPayments table
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m36s
feat(mappings): implement DiscountCategoryProfile for mapping between application DTOs and protobuf responses
2026-01-03 07:37:45 +03:30
masoodafar-web bea43a0569 Add ImagePath column to ManualPayments table in CMS schema
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m52s
2026-01-02 02:13:57 +03:30
masoodafar-web 1cf501711f Implement Inventory Management Service with CRUD operations for warehouses and inventory items, stock operations, and bulk processing capabilities.
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m48s
2026-01-02 00:45:37 +03:30
masoodafar-web f0117eb1d5 Add migration for DiscountProductImages table
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m53s
- Created a new table `DiscountProductImages` in the CMS schema.
- Added columns for image details including `Title`, `AltText`, `ImagePath`, `ThumbnailPath`, `SortOrder`, `IsActive`, `Created`, `CreatedBy`, `LastModified`, `LastModifiedBy`, and `IsDeleted`.
- Established a foreign key relationship with the `DiscountProducts` table.
- Created indexes on `DiscountProductId` and a composite index on `DiscountProductId` and `SortOrder`.
2026-01-01 02:26:33 +03:30
masoodafar-web 6f8aefc2ce Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 1m40s
2025-12-29 00:36:51 +03:30
masoodafar-web 500e169141 feat: add Id property to WeekDefinitionItemDto and map it in CommissionProfile - Enhanced week definition handling by including the Id in the DTO and mapping configuration
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m51s
2025-12-28 22:21:43 +03:30
masoodafar-web ed45a1759b feat: update user weekly balances model and mappings - Enhanced UserWeeklyBalanceModel with new properties and updated mappings in response DTO and profile
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m34s
2025-12-27 21:52:42 +03:30
masoodafar-web 2bd5c7db78 Merge branch 'kub-stage' into production
Build and Deploy to Production / build-and-deploy (push) Successful in 1m50s
2025-12-27 07:37:30 +03:30
masoodafar-web 7087df23ef feat: remove CheckDayaLoanStatusCommandHandler and ProcessDayaLoanApprovalCommandHandler - Deleted unused command handlers to streamline codebase
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m48s
2025-12-27 06:40:30 +03:30
masoodafar-web 6374d5c343 feat: implement CheckDayaLoanStatusCommandHandler - Added handler for checking Daya loan status and updating contracts, including error handling and logging
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 1m10s
2025-12-27 06:21:52 +03:30
masoodafar-web 1dbb3ee502 feat: implement unified command for Daya loan status check and processing - Refactored DayaLoanCheckWorker to use CheckAndProcessDayaLoansCommand, enhancing functionality and logging
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m50s
2025-12-27 02:30:40 +03:30
masoodafar-web 0728ec2b76 feat: add background job configuration for weekly commission calculation
Build and Deploy to Production / build-and-deploy (push) Successful in 3m18s
2025-12-27 01:51:32 +03:30
masoodafar-web 1425fb187b Merge branch 'kub-stage' into production
# Conflicts:
#	src/CMSMicroservice.WebApi/Program.cs
2025-12-27 01:49:11 +03:30
masoodafar-web cd2549775a feat: add background job configuration for weekly commission calculation - Updated appsettings and Program.cs to enable configurable scheduling for weekly commission jobs
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 2m9s
2025-12-27 01:37:43 +03:30
masoodafar-web 81d2b39ee1 fix: update Seq ServerUrl and change Hangfire job timezone to local - Adjusted Seq server URL for production and modified recurring job options to use local timezone 2025-12-27 01:14:31 +03:30
masoodafar-web fce194a195 feat: update connection strings and add production configuration - Modified database connection details and created appsettings.Production.json for production environment
Build and Deploy to Production / build-and-deploy (push) Successful in 4m2s
2025-12-27 00:16:36 +03:30
masoodafar-web 322242fbab feat: add mapping profile for AppVersion - Implemented mappings for AppVersionItemDto to proto messages and response creation
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 3m40s
2025-12-26 09:36:21 +03:30
masoodafar-web 3d42c91d21 feat: add SMS notification for Daya loan approval - Implemented SMS sending functionality and created SmsTemplates for message formatting
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 4m11s
2025-12-26 09:20:15 +03:30
masoodafar-web 9448f3fff0 refactor: remove LockedWalletAmount from DayaLoan processing logic
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 3m56s
2025-12-26 09:07:28 +03:30
masoodafar-web 02e2f8111f feat: implement Kavenegar SMS service and refactor system configurations to use static constants
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 1m38s
2025-12-26 09:04:27 +03:30
masoodafar-web 9d2b5ad2d4 fix: update database connection and remove production config
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 5m4s
2025-12-26 06:31:19 +03:30
masoodafar-web 8940362575 fix: update MaxDepth validation range to allow values between 1 and 100 - Bump Protobuf version to 0.0.159
Build and Deploy to Production / build-and-deploy (push) Successful in 3m8s
2025-12-25 19:30:06 +03:30
masoodafar-web bca3b7fe62 feat: add ReferralCode to NetworkTree nodes - Added ReferralCode to SP_GetNetworkTree stored procedure - Added ReferralCode property to NetworkTreeDto and NetworkTreeNodeDto - Added referral_code field to networkmembership.proto - Updated Handler and Profile mappings
Build and Deploy to Production / build-and-deploy (push) Successful in 1m45s
2025-12-25 19:21:36 +03:30
masoodafar-web c03b3705c3 fix(NetworkTree): Use Convert.ToBoolean for IsClubActive and IsActivatedInTargetWeek
Build and Deploy to Production / build-and-deploy (push) Successful in 2m27s
SP returns BIT which maps to Boolean in C#, not Int32
2025-12-25 19:13:06 +03:30
masoodafar-web a9140bec04 chore: bump CMSMicroservice.Protobuf to 0.0.158
Build and Deploy to Production / build-and-deploy (push) Has been cancelled
2025-12-25 19:08:51 +03:30
masoodafar-web 17c2958b9c feat(AppVersion): Add version tracking system for frontend cache invalidation
Build and Deploy to Production / build-and-deploy (push) Successful in 1m37s
- Add AppVersion entity with CurrentVersion, MinRequiredVersion, RequiresFullCacheClear
- Add GetAppVersion query to check app version and compare with client version
- Add GetAllAppVersions query for admin panel
- Add UpdateAppVersion command to update/create app versions
- Add appversion.proto for gRPC communication
- Add AppVersionService for gRPC endpoints
- Add database migration for AppVersions table
2025-12-25 18:06:12 +03:30
masoodafar-web 2e54aa7aca feat: update boolean handling for database compatibility
Build and Deploy to Production / build-and-deploy (push) Successful in 1m45s
2025-12-25 02:34:06 +03:30
masoodafar-web 7b26073c63 update
Build and Deploy to Production / build-and-deploy (push) Successful in 1m40s
2025-12-25 01:24:58 +03:30
masoodafar-web 28e94d6137 feat: update appsettings for production environment and clear default connection string 2025-12-25 01:24:58 +03:30
masoodafar-web c6ee356cbd update 2025-12-25 01:24:58 +03:30
masoodafar-web 2d09a69be9 feat: add DatabaseFacade property to IApplicationDbContext for raw SQL access 2025-12-25 01:24:58 +03:30
masoud 7cebb27171 Update src/CMSMicroservice.Infrastructure/BackgroundJobs/ChatikaAccountActivationJob.cs 2025-12-25 01:24:58 +03:30
masoodafar-web 68489a8374 feat: update database connection string in appsettings.json 2025-12-25 01:24:58 +03:30
masoodafar-web 330f0cae5a feat: enable Chatika integration in appsettings.json 2025-12-25 01:24:58 +03:30
masoodafar-web b16f01b6e4 chore: fix trailing whitespace in appsettings.json 2025-12-25 01:24:58 +03:30
masoodafar-web 13f24d523b feat: refine user filtering logic in Chatika account activation and Daya loan check jobs 2025-12-25 01:24:58 +03:30
admin 41308e189a Add production deployment workflow
Build and Deploy to Production / build-and-deploy (push) Successful in 1m46s
2025-12-23 20:16:13 +00:00
masoodafar-web 8953d86755 chore: fix trailing whitespace in appsettings.json 2025-12-23 23:31:47 +03:30
masoodafar-web ef8d5d4d97 feat: add configuration option to enable/disable Chatika integration 2025-12-23 23:09:18 +03:30
masoodafar-web 288b85a59b feat: implement Chatika account activation job for new club members 2025-12-23 22:52:49 +03:30
masoodafar-web 30144a07c8 feat: enhance club membership activation with pool and features 2025-12-23 00:02:14 +03:30
masoodafar-web 5bcf6c9840 feat: add network leg position assignment for new users 2025-12-22 22:39:15 +03:30
masoodafar-web 9d51e70a7f chore: fix trailing whitespace in appsettings.json 2025-12-20 06:29:47 +03:30
masoodafar-web a31c88219f chore: remove appsettings.Production.json file 2025-12-20 06:18:03 +03:30
masoodafar-web ceeb29d843 chore: add Seq API key in appsettings.json 2025-12-20 06:07:13 +03:30
masoodafar-web 0ba6af9049 chore: update Seq server URL in appsettings.json 2025-12-20 05:22:47 +03:30
masoodafar-web 5ad69cb3fa update 2025-12-20 04:54:59 +03:30
920 changed files with 113284 additions and 9674 deletions
+2
View File
@@ -0,0 +1,2 @@
# Keep production config from current branch during merges — never overwrite
src/CMSMicroservice.WebApi/appsettings.Production.json merge=ours
-46
View File
@@ -1,46 +0,0 @@
name: Push nuget and docker image Actions Workflow
on:
push:
branches:
- stage_new
jobs:
Deploy:
runs-on: windows
steps:
- name: Checkout
uses: https://git.afrino.co/actions/checkout@v3
- name: Setup dotnet
uses: https://git.afrino.co/actions/setup-dotnet@v3
with:
dotnet-version: 7.0.x
- name: Remove Package Source
run: dotnet nuget remove source FourSat
continue-on-error: true
- name: Add Package Source
run: dotnet nuget add source --name FourSat --username systemuser --password sZSA7PTiv3pUSQZ https://git.afrino.co/api/packages/FourSat/nuget/index.json --store-password-in-clear-text
- name: Install dependencies
run: dotnet restore ".\src\CMSMicroservice.WebApi\CMSMicroservice.WebApi.csproj"
- name: Build
run: dotnet build ".\src\CMSMicroservice.WebApi\CMSMicroservice.WebApi.csproj" --configuration Release --no-restore
- name: Test
run: dotnet test ".\src\CMSMicroservice.WebApi\CMSMicroservice.WebApi.csproj" --no-restore --verbosity normal
- name: Recycle Apppool
run: |
& "C:\Windows\System32\inetsrv\appcmd.exe" recycle apppool /apppool.name:cms.kbs1.ir
shell: powershell
- name: Stop Website
run: |
& "C:\Windows\System32\inetsrv\appcmd.exe" stop site /site.name:cms.kbs1.ir
shell: powershell
- name: Publish
run: dotnet publish ".\src\CMSMicroservice.WebApi\CMSMicroservice.WebApi.csproj" -c Release -o publish
- name: Copy Publish To IIS Directory
run: Get-ChildItem -Path "publish\*" | Copy-Item -Destination "E:\kbs1.ir\cms.kbs1.ir\" -Recurse -Force
- name: Start Website
run: |
& "C:\Windows\System32\inetsrv\appcmd.exe" start site /site.name:cms.kbs1.ir
shell: powershell
+67 -50
View File
@@ -6,81 +6,98 @@ on:
- kub-stage
env:
REGISTRY: git.foursat.afrino.co
REGISTRY: 194.5.195.53:30080
IMAGE_NAME: admin/cms
K8S_SERVER: 194.5.195.53
jobs:
build-and-deploy:
runs-on: ubuntu-latest
container:
image: docker:latest
image: 194.5.195.53:32082/docker-sshpass:latest
options: --privileged
env:
HTTP_PROXY: http://proxyuser:87zH26nbqT2@46.249.98.211:3128
HTTPS_PROXY: http://proxyuser:87zH26nbqT2@46.249.98.211:3128
NO_PROXY: localhost,127.0.0.1,gitea-svc,194.5.195.53,10.0.0.0/8
steps:
- name: Install dependencies
run: |
apk add --no-cache git curl
# Install kubectl
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl
mv kubectl /usr/local/bin/
- name: Start Docker daemon with insecure registry
- name: Start Docker daemon
run: |
mkdir -p /etc/docker
cat > /etc/docker/daemon.json << 'DAEMON'
{
"insecure-registries": ["git.foursat.afrino.co", "gitea-svc:3000"]
"insecure-registries": ["194.5.195.53:30080", "194.5.195.53:32500", "194.5.195.53:32082"]
}
DAEMON
mkdir -p ~/.docker
cat > ~/.docker/config.json << 'CONF'
{
"proxies": {
"default": {
"httpProxy": "http://proxyuser:87zH26nbqT2@46.249.98.211:3128",
"httpsProxy": "http://proxyuser:87zH26nbqT2@46.249.98.211:3128",
"noProxy": "localhost,127.0.0.1,gitea-svc,194.5.195.53,10.0.0.0/8"
}
}
}
CONF
dockerd &
for i in $(seq 1 30); do
docker info >/dev/null 2>&1 && break || sleep 2
echo "🚀 Starting Docker daemon..."
dockerd --iptables=false --ip6tables=false --bridge=none --storage-driver=vfs &
# Wait up to 3 minutes for Docker to be ready
for i in $(seq 1 90); do
if docker info >/dev/null 2>&1; then
echo "✅ Docker daemon is ready (attempt $i)"
docker version
break
else
echo "⏳ Waiting for Docker daemon... (attempt $i/90)"
sleep 2
fi
done
docker info
# Final check
if ! docker info >/dev/null 2>&1; then
echo "❌ Docker daemon failed to start after 3 minutes"
exit 1
fi
- name: Checkout code
run: |
git clone --depth 1 --branch kub-stage http://gitea-svc:3000/admin/CMS.git .
git log -1 --format="%H %s"
- name: Login to Docker registries
run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login 194.5.195.53:32082 -u admin --password-stdin
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ${{ env.REGISTRY }} -u admin --password-stdin
- name: Publish Protobuf packages
run: |
echo "📦 Publishing Protobuf packages..."
docker run --rm --network host -e CI=true -v $(pwd):/src -w /src \
194.5.195.53:32082/dotnet/sdk:9.0 sh -c '
for proj in $(find . -name "*Protobuf*.csproj" -type f); do
echo "📦 $proj"
dotnet restore "$proj" --configfile src/NuGet.config
dotnet build "$proj" -c Release --no-restore
dotnet pack "$proj" -c Release --no-build -o "$(dirname $proj)/nupkg"
for nupkg in $(dirname $proj)/nupkg/*.nupkg; do
[ -f "$nupkg" ] && dotnet nuget push "$nupkg" \
--source "foursat-hosted" \
--api-key "admin:87zH26nbqT" \
--skip-duplicate --configfile src/NuGet.config || true
done
done
'
echo "✅ Protobuf packages done!"
- name: Build Docker Image
run: |
docker build -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest \
--build-arg HTTP_PROXY=http://proxyuser:87zH26nbqT2@46.249.98.211:3128 \
--build-arg HTTPS_PROXY=http://proxyuser:87zH26nbqT2@46.249.98.211:3128 \
.
DOCKER_BUILDKIT=0 docker build --network host -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest .
- name: Push to Registry
run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ${{ env.REGISTRY }} -u admin --password-stdin
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
- name: Deploy to Kubernetes
run: |
# Setup kubeconfig
mkdir -p ~/.kube
echo "${{ secrets.KUBECONFIG }}" | base64 -d > ~/.kube/config
export SSHPASS="${{ secrets.SERVER_PASSWORD }}"
# Restart deployment to pull new image
kubectl rollout restart deployment/cms || echo "Deployment doesn't exist yet"
# Copy K8s manifests to server
sshpass -e scp -o StrictHostKeyChecking=no k8s/staging/cms-config.yaml root@${{ env.K8S_SERVER }}:/tmp/cms-config.yaml
sshpass -e scp -o StrictHostKeyChecking=no k8s/staging/cms-deployment.yaml root@${{ env.K8S_SERVER }}:/tmp/cms-deployment.yaml
# Wait for rollout to complete
kubectl rollout status deployment/cms --timeout=5m || echo "Deployment rollout pending"
# Apply config (Secret) first, then deployment
sshpass -e ssh -o StrictHostKeyChecking=no root@${{ env.K8S_SERVER }} "
kubectl apply -f /tmp/cms-config.yaml &&
kubectl apply -f /tmp/cms-deployment.yaml &&
crictl rmi ${REGISTRY}/${IMAGE_NAME}:latest 2>/dev/null || true &&
kubectl rollout restart deployment/cms &&
kubectl rollout status deployment/cms --timeout=180s &&
rm -f /tmp/cms-config.yaml /tmp/cms-deployment.yaml
"
echo "✅ Deployed!"
+104
View File
@@ -0,0 +1,104 @@
name: Build and Deploy to Production
on:
push:
branches:
- production
env:
REGISTRY: 194.5.195.53:30080
IMAGE_NAME: admin/cms
K8S_SERVER: 45.149.79.127
jobs:
build-and-deploy:
runs-on: ubuntu-latest
container:
image: 194.5.195.53:32082/docker-sshpass:latest
options: --privileged
steps:
- name: Start Docker daemon
run: |
mkdir -p /etc/docker
cat > /etc/docker/daemon.json << 'DAEMON'
{
"insecure-registries": ["194.5.195.53:30080", "194.5.195.53:32500", "194.5.195.53:32082"]
}
DAEMON
echo "🚀 Starting Docker daemon..."
dockerd --iptables=false --ip6tables=false --bridge=none --storage-driver=vfs &
for i in $(seq 1 90); do
if docker info >/dev/null 2>&1; then
echo "✅ Docker daemon is ready (attempt $i)"
docker version
break
else
echo "⏳ Waiting for Docker daemon... (attempt $i/90)"
sleep 2
fi
done
if ! docker info >/dev/null 2>&1; then
echo "❌ Docker daemon failed to start"
exit 1
fi
- name: Checkout code
run: |
git clone --depth 1 --branch production http://gitea-svc:3000/admin/CMS.git .
- name: Login to Docker registries
run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login 194.5.195.53:32082 -u admin --password-stdin
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login ${{ env.REGISTRY }} -u admin --password-stdin
- name: Publish Protobuf packages
run: |
echo "📦 Publishing Protobuf packages..."
docker run --rm --network host -v $(pwd):/src -w /src \
194.5.195.53:32082/dotnet/sdk:9.0 sh -c '
for proj in $(find . -name "*Protobuf*.csproj" -type f); do
echo "📦 $proj"
dotnet restore "$proj" --configfile src/NuGet.config
dotnet build "$proj" -c Release --no-restore
dotnet pack "$proj" -c Release --no-build -o "$(dirname $proj)/nupkg"
for nupkg in $(dirname $proj)/nupkg/*.nupkg; do
[ -f "$nupkg" ] && dotnet nuget push "$nupkg" \
--source "http://194.5.195.53:32081/repository/foursat-nuget-hosted/index.json" \
--api-key "admin:87zH26nbqT" \
--skip-duplicate --allow-insecure-connections || true
done
done
'
echo "✅ Protobuf packages done!"
- name: Build Docker Image
run: |
DOCKER_BUILDKIT=0 docker build --network host \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:prod \
.
- name: Push to Registry
run: |
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:prod
- name: Deploy to Production
run: |
export SSHPASS="${{ secrets.SERVER_PASSWORD }}"
# Copy K8s manifests to server
sshpass -e scp -o StrictHostKeyChecking=no k8s/production/cms-config.yaml root@${{ env.K8S_SERVER }}:/tmp/cms-config.yaml
sshpass -e scp -o StrictHostKeyChecking=no k8s/production/cms-deployment.yaml root@${{ env.K8S_SERVER }}:/tmp/cms-deployment.yaml
# Apply config (Secret) first, then deployment and update image
sshpass -e ssh -o StrictHostKeyChecking=no root@${{ env.K8S_SERVER }} "
kubectl apply -f /tmp/cms-config.yaml &&
kubectl apply -f /tmp/cms-deployment.yaml &&
kubectl set image deployment/cms cms=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} &&
kubectl rollout status deployment/cms --timeout=300s &&
rm -f /tmp/cms-config.yaml /tmp/cms-deployment.yaml
"
echo "✅ Deployed to Production!"
+5
View File
@@ -492,3 +492,8 @@ fabric.properties
.idea/caches/build_file_checksums.ser
/src/.idea
# Environment-specific configuration files with sensitive data
**/appsettings.Staging.json
**/appsettings.Production.json
**/appsettings.*.local.json
+7 -4
View File
@@ -1,14 +1,17 @@
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
FROM 194.5.195.53:32082/dotnet/sdk:9.0 AS build
WORKDIR /src
# Copy NuGet config first
COPY src/NuGet.config ./
# Copy solution and project files
COPY src/ ./
# Restore and publish
RUN dotnet restore "CMSMicroservice.WebApi/CMSMicroservice.WebApi.csproj"
# Restore with Nexus config and publish
RUN dotnet restore "CMSMicroservice.WebApi/CMSMicroservice.WebApi.csproj" --configfile NuGet.config
RUN dotnet publish "CMSMicroservice.WebApi/CMSMicroservice.WebApi.csproj" -c Release -o /app/publish --no-restore
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS runtime
FROM 194.5.195.53:32082/dotnet/aspnet:9.0 AS runtime
WORKDIR /app
COPY --from=build /app/publish .
ENV ASPNETCORE_URLS=http://+:8080
+3 -258
View File
@@ -1,259 +1,4 @@
# CMS Microservice - Network & Club Commission System
# CMS Microservice
[![Status](https://img.shields.io/badge/Status-Production%20Ready-success)]()
[![Progress](https://img.shields.io/badge/Progress-85%25-blue)]()
[![MVP](https://img.shields.io/badge/MVP-100%25%20Complete-brightgreen)]()
## 📊 Project Status (2025-12-01)
**Overall Progress**: 85% Complete (7/10 phases)
**Production Readiness**: 95%
**MVP Status**: ✅ 100% Complete
### ✅ Completed Phases (7)
1. ✅ Domain Layer (Entities, Enums, Value Objects)
2. ✅ Club Membership System
3. ✅ Binary Network Tree
4.**Commission Calculation & Background Worker** (MVP)
5. ✅ Protobuf gRPC Services
6. ✅ History & Configuration Management
7. ✅ Database Migration & Seed Data
### 🟡 Partially Complete (1)
- Phase 10: Withdrawal & Settlement (40%)
- ✅ Commands & Database
- ❌ Payment Gateway Integration
### ❌ Not Started (1)
- Phase 9: Club Shop & Product Integration (0%)
### ⏸️ Postponed (1)
- Phase 7: Testing (Unit, Integration, Load tests)
---
## 🚀 Recent Updates (2025-12-01)
### Email & SMS Notifications - COMPLETED ✅
-**MailKit 4.14.1** for Email (SMTP with HTML templates)
-**Kavenegar 1.2.5** for SMS (Iranian SMS gateway)
- ✅ User.Email field added with migration
- ✅ 3 notification types: Commission, Club activation, Errors
- ✅ Persian RTL templates with rich formatting
- ✅ Production configuration guide created
### Hangfire Job Scheduling - COMPLETED ✅
- ✅ Dashboard UI at `/hangfire`
- ✅ Cron schedule: Sunday 00:05 UTC
- ✅ SQL Server persistence
- ✅ Manual trigger API endpoints
- ✅ Distributed execution support
### Infrastructure Enhancements - COMPLETED ✅
- ✅ Health Check endpoints (`/health`, `/health/ready`, `/health/live`)
- ✅ AlertService (structured logging for Sentry/Slack)
- ✅ Retry logic (Polly 8.5.0 with exponential backoff)
- ✅ WorkerExecutionLog (database audit trail)
- ✅ CurrentUserService (JWT authentication context)
---
## 🏗️ Architecture
**Clean Architecture** with 4 layers:
```
CMSMicroservice.Domain/ # Entities, Enums, Interfaces
CMSMicroservice.Application/ # CQRS (Commands, Queries, MediatR)
CMSMicroservice.Infrastructure/ # DbContext, Services, Background Jobs
CMSMicroservice.WebApi/ # gRPC Services, Controllers
CMSMicroservice.Protobuf/ # Protocol Buffers definitions
```
**Technology Stack**:
- .NET 9.0
- Entity Framework Core 9.0.11
- gRPC + JSON Transcoding
- Hangfire 1.8.22 (Job Scheduling)
- MediatR 13.0.0 (CQRS)
- Polly 8.5.0 (Resilience)
- MailKit 4.14.1 (Email)
- Kavenegar 1.2.5 (SMS)
- SQL Server
---
## 📖 Documentation
- **[Implementation Progress](docs/implementation-progress.md)** - Detailed phase-by-phase progress
- **[Email/SMS Configuration Guide](docs/email-sms-configuration-guide.md)** - Production setup instructions
- **[Balance Calculation Logic](docs/balance-calculation-carryover-logic.md)** - Commission algorithm details
- **[Binary Tree Registration](docs/binary-tree-registration-guide.md)** - Network tree guide
- **[Network Club Commission System](docs/network-club-commission-system-v1.1.md)** - Full system specification
---
## 🚀 Quick Start
### Prerequisites
- .NET 9.0 SDK
- SQL Server (local or remote)
- (Optional) Gmail account for Email
- (Optional) Kavenegar account for SMS
### 1. Clone & Build
```bash
cd /home/masoud/Apps/project/FourSat/CMS/src
dotnet build
```
### 2. Configure Database
Update `appsettings.json` with your SQL Server connection:
```json
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=Foursat_CMS;..."
}
```
### 3. Apply Migrations
```bash
cd CMSMicroservice.WebApi
dotnet ef database update
```
### 4. Configure Notifications (Optional)
See [Email/SMS Configuration Guide](docs/email-sms-configuration-guide.md)
### 5. Run
```bash
dotnet run --urls="http://localhost:5133"
```
### 6. Access Endpoints
- **Health**: http://localhost:5133/health
- **Hangfire Dashboard**: http://localhost:5133/hangfire
- **gRPC**: localhost:5133 (HTTP/2)
---
## 🔧 Configuration
### Email (SMTP)
```json
"Email": {
"Enabled": true,
"SmtpHost": "smtp.gmail.com",
"SmtpPort": 587,
"SmtpUsername": "your-email@gmail.com",
"SmtpPassword": "your-gmail-app-password",
"FromEmail": "noreply@foursat.com",
"FromName": "FourSat CMS",
"EnableSsl": true
}
```
### SMS (Kavenegar)
```json
"Sms": {
"Enabled": true,
"Provider": "Kavenegar",
"KavenegarApiKey": "YOUR_API_KEY",
"Sender": "10008663"
}
```
### Background Worker
```csharp
// Cron: "5 0 * * 0" = Every Sunday at 00:05 UTC
RecurringJob.AddOrUpdate<WeeklyCommissionJob>(
"weekly-commission-calculation",
job => job.ExecuteAsync(CancellationToken.None),
"5 0 * * 0");
```
---
## 🧪 Testing
### Manual Trigger (via API)
```bash
# Trigger weekly calculation immediately
curl -X POST http://localhost:5133/api/admin/trigger-weekly-calculation
# Trigger recurring job now
curl -X POST http://localhost:5133/api/admin/trigger-recurring-job-now
# Get recurring jobs status
curl http://localhost:5133/api/admin/recurring-jobs-status
```
### Health Checks
```bash
curl http://localhost:5133/health # Overall health
curl http://localhost:5133/health/ready # Readiness probe (K8s)
curl http://localhost:5133/health/live # Liveness probe (K8s)
```
---
## 📊 What's Remaining?
### High Priority
1. **Payment Gateway Integration** (Phase 10 - 1 week)
- Daya or Bank Mellat API integration
- IBAN transfer automation
- Admin approval UI in BackOffice
2. **Production Configuration** (30 minutes)
- Gmail App Password setup
- Kavenegar API key registration
- Update `appsettings.Production.json`
### Medium Priority
3. **Club Shop Integration** (Phase 9 - 2 weeks)
- Product catalog for club memberships
- Shopping cart integration
- Auto-activation on purchase
### Low Priority
4. **Testing** (Phase 7 - Postponed)
- Unit tests for business logic
- Integration tests for API
- Load testing for background worker
### Optional Enhancements
- Redis distributed locks (multi-server deployment)
- Sentry error tracking (API key needed)
- Slack notifications (webhook needed)
- FCM push notifications
---
## 🎯 MVP Features (100% Complete)
✅ Binary network tree with automatic placement
✅ Club membership (Member/Trial) with different commission rates
✅ Weekly commission calculation (Lesser Leg algorithm)
✅ Background worker with Hangfire (cron scheduling)
✅ Balance carryover logic (rollover unused volumes)
✅ MaxWeeklyBalances cap enforcement
✅ Health check endpoints (Kubernetes-ready)
✅ Manual trigger API (admin control)
✅ Email + SMS notifications (MailKit + Kavenegar)
✅ Retry logic with exponential backoff (Polly)
✅ Audit trail (WorkerExecutionLog, History tables)
✅ Structured logging (AlertService for Sentry/Slack)
✅ JWT authentication context (CurrentUserService)
---
## 👥 Team
**Development**: FourSat Team
**Last Updated**: 2025-12-01
---
## 📝 License
Proprietary - FourSat Company
# Multi-remote push enabled
Documentation moved to [totalDoc/INDEX.md](../totalDoc/INDEX.md).
+1
View File
@@ -0,0 +1 @@
Docs moved to /totalDoc — see totalDoc/INDEX.md
File diff suppressed because it is too large Load Diff
+421
View File
@@ -0,0 +1,421 @@
{
"info": {
"_postman_id": "a5404a90-7d5a-4e9f-a26b-bb2bc93f19a2",
"name": "hushyar",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "12336342",
"_collection_link": "https://abbas-rahimzadeh-postman.postman.co/workspace/public-workspace~57c702f9-fed1-4b27-b507-0b0252812bf7/collection/12336342-a5404a90-7d5a-4e9f-a26b-bb2bc93f19a2?action=share&source=collection_link&creator=12336342"
},
"item": [
{
"name": "v1",
"item": [
{
"name": "organization",
"item": [
{
"name": "register-user",
"request": {
"method": "POST",
"header": [
{
"key": "X-API-Key",
"value": "{{organizationApiKey}}",
"description": "Organization API Key",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"mobile_number\": \"09123456789\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{baseURL}}/api/v1/organizations/register-user",
"host": [
"{{baseURL}}"
],
"path": [
"api",
"v1",
"organizations",
"register-user"
]
},
"description": "Register a new user or get existing user via organization API key. If user is new or has no organization, they will be assigned to this organization and their wallet will be charged with the organization's user_credit."
},
"response": [
{
"name": "success - new user",
"originalRequest": {
"method": "POST",
"header": [
{
"key": "X-API-Key",
"value": "{{organizationApiKey}}",
"description": "Organization API Key",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"mobile_number\": \"09123456789\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{baseURL}}/api/v1/organizations/register-user",
"host": [
"{{baseURL}}"
],
"path": [
"api",
"v1",
"organizations",
"register-user"
]
}
},
"status": "OK",
"code": 200,
"_postman_previewlanguage": "json",
"header": [
{
"key": "content-type",
"value": "application/json"
}
],
"cookie": [],
"body": "{\n \"id\": 1,\n \"mobile_number\": \"09123456789\",\n \"organization_id\": 1,\n \"organization_title\": \"Test Organization\",\n \"wallet_balance\": 100.0,\n \"is_new_user\": true,\n \"credit_charged\": 100.0\n}"
},
{
"name": "success - existing user",
"originalRequest": {
"method": "POST",
"header": [
{
"key": "X-API-Key",
"value": "{{organizationApiKey}}",
"description": "Organization API Key",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"mobile_number\": \"09123456789\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{baseURL}}/api/v1/organizations/register-user",
"host": [
"{{baseURL}}"
],
"path": [
"api",
"v1",
"organizations",
"register-user"
]
}
},
"status": "OK",
"code": 200,
"_postman_previewlanguage": "json",
"header": [
{
"key": "content-type",
"value": "application/json"
}
],
"cookie": [],
"body": "{\n \"id\": 1,\n \"mobile_number\": \"09123456789\",\n \"organization_id\": 1,\n \"organization_title\": \"Test Organization\",\n \"wallet_balance\": 100.0,\n \"is_new_user\": false,\n \"credit_charged\": 0.0\n}"
},
{
"name": "invalid api key",
"originalRequest": {
"method": "POST",
"header": [
{
"key": "X-API-Key",
"value": "invalid-api-key",
"description": "Organization API Key",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"mobile_number\": \"09123456789\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{baseURL}}/api/v1/organizations/register-user",
"host": [
"{{baseURL}}"
],
"path": [
"api",
"v1",
"organizations",
"register-user"
]
}
},
"status": "Unauthorized",
"code": 401,
"_postman_previewlanguage": "json",
"header": [
{
"key": "content-type",
"value": "application/json"
}
],
"cookie": [],
"body": "{\n \"error_code\": \"INVALID_API_KEY\",\n \"message\": \"Invalid API key\",\n \"context\": {\n \"api_key_prefix\": \"invalid-\"\n }\n}"
},
{
"name": "organization disabled",
"originalRequest": {
"method": "POST",
"header": [
{
"key": "X-API-Key",
"value": "{{organizationApiKey}}",
"description": "Organization API Key",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"mobile_number\": \"09123456789\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{baseURL}}/api/v1/organizations/register-user",
"host": [
"{{baseURL}}"
],
"path": [
"api",
"v1",
"organizations",
"register-user"
]
}
},
"status": "Forbidden",
"code": 403,
"_postman_previewlanguage": "json",
"header": [
{
"key": "content-type",
"value": "application/json"
}
],
"cookie": [],
"body": "{\n \"error_code\": \"ORGANIZATION_DISABLED\",\n \"message\": \"Organization is disabled\",\n \"context\": {\n \"organization_id\": 1\n }\n}"
},
{
"name": "organization expired",
"originalRequest": {
"method": "POST",
"header": [
{
"key": "X-API-Key",
"value": "{{organizationApiKey}}",
"description": "Organization API Key",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"mobile_number\": \"09123456789\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{baseURL}}/api/v1/organizations/register-user",
"host": [
"{{baseURL}}"
],
"path": [
"api",
"v1",
"organizations",
"register-user"
]
}
},
"status": "Forbidden",
"code": 403,
"_postman_previewlanguage": "json",
"header": [
{
"key": "content-type",
"value": "application/json"
}
],
"cookie": [],
"body": "{\n \"error_code\": \"ORGANIZATION_EXPIRED\",\n \"message\": \"Organization has expired\",\n \"context\": {\n \"organization_id\": 1,\n \"expires_at\": \"2024-01-01T00:00:00\"\n }\n}"
},
{
"name": "invalid mobile format",
"originalRequest": {
"method": "POST",
"header": [
{
"key": "X-API-Key",
"value": "{{organizationApiKey}}",
"description": "Organization API Key",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"mobile_number\": \"01234567890\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{baseURL}}/api/v1/organizations/register-user",
"host": [
"{{baseURL}}"
],
"path": [
"api",
"v1",
"organizations",
"register-user"
]
}
},
"status": "Unprocessable Entity",
"code": 422,
"_postman_previewlanguage": "json",
"header": [
{
"key": "content-type",
"value": "application/json"
}
],
"cookie": [],
"body": "{\n \"mobile_number\": \"String should match pattern '^09\\\\d{9}$'\"\n}"
},
{
"name": "missing api key header",
"originalRequest": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"mobile_number\": \"09123456789\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{baseURL}}/api/v1/organizations/register-user",
"host": [
"{{baseURL}}"
],
"path": [
"api",
"v1",
"organizations",
"register-user"
]
}
},
"status": "Unprocessable Entity",
"code": 422,
"_postman_previewlanguage": "json",
"header": [
{
"key": "content-type",
"value": "application/json"
}
],
"cookie": [],
"body": "{\n \"detail\": [\n {\n \"type\": \"missing\",\n \"loc\": [\"header\", \"x-api-key\"],\n \"msg\": \"Field required\",\n \"input\": null\n }\n ]\n}"
}
]
}
]
}
]
}
],
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"packages": {},
"exec": [
""
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"packages": {},
"exec": [
""
]
}
}
],
"variable": [
{
"key": "baseURL",
"value": "http://127.0.0.0:8000",
"type": "string"
},
{
"key": "access_token",
"value": "",
"type": "string"
},
{
"key": "accessToken",
"value": ""
},
{
"key": "refreshToken",
"value": ""
},
{
"key": "organizationApiKey",
"value": "",
"type": "string"
}
]
}
-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
+116
View File
@@ -0,0 +1,116 @@
---
# CMS Application Configuration Secret (Production)
# This Secret stores appsettings.Production.json externally in K8s
# so configuration persists independently of Docker image rebuilds.
#
# To edit config without redeploying:
# kubectl edit secret cms-appsettings
# kubectl rollout restart deployment/cms
#
apiVersion: v1
kind: Secret
metadata:
name: cms-appsettings
namespace: default
labels:
app: cms
environment: production
type: Opaque
stringData:
appsettings.Production.json: |
{
"PaymentProvider": "zarinpal",
"ZarinPal": {
"MerchantId": "4225d555-5fa9-4df0-9b61-1ce152cbbba8",
"UseSandbox": false
},
"CmsBaseUrl": "https://cms.kbs2.ir",
"FrontOfficeBaseUrl": "https://kbs2.ir",
"JwtSecurityKey": "TvlZVx5TJaHs8e9HgUdGzhGP2CIidoI444nAj+8+g7c=",
"JwtIssuer": "https://localhost",
"JwtAudience": "https://localhost",
"JwtExpiryInDays": 5,
"ConnectionStrings": {
"DefaultConnection": "Server=mssql-svc;Database=KBS;User Id=sa;Password=YourStrong@Passw0rd;TrustServerCertificate=True;",
"providerName": "System.Data.SqlClient"
},
"Otp": {
"Secret": "K2w8k1h1mH2Qz1kqWk0c8kQ2Pq8q9H1eE2nqN1qQ8x7M="
},
"Monitoring": {
"SentryEnabled": false,
"SentryDsn": "",
"SlackEnabled": false,
"SlackWebhookUrl": "",
"EmailAlertsEnabled": false,
"AdminEmails": [
"admin@example.com"
],
"SmsNotificationsEnabled": false,
"SmsApiKey": "",
"SmsGatewayUrl": ""
},
"Email": {
"Enabled": true,
"SmtpHost": "smtp.gmail.com",
"SmtpPort": 587,
"SmtpUsername": "your-email@gmail.com",
"SmtpPassword": "your-app-password",
"FromEmail": "noreply@foursat.com",
"FromName": "FourSat CMS",
"EnableSsl": true
},
"Sms": {
"Enabled": true,
"Provider": "Kavenegar",
"KavenegarApiKey": "43676A4E786A6C50452F2F6252507939346A5145764B33566B456454374E657A614468706658656D6534593D",
"Sender": "1000001110100"
},
"DayaPayment": {
"BaseUrl": "https://api.daya.ir",
"ApiKey": "YOUR_DAYA_API_KEY"
},
"DayaApi": {
"UseMock": false,
"BaseAddress": "https://Dayadiamond.ir",
"MerchantPermissionKey": "56146364$04sXjethI5WxhItR1Q9xnmFdJzl2BB8Bclsq8dAy7YVSZp3vtt-wP7ivrcCvmKLq",
"CacheDurationMinutes": 20
},
"Chatika": {
"Enabled": true,
"BaseUrl": "https://api.chatika.ir",
"ApiKey": "tIukvL8dnV4cB3yVWcCD9Xyfbj8rBxm5wPt2mLyJCgTsBBoMTWjt6mFEqQwpw-er"
},
"BackgroundJobs": {
"WeeklyCommissionCalculation": {
"Enabled": false,
"CronExpression": "5 0 * * 0"
}
},
"SeedWorkers": {
"MagicWalletCycleSeed": {
"Enabled": true
}
},
"AllowedHosts": "*",
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http2"
}
},
"Authentication": {
"Authority": "https://ids.domain.com/",
"Audience": "domain_api"
},
"Seq": {
"ServerUrl": "http://seq-svc:5341",
"ApiKey": "oxpvpUzU1pZxMS4s3Fqq"
},
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft.AspNetCore": "Warning"
}
}
}
+139
View File
@@ -0,0 +1,139 @@
---
# CMS Uploads PersistentVolumeClaim (Production)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: cms-uploads-pvc
namespace: default
labels:
app: cms
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi
---
# CMS Microservice Deployment (Production)
apiVersion: apps/v1
kind: Deployment
metadata:
name: cms
namespace: default
labels:
app: cms
spec:
replicas: 1
selector:
matchLabels:
app: cms
template:
metadata:
labels:
app: cms
spec:
containers:
- name: cms
image: 194.5.195.53:30080/admin/cms:prod
imagePullPolicy: Always
ports:
- containerPort: 8080
name: http
env:
- name: ASPNETCORE_ENVIRONMENT
value: "Production"
- name: ASPNETCORE_URLS
value: "http://+:8080"
volumeMounts:
- name: cms-uploads
mountPath: /app/Uploads
- name: cms-config
mountPath: /app/appsettings.Production.json
subPath: appsettings.Production.json
readOnly: true
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
livenessProbe:
httpGet:
path: /health/live
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
volumes:
- name: cms-uploads
persistentVolumeClaim:
claimName: cms-uploads-pvc
- name: cms-config
secret:
secretName: cms-appsettings
---
# CMS Service (Production)
apiVersion: v1
kind: Service
metadata:
name: cms-svc
namespace: default
spec:
selector:
app: cms
ports:
- name: http
port: 8080
targetPort: 8080
type: ClusterIP
---
# CMS Ingress (Production)
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: cms-ingress
namespace: default
annotations:
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
ingressClassName: nginx
tls:
- hosts:
- cms.kbs1.ir
- cms.kbs2.ir
secretName: cms-tls
rules:
- host: cms.kbs2.ir
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: cms-svc
port:
number: 8080
- host: cms.kbs1.ir
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: cms-svc
port:
number: 8080
+113
View File
@@ -0,0 +1,113 @@
---
# CMS Application Configuration Secret (Staging)
# This Secret stores appsettings.Staging.json externally in K8s
# so configuration persists independently of Docker image rebuilds.
#
# To edit config without redeploying:
# kubectl edit secret cms-appsettings
# kubectl rollout restart deployment/cms
#
apiVersion: v1
kind: Secret
metadata:
name: cms-appsettings
namespace: default
labels:
app: cms
environment: staging
type: Opaque
stringData:
appsettings.Staging.json: |
{
"PaymentProvider": "zarinpal",
"ZarinPal": {
"MerchantId": "4225d555-5fa9-4df0-9b61-1ce152cbbba8",
"UseSandbox": true
},
"CmsBaseUrl": "https://cms.se.kbs1.ir",
"FrontOfficeBaseUrl": "https://frontoffice.se.kbs1.ir",
"FMS": {
"Address": "https://dl.afrino.co"
},
"JwtSecurityKey": "TvlZVx5TJaHs8e9HgUdGzhGP2CIidoI444nAj+8+g7c=",
"JwtIssuer": "https://localhost",
"JwtAudience": "https://localhost",
"JwtExpiryInDays": 5,
"ConnectionStrings": {
"DefaultConnection": "Data Source=194.5.195.53,31433; Initial Catalog=Foursat;User ID=sa;Password=87zH26nbqT;Connection Timeout=300000;MultipleActiveResultSets=True;Encrypt=False",
"providerName": "System.Data.SqlClient"
},
"Otp": {
"Secret": "K2w8k1h1mH2Qz1kqWk0c8kQ2Pq8q9H1eE2nqN1qQ8x7M="
},
"Monitoring": {
"SentryEnabled": false,
"SentryDsn": "",
"SlackEnabled": false,
"SlackWebhookUrl": "",
"EmailAlertsEnabled": false,
"AdminEmails": ["admin@example.com"],
"SmsNotificationsEnabled": false,
"SmsApiKey": "",
"SmsGatewayUrl": ""
},
"Email": {
"Enabled": true,
"SmtpHost": "smtp.gmail.com",
"SmtpPort": 587,
"SmtpUsername": "your-email@gmail.com",
"SmtpPassword": "your-app-password",
"FromEmail": "noreply@foursat.com",
"FromName": "FourSat CMS",
"EnableSsl": true
},
"Sms": {
"Enabled": true,
"Provider": "Kavenegar",
"KavenegarApiKey": "43676A4E786A6C50452F2F6252507939346A5145764B33566B456454374E657A614468706658656D6534593D",
"Sender": "1000001110100"
},
"DayaPayment": {
"BaseUrl": "https://api.daya.ir",
"ApiKey": "YOUR_DAYA_API_KEY"
},
"DayaApi": {
"UseMock": false,
"BaseAddress": "https://Dayadiamond.ir",
"MerchantPermissionKey": "56146364$04sXjethI5WxhItR1Q9xnmFdJzl2BB8Bclsq8dAy7YVSZp3vtt-wP7ivrcCvmKLq",
"CacheDurationMinutes": 20
},
"Chatika": {
"Enabled": true,
"BaseUrl": "https://api.chatika.ir",
"ApiKey": "tIukvL8dnV4cB3yVWcCD9Xyfbj8rBxm5wPt2mLyJCgTsBBoMTWjt6mFEqQwpw-er"
},
"BackgroundJobs": {
"WeeklyCommissionCalculation": {
"Enabled": true,
"CronExpression": "5 0 * * 0"
}
},
"SeedWorkers": {
"MagicWalletCycleSeed": {
"Enabled": true
}
},
"FileStorage": {
"UploadPath": "/app/Uploads"
},
"AllowedHosts": "*",
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1AndHttp2"
}
},
"Authentication": {
"Authority": "https://ids.domain.com/",
"Audience": "domain_api"
},
"Seq": {
"ServerUrl": "https://seq.afrino.co",
"ApiKey": "oxpvpUzU1pZxMS4s3Fqq"
}
}
+132
View File
@@ -0,0 +1,132 @@
---
# CMS Uploads PersistentVolumeClaim
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: cms-uploads-pvc
namespace: default
labels:
app: cms
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi
---
# CMS Microservice Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: cms
namespace: default
labels:
app: cms
spec:
replicas: 1
selector:
matchLabels:
app: cms
template:
metadata:
labels:
app: cms
spec:
containers:
- name: cms
image: 194.5.195.53:30080/admin/cms:latest
imagePullPolicy: Always
ports:
- containerPort: 8080
name: http
env:
- name: ASPNETCORE_ENVIRONMENT
value: "Staging"
- name: ASPNETCORE_URLS
value: "http://+:8080"
volumeMounts:
- name: cms-uploads
mountPath: /app/Uploads
- name: cms-config
mountPath: /app/appsettings.Staging.json
subPath: appsettings.Staging.json
readOnly: true
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
livenessProbe:
httpGet:
path: /health/live
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
volumes:
- name: cms-uploads
persistentVolumeClaim:
claimName: cms-uploads-pvc
- name: cms-config
secret:
secretName: cms-appsettings
---
# CMS Service
apiVersion: v1
kind: Service
metadata:
name: cms-svc
namespace: default
spec:
selector:
app: cms
ports:
- name: http
port: 8080
targetPort: 8080
type: ClusterIP
---
# CMS Ingress
# If clients report TLS PartialChain, the tls secret (cms-tls) tls.crt must include the full chain
# (leaf + intermediates). cert-manager ACME usually provides this; manual certs need fullchain.pem in tls.crt.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: cms-ingress
namespace: default
annotations:
kubernetes.io/ingress.class: "nginx"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
spec:
tls:
- hosts:
- cms.se.kbs1.ir
secretName: cms-tls
rules:
- host: cms.se.kbs1.ir
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: cms-svc
port:
number: 8080
@@ -0,0 +1,42 @@
namespace CMSMicroservice.Application.AppVersionCQ.Commands.UpdateAppVersion;
/// <summary>
/// Command برای آپدیت یا ایجاد نسخه جدید اپلیکیشن
/// </summary>
public record UpdateAppVersionCommand : IRequest<Unit>
{
/// <summary>
/// نام اپلیکیشن (FrontOffice, BackOffice, MobileApp)
/// </summary>
public string AppName { get; init; } = string.Empty;
/// <summary>
/// شماره نسخه جدید (مثلاً 1.2.3)
/// </summary>
public string CurrentVersion { get; init; } = string.Empty;
/// <summary>
/// حداقل نسخه مورد نیاز
/// </summary>
public string? MinRequiredVersion { get; init; }
/// <summary>
/// آیا کش کامل باید پاک بشه؟
/// </summary>
public bool RequiresFullCacheClear { get; init; }
/// <summary>
/// پیام آپدیت
/// </summary>
public string? UpdateMessage { get; init; }
/// <summary>
/// توضیحات تغییرات این نسخه
/// </summary>
public string? ReleaseNotes { get; init; }
/// <summary>
/// دلیل آپدیت (برای لاگ)
/// </summary>
public string? UpdateReason { get; init; }
}
@@ -0,0 +1,65 @@
using CMSMicroservice.Domain.Entities.Configuration;
namespace CMSMicroservice.Application.AppVersionCQ.Commands.UpdateAppVersion;
/// <summary>
/// Handler برای آپدیت یا ایجاد نسخه جدید اپلیکیشن
/// </summary>
public class UpdateAppVersionCommandHandler : IRequestHandler<UpdateAppVersionCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly ILogger<UpdateAppVersionCommandHandler> _logger;
public UpdateAppVersionCommandHandler(
IApplicationDbContext context,
ILogger<UpdateAppVersionCommandHandler> logger)
{
_context = context;
_logger = logger;
}
public async Task<Unit> Handle(UpdateAppVersionCommand request, CancellationToken cancellationToken)
{
// پیدا کردن نسخه موجود برای این اپ
var existingVersion = await _context.AppVersions
.Where(v => v.AppName == request.AppName && !v.IsDeleted)
.FirstOrDefaultAsync(cancellationToken);
if (existingVersion != null)
{
// آپدیت نسخه موجود
existingVersion.CurrentVersion = request.CurrentVersion;
existingVersion.MinRequiredVersion = request.MinRequiredVersion ?? request.CurrentVersion;
existingVersion.RequiresFullCacheClear = request.RequiresFullCacheClear;
existingVersion.UpdateMessage = request.UpdateMessage;
existingVersion.ReleaseNotes = request.ReleaseNotes;
_logger.LogInformation(
"App version updated: {AppName} v{Version}, CacheClear={CacheClear}, Reason={Reason}",
request.AppName, request.CurrentVersion, request.RequiresFullCacheClear, request.UpdateReason);
}
else
{
// ایجاد نسخه جدید
var newVersion = new AppVersion
{
AppName = request.AppName,
CurrentVersion = request.CurrentVersion,
MinRequiredVersion = request.MinRequiredVersion ?? request.CurrentVersion,
RequiresFullCacheClear = request.RequiresFullCacheClear,
UpdateMessage = request.UpdateMessage,
ReleaseNotes = request.ReleaseNotes,
IsActive = true
};
_context.AppVersions.Add(newVersion);
_logger.LogInformation(
"New app version created: {AppName} v{Version}, CacheClear={CacheClear}, Reason={Reason}",
request.AppName, request.CurrentVersion, request.RequiresFullCacheClear, request.UpdateReason);
}
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,23 @@
namespace CMSMicroservice.Application.AppVersionCQ.Queries.GetAllAppVersions;
/// <summary>
/// Query برای دریافت همه نسخه‌های اپلیکیشن‌ها
/// </summary>
public record GetAllAppVersionsQuery(bool IncludeInactive = false) : IRequest<List<AppVersionItemDto>>;
/// <summary>
/// DTO برای هر آیتم نسخه اپلیکیشن
/// </summary>
public record AppVersionItemDto
{
public long Id { get; init; }
public string AppName { get; init; } = string.Empty;
public string CurrentVersion { get; init; } = string.Empty;
public string MinRequiredVersion { get; init; } = string.Empty;
public bool RequiresFullCacheClear { get; init; }
public string? UpdateMessage { get; init; }
public string? ReleaseNotes { get; init; }
public bool IsActive { get; init; }
public DateTime Created { get; init; }
public DateTime? LastModified { get; init; }
}
@@ -0,0 +1,44 @@
namespace CMSMicroservice.Application.AppVersionCQ.Queries.GetAllAppVersions;
/// <summary>
/// Handler برای دریافت همه نسخه‌های اپلیکیشن‌ها
/// </summary>
public class GetAllAppVersionsQueryHandler : IRequestHandler<GetAllAppVersionsQuery, List<AppVersionItemDto>>
{
private readonly IApplicationDbContext _context;
public GetAllAppVersionsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<AppVersionItemDto>> Handle(GetAllAppVersionsQuery request, CancellationToken cancellationToken)
{
var query = _context.AppVersions
.Where(v => !v.IsDeleted);
if (!request.IncludeInactive)
{
query = query.Where(v => v.IsActive);
}
var versions = await query
.OrderBy(v => v.AppName)
.Select(v => new AppVersionItemDto
{
Id = v.Id,
AppName = v.AppName,
CurrentVersion = v.CurrentVersion,
MinRequiredVersion = v.MinRequiredVersion,
RequiresFullCacheClear = v.RequiresFullCacheClear,
UpdateMessage = v.UpdateMessage,
ReleaseNotes = v.ReleaseNotes,
IsActive = v.IsActive,
Created = v.Created,
LastModified = v.LastModified
})
.ToListAsync(cancellationToken);
return versions;
}
}
@@ -0,0 +1,22 @@
namespace CMSMicroservice.Application.AppVersionCQ.Queries.GetAppVersion;
/// <summary>
/// Query برای دریافت آخرین نسخه یک اپلیکیشن
/// </summary>
public record GetAppVersionQuery(string AppName, string? CurrentClientVersion = null) : IRequest<AppVersionDto?>;
/// <summary>
/// DTO برای اطلاعات نسخه اپلیکیشن
/// </summary>
public record AppVersionDto
{
public bool Found { get; init; }
public string AppName { get; init; } = string.Empty;
public string CurrentVersion { get; init; } = string.Empty;
public string MinRequiredVersion { get; init; } = string.Empty;
public bool RequiresFullCacheClear { get; init; }
public bool RequiresUpdate { get; init; }
public string? UpdateMessage { get; init; }
public string? ReleaseNotes { get; init; }
public DateTime? LastUpdated { get; init; }
}
@@ -0,0 +1,75 @@
using CMSMicroservice.Domain.Entities.Configuration;
namespace CMSMicroservice.Application.AppVersionCQ.Queries.GetAppVersion;
/// <summary>
/// Handler برای دریافت آخرین نسخه اپلیکیشن
/// </summary>
public class GetAppVersionQueryHandler : IRequestHandler<GetAppVersionQuery, AppVersionDto?>
{
private readonly IApplicationDbContext _context;
public GetAppVersionQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<AppVersionDto?> Handle(GetAppVersionQuery request, CancellationToken cancellationToken)
{
var appVersion = await _context.AppVersions
.Where(v => v.AppName == request.AppName && v.IsActive && !v.IsDeleted)
.FirstOrDefaultAsync(cancellationToken);
if (appVersion == null)
{
return new AppVersionDto
{
Found = false,
AppName = request.AppName
};
}
// مقایسه ورژن کلاینت با حداقل نسخه مورد نیاز
bool requiresUpdate = false;
if (!string.IsNullOrEmpty(request.CurrentClientVersion) && !string.IsNullOrEmpty(appVersion.MinRequiredVersion))
{
requiresUpdate = CompareVersions(request.CurrentClientVersion, appVersion.MinRequiredVersion) < 0;
}
return new AppVersionDto
{
Found = true,
AppName = appVersion.AppName,
CurrentVersion = appVersion.CurrentVersion,
MinRequiredVersion = appVersion.MinRequiredVersion,
RequiresFullCacheClear = appVersion.RequiresFullCacheClear,
RequiresUpdate = requiresUpdate,
UpdateMessage = appVersion.UpdateMessage,
ReleaseNotes = appVersion.ReleaseNotes,
LastUpdated = appVersion.LastModified ?? appVersion.Created
};
}
/// <summary>
/// مقایسه دو نسخه (مثلاً 1.2.3 با 1.3.0)
/// برگشت: منفی = اولی کوچکتر، مثبت = اولی بزرگتر، صفر = برابر
/// </summary>
private static int CompareVersions(string version1, string version2)
{
var v1Parts = version1.Split('.').Select(s => int.TryParse(s, out var n) ? n : 0).ToArray();
var v2Parts = version2.Split('.').Select(s => int.TryParse(s, out var n) ? n : 0).ToArray();
var maxLen = Math.Max(v1Parts.Length, v2Parts.Length);
for (int i = 0; i < maxLen; i++)
{
var v1 = i < v1Parts.Length ? v1Parts[i] : 0;
var v2 = i < v2Parts.Length ? v2Parts[i] : 0;
if (v1 != v2)
return v1.CompareTo(v2);
}
return 0;
}
}
@@ -0,0 +1,13 @@
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.CreateBlogCategory;
public class CreateBlogCategoryCommand : IRequest<long>
{
public string Title { get; set; } = default!;
public string Slug { get; set; } = default!;
public string? Description { get; set; }
public string? IconName { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
}
@@ -0,0 +1,33 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.CreateBlogCategory;
public class CreateBlogCategoryCommandHandler : IRequestHandler<CreateBlogCategoryCommand, long>
{
private readonly IApplicationDbContext _context;
public CreateBlogCategoryCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<long> Handle(CreateBlogCategoryCommand request, CancellationToken cancellationToken)
{
var entity = new BlogCategory
{
Title = request.Title,
Slug = request.Slug.ToLower(),
Description = request.Description,
IconName = request.IconName,
SortOrder = request.SortOrder,
IsActive = request.IsActive
};
_context.BlogCategories.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return entity.Id;
}
}
@@ -0,0 +1,24 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.CreateBlogCategory;
public class CreateBlogCategoryCommandValidator : AbstractValidator<CreateBlogCategoryCommand>
{
public CreateBlogCategoryCommandValidator()
{
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان دسته‌بندی الزامی است")
.MaximumLength(200).WithMessage("عنوان دسته‌بندی حداکثر ۲۰۰ کاراکتر");
RuleFor(x => x.Slug)
.NotEmpty().WithMessage("اسلاگ الزامی است")
.MaximumLength(200).WithMessage("اسلاگ حداکثر ۲۰۰ کاراکتر")
.Matches(@"^[a-z0-9\-]+$").WithMessage("اسلاگ فقط شامل حروف کوچک، اعداد و خط تیره");
RuleFor(x => x.Description)
.MaximumLength(1000).WithMessage("توضیحات حداکثر ۱۰۰۰ کاراکتر");
RuleFor(x => x.IconName)
.MaximumLength(100).WithMessage("نام آیکون حداکثر ۱۰۰ کاراکتر");
}
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.DeleteBlogCategory;
public class DeleteBlogCategoryCommand : IRequest<Unit>
{
public long Id { get; set; }
}
@@ -0,0 +1,29 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.DeleteBlogCategory;
public class DeleteBlogCategoryCommandHandler : IRequestHandler<DeleteBlogCategoryCommand, Unit>
{
private readonly IApplicationDbContext _context;
public DeleteBlogCategoryCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(DeleteBlogCategoryCommand request, CancellationToken cancellationToken)
{
var entity = await _context.BlogCategories.FindAsync(new object[] { request.Id }, cancellationToken);
if (entity == null || entity.IsDeleted)
throw new NotFoundException(nameof(BlogCategory), request.Id);
entity.IsDeleted = true;
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,14 @@
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.UpdateBlogCategory;
public class UpdateBlogCategoryCommand : IRequest<Unit>
{
public long Id { get; set; }
public string Title { get; set; } = default!;
public string Slug { get; set; } = default!;
public string? Description { get; set; }
public string? IconName { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; }
}
@@ -0,0 +1,34 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.UpdateBlogCategory;
public class UpdateBlogCategoryCommandHandler : IRequestHandler<UpdateBlogCategoryCommand, Unit>
{
private readonly IApplicationDbContext _context;
public UpdateBlogCategoryCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(UpdateBlogCategoryCommand request, CancellationToken cancellationToken)
{
var entity = await _context.BlogCategories.FindAsync(new object[] { request.Id }, cancellationToken);
if (entity == null || entity.IsDeleted)
throw new NotFoundException(nameof(BlogCategory), request.Id);
entity.Title = request.Title;
entity.Slug = request.Slug.ToLower();
entity.Description = request.Description;
entity.IconName = request.IconName;
entity.SortOrder = request.SortOrder;
entity.IsActive = request.IsActive;
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,27 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogCategoryCQ.Commands.UpdateBlogCategory;
public class UpdateBlogCategoryCommandValidator : AbstractValidator<UpdateBlogCategoryCommand>
{
public UpdateBlogCategoryCommandValidator()
{
RuleFor(x => x.Id)
.GreaterThan(0).WithMessage("شناسه دسته‌بندی نامعتبر است");
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان دسته‌بندی الزامی است")
.MaximumLength(200).WithMessage("عنوان دسته‌بندی حداکثر ۲۰۰ کاراکتر");
RuleFor(x => x.Slug)
.NotEmpty().WithMessage("اسلاگ الزامی است")
.MaximumLength(200).WithMessage("اسلاگ حداکثر ۲۰۰ کاراکتر")
.Matches(@"^[a-z0-9\-]+$").WithMessage("اسلاگ فقط شامل حروف کوچک، اعداد و خط تیره");
RuleFor(x => x.Description)
.MaximumLength(1000).WithMessage("توضیحات حداکثر ۱۰۰۰ کاراکتر");
RuleFor(x => x.IconName)
.MaximumLength(100).WithMessage("نام آیکون حداکثر ۱۰۰ کاراکتر");
}
}
@@ -0,0 +1,45 @@
using CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetActiveBlogCategories;
public class GetActiveBlogCategoriesQuery : IRequest<List<BlogCategoryDto>>
{
}
public class GetActiveBlogCategoriesQueryHandler : IRequestHandler<GetActiveBlogCategoriesQuery, List<BlogCategoryDto>>
{
private readonly IApplicationDbContext _context;
public GetActiveBlogCategoriesQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<BlogCategoryDto>> Handle(GetActiveBlogCategoriesQuery request, CancellationToken cancellationToken)
{
var categories = await _context.BlogCategories
.Include(x => x.BlogPostCategories)
.Where(x => !x.IsDeleted && x.IsActive)
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Title)
.Select(x => new BlogCategoryDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Description = x.Description,
IconName = x.IconName,
SortOrder = x.SortOrder,
IsActive = x.IsActive,
PostCount = x.BlogPostCategories.Count,
Created = x.Created,
LastModified = x.LastModified
})
.ToListAsync(cancellationToken);
return categories;
}
}
@@ -0,0 +1,11 @@
using CMSMicroservice.Application.Common.Models;
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetAllBlogCategories;
public class GetAllBlogCategoriesQuery : IRequest<GetAllBlogCategoriesResponseDto>
{
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 20;
public string? SearchTerm { get; set; }
}
@@ -0,0 +1,64 @@
using CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetAllBlogCategories;
public class GetAllBlogCategoriesQueryHandler : IRequestHandler<GetAllBlogCategoriesQuery, GetAllBlogCategoriesResponseDto>
{
private readonly IApplicationDbContext _context;
public GetAllBlogCategoriesQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllBlogCategoriesResponseDto> Handle(GetAllBlogCategoriesQuery request, CancellationToken cancellationToken)
{
var query = _context.BlogCategories
.Include(x => x.BlogPostCategories)
.Where(x => !x.IsDeleted);
if (!string.IsNullOrEmpty(request.SearchTerm))
{
var term = request.SearchTerm.ToLower();
query = query.Where(x => x.Title.ToLower().Contains(term) || x.Slug.ToLower().Contains(term));
}
var totalCount = await query.CountAsync(cancellationToken);
var categories = await query
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Title)
.Skip((request.PageNumber - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new BlogCategoryDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Description = x.Description,
IconName = x.IconName,
SortOrder = x.SortOrder,
IsActive = x.IsActive,
PostCount = x.BlogPostCategories.Count,
Created = x.Created,
LastModified = x.LastModified
})
.ToListAsync(cancellationToken);
var metaData = new MetaData
{
TotalCount = totalCount,
PageSize = request.PageSize,
CurrentPage = request.PageNumber,
TotalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasNext = request.PageNumber < (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasPrevious = request.PageNumber > 1
};
return new GetAllBlogCategoriesResponseDto { MetaData = metaData, Models = categories };
}
}
@@ -0,0 +1,10 @@
using CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
using CMSMicroservice.Application.Common.Models;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetAllBlogCategories;
public class GetAllBlogCategoriesResponseDto
{
public MetaData MetaData { get; set; } = default!;
public List<BlogCategoryDto> Models { get; set; } = new();
}
@@ -0,0 +1,15 @@
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
public class BlogCategoryDto
{
public long Id { get; set; }
public string Title { get; set; } = default!;
public string Slug { get; set; } = default!;
public string? Description { get; set; }
public string? IconName { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; }
public int PostCount { get; set; }
public DateTime Created { get; set; }
public DateTime? LastModified { get; set; }
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
public class GetBlogCategoryQuery : IRequest<BlogCategoryDto>
{
public long Id { get; set; }
}
@@ -0,0 +1,41 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
public class GetBlogCategoryQueryHandler : IRequestHandler<GetBlogCategoryQuery, BlogCategoryDto>
{
private readonly IApplicationDbContext _context;
public GetBlogCategoryQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<BlogCategoryDto> Handle(GetBlogCategoryQuery request, CancellationToken cancellationToken)
{
var entity = await _context.BlogCategories
.Include(x => x.BlogPostCategories)
.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken);
if (entity == null)
throw new NotFoundException(nameof(BlogCategory), request.Id);
return new BlogCategoryDto
{
Id = entity.Id,
Title = entity.Title,
Slug = entity.Slug,
Description = entity.Description,
IconName = entity.IconName,
SortOrder = entity.SortOrder,
IsActive = entity.IsActive,
PostCount = entity.BlogPostCategories.Count,
Created = entity.Created,
LastModified = entity.LastModified
};
}
}
@@ -0,0 +1,14 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.ArchiveBlogPost;
public class ArchiveBlogPostCommand : IRequest<ArchiveBlogPostResult>
{
public long Id { get; set; }
}
public class ArchiveBlogPostResult
{
public bool Success { get; set; }
public string Message { get; set; } = string.Empty;
}
@@ -0,0 +1,32 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.ArchiveBlogPost;
public class ArchiveBlogPostCommandHandler : IRequestHandler<ArchiveBlogPostCommand, ArchiveBlogPostResult>
{
private readonly IApplicationDbContext _context;
private readonly ILogger<ArchiveBlogPostCommandHandler> _logger;
public ArchiveBlogPostCommandHandler(IApplicationDbContext context, ILogger<ArchiveBlogPostCommandHandler> logger)
{
_context = context;
_logger = logger;
}
public async Task<ArchiveBlogPostResult> Handle(ArchiveBlogPostCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
post.Status = BlogPostStatus.Archived;
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("Blog post archived. Id: {Id}, Title: {Title}", post.Id, post.Title);
return new ArchiveBlogPostResult { Success = true, Message = "مقاله آرشیو شد" };
}
}
@@ -0,0 +1,25 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.CreateBlogPost;
/// <summary>
/// دستور ایجاد مقاله جدید
/// </summary>
public class CreateBlogPostCommand : IRequest<long>
{
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string? Summary { get; set; }
public string HtmlContent { get; set; } = string.Empty;
public string? FeaturedImagePath { get; set; }
public string? FeaturedImageThumbnailPath { get; set; }
public List<long> CategoryIds { get; set; } = new();
public List<long> TagIds { get; set; } = new();
public bool IsFeatured { get; set; }
public int SortOrder { get; set; }
// Image upload properties
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
}
@@ -0,0 +1,100 @@
using CMSMicroservice.Application.Common;
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.CreateBlogPost;
public class CreateBlogPostCommandHandler : IRequestHandler<CreateBlogPostCommand, long>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
private readonly IFileManager _fileManager;
private readonly ILogger<CreateBlogPostCommandHandler> _logger;
public CreateBlogPostCommandHandler(
IApplicationDbContext context,
ICurrentUserService currentUser,
IFileManager fileManager,
ILogger<CreateBlogPostCommandHandler> logger)
{
_context = context;
_currentUser = currentUser;
_fileManager = fileManager;
_logger = logger;
}
public async Task<long> Handle(CreateBlogPostCommand request, CancellationToken cancellationToken)
{
var currentUserId = _currentUser.UserId;
if (string.IsNullOrEmpty(currentUserId) || !long.TryParse(currentUserId, out var authorUserId))
throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
var slug = BlogSlugHelper.ResolveForCreate(request.Slug, request.Title.Trim());
slug = await BlogSlugHelper.EnsureUniquePostSlugAsync(_context, slug, cancellationToken: cancellationToken);
var post = new BlogPost
{
Title = request.Title.Trim(),
Slug = slug,
Summary = request.Summary?.Trim(),
HtmlContent = request.HtmlContent,
FeaturedImagePath = request.FeaturedImagePath,
FeaturedImageThumbnailPath = request.FeaturedImageThumbnailPath,
Status = BlogPostStatus.Draft,
AuthorUserId = authorUserId,
IsFeatured = request.IsFeatured,
SortOrder = request.SortOrder,
ViewCount = 0
};
// آپلود تصویر شاخص (اگر فایل ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
"Images/BlogPosts",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
post.FeaturedImagePath = result.Main.Path;
post.FeaturedImageThumbnailPath = result.Thumbnail.Path;
}
_context.BlogPosts.Add(post);
await _context.SaveChangesAsync(cancellationToken);
// افزودن دسته‌بندی‌ها
foreach (var categoryId in request.CategoryIds)
{
_context.BlogPostCategories.Add(new BlogPostCategory
{
BlogPostId = post.Id,
BlogCategoryId = categoryId
});
}
// افزودن تگ‌ها
foreach (var tagId in request.TagIds)
{
_context.BlogPostTags.Add(new BlogPostTag
{
BlogPostId = post.Id,
TagId = tagId
});
}
if (request.CategoryIds.Any() || request.TagIds.Any())
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Blog post created. Id: {Id}, Title: {Title}, Author: {Author}",
post.Id, post.Title, authorUserId);
return post.Id;
}
}
@@ -0,0 +1,25 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.CreateBlogPost;
public class CreateBlogPostCommandValidator : AbstractValidator<CreateBlogPostCommand>
{
public CreateBlogPostCommandValidator()
{
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان مقاله الزامی است")
.MaximumLength(200).WithMessage("عنوان نمی‌تواند بیشتر از 200 کاراکتر باشد");
RuleFor(x => x.Slug)
.MaximumLength(200).WithMessage("نشانی نمی‌تواند بیشتر از 200 کاراکتر باشد")
.Matches(@"^[a-z0-9\-]+$").WithMessage("نشانی فقط می‌تواند شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد")
.When(x => !string.IsNullOrWhiteSpace(x.Slug));
RuleFor(x => x.Summary)
.MaximumLength(500).WithMessage("خلاصه نمی‌تواند بیشتر از 500 کاراکتر باشد")
.When(x => !string.IsNullOrEmpty(x.Summary));
RuleFor(x => x.HtmlContent)
.NotEmpty().WithMessage("محتوای مقاله الزامی است");
}
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.DeleteBlogPost;
public class DeleteBlogPostCommand : IRequest<Unit>
{
public long Id { get; set; }
}
@@ -0,0 +1,31 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.DeleteBlogPost;
public class DeleteBlogPostCommandHandler : IRequestHandler<DeleteBlogPostCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly ILogger<DeleteBlogPostCommandHandler> _logger;
public DeleteBlogPostCommandHandler(IApplicationDbContext context, ILogger<DeleteBlogPostCommandHandler> logger)
{
_context = context;
_logger = logger;
}
public async Task<Unit> Handle(DeleteBlogPostCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
post.IsDeleted = true;
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("Blog post soft-deleted. Id: {Id}", post.Id);
return Unit.Value;
}
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.IncrementViewCount;
public class IncrementViewCountCommand : IRequest<Unit>
{
public long Id { get; set; }
}
@@ -0,0 +1,27 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.IncrementViewCount;
public class IncrementViewCountCommandHandler : IRequestHandler<IncrementViewCountCommand, Unit>
{
private readonly IApplicationDbContext _context;
public IncrementViewCountCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(IncrementViewCountCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken);
if (post != null)
{
post.ViewCount++;
await _context.SaveChangesAsync(cancellationToken);
}
return Unit.Value;
}
}
@@ -0,0 +1,15 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.PublishBlogPost;
public class PublishBlogPostCommand : IRequest<PublishBlogPostResult>
{
public long Id { get; set; }
}
public class PublishBlogPostResult
{
public bool Success { get; set; }
public string Message { get; set; } = string.Empty;
public DateTime? PublishedAt { get; set; }
}
@@ -0,0 +1,41 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.PublishBlogPost;
public class PublishBlogPostCommandHandler : IRequestHandler<PublishBlogPostCommand, PublishBlogPostResult>
{
private readonly IApplicationDbContext _context;
private readonly ILogger<PublishBlogPostCommandHandler> _logger;
public PublishBlogPostCommandHandler(IApplicationDbContext context, ILogger<PublishBlogPostCommandHandler> logger)
{
_context = context;
_logger = logger;
}
public async Task<PublishBlogPostResult> Handle(PublishBlogPostCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
if (post.Status == BlogPostStatus.Published)
return new PublishBlogPostResult { Success = false, Message = "مقاله قبلاً منتشر شده است" };
post.Status = BlogPostStatus.Published;
post.PublishedAt = DateTime.UtcNow;
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("Blog post published. Id: {Id}, Title: {Title}", post.Id, post.Title);
return new PublishBlogPostResult
{
Success = true,
Message = "مقاله با موفقیت منتشر شد",
PublishedAt = post.PublishedAt
};
}
}
@@ -0,0 +1,23 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.UpdateBlogPost;
public class UpdateBlogPostCommand : IRequest<Unit>
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string? Summary { get; set; }
public string HtmlContent { get; set; } = string.Empty;
public string? FeaturedImagePath { get; set; }
public string? FeaturedImageThumbnailPath { get; set; }
public List<long> CategoryIds { get; set; } = new();
public List<long> TagIds { get; set; } = new();
public bool IsFeatured { get; set; }
public int SortOrder { get; set; }
// Image upload properties
public byte[]? ImageFileBytes { get; set; }
public string? ImageFileMime { get; set; }
public string? ImageFileName { get; set; }
}
@@ -0,0 +1,101 @@
using CMSMicroservice.Application.Common;
using CMSMicroservice.Application.Common.FileManager;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.UpdateBlogPost;
public class UpdateBlogPostCommandHandler : IRequestHandler<UpdateBlogPostCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly IFileManager _fileManager;
private readonly ILogger<UpdateBlogPostCommandHandler> _logger;
public UpdateBlogPostCommandHandler(
IApplicationDbContext context,
IFileManager fileManager,
ILogger<UpdateBlogPostCommandHandler> logger)
{
_context = context;
_fileManager = fileManager;
_logger = logger;
}
public async Task<Unit> Handle(UpdateBlogPostCommand request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
post.Title = request.Title.Trim();
if (!string.IsNullOrWhiteSpace(request.Slug))
{
post.Slug = await BlogSlugHelper.EnsureUniquePostSlugAsync(
_context,
BlogSlugHelper.NormalizeOptional(request.Slug)!,
post.Id,
cancellationToken);
}
else if (string.IsNullOrWhiteSpace(post.Slug))
{
var slug = BlogSlugHelper.ResolveForCreate(null, post.Title);
post.Slug = await BlogSlugHelper.EnsureUniquePostSlugAsync(
_context, slug, post.Id, cancellationToken);
}
post.Summary = request.Summary?.Trim();
post.HtmlContent = request.HtmlContent;
post.FeaturedImagePath = request.FeaturedImagePath;
post.FeaturedImageThumbnailPath = request.FeaturedImageThumbnailPath;
post.IsFeatured = request.IsFeatured;
post.SortOrder = request.SortOrder;
// آپلود تصویر شاخص (اگر فایل جدید ارسال شده باشد)
if (request.ImageFileBytes is { Length: > 0 })
{
var result = await _fileManager.UploadImageAsync(
"Images/BlogPosts",
request.ImageFileBytes,
request.ImageFileMime ?? "image/jpeg",
request.ImageFileName,
cancellationToken);
post.FeaturedImagePath = result.Main.Path;
post.FeaturedImageThumbnailPath = result.Thumbnail.Path;
}
// بروزرسانی دسته‌بندی‌ها
var existingCategories = await _context.BlogPostCategories
.Where(x => x.BlogPostId == post.Id).ToListAsync(cancellationToken);
_context.BlogPostCategories.RemoveRange(existingCategories);
foreach (var categoryId in request.CategoryIds)
{
_context.BlogPostCategories.Add(new BlogPostCategory
{
BlogPostId = post.Id,
BlogCategoryId = categoryId
});
}
// بروزرسانی تگ‌ها
var existingTags = await _context.BlogPostTags
.Where(x => x.BlogPostId == post.Id).ToListAsync(cancellationToken);
_context.BlogPostTags.RemoveRange(existingTags);
foreach (var tagId in request.TagIds)
{
_context.BlogPostTags.Add(new BlogPostTag
{
BlogPostId = post.Id,
TagId = tagId
});
}
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation("Blog post updated. Id: {Id}, Title: {Title}", post.Id, post.Title);
return Unit.Value;
}
}
@@ -0,0 +1,23 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogPostCQ.Commands.UpdateBlogPost;
public class UpdateBlogPostCommandValidator : AbstractValidator<UpdateBlogPostCommand>
{
public UpdateBlogPostCommandValidator()
{
RuleFor(x => x.Id).GreaterThan(0).WithMessage("شناسه مقاله نامعتبر است");
RuleFor(x => x.Title)
.NotEmpty().WithMessage("عنوان مقاله الزامی است")
.MaximumLength(200).WithMessage("عنوان نمی‌تواند بیشتر از 200 کاراکتر باشد");
RuleFor(x => x.Slug)
.MaximumLength(200).WithMessage("نشانی نمی‌تواند بیشتر از 200 کاراکتر باشد")
.Matches(@"^[a-z0-9\-]+$").WithMessage("نشانی فقط می‌تواند شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد")
.When(x => !string.IsNullOrWhiteSpace(x.Slug));
RuleFor(x => x.HtmlContent)
.NotEmpty().WithMessage("محتوای مقاله الزامی است");
}
}
@@ -0,0 +1,16 @@
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetAllBlogPosts;
public class GetAllBlogPostsQuery : IRequest<GetAllBlogPostsResponseDto>
{
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
public string? SortBy { get; set; }
public string? SearchTerm { get; set; }
public BlogPostStatus? Status { get; set; }
public long? CategoryId { get; set; }
public bool? IsFeatured { get; set; }
}
@@ -0,0 +1,85 @@
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetAllBlogPosts;
public class GetAllBlogPostsQueryHandler : IRequestHandler<GetAllBlogPostsQuery, GetAllBlogPostsResponseDto>
{
private readonly IApplicationDbContext _context;
public GetAllBlogPostsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllBlogPostsResponseDto> Handle(GetAllBlogPostsQuery request, CancellationToken cancellationToken)
{
var query = _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Where(x => !x.IsDeleted);
// فیلترها
if (request.Status.HasValue)
query = query.Where(x => x.Status == request.Status.Value);
if (request.CategoryId.HasValue)
query = query.Where(x => x.BlogPostCategories.Any(c => c.BlogCategoryId == request.CategoryId.Value));
if (request.IsFeatured.HasValue)
query = query.Where(x => x.IsFeatured == request.IsFeatured.Value);
if (!string.IsNullOrEmpty(request.SearchTerm))
{
var term = request.SearchTerm.ToLower();
query = query.Where(x => x.Title.ToLower().Contains(term) || (x.Summary != null && x.Summary.ToLower().Contains(term)));
}
var totalCount = await query.CountAsync(cancellationToken);
// مرتب‌سازی
query = request.SortBy?.ToLower() switch
{
"title" => query.OrderBy(x => x.Title),
"viewcount" => query.OrderByDescending(x => x.ViewCount),
"publishedat" => query.OrderByDescending(x => x.PublishedAt),
_ => query.OrderByDescending(x => x.Created)
};
var posts = await query
.Skip((request.PageNumber - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new BlogPostListItemDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Summary = x.Summary,
FeaturedImageThumbnailPath = x.FeaturedImageThumbnailPath,
Status = (int)x.Status,
StatusName = GetBlogPostQueryHandler.GetStatusName(x.Status),
PublishedAt = x.PublishedAt,
ViewCount = x.ViewCount,
IsFeatured = x.IsFeatured,
Created = x.Created,
Categories = x.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList()
})
.ToListAsync(cancellationToken);
var metaData = new MetaData
{
TotalCount = totalCount,
PageSize = request.PageSize,
CurrentPage = request.PageNumber,
TotalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasNext = request.PageNumber < (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasPrevious = request.PageNumber > 1
};
return new GetAllBlogPostsResponseDto { MetaData = metaData, Models = posts };
}
}
@@ -0,0 +1,26 @@
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetAllBlogPosts;
public class GetAllBlogPostsResponseDto
{
public MetaData MetaData { get; set; } = new();
public List<BlogPostListItemDto> Models { get; set; } = new();
}
public class BlogPostListItemDto
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string? Summary { get; set; }
public string? FeaturedImageThumbnailPath { get; set; }
public int Status { get; set; }
public string StatusName { get; set; } = string.Empty;
public DateTime? PublishedAt { get; set; }
public int ViewCount { get; set; }
public bool IsFeatured { get; set; }
public DateTime Created { get; set; }
public List<BlogPostCategoryDto> Categories { get; set; } = new();
}
@@ -0,0 +1,39 @@
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
public class BlogPostDto
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string? Summary { get; set; }
public string HtmlContent { get; set; } = string.Empty;
public string? FeaturedImagePath { get; set; }
public string? FeaturedImageThumbnailPath { get; set; }
public BlogPostStatus Status { get; set; }
public string StatusName { get; set; } = string.Empty;
public DateTime? PublishedAt { get; set; }
public int ViewCount { get; set; }
public long AuthorUserId { get; set; }
public bool IsFeatured { get; set; }
public int SortOrder { get; set; }
public DateTime Created { get; set; }
public DateTime? LastModified { get; set; }
public List<BlogPostCategoryDto> Categories { get; set; } = new();
public List<BlogPostTagDto> Tags { get; set; } = new();
}
public class BlogPostCategoryDto
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
}
public class BlogPostTagDto
{
public long Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
public class GetBlogPostQuery : IRequest<BlogPostDto>
{
public long Id { get; set; }
}
@@ -0,0 +1,66 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
public class GetBlogPostQueryHandler : IRequestHandler<GetBlogPostQuery, BlogPostDto>
{
private readonly IApplicationDbContext _context;
public GetBlogPostQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<BlogPostDto> Handle(GetBlogPostQuery request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Include(x => x.BlogPostTags).ThenInclude(x => x.Tag)
.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
return new BlogPostDto
{
Id = post.Id,
Title = post.Title,
Slug = post.Slug,
Summary = post.Summary,
HtmlContent = post.HtmlContent,
FeaturedImagePath = post.FeaturedImagePath,
FeaturedImageThumbnailPath = post.FeaturedImageThumbnailPath,
Status = post.Status,
StatusName = GetStatusName(post.Status),
PublishedAt = post.PublishedAt,
ViewCount = post.ViewCount,
AuthorUserId = post.AuthorUserId,
IsFeatured = post.IsFeatured,
SortOrder = post.SortOrder,
Created = post.Created,
LastModified = post.LastModified,
Categories = post.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList(),
Tags = post.BlogPostTags.Select(t => new BlogPostTagDto
{
Id = t.Tag.Id,
Title = t.Tag.Title,
Name = t.Tag.Name
}).ToList()
};
}
public static string GetStatusName(BlogPostStatus status) => status switch
{
BlogPostStatus.Draft => "پیش‌نویس",
BlogPostStatus.Published => "منتشرشده",
BlogPostStatus.Scheduled => "زمانبندی‌شده",
BlogPostStatus.Archived => "آرشیو",
_ => "نامشخص"
};
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPostBySlug;
public class GetBlogPostBySlugQuery : IRequest<GetBlogPost.BlogPostDto>
{
public string Slug { get; set; } = string.Empty;
}
@@ -0,0 +1,58 @@
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPostBySlug;
public class GetBlogPostBySlugQueryHandler : IRequestHandler<GetBlogPostBySlugQuery, BlogPostDto>
{
private readonly IApplicationDbContext _context;
public GetBlogPostBySlugQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<BlogPostDto> Handle(GetBlogPostBySlugQuery request, CancellationToken cancellationToken)
{
var post = await _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Include(x => x.BlogPostTags).ThenInclude(x => x.Tag)
.FirstOrDefaultAsync(x => x.Slug == request.Slug && !x.IsDeleted, cancellationToken)
?? throw new KeyNotFoundException($"مقاله با نشانی '{request.Slug}' یافت نشد");
return new BlogPostDto
{
Id = post.Id,
Title = post.Title,
Slug = post.Slug,
Summary = post.Summary,
HtmlContent = post.HtmlContent,
FeaturedImagePath = post.FeaturedImagePath,
FeaturedImageThumbnailPath = post.FeaturedImageThumbnailPath,
Status = post.Status,
StatusName = GetBlogPostQueryHandler.GetStatusName(post.Status),
PublishedAt = post.PublishedAt,
ViewCount = post.ViewCount,
AuthorUserId = post.AuthorUserId,
IsFeatured = post.IsFeatured,
SortOrder = post.SortOrder,
Created = post.Created,
LastModified = post.LastModified,
Categories = post.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList(),
Tags = post.BlogPostTags.Select(t => new BlogPostTagDto
{
Id = t.Tag.Id,
Title = t.Tag.Title,
Name = t.Tag.Name
}).ToList()
};
}
}
@@ -0,0 +1,55 @@
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetFeaturedBlogPosts;
public class GetFeaturedBlogPostsQuery : IRequest<List<GetAllBlogPosts.BlogPostListItemDto>>
{
public int Count { get; set; } = 5;
}
public class GetFeaturedBlogPostsQueryHandler : IRequestHandler<GetFeaturedBlogPostsQuery, List<GetAllBlogPosts.BlogPostListItemDto>>
{
private readonly IApplicationDbContext _context;
public GetFeaturedBlogPostsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<GetAllBlogPosts.BlogPostListItemDto>> Handle(GetFeaturedBlogPostsQuery request, CancellationToken cancellationToken)
{
var posts = await _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Where(x => !x.IsDeleted && x.Status == BlogPostStatus.Published && x.IsFeatured)
.OrderBy(x => x.SortOrder)
.ThenByDescending(x => x.PublishedAt)
.Take(request.Count)
.Select(x => new GetAllBlogPosts.BlogPostListItemDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Summary = x.Summary,
FeaturedImageThumbnailPath = x.FeaturedImageThumbnailPath,
Status = (int)x.Status,
StatusName = GetBlogPostQueryHandler.GetStatusName(x.Status),
PublishedAt = x.PublishedAt,
ViewCount = x.ViewCount,
IsFeatured = x.IsFeatured,
Created = x.Created,
Categories = x.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList()
})
.ToListAsync(cancellationToken);
return posts;
}
}
@@ -0,0 +1,81 @@
using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetPublishedBlogPosts;
public class GetPublishedBlogPostsQuery : IRequest<GetAllBlogPosts.GetAllBlogPostsResponseDto>
{
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
public string? SearchTerm { get; set; }
public long? CategoryId { get; set; }
}
public class GetPublishedBlogPostsQueryHandler : IRequestHandler<GetPublishedBlogPostsQuery, GetAllBlogPosts.GetAllBlogPostsResponseDto>
{
private readonly IApplicationDbContext _context;
public GetPublishedBlogPostsQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllBlogPosts.GetAllBlogPostsResponseDto> Handle(GetPublishedBlogPostsQuery request, CancellationToken cancellationToken)
{
var query = _context.BlogPosts
.Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
.Where(x => !x.IsDeleted && x.Status == BlogPostStatus.Published);
if (request.CategoryId.HasValue)
query = query.Where(x => x.BlogPostCategories.Any(c => c.BlogCategoryId == request.CategoryId.Value));
if (!string.IsNullOrEmpty(request.SearchTerm))
{
var term = request.SearchTerm.ToLower();
query = query.Where(x => x.Title.ToLower().Contains(term) || (x.Summary != null && x.Summary.ToLower().Contains(term)));
}
var totalCount = await query.CountAsync(cancellationToken);
var posts = await query
.OrderByDescending(x => x.PublishedAt)
.Skip((request.PageNumber - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new GetAllBlogPosts.BlogPostListItemDto
{
Id = x.Id,
Title = x.Title,
Slug = x.Slug,
Summary = x.Summary,
FeaturedImageThumbnailPath = x.FeaturedImageThumbnailPath,
Status = (int)x.Status,
StatusName = GetBlogPostQueryHandler.GetStatusName(x.Status),
PublishedAt = x.PublishedAt,
ViewCount = x.ViewCount,
IsFeatured = x.IsFeatured,
Created = x.Created,
Categories = x.BlogPostCategories.Select(c => new BlogPostCategoryDto
{
Id = c.BlogCategory.Id,
Title = c.BlogCategory.Title,
Slug = c.BlogCategory.Slug
}).ToList()
})
.ToListAsync(cancellationToken);
var metaData = new MetaData
{
TotalCount = totalCount,
PageSize = request.PageSize,
CurrentPage = request.PageNumber,
TotalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasNext = request.PageNumber < (int)Math.Ceiling(totalCount / (double)request.PageSize),
HasPrevious = request.PageNumber > 1
};
return new GetAllBlogPosts.GetAllBlogPostsResponseDto { MetaData = metaData, Models = posts };
}
}
@@ -0,0 +1,13 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.AddBlogPostImage;
public class AddBlogPostImageCommand : IRequest<long>
{
public long BlogPostId { get; set; }
public string ImagePath { get; set; } = default!;
public string ThumbnailPath { get; set; } = default!;
public string? AltText { get; set; }
public string? Caption { get; set; }
public int SortOrder { get; set; }
}
@@ -0,0 +1,39 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.AddBlogPostImage;
public class AddBlogPostImageCommandHandler : IRequestHandler<AddBlogPostImageCommand, long>
{
private readonly IApplicationDbContext _context;
public AddBlogPostImageCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<long> Handle(AddBlogPostImageCommand request, CancellationToken cancellationToken)
{
var blogPost = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.BlogPostId && !x.IsDeleted, cancellationToken);
if (blogPost == null)
throw new NotFoundException(nameof(BlogPost), request.BlogPostId);
var entity = new BlogPostImage
{
BlogPostId = request.BlogPostId,
ImagePath = request.ImagePath,
ThumbnailPath = request.ThumbnailPath,
AltText = request.AltText,
Caption = request.Caption,
SortOrder = request.SortOrder
};
_context.BlogPostImages.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return entity.Id;
}
}
@@ -0,0 +1,21 @@
using FluentValidation;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.AddBlogPostImage;
public class AddBlogPostImageCommandValidator : AbstractValidator<AddBlogPostImageCommand>
{
public AddBlogPostImageCommandValidator()
{
RuleFor(x => x.BlogPostId)
.GreaterThan(0).WithMessage("شناسه پست نامعتبر است");
RuleFor(x => x.ImagePath)
.NotEmpty().WithMessage("مسیر تصویر الزامی است");
RuleFor(x => x.AltText)
.MaximumLength(500).WithMessage("متن جایگزین حداکثر ۵۰۰ کاراکتر");
RuleFor(x => x.Caption)
.MaximumLength(1000).WithMessage("عنوان تصویر حداکثر ۱۰۰۰ کاراکتر");
}
}
@@ -0,0 +1,8 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.DeleteBlogPostImage;
public class DeleteBlogPostImageCommand : IRequest<Unit>
{
public long Id { get; set; }
}
@@ -0,0 +1,29 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.DeleteBlogPostImage;
public class DeleteBlogPostImageCommandHandler : IRequestHandler<DeleteBlogPostImageCommand, Unit>
{
private readonly IApplicationDbContext _context;
public DeleteBlogPostImageCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(DeleteBlogPostImageCommand request, CancellationToken cancellationToken)
{
var entity = await _context.BlogPostImages.FindAsync(new object[] { request.Id }, cancellationToken);
if (entity == null || entity.IsDeleted)
throw new NotFoundException(nameof(BlogPostImage), request.Id);
entity.IsDeleted = true;
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,14 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.ReorderBlogPostImages;
public class ReorderBlogPostImagesCommand : IRequest<Unit>
{
public List<ImageSortItem> Items { get; set; } = new();
}
public class ImageSortItem
{
public long Id { get; set; }
public int SortOrder { get; set; }
}
@@ -0,0 +1,34 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.ReorderBlogPostImages;
public class ReorderBlogPostImagesCommandHandler : IRequestHandler<ReorderBlogPostImagesCommand, Unit>
{
private readonly IApplicationDbContext _context;
public ReorderBlogPostImagesCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Unit> Handle(ReorderBlogPostImagesCommand request, CancellationToken cancellationToken)
{
var ids = request.Items.Select(x => x.Id).ToList();
var images = await _context.BlogPostImages
.Where(x => ids.Contains(x.Id) && !x.IsDeleted)
.ToListAsync(cancellationToken);
foreach (var item in request.Items)
{
var image = images.FirstOrDefault(x => x.Id == item.Id);
if (image != null)
image.SortOrder = item.SortOrder;
}
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -0,0 +1,19 @@
using MediatR;
namespace CMSMicroservice.Application.BlogPostImageCQ.Queries.GetBlogPostImages;
public class GetBlogPostImagesQuery : IRequest<List<BlogPostImageDto>>
{
public long BlogPostId { get; set; }
}
public class BlogPostImageDto
{
public long Id { get; set; }
public long BlogPostId { get; set; }
public string ImagePath { get; set; } = default!;
public string? ThumbnailPath { get; set; }
public string? AltText { get; set; }
public string? Caption { get; set; }
public int SortOrder { get; set; }
}
@@ -0,0 +1,35 @@
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CMSMicroservice.Application.BlogPostImageCQ.Queries.GetBlogPostImages;
public class GetBlogPostImagesQueryHandler : IRequestHandler<GetBlogPostImagesQuery, List<BlogPostImageDto>>
{
private readonly IApplicationDbContext _context;
public GetBlogPostImagesQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<List<BlogPostImageDto>> Handle(GetBlogPostImagesQuery request, CancellationToken cancellationToken)
{
var images = await _context.BlogPostImages
.Where(x => x.BlogPostId == request.BlogPostId && !x.IsDeleted)
.OrderBy(x => x.SortOrder)
.Select(x => new BlogPostImageDto
{
Id = x.Id,
BlogPostId = x.BlogPostId,
ImagePath = x.ImagePath,
ThumbnailPath = x.ThumbnailPath,
AltText = x.AltText,
Caption = x.Caption,
SortOrder = x.SortOrder
})
.ToListAsync(cancellationToken);
return images;
}
}
@@ -7,10 +7,13 @@
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.2.2" />
<PackageReference Include="Mapster" Version="7.4.0" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.11" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.11" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.4.0" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.6.10" />
@@ -31,7 +31,18 @@ public class GetAllCategoryByFilterQueryHandler : IRequestHandler<GetAllCategory
{
MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
.ProjectToType<GetAllCategoryByFilterResponseModel>().ToListAsync(cancellationToken)
.Select(x => new GetAllCategoryByFilterResponseModel
{
Id = x.Id,
Name = x.Name,
Title = x.Title,
Description = x.Description,
ImagePath = x.ImagePath,
ParentId = x.ParentId,
IsActive = x.IsActive,
SortOrder = x.SortOrder,
ProductCount = x.ProductCategories.Count
}).ToListAsync(cancellationToken)
};
}
}
@@ -24,4 +24,6 @@ public class GetAllCategoryByFilterResponseDto
public bool IsActive { get; set; }
//ترتیب نمایش
public int SortOrder { get; set; }
//تعداد محصولات
public int ProductCount { get; set; }
}
@@ -1,5 +1,10 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Common;
using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Entities.Club;
using CMSMicroservice.Domain.Entities.Commission;
using CMSMicroservice.Domain.Entities.History;
using CMSMicroservice.Domain.Enums;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
@@ -12,6 +17,8 @@ namespace CMSMicroservice.Application.ClubMembershipCQ.Commands.AcceptClubMember
/// 1. کد OTP را تایید می‌کند
/// 2. قرارداد را در جدول UserContract ثبت می‌کند
/// 3. باشگاه مشتری را فعال می‌کند (IsActive = true)
/// 4. مبلغ را به Pool هفته جاری اضافه می‌کند
/// 5. ویژگی‌های باشگاه را به کاربر اعطا می‌کند
/// </summary>
public class AcceptClubMembershipContractCommandHandler
: IRequestHandler<AcceptClubMembershipContractCommand, AcceptClubMembershipContractResponseDto>
@@ -19,6 +26,8 @@ public class AcceptClubMembershipContractCommandHandler
private readonly IApplicationDbContext _context;
private readonly IConfiguration _cfg;
private readonly IHashService _hashService;
private readonly ICurrentUserService _currentUser;
private readonly IWeekDefinitionRepository _weekRepository;
private readonly ILogger<AcceptClubMembershipContractCommandHandler> _logger;
private const int MaxAttempts = 5;
@@ -28,11 +37,15 @@ public class AcceptClubMembershipContractCommandHandler
IApplicationDbContext context,
IConfiguration cfg,
IHashService hashService,
ICurrentUserService currentUser,
IWeekDefinitionRepository weekRepository,
ILogger<AcceptClubMembershipContractCommandHandler> logger)
{
_context = context;
_cfg = cfg;
_hashService = hashService;
_currentUser = currentUser;
_weekRepository = weekRepository;
_logger = logger;
}
@@ -40,20 +53,28 @@ public class AcceptClubMembershipContractCommandHandler
AcceptClubMembershipContractCommand request,
CancellationToken cancellationToken)
{
// خواندن UserId از JWT (امن‌تر از دریافت از کلاینت)
if (!long.TryParse(_currentUser.UserId, out var userId))
return new AcceptClubMembershipContractResponseDto
{
Success = false,
Message = "کاربر احراز هویت نشده است"
};
_logger.LogInformation(
"Processing club membership contract for UserId: {UserId}",
request.UserId
userId
);
// 1. دریافت کاربر
var user = await _context.Users
.Include(u => u.ClubMembership)
.FirstOrDefaultAsync(u => u.Id == request.UserId, cancellationToken);
.FirstOrDefaultAsync(u => u.Id == userId, cancellationToken);
if (user == null)
{
_logger.LogWarning("User not found: {UserId}", request.UserId);
throw new NotFoundException(nameof(User), request.UserId);
_logger.LogWarning("User not found: {UserId}", userId);
throw new NotFoundException(nameof(User), userId);
}
// 2. بررسی خرید پکیج
@@ -114,33 +135,238 @@ public class AcceptClubMembershipContractCommandHandler
};
await _context.UserContracts.AddAsync(userContract, cancellationToken);
// 6. فعال‌سازی باشگاه مشتریان
if (user.ClubMembership == null)
// 6. بارگذاری پکیج موثر برای امضای قرارداد
// اولویت:
// 1) پکیج Cycle جاری (مسیر صحیح برای پرداخت دستی)
// 2) آخرین خرید پکیج
// 3) پکیج پایه
var currentCyclePackageId = await _context.ClubMembershipCycles
.Where(c => c.UserId == userId && c.IsCurrentCycle)
.OrderByDescending(c => c.CycleNumber)
.Select(c => (long?)c.PackageId)
.FirstOrDefaultAsync(cancellationToken);
var latestPurchase = await _context.UserPackagePurchases
.Where(p => p.UserId == userId)
.OrderByDescending(p => p.PurchasedAt)
.FirstOrDefaultAsync(cancellationToken);
Package? package = null;
if (currentCyclePackageId.HasValue && currentCyclePackageId.Value > 0)
{
user.ClubMembership = new Domain.Entities.Club.ClubMembership
package = await _context.Packages
.FirstOrDefaultAsync(p => p.Id == currentCyclePackageId.Value && !p.IsDeleted, cancellationToken);
if (package != null)
{
_logger.LogInformation(
"AcceptContract package source: CurrentCycle (UserId={UserId}, PackageId={PackageId})",
userId,
package.Id);
}
}
if (package == null && latestPurchase != null)
{
package = await _context.Packages
.FirstOrDefaultAsync(p => p.Id == latestPurchase.PackageId && !p.IsDeleted, cancellationToken);
if (package != null)
{
_logger.LogInformation(
"AcceptContract package source: LatestPurchase (UserId={UserId}, PackageId={PackageId})",
userId,
package.Id);
}
}
if (package == null)
{
package = await _context.Packages
.FirstOrDefaultAsync(p => p.IsBasePackage && !p.IsDeleted, cancellationToken);
if (package != null)
{
_logger.LogInformation(
"AcceptContract package source: BasePackage (UserId={UserId}, PackageId={PackageId})",
userId,
package.Id);
}
}
if (package == null)
throw new NotFoundException("پکیج یافت نشد");
long giftValue = package.ActivationFee;
long activationFeeValue = package.ActivationFee;
_logger.LogInformation(
"Using Package {PackageId} ({PackageName}): GiftValue={GiftValue}, ActivationFee={ActivationFee}",
package.Id, package.Title, giftValue, activationFeeValue
);
// 7. فعال‌سازی باشگاه مشتریان
ClubMembership clubMembership;
bool isNewMembership = user.ClubMembership == null;
var activationDate = DateTime.Now;
if (isNewMembership)
{
clubMembership = new ClubMembership
{
UserId = user.Id,
IsActive = true,
ActivatedAt = DateTime.Now,
InitialContribution = 56_000_000,
GiftValue = 25_200_000,
ActivatedAt = activationDate,
FirstActivationDate = activationDate,
FirstPackageId = package.Id,
LastActivationDate = activationDate,
LastPackageId = package.Id,
InitialContribution = activationFeeValue,
GiftValue = giftValue,
TotalEarned = 0,
PurchaseMethod = user.PackagePurchaseMethod
};
await _context.ClubMemberships.AddAsync(user.ClubMembership, cancellationToken);
await _context.ClubMemberships.AddAsync(clubMembership, cancellationToken);
_logger.LogInformation(
"Created new club membership for UserId {UserId} via {Method}, GiftValue: {GiftValue}",
user.Id,
user.PackagePurchaseMethod,
giftValue
);
}
else
{
user.ClubMembership.IsActive = true;
user.ClubMembership.ActivatedAt = DateTime.Now;
_context.ClubMemberships.Update(user.ClubMembership);
clubMembership = user.ClubMembership!;
clubMembership.IsActive = true;
clubMembership.ActivatedAt = activationDate;
clubMembership.LastActivationDate = activationDate;
clubMembership.LastPackageId = package.Id;
clubMembership.PurchaseMethod = user.PackagePurchaseMethod;
_context.ClubMemberships.Update(clubMembership);
_logger.LogInformation(
"Reactivated club membership for UserId {UserId}",
user.Id
);
}
await _context.SaveChangesAsync(cancellationToken);
// 8. ثبت تاریخچه
var history = new ClubMembershipHistory
{
ClubMembershipId = clubMembership.Id,
UserId = clubMembership.UserId,
OldIsActive = !isNewMembership && !user.ClubMembership!.IsActive,
NewIsActive = true,
Action = ClubMembershipAction.Activated,
Reason = isNewMembership
? $"Initial activation via contract signing - {user.PackagePurchaseMethod}"
: $"Reactivated via contract signing - {user.PackagePurchaseMethod}",
PerformedBy = _currentUser.GetPerformedBy()
};
_context.ClubMembershipHistories.Add(history);
await _context.SaveChangesAsync(cancellationToken);
// 8.5. آپدیت PackagePurchasedAt سایکل جاری به زمان امضای قرارداد
// دلیل: Pool در همین لحظه شارژ می‌شود — Validation باید به همین هفته اشاره کند
// سناریوی cross-week: کاربر هفته ۱۸ پکیج خریده، هفته ۱۹ قرارداد امضا کرده
// بدون این Fix: Cycle.PackagePurchasedAt = هفته ۱۸ ولی Pool هفته ۱۹ → اختلاف
// با این Fix: Cycle.PackagePurchasedAt = هفته ۱۹ = Pool هفته ۱۹ → درست
var currentCycle = await _context.ClubMembershipCycles
.FirstOrDefaultAsync(c => c.UserId == userId && c.IsCurrentCycle, cancellationToken);
if (currentCycle != null)
{
currentCycle.PackagePurchasedAt = activationDate;
_context.ClubMembershipCycles.Update(currentCycle);
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Updated Cycle #{CycleNumber} PackagePurchasedAt to contract-signing time for UserId {UserId}",
currentCycle.CycleNumber,
userId
);
}
else
{
// در صورتی که Cycle وجود ندارد (legacy یا مسیر مستقیم AcceptContract)
// Cycle را همین‌جا بساز تا Validation درست کار کند
_logger.LogWarning(
"No IsCurrentCycle found for UserId {UserId} at AcceptContract — creating Cycle now",
userId
);
var maxCycleNumber = await _context.ClubMembershipCycles
.Where(c => c.ClubMembershipId == clubMembership.Id)
.MaxAsync(c => (int?)c.CycleNumber, cancellationToken) ?? 0;
var newCycle = new ClubMembershipCycle
{
UserId = userId,
ClubMembershipId = clubMembership.Id,
CycleNumber = maxCycleNumber + 1,
PackagePurchasedAt = activationDate,
PurchaseMethod = user.PackagePurchaseMethod,
PackageAmount = package.Price,
PackageId = package.Id,
IsCurrentCycle = true
};
_context.ClubMembershipCycles.Add(newCycle);
await _context.SaveChangesAsync(cancellationToken);
}
var currentWeekDefinitionId = GetCurrentWeekDefinitionId();
var weeklyPool = await _context.WeeklyCommissionPools
.FirstOrDefaultAsync(p => p.WeekDefinitionId == currentWeekDefinitionId && p.PackageId == package.Id, cancellationToken);
if (weeklyPool == null)
{
weeklyPool = new WeeklyCommissionPool
{
WeekDefinitionId = currentWeekDefinitionId,
PackageId = package.Id,
TotalPoolAmount = activationFeeValue,
TotalBalances = 0,
ValuePerBalance = 0,
IsCalculated = false,
CalculatedAt = null
};
await _context.WeeklyCommissionPools.AddAsync(weeklyPool, cancellationToken);
_logger.LogInformation(
"Created new WeeklyCommissionPool for WeekDefinitionId={WeekDefinitionId} with initial amount: {Amount}",
currentWeekDefinitionId,
activationFeeValue
);
}
else
{
weeklyPool.TotalPoolAmount += activationFeeValue;
_context.WeeklyCommissionPools.Update(weeklyPool);
_logger.LogInformation(
"Added {Amount} to existing WeeklyCommissionPool for WeekDefinitionId={WeekDefinitionId}. New total: {NewTotal}",
activationFeeValue,
currentWeekDefinitionId,
weeklyPool.TotalPoolAmount
);
}
await _context.SaveChangesAsync(cancellationToken);
// 10. اعمال ویژگی‌های پکیج — DIFF/تفاضل (Q20)
await ApplyFeatureDiffAsync(user.Id, clubMembership.Id, package.Id, isNewMembership, activationDate, cancellationToken);
_logger.LogInformation(
"Club membership contract accepted and activated for UserId: {UserId}, ContractId: {ContractId}",
"Club membership contract accepted and activated for UserId: {UserId}, ContractId: {ContractId}, MembershipId: {MembershipId}",
request.UserId,
userContract.Id
userContract.Id,
clubMembership.Id
);
return new AcceptClubMembershipContractResponseDto
@@ -151,6 +377,74 @@ public class AcceptClubMembershipContractCommandHandler
};
}
/// <summary>
/// دریافت شناسه تعریف هفته جاری
/// </summary>
private long GetCurrentWeekDefinitionId()
{
var week = _weekRepository.GetCurrentWeek();
if (week == null)
{
throw new InvalidOperationException("هفته جاری در سیستم تعریف نشده است");
}
return week.Id;
}
private async Task ApplyFeatureDiffAsync(
long userId, long membershipId, long packageId,
bool isNewMembership, DateTime activationDate,
CancellationToken cancellationToken)
{
var newFeatureIds = await _context.PackageFeatures
.Where(pf => pf.PackageId == packageId && pf.IsIncluded && !pf.IsDeleted)
.Select(pf => pf.ClubFeatureId)
.ToListAsync(cancellationToken);
if (!newFeatureIds.Any())
{
_logger.LogWarning("No PackageFeatures for PackageId {PackageId}", packageId);
return;
}
var currentFeatures = await _context.UserClubFeatures
.Where(ucf => ucf.UserId == userId && ucf.IsActive)
.ToListAsync(cancellationToken);
var currentFeatureIds = currentFeatures.Select(f => f.ClubFeatureId).ToHashSet();
var toAdd = newFeatureIds.Where(id => !currentFeatureIds.Contains(id)).ToList();
var toRemove = currentFeatures.Where(f => !newFeatureIds.Contains(f.ClubFeatureId)).ToList();
foreach (var feature in toRemove)
{
feature.IsActive = false;
feature.Notes = $"حذف شده بابت تغییر پکیج (PackageId: {packageId})";
}
if (toAdd.Any())
{
var newUserFeatures = toAdd.Select(featureId => new UserClubFeature
{
UserId = userId,
ClubMembershipId = membershipId,
ClubFeatureId = featureId,
GrantedAt = activationDate,
IsActive = true,
Notes = isNewMembership
? "اعطا شده هنگام امضای قرارداد"
: $"اضافه شده بابت خرید مجدد پکیج (PackageId: {packageId})"
}).ToList();
_context.UserClubFeatures.AddRange(newUserFeatures);
}
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Feature DIFF applied for UserId={UserId}: Added={Added}, Removed={Removed}, Kept={Kept}",
userId, toAdd.Count, toRemove.Count,
currentFeatureIds.Count - toRemove.Count);
}
private async Task<(bool Success, string Message)> VerifyOtpAsync(
string mobile,
string code,
@@ -4,10 +4,6 @@ public class AcceptClubMembershipContractCommandValidator : AbstractValidator<Ac
{
public AcceptClubMembershipContractCommandValidator()
{
RuleFor(x => x.UserId)
.GreaterThan(0)
.WithMessage("شناسه کاربر الزامی است");
RuleFor(x => x.OtpCode)
.NotEmpty()
.WithMessage("کد تایید الزامی است")
@@ -12,4 +12,15 @@ public record ActivateClubMembershipCommand : IRequest<bool>
/// شناسه کاربر
/// </summary>
public long UserId { get; init; }
/// <summary>
/// فعال‌سازی اجباری توسط ادمین — بدون بررسی سفارش و کیف‌پول
/// </summary>
public bool ForceActivation { get; init; }
/// <summary>
/// شناسه پکیج — فقط در ForceActivation استفاده می‌شود.
/// اگر 0 باشد، پکیج پایه (IsBasePackage) استفاده می‌شود.
/// </summary>
public long PackageId { get; init; }
}
@@ -1,6 +1,8 @@
using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Helpers;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Common;
using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Entities.Club;
using CMSMicroservice.Domain.Entities.Commission;
@@ -53,133 +55,149 @@ public class ActivateClubMembershipCommandHandler : IRequestHandler<ActivateClub
throw new NotFoundException(nameof(User), request.UserId);
}
// 2. بررسی اینکه پکیج خریده باشد
if (user.PackagePurchaseMethod == PackagePurchaseMethod.None)
// متغیر پکیج — در هر دو مسیر (عادی و Force) مقداردهی می‌شود
Package package;
// 2-5: بررسی‌های مالی — در حالت ForceActivation (ادمین) رد می‌شود
if (!request.ForceActivation)
{
_logger.LogWarning(
"User {UserId} has not purchased golden package yet",
// 2. بررسی اینکه پکیج خریده باشد
if (user.PackagePurchaseMethod == PackagePurchaseMethod.None)
{
_logger.LogWarning(
"User {UserId} has not purchased any package yet",
request.UserId
);
throw new BadRequestException(
"برای فعالسازی باشگاه مشتریان ابتدا باید یک پکیج خریداری کنید"
);
}
// 3. بررسی موجودی کیف پول
var wallet = await _context.UserWallets
.FirstOrDefaultAsync(w => w.UserId == user.Id, cancellationToken);
if (wallet == null)
{
_logger.LogError("Wallet not found for UserId: {UserId}", request.UserId);
throw new NotFoundException("کیف پول کاربر یافت نشد");
}
// NOTE: balance check uses package.Price — loaded after finding order (step 4)
// Moved to after package loading
// 3.5. بررسی وضعیت کیف‌پول جادویی — اگر در حالت Magic است، فعالسازی مجاز نیست
if (wallet.WalletMode == WalletMode.Magic)
{
_logger.LogWarning(
"User {UserId} cannot activate club while in Magic wallet mode",
request.UserId
);
throw new BadRequestException(
"ابتدا باید چرخه کیف‌پول جادویی تکمیل شود"
);
}
// 4. پیدا کردن آخرین خرید موفق پکیج
var packagePurchase = await _context.UserPackagePurchases
.Include(p => p.Transaction)
.Where(p =>
p.UserId == user.Id &&
p.Transaction != null &&
p.Transaction.PaymentStatus == PaymentStatus.Success)
.OrderByDescending(p => p.Created)
.FirstOrDefaultAsync(cancellationToken);
if (packagePurchase == null)
{
_logger.LogWarning(
"No successful package purchase found for UserId: {UserId}",
request.UserId
);
throw new NotFoundException("سفارش پکیج یافت نشد");
}
// 5. بررسی Transaction
if (packagePurchase.Transaction == null)
{
_logger.LogError(
"Transaction not found for PurchaseId: {PurchaseId}",
packagePurchase.Id
);
throw new NotFoundException("تراکنش مربوط به سفارش یافت نشد");
}
var transaction = packagePurchase.Transaction;
if (transaction.Type != TransactionType.Buy &&
transaction.Type != TransactionType.DepositIpg &&
transaction.Type != TransactionType.DepositExternal1)
{
_logger.LogWarning(
"Invalid transaction type for PurchaseId {PurchaseId}: {Type}",
packagePurchase.Id,
transaction.Type
);
throw new BadRequestException(
"تراکنش معتبر برای فعالسازی باشگاه یافت نشد"
);
}
// 5.5. بارگذاری پکیج از خرید
package = await _context.Packages
.FirstOrDefaultAsync(p => p.Id == packagePurchase.PackageId && !p.IsDeleted, cancellationToken)
?? throw new NotFoundException("پکیج یافت نشد");
// بررسی موجودی با مبلغ پکیج واقعی
if (wallet.Balance < package.Price)
{
throw new BadRequestException(
$"برای فعالسازی باشگاه مشتریان باید حداقل {package.Price:N0} تومان موجودی اصلی داشته باشید"
);
}
}
else
{
_logger.LogInformation(
"Force activation by admin for UserId: {UserId} — skipping order/wallet validation",
request.UserId
);
throw new BadRequestException(
"برای فعالسازی باشگاه مشتریان ابتدا باید پکیج طلایی خریداری کنید"
);
}
// 3. بررسی موجودی کیف پول
var wallet = await _context.UserWallets
.FirstOrDefaultAsync(w => w.UserId == user.Id, cancellationToken);
// در فعال‌سازی اجباری ادمین، اگر روش خرید تنظیم نشده، دستی در نظر بگیر
if (user.PackagePurchaseMethod == PackagePurchaseMethod.None)
{
user.PackagePurchaseMethod = PackagePurchaseMethod.Manual;
_context.Users.Update(user);
await _context.SaveChangesAsync(cancellationToken);
}
if (wallet == null)
{
_logger.LogError("Wallet not found for UserId: {UserId}", request.UserId);
throw new NotFoundException("کیف پول کاربر یافت نشد");
}
if (wallet.Balance < 56_000_000)
{
_logger.LogWarning(
"User {UserId} has insufficient balance: {Balance}",
request.UserId,
wallet.Balance
);
throw new BadRequestException(
"برای فعالسازی باشگاه مشتریان باید حداقل 56 میلیون تومان موجودی اصلی داشته باشید"
);
}
// 4. پیدا کردن UserOrder با PackageId
var packageOrder = await _context.UserOrders
.Include(o => o.Transaction)
.Where(o =>
o.UserId == user.Id &&
o.PackageId != null &&
o.PaymentStatus == PaymentStatus.Success)
.OrderByDescending(o => o.Created)
.FirstOrDefaultAsync(cancellationToken);
if (packageOrder == null)
{
_logger.LogWarning(
"No successful package order found for UserId: {UserId}",
request.UserId
);
throw new NotFoundException("سفارش پکیج طلایی یافت نشد");
}
// 5. بررسی Transaction
if (packageOrder.Transaction == null)
{
_logger.LogError(
"Transaction not found for OrderId: {OrderId}",
packageOrder.Id
);
throw new NotFoundException("تراکنش مربوط به سفارش یافت نشد");
}
var transaction = packageOrder.Transaction;
if (transaction.Type != TransactionType.DepositIpg &&
transaction.Type != TransactionType.DepositExternal1)
{
_logger.LogWarning(
"Invalid transaction type for OrderId {OrderId}: {Type}",
packageOrder.Id,
transaction.Type
);
throw new BadRequestException(
"تراکنش معتبر برای فعالسازی باشگاه یافت نشد"
);
// بارگذاری پکیج — اگر PackageId مشخص شده همان را لود کن، وگرنه پکیج پایه
if (request.PackageId > 0)
{
package = await _context.Packages
.FirstOrDefaultAsync(p => p.Id == request.PackageId && !p.IsDeleted, cancellationToken)
?? throw new NotFoundException($"پکیج {request.PackageId} یافت نشد");
}
else
{
package = await _context.Packages
.FirstOrDefaultAsync(p => p.IsBasePackage && !p.IsDeleted, cancellationToken)
?? throw new NotFoundException("پکیج پایه یافت نشد");
}
}
// 6. بررسی عضویت فعلی
var existingMembership = await _context.ClubMemberships
.FirstOrDefaultAsync(c => c.UserId == user.Id, cancellationToken);
// 6.1. دریافت مبلغ هدیه از تنظیمات
var giftValueConfig = await _context.SystemConfigurations
.FirstOrDefaultAsync(
c => c.Key == "Club.MembershipGiftValue" && c.IsActive,
cancellationToken
);
// 6.1. دریافت مبلغ هدیه و هزینه فعالسازی از پکیج
long giftValue = package.ActivationFee;
long activationFeeValue = package.ActivationFee;
var activationFeeConfig = await _context.SystemConfigurations
.FirstOrDefaultAsync(
c => c.Key == "Club.ActivationFee" && c.IsActive,
cancellationToken
);
long giftValue = 28_000_000; // مقدار پیش‌فرض
if (giftValueConfig != null && long.TryParse(giftValueConfig.Value, out var configValue))
{
giftValue = configValue;
_logger.LogInformation(
"Using Club.MembershipGiftValue from configuration: {GiftValue}",
giftValue
);
}
else
{
_logger.LogWarning(
"Club.MembershipGiftValue not found in configuration, using default: {GiftValue}",
giftValue
);
}
long activationFeeValue = 25_200_000; // مقدار پیش‌فرض
if (activationFeeConfig != null && long.TryParse(activationFeeConfig.Value, out var activationFeeConfigValue))
{
activationFeeValue = activationFeeConfigValue;
_logger.LogInformation(
"Using Club.ActivationFee from configuration: {activationFeeValue}",
activationFeeValue
);
}
else
{
_logger.LogWarning(
"Club.ActivationFee not found in configuration, using default: {activationFeeValue}",
activationFeeValue
);
}
_logger.LogInformation(
"Using Package {PackageId} ({PackageName}): GiftValue={GiftValue}, ActivationFee={ActivationFee}, Price={Price}",
package.Id, package.Title, giftValue, activationFeeValue, package.Price
);
ClubMembership entity;
bool isNewMembership = existingMembership == null;
@@ -187,14 +205,18 @@ public class ActivateClubMembershipCommandHandler : IRequestHandler<ActivateClub
if (isNewMembership)
{
// ایجاد عضویت جدید
// ایجاد عضویت جدید — IsActive = false تا زمان امضای قرارداد باشگاه
entity = new ClubMembership
{
UserId = user.Id,
IsActive = true,
IsActive = false,
ActivatedAt = activationDate,
InitialContribution =activationFeeValue,
GiftValue = giftValue, // مقدار از تنظیمات
FirstActivationDate = activationDate,
FirstPackageId = package.Id,
LastActivationDate = activationDate,
LastPackageId = package.Id,
InitialContribution = activationFeeValue,
GiftValue = giftValue,
TotalEarned = 0,
PurchaseMethod = user.PackagePurchaseMethod
};
@@ -210,31 +232,79 @@ public class ActivateClubMembershipCommandHandler : IRequestHandler<ActivateClub
}
else
{
if (existingMembership.IsActive)
// بررسی آیا چرخه فعال دارد — اگر بله، واقعاً فعال است و نیازی به کار نیست
var hasCurrentCycle = await _context.ClubMembershipCycles
.AnyAsync(c => c.UserId == user.Id && c.IsCurrentCycle, cancellationToken);
// اگر چرخه فعال دارد و درخواست Force نیست — احتمال اجرای تکراری همان خرید
// در حالت ForceActivation (مثل پرداخت دستی)، باید چرخه جدید ساخته شود تا پکیج جدید ثبت شود.
if (hasCurrentCycle && !request.ForceActivation)
{
_logger.LogInformation(
"User {UserId} is already an active club member",
"User {UserId} already has a running cycle — skipping duplicate activation",
user.Id
);
return true;
}
// فعال‌سازی مجدد
// فعال‌سازی مجدد یا خرید مجدد (Q19/Q20) — FirstActivation حفظ میشه (Q21), Last بروزرسانی میشه
// مقدار IsActive قبلی حفظ میشه — اگر قبلاً فعال بوده، فعال بمونه
entity = existingMembership;
entity.IsActive = true;
entity.ActivatedAt = activationDate;
entity.LastActivationDate = activationDate;
entity.LastPackageId = package.Id;
entity.PurchaseMethod = user.PackagePurchaseMethod;
_context.ClubMemberships.Update(entity);
_logger.LogInformation(
"Reactivated club membership for UserId {UserId}",
user.Id
"Re-activating club membership for UserId {UserId} (re-purchase scenario, IsActive was {WasActive})",
user.Id,
existingMembership.IsActive
);
}
await _context.SaveChangesAsync(cancellationToken);
// 6.5. ایجاد ClubMembershipCycle — هر خرید پکیج یک دور جدید
var previousCycles = await _context.ClubMembershipCycles
.Where(c => c.UserId == user.Id && c.IsCurrentCycle)
.ToListAsync(cancellationToken);
foreach (var prevCycle in previousCycles)
{
prevCycle.IsCurrentCycle = false;
ClubMembershipCycleHistoryWriter.WriteCycleClosed(_context, prevCycle, reason: "شروع دوره جدید");
}
var maxCycleNumber = await _context.ClubMembershipCycles
.Where(c => c.ClubMembershipId == entity.Id)
.MaxAsync(c => (int?)c.CycleNumber, cancellationToken) ?? 0;
var newCycle = new ClubMembershipCycle
{
UserId = user.Id,
ClubMembershipId = entity.Id,
CycleNumber = maxCycleNumber + 1,
PackagePurchasedAt = activationDate,
PurchaseMethod = user.PackagePurchaseMethod,
PackageAmount = package.Price,
PackageId = package.Id,
IsCurrentCycle = true
};
_context.ClubMembershipCycles.Add(newCycle);
await _context.SaveChangesAsync(cancellationToken);
ClubMembershipCycleHistoryWriter.WriteCycleStarted(_context, newCycle, reason: "فعال‌سازی عضویت باشگاه");
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Created ClubMembershipCycle #{CycleNumber} for UserId {UserId}, MembershipId {MembershipId}",
newCycle.CycleNumber,
user.Id,
entity.Id
);
// 7. ثبت تاریخچه
var history = new ClubMembershipHistory
{
@@ -253,81 +323,62 @@ public class ActivateClubMembershipCommandHandler : IRequestHandler<ActivateClub
await _context.SaveChangesAsync(cancellationToken);
// ⭐ 8. اضافه کردن مبلغ به Pool هفته جاری
var currentWeekDefinitionId = GetCurrentWeekDefinitionId();
var weeklyPool = await _context.WeeklyCommissionPools
.FirstOrDefaultAsync(p => p.WeekDefinitionId == currentWeekDefinitionId, cancellationToken);
if (weeklyPool == null)
// عضو جدید (isNewMembership=true): Pool توسط AcceptClubMembershipContract شارژ می‌شود
// چون کاربر قبل از امضای قرارداد IsActive=false است و قرارداد فقط یک‌بار امضا می‌شود.
// خرید مجدد (isNewMembership=false): قرارداد مجدد امضا نمی‌شود — Pool همین‌جا شارژ می‌شود.
if (!isNewMembership)
{
// ایجاد Pool جدید برای این هفته
weeklyPool = new WeeklyCommissionPool
var currentWeekDefinitionId = GetCurrentWeekDefinitionId();
var weeklyPool = await _context.WeeklyCommissionPools
.FirstOrDefaultAsync(p => p.WeekDefinitionId == currentWeekDefinitionId && p.PackageId == package.Id, cancellationToken);
if (weeklyPool == null)
{
WeekDefinitionId = currentWeekDefinitionId,
TotalPoolAmount = activationFeeValue, // مبلغ هدیه به Pool اضافه میشه
TotalBalances = 0, // در CalculateWeeklyBalances محاسبه میشه
ValuePerBalance = 0, // در CalculateWeeklyCommissionPool محاسبه میشه
IsCalculated = false,
CalculatedAt = null
};
// ایجاد Pool جدید برای این هفته × این پکیج
weeklyPool = new WeeklyCommissionPool
{
WeekDefinitionId = currentWeekDefinitionId,
PackageId = package.Id,
TotalPoolAmount = activationFeeValue,
TotalBalances = 0,
ValuePerBalance = 0,
IsCalculated = false,
CalculatedAt = null
};
await _context.WeeklyCommissionPools.AddAsync(weeklyPool, cancellationToken);
_logger.LogInformation(
"Created new WeeklyCommissionPool for WeekDefinitionId={WeekDefinitionId} with initial amount: {Amount}",
currentWeekDefinitionId,
giftValue
);
}
else
{
// اضافه کردن به Pool موجود
weeklyPool.TotalPoolAmount += activationFeeValue;
_context.WeeklyCommissionPools.Update(weeklyPool);
_logger.LogInformation(
"Added {Amount} to existing WeeklyCommissionPool for WeekDefinitionId={WeekDefinitionId}. New total: {NewTotal}",
activationFeeValue,
currentWeekDefinitionId,
weeklyPool.TotalPoolAmount
);
}
await _context.SaveChangesAsync(cancellationToken);
// 9. اضافه کردن ویژگی‌های باشگاه برای کاربر (فقط برای عضویت جدید)
if (isNewMembership)
{
var clubFeatures = await _context.ClubFeatures
.Where(f => !f.IsDeleted && new long[] { 1, 2, 3, 4 }.Contains(f.Id))
.ToListAsync(cancellationToken);
if (clubFeatures.Any())
{
var userClubFeatures = clubFeatures.Select(feature => new UserClubFeature
{
UserId = user.Id,
ClubMembershipId = entity.Id,
ClubFeatureId = feature.Id,
GrantedAt = activationDate,
IsActive = true,
Notes = "اعطا شده به‌طور خودکار هنگام فعالسازی"
}).ToList(); _context.UserClubFeatures.AddRange(userClubFeatures);
await _context.SaveChangesAsync(cancellationToken);
await _context.WeeklyCommissionPools.AddAsync(weeklyPool, cancellationToken);
_logger.LogInformation(
"Granted {Count} club features to UserId {UserId}",
clubFeatures.Count,
user.Id
"Created new WeeklyCommissionPool for WeekDefinitionId={WeekDefinitionId} with initial amount: {Amount}",
currentWeekDefinitionId,
activationFeeValue
);
}
else
{
_logger.LogWarning(
"No club features found to grant to UserId {UserId}",
user.Id
weeklyPool.TotalPoolAmount += activationFeeValue;
_context.WeeklyCommissionPools.Update(weeklyPool);
_logger.LogInformation(
"Added {Amount} to existing WeeklyCommissionPool for WeekDefinitionId={WeekDefinitionId}. New total: {NewTotal}",
activationFeeValue,
currentWeekDefinitionId,
weeklyPool.TotalPoolAmount
);
}
await _context.SaveChangesAsync(cancellationToken);
}
else
{
_logger.LogInformation(
"New member — Pool charge deferred to AcceptClubMembershipContract for UserId {UserId}",
user.Id
);
}
// 9. اعمال ویژگی‌های پکیج — DIFF/تفاضل (Q20)
await ApplyFeatureDiffAsync(user.Id, entity.Id, package.Id, isNewMembership, activationDate, cancellationToken);
_logger.LogInformation(
"Club membership activated successfully. UserId: {UserId}, MembershipId: {MembershipId}",
@@ -348,6 +399,74 @@ public class ActivateClubMembershipCommandHandler : IRequestHandler<ActivateClub
}
}
/// <summary>
/// اعمال DIFF فیچرها بر اساس پکیج (Q20)
/// عضویت جدید: همه فیچرهای پکیج اضافه میشه
/// خرید مجدد: تفاضل فیچرهای فعلی و پکیج جدید
/// </summary>
private async Task ApplyFeatureDiffAsync(
long userId, long membershipId, long packageId,
bool isNewMembership, DateTime activationDate,
CancellationToken cancellationToken)
{
// فیچرهای پکیج جدید
var newFeatureIds = await _context.PackageFeatures
.Where(pf => pf.PackageId == packageId && pf.IsIncluded && !pf.IsDeleted)
.Select(pf => pf.ClubFeatureId)
.ToListAsync(cancellationToken);
if (!newFeatureIds.Any())
{
_logger.LogWarning(
"No PackageFeatures found for PackageId {PackageId} — skipping feature assignment for UserId {UserId}",
packageId, userId);
return;
}
// فیچرهای فعال فعلی کاربر
var currentFeatures = await _context.UserClubFeatures
.Where(ucf => ucf.UserId == userId && ucf.IsActive)
.ToListAsync(cancellationToken);
var currentFeatureIds = currentFeatures.Select(f => f.ClubFeatureId).ToHashSet();
// DIFF
var toAdd = newFeatureIds.Where(id => !currentFeatureIds.Contains(id)).ToList();
var toRemove = currentFeatures.Where(f => !newFeatureIds.Contains(f.ClubFeatureId)).ToList();
// حذف فیچرهای قدیمی که پکیج جدید ندارد
foreach (var feature in toRemove)
{
feature.IsActive = false;
feature.Notes = $"حذف شده بابت تغییر پکیج (PackageId: {packageId})";
}
// اضافه فیچرهای جدید
if (toAdd.Any())
{
var newUserFeatures = toAdd.Select(featureId => new UserClubFeature
{
UserId = userId,
ClubMembershipId = membershipId,
ClubFeatureId = featureId,
GrantedAt = activationDate,
IsActive = true,
Notes = isNewMembership
? "اعطا شده هنگام فعالسازی اولیه"
: $"اضافه شده بابت خرید مجدد پکیج (PackageId: {packageId})"
}).ToList();
_context.UserClubFeatures.AddRange(newUserFeatures);
}
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Feature DIFF applied for UserId={UserId}: Added={Added}, Removed={Removed}, Kept={Kept}",
userId, toAdd.Count, toRemove.Count,
currentFeatureIds.Count - toRemove.Count);
}
/// <summary>
/// دریافت شناسه تعریف هفته جاری
/// </summary>
@@ -13,6 +13,7 @@ public class GetAllClubMembershipsQueryHandler : IRequestHandler<GetAllClubMembe
{
var query = _context.ClubMemberships
.Include(x => x.User)
.Include(x => x.LastPackage)
.ApplyOrder(sortBy: request.SortBy)
.AsNoTracking()
.AsQueryable();
@@ -35,8 +36,10 @@ public class GetAllClubMembershipsQueryHandler : IRequestHandler<GetAllClubMembe
Id = x.Id,
UserId = x.UserId,
UserName = x.User != null ? $"{x.User.FirstName} {x.User.LastName}" : string.Empty,
PackageId = x.LastPackageId ?? 0,
PackageName = x.LastPackage != null ? x.LastPackage.Title : string.Empty,
IsActive = x.IsActive,
ActivatedAt = x.ActivatedAt,
ActivatedAt = x.LastActivationDate ?? x.ActivatedAt,
InitialContribution = x.InitialContribution,
TotalEarned = x.TotalEarned,
Created = x.Created,
@@ -11,6 +11,8 @@ public class GetAllClubMembershipsResponseModel
public long Id { get; set; }
public long UserId { get; set; }
public string UserName { get; set; } = string.Empty;
public long PackageId { get; set; }
public string PackageName { get; set; } = string.Empty;
public bool IsActive { get; set; }
public DateTime? ActivatedAt { get; set; }
public long InitialContribution { get; set; }
@@ -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;
}
}
@@ -1,27 +1,17 @@
namespace CMSMicroservice.Application.ClubMembershipCQ.Queries.GetClubMembershipHistory;
/// <summary>
/// Query برای دریافت تاریخچه تغییرات عضویت باشگاه
/// </summary>
public record GetClubMembershipHistoryQuery : IRequest<GetClubMembershipHistoryResponseDto>
{
/// <summary>
/// شناسه عضویت (اختیاری)
/// </summary>
public long? MembershipId { get; init; }
/// <summary>
/// شناسه کاربر (اختیاری)
/// </summary>
public long? UserId { get; init; }
/// <summary>
/// موقعیت صفحه‌بندی
/// </summary>
public PaginationState? PaginationState { get; init; }
/// <summary>
/// مرتب‌سازی بر اساس
/// </summary>
public string? SortBy { get; init; }
public GetClubMembershipHistoryFilter? Filter { get; init; }
}
public class GetClubMembershipHistoryFilter
{
public long? UserId { get; set; }
public long? ClubMembershipId { get; set; }
public ClubMembershipAction? Action { get; set; }
public DateTime? CreatedFrom { get; set; }
public DateTime? CreatedTo { get; set; }
}
@@ -12,20 +12,30 @@ public class GetClubMembershipHistoryQueryHandler : IRequestHandler<GetClubMembe
public async Task<GetClubMembershipHistoryResponseDto> Handle(GetClubMembershipHistoryQuery request, CancellationToken cancellationToken)
{
var query = _context.ClubMembershipHistories
.Include(x => x.ClubMembership)
.ThenInclude(m => m!.User)
.AsNoTracking()
.AsQueryable();
if (request.MembershipId.HasValue)
if (request.Filter != null)
{
query = query.Where(x => x.ClubMembershipId == request.MembershipId.Value);
if (request.Filter.ClubMembershipId.HasValue)
query = query.Where(x => x.ClubMembershipId == request.Filter.ClubMembershipId.Value);
if (request.Filter.UserId.HasValue)
query = query.Where(x => x.UserId == request.Filter.UserId.Value);
if (request.Filter.Action.HasValue)
query = query.Where(x => x.Action == request.Filter.Action.Value);
if (request.Filter.CreatedFrom.HasValue)
query = query.Where(x => x.Created >= request.Filter.CreatedFrom.Value);
if (request.Filter.CreatedTo.HasValue)
query = query.Where(x => x.Created <= request.Filter.CreatedTo.Value);
}
if (request.UserId.HasValue)
{
query = query.Where(x => x.UserId == request.UserId.Value);
}
query = query.ApplyOrder(sortBy: request.SortBy ?? "Created"); // پیش‌فرض: جدیدترین اول
query = query.ApplyOrder(sortBy: request.SortBy ?? "-Created");
var meta = await query.GetMetaData(request.PaginationState, cancellationToken);
@@ -36,6 +46,9 @@ public class GetClubMembershipHistoryQueryHandler : IRequestHandler<GetClubMembe
Id = x.Id,
ClubMembershipId = x.ClubMembershipId,
UserId = x.UserId,
UserName = x.ClubMembership != null && x.ClubMembership.User != null
? $"{x.ClubMembership.User.FirstName} {x.ClubMembership.User.LastName}"
: string.Empty,
OldIsActive = x.OldIsActive,
NewIsActive = x.NewIsActive,
OldInitialContribution = x.OldInitialContribution,
@@ -4,31 +4,6 @@ public class GetClubMembershipHistoryQueryValidator : AbstractValidator<GetClubM
{
public GetClubMembershipHistoryQueryValidator()
{
RuleFor(x => x.MembershipId)
.GreaterThan(0)
.WithMessage("شناسه عضویت معتبر نیست")
.When(x => x.MembershipId.HasValue);
RuleFor(x => x.UserId)
.GreaterThan(0)
.WithMessage("شناسه کاربر معتبر نیست")
.When(x => x.UserId.HasValue);
RuleFor(x => x)
.Must(x => x.MembershipId.HasValue || x.UserId.HasValue)
.WithMessage("حداقل یکی از MembershipId یا UserId باید مقداردهی شود");
// Admin report: filters are all optional
}
public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
{
var result = await ValidateAsync(
ValidationContext<GetClubMembershipHistoryQuery>.CreateWithOptions(
(GetClubMembershipHistoryQuery)model,
x => x.IncludeProperties(propertyName)));
if (result.IsValid)
return Array.Empty<string>();
return result.Errors.Select(e => e.ErrorMessage);
};
}
@@ -11,6 +11,7 @@ public class GetClubMembershipHistoryResponseModel
public long Id { get; set; }
public long ClubMembershipId { get; set; }
public long UserId { get; set; }
public string UserName { get; set; } = string.Empty;
public bool OldIsActive { get; set; }
public bool NewIsActive { get; set; }
public long? OldInitialContribution { get; set; }
@@ -0,0 +1,46 @@
using CMSMicroservice.Domain.Entities.Club;
namespace CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetAllClubMembershipCycleByFilter;
public static class ClubMembershipCycleFilterExtensions
{
public static IQueryable<ClubMembershipCycle> ApplyClubMembershipCycleFilter(
this IQueryable<ClubMembershipCycle> query,
GetAllClubMembershipCycleByFilterFilter? filter)
{
if (filter == null) return query;
if (filter.UserId.HasValue)
query = query.Where(x => x.UserId == filter.UserId.Value);
if (filter.IsCurrentCycle.HasValue)
query = query.Where(x => x.IsCurrentCycle == filter.IsCurrentCycle.Value);
if (filter.PackageId.HasValue)
query = query.Where(x => x.PackageId == filter.PackageId.Value);
if (filter.CycleNumber.HasValue)
query = query.Where(x => x.CycleNumber == filter.CycleNumber.Value);
if (filter.PurchaseMethod.HasValue)
query = query.Where(x => x.PurchaseMethod == filter.PurchaseMethod.Value);
if (filter.MagicState.HasValue)
{
query = filter.MagicState.Value switch
{
1 => query.Where(x => x.MagicStartedAt != null && x.MagicCompletedAt == null),
2 => query.Where(x => x.MagicCompletedAt != null),
_ => query.Where(x => x.MagicStartedAt == null && x.MagicCompletedAt == null)
};
}
if (filter.PackagePurchasedFrom.HasValue)
query = query.Where(x => x.PackagePurchasedAt >= filter.PackagePurchasedFrom.Value);
if (filter.PackagePurchasedTo.HasValue)
query = query.Where(x => x.PackagePurchasedAt <= filter.PackagePurchasedTo.Value);
return query;
}
}
@@ -0,0 +1,47 @@
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetAllClubMembershipCycleByFilter;
public record GetAllClubMembershipCycleByFilterQuery : IRequest<GetAllClubMembershipCycleByFilterResponseDto>
{
public PaginationState? PaginationState { get; init; }
public string? SortBy { get; init; }
public GetAllClubMembershipCycleByFilterFilter? Filter { get; init; }
}
public class GetAllClubMembershipCycleByFilterFilter
{
public long? UserId { get; set; }
public bool? IsCurrentCycle { get; set; }
public long? PackageId { get; set; }
public int? CycleNumber { get; set; }
public PackagePurchaseMethod? PurchaseMethod { get; set; }
/// <summary>0=none, 1=active magic, 2=completed magic</summary>
public int? MagicState { get; set; }
public DateTime? PackagePurchasedFrom { get; set; }
public DateTime? PackagePurchasedTo { get; set; }
}
public class GetAllClubMembershipCycleByFilterResponseDto
{
public MetaData MetaData { get; set; }
public List<GetAllClubMembershipCycleByFilterResponseModel>? Models { get; set; }
}
public class GetAllClubMembershipCycleByFilterResponseModel
{
public long Id { get; set; }
public long UserId { get; set; }
public string UserName { get; set; } = string.Empty;
public long ClubMembershipId { get; set; }
public int CycleNumber { get; set; }
public long PackageId { get; set; }
public string PackageName { get; set; } = string.Empty;
public long PackageAmount { get; set; }
public PackagePurchaseMethod PurchaseMethod { get; set; }
public DateTime PackagePurchasedAt { get; set; }
public DateTime? MagicStartedAt { get; set; }
public DateTime? MagicCompletedAt { get; set; }
public bool IsCurrentCycle { get; set; }
public DateTimeOffset Created { get; set; }
}
@@ -0,0 +1,49 @@
namespace CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetAllClubMembershipCycleByFilter;
public class GetAllClubMembershipCycleByFilterQueryHandler
: IRequestHandler<GetAllClubMembershipCycleByFilterQuery, GetAllClubMembershipCycleByFilterResponseDto>
{
private readonly IApplicationDbContext _context;
public GetAllClubMembershipCycleByFilterQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllClubMembershipCycleByFilterResponseDto> Handle(
GetAllClubMembershipCycleByFilterQuery request,
CancellationToken cancellationToken)
{
var query = _context.ClubMembershipCycles
.Include(x => x.User)
.Include(x => x.Package)
.AsNoTracking()
.ApplyClubMembershipCycleFilter(request.Filter)
.ApplyOrder(sortBy: request.SortBy ?? "-PackagePurchasedAt");
return new GetAllClubMembershipCycleByFilterResponseDto
{
MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
Models = await query
.PaginatedListAsync(paginationState: request.PaginationState)
.Select(x => new GetAllClubMembershipCycleByFilterResponseModel
{
Id = x.Id,
UserId = x.UserId,
UserName = x.User != null ? $"{x.User.FirstName} {x.User.LastName}" : string.Empty,
ClubMembershipId = x.ClubMembershipId,
CycleNumber = x.CycleNumber,
PackageId = x.PackageId,
PackageName = x.Package != null ? x.Package.Title : string.Empty,
PackageAmount = x.PackageAmount,
PurchaseMethod = x.PurchaseMethod,
PackagePurchasedAt = x.PackagePurchasedAt,
MagicStartedAt = x.MagicStartedAt,
MagicCompletedAt = x.MagicCompletedAt,
IsCurrentCycle = x.IsCurrentCycle,
Created = x.Created
})
.ToListAsync(cancellationToken)
};
}
}
@@ -0,0 +1,13 @@
namespace CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetClubMembershipCycleSummary;
public record GetClubMembershipCycleSummaryQuery : IRequest<GetClubMembershipCycleSummaryResponseDto>
{
public GetAllClubMembershipCycleByFilter.GetAllClubMembershipCycleByFilterFilter? Filter { get; init; }
}
public class GetClubMembershipCycleSummaryResponseDto
{
public long TotalCount { get; set; }
public long CurrentCycleCount { get; set; }
public long MagicActiveCount { get; set; }
}
@@ -0,0 +1,36 @@
using CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetAllClubMembershipCycleByFilter;
namespace CMSMicroservice.Application.ClubMembershipCycleCQ.Queries.GetClubMembershipCycleSummary;
public class GetClubMembershipCycleSummaryQueryHandler
: IRequestHandler<GetClubMembershipCycleSummaryQuery, GetClubMembershipCycleSummaryResponseDto>
{
private readonly IApplicationDbContext _context;
public GetClubMembershipCycleSummaryQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetClubMembershipCycleSummaryResponseDto> Handle(
GetClubMembershipCycleSummaryQuery request,
CancellationToken cancellationToken)
{
var query = _context.ClubMembershipCycles
.AsNoTracking()
.ApplyClubMembershipCycleFilter(request.Filter);
var totalCount = await query.LongCountAsync(cancellationToken);
var currentCycleCount = await query.LongCountAsync(x => x.IsCurrentCycle, cancellationToken);
var magicActiveCount = await query.LongCountAsync(
x => x.MagicStartedAt != null && x.MagicCompletedAt == null,
cancellationToken);
return new GetClubMembershipCycleSummaryResponseDto
{
TotalCount = totalCount,
CurrentCycleCount = currentCycleCount,
MagicActiveCount = magicActiveCount
};
}
}
@@ -0,0 +1,33 @@
using CMSMicroservice.Domain.Entities.History;
namespace CMSMicroservice.Application.ClubMembershipCycleHistoryCQ.Queries.GetAllClubMembershipCycleHistoryByFilter;
public static class ClubMembershipCycleHistoryFilterExtensions
{
public static IQueryable<ClubMembershipCycleHistory> ApplyClubMembershipCycleHistoryFilter(
this IQueryable<ClubMembershipCycleHistory> query,
GetAllClubMembershipCycleHistoryByFilterFilter? filter)
{
if (filter == null) return query;
if (filter.UserId.HasValue)
query = query.Where(x => x.UserId == filter.UserId.Value);
if (filter.ClubMembershipCycleId.HasValue)
query = query.Where(x => x.ClubMembershipCycleId == filter.ClubMembershipCycleId.Value);
if (filter.CycleNumber.HasValue)
query = query.Where(x => x.CycleNumber == filter.CycleNumber.Value);
if (filter.Action.HasValue)
query = query.Where(x => x.Action == filter.Action.Value);
if (filter.CreatedFrom.HasValue)
query = query.Where(x => x.Created >= filter.CreatedFrom.Value);
if (filter.CreatedTo.HasValue)
query = query.Where(x => x.Created <= filter.CreatedTo.Value);
return query;
}
}
@@ -0,0 +1,45 @@
using CMSMicroservice.Domain.Enums;
namespace CMSMicroservice.Application.ClubMembershipCycleHistoryCQ.Queries.GetAllClubMembershipCycleHistoryByFilter;
public record GetAllClubMembershipCycleHistoryByFilterQuery : IRequest<GetAllClubMembershipCycleHistoryByFilterResponseDto>
{
public PaginationState? PaginationState { get; init; }
public string? SortBy { get; init; }
public GetAllClubMembershipCycleHistoryByFilterFilter? Filter { get; init; }
}
public class GetAllClubMembershipCycleHistoryByFilterFilter
{
public long? UserId { get; set; }
public long? ClubMembershipCycleId { get; set; }
public int? CycleNumber { get; set; }
public ClubMembershipCycleAction? Action { get; set; }
public DateTime? CreatedFrom { get; set; }
public DateTime? CreatedTo { get; set; }
}
public class GetAllClubMembershipCycleHistoryByFilterResponseDto
{
public MetaData MetaData { get; set; }
public List<GetAllClubMembershipCycleHistoryByFilterResponseModel>? Models { get; set; }
}
public class GetAllClubMembershipCycleHistoryByFilterResponseModel
{
public long Id { get; set; }
public long ClubMembershipCycleId { get; set; }
public long UserId { get; set; }
public string UserName { get; set; } = string.Empty;
public int CycleNumber { get; set; }
public bool OldIsCurrentCycle { get; set; }
public bool NewIsCurrentCycle { get; set; }
public DateTime? OldMagicStartedAt { get; set; }
public DateTime? NewMagicStartedAt { get; set; }
public DateTime? OldMagicCompletedAt { get; set; }
public DateTime? NewMagicCompletedAt { get; set; }
public ClubMembershipCycleAction Action { get; set; }
public string? PerformedBy { get; set; }
public string? Reason { get; set; }
public DateTimeOffset Created { get; set; }
}
@@ -0,0 +1,52 @@
namespace CMSMicroservice.Application.ClubMembershipCycleHistoryCQ.Queries.GetAllClubMembershipCycleHistoryByFilter;
public class GetAllClubMembershipCycleHistoryByFilterQueryHandler
: IRequestHandler<GetAllClubMembershipCycleHistoryByFilterQuery, GetAllClubMembershipCycleHistoryByFilterResponseDto>
{
private readonly IApplicationDbContext _context;
public GetAllClubMembershipCycleHistoryByFilterQueryHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<GetAllClubMembershipCycleHistoryByFilterResponseDto> Handle(
GetAllClubMembershipCycleHistoryByFilterQuery request,
CancellationToken cancellationToken)
{
var query = _context.ClubMembershipCycleHistories
.Include(x => x.ClubMembershipCycle)
.ThenInclude(c => c!.User)
.AsNoTracking()
.ApplyClubMembershipCycleHistoryFilter(request.Filter)
.ApplyOrder(sortBy: request.SortBy ?? "-Created");
return new GetAllClubMembershipCycleHistoryByFilterResponseDto
{
MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
Models = await query
.PaginatedListAsync(paginationState: request.PaginationState)
.Select(x => new GetAllClubMembershipCycleHistoryByFilterResponseModel
{
Id = x.Id,
ClubMembershipCycleId = x.ClubMembershipCycleId,
UserId = x.UserId,
UserName = x.ClubMembershipCycle != null && x.ClubMembershipCycle.User != null
? $"{x.ClubMembershipCycle.User.FirstName} {x.ClubMembershipCycle.User.LastName}"
: string.Empty,
CycleNumber = x.CycleNumber,
OldIsCurrentCycle = x.OldIsCurrentCycle,
NewIsCurrentCycle = x.NewIsCurrentCycle,
OldMagicStartedAt = x.OldMagicStartedAt,
NewMagicStartedAt = x.NewMagicStartedAt,
OldMagicCompletedAt = x.OldMagicCompletedAt,
NewMagicCompletedAt = x.NewMagicCompletedAt,
Action = x.Action,
PerformedBy = x.PerformedBy,
Reason = x.Reason,
Created = x.Created
})
.ToListAsync(cancellationToken)
};
}
}
@@ -0,0 +1,12 @@
namespace CMSMicroservice.Application.CommissionCQ.Commands.BulkCreditPayouts;
public class BulkCreditPayoutsCommand : IRequest<BulkCreditPayoutsResult>
{
public long WeekDefinitionId { get; set; }
}
public class BulkCreditPayoutsResult
{
public int CreditedCount { get; set; }
public long TotalCredited { get; set; }
}
@@ -0,0 +1,82 @@
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Commission;
using CMSMicroservice.Domain.Entities.History;
using CMSMicroservice.Domain.Enums;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.CommissionCQ.Commands.BulkCreditPayouts;
public class BulkCreditPayoutsCommandHandler : IRequestHandler<BulkCreditPayoutsCommand, BulkCreditPayoutsResult>
{
private readonly IApplicationDbContext _context;
private readonly ICurrentUserService _currentUser;
private readonly ILogger<BulkCreditPayoutsCommandHandler> _logger;
public BulkCreditPayoutsCommandHandler(
IApplicationDbContext context,
ICurrentUserService currentUser,
ILogger<BulkCreditPayoutsCommandHandler> logger)
{
_context = context;
_currentUser = currentUser;
_logger = logger;
}
public async Task<BulkCreditPayoutsResult> Handle(BulkCreditPayoutsCommand request, CancellationToken cancellationToken)
{
var pendingPayouts = await _context.UserCommissionPayouts
.Where(p => p.WeekDefinitionId == request.WeekDefinitionId
&& p.Status == CommissionPayoutStatus.Pending
&& !p.IsDeleted)
.ToListAsync(cancellationToken);
if (!pendingPayouts.Any())
{
return new BulkCreditPayoutsResult { CreditedCount = 0, TotalCredited = 0 };
}
var performedBy = _currentUser.GetPerformedBy() ?? "System";
var now = DateTime.UtcNow;
var payoutHistories = new List<CommissionPayoutHistory>();
var creditedCount = 0;
long totalCredited = 0;
foreach (var payout in pendingPayouts)
{
payout.Status = CommissionPayoutStatus.Paid;
payout.PaidAt = now;
payout.LastModified = now;
payoutHistories.Add(new CommissionPayoutHistory
{
UserCommissionPayoutId = payout.Id,
UserId = payout.UserId,
WeekDefinitionId = payout.WeekDefinitionId,
AmountBefore = payout.TotalAmount,
AmountAfter = payout.TotalAmount,
OldStatus = CommissionPayoutStatus.Pending,
NewStatus = CommissionPayoutStatus.Paid,
Action = CommissionPayoutAction.Paid,
PerformedBy = performedBy,
Reason = $"تایید پرداخت دسته‌جمعی کمیسیون هفته {payout.WeekDefinitionId} توسط {performedBy}"
});
creditedCount++;
totalCredited += payout.TotalAmount;
}
await _context.CommissionPayoutHistories.AddRangeAsync(payoutHistories, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"BulkCreditPayouts completed: Week={WeekId}, Credited={Count}, TotalAmount={Total}, By={By}",
request.WeekDefinitionId, creditedCount, totalCredited, performedBy);
return new BulkCreditPayoutsResult
{
CreditedCount = creditedCount,
TotalCredited = totalCredited
};
}
}
@@ -1,3 +1,5 @@
using CMSMicroservice.Domain.Common;
namespace CMSMicroservice.Application.CommissionCQ.Commands.CalculateWeeklyBalances;
public class CalculateWeeklyBalancesCommandHandler : IRequestHandler<CalculateWeeklyBalancesCommand, int>
@@ -41,8 +43,14 @@ public class CalculateWeeklyBalancesCommandHandler : IRequestHandler<CalculateWe
// ⭐ دریافت همه کاربرانی که عضو فعال باشگاه هستند
// بدون محدودیت زمانی - همه اعضای فعال کلاب باید کمیسیون بگیرند
// ⚠️ Magic Wallet: کاربرهایی که در حالت جادویی هستند از کمیسیون خارج میشن
var magicModeUserIds = await _context.UserWallets
.Where(w => w.WalletMode == WalletMode.Magic)
.Select(w => w.UserId)
.ToHashSetAsync(cancellationToken);
var activeClubMemberUserIds = await _context.ClubMemberships
.Where(c => c.IsActive)
.Where(c => c.IsActive && !magicModeUserIds.Contains(c.UserId))
.Select(c => c.UserId)
.ToHashSetAsync(cancellationToken);
@@ -74,21 +82,14 @@ public class CalculateWeeklyBalancesCommandHandler : IRequestHandler<CalculateWe
var balancesList = new List<NetworkWeeklyBalance>();
var calculatedAt = DateTime.Now;
// خواندن یکباره Configuration ها (بهینه‌سازی - به جای N query)
var configs = await _context.SystemConfigurations
.Where(x => x.IsActive && (
x.Key == "Club.ActivationFee" ||
x.Key == "Commission.WeeklyPoolContributionPercent" ||
x.Key == "Commission.MaxWeeklyBalancesPerLeg" ||
x.Key == "Commission.MaxNetworkLevel"))
.ToDictionaryAsync(x => x.Key, x => x.Value, cancellationToken);
// بارگذاری پکیج پایه برای خواندن سقف‌ها
var package = await _context.Packages
.FirstOrDefaultAsync(p => p.IsBasePackage && !p.IsDeleted, cancellationToken)
?? throw new InvalidOperationException("پکیج پایه یافت نشد");
// var activationFee = long.Parse(configs.GetValueOrDefault("Club.ActivationFee", "25000000"));
// var poolPercent = decimal.Parse(configs.GetValueOrDefault("Commission.WeeklyPoolContributionPercent", "20")) / 100m;
// سقف تعادل هفتگی برای هر دست (نه کل) - 300 برای چپ + 300 برای راست = حداکثر 600 تعادل
var maxBalancesPerLeg = int.Parse(configs.GetValueOrDefault("Commission.MaxWeeklyBalancesPerLeg", "300"));
// حداکثر عمق شبکه برای شمارش اعضا (15 لول)
var maxNetworkLevel = int.Parse(configs.GetValueOrDefault("Commission.MaxNetworkLevel", "15"));
// خواندن سقف‌ها از پکیج (قبلاً از SystemConstants بود)
var maxBalancesPerLeg = package.MaxBalancesPerLeg;
var maxNetworkLevel = package.MaxNetworkLevel;
foreach (var user in usersInNetwork.OrderBy(o=>o.Id))
{
@@ -142,6 +143,7 @@ public class CalculateWeeklyBalancesCommandHandler : IRequestHandler<CalculateWe
{
UserId = user.Id,
WeekDefinitionId = request.WeekDefinitionId,
PackageId = package.Id,
// اطلاعات جدید
LeftLegNewMembers = leftNewMembers,
@@ -264,11 +266,16 @@ public class CalculateWeeklyBalancesCommandHandler : IRequestHandler<CalculateWe
var count = 0;
// اگر فرزند در این هفته فعال شده، 1 امتیاز
var membership = await _context.ClubMemberships
.FirstOrDefaultAsync(x => x.UserId == child.Id && x.IsActive, cancellationToken);
// ⭐ بر اساس بازه تاریخی هفته، نه IsCurrentCycle
// IsCurrentCycle فقط آخرین خرید را نشان می‌دهد — برای تاریخچه‌ای (هفته‌های گذشته)
// باید از PackagePurchasedAt استفاده کرد که تاریخ دقیق خرید را نگه می‌دارد
var hadCycleInWeek = await _context.ClubMembershipCycles
.AnyAsync(x => x.UserId == child.Id
&& x.PackagePurchasedAt >= startDate
&& x.PackagePurchasedAt <= endDate,
cancellationToken);
if (membership?.ActivatedAt >= startDate && membership?.ActivatedAt <= endDate)
if (hadCycleInWeek)
{
count = 1;
}
@@ -10,6 +10,11 @@ public record CalculateWeeklyCommissionPoolCommand : IRequest<long>
/// </summary>
public long WeekDefinitionId { get; init; }
/// <summary>
/// شناسه پکیج — اگر مقدار داشته باشد فقط همین پکیج محاسبه می‌شود.
/// </summary>
public long? PackageId { get; init; }
/// <summary>
/// آیا محاسبه مجدد انجام شود؟
/// </summary>
@@ -23,8 +23,17 @@ public class CalculateWeeklyCommissionPoolCommandHandler : IRequestHandler<Calcu
}
// بررسی وجود استخر
var existingPool = await _context.WeeklyCommissionPools
.FirstOrDefaultAsync(x => x.WeekDefinitionId == request.WeekDefinitionId, cancellationToken);
var existingPoolQuery = _context.WeeklyCommissionPools
.Where(x => x.WeekDefinitionId == request.WeekDefinitionId);
if (request.PackageId.HasValue)
{
existingPoolQuery = existingPoolQuery.Where(x => x.PackageId == request.PackageId.Value);
}
var existingPool = await existingPoolQuery
.OrderBy(x => x.Id)
.FirstOrDefaultAsync(cancellationToken);
if (existingPool == null)
{
@@ -40,9 +49,15 @@ public class CalculateWeeklyCommissionPoolCommandHandler : IRequestHandler<Calcu
}
// بررسی وجود تعادل‌های هفتگی
var weeklyBalances = await _context.NetworkWeeklyBalances
.Where(x => x.WeekDefinitionId == request.WeekDefinitionId)
.ToListAsync(cancellationToken);
var weeklyBalancesQuery = _context.NetworkWeeklyBalances
.Where(x => x.WeekDefinitionId == request.WeekDefinitionId);
if (request.PackageId.HasValue)
{
weeklyBalancesQuery = weeklyBalancesQuery.Where(x => x.PackageId == request.PackageId.Value);
}
var weeklyBalances = await weeklyBalancesQuery.ToListAsync(cancellationToken);
if (!weeklyBalances.Any())
{
@@ -76,9 +91,15 @@ public class CalculateWeeklyCommissionPoolCommandHandler : IRequestHandler<Calcu
// حذف پرداخت‌های قبلی در صورت ForceRecalculate
if (request.ForceRecalculate)
{
var oldPayouts = await _context.UserCommissionPayouts
.Where(p => p.WeekDefinitionId == request.WeekDefinitionId)
.ToListAsync(cancellationToken);
var oldPayoutsQuery = _context.UserCommissionPayouts
.Where(p => p.WeekDefinitionId == request.WeekDefinitionId);
if (request.PackageId.HasValue)
{
oldPayoutsQuery = oldPayoutsQuery.Where(p => p.PackageId == request.PackageId.Value);
}
var oldPayouts = await oldPayoutsQuery.ToListAsync(cancellationToken);
if (oldPayouts.Any())
{
@@ -192,7 +213,7 @@ public class CalculateWeeklyCommissionPoolCommandHandler : IRequestHandler<Calcu
.ToDictionaryAsync(w => w.UserId, cancellationToken);
var newWallets = new List<UserWallet>();
var walletLogs = new List<UserWalletChangeLog>();
var walletLogs = new List<UserWalletHistory>();
foreach (var payout in payouts)
{
@@ -241,7 +262,7 @@ public class CalculateWeeklyCommissionPoolCommandHandler : IRequestHandler<Calcu
wallet.NetworkBalance += payout.TotalAmount;
// ایجاد لاگ تغییر کیف پول
var walletLog = new UserWalletChangeLog
var walletLog = new UserWalletHistory
{
WalletId = wallet.Id,
CurrentBalance = wallet.Balance,
@@ -258,7 +279,7 @@ public class CalculateWeeklyCommissionPoolCommandHandler : IRequestHandler<Calcu
}
// ذخیره تغییرات کیف پول و لاگ‌ها
await _context.UserWalletChangeLogs.AddRangeAsync(walletLogs, cancellationToken);
await _context.UserWalletHistories.AddRangeAsync(walletLogs, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
}
@@ -271,7 +292,7 @@ public class CalculateWeeklyCommissionPoolCommandHandler : IRequestHandler<Calcu
CancellationToken cancellationToken)
{
// پیدا کردن لاگ‌های کیف پول مرتبط با پرداخت‌های قبلی
var oldWalletLogs = await _context.UserWalletChangeLogs
var oldWalletLogs = await _context.UserWalletHistories
.Where(l => l.RefrenceId.HasValue && oldPayoutIds.Contains(l.RefrenceId.Value))
.ToListAsync(cancellationToken);
@@ -300,7 +321,7 @@ public class CalculateWeeklyCommissionPoolCommandHandler : IRequestHandler<Calcu
}
// حذف لاگ‌های قبلی
_context.UserWalletChangeLogs.RemoveRange(oldWalletLogs);
_context.UserWalletHistories.RemoveRange(oldWalletLogs);
await _context.SaveChangesAsync(cancellationToken);
}
@@ -1,3 +1,5 @@
using CMSMicroservice.Domain.Common;
namespace CMSMicroservice.Application.CommissionCQ.Commands.ProcessUserPayouts;
public class ProcessUserPayoutsCommandHandler : IRequestHandler<ProcessUserPayoutsCommand, int>
@@ -47,12 +49,11 @@ public class ProcessUserPayoutsCommandHandler : IRequestHandler<ProcessUserPayou
await _context.SaveChangesAsync(cancellationToken);
}
// ⭐ خواندن MaxNetworkLevel از Config
var maxNetworkLevelConfig = await _context.SystemConfigurations
.Where(x => x.Key == "Commission.MaxNetworkLevel" && x.IsActive)
.Select(x => x.Value)
.FirstOrDefaultAsync(cancellationToken);
var maxNetworkLevel = int.Parse(maxNetworkLevelConfig ?? "15");
// بارگذاری پکیج پایه برای خواندن سقف‌ها
var package = await _context.Packages
.FirstOrDefaultAsync(p => p.IsBasePackage && !p.IsDeleted, cancellationToken)
?? throw new InvalidOperationException("پکیج پایه یافت نشد");
var maxNetworkLevel = package.MaxNetworkLevel;
// دریافت همه تعادل‌های هفتگی (شامل صفرها هم برای محاسبه زیرمجموعه)
var allWeeklyBalances = await _context.NetworkWeeklyBalances
@@ -115,6 +116,7 @@ public class ProcessUserPayoutsCommandHandler : IRequestHandler<ProcessUserPayou
UserId = userId,
WeekDefinitionId = request.WeekDefinitionId,
WeeklyPoolId = pool.Id,
PackageId = package.Id,
BalancesEarned = totalBalancesWithSubordinates, // ⭐ شامل زیرمجموعه
ValuePerBalance = pool.ValuePerBalance,
TotalAmount = totalAmount,
@@ -21,4 +21,9 @@ public record TriggerWeeklyCalculationCommand : IRequest<TriggerWeeklyCalculatio
/// Skip pool calculation and payout processing (Step 2)
/// </summary>
public bool SkipPayouts { get; init; }
/// <summary>
/// شناسه پکیج — اگر مقدار داشته باشد فقط این پکیج محاسبه می‌شود، در غیر این صورت همه پکیج‌ها
/// </summary>
public long? PackageId { get; init; }
}
@@ -53,6 +53,7 @@ public class TriggerWeeklyCalculationCommandHandler : IRequestHandler<TriggerWee
var balancesCount = await strategy.CalculateWeeklyBalancesAsync(
request.WeekDefinitionId,
request.ForceRecalculate,
request.PackageId,
cancellationToken);
steps.Add($"محاسبه امتیازات هفتگی ({balancesCount} کاربر)");
@@ -64,6 +65,7 @@ public class TriggerWeeklyCalculationCommandHandler : IRequestHandler<TriggerWee
var poolId = await strategy.CalculateWeeklyCommissionPoolAsync(
request.WeekDefinitionId,
request.ForceRecalculate,
request.PackageId,
cancellationToken);
steps.Add($"محاسبه استخر و پرداخت کاربران (Pool: {poolId})");
@@ -6,20 +6,25 @@ namespace CMSMicroservice.Application.CommissionCQ.Queries.GetAllWeeklyPools;
public record GetAllWeeklyPoolsQuery : IRequest<GetAllWeeklyPoolsResponseDto>
{
/// <summary>
/// از هفته (فیلتر اختیاری)
/// از هفته — WeekDefinitionId (فیلتر اختیاری)
/// </summary>
public int? FromWeekOrder { get; init; }
public long? FromWeekDefinitionId { get; init; }
/// <summary>
/// تا هفته (فیلتر اختیاری)
/// تا هفته — WeekDefinitionId (فیلتر اختیاری)
/// </summary>
public int? ToWeekOrder { get; init; }
public long? ToWeekDefinitionId { get; init; }
/// <summary>
/// فقط Pool های محاسبه شده
/// </summary>
public bool? OnlyCalculated { get; init; }
/// <summary>
/// فیلتر بر اساس پکیج (اختیاری)
/// </summary>
public long? PackageId { get; init; }
/// <summary>
/// شماره صفحه
/// </summary>

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