Wonky.Client/Wonky.Client/Pages/CustomerInvoiceListPage.razor.cs
2022-12-22 08:19:08 +01:00

78 lines
3 KiB
C#

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<CustomerInvoiceListPage> 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<InvoiceListView> 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<InvoiceListView>(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();
}
}