Compare commits

...

8 Commits

Author SHA1 Message Date
masoodafar-web eb76791dc0 feat: add production configuration settings; include URLs, encryption settings, and logging levels
Build and Deploy to Production / build-and-deploy (push) Successful in 2m0s
2025-12-27 07:45:16 +03:30
masoodafar-web 2a8c24ef42 feat: update query parameter handling for week selection; improve fallback logic for week definition creation
Build and Deploy / build (push) Successful in 1m21s
2025-12-27 07:41:47 +03:30
masoodafar-web 3fdaa2c22a feat: update commission status handling and UI; enhance status representation with computed properties and improve filtering logic
Build and Deploy / build (push) Successful in 2m20s
2025-12-27 07:31:31 +03:30
masoodafar-web e3521af071 feat: enhance WithdrawalRequests page with payout selection and improved submission logic; add sorting options for products
Build and Deploy / build (push) Successful in 1m18s
2025-12-27 06:22:41 +03:30
masoodafar-web 43cdf7c897 feat: enhance ReleaseNotesDialog with improved UI elements and animations; update button labels and alert messages
Build and Deploy / build (push) Successful in 1m26s
2025-12-27 05:06:03 +03:30
masoodafar-web 9cd275a777 feat: implement version check and update dialog; add browser cache clearing functionality
Build and Deploy / build (push) Successful in 1m40s
2025-12-27 04:47:27 +03:30
masoodafar-web 51129704a0 feat: add staging configuration with gateway and logging settings
Build and Deploy / build (push) Successful in 1m25s
2025-12-27 02:56:24 +03:30
masoodafar-web 00f805dcd8 fix: update gateway URL to new front office endpoint
Build and Deploy / build (push) Successful in 2m16s
2025-12-27 01:13:21 +03:30
22 changed files with 868 additions and 123 deletions
+75 -3
View File
@@ -17,8 +17,8 @@ public partial class App
{ {
await base.OnInitializedAsync(); await base.OnInitializedAsync();
// Check app version and clear cache if needed // Check app version and show update dialog if needed
await AppVersionService.CheckVersionAndClearCacheIfNeededAsync(); await CheckAndShowVersionUpdateAsync();
// Check for referral code in URL query parameters // Check for referral code in URL query parameters
var uri = Navigation.ToAbsoluteUri(Navigation.Uri); var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
@@ -58,5 +58,77 @@ public partial class App
} }
} }
} }
}
/// <summary>
/// بررسی نسخه و نمایش دیالوگ آپدیت در صورت نیاز
/// فقط برای کاربران لاگین شده
/// </summary>
private async Task CheckAndShowVersionUpdateAsync()
{
try
{
// فقط برای کاربران لاگین شده
if (!await AuthService.IsAuthenticatedAsync())
return;
// forDialog: true یعنی اگه skip کرده ولی یک روز گذشته، دوباره نشون بده
var versionCheck = await AppVersionService.CheckVersionAsync(forDialog: true);
if (!versionCheck.HasNewVersion || string.IsNullOrEmpty(versionCheck.NewVersion))
return;
// ثبت زمان نمایش دیالوگ
await AppVersionService.RecordDialogShownAsync();
// تنظیمات دیالوگ
var dialogOptions = new DialogOptions
{
BackdropClick = !versionCheck.IsForceUpdate, // اگر force باشه نتونه بیرون کلیک کنه
CloseOnEscapeKey = !versionCheck.IsForceUpdate,
CloseButton = !versionCheck.IsForceUpdate,
MaxWidth = MaxWidth.Small,
FullWidth = true
};
var parameters = new DialogParameters<ReleaseNotesDialog>
{
{ x => x.OldVersion, versionCheck.OldVersion },
{ x => x.NewVersion, versionCheck.NewVersion },
{ x => x.ReleaseNotes, versionCheck.ReleaseNotes },
{ x => x.UpdateMessage, versionCheck.UpdateMessage },
{ x => x.IsForceUpdate, versionCheck.IsForceUpdate }
};
var dialog = await DialogService.ShowAsync<ReleaseNotesDialog>("بروزرسانی", parameters, dialogOptions);
var result = await dialog.Result;
if (result is { Canceled: false, Data: bool shouldUpdate })
{
if (shouldUpdate)
{
// کاربر خواست آپدیت کنه
await AppVersionService.ApplyUpdateAsync(versionCheck.NewVersion);
// رفرش صفحه
Navigation.NavigateTo(Navigation.Uri, forceLoad: true);
}
else
{
// کاربر گفت بعداً (فقط وقتی force نیست)
await AppVersionService.SkipVersionAsync(versionCheck.NewVersion);
}
}
else if (versionCheck.IsForceUpdate)
{
// اگر force بود و دیالوگ بسته شد، باز هم آپدیت کن
await AppVersionService.ApplyUpdateAsync(versionCheck.NewVersion);
Navigation.NavigateTo(Navigation.Uri, forceLoad: true);
}
}
catch (Exception ex)
{
// در صورت خطا، لاگ کن ولی ادامه بده
Console.WriteLine($"Error checking version: {ex.Message}");
}
}
}
+1 -1
View File
@@ -12,7 +12,7 @@
<PackageReference Include="DateTimeConverterCL" Version="1.0.0" /> <PackageReference Include="DateTimeConverterCL" Version="1.0.0" />
<PackageReference Include="Foursat.FrontOffice.BFF.City.Protobuf" Version="0.0.2" /> <PackageReference Include="Foursat.FrontOffice.BFF.City.Protobuf" Version="0.0.2" />
<PackageReference Include="Foursat.FrontOffice.BFF.ClubMembership.Protobuf" Version="0.0.4" /> <PackageReference Include="Foursat.FrontOffice.BFF.ClubMembership.Protobuf" Version="0.0.4" />
<PackageReference Include="Foursat.FrontOffice.BFF.Commission.Protobuf" Version="0.0.3" /> <PackageReference Include="Foursat.FrontOffice.BFF.Commission.Protobuf" Version="0.0.4" />
<PackageReference Include="Foursat.FrontOffice.BFF.Configuration.Protobuf" Version="0.0.4" /> <PackageReference Include="Foursat.FrontOffice.BFF.Configuration.Protobuf" Version="0.0.4" />
<!-- <PackageReference Include="Foursat.FrontOffice.BFF.ClubMembership.Protobuf" Version="0.0.3" /> --> <!-- <PackageReference Include="Foursat.FrontOffice.BFF.ClubMembership.Protobuf" Version="0.0.3" /> -->
<!-- <PackageReference Include="Foursat.FrontOffice.BFF.Commission.Protobuf" Version="0.0.2" /> --> <!-- <PackageReference Include="Foursat.FrontOffice.BFF.Commission.Protobuf" Version="0.0.2" /> -->
@@ -28,10 +28,11 @@
Style="max-width: 150px;" /> Style="max-width: 150px;" />
<MudSelect T="string" @bind-Value="_filterStatus" Label="وضعیت" Variant="Variant.Outlined" Style="max-width: 200px;"> <MudSelect T="string" @bind-Value="_filterStatus" Label="وضعیت" Variant="Variant.Outlined" Style="max-width: 200px;">
<MudSelectItem T="string" Value="@string.Empty">همه</MudSelectItem> <MudSelectItem T="string" Value="@string.Empty">همه</MudSelectItem>
<MudSelectItem T="string" Value="@("Created")">ایجاد شده</MudSelectItem> <MudSelectItem T="string" Value="@("Pending")">در انتظار</MudSelectItem>
<MudSelectItem T="string" Value="@("Paid")">پرداخت شده</MudSelectItem> <MudSelectItem T="string" Value="@("Paid")">پرداخت شده</MudSelectItem>
<MudSelectItem T="string" Value="@("WithdrawalRequested")">درخواست برداشت</MudSelectItem> <MudSelectItem T="string" Value="@("WithdrawalRequested")">درخواست برداشت</MudSelectItem>
<MudSelectItem T="string" Value="@("Withdrawn")">برداشت شده</MudSelectItem> <MudSelectItem T="string" Value="@("Withdrawn")">برداشت شده</MudSelectItem>
<MudSelectItem T="string" Value="@("PaymentFailed")">شکست خورده</MudSelectItem>
<MudSelectItem T="string" Value="@("Cancelled")">لغو شده</MudSelectItem> <MudSelectItem T="string" Value="@("Cancelled")">لغو شده</MudSelectItem>
</MudSelect> </MudSelect>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="ApplyFiltersAsync" StartIcon="@Icons.Material.Filled.FilterList"> <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="ApplyFiltersAsync" StartIcon="@Icons.Material.Filled.FilterList">
@@ -65,8 +66,8 @@
<MudText Color="Color.Success"><strong>@context.AmountFormatted</strong></MudText> <MudText Color="Color.Success"><strong>@context.AmountFormatted</strong></MudText>
</MudTd> </MudTd>
<MudTd> <MudTd>
<MudChip T="string" Color="@GetStatusColor(context.StatusBadgeColor)" Size="Size.Small" Variant="Variant.Outlined"> <MudChip T="string" Color="@GetStatusColor(context.StatusColor)" Size="Size.Small" Variant="Variant.Outlined">
@context.Status @context.StatusText
</MudChip> </MudChip>
</MudTd> </MudTd>
<MudTd>@context.DatePersian</MudTd> <MudTd>@context.DatePersian</MudTd>
@@ -91,8 +92,8 @@
<MudStack Spacing="1"> <MudStack Spacing="1">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"> <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center">
<MudChip T="string" Color="Color.Default" Size="Size.Small">@payout.WeekDisplayName</MudChip> <MudChip T="string" Color="Color.Default" Size="Size.Small">@payout.WeekDisplayName</MudChip>
<MudChip T="string" Color="@GetStatusColor(payout.StatusBadgeColor)" Size="Size.Small" Variant="Variant.Outlined"> <MudChip T="string" Color="@GetStatusColor(payout.StatusColor)" Size="Size.Small" Variant="Variant.Outlined">
@payout.Status @payout.StatusText
</MudChip> </MudChip>
</MudStack> </MudStack>
<MudText Typo="Typo.h6" Color="Color.Success">@payout.AmountFormatted</MudText> <MudText Typo="Typo.h6" Color="Color.Success">@payout.AmountFormatted</MudText>
@@ -61,8 +61,8 @@
<MudText Color="Color.Success" Typo="Typo.body1"><strong>@context.AmountFormatted</strong></MudText> <MudText Color="Color.Success" Typo="Typo.body1"><strong>@context.AmountFormatted</strong></MudText>
</MudTd> </MudTd>
<MudTd DataLabel="وضعیت"> <MudTd DataLabel="وضعیت">
<MudChip T="string" Color="@GetStatusColor(context.StatusBadgeColor)" Size="Size.Small"> <MudChip T="string" Color="@GetStatusColor(context.StatusColor)" Size="Size.Small">
@context.Status @context.StatusText
</MudChip> </MudChip>
</MudTd> </MudTd>
<MudTd DataLabel="تاریخ"> <MudTd DataLabel="تاریخ">
@@ -39,16 +39,25 @@ public partial class WeeklyBalancePage : ComponentBase
{ {
await _weekSelector.EnsureLoadedAsync(); await _weekSelector.EnsureLoadedAsync();
// Handle query parameter ?week=46 (WeekOrder) or ?week=123 (Id) // Handle query parameter ?week=7 (WeekDefinitionId)
if (!string.IsNullOrEmpty(QueryWeekNumber)) if (!string.IsNullOrEmpty(QueryWeekNumber))
{ {
// Try to parse as integer (first try as WeekOrder, then as Id) // Try to parse as WeekDefinitionId first (most common from dashboard links)
if (int.TryParse(QueryWeekNumber, out int weekOrder)) if (long.TryParse(QueryWeekNumber, out long id))
{ {
_selectedWeekDefinition = _weekSelector.FindByWeekOrder(weekOrder); _selectedWeekDefinition = _weekSelector.FindById(id);
if (_selectedWeekDefinition == null && long.TryParse(QueryWeekNumber, out long id))
// Fallback: try as WeekOrder if not found by Id
if (_selectedWeekDefinition == null && int.TryParse(QueryWeekNumber, out int weekOrder))
{ {
_selectedWeekDefinition = _weekSelector.FindById(id); _selectedWeekDefinition = _weekSelector.FindByWeekOrder(weekOrder);
}
// If still not found in cache, create a temporary definition with just the Id
// so we can still query the balance from BFF
if (_selectedWeekDefinition == null)
{
_selectedWeekDefinition = new WeekDefinitionDto { Id = id, DisplayName = $"هفته {id}" };
} }
} }
} }
@@ -11,35 +11,73 @@
<!-- فرم درخواست برداشت جدید --> <!-- فرم درخواست برداشت جدید -->
<MudPaper Elevation="2" Class="pa-4 rounded-lg"> <MudPaper Elevation="2" Class="pa-4 rounded-lg">
<MudText Typo="Typo.h6" Class="mb-2">ثبت درخواست برداشت جدید</MudText> <MudText Typo="Typo.h6" Class="mb-3">ثبت درخواست برداشت جدید</MudText>
<MudStack Spacing="2">
<MudTextField @bind-Value="_withdrawPayoutId" @if (!_availablePayouts.Any())
Label="شناسه واریز (PayoutId)" {
Variant="Variant.Outlined" <MudAlert Severity="Severity.Info" Variant="Variant.Outlined" Class="mb-3">
Type="MudBlazor.InputType.Number" <MudText>در حال حاضر واریزی برای برداشت وجود ندارد.</MudText>
Required="true" /> </MudAlert>
<MudRadioGroup T="WithdrawalMethodClient" @bind-Value="_withdrawMethod" Row="true"> }
<MudRadio T="WithdrawalMethodClient" Option="@WithdrawalMethodClient.Cash" Color="Color.Primary">برداشت نقدی (نیاز به شبا)</MudRadio> else
<MudRadio T="WithdrawalMethodClient" Option="@WithdrawalMethodClient.Diamond" Color="Color.Secondary">الماس/غیرنقدی</MudRadio> {
</MudRadioGroup> <MudStack Spacing="2">
<MudTextField @bind-Value="_withdrawIban" <MudSelect T="CommissionPayoutDto" @bind-Value="_selectedPayout"
Label="شماره شبا" Label="انتخاب واریز"
Variant="Variant.Outlined" Variant="Variant.Outlined"
Disabled="_withdrawMethod == WithdrawalMethodClient.Diamond" AnchorOrigin="Origin.BottomLeft"
Placeholder="IRxxxxxxxxxxxx" Required="true"
Adornment="Adornment.Start" ToStringFunc="@(p => p != null ? $"{p.WeekDisplayName} - {p.AmountFormatted}" : "")">
AdornmentText="IR" /> @foreach (var payout in _availablePayouts)
<MudText Typo="Typo.caption" Class="mud-text-secondary"> {
حداقل مبلغ برداشت: @FormatPrice(_minWithdrawalAmount) <MudSelectItem T="CommissionPayoutDto" Value="@payout">
</MudText> <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center" Class="w-100">
<MudButton Disabled="_isSubmittingWithdrawal" <MudText>@payout.WeekDisplayName</MudText>
Variant="Variant.Filled" <MudChip T="string" Color="Color.Success" Size="Size.Small" Variant="Variant.Filled">
Color="Color.Primary" @payout.AmountFormatted
StartIcon="@Icons.Material.Filled.Outbound" </MudChip>
OnClick="SubmitWithdrawal"> </MudStack>
@(_isSubmittingWithdrawal ? "در حال ثبت..." : "ثبت درخواست برداشت") </MudSelectItem>
</MudButton> }
</MudStack> </MudSelect>
@if (_selectedPayout != null)
{
<MudAlert Severity="Severity.Success" Variant="Variant.Text" Dense="true">
مبلغ قابل برداشت: <strong>@_selectedPayout.AmountFormatted</strong>
</MudAlert>
}
<MudRadioGroup T="WithdrawalMethodClient" @bind-Value="_withdrawMethod" Row="true">
<MudRadio T="WithdrawalMethodClient" Value="@WithdrawalMethodClient.Cash" Color="Color.Primary">
برداشت نقدی (نیاز به شبا)
</MudRadio>
<MudRadio T="WithdrawalMethodClient" Disabled="true" Value="@WithdrawalMethodClient.Diamond" Color="Color.Secondary">
الماس/غیرنقدی
</MudRadio>
</MudRadioGroup>
<MudTextField @bind-Value="_withdrawIban"
Label="شماره شبا"
Variant="Variant.Outlined"
Disabled="_withdrawMethod == WithdrawalMethodClient.Diamond"
Placeholder="IRxxxxxxxxxxxx"
Adornment="Adornment.Start"
AdornmentText="IR" />
<MudText Typo="Typo.caption" Class="mud-text-secondary">
حداقل مبلغ برداشت: @FormatPrice(_minWithdrawalAmount)
</MudText>
<MudButton Disabled="@(_isSubmittingWithdrawal || _selectedPayout == null)"
Variant="Variant.Filled"
Color="Color.Primary"
StartIcon="@Icons.Material.Filled.Outbound"
OnClick="SubmitWithdrawal">
@(_isSubmittingWithdrawal ? "در حال ثبت..." : "ثبت درخواست برداشت")
</MudButton>
</MudStack>
}
</MudPaper> </MudPaper>
<!-- فیلتر وضعیت --> <!-- فیلتر وضعیت -->
@@ -6,12 +6,15 @@ namespace FrontOffice.Main.Pages.Profile;
public partial class WithdrawalRequests : ComponentBase public partial class WithdrawalRequests : ComponentBase
{ {
[Inject] private CommissionService CommissionService { get; set; } = default!;
private long _minWithdrawalAmount = 1_000_000; private long _minWithdrawalAmount = 1_000_000;
private List<WalletWithdrawal> _withdrawals = new(); private List<WalletWithdrawal> _withdrawals = new();
private List<CommissionPayoutDto> _availablePayouts = new();
private string _statusFilter = "all"; private string _statusFilter = "all";
private bool _isLoading = true; private bool _isLoading = true;
private bool _isSubmittingWithdrawal; private bool _isSubmittingWithdrawal;
private long _withdrawPayoutId; private CommissionPayoutDto? _selectedPayout;
private WithdrawalMethodClient _withdrawMethod = WithdrawalMethodClient.Cash; private WithdrawalMethodClient _withdrawMethod = WithdrawalMethodClient.Cash;
private string? _withdrawIban; private string? _withdrawIban;
@@ -26,6 +29,7 @@ public partial class WithdrawalRequests : ComponentBase
try try
{ {
_withdrawals = await WalletService.GetWithdrawalsAsync(); _withdrawals = await WalletService.GetWithdrawalsAsync();
_availablePayouts = await CommissionService.GetWithdrawablePayoutsAsync();
var settings = await WalletService.GetWithdrawalSettingsAsync(); var settings = await WalletService.GetWithdrawalSettingsAsync();
if (settings.MinWithdrawalAmount > 0) if (settings.MinWithdrawalAmount > 0)
_minWithdrawalAmount = settings.MinWithdrawalAmount; _minWithdrawalAmount = settings.MinWithdrawalAmount;
@@ -40,9 +44,9 @@ public partial class WithdrawalRequests : ComponentBase
private async Task SubmitWithdrawal() private async Task SubmitWithdrawal()
{ {
if (_withdrawPayoutId <= 0) if (_selectedPayout == null)
{ {
Snackbar.Add("شناسه واریز (PayoutId) الزامی است.", Severity.Warning); Snackbar.Add("لطفاً یک واریز را انتخاب کنید.", Severity.Warning);
return; return;
} }
if (_withdrawMethod == WithdrawalMethodClient.Cash && string.IsNullOrWhiteSpace(_withdrawIban)) if (_withdrawMethod == WithdrawalMethodClient.Cash && string.IsNullOrWhiteSpace(_withdrawIban))
@@ -54,14 +58,14 @@ public partial class WithdrawalRequests : ComponentBase
try try
{ {
_isSubmittingWithdrawal = true; _isSubmittingWithdrawal = true;
await WalletService.RequestWithdrawalAsync(_withdrawPayoutId, _withdrawMethod, _withdrawIban); await WalletService.RequestWithdrawalAsync(_selectedPayout.Id, _withdrawMethod, _withdrawIban);
Snackbar.Add("درخواست برداشت ثبت شد.", Severity.Success); Snackbar.Add("درخواست برداشت ثبت شد.", Severity.Success);
// بروزرسانی لیست // بروزرسانی لیست
await LoadData(); await LoadData();
// ریست فرم // ریست فرم
_withdrawPayoutId = 0; _selectedPayout = null;
_withdrawIban = null; _withdrawIban = null;
} }
catch (Exception ex) catch (Exception ex)
+71 -17
View File
@@ -3,37 +3,91 @@
<PageTitle>محصولات</PageTitle> <PageTitle>محصولات</PageTitle>
<MudContainer MaxWidth="MaxWidth.Large" Class="pa-2 pa-md-6 "> <MudContainer MaxWidth="MaxWidth.Large" Class="pa-2 pa-md-6">
<MudPaper Elevation="1" Class="pa-4 mb-4 rounded-lg"> <MudPaper Elevation="1" Class="pa-3 pa-md-4 mb-4 rounded-lg">
<MudGrid Spacing="2" AlignItems="AlignItems.Center"> <MudGrid Spacing="2" AlignItems="AlignItems.Center">
<MudItem xs="12" md="8"> @* ردیف اول: جستجو و دکمه‌ها *@
<MudItem xs="12" md="6">
<MudTextField @bind-Value="_query" <MudTextField @bind-Value="_query"
Placeholder="جستجو در محصولات..." Placeholder="جستجو در محصولات..."
AdornmentIcon="@Icons.Material.Filled.Search" AdornmentIcon="@Icons.Material.Filled.Search"
Adornment="Adornment.Start" Adornment="Adornment.Start"
Immediate="true" Immediate="true"
OnKeyUp="OnQueryChanged" OnKeyUp="OnQueryChanged"
Class="w-100"/> Variant="Variant.Outlined"
Margin="Margin.Dense"/>
</MudItem> </MudItem>
<MudItem xs="12" md="4" Class="d-flex justify-end flex-wrap gap-2"> <MudItem xs="12" md="6" Class="d-flex justify-start justify-md-end gap-2">
<MudButton Class="w-100-mobile" Variant="Variant.Outlined" Color="Color.Primary" <MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Primary"
StartIcon="@Icons.Material.Filled.ViewList" Href="@RouteConstants.Store.Categories"> StartIcon="@Icons.Material.Filled.Category" Href="@RouteConstants.Store.Categories">
دسته‌بندی‌ها دسته‌بندی‌ها
</MudButton> </MudButton>
<MudButton Class="w-100-mobile" Variant="Variant.Filled" Color="Color.Primary" <MudButton Size="Size.Small" Variant="Variant.Filled" Color="Color.Primary"
StartIcon="@Icons.Material.Filled.ShoppingCart" Href="@RouteConstants.Store.Cart"> StartIcon="@Icons.Material.Filled.ShoppingCart" Href="@RouteConstants.Store.Cart">
سبد خرید (@Cart.Count) سبد خرید
@if (Cart.Count > 0)
{
<MudBadge Content="@Cart.Count" Color="Color.Error" Overlap="true" Class="ms-2"/>
}
</MudButton> </MudButton>
</MudItem> </MudItem>
@* ردیف دوم: فیلترها و مرتب‌سازی *@
<MudItem xs="12">
<MudDivider Class="my-2"/>
</MudItem>
<MudItem xs="6" sm="4" md="3">
<MudSelect T="ProductSortOption" @bind-Value="_sortOption"
@bind-Value:after="OnSortChanged"
Label="مرتب‌سازی"
Variant="Variant.Outlined"
Margin="Margin.Dense"
AnchorOrigin="Origin.BottomCenter"
AdornmentIcon="@Icons.Material.Filled.Sort">
<MudSelectItem Value="ProductSortOption.PriceDesc">
<div class="d-flex align-center gap-2">
<MudIcon Icon="@Icons.Material.Filled.ArrowDownward" Size="Size.Small"/>
گران‌ترین
</div>
</MudSelectItem>
<MudSelectItem Value="ProductSortOption.PriceAsc">
<div class="d-flex align-center gap-2">
<MudIcon Icon="@Icons.Material.Filled.ArrowUpward" Size="Size.Small"/>
ارزان‌ترین
</div>
</MudSelectItem>
<MudSelectItem Value="ProductSortOption.Newest">
<div class="d-flex align-center gap-2">
<MudIcon Icon="@Icons.Material.Filled.NewReleases" Size="Size.Small"/>
جدیدترین
</div>
</MudSelectItem>
<MudSelectItem Value="ProductSortOption.Title">
<div class="d-flex align-center gap-2">
<MudIcon Icon="@Icons.Material.Filled.SortByAlpha" Size="Size.Small"/>
الفبایی
</div>
</MudSelectItem>
</MudSelect>
</MudItem>
<MudItem xs="6" sm="8" md="9" Class="d-flex align-center">
@if (_activeCategoryId.HasValue)
{
<MudChip T="string" Color="Color.Info" Variant="Variant.Filled" Size="Size.Small"
Icon="@Icons.Material.Filled.FilterAlt"
Closeable="true" OnClose="ClearCategoryFilter">
@(_activeCategoryTitle ?? $"دسته‌بندی #{_activeCategoryId}")
</MudChip>
}
else
{
<MudText Typo="Typo.body2" Class="mud-text-secondary">
<MudIcon Icon="@Icons.Material.Filled.Inventory2" Size="Size.Small" Class="me-1"/>
@(_products.Count) محصول
</MudText>
}
</MudItem>
</MudGrid> </MudGrid>
@if (_activeCategoryId.HasValue)
{
<MudStack Spacing="1" Class="mt-3">
<MudChip T="string" Color="Color.Info" Variant="Variant.Filled" Closeable="true" OnClose="ClearCategoryFilter">
@(_activeCategoryTitle ?? $"دسته‌بندی #{_activeCategoryId}")
</MudChip>
</MudStack>
}
</MudPaper> </MudPaper>
@if (_loading) @if (_loading)
@@ -7,6 +7,14 @@ using FrontOffice.Main.Utilities;
namespace FrontOffice.Main.Pages.Store; namespace FrontOffice.Main.Pages.Store;
public enum ProductSortOption
{
PriceDesc, // گران‌ترین (پیش‌فرض)
PriceAsc, // ارزان‌ترین
Newest, // جدیدترین
Title // الفبایی
}
public partial class Products : ComponentBase, IDisposable public partial class Products : ComponentBase, IDisposable
{ {
[Inject] private ProductService ProductService { get; set; } = default!; [Inject] private ProductService ProductService { get; set; } = default!;
@@ -20,6 +28,8 @@ public partial class Products : ComponentBase, IDisposable
private long? _activeCategoryId; private long? _activeCategoryId;
private string? _activeCategoryTitle; private string? _activeCategoryTitle;
private ProductSortOption _sortOption = ProductSortOption.PriceDesc; // پیش‌فرض: گران‌ترین
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
// لود سبد خرید (فقط اگر کاربر لاگین کرده باشد) // لود سبد خرید (فقط اگر کاربر لاگین کرده باشد)
@@ -43,13 +53,31 @@ public partial class Products : ComponentBase, IDisposable
{ {
_loading = true; _loading = true;
UpdateCategoryFilterFromUri(); UpdateCategoryFilterFromUri();
_products = await ProductService.GetProductsAsync(_query, _activeCategoryId); var sortBy = GetSortByValue();
_products = await ProductService.GetProductsAsync(_query, _activeCategoryId, sortBy);
_activeCategoryTitle = _activeCategoryId is { } categoryId _activeCategoryTitle = _activeCategoryId is { } categoryId
? (await CategoryService.GetByIdAsync(categoryId))?.Title ? (await CategoryService.GetByIdAsync(categoryId))?.Title
: null; : null;
_loading = false; _loading = false;
} }
private string GetSortByValue()
{
return _sortOption switch
{
ProductSortOption.PriceDesc => "price desc",
ProductSortOption.PriceAsc => "price asc",
ProductSortOption.Newest => "id desc",
ProductSortOption.Title => "title asc",
_ => "price desc"
};
}
private async Task OnSortChanged()
{
await Load();
}
private async Task OnQueryChanged(KeyboardEventArgs _) private async Task OnQueryChanged(KeyboardEventArgs _)
{ {
await Load(); await Load();
+24 -1
View File
@@ -4,7 +4,7 @@
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html> <!DOCTYPE html>
<html lang="fa"> <html lang="fa" dir="rtl">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
@@ -106,6 +106,29 @@
// اجرای اولیه (حتی اگر کاربر اسکرول نکرده) // اجرای اولیه (حتی اگر کاربر اسکرول نکرده)
requestAnimationFrame(update); requestAnimationFrame(update);
} }
// پاک کردن کش مرورگر (Cache Storage و Service Worker)
window.clearBrowserCache = async function() {
// پاک کردن Cache Storage (Service Worker cache)
if ('caches' in window) {
const cacheNames = await caches.keys();
await Promise.all(
cacheNames.map(cacheName => caches.delete(cacheName))
);
console.log('Cache Storage cleared:', cacheNames.length, 'caches deleted');
}
// پاک کردن Service Worker registration
if ('serviceWorker' in navigator) {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(
registrations.map(registration => registration.unregister())
);
console.log('Service Workers unregistered:', registrations.length);
}
return true;
};
</script> </script>
</body> </body>
</html> </html>
+42 -3
View File
@@ -63,11 +63,32 @@
@* </MudBadge> *@ @* </MudBadge> *@
<MudIconButton Icon="@Icons.Material.Filled.ShoppingCart" Color="@(_cartCount > 0?Color.Success:Color.Inherit)" <MudIconButton Icon="@Icons.Material.Filled.ShoppingCart" Color="@(_cartCount > 0?Color.Success:Color.Inherit)"
Href="@(RouteConstants.Store.Cart)" /> Href="@(RouteConstants.Store.Cart)" />
@* دکمه بروزرسانی *@
@if (_hasUpdate)
{
<MudBadge Dot="true" Color="Color.Error" Overlap="true" Bordered="true">
<MudIconButton Icon="@Icons.Material.Filled.SystemUpdateAlt"
Color="Color.Warning"
OnClick="OpenUpdateDialog"
Title="بروزرسانی موجود است"/>
</MudBadge>
}
<MudMenu Icon="@Icons.Material.Filled.Person" Color="Color.Inherit" Size="Size.Medium"> <MudMenu Icon="@Icons.Material.Filled.Person" Color="Color.Inherit" Size="Size.Medium">
<MudMenuItem OnClick="NavigateToProfile" Disabled="@(!AuthService.IsCompleteRegister())"> <MudMenuItem OnClick="NavigateToProfile" Disabled="@(!AuthService.IsCompleteRegister())">
پروفایل پروفایل
</MudMenuItem> </MudMenuItem>
<MudDivider/> <MudDivider/>
@if (_hasUpdate)
{
<MudMenuItem OnClick="OpenUpdateDialog" IconColor="Color.Warning" Icon="@Icons.Material.Filled.SystemUpdateAlt">
<MudText Color="Color.Warning">بروزرسانی (@_newVersion)</MudText>
</MudMenuItem>
<MudDivider/>
}
<MudMenuItem OnClick="ToggleTheme" Icon="@(_isDark ? Icons.Material.Filled.LightMode : Icons.Material.Filled.DarkMode)">
@(_isDark ? "حالت روشن" : "حالت تاریک")
</MudMenuItem>
<MudDivider/>
<MudMenuItem OnClick="Logout">خروج از حساب</MudMenuItem> <MudMenuItem OnClick="Logout">خروج از حساب</MudMenuItem>
</MudMenu> </MudMenu>
} }
@@ -75,10 +96,10 @@
{ {
<MudIconButton Icon="@Icons.Material.Filled.Login" Color="Color.Inherit" <MudIconButton Icon="@Icons.Material.Filled.Login" Color="Color.Inherit"
OnClick="OpenAuthDialog"/> OnClick="OpenAuthDialog"/>
<MudIconButton OnClick="@ToggleTheme"
Icon="@(_isDark ? Icons.Material.Filled.LightMode : Icons.Material.Filled.DarkMode)"
Title="@(_isDark ? "حالت روشن" : "حالت تاریک")"/>
} }
<MudIconButton OnClick="@ToggleTheme" Edge="Edge.End"
Icon="@(_isDark ? Icons.Material.Filled.DarkMode : Icons.Material.Filled.LightMode)"/>
</div> </div>
</MudContainer> </MudContainer>
</MudAppBar> </MudAppBar>
@@ -114,6 +135,19 @@
{ {
<MudButton Href="/profile" Color="Color.Primary" OnClick="() => _drawerOpen=false">پروفایل <MudButton Href="/profile" Color="Color.Primary" OnClick="() => _drawerOpen=false">پروفایل
</MudButton> </MudButton>
@if (_hasUpdate)
{
<MudButton Variant="Variant.Filled" Color="Color.Warning"
StartIcon="@Icons.Material.Filled.SystemUpdateAlt"
OnClick="() => { _drawerOpen=false; OpenUpdateDialog(); }">
بروزرسانی (@_newVersion)
</MudButton>
}
<MudButton Variant="Variant.Text"
StartIcon="@(_isDark ? Icons.Material.Filled.LightMode : Icons.Material.Filled.DarkMode)"
OnClick="ToggleTheme">
@(_isDark ? "حالت روشن" : "حالت تاریک")
</MudButton>
<MudButton Variant="Variant.Text" Color="Color.Error" <MudButton Variant="Variant.Text" Color="Color.Error"
OnClick="() => { _drawerOpen=false; Logout(); }">خروج از حساب OnClick="() => { _drawerOpen=false; Logout(); }">خروج از حساب
</MudButton> </MudButton>
@@ -122,6 +156,11 @@
{ {
<MudButton Color="Color.Primary" OnClick="() => { _drawerOpen=false; OpenAuthDialog(); }">ورود <MudButton Color="Color.Primary" OnClick="() => { _drawerOpen=false; OpenAuthDialog(); }">ورود
</MudButton> </MudButton>
<MudButton Variant="Variant.Text"
StartIcon="@(_isDark ? Icons.Material.Filled.LightMode : Icons.Material.Filled.DarkMode)"
OnClick="ToggleTheme">
@(_isDark ? "حالت روشن" : "حالت تاریک")
</MudButton>
} }
</MudStack> </MudStack>
</MudDrawer> </MudDrawer>
@@ -17,10 +17,16 @@ public partial class MainLayout : IDisposable
private string? _email; private string? _email;
private int _cartCount; private int _cartCount;
// متغیرهای بروزرسانی
private bool _hasUpdate;
private string? _newVersion;
private VersionCheckResult? _versionCheckResult;
[Inject] private ILocalStorageService LocalStorage { get; set; } = default!; [Inject] private ILocalStorageService LocalStorage { get; set; } = default!;
[Inject] private AuthService AuthService { get; set; } = default!; [Inject] private AuthService AuthService { get; set; } = default!;
[Inject] private AuthDialogService AuthDialogService { get; set; } = default!; [Inject] private AuthDialogService AuthDialogService { get; set; } = default!;
[Inject] private CartService CartService { get; set; } = default!; [Inject] private CartService CartService { get; set; } = default!;
[Inject] private AppVersionService AppVersionService { get; set; } = default!;
private void ToggleTheme() => _isDark = !_isDark; private void ToggleTheme() => _isDark = !_isDark;
private void ToggleDrawer() => _drawerOpen = !_drawerOpen; private void ToggleDrawer() => _drawerOpen = !_drawerOpen;
@@ -42,12 +48,83 @@ public partial class MainLayout : IDisposable
await CartService.EnsureInitializedAsync(); await CartService.EnsureInitializedAsync();
CartService.OnChange += OnCartChanged; CartService.OnChange += OnCartChanged;
_cartCount = CartService.Count; _cartCount = CartService.Count;
// چک کردن بروزرسانی (بدون نمایش popup - فقط برای نشون دادن آیکون)
await CheckForUpdateSilentlyAsync();
} }
StateHasChanged(); StateHasChanged();
} }
} }
/// <summary>
/// چک کردن بروزرسانی بدون نمایش popup
/// </summary>
private async Task CheckForUpdateSilentlyAsync()
{
try
{
_versionCheckResult = await AppVersionService.CheckVersionAsync(ignoreSkipped: true);
if (_versionCheckResult.HasNewVersion && !string.IsNullOrEmpty(_versionCheckResult.NewVersion))
{
_hasUpdate = true;
_newVersion = _versionCheckResult.NewVersion;
}
}
catch
{
// در صورت خطا نادیده بگیر
}
}
/// <summary>
/// باز کردن دیالوگ بروزرسانی
/// </summary>
private async Task OpenUpdateDialog()
{
if (_versionCheckResult == null || string.IsNullOrEmpty(_versionCheckResult.NewVersion))
return;
// ثبت زمان نمایش دیالوگ
await AppVersionService.RecordDialogShownAsync();
var dialogOptions = new DialogOptions
{
BackdropClick = !_versionCheckResult.IsForceUpdate,
CloseOnEscapeKey = !_versionCheckResult.IsForceUpdate,
CloseButton = !_versionCheckResult.IsForceUpdate,
MaxWidth = MaxWidth.Small,
FullWidth = true
};
var parameters = new DialogParameters<ReleaseNotesDialog>
{
{ x => x.OldVersion, _versionCheckResult.OldVersion },
{ x => x.NewVersion, _versionCheckResult.NewVersion },
{ x => x.ReleaseNotes, _versionCheckResult.ReleaseNotes },
{ x => x.UpdateMessage, _versionCheckResult.UpdateMessage },
{ x => x.IsForceUpdate, _versionCheckResult.IsForceUpdate }
};
var dialog = await DialogService.ShowAsync<ReleaseNotesDialog>("بروزرسانی", parameters, dialogOptions);
var result = await dialog.Result;
if (result is { Canceled: false, Data: bool shouldUpdate })
{
if (shouldUpdate)
{
await AppVersionService.ApplyUpdateAsync(_versionCheckResult.NewVersion);
Navigation.NavigateTo(Navigation.Uri, forceLoad: true);
}
else
{
await AppVersionService.SkipVersionAsync(_versionCheckResult.NewVersion);
// نمایش آپدیت همچنان باقی بمونه (hasUpdate true بمونه)
}
}
}
private void OnCartChanged() private void OnCartChanged()
{ {
_cartCount = CartService.Count; _cartCount = CartService.Count;
@@ -0,0 +1,172 @@
@using FrontOffice.Main.Utilities
@using MudBlazor
<MudDialog>
<TitleContent>
<MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
@if (IsForceUpdate)
{
<MudIcon Icon="@Icons.Material.Filled.Warning" Color="Color.Warning" Size="Size.Large"/>
<MudText Typo="Typo.h6" Color="Color.Warning">بروزرسانی اجباری</MudText>
}
else
{
<MudIcon Icon="@Icons.Material.Filled.NewReleases" Color="Color.Success" Size="Size.Large"/>
<MudText Typo="Typo.h6">نسخه جدید موجود است 🎉</MudText>
}
</MudStack>
</TitleContent>
<DialogContent>
<MudStack Spacing="3">
@* اطلاعات نسخه با انیمیشن *@
<MudPaper Class="pa-4 rounded-lg" Elevation="0"
Style="">
<MudGrid Spacing="2">
<MudItem xs="6">
<MudStack AlignItems="AlignItems.Center" Spacing="1">
<MudIcon Icon="@Icons.Material.Outlined.History" Size="Size.Medium" Color="Color.Secondary"/>
<MudText Typo="Typo.caption" Color="Color.Secondary">نسخه فعلی</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined" Color="Color.Secondary">
@(OldVersion ?? "---")
</MudChip>
</MudStack>
</MudItem>
<MudItem xs="6">
<MudStack AlignItems="AlignItems.Center" Spacing="1">
<MudIcon Icon="@Icons.Material.Filled.Verified" Size="Size.Medium" Color="Color.Success"/>
<MudText Typo="Typo.caption" Color="Color.Success">نسخه جدید</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Filled" Color="Color.Success">
@NewVersion
</MudChip>
</MudStack>
</MudItem>
</MudGrid>
</MudPaper>
@* پیام آپدیت *@
@if (!string.IsNullOrWhiteSpace(UpdateMessage))
{
<MudAlert Severity="@(IsForceUpdate ? Severity.Warning : Severity.Info)"
Variant="Variant.Text"
Dense="true"
Icon="@Icons.Material.Filled.Info"
Class="rounded-lg">
@UpdateMessage
</MudAlert>
}
@* یادداشت‌های انتشار *@
@if (!string.IsNullOrWhiteSpace(ReleaseNotes))
{
<MudStack Spacing="1">
<MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
<MudIcon Icon="@Icons.Material.Filled.Article" Size="Size.Small" Color="Color.Primary"/>
<MudText Typo="Typo.subtitle2" Color="Color.Primary">تغییرات این نسخه:</MudText>
</MudStack>
<MudPaper Class="pa-3 rounded-lg release-notes-content" Elevation="0"
Style="max-height: 220px; overflow-y: auto; background-color: var(--mud-palette-background-grey); border: 1px solid var(--mud-palette-lines-default);">
@((MarkupString)ReleaseNotes)
</MudPaper>
</MudStack>
}
@if (IsForceUpdate)
{
<MudAlert Severity="Severity.Error" Variant="Variant.Filled" Dense="true" Class="rounded-lg">
<MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
<MudIcon Icon="@Icons.Material.Filled.Error" Size="Size.Small"/>
<MudText Typo="Typo.body2">
این بروزرسانی اجباری است و باید انجام شود.
</MudText>
</MudStack>
</MudAlert>
}
</MudStack>
</DialogContent>
<DialogActions>
@if (!IsForceUpdate)
{
<MudButton OnClick="OnSkipClicked"
Color="Color.Default"
Variant="Variant.Text"
Size="Size.Medium">
بعداً یادآوری کن
</MudButton>
}
<MudButton OnClick="OnUpdateClicked"
Color="@(IsForceUpdate ? Color.Warning : Color.Success)"
Variant="Variant.Filled"
Size="Size.Medium"
StartIcon="@(_isUpdating ? null : Icons.Material.Filled.SystemUpdateAlt)"
Class="px-6">
@if (_isUpdating)
{
<MudProgressCircular Size="Size.Small" Indeterminate="true" Color="Color.Surface"/>
<span class="ms-2">در حال بروزرسانی...</span>
}
else
{
<span>بروزرسانی کن!</span>
}
</MudButton>
</DialogActions>
</MudDialog>
<style>
.release-notes-content {
font-size: 0.9rem;
line-height: 1.8;
}
.release-notes-content ul, .release-notes-content ol {
padding-right: 1.5rem;
margin: 0.5rem 0;
}
.release-notes-content li {
margin-bottom: 0.3rem;
}
.release-notes-content p {
margin: 0.5rem 0;
}
</style>
@code {
[CascadingParameter]
private IMudDialogInstance MudDialog { get; set; } = default!;
[Parameter]
public string? OldVersion { get; set; }
[Parameter]
public string NewVersion { get; set; } = string.Empty;
[Parameter]
public string? ReleaseNotes { get; set; }
[Parameter]
public string? UpdateMessage { get; set; }
[Parameter]
public bool IsForceUpdate { get; set; }
private bool _isUpdating;
private async Task OnUpdateClicked()
{
_isUpdating = true;
StateHasChanged();
// کمی صبر کنیم برای UI
await Task.Delay(500);
// برگردوندن نتیجه "آپدیت"
MudDialog.Close(DialogResult.Ok(true));
}
private void OnSkipClicked()
{
// برگردوندن نتیجه "بعداً"
MudDialog.Close(DialogResult.Ok(false));
}
}
@@ -1,8 +1,50 @@
using FrontOffice.BFF.Configuration.Protobuf.Protos.AppVersion; using FrontOffice.BFF.Configuration.Protobuf.Protos.AppVersion;
using Blazored.LocalStorage; using Blazored.LocalStorage;
using Microsoft.JSInterop;
namespace FrontOffice.Main.Utilities; namespace FrontOffice.Main.Utilities;
/// <summary>
/// نتیجه بررسی نسخه اپلیکیشن
/// </summary>
public class VersionCheckResult
{
/// <summary>
/// آیا نسخه جدیدی وجود دارد
/// </summary>
public bool HasNewVersion { get; set; }
/// <summary>
/// آیا آپدیت اجباری است (force update)
/// </summary>
public bool IsForceUpdate { get; set; }
/// <summary>
/// نسخه فعلی (local)
/// </summary>
public string? OldVersion { get; set; }
/// <summary>
/// نسخه جدید (server)
/// </summary>
public string? NewVersion { get; set; }
/// <summary>
/// یادداشت‌های انتشار
/// </summary>
public string? ReleaseNotes { get; set; }
/// <summary>
/// پیام آپدیت
/// </summary>
public string? UpdateMessage { get; set; }
/// <summary>
/// آیا کش باید پاک شود
/// </summary>
public bool RequiresCacheClear { get; set; }
}
/// <summary> /// <summary>
/// سرویس مدیریت نسخه اپلیکیشن و کش /// سرویس مدیریت نسخه اپلیکیشن و کش
/// وقتی نسخه جدید منتشر بشه، این سرویس متوجه میشه و کش رو پاک می‌کنه /// وقتی نسخه جدید منتشر بشه، این سرویس متوجه میشه و کش رو پاک می‌کنه
@@ -11,31 +53,44 @@ public class AppVersionService
{ {
private readonly AppVersionContract.AppVersionContractClient _client; private readonly AppVersionContract.AppVersionContractClient _client;
private readonly ILocalStorageService _localStorage; private readonly ILocalStorageService _localStorage;
private readonly IJSRuntime _jsRuntime;
private readonly ILogger<AppVersionService> _logger; private readonly ILogger<AppVersionService> _logger;
private const string APP_NAME = "FrontOffice"; private const string APP_NAME = "KaraBazarApp";
private const string LOCAL_VERSION_KEY = "app_version"; private const string LOCAL_VERSION_KEY = "app_version";
private const string LAST_CHECK_KEY = "app_version_last_check"; private const string LAST_CHECK_KEY = "app_version_last_check";
private const string SKIPPED_VERSION_KEY = "app_version_skipped";
private const string LAST_DIALOG_SHOWN_KEY = "app_version_last_dialog_shown";
public AppVersionService( public AppVersionService(
AppVersionContract.AppVersionContractClient client, AppVersionContract.AppVersionContractClient client,
ILocalStorageService localStorage, ILocalStorageService localStorage,
IJSRuntime jsRuntime,
ILogger<AppVersionService> logger) ILogger<AppVersionService> logger)
{ {
_client = client; _client = client;
_localStorage = localStorage; _localStorage = localStorage;
_jsRuntime = jsRuntime;
_logger = logger; _logger = logger;
} }
/// <summary> /// <summary>
/// بررسی نسخه اپلیکیشن و پاک کردن کش در صورت نیاز /// بررسی نسخه اپلیکیشن و برگرداندن نتیجه
/// </summary> /// </summary>
public async Task CheckVersionAndClearCacheIfNeededAsync() /// <param name="ignoreSkipped">اگر true باشه، نسخه‌های skip شده هم نشون داده میشن (برای آیکون منو)</param>
/// <param name="forDialog">اگر true باشه، چک میکنه که یک روز از آخرین نمایش گذشته (برای popup)</param>
public async Task<VersionCheckResult> CheckVersionAsync(bool ignoreSkipped = false, bool forDialog = false)
{ {
var result = new VersionCheckResult();
try try
{ {
// دریافت نسخه فعلی از localStorage // دریافت نسخه فعلی از localStorage
var localVersion = await _localStorage.GetItemAsStringAsync(LOCAL_VERSION_KEY); var localVersion = await _localStorage.GetItemAsStringAsync(LOCAL_VERSION_KEY);
var skippedVersion = await _localStorage.GetItemAsStringAsync(SKIPPED_VERSION_KEY);
var lastDialogShown = await _localStorage.GetItemAsStringAsync(LAST_DIALOG_SHOWN_KEY);
result.OldVersion = localVersion;
// بررسی نسخه از سرور // بررسی نسخه از سرور
var response = await _client.GetAppVersionAsync(new GetAppVersionRequest var response = await _client.GetAppVersionAsync(new GetAppVersionRequest
@@ -47,32 +102,119 @@ public class AppVersionService
if (!response.Found) if (!response.Found)
{ {
_logger.LogWarning("App version not found on server for {AppName}", APP_NAME); _logger.LogWarning("App version not found on server for {AppName}", APP_NAME);
return; return result;
} }
var serverVersion = response.CurrentVersion; var serverVersion = response.CurrentVersion;
result.NewVersion = serverVersion;
result.ReleaseNotes = response.ReleaseNotes;
result.UpdateMessage = response.UpdateMessage;
result.RequiresCacheClear = response.RequiresFullCacheClear;
result.IsForceUpdate = response.RequiresUpdate; // اگر نسخه کمتر از حداقل باشه
// اگر نسخه جدید باشه یا پاک کردن کش لازم باشه // آیا نسخه جدید داریم؟
if (localVersion != serverVersion || response.RequiresFullCacheClear) if (localVersion != serverVersion)
{ {
result.HasNewVersion = true;
// اگر این نسخه رو قبلاً skip کرده و force نیست
if (!result.IsForceUpdate && skippedVersion == serverVersion && !ignoreSkipped)
{
// برای popup: چک کن یک روز گذشته یا نه
if (forDialog)
{
var oneDayPassed = await HasOneDayPassedSinceLastDialogAsync(lastDialogShown);
if (!oneDayPassed)
{
result.HasNewVersion = false;
}
// اگه یک روز گذشته، HasNewVersion = true میمونه
}
else
{
result.HasNewVersion = false;
}
}
_logger.LogInformation( _logger.LogInformation(
"New version detected: {OldVersion} -> {NewVersion}, CacheClear: {CacheClear}", "Version check: {OldVersion} -> {NewVersion}, Force: {Force}, Skipped: {Skipped}",
localVersion ?? "null", serverVersion, response.RequiresFullCacheClear); localVersion ?? "null", serverVersion, result.IsForceUpdate, skippedVersion);
// پاک کردن کش
await ClearAllCacheAsync();
// ذخیره نسخه جدید
await _localStorage.SetItemAsStringAsync(LOCAL_VERSION_KEY, serverVersion);
await _localStorage.SetItemAsStringAsync(LAST_CHECK_KEY, DateTime.UtcNow.ToString("O"));
_logger.LogInformation("Cache cleared and version updated to {Version}", serverVersion);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error checking app version"); _logger.LogError(ex, "Error checking app version");
} }
return result;
}
/// <summary>
/// چک کردن اینکه یک روز از آخرین نمایش دیالوگ گذشته یا نه
/// </summary>
private async Task<bool> HasOneDayPassedSinceLastDialogAsync(string? lastDialogShown)
{
if (string.IsNullOrEmpty(lastDialogShown))
return true; // اگه هیچوقت نشون نداده، نشون بده
if (DateTime.TryParse(lastDialogShown, out var lastShown))
{
return DateTime.UtcNow.Subtract(lastShown).TotalDays >= 1;
}
return true;
}
/// <summary>
/// ثبت زمان نمایش دیالوگ
/// </summary>
public async Task RecordDialogShownAsync()
{
await _localStorage.SetItemAsStringAsync(LAST_DIALOG_SHOWN_KEY, DateTime.UtcNow.ToString("O"));
}
/// <summary>
/// اعمال آپدیت - پاک کردن کش و ذخیره نسخه جدید
/// </summary>
public async Task ApplyUpdateAsync(string newVersion)
{
try
{
_logger.LogInformation("Applying update to version {Version}", newVersion);
// پاک کردن کش
await ClearAllCacheAsync();
// ذخیره نسخه جدید
await _localStorage.SetItemAsStringAsync(LOCAL_VERSION_KEY, newVersion);
await _localStorage.SetItemAsStringAsync(LAST_CHECK_KEY, DateTime.UtcNow.ToString("O"));
// پاک کردن نسخه skip شده
await _localStorage.RemoveItemAsync(SKIPPED_VERSION_KEY);
_logger.LogInformation("Update applied successfully to {Version}", newVersion);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error applying update");
throw;
}
}
/// <summary>
/// Skip کردن این نسخه (بعداً)
/// </summary>
public async Task SkipVersionAsync(string version)
{
try
{
await _localStorage.SetItemAsStringAsync(SKIPPED_VERSION_KEY, version);
_logger.LogInformation("Version {Version} skipped by user", version);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error skipping version");
}
} }
/// <summary> /// <summary>
@@ -82,33 +224,14 @@ public class AppVersionService
{ {
try try
{ {
// لیست کلیدهایی که باید حفظ بشن (مثل توکن و اطلاعات کاربر) // پاک کردن کش مرورگر (Cache Storage و Service Worker)
var keysToKeep = new HashSet<string> await _jsRuntime.InvokeVoidAsync("clearBrowserCache");
{
"access_token",
"refresh_token",
"user_info",
"user_roles"
};
// دریافت همه کلیدها _logger.LogInformation("Browser cache cleared successfully");
var allKeys = await _localStorage.KeysAsync();
// پاک کردن کلیدهایی که در لیست حفظ نیستن
foreach (var key in allKeys)
{
if (!keysToKeep.Contains(key) && key != LOCAL_VERSION_KEY)
{
await _localStorage.RemoveItemAsync(key);
}
}
_logger.LogInformation("Local storage cache cleared, {Count} keys removed",
allKeys.Count() - keysToKeep.Count);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error clearing cache"); _logger.LogError(ex, "Error clearing browser cache");
} }
} }
@@ -13,9 +13,31 @@ public class CommissionPayoutDto
public int BalancesEarned { get; set; } public int BalancesEarned { get; set; }
public long TotalAmount { get; set; } public long TotalAmount { get; set; }
public string AmountFormatted { get; set; } = string.Empty; public string AmountFormatted { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty; public int Status { get; set; }
public string StatusBadgeColor { get; set; } = string.Empty;
public string DatePersian { get; set; } = string.Empty; public string DatePersian { get; set; } = string.Empty;
// Computed properties for UI
public string StatusText => Status switch
{
0 => "در انتظار",
1 => "پرداخت شده",
2 => "درخواست برداشت",
3 => "برداشت شده",
4 => "شکست خورده",
5 => "لغو شده",
_ => "نامشخص"
};
public string StatusColor => Status switch
{
0 => "warning",
1 => "success",
2 => "info",
3 => "success",
4 => "error",
5 => "default",
_ => "default"
};
} }
/// <summary> /// <summary>
@@ -98,10 +98,12 @@ public class CommissionService
{ {
request.Status = status switch request.Status = status switch
{ {
"Pending" or "ایجاد شده" => 0, "Pending" or "در انتظار" or "Created" or "ایجاد شده" => 0,
"Calculated" or "محاسبه شده" => 1, "Paid" or "پرداخت شده" => 1,
"Paid" or "پرداخت شده" => 2, "WithdrawalRequested" or "درخواست برداشت" => 2,
"Withdrawn" or "برداشت شده" => 3, "Withdrawn" or "برداشت شده" => 3,
"PaymentFailed" or "شکست خورده" => 4,
"Cancelled" or "لغو شده" => 5,
_ => null _ => null
}; };
} }
@@ -119,7 +121,6 @@ public class CommissionService
TotalAmount = p.TotalAmount, TotalAmount = p.TotalAmount,
AmountFormatted = p.AmountFormatted, AmountFormatted = p.AmountFormatted,
Status = p.Status, Status = p.Status,
StatusBadgeColor = p.StatusBadgeColor,
DatePersian = p.DatePersian DatePersian = p.DatePersian
}).ToList(), }).ToList(),
TotalCount = (int)(response.MetaData?.TotalCount ?? 0), TotalCount = (int)(response.MetaData?.TotalCount ?? 0),
@@ -191,6 +192,45 @@ public class CommissionService
#region Helper Methods #region Helper Methods
/// <summary>
/// Get payouts that are eligible for withdrawal (all statuses except Withdrawn=3)
/// </summary>
public async Task<List<CommissionPayoutDto>> GetWithdrawablePayoutsAsync()
{
try
{
// Get all payouts that are not yet withdrawn
// We'll get all and filter out Withdrawn (status=3) on client side
var request = new GetMyCommissionPayoutsRequest
{
PageNumber = 1,
PageSize = 100
// No status filter - get all
};
var response = await _client.GetMyCommissionPayoutsAsync(request);
// Filter: exclude already withdrawn (status=3) and withdrawal requested (status=2)
return response.Payouts
.Where(p => p.Status != 2 && p.Status != 3)
.Select(p => new CommissionPayoutDto
{
Id = p.Id,
WeekDefinitionId = p.WeekDefinitionId,
WeekDisplayName = p.WeekDisplayName,
BalancesEarned = p.BalancesEarned,
TotalAmount = p.TotalAmount,
AmountFormatted = p.AmountFormatted,
Status = p.Status,
DatePersian = p.DatePersian
}).ToList();
}
catch
{
return new List<CommissionPayoutDto>();
}
}
private static WeeklyBalanceDto CreateEmptyWeeklyBalance() private static WeeklyBalanceDto CreateEmptyWeeklyBalance()
{ {
return new WeeklyBalanceDto return new WeeklyBalanceDto
@@ -58,7 +58,7 @@ public class ProductService
_client = client; _client = client;
} }
public async Task<List<Product>> GetProductsAsync(string? query = null, long? categoryId = null) public async Task<List<Product>> GetProductsAsync(string? query = null, long? categoryId = null, string? sortBy = null)
{ {
try try
{ {
@@ -75,7 +75,12 @@ public class ProductService
if (categoryId is { } value) if (categoryId is { } value)
{ {
request.Filter.CategoryId = value ; request.Filter.CategoryId = value;
}
if (!string.IsNullOrEmpty(sortBy))
{
request.SortBy = sortBy;
} }
var resp = await _client.GetAllProductsByFilterAsync(request); var resp = await _client.GetAllProductsByFilterAsync(request);
@@ -0,0 +1,18 @@
{
"GwUrl": "https://fogw.kbs2.ir",
"DownloadUrl": "https://dl.afrino.co",
"EncryptionSettings": {
"Key": "kmcQ3XTmH4mrdh8VHziuscyf8LLYjG//Kyni81nH/0E=",
"IV": "1wyF3Tt142MOkCpIyCxh/g=="
},
"SignalR": {
"HubPath": "/hubs/token-relay"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
@@ -0,0 +1,18 @@
{
"GwUrl": "https://frontoffice-bff.foursat.afrino.co",
"DownloadUrl": "https://dl.afrino.co",
"EncryptionSettings": {
"Key": "kmcQ3XTmH4mrdh8VHziuscyf8LLYjG//Kyni81nH/0E=",
"IV": "1wyF3Tt142MOkCpIyCxh/g=="
},
"SignalR": {
"HubPath": "/hubs/token-relay"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"GwUrl": "https://fogw.kbs2.ir", "GwUrl": "https://frontoffice-bff.foursat.afrino.co",
"DownloadUrl": "https://dl.afrino.co", "DownloadUrl": "https://dl.afrino.co",
"EncryptionSettings": { "EncryptionSettings": {
"Key": "kmcQ3XTmH4mrdh8VHziuscyf8LLYjG//Kyni81nH/0E=", "Key": "kmcQ3XTmH4mrdh8VHziuscyf8LLYjG//Kyni81nH/0E=",
@@ -49,6 +49,8 @@ html, body {
font-weight: 400; font-weight: 400;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
direction: rtl;
text-align: right;
} }
/* Apply Vazir to common Mud components */ /* Apply Vazir to common Mud components */
@@ -27,7 +27,7 @@
var doc = iframe.contentDocument || iframe.contentWindow.document; var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open(); doc.open();
doc.write("<!DOCTYPE html><html lang='fa'><head><meta charset='utf-8'>"+ doc.write("<!DOCTYPE html><html lang='fa' dir='rtl'><head><meta charset='utf-8'>"+
"<title>"+ title +"</title>"+ "<title>"+ title +"</title>"+
"<link rel='stylesheet' href='/_content/MudBlazor/MudBlazor.min.css'>"+ "<link rel='stylesheet' href='/_content/MudBlazor/MudBlazor.min.css'>"+
"<link rel='stylesheet' href='/css/site.css'>"+ "<link rel='stylesheet' href='/css/site.css'>"+