Implementato controllo conessione dispositivo e servizi. Completata pagination commesse e attività per cliente

This commit is contained in:
2025-09-08 10:24:50 +02:00
parent 014e2ffc41
commit 82d268d9f8
23 changed files with 530 additions and 139 deletions

View File

@@ -26,7 +26,7 @@ public class ManageDataService(
whereCond ??= new WhereCondContact(); whereCond ??= new WhereCondContact();
whereCond.OnlyContact = true; whereCond.OnlyContact = true;
if (networkService.IsNetworkAvailable()) if (networkService.ConnectionAvailable)
{ {
var response = await integryApiService.RetrieveAnagClie( var response = await integryApiService.RetrieveAnagClie(
new CRMAnagRequestDTO new CRMAnagRequestDTO
@@ -58,7 +58,7 @@ public class ManageDataService(
whereCond ??= new WhereCondContact(); whereCond ??= new WhereCondContact();
whereCond.OnlyContact = true; whereCond.OnlyContact = true;
if (networkService.IsNetworkAvailable()) if (networkService.ConnectionAvailable)
{ {
var response = await integryApiService.RetrieveProspect( var response = await integryApiService.RetrieveProspect(
new CRMProspectRequestDTO new CRMProspectRequestDTO
@@ -88,7 +88,7 @@ public class ManageDataService(
List<PtbPros>? prospectList; List<PtbPros>? prospectList;
whereCond ??= new WhereCondContact(); whereCond ??= new WhereCondContact();
if (networkService.IsNetworkAvailable()) if (networkService.ConnectionAvailable)
{ {
var clienti = await integryApiService.RetrieveAnagClie( var clienti = await integryApiService.RetrieveAnagClie(
new CRMAnagRequestDTO new CRMAnagRequestDTO
@@ -160,7 +160,7 @@ public class ManageDataService(
{ {
List<StbActivity>? activities; List<StbActivity>? activities;
if (networkService.IsNetworkAvailable() && !useLocalDb) if (networkService.ConnectionAvailable && !useLocalDb)
{ {
activities = await integryApiService.RetrieveActivity( activities = await integryApiService.RetrieveActivity(
new CRMRetrieveActivityRequestDTO new CRMRetrieveActivityRequestDTO

View File

@@ -4,9 +4,11 @@ namespace salesbook.Maui.Core.Services;
public class NetworkService : INetworkService public class NetworkService : INetworkService
{ {
public bool ConnectionAvailable { get; set; }
public bool IsNetworkAvailable() public bool IsNetworkAvailable()
{ {
return false; //return false;
return Connectivity.Current.NetworkAccess == NetworkAccess.Internet; return Connectivity.Current.NetworkAccess == NetworkAccess.Internet;
} }

View File

@@ -54,7 +54,6 @@ namespace salesbook.Maui
builder.Services.AddScoped<AuthenticationStateProvider>(provider => builder.Services.AddScoped<AuthenticationStateProvider>(provider =>
provider.GetRequiredService<AppAuthenticationStateProvider>()); provider.GetRequiredService<AppAuthenticationStateProvider>());
builder.Services.AddScoped<INetworkService, NetworkService>();
builder.Services.AddScoped<IIntegryApiService, IntegryApiService>(); builder.Services.AddScoped<IIntegryApiService, IntegryApiService>();
builder.Services.AddScoped<ISyncDbService, SyncDbService>(); builder.Services.AddScoped<ISyncDbService, SyncDbService>();
builder.Services.AddScoped<IManageDataService, ManageDataService>(); builder.Services.AddScoped<IManageDataService, ManageDataService>();
@@ -80,6 +79,7 @@ namespace salesbook.Maui
builder.Services.AddSingleton<IFormFactor, FormFactor>(); builder.Services.AddSingleton<IFormFactor, FormFactor>();
builder.Services.AddSingleton<IAttachedService, AttachedService>(); builder.Services.AddSingleton<IAttachedService, AttachedService>();
builder.Services.AddSingleton<INetworkService, NetworkService>();
builder.Services.AddSingleton<LocalDbService>(); builder.Services.AddSingleton<LocalDbService>();
return builder.Build(); return builder.Build();

View File

@@ -1,10 +1,11 @@
@using System.Globalization @using System.Globalization
@using CommunityToolkit.Mvvm.Messaging @using salesbook.Shared.Core.Interface
@using salesbook.Shared.Core.Messages.Back @using salesbook.Shared.Core.Messages.Back
@inherits LayoutComponentBase @inherits LayoutComponentBase
@inject IJSRuntime JS @inject IJSRuntime JS
@inject IMessenger Messenger
@inject BackNavigationService BackService @inject BackNavigationService BackService
@inject INetworkService NetworkService
@inject IIntegryApiService IntegryApiService
<MudThemeProvider Theme="_currentTheme" @ref="@_mudThemeProvider" @bind-IsDarkMode="@IsDarkMode" /> <MudThemeProvider Theme="_currentTheme" @ref="@_mudThemeProvider" @bind-IsDarkMode="@IsDarkMode" />
<MudPopoverProvider/> <MudPopoverProvider/>
@@ -14,12 +15,32 @@
<div class="page"> <div class="page">
<NavMenu/> <NavMenu/>
<div class="Connection @(ShowWarning ? "Show" : "Hide") @(IsNetworkAvailable? ServicesIsDown ? "ServicesIsDown" : "SystemOk" : "NetworkKo")">
@if (IsNetworkAvailable)
{
if(ServicesIsDown)
{
<i class="ri-cloud-off-fill"></i>
<span>Servizi offline</span>
}
else
{
<i class="ri-cloud-fill"></i>
<span>Online</span>
}
}
else
{
<i class="ri-wifi-off-line"></i>
<span>Nessuna connessione</span>
}
</div>
<main> <main>
<article> <article>
@Body @Body
</article> </article>
</main> </main>
</div> </div>
@code { @code {
@@ -27,6 +48,50 @@
private bool IsDarkMode { get; set; } private bool IsDarkMode { get; set; }
private string _mainContentClass = ""; private string _mainContentClass = "";
//Connection state
private bool FirstCheck { get; set; } = true;
private bool _isNetworkAvailable;
private bool _servicesIsDown;
private bool _showWarning;
private DateTime _lastApiCheck = DateTime.MinValue;
private int _delaySeconds = 3;
private CancellationTokenSource? _cts;
private bool ServicesIsDown
{
get => _servicesIsDown;
set
{
if (_servicesIsDown == value) return;
_servicesIsDown = value;
StateHasChanged();
}
}
private bool IsNetworkAvailable
{
get => _isNetworkAvailable;
set
{
if (_isNetworkAvailable == value) return;
_isNetworkAvailable = value;
StateHasChanged();
}
}
private bool ShowWarning
{
get => _showWarning;
set
{
if (_showWarning == value) return;
_showWarning = value;
StateHasChanged();
}
}
private readonly MudTheme _currentTheme = new() private readonly MudTheme _currentTheme = new()
{ {
PaletteLight = new PaletteLight() PaletteLight = new PaletteLight()
@@ -81,6 +146,9 @@
protected override void OnInitialized() protected override void OnInitialized()
{ {
_cts = new CancellationTokenSource();
_ = CheckConnectionState(_cts.Token);
BackService.OnHardwareBack += async () => { await JS.InvokeVoidAsync("goBack"); }; BackService.OnHardwareBack += async () => { await JS.InvokeVoidAsync("goBack"); };
var culture = new CultureInfo("it-IT", false); var culture = new CultureInfo("it-IT", false);
@@ -89,4 +157,40 @@
CultureInfo.CurrentUICulture = culture; CultureInfo.CurrentUICulture = culture;
} }
private Task CheckConnectionState(CancellationToken token)
{
return Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
var isNetworkAvailable = NetworkService.IsNetworkAvailable();
var servicesDown = ServicesIsDown;
if (isNetworkAvailable && (DateTime.UtcNow - _lastApiCheck).TotalSeconds >= _delaySeconds)
{
servicesDown = !await IntegryApiService.SystemOk();
_lastApiCheck = DateTime.UtcNow;
}
await InvokeAsync(async () =>
{
IsNetworkAvailable = isNetworkAvailable;
ServicesIsDown = servicesDown;
await Task.Delay(1500, token);
ShowWarning = !(IsNetworkAvailable && !ServicesIsDown);
NetworkService.ConnectionAvailable = !ShowWarning;
});
await Task.Delay(500, token);
}
}, token);
}
public void Dispose()
{
_cts?.Cancel();
_cts?.Dispose();
}
} }

View File

@@ -78,7 +78,7 @@ else
{ {
<div class="contentFlex"> <div class="contentFlex">
<Virtualize Items="ActivityList" Context="activity"> <Virtualize Items="ActivityList" Context="activity">
<ActivityCard Activity="activity" /> <ActivityCard ShowDate="true" Activity="activity" />
</Virtualize> </Virtualize>
</div> </div>
} }
@@ -148,7 +148,10 @@ else
await Task.Run(async () => await Task.Run(async () =>
{ {
var activities = await IntegryApiService.RetrieveActivity(new CRMRetrieveActivityRequestDTO { CodJcom = CodJcom }); var activities = await IntegryApiService.RetrieveActivity(new CRMRetrieveActivityRequestDTO { CodJcom = CodJcom });
ActivityList = Mapper.Map<List<ActivityDTO>>(activities); ActivityList = Mapper.Map<List<ActivityDTO>>(activities)
.OrderBy(x =>
(x.EffectiveTime ?? x.EstimatedTime) ?? x.DataInsAct
).ToList();
}); });
ActivityIsLoading = false; ActivityIsLoading = false;

View File

@@ -15,7 +15,7 @@
{ {
var lastSyncDate = LocalStorage.Get<DateTime>("last-sync"); var lastSyncDate = LocalStorage.Get<DateTime>("last-sync");
if (!FormFactor.IsWeb() && NetworkService.IsNetworkAvailable() && lastSyncDate.Equals(DateTime.MinValue)) if (!FormFactor.IsWeb() && NetworkService.ConnectionAvailable && lastSyncDate.Equals(DateTime.MinValue))
{ {
NavigationManager.NavigateTo("/sync"); NavigationManager.NavigateTo("/sync");
return; return;

View File

@@ -1,8 +1,10 @@
@page "/login" @page "/login"
@using salesbook.Shared.Components.Layout.Spinner @using salesbook.Shared.Components.Layout.Spinner
@using salesbook.Shared.Core.Interface
@using salesbook.Shared.Core.Services @using salesbook.Shared.Core.Services
@inject IUserAccountService UserAccountService @inject IUserAccountService UserAccountService
@inject AppAuthenticationStateProvider AuthenticationStateProvider @inject AppAuthenticationStateProvider AuthenticationStateProvider
@inject INetworkService NetworkService
@if (Spinner) @if (Spinner)
{ {
@@ -26,7 +28,7 @@ else
<MudTextField @bind-Value="UserData.CodHash" Label="Profilo azienda" Variant="Variant.Outlined"/> <MudTextField @bind-Value="UserData.CodHash" Label="Profilo azienda" Variant="Variant.Outlined"/>
</div> </div>
<MudButton OnClick="SignInUser" Color="Color.Primary" Variant="Variant.Filled">Login</MudButton> <MudButton Disabled="@(!NetworkService.ConnectionAvailable)" OnClick="SignInUser" Color="Color.Primary" Variant="Variant.Filled">Login</MudButton>
@if (_attemptFailed) @if (_attemptFailed)
{ {
<MudAlert Class="my-3" Dense="true" Severity="Severity.Error" Variant="Variant.Filled">@ErrorMessage</MudAlert> <MudAlert Class="my-3" Dense="true" Severity="Severity.Error" Variant="Variant.Filled">@ErrorMessage</MudAlert>

View File

@@ -39,7 +39,7 @@
<div> <div>
<span class="info-title">Status</span> <span class="info-title">Status</span>
@if (NetworkService.IsNetworkAvailable()) @if (NetworkService.ConnectionAvailable)
{ {
<div class="status online"> <div class="status online">
<i class="ri-wifi-line"></i> <i class="ri-wifi-line"></i>
@@ -129,7 +129,7 @@
{ {
await Task.Run(() => await Task.Run(() =>
{ {
Unavailable = FormFactor.IsWeb() || !NetworkService.IsNetworkAvailable(); Unavailable = FormFactor.IsWeb() || !NetworkService.ConnectionAvailable;
LastSync = LocalStorage.Get<DateTime>("last-sync"); LastSync = LocalStorage.Get<DateTime>("last-sync");
}); });

View File

@@ -7,6 +7,7 @@
@using salesbook.Shared.Components.Layout.Spinner @using salesbook.Shared.Components.Layout.Spinner
@using salesbook.Shared.Core.Dto @using salesbook.Shared.Core.Dto
@using salesbook.Shared.Components.SingleElements @using salesbook.Shared.Components.SingleElements
@using salesbook.Shared.Core.Dto.Activity
@using salesbook.Shared.Core.Dto.JobProgress @using salesbook.Shared.Core.Dto.JobProgress
@using salesbook.Shared.Core.Dto.PageState @using salesbook.Shared.Core.Dto.PageState
@implements IAsyncDisposable @implements IAsyncDisposable
@@ -93,6 +94,7 @@ else
<input type="radio" class="tab-toggle" name="tab-toggle" id="tab1" checked="@(ActiveTab == 0)"> <input type="radio" class="tab-toggle" name="tab-toggle" id="tab1" checked="@(ActiveTab == 0)">
<input type="radio" class="tab-toggle" name="tab-toggle" id="tab2" checked="@(ActiveTab == 1)"> <input type="radio" class="tab-toggle" name="tab-toggle" id="tab2" checked="@(ActiveTab == 1)">
<input type="radio" class="tab-toggle" name="tab-toggle" id="tab3" checked="@(ActiveTab == 2)">
<div class="box"> <div class="box">
<ul class="tab-list"> <ul class="tab-list">
@@ -102,6 +104,9 @@ else
<li class="tab-item"> <li class="tab-item">
<label class="tab-trigger" for="tab2" @onclick="() => SwitchTab(1)">Commesse</label> <label class="tab-trigger" for="tab2" @onclick="() => SwitchTab(1)">Commesse</label>
</li> </li>
<li class="tab-item">
<label class="tab-trigger" for="tab3" @onclick="() => SwitchTab(2)">Attivit<69></label>
</li>
</ul> </ul>
</div> </div>
@@ -150,8 +155,8 @@ else
<MudTextField T="string?" <MudTextField T="string?"
Placeholder="Cerca..." Placeholder="Cerca..."
Variant="Variant.Text" Variant="Variant.Text"
@bind-Value="SearchTerm" @bind-Value="SearchTermCommesse"
OnDebounceIntervalElapsed="() => ApplyFilters()" OnDebounceIntervalElapsed="() => ApplyFiltersCommesse()"
DebounceInterval="500" /> DebounceInterval="500" />
</div> </div>
@@ -179,46 +184,86 @@ else
</div> </div>
} }
@if (TotalPages > 1) @if (TotalPagesCommesse > 1)
{ {
<div class="custom-pagination"> <div class="custom-pagination">
<MudPagination BoundaryCount="1" MiddleCount="1" Count="@TotalPages" <MudPagination BoundaryCount="1" MiddleCount="1" Count="@TotalPagesCommesse"
@bind-Selected="CurrentPage" @bind-Selected="SelectedPageCommesse"
Color="Color.Primary"/> Color="Color.Primary" />
</div> </div>
<div class="SelectedPageSize"> <div class="SelectedPageSize">
<MudSelect @bind-Value="SelectedPageSize" <MudSelect @bind-Value="SelectedPageSizeCommesse"
Variant="Variant.Text" Variant="Variant.Text"
Label="Elementi per pagina" Label="Elementi per pagina"
Dense="true" Dense="true"
Style="width: 100%;"> Style="width: 100%;">
<MudSelectItem Value="5">5</MudSelectItem> <MudSelectItem Value="5">5</MudSelectItem>
<MudSelectItem Value="10">10</MudSelectItem> <MudSelectItem Value="10">10</MudSelectItem>
<MudSelectItem Value="20">15</MudSelectItem> <MudSelectItem Value="15">15</MudSelectItem>
</MudSelect> </MudSelect>
</div> </div>
}
</div>
}
</div>
<MudScrollToTop Selector="#topPage" VisibleCssClass="visible absolute" TopOffset="100" HiddenCssClass="invisible"> <!-- Tab Attivit<69> -->
<MudFab Size="Size.Small" Color="Color.Primary" StartIcon="@Icons.Material.Rounded.KeyboardArrowUp" /> <div class="tab-content" style="display: @(ActiveTab == 2 ? "block" : "none")">
</MudScrollToTop> @if (ActivityIsLoading)
{
<MudProgressLinear Color="Color.Primary" Indeterminate="true" Class="my-7" />
}
else if (ActivityList?.Count == 0)
{
<NoDataAvailable Text="Nessuna attivit<69> presente" />
}
else if (ActivityList != null)
{
<!-- Filtri e ricerca -->
<div class="input-card clearButton">
<MudTextField T="string?"
Placeholder="Cerca..."
Variant="Variant.Text"
@bind-Value="SearchTermActivity"
OnDebounceIntervalElapsed="() => ApplyFiltersActivity()"
DebounceInterval="500" />
</div>
<div class="attivita-container">
@foreach (var activity in CurrentPageActivity)
{
<ActivityCard ShowDate="true" Activity="activity" />
} }
@* <div class="commesse-stats mt-4"> @if (TotalPagesActivity > 1)
<MudChip T="string" Size="Size.Small" Color="Color.Info"> {
Visualizzate: @CurrentPageCommesse.Count() / @FilteredCommesse.Count() <div class="custom-pagination">
</MudChip> <MudPagination BoundaryCount="1" MiddleCount="1" Count="@TotalPagesActivity"
@if (!string.IsNullOrEmpty(SearchTerm)) @bind-Selected="CurrentPageActivityIndex"
{ Color="Color.Primary" />
<MudChip T="string" Size="Size.Small" Color="Color.Warning" OnClose="ClearSearch"> </div>
Filtro: "@SearchTerm"
</MudChip> <div class="SelectedPageSize">
} <MudSelect @bind-Value="SelectedPageSizeActivity"
</div> *@ Variant="Variant.Text"
Label="Elementi per pagina"
Dense="true"
Style="width: 100%;">
<MudSelectItem Value="5">5</MudSelectItem>
<MudSelectItem Value="15">15</MudSelectItem>
<MudSelectItem Value="30">30</MudSelectItem>
</MudSelect>
</div>
}
</div> </div>
} }
</div> </div>
</div> </div>
<MudScrollToTop Selector="#topPage" VisibleCssClass="visible absolute" TopOffset="100" HiddenCssClass="invisible">
<MudFab Size="Size.Small" Color="Color.Primary" StartIcon="@Icons.Material.Rounded.KeyboardArrowUp" />
</MudScrollToTop>
</div> </div>
} }
@@ -230,75 +275,77 @@ else
private ContactDTO Anag { get; set; } = new(); private ContactDTO Anag { get; set; } = new();
private List<PersRifDTO>? PersRif { get; set; } private List<PersRifDTO>? PersRif { get; set; }
private List<JtbComt>? Commesse { get; set; } private List<JtbComt>? Commesse { get; set; }
private List<ActivityDTO> ActivityList { get; set; } = [];
private StbUser? Agente { get; set; } private StbUser? Agente { get; set; }
private Dictionary<string, List<CRMJobStepDTO>?> Steps { get; set; } = new(); private Dictionary<string, List<CRMJobStepDTO>?> Steps { get; set; } = new();
// Stati di caricamento // Stati di caricamento
private bool IsLoading { get; set; } = true; private bool IsLoading { get; set; } = true;
private bool IsLoadingCommesse { get; set; } = true; private bool IsLoadingCommesse { get; set; } = true;
private bool IsLoadingSteps { get; set; } = false; private bool ActivityIsLoading { get; set; } = true;
private readonly HashSet<string> _loadingSteps = new(); private bool IsLoadingSteps { get; set; }
private readonly HashSet<string> _loadingSteps = [];
// Gestione tab // Gestione tab
private int ActiveTab { get; set; } = 0; private int ActiveTab { get; set; }
// Paginazione e filtri // Paginazione e filtri per COMMESSE
private int _currentPage = 1; private int _selectedPageCommesse = 1;
private int _selectedPageSize = 5; private int _selectedPageSizeCommesse = 5;
private string _searchTerm = string.Empty; private string _searchTermCommesse = string.Empty;
private List<JtbComt> _filteredCommesse = new(); private List<JtbComt> _filteredCommesse = [];
// Paginazione e filtri per ATTIVIT<49>
private int _currentPageActivity = 1;
private int _selectedPageSizeActivity = 5;
private string _searchTermActivity = string.Empty;
private List<ActivityDTO> _filteredActivity = [];
// Cancellation tokens per gestire le richieste asincrone // Cancellation tokens per gestire le richieste asincrone
private CancellationTokenSource? _loadingCts; private CancellationTokenSource? _loadingCts;
private CancellationTokenSource? _stepsCts; private CancellationTokenSource? _stepsCts;
// Timer per il debounce della ricerca // Timer per il debounce della ricerca
private Timer? _searchTimer; private Timer? _searchTimerCommesse;
private Timer? _searchTimerActivity;
private const int SearchDelayMs = 300; private const int SearchDelayMs = 300;
#region Properties #region Properties per Commesse
private int CurrentPage private int SelectedPageCommesse
{ {
get => _currentPage; get => _selectedPageCommesse;
set set
{ {
if (_currentPage != value) if (_selectedPageCommesse == value) return;
{ _selectedPageCommesse = value;
_currentPage = value; _ = LoadStepsForCurrentPageAsync();
_ = LoadStepsForCurrentPageAsync();
}
} }
} }
private int SelectedPageSize private int SelectedPageSizeCommesse
{ {
get => _selectedPageSize; get => _selectedPageSizeCommesse;
set set
{ {
if (_selectedPageSize != value) if (_selectedPageSizeCommesse == value) return;
{ _selectedPageSizeCommesse = value;
_selectedPageSize = value; _selectedPageCommesse = 1;
_currentPage = 1; ApplyFiltersCommesse();
ApplyFilters(); _ = LoadStepsForCurrentPageAsync();
_ = LoadStepsForCurrentPageAsync();
}
} }
} }
private string SearchTerm private string SearchTermCommesse
{ {
get => _searchTerm; get => _searchTermCommesse;
set set
{ {
if (_searchTerm != value) if (_searchTermCommesse == value) return;
{ _searchTermCommesse = value;
_searchTerm = value;
// Debounce della ricerca _searchTimerCommesse?.Dispose();
_searchTimer?.Dispose(); _searchTimerCommesse = new Timer(async _ => await InvokeAsync(ApplyFiltersCommesse), null, SearchDelayMs, Timeout.Infinite);
_searchTimer = new Timer(async _ => await InvokeAsync(ApplyFilters), null, SearchDelayMs, Timeout.Infinite);
}
} }
} }
@@ -312,11 +359,67 @@ else
} }
} }
private int TotalPages => private int TotalPagesCommesse =>
FilteredCommesse.Count == 0 ? 1 : (int)Math.Ceiling(FilteredCommesse.Count / (double)SelectedPageSize); FilteredCommesse.Count == 0 ? 1 : (int)Math.Ceiling(FilteredCommesse.Count / (double)SelectedPageSizeCommesse);
private IEnumerable<JtbComt> CurrentPageCommesse => private IEnumerable<JtbComt> CurrentPageCommesse =>
FilteredCommesse.Skip((CurrentPage - 1) * SelectedPageSize).Take(SelectedPageSize); FilteredCommesse.Skip((SelectedPageCommesse - 1) * SelectedPageSizeCommesse).Take(SelectedPageSizeCommesse);
#endregion
#region Properties per Attivit<69>
private int CurrentPageActivityIndex
{
get => _currentPageActivity;
set
{
if (_currentPageActivity == value) return;
_currentPageActivity = value;
StateHasChanged();
}
}
private int SelectedPageSizeActivity
{
get => _selectedPageSizeActivity;
set
{
if (_selectedPageSizeActivity == value) return;
_selectedPageSizeActivity = value;
_currentPageActivity = 1;
ApplyFiltersActivity();
}
}
private string SearchTermActivity
{
get => _searchTermActivity;
set
{
if (_searchTermActivity == value) return;
_searchTermActivity = value;
_searchTimerActivity?.Dispose();
_searchTimerActivity = new Timer(async _ => await InvokeAsync(ApplyFiltersActivity), null, SearchDelayMs, Timeout.Infinite);
}
}
private List<ActivityDTO> FilteredActivity
{
get => _filteredActivity;
set
{
_filteredActivity = value;
StateHasChanged();
}
}
private int TotalPagesActivity =>
FilteredActivity.Count == 0 ? 1 : (int)Math.Ceiling(FilteredActivity.Count / (double)SelectedPageSizeActivity);
private IEnumerable<ActivityDTO> CurrentPageActivity =>
FilteredActivity.Skip((CurrentPageActivityIndex - 1) * SelectedPageSizeActivity).Take(SelectedPageSizeActivity);
#endregion #endregion
@@ -339,7 +442,6 @@ else
} }
catch (Exception ex) catch (Exception ex)
{ {
// Log dell'errore
Console.WriteLine($"Errore in OnInitializedAsync: {ex.Message}"); Console.WriteLine($"Errore in OnInitializedAsync: {ex.Message}");
} }
finally finally
@@ -351,11 +453,12 @@ else
public async ValueTask DisposeAsync() public async ValueTask DisposeAsync()
{ {
_loadingCts?.Cancel(); _loadingCts?.CancelAsync();
_loadingCts?.Dispose(); _loadingCts?.Dispose();
_stepsCts?.Cancel(); _stepsCts?.CancelAsync();
_stepsCts?.Dispose(); _stepsCts?.Dispose();
_searchTimer?.Dispose(); _searchTimerCommesse?.DisposeAsync();
_searchTimerActivity?.DisposeAsync();
} }
#endregion #endregion
@@ -366,21 +469,18 @@ else
{ {
try try
{ {
// Caricamento dati principali
await LoadAnagAsync(); await LoadAnagAsync();
await LoadPersRifAsync(); await LoadPersRifAsync();
_ = LoadActivity();
// Caricamento agente
if (!string.IsNullOrEmpty(Anag.CodVage)) if (!string.IsNullOrEmpty(Anag.CodVage))
{ {
Agente = (await ManageData.GetTable<StbUser>(x => x.UserCode != null && x.UserCode.Equals(Anag.CodVage))) Agente = (await ManageData.GetTable<StbUser>(x => x.UserCode != null && x.UserCode.Equals(Anag.CodVage)))
.LastOrDefault(); .LastOrDefault();
} }
// Salvataggio in sessione
SaveDataToSession(); SaveDataToSession();
// Caricamento commesse in background
_ = Task.Run(async () => await LoadCommesseAsync()); _ = Task.Run(async () => await LoadCommesseAsync());
} }
catch (Exception ex) catch (Exception ex)
@@ -393,12 +493,12 @@ else
{ {
if (IsContact) if (IsContact)
{ {
var clie = (await ManageData.GetTable<AnagClie>(x => x.CodAnag.Equals(CodContact))).Last(); var clie = (await ManageData.GetTable<AnagClie>(x => x.CodAnag!.Equals(CodContact))).Last();
Anag = Mapper.Map<ContactDTO>(clie); Anag = Mapper.Map<ContactDTO>(clie);
} }
else else
{ {
var pros = (await ManageData.GetTable<PtbPros>(x => x.CodPpro.Equals(CodContact))).Last(); var pros = (await ManageData.GetTable<PtbPros>(x => x.CodPpro!.Equals(CodContact))).Last();
Anag = Mapper.Map<ContactDTO>(pros); Anag = Mapper.Map<ContactDTO>(pros);
} }
} }
@@ -407,16 +507,35 @@ else
{ {
if (IsContact) if (IsContact)
{ {
var pers = await ManageData.GetTable<VtbCliePersRif>(x => x.CodAnag.Equals(Anag.CodContact)); var pers = await ManageData.GetTable<VtbCliePersRif>(x => x.CodAnag!.Equals(Anag.CodContact));
PersRif = Mapper.Map<List<PersRifDTO>>(pers); PersRif = Mapper.Map<List<PersRifDTO>>(pers);
} }
else else
{ {
var pers = await ManageData.GetTable<PtbProsRif>(x => x.CodPpro.Equals(Anag.CodContact)); var pers = await ManageData.GetTable<PtbProsRif>(x => x.CodPpro!.Equals(Anag.CodContact));
PersRif = Mapper.Map<List<PersRifDTO>>(pers); PersRif = Mapper.Map<List<PersRifDTO>>(pers);
} }
} }
private async Task LoadActivity()
{
await Task.Run(async () =>
{
var activities = await IntegryApiService.RetrieveActivity(new CRMRetrieveActivityRequestDTO { CodAnag = Anag.CodContact });
ActivityList = Mapper.Map<List<ActivityDTO>>(activities)
.OrderByDescending(x =>
(x.EffectiveTime ?? x.EstimatedTime) ?? x.DataInsAct
).ToList();
});
UserState.Activitys = ActivityList;
ApplyFiltersActivity();
ActivityIsLoading = false;
StateHasChanged();
}
private async Task LoadCommesseAsync() private async Task LoadCommesseAsync()
{ {
try try
@@ -425,17 +544,14 @@ else
Commesse = await ManageData.GetTable<JtbComt>(x => x.CodAnag != null && x.CodAnag.Equals(CodContact)); Commesse = await ManageData.GetTable<JtbComt>(x => x.CodAnag != null && x.CodAnag.Equals(CodContact));
// Ordinamento ottimizzato
Commesse = Commesse? Commesse = Commesse?
.OrderByDescending(x => x.LastUpd ?? DateTime.MinValue) .OrderByDescending(x => x.CodJcom)
.ThenByDescending(x => x.CodJcom)
.ToList(); .ToList();
UserState.Commesse = Commesse; UserState.Commesse = Commesse;
ApplyFilters(); ApplyFiltersCommesse();
// Caricamento steps per la prima pagina
await LoadStepsForCurrentPageAsync(); await LoadStepsForCurrentPageAsync();
} }
catch (Exception ex) catch (Exception ex)
@@ -455,11 +571,14 @@ else
PersRif = UserState.PersRif; PersRif = UserState.PersRif;
Commesse = UserState.Commesse; Commesse = UserState.Commesse;
Agente = UserState.Agente; Agente = UserState.Agente;
Steps = UserState.Steps ?? new Dictionary<string, List<CRMJobStepDTO>?>(); Steps = UserState.Steps;
ActivityList = UserState.Activitys;
ApplyFilters(); ApplyFiltersCommesse();
ApplyFiltersActivity();
IsLoadingCommesse = false; IsLoadingCommesse = false;
ActivityIsLoading = false;
} }
private void SaveDataToSession() private void SaveDataToSession()
@@ -469,6 +588,7 @@ else
UserState.PersRif = PersRif; UserState.PersRif = PersRif;
UserState.Agente = Agente; UserState.Agente = Agente;
UserState.Steps = Steps; UserState.Steps = Steps;
UserState.Activitys = ActivityList;
} }
#endregion #endregion
@@ -560,30 +680,32 @@ else
{ {
ActiveTab = tabIndex; ActiveTab = tabIndex;
// Se si passa alle commesse e non sono ancora state caricate
if (tabIndex == 1 && Commesse == null) if (tabIndex == 1 && Commesse == null)
{ {
_ = Task.Run(async () => await LoadCommesseAsync()); _ = Task.Run(async () => await LoadCommesseAsync());
} else if (tabIndex == 1 && Steps.IsNullOrEmpty()) }
else if (tabIndex == 1 && Steps.IsNullOrEmpty())
{ {
_ = Task.Run(async () => await LoadStepsForCurrentPageAsync()); _ = Task.Run(async () => await LoadStepsForCurrentPageAsync());
} }
else if (tabIndex == 2 && ActivityList?.Count == 0)
{
_ = Task.Run(async () => await LoadActivity());
}
} }
private void ApplyFilters() private void ApplyFiltersCommesse()
{ {
if (Commesse == null) if (Commesse == null)
{ {
FilteredCommesse = new List<JtbComt>(); FilteredCommesse = [];
return; return;
} }
var filtered = Commesse.AsEnumerable(); var filtered = Commesse.AsEnumerable();
if (!string.IsNullOrWhiteSpace(SearchTermCommesse))
// Filtro per testo di ricerca
if (!string.IsNullOrWhiteSpace(SearchTerm))
{ {
var searchLower = SearchTerm.ToLowerInvariant(); var searchLower = SearchTermCommesse.ToLowerInvariant();
filtered = filtered.Where(c => filtered = filtered.Where(c =>
c.CodJcom?.ToLowerInvariant().Contains(searchLower) == true || c.CodJcom?.ToLowerInvariant().Contains(searchLower) == true ||
c.Descrizione?.ToLowerInvariant().Contains(searchLower) == true || c.Descrizione?.ToLowerInvariant().Contains(searchLower) == true ||
@@ -591,21 +713,40 @@ else
} }
FilteredCommesse = filtered.ToList(); FilteredCommesse = filtered.ToList();
if (SelectedPageCommesse > TotalPagesCommesse && TotalPagesCommesse > 0) _selectedPageCommesse = 1;
// Reset della pagina se necessario
if (CurrentPage > TotalPages && TotalPages > 0)
{
_currentPage = 1;
}
// Carica gli steps per la pagina corrente
_ = LoadStepsForCurrentPageAsync(); _ = LoadStepsForCurrentPageAsync();
} }
private void ClearSearch() private void ApplyFiltersActivity()
{ {
SearchTerm = string.Empty; var filtered = ActivityList.AsEnumerable();
ApplyFilters();
if (!string.IsNullOrWhiteSpace(SearchTermActivity))
{
var searchLower = SearchTermActivity.ToLowerInvariant();
filtered = filtered.Where(a =>
a.ActivityDescription?.ToLowerInvariant().Contains(searchLower) == true ||
a.ActivityId?.ToLowerInvariant().Contains(searchLower) == true);
}
FilteredActivity = filtered.ToList();
if (CurrentPageActivityIndex > TotalPagesActivity && TotalPagesActivity > 0)
{
_currentPageActivity = 1;
}
}
private void ClearSearchCommesse()
{
SearchTermCommesse = string.Empty;
ApplyFiltersCommesse();
}
private void ClearSearchActivity()
{
SearchTermActivity = string.Empty;
ApplyFiltersActivity();
} }
#endregion #endregion
@@ -629,12 +770,10 @@ else
if (result is { Canceled: false }) if (result is { Canceled: false })
{ {
// Aggiorna i dati se necessario
await LoadAnagAsync(); await LoadAnagAsync();
SaveDataToSession(); SaveDataToSession();
} }
} }
#endregion #endregion
} }

View File

@@ -165,10 +165,15 @@
gap: 1.25rem; gap: 1.25rem;
} }
.attivita-container {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
/*-------------- /*--------------
TabPanel TabPanel
----------------*/ ----------------*/
.box { .box {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -199,7 +204,7 @@
content: ''; content: '';
display: block; display: block;
height: 3px; height: 3px;
width: calc(100% / 2); width: calc(100% / 3);
position: absolute; position: absolute;
bottom: 0; bottom: 0;
left: 0; left: 0;
@@ -223,7 +228,8 @@
/* tab attivo */ /* tab attivo */
#tab1:checked ~ .box .tab-list .tab-item:nth-child(1), #tab1:checked ~ .box .tab-list .tab-item:nth-child(1),
#tab2:checked ~ .box .tab-list .tab-item:nth-child(2) { #tab2:checked ~ .box .tab-list .tab-item:nth-child(2),
#tab3:checked ~ .box .tab-list .tab-item:nth-child(3) {
opacity: 1; opacity: 1;
font-weight: bold; font-weight: bold;
display: block; display: block;
@@ -235,6 +241,8 @@
#tab2:checked ~ .box .tab-list::before { transform: translateX(100%); } #tab2:checked ~ .box .tab-list::before { transform: translateX(100%); }
#tab3:checked ~ .box .tab-list::before { transform: translateX(200%); }
.tab-container { .tab-container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -257,7 +265,10 @@
} }
#tab1:checked ~ .tab-container .tab-content:nth-child(1), #tab1:checked ~ .tab-container .tab-content:nth-child(1),
#tab2:checked ~ .tab-container .tab-content:nth-child(2) { display: block; } #tab2:checked ~ .tab-container .tab-content:nth-child(2),
#tab3:checked ~ .tab-container .tab-content:nth-child(3) {
display: block;
}
@keyframes fade { @keyframes fade {
from { from {

View File

@@ -29,11 +29,25 @@
<span class="activity-hours"> <span class="activity-hours">
@if (Activity.EffectiveTime is null) @if (Activity.EffectiveTime is null)
{ {
@($"{Activity.EstimatedTime:t}") if (ShowDate)
{
@($"{Activity.EstimatedTime:g}")
}
else
{
@($"{Activity.EstimatedTime:t}")
}
} }
else else
{ {
@($"{Activity.EffectiveTime:t}") if (ShowDate)
{
@($"{Activity.EffectiveTime:g}")
}
else
{
@($"{Activity.EffectiveTime:t}")
}
} }
</span> </span>
</div> </div>
@@ -68,6 +82,8 @@
[Parameter] public EventCallback<string> ActivityChanged { get; set; } [Parameter] public EventCallback<string> ActivityChanged { get; set; }
[Parameter] public EventCallback<ActivityDTO> ActivityDeleted { get; set; } [Parameter] public EventCallback<ActivityDTO> ActivityDeleted { get; set; }
[Parameter] public bool ShowDate { get; set; }
private TimeSpan? Durata { get; set; } private TimeSpan? Durata { get; set; }
protected override void OnParametersSet() protected override void OnParametersSet()
@@ -82,7 +98,7 @@
private async Task OpenActivity() private async Task OpenActivity()
{ {
var result = await ModalHelpers.OpenActivityForm(Dialog, null, Activity.ActivityId); var result = await ModalHelpers.OpenActivityForm(Dialog, Activity, null);
switch (result) switch (result)
{ {

View File

@@ -25,11 +25,23 @@
@if (!Commesse.IsNullOrEmpty()) @if (!Commesse.IsNullOrEmpty())
{ {
<div @onclick="OpenUser" class="container-commesse"> <div @onclick="OpenUser" class="container-commesse">
@foreach (var commessa in Commesse!)
@for (var i = 0; i < Commesse!.Count; i++)
{ {
var commessa = Commesse[i];
<div class="commessa"> <div class="commessa">
<span>@($"{commessa.CodJcom} - {commessa.Descrizione}")</span> @if (i > 5 && Commesse.Count - i > 1)
{
<span>@($"E altre {Commesse.Count - i} commesse")</span>
}
else
{
<span>@($"{commessa.CodJcom} - {commessa.Descrizione}")</span>
}
</div> </div>
@if (i > 5 && Commesse.Count - i > 1) break;
} }
</div> </div>
} }
@@ -63,7 +75,8 @@
if (ShowSectionCommesse) if (ShowSectionCommesse)
{ {
Commesse = await ManageData.GetTable<JtbComt>(x => x.CodAnag.Equals(User.CodContact)); Commesse = (await ManageData.GetTable<JtbComt>(x => x.CodAnag.Equals(User.CodContact)))
.OrderByDescending(x => x.CodJcom).ToList();
IsLoading = false; IsLoading = false;
StateHasChanged(); StateHasChanged();
return; return;

View File

@@ -250,8 +250,8 @@
private List<PtbPros> Pros { get; set; } = []; private List<PtbPros> Pros { get; set; } = [];
private List<ActivityFileDto>? ActivityFileList { get; set; } private List<ActivityFileDto>? ActivityFileList { get; set; }
private bool IsNew => Id.IsNullOrEmpty(); private bool IsNew { get; set; }
private bool IsView => !NetworkService.IsNetworkAvailable(); private bool IsView => !NetworkService.ConnectionAvailable;
private string? LabelSave { get; set; } private string? LabelSave { get; set; }
@@ -276,18 +276,18 @@
{ {
Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter; Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter;
_ = LoadData();
LabelSave = IsNew ? "Aggiungi" : null;
if (!Id.IsNullOrEmpty())
ActivityModel = (await ManageData.GetActivity(new WhereCondActivity { ActivityId = Id }, true)).Last();
if (ActivityCopied != null) if (ActivityCopied != null)
{ {
ActivityModel = ActivityCopied.Clone(); ActivityModel = ActivityCopied.Clone();
} }
else if (!Id.IsNullOrEmpty())
ActivityModel = (await ManageData.GetActivity(new WhereCondActivity { ActivityId = Id }, true)).Last();
if (Id.IsNullOrEmpty()) Id = ActivityModel.ActivityId;
IsNew = Id.IsNullOrEmpty();
LabelSave = IsNew ? "Aggiungi" : null;
_ = LoadData();
await LoadCommesse(); await LoadCommesse();
if (IsNew) if (IsNew)

View File

@@ -280,7 +280,7 @@
} }
else else
{ {
@if (NetworkService.IsNetworkAvailable() && !ContactModel.IsContact) @if (NetworkService.ConnectionAvailable && !ContactModel.IsContact)
{ {
<MudButton Class="button-settings blue-icon" <MudButton Class="button-settings blue-icon"
FullWidth="true" FullWidth="true"
@@ -332,7 +332,7 @@
private List<StbUser> Users { get; set; } = []; private List<StbUser> Users { get; set; } = [];
private bool IsNew => OriginalModel is null; private bool IsNew => OriginalModel is null;
private bool IsView => !NetworkService.IsNetworkAvailable(); private bool IsView => !NetworkService.ConnectionAvailable;
private string? LabelSave { get; set; } private string? LabelSave { get; set; }

View File

@@ -118,7 +118,7 @@
private PersRifDTO PersRifModel { get; set; } = new(); private PersRifDTO PersRifModel { get; set; } = new();
private bool IsNew => OriginalModel is null; private bool IsNew => OriginalModel is null;
private bool IsView => !NetworkService.IsNetworkAvailable(); private bool IsView => !NetworkService.ConnectionAvailable;
private string? LabelSave { get; set; } private string? LabelSave { get; set; }

View File

@@ -10,6 +10,9 @@ public class CRMRetrieveActivityRequestDTO
[JsonPropertyName("activityId")] [JsonPropertyName("activityId")]
public string? ActivityId { get; set; } public string? ActivityId { get; set; }
[JsonPropertyName("codAnag")]
public string? CodAnag { get; set; }
[JsonPropertyName("codJcom")] [JsonPropertyName("codJcom")]
public string? CodJcom { get; set; } public string? CodJcom { get; set; }

View File

@@ -1,4 +1,5 @@
using salesbook.Shared.Core.Dto.JobProgress; using salesbook.Shared.Core.Dto.Activity;
using salesbook.Shared.Core.Dto.JobProgress;
using salesbook.Shared.Core.Entity; using salesbook.Shared.Core.Entity;
namespace salesbook.Shared.Core.Dto.PageState; namespace salesbook.Shared.Core.Dto.PageState;
@@ -12,4 +13,5 @@ public class UserPageState
public List<JtbComt> Commesse { get; set; } public List<JtbComt> Commesse { get; set; }
public StbUser? Agente { get; set; } public StbUser? Agente { get; set; }
public Dictionary<string, List<CRMJobStepDTO>?> Steps { get; set; } public Dictionary<string, List<CRMJobStepDTO>?> Steps { get; set; }
public List<ActivityDTO> Activitys { get; set; }
} }

View File

@@ -8,6 +8,8 @@ namespace salesbook.Shared.Core.Interface;
public interface IIntegryApiService public interface IIntegryApiService
{ {
Task<bool> SystemOk();
Task<List<StbActivity>?> RetrieveActivity(CRMRetrieveActivityRequestDTO activityRequest); Task<List<StbActivity>?> RetrieveActivity(CRMRetrieveActivityRequestDTO activityRequest);
Task<List<JtbComt>?> RetrieveAllCommesse(string? dateFilter = null); Task<List<JtbComt>?> RetrieveAllCommesse(string? dateFilter = null);
Task<UsersSyncResponseDTO> RetrieveAnagClie(CRMAnagRequestDTO request); Task<UsersSyncResponseDTO> RetrieveAnagClie(CRMAnagRequestDTO request);

View File

@@ -2,5 +2,7 @@
public interface INetworkService public interface INetworkService
{ {
public bool ConnectionAvailable { get; set; }
public bool IsNetworkAvailable(); public bool IsNetworkAvailable();
} }

View File

@@ -13,6 +13,19 @@ namespace salesbook.Shared.Core.Services;
public class IntegryApiService(IIntegryApiRestClient integryApiRestClient, IUserSession userSession) public class IntegryApiService(IIntegryApiRestClient integryApiRestClient, IUserSession userSession)
: IIntegryApiService : IIntegryApiService
{ {
public async Task<bool> SystemOk()
{
try
{
await integryApiRestClient.Get<object>("system/ok");
return true;
}
catch (Exception e)
{
return false;
}
}
public Task<List<StbActivity>?> RetrieveActivity(CRMRetrieveActivityRequestDTO activityRequest) => public Task<List<StbActivity>?> RetrieveActivity(CRMRetrieveActivityRequestDTO activityRequest) =>
integryApiRestClient.AuthorizedPost<List<StbActivity>?>("crm/retrieveActivity", activityRequest); integryApiRestClient.AuthorizedPost<List<StbActivity>?>("crm/retrieveActivity", activityRequest);

View File

@@ -22,6 +22,42 @@ a, .btn-link {
color: inherit; color: inherit;
} }
/*ServicesIsDown" : "SystemOk" : "NetworkKo*/
.Connection {
padding: 0 .75rem;
font-weight: 700;
display: flex;
flex-direction: row;
gap: 1rem;
font-size: larger;
transition: all 0.5s ease;
opacity: 0;
transform: translateY(-35px);
min-height: 35px;
align-items: center;
}
.Connection.ServicesIsDown, .Connection.NetworkKo {
background-color: var(--mud-palette-error);
color: white;
}
.Connection.SystemOk {
background-color: var(--mud-palette-success);
color: white;
}
.Connection.Show {
opacity: 1;
transform: translateY(0);
}
.page > .Connection.Hide ~ main {
transition: all 0.5s ease;
transform: translateY(-35px);
}
.btn-primary { .btn-primary {
color: #fff; color: #fff;
background-color: var(--primary-color); background-color: var(--primary-color);

View File

@@ -38,16 +38,41 @@ function monitorExpandedClass(mutations) {
}); });
} }
// Funzione per monitorare bottom-sheet-container e gestire la navbar
function monitorBottomSheetClass(mutations) {
const bottomSheet = document.querySelector(".bottom-sheet-container");
const navbar = document.querySelector(".animated-navbar");
if (!bottomSheet || !navbar) return;
mutations.forEach(function (mutation) {
if (mutation.type === 'attributes' && mutation.attributeName === 'class' && mutation.target === bottomSheet) {
if (bottomSheet.classList.contains("show")) {
navbar.classList.remove("show-nav");
navbar.classList.add("hide-nav");
console.log("Navbar nascosta (hide-nav)");
} else {
navbar.classList.remove("hide-nav");
navbar.classList.add("show-nav");
console.log("Navbar mostrata (show-nav)");
}
}
});
}
// Esegui la funzione tabindex inizialmente // Esegui la funzione tabindex inizialmente
addTabindexToButtons(); addTabindexToButtons();
// Observer combinato per entrambe le funzionalità // Observer combinato per tutte le funzionalità
const observer = new MutationObserver((mutations) => { const observer = new MutationObserver((mutations) => {
// Aggiungi tabindex ai nuovi bottoni // Aggiungi tabindex ai nuovi bottoni
addTabindexToButtons(); addTabindexToButtons();
// Monitora le classi expanded // Monitora le classi expanded
monitorExpandedClass(mutations); monitorExpandedClass(mutations);
// Monitora bottom-sheet-container
monitorBottomSheetClass(mutations);
}); });
// Osserva sia i cambiamenti nel DOM che gli attributi // Osserva sia i cambiamenti nel DOM che gli attributi
@@ -57,3 +82,19 @@ observer.observe(document.body, {
attributes: true, attributes: true,
attributeFilter: ['class'] attributeFilter: ['class']
}); });
// Sync iniziale per la navbar (nel caso la pagina parte già con .show)
document.addEventListener("DOMContentLoaded", () => {
const bottomSheet = document.querySelector(".bottom-sheet-container");
const navbar = document.querySelector(".animated-navbar");
if (bottomSheet && navbar) {
if (bottomSheet.classList.contains("show")) {
navbar.classList.remove("show-nav");
navbar.classList.add("hide-nav");
} else {
navbar.classList.remove("hide-nav");
navbar.classList.add("show-nav");
}
}
});

View File

@@ -4,6 +4,8 @@ namespace salesbook.Web.Core.Services;
public class NetworkService : INetworkService public class NetworkService : INetworkService
{ {
public bool ConnectionAvailable { get; set; }
public bool IsNetworkAvailable() public bool IsNetworkAvailable()
{ {
return true; return true;