using System.Globalization; using System.Net.NetworkInformation; using System.Text.Json; using Blazored.LocalStorage; using Blazored.Toast.Services; using Microsoft.AspNetCore.Components; using Wonky.Client.HttpInterceptors; using Wonky.Client.HttpInterfaces; using Wonky.Entity.DTO; using Wonky.Entity.Views; namespace Wonky.Client.Pages; public partial class CustomerInvoiceListPage : IDisposable { [Parameter] public string CompanyId { get; set; } = ""; [Inject] public ICrmCompanyHttpRepository CompanyRepo { get; set; } [Inject] public HttpInterceptorService Interceptor { get; set; } [Inject] public ICrmHistoryHttpRepository HistoryRepo { get; set; } [Inject] public IToastService Toaster { get; set; } [Inject] public ILocalStorageService Storage { get; set; } [Inject] public ILogger Logger { get; set; } private InvoiceListView CompanyInvoices { get; set; } = new(); private CompanyDto Company { get; set; } = new(); private bool Working { get; set; } = true; protected override async Task OnInitializedAsync() { Interceptor.RegisterEvent(); Interceptor.RegisterBeforeSendEvent(); Company = await CompanyRepo.GetCompanyById(CompanyId); while (string.IsNullOrWhiteSpace(Company.HistorySync)) { await Task.Delay(1000); } var iDate = await Storage.GetItemAsStringAsync($"{Company.CompanyId}-iDate"); if (string.IsNullOrWhiteSpace(iDate) || (iDate == Company.HistorySync && iDate != $"{DateTime.Now:yyyy-MM-dd}")) { // send rpc to sync invoices from ERP to CRM var ts = await HistoryRepo.ErpInvoiceToCrmRpc(CompanyId, Company.HistorySync); // wait until we have the result while (string.IsNullOrWhiteSpace(ts)) { await Task.Delay(1000); } await Storage.SetItemAsync($"{Company.CompanyId}-iDate", ts); } CompanyInvoices = await FetchCompanyInvoices(); Working = false; } private async Task FetchCompanyInvoices() { var storage = await Storage.GetItemAsStringAsync($"{Company.CompanyId}-invoices"); var iDate = await Storage.GetItemAsStringAsync($"{Company.CompanyId}-iDate"); // if we have a list and iDate was today return the list if (!string.IsNullOrWhiteSpace(storage) && DateTime.Parse(iDate.Replace("\"", "")) >= DateTime.Now) { Logger.LogDebug("return invoices from storage"); return JsonSerializer.Deserialize(storage); } Logger.LogDebug("pulling invoices from backend"); // pull invoices var invoices = await HistoryRepo.FetchInvoiceList(CompanyId); // send invoices to storage await Storage.SetItemAsync($"{Company.CompanyId}-invoices", invoices); Logger.LogDebug("return invoices from backend"); return invoices; } public void Dispose() { Interceptor.DisposeEvent(); } }