Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
436bbb8bfb | ||
|
|
8242184c18 | ||
|
|
124a891025 |
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
#define MyAppName "Электронная Фармация"
|
#define MyAppName "Электронная Фармация"
|
||||||
#define MyAppBrand "ЭльФиСА"
|
#define MyAppBrand "ЭльФиСА"
|
||||||
#define MyAppVersion "2.0.1"
|
#define MyAppVersion "2.0.3"
|
||||||
#define MyAppPublisher "PharmData"
|
#define MyAppPublisher "PharmData"
|
||||||
#define MyAppURL "https://cdn.24pharmdata.ru"
|
#define MyAppURL "https://cdn.24pharmdata.ru"
|
||||||
#define MyAppSupportURL "https://24pharmdata.ru"
|
#define MyAppSupportURL "https://24pharmdata.ru"
|
||||||
|
|||||||
@ -5,9 +5,9 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||||
<Version>2.0.1</Version>
|
<Version>2.0.3</Version>
|
||||||
<AssemblyVersion>2.0.1.0</AssemblyVersion>
|
<AssemblyVersion>2.0.3.0</AssemblyVersion>
|
||||||
<FileVersion>2.0.1.0</FileVersion>
|
<FileVersion>2.0.3.0</FileVersion>
|
||||||
<Product>ЭльФиСА — Электронная Фармация</Product>
|
<Product>ЭльФиСА — Электронная Фармация</Product>
|
||||||
<Company>PharmData</Company>
|
<Company>PharmData</Company>
|
||||||
<!-- Кросс-платформенная публикация задаётся флагами CLI (RID + self-contained). -->
|
<!-- Кросс-платформенная публикация задаётся флагами CLI (RID + self-contained). -->
|
||||||
|
|||||||
@ -61,7 +61,9 @@ public partial class LoadPriceViewModel : ViewModelBase
|
|||||||
ProgressText = "Соединение с сервером…";
|
ProgressText = "Соединение с сервером…";
|
||||||
|
|
||||||
var all = new List<PriceItem>();
|
var all = new List<PriceItem>();
|
||||||
const int page = 500;
|
// Большая страница: сервер на каждый запрос заново прогоняет тяжёлый
|
||||||
|
// сводный запрос, поэтому одна большая страница в разы быстрее десятков мелких.
|
||||||
|
const int page = 20000;
|
||||||
int offset = 0, total = 0;
|
int offset = 0, total = 0;
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
@ -77,7 +79,7 @@ public partial class LoadPriceViewModel : ViewModelBase
|
|||||||
: $"Загружено {all.Count} позиций…";
|
: $"Загружено {all.Count} позиций…";
|
||||||
|
|
||||||
offset += batch.Count;
|
offset += batch.Count;
|
||||||
if (batch.Count < page || (total > 0 && all.Count >= total) || offset > 30000)
|
if (batch.Count < page || (total > 0 && all.Count >= total) || offset > 500000)
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -15,6 +15,12 @@ public partial class RootViewModel : ViewModelBase
|
|||||||
|
|
||||||
public RootViewModel()
|
public RootViewModel()
|
||||||
{
|
{
|
||||||
|
// Запомнили вход в прошлый раз и токен ещё живой — сразу в программу.
|
||||||
|
if (Session.TryRestore())
|
||||||
|
{
|
||||||
|
Current = new ShellViewModel(Logout);
|
||||||
|
return;
|
||||||
|
}
|
||||||
Current = new LoginViewModel(OnLoggedIn);
|
Current = new LoginViewModel(OnLoggedIn);
|
||||||
TryDevAutoLogin();
|
TryDevAutoLogin();
|
||||||
}
|
}
|
||||||
@ -38,7 +44,11 @@ public partial class RootViewModel : ViewModelBase
|
|||||||
catch { /* остаёмся на экране входа */ }
|
catch { /* остаёмся на экране входа */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnLoggedIn() => Current = new ShellViewModel(Logout);
|
private void OnLoggedIn()
|
||||||
|
{
|
||||||
|
Session.Current.Save(); // запомнить вход между запусками
|
||||||
|
Current = new ShellViewModel(Logout);
|
||||||
|
}
|
||||||
|
|
||||||
private void Logout()
|
private void Logout()
|
||||||
{
|
{
|
||||||
|
|||||||
@ -9,98 +9,119 @@ using Elfisa.Core;
|
|||||||
namespace Elfisa.Avalonia.ViewModels;
|
namespace Elfisa.Avalonia.ViewModels;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить: поиск по прайсу → корзина (общая с Прайс-листом) → создание заказа.
|
/// Отправить — отправка НЕОТПРАВЛЕННЫХ накладных (черновиков заказов из раздела
|
||||||
/// ВНИМАНИЕ: отправка создаёт реальный заказ у поставщика.
|
/// «Заказы»). Список готовых накладных, кнопка «Отправить» (создаёт реальный заказ
|
||||||
|
/// у поставщика). Без поиска по прайсу и наименований — только сами накладные.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public partial class SendOrderViewModel : ViewModelBase
|
public partial class SendOrderViewModel : ViewModelBase
|
||||||
{
|
{
|
||||||
private readonly ApiClient _api = new();
|
private readonly ApiClient _api = new();
|
||||||
private readonly CartService _cart = CartService.Instance;
|
|
||||||
|
|
||||||
public ObservableCollection<PriceItem> Results { get; } = new();
|
/// <summary>Неотправленные накладные (черновики).</summary>
|
||||||
public ObservableCollection<CartItem> Cart => _cart.Items;
|
public ObservableCollection<DraftOrder> Drafts { get; } = new();
|
||||||
public ObservableCollection<BuyerLocationDto> Locations { get; } = new();
|
|
||||||
|
|
||||||
[ObservableProperty] private string _search = "";
|
[ObservableProperty] private DraftOrder? _selected;
|
||||||
[ObservableProperty] private PriceItem? _selectedResult;
|
|
||||||
[ObservableProperty] private BuyerLocationDto? _selectedLocation;
|
|
||||||
[ObservableProperty] private string _comment = "";
|
|
||||||
[ObservableProperty] private bool _busy;
|
[ObservableProperty] private bool _busy;
|
||||||
[ObservableProperty] private string? _status;
|
[ObservableProperty] private string? _status;
|
||||||
[ObservableProperty] private decimal _cartTotal;
|
[ObservableProperty] private decimal _totalSum;
|
||||||
|
[ObservableProperty] private bool _isEmpty = true;
|
||||||
|
[ObservableProperty] private int _count;
|
||||||
|
|
||||||
public SendOrderViewModel()
|
public SendOrderViewModel()
|
||||||
{
|
{
|
||||||
_api.SetToken(Session.Current.Token);
|
_api.SetToken(Session.Current.Token);
|
||||||
_cart.Changed += Recalc;
|
Load();
|
||||||
Recalc();
|
|
||||||
if (Session.Current.IsAuthenticated) _ = InitAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task InitAsync()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var locs = await _api.GetBuyerLocationsAsync();
|
|
||||||
Locations.Clear();
|
|
||||||
foreach (var l in locs) Locations.Add(l);
|
|
||||||
SelectedLocation = Locations.FirstOrDefault(l => l.IsDefault) ?? Locations.FirstOrDefault();
|
|
||||||
await SearchAsync();
|
|
||||||
}
|
|
||||||
catch (Exception ex) { Status = ex.Message; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
private async Task SearchAsync()
|
private void Refresh() => Load();
|
||||||
|
|
||||||
|
private void Load()
|
||||||
{
|
{
|
||||||
try
|
Drafts.Clear();
|
||||||
{
|
foreach (var d in DraftStore.All.OrderByDescending(x => x.CreatedAt))
|
||||||
Busy = true; Status = null;
|
Drafts.Add(d);
|
||||||
var resp = await _api.GetPriceSummaryAsync(Search, limit: 200);
|
TotalSum = Drafts.Sum(d => d.Total);
|
||||||
Results.Clear();
|
Count = Drafts.Count;
|
||||||
foreach (var it in resp.Summary ?? new()) Results.Add(it);
|
IsEmpty = Drafts.Count == 0;
|
||||||
}
|
if (Selected is null || !Drafts.Contains(Selected))
|
||||||
catch (Exception ex) { Status = ex.Message; }
|
Selected = Drafts.FirstOrDefault();
|
||||||
finally { Busy = false; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Отправить одну накладную.</summary>
|
||||||
[RelayCommand]
|
[RelayCommand]
|
||||||
private void AddToCart()
|
private async Task SendAsync(DraftOrder? draft)
|
||||||
{
|
|
||||||
if (SelectedResult is null) { Status = "Выберите позицию в списке слева."; return; }
|
|
||||||
_cart.Add(SelectedResult);
|
|
||||||
}
|
|
||||||
|
|
||||||
[RelayCommand]
|
|
||||||
private void RemoveFromCart(CartItem? item) => _cart.Remove(item!);
|
|
||||||
|
|
||||||
private void Recalc() => CartTotal = _cart.Total;
|
|
||||||
|
|
||||||
[RelayCommand]
|
|
||||||
private async Task SendAsync()
|
|
||||||
{
|
{
|
||||||
|
var d = draft ?? Selected;
|
||||||
|
if (d is null) { Status = "Выберите накладную для отправки."; return; }
|
||||||
Status = null;
|
Status = null;
|
||||||
if (_cart.Count == 0) { Status = "Корзина пуста."; return; }
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Busy = true;
|
Busy = true;
|
||||||
var req = new BuyerOrderCreateRequest
|
var resp = await CreateFromDraft(d);
|
||||||
{
|
DraftStore.Remove(d.Id);
|
||||||
LocationId = SelectedLocation?.BuyerLocationId,
|
Status = $"✓ Накладная {resp.GlobalSign ?? resp.OrderId} отправлена ({resp.ItemsCount} поз., {resp.TotalAmount:N2}).";
|
||||||
Comment = string.IsNullOrWhiteSpace(Comment) ? null : Comment.Trim(),
|
|
||||||
Items = _cart.Items.Select(c => new BuyerOrderItemReq
|
|
||||||
{
|
|
||||||
SupplierPriceId = c.Source.SupplierPriceId ?? "",
|
|
||||||
Qty = (double)c.Qty,
|
|
||||||
ItemName = c.Source.DrugName,
|
|
||||||
Barcode = c.Source.Barcode
|
|
||||||
}).ToList()
|
|
||||||
};
|
|
||||||
var resp = await _api.CreateOrderAsync(req);
|
|
||||||
Status = $"✓ Заказ {resp.GlobalSign ?? resp.OrderId} создан: {resp.ItemsCount} поз., {resp.TotalAmount:N2}.";
|
|
||||||
_cart.Clear();
|
|
||||||
}
|
}
|
||||||
catch (Exception ex) { Status = "Ошибка отправки: " + ex.Message; }
|
catch (Exception ex) { Status = "Ошибка отправки: " + ex.Message; }
|
||||||
finally { Busy = false; }
|
finally { Busy = false; Load(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Отправить все неотправленные накладные.</summary>
|
||||||
|
[RelayCommand]
|
||||||
|
private async Task SendAllAsync()
|
||||||
|
{
|
||||||
|
if (Drafts.Count == 0) { Status = "Нет неотправленных накладных."; return; }
|
||||||
|
Status = null;
|
||||||
|
int ok = 0;
|
||||||
|
string? lastErr = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Busy = true;
|
||||||
|
foreach (var d in DraftStore.All.ToList())
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await CreateFromDraft(d);
|
||||||
|
DraftStore.Remove(d.Id);
|
||||||
|
ok++;
|
||||||
|
}
|
||||||
|
catch (Exception ex) { lastErr = ex.Message; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally { Busy = false; Load(); }
|
||||||
|
|
||||||
|
Status = lastErr is null
|
||||||
|
? $"✓ Отправлено накладных: {ok}."
|
||||||
|
: $"Отправлено: {ok}. Не удалось часть — {lastErr}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Удалить неотправленную накладную (не отправляя).</summary>
|
||||||
|
[RelayCommand]
|
||||||
|
private void Delete(DraftOrder? draft)
|
||||||
|
{
|
||||||
|
var d = draft ?? Selected;
|
||||||
|
if (d is null) return;
|
||||||
|
DraftStore.Remove(d.Id);
|
||||||
|
Load();
|
||||||
|
Status = "Накладная удалена.";
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<BuyerOrderResponse> CreateFromDraft(DraftOrder d)
|
||||||
|
{
|
||||||
|
var req = new BuyerOrderCreateRequest
|
||||||
|
{
|
||||||
|
// Номер EX резервировался при сохранении черновика — используем его.
|
||||||
|
GlobalSign = d.Number.StartsWith("EX-", StringComparison.OrdinalIgnoreCase) ? d.Number : null,
|
||||||
|
LocationId = d.LocationId,
|
||||||
|
Comment = d.Comment,
|
||||||
|
Items = d.Items.Select(i => new BuyerOrderItemReq
|
||||||
|
{
|
||||||
|
SupplierPriceId = i.SupplierPriceId,
|
||||||
|
Qty = (double)i.Qty,
|
||||||
|
ItemName = i.Name,
|
||||||
|
Barcode = i.Barcode
|
||||||
|
}).ToList()
|
||||||
|
};
|
||||||
|
return await _api.CreateOrderAsync(req);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,16 +1,19 @@
|
|||||||
<UserControl xmlns="https://github.com/avaloniaui"
|
<UserControl xmlns="https://github.com/avaloniaui"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:vm="using:Elfisa.Avalonia.ViewModels"
|
xmlns:vm="using:Elfisa.Avalonia.ViewModels"
|
||||||
|
xmlns:core="using:Elfisa.Core"
|
||||||
xmlns:conv="using:Avalonia.Data.Converters"
|
xmlns:conv="using:Avalonia.Data.Converters"
|
||||||
x:Class="Elfisa.Avalonia.Views.SendOrderView"
|
x:Class="Elfisa.Avalonia.Views.SendOrderView"
|
||||||
x:DataType="vm:SendOrderViewModel">
|
x:DataType="vm:SendOrderViewModel">
|
||||||
|
|
||||||
<DockPanel Margin="24">
|
<DockPanel Margin="24">
|
||||||
<Grid DockPanel.Dock="Top" Margin="0,0,0,14">
|
<Grid DockPanel.Dock="Top" Margin="0,0,0,14" ColumnDefinitions="*,Auto">
|
||||||
<StackPanel Spacing="2" VerticalAlignment="Center">
|
<StackPanel Grid.Column="0" Spacing="2" VerticalAlignment="Center">
|
||||||
<TextBlock Text="Отправить заказ" Classes="h1"/>
|
<TextBlock Text="Отправить" Classes="h1"/>
|
||||||
<TextBlock Text="Найдите позиции в прайсе, соберите корзину и отправьте поставщику" Classes="muted"/>
|
<TextBlock Text="Отправка неотправленных накладных из раздела «Заказы»" Classes="muted"/>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
|
<Button Grid.Column="1" Content="Обновить" VerticalAlignment="Center"
|
||||||
|
Command="{Binding RefreshCommand}"/>
|
||||||
</Grid>
|
</Grid>
|
||||||
|
|
||||||
<Border DockPanel.Dock="Bottom" Margin="0,10,0,0" Padding="10,7" CornerRadius="6"
|
<Border DockPanel.Dock="Bottom" Margin="0,10,0,0" Padding="10,7" CornerRadius="6"
|
||||||
@ -19,86 +22,68 @@
|
|||||||
<TextBlock Text="{Binding Status}" Foreground="{DynamicResource AccentPressed}" TextWrapping="Wrap" FontSize="12.5"/>
|
<TextBlock Text="{Binding Status}" Foreground="{DynamicResource AccentPressed}" TextWrapping="Wrap" FontSize="12.5"/>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
<Grid ColumnDefinitions="*,16,440">
|
<!-- Панель отправки: главное действие — отправить все -->
|
||||||
|
<Border DockPanel.Dock="Top" Classes="card" Padding="16" Margin="0,0,0,12">
|
||||||
|
<Grid ColumnDefinitions="*,Auto" VerticalAlignment="Center">
|
||||||
|
<StackPanel Grid.Column="0" Spacing="2" VerticalAlignment="Center">
|
||||||
|
<TextBlock Foreground="{DynamicResource Text}" FontWeight="SemiBold" FontSize="15"
|
||||||
|
Text="{Binding Count, StringFormat='Неотправленных накладных: {0}'}"/>
|
||||||
|
<TextBlock Classes="muted" FontSize="12.5"
|
||||||
|
Text="{Binding TotalSum, StringFormat='на сумму {0:N2}'}"/>
|
||||||
|
</StackPanel>
|
||||||
|
<Button Grid.Column="1" Classes="primary" Padding="26,12" FontSize="15"
|
||||||
|
Content="Отправить все ▸" Command="{Binding SendAllCommand}"
|
||||||
|
IsEnabled="{Binding !Busy}" IsVisible="{Binding !IsEmpty}"/>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
<!-- Прайс: поиск + результаты -->
|
<!-- Список накладных -->
|
||||||
<Border Grid.Column="0" Classes="card" Padding="0" ClipToBounds="True">
|
<Border Classes="card" Padding="0" ClipToBounds="True">
|
||||||
<DockPanel>
|
<Grid>
|
||||||
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Spacing="10" Margin="14">
|
<!-- Пусто -->
|
||||||
<TextBox Text="{Binding Search}" Width="330" Watermark="поиск по наименованию…"/>
|
<StackPanel IsVisible="{Binding IsEmpty}" VerticalAlignment="Center" HorizontalAlignment="Center"
|
||||||
<Button Classes="primary" Content="Найти" Command="{Binding SearchCommand}" IsEnabled="{Binding !Busy}"/>
|
Spacing="8" Margin="24">
|
||||||
</StackPanel>
|
<TextBlock Text="📭" FontSize="34" HorizontalAlignment="Center"/>
|
||||||
<Button DockPanel.Dock="Bottom" Classes="primary" Content="Добавить в заказ ▸"
|
<TextBlock Text="Нет неотправленных накладных" Classes="h2" HorizontalAlignment="Center"/>
|
||||||
Margin="14" HorizontalAlignment="Left"
|
<TextBlock Classes="muted" HorizontalAlignment="Center" TextAlignment="Center" MaxWidth="360" TextWrapping="Wrap"
|
||||||
Command="{Binding AddToCartCommand}"/>
|
Text="Соберите заказ в разделе «Прайс-лист» и нажмите «Сохранить заказ» — он появится здесь для отправки."/>
|
||||||
<DataGrid ItemsSource="{Binding Results}" SelectedItem="{Binding SelectedResult}"
|
</StackPanel>
|
||||||
x:CompileBindings="False" AutoGenerateColumns="False" IsReadOnly="True"
|
|
||||||
HeadersVisibility="Column" CanUserResizeColumns="True" CanUserSortColumns="False">
|
|
||||||
<DataGrid.Columns>
|
|
||||||
<DataGridTextColumn Header="Наименование" Width="*" Binding="{Binding DrugName}"/>
|
|
||||||
<DataGridTextColumn Header="Поставщик" Width="120" Binding="{Binding SupplierName}"/>
|
|
||||||
<DataGridTextColumn Header="Цена" Width="100" Binding="{Binding Price, StringFormat='{}{0:N2}'}" CellStyleClasses="num"/>
|
|
||||||
</DataGrid.Columns>
|
|
||||||
</DataGrid>
|
|
||||||
</DockPanel>
|
|
||||||
</Border>
|
|
||||||
|
|
||||||
<!-- Корзина -->
|
<!-- Есть накладные -->
|
||||||
<Border Grid.Column="2" Classes="card" Padding="16">
|
<ScrollViewer IsVisible="{Binding !IsEmpty}">
|
||||||
<DockPanel>
|
<ItemsControl ItemsSource="{Binding Drafts}" x:CompileBindings="False" Margin="0,0,0,14">
|
||||||
<TextBlock DockPanel.Dock="Top" Text="Корзина" Classes="h2" Margin="0,0,0,10"/>
|
<ItemsControl.ItemTemplate>
|
||||||
|
<DataTemplate x:DataType="core:DraftOrder">
|
||||||
<StackPanel DockPanel.Dock="Bottom" Spacing="10" Margin="0,12,0,0">
|
<Border Padding="14" Margin="14,14,14,0" CornerRadius="10"
|
||||||
<StackPanel Spacing="5">
|
Background="{DynamicResource RowAlt}" BorderThickness="1" BorderBrush="{DynamicResource Border}">
|
||||||
<TextBlock Text="Грузополучатель" Classes="muted"/>
|
<Grid ColumnDefinitions="*,Auto" VerticalAlignment="Center">
|
||||||
<ComboBox ItemsSource="{Binding Locations}" SelectedItem="{Binding SelectedLocation}"
|
<StackPanel Grid.Column="0" Spacing="3">
|
||||||
HorizontalAlignment="Stretch"/>
|
<TextBlock Text="{Binding Number}" FontWeight="Bold" FontSize="15" Foreground="{DynamicResource Text}"/>
|
||||||
</StackPanel>
|
<TextBlock Classes="muted" FontSize="12.5"
|
||||||
<TextBox Text="{Binding Comment}" Watermark="комментарий к заказу (необязательно)"/>
|
Text="{Binding CreatedAt, StringFormat='dd.MM.yyyy HH:mm'}"/>
|
||||||
<Grid ColumnDefinitions="*,Auto">
|
<TextBlock Classes="muted" FontSize="12.5" TextTrimming="CharacterEllipsis"
|
||||||
<TextBlock Grid.Column="0" Text="Итого" FontWeight="SemiBold" VerticalAlignment="Center"
|
Text="{Binding LocationAddress}"/>
|
||||||
Foreground="{DynamicResource Text}"/>
|
<TextBlock Classes="muted" FontSize="12.5"
|
||||||
<TextBlock Grid.Column="1" Text="{Binding CartTotal, StringFormat='{}{0:N2}'}"
|
Text="{Binding ItemsCount, StringFormat='Позиций: {0}'}"/>
|
||||||
FontWeight="Bold" FontSize="16" Foreground="{DynamicResource Accent}"/>
|
</StackPanel>
|
||||||
</Grid>
|
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="12" VerticalAlignment="Center">
|
||||||
<Button Classes="primary" Content="Отправить заказ" HorizontalAlignment="Stretch"
|
<TextBlock Text="{Binding Total, StringFormat='{}{0:N2}'}" FontWeight="Bold"
|
||||||
Command="{Binding SendCommand}" IsEnabled="{Binding !Busy}"/>
|
FontSize="16" Foreground="{DynamicResource Accent}" VerticalAlignment="Center"/>
|
||||||
</StackPanel>
|
<Button Classes="primary" Content="Отправить"
|
||||||
|
Command="{Binding $parent[ItemsControl].DataContext.SendCommand}"
|
||||||
<ScrollViewer>
|
|
||||||
<ItemsControl ItemsSource="{Binding Cart}" x:CompileBindings="False">
|
|
||||||
<ItemsControl.ItemTemplate>
|
|
||||||
<DataTemplate x:DataType="vm:CartItem">
|
|
||||||
<Border Padding="10" Margin="0,0,0,8" CornerRadius="9"
|
|
||||||
Background="{DynamicResource RowAlt}" BorderThickness="1" BorderBrush="{DynamicResource Border}">
|
|
||||||
<DockPanel>
|
|
||||||
<Button DockPanel.Dock="Right" Content="✕" Width="30" Height="30" Padding="0"
|
|
||||||
VerticalAlignment="Top" Background="Transparent"
|
|
||||||
Foreground="{DynamicResource Muted}" Cursor="Hand"
|
|
||||||
Command="{Binding $parent[ItemsControl].DataContext.RemoveFromCartCommand}"
|
|
||||||
CommandParameter="{Binding}"/>
|
CommandParameter="{Binding}"/>
|
||||||
<StackPanel Spacing="6">
|
<Button Content="✕" Width="32" Height="32" Padding="0" VerticalAlignment="Center"
|
||||||
<TextBlock Text="{Binding Name}" Foreground="{DynamicResource Text}"
|
Background="Transparent" Foreground="{DynamicResource Muted}" Cursor="Hand"
|
||||||
TextWrapping="Wrap" MaxLines="2" TextTrimming="CharacterEllipsis"/>
|
Command="{Binding $parent[ItemsControl].DataContext.DeleteCommand}"
|
||||||
<TextBlock Text="{Binding Supplier}" Classes="muted"/>
|
CommandParameter="{Binding}"/>
|
||||||
<Grid ColumnDefinitions="Auto,*,Auto" VerticalAlignment="Center">
|
</StackPanel>
|
||||||
<NumericUpDown Grid.Column="0" Value="{Binding Qty}" Minimum="1" Maximum="100000"
|
</Grid>
|
||||||
Increment="1" FormatString="0" Width="120"/>
|
</Border>
|
||||||
<TextBlock Grid.Column="1" Text="{Binding Price, StringFormat='× {0:N2}'}"
|
</DataTemplate>
|
||||||
Classes="muted" VerticalAlignment="Center" Margin="10,0"/>
|
</ItemsControl.ItemTemplate>
|
||||||
<TextBlock Grid.Column="2" Text="{Binding LineSum, StringFormat='{}{0:N2}'}"
|
</ItemsControl>
|
||||||
FontWeight="SemiBold" Foreground="{DynamicResource Text}"
|
</ScrollViewer>
|
||||||
VerticalAlignment="Center"/>
|
</Grid>
|
||||||
</Grid>
|
</Border>
|
||||||
</StackPanel>
|
|
||||||
</DockPanel>
|
|
||||||
</Border>
|
|
||||||
</DataTemplate>
|
|
||||||
</ItemsControl.ItemTemplate>
|
|
||||||
</ItemsControl>
|
|
||||||
</ScrollViewer>
|
|
||||||
</DockPanel>
|
|
||||||
</Border>
|
|
||||||
</Grid>
|
|
||||||
</DockPanel>
|
</DockPanel>
|
||||||
</UserControl>
|
</UserControl>
|
||||||
|
|||||||
@ -37,12 +37,14 @@ public sealed class ApiClient
|
|||||||
public async Task<LoginResponse> LoginAsync(string username, string password)
|
public async Task<LoginResponse> LoginAsync(string username, string password)
|
||||||
{
|
{
|
||||||
var body = JsonSerializer.Serialize(new LoginRequest { Username = username, Password = password }, Json);
|
var body = JsonSerializer.Serialize(new LoginRequest { Username = username, Password = password }, Json);
|
||||||
using var req = new HttpRequestMessage(HttpMethod.Post, Url("/auth/login"))
|
|
||||||
{
|
|
||||||
Content = new StringContent(body, Encoding.UTF8, "application/json")
|
|
||||||
};
|
|
||||||
HttpResponseMessage resp;
|
HttpResponseMessage resp;
|
||||||
try { resp = await _http.SendAsync(req).ConfigureAwait(false); }
|
try
|
||||||
|
{
|
||||||
|
resp = await SendWithRetryAsync(() => new HttpRequestMessage(HttpMethod.Post, Url("/auth/login"))
|
||||||
|
{
|
||||||
|
Content = new StringContent(body, Encoding.UTF8, "application/json")
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
catch (Exception ex) { throw new ApiException($"Не удалось связаться с сервером ({_baseUrl}): {ex.Message}", ex); }
|
catch (Exception ex) { throw new ApiException($"Не удалось связаться с сервером ({_baseUrl}): {ex.Message}", ex); }
|
||||||
|
|
||||||
var text = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
|
var text = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||||
@ -164,10 +166,16 @@ public sealed class ApiClient
|
|||||||
|
|
||||||
private async Task<string> AuthorizedGetAsync(string path, string op)
|
private async Task<string> AuthorizedGetAsync(string path, string op)
|
||||||
{
|
{
|
||||||
using var req = new HttpRequestMessage(HttpMethod.Get, Url(path));
|
|
||||||
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
|
|
||||||
HttpResponseMessage resp;
|
HttpResponseMessage resp;
|
||||||
try { resp = await _http.SendAsync(req).ConfigureAwait(false); }
|
try
|
||||||
|
{
|
||||||
|
resp = await SendWithRetryAsync(() =>
|
||||||
|
{
|
||||||
|
var r = new HttpRequestMessage(HttpMethod.Get, Url(path));
|
||||||
|
r.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
|
||||||
|
return r;
|
||||||
|
}).ConfigureAwait(false);
|
||||||
|
}
|
||||||
catch (Exception ex) { throw new ApiException($"Не удалось выполнить {op}: {ex.Message}", ex); }
|
catch (Exception ex) { throw new ApiException($"Не удалось выполнить {op}: {ex.Message}", ex); }
|
||||||
|
|
||||||
var text = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
|
var text = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||||
@ -176,6 +184,21 @@ public sealed class ApiClient
|
|||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Отправляет запрос с повтором на транзиентных сбоях (холодный TLS,
|
||||||
|
/// сброс соединения, hairpin-NAT) — чтобы поиск/загрузка не падали с первого раза.</summary>
|
||||||
|
private async Task<HttpResponseMessage> SendWithRetryAsync(Func<HttpRequestMessage> make, int retries = 2)
|
||||||
|
{
|
||||||
|
Exception? last = null;
|
||||||
|
for (int attempt = 0; attempt <= retries; attempt++)
|
||||||
|
{
|
||||||
|
using var req = make();
|
||||||
|
try { return await _http.SendAsync(req).ConfigureAwait(false); }
|
||||||
|
catch (HttpRequestException ex) { last = ex; } // сеть/TLS — повторяем
|
||||||
|
if (attempt < retries) await Task.Delay(250 * (attempt + 1)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
throw last!;
|
||||||
|
}
|
||||||
|
|
||||||
private void EnsureAuth()
|
private void EnsureAuth()
|
||||||
{
|
{
|
||||||
if (!IsAuthenticated) throw new ApiException("Требуется авторизация.");
|
if (!IsAuthenticated) throw new ApiException("Требуется авторизация.");
|
||||||
|
|||||||
@ -1,6 +1,9 @@
|
|||||||
|
using System;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace Elfisa.Core;
|
namespace Elfisa.Core;
|
||||||
|
|
||||||
/// <summary>Текущая сессия пользователя (токен, роль, логин).</summary>
|
/// <summary>Текущая сессия пользователя (токен, роль, логин). Сохраняется между запусками.</summary>
|
||||||
public sealed class Session
|
public sealed class Session
|
||||||
{
|
{
|
||||||
public static Session Current { get; } = new();
|
public static Session Current { get; } = new();
|
||||||
@ -11,10 +14,57 @@ public sealed class Session
|
|||||||
|
|
||||||
public bool IsAuthenticated => !string.IsNullOrWhiteSpace(Token);
|
public bool IsAuthenticated => !string.IsNullOrWhiteSpace(Token);
|
||||||
|
|
||||||
|
/// <summary>Сохранить сессию в настройки (чтобы не логиниться каждый раз).</summary>
|
||||||
|
public void Save()
|
||||||
|
{
|
||||||
|
SettingsStore.Current.Token = Token;
|
||||||
|
SettingsStore.Current.Role = Role;
|
||||||
|
SettingsStore.Current.Username = Username;
|
||||||
|
SettingsStore.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Восстановить сессию из настроек, если токен есть и не истёк.</summary>
|
||||||
|
public static bool TryRestore()
|
||||||
|
{
|
||||||
|
var s = SettingsStore.Current;
|
||||||
|
if (string.IsNullOrWhiteSpace(s.Token) || IsJwtExpired(s.Token))
|
||||||
|
return false;
|
||||||
|
Current.Token = s.Token;
|
||||||
|
Current.Role = s.Role;
|
||||||
|
Current.Username = s.Username;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
public void Clear()
|
public void Clear()
|
||||||
{
|
{
|
||||||
Token = null;
|
Token = null;
|
||||||
Role = null;
|
Role = null;
|
||||||
Username = null;
|
Username = null;
|
||||||
|
SettingsStore.Current.Token = null;
|
||||||
|
SettingsStore.Current.Role = null;
|
||||||
|
SettingsStore.Current.Username = null;
|
||||||
|
SettingsStore.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Проверяет, истёк ли JWT (по claim exp), с запасом в 1 минуту.</summary>
|
||||||
|
private static bool IsJwtExpired(string token)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var parts = token.Split('.');
|
||||||
|
if (parts.Length != 3) return true;
|
||||||
|
var payload = parts[1].Replace('-', '+').Replace('_', '/');
|
||||||
|
switch (payload.Length % 4)
|
||||||
|
{
|
||||||
|
case 2: payload += "=="; break;
|
||||||
|
case 3: payload += "="; break;
|
||||||
|
}
|
||||||
|
var json = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(payload));
|
||||||
|
using var doc = JsonDocument.Parse(json);
|
||||||
|
if (doc.RootElement.TryGetProperty("exp", out var exp) && exp.TryGetInt64(out var expUnix))
|
||||||
|
return DateTimeOffset.UtcNow.ToUnixTimeSeconds() >= expUnix - 60;
|
||||||
|
return false; // нет exp — считаем валидным
|
||||||
|
}
|
||||||
|
catch { return true; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -116,6 +116,8 @@
|
|||||||
background:var(--brand-soft); color:var(--brand-ink); border:1px solid color-mix(in srgb,var(--brand) 26%, transparent)}
|
background:var(--brand-soft); color:var(--brand-ink); border:1px solid color-mix(in srgb,var(--brand) 26%, transparent)}
|
||||||
.dl:hover{background:var(--brand); color:#fff}
|
.dl:hover{background:var(--brand); color:#fff}
|
||||||
.dl svg{width:17px; height:17px; fill:currentColor}
|
.dl svg{width:17px; height:17px; fill:currentColor}
|
||||||
|
.dl.soon{background:var(--panel-2); color:var(--muted); border-color:var(--line); cursor:default}
|
||||||
|
.dl.soon:hover{background:var(--panel-2); color:var(--muted)}
|
||||||
|
|
||||||
/* ---- features ---- */
|
/* ---- features ---- */
|
||||||
.feats{padding:30px 0 8px; display:grid; grid-template-columns:repeat(3,1fr); gap:14px}
|
.feats{padding:30px 0 8px; display:grid; grid-template-columns:repeat(3,1fr); gap:14px}
|
||||||
@ -173,7 +175,7 @@
|
|||||||
<div class="spec"><span>Формат</span><b>.exe установщик</b></div>
|
<div class="spec"><span>Формат</span><b>.exe установщик</b></div>
|
||||||
<div class="spec"><span>Система</span><b>Windows 10 / 11</b></div>
|
<div class="spec"><span>Система</span><b>Windows 10 / 11</b></div>
|
||||||
<div class="spec"><span>Разрядность</span><b>64-бит</b></div>
|
<div class="spec"><span>Разрядность</span><b>64-бит</b></div>
|
||||||
<div class="spec"><span>Размер</span><b>~90 МБ</b></div>
|
<div class="spec"><span>Размер</span><b>~48 МБ</b></div>
|
||||||
</div>
|
</div>
|
||||||
<a class="dl" href="ElfisaPharmacy-Setup.exe" download>
|
<a class="dl" href="ElfisaPharmacy-Setup.exe" download>
|
||||||
<svg viewBox="0 0 24 24"><path d="M12 3v10m0 0 4-4m-4 4-4-4M4 17v2a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
<svg viewBox="0 0 24 24"><path d="M12 3v10m0 0 4-4m-4 4-4-4M4 17v2a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||||
@ -185,17 +187,14 @@
|
|||||||
<span class="youbadge">Ваша система</span>
|
<span class="youbadge">Ваша система</span>
|
||||||
<div class="os-ico"><svg viewBox="0 0 24 24"><path d="M16.4 12.7c0-2.3 1.9-3.4 2-3.5-1.1-1.6-2.8-1.8-3.4-1.8-1.4-.1-2.8.9-3.5.9-.7 0-1.8-.8-3-.8-1.5 0-3 .9-3.8 2.3-1.6 2.8-.4 7 1.2 9.3.8 1.1 1.7 2.4 2.9 2.3 1.2 0 1.6-.7 3-.7s1.8.7 3 .7c1.2 0 2-1.1 2.8-2.2.5-.8.9-1.6 1.2-2.5-.1 0-2.1-.9-2.1-3.2zM14.2 5.9c.6-.8 1-1.8.9-2.9-.9 0-2 .6-2.6 1.4-.6.7-1.1 1.7-.9 2.7 1 .1 2-.5 2.6-1.2z"/></svg></div>
|
<div class="os-ico"><svg viewBox="0 0 24 24"><path d="M16.4 12.7c0-2.3 1.9-3.4 2-3.5-1.1-1.6-2.8-1.8-3.4-1.8-1.4-.1-2.8.9-3.5.9-.7 0-1.8-.8-3-.8-1.5 0-3 .9-3.8 2.3-1.6 2.8-.4 7 1.2 9.3.8 1.1 1.7 2.4 2.9 2.3 1.2 0 1.6-.7 3-.7s1.8.7 3 .7c1.2 0 2-1.1 2.8-2.2.5-.8.9-1.6 1.2-2.5-.1 0-2.1-.9-2.1-3.2zM14.2 5.9c.6-.8 1-1.8.9-2.9-.9 0-2 .6-2.6 1.4-.6.7-1.1 1.7-.9 2.7 1 .1 2-.5 2.6-1.2z"/></svg></div>
|
||||||
<h3>macOS</h3>
|
<h3>macOS</h3>
|
||||||
<p class="os-sub">Образ диска · Apple Silicon и Intel</p>
|
<p class="os-sub">Apple Silicon и Intel · готовим сборку</p>
|
||||||
<div class="specs">
|
<div class="specs">
|
||||||
<div class="spec"><span>Формат</span><b>.dmg образ</b></div>
|
<div class="spec"><span>Формат</span><b>.dmg образ</b></div>
|
||||||
<div class="spec"><span>Система</span><b>macOS 12+</b></div>
|
<div class="spec"><span>Система</span><b>macOS 12+</b></div>
|
||||||
<div class="spec"><span>Процессор</span><b>Apple / Intel</b></div>
|
<div class="spec"><span>Процессор</span><b>Apple / Intel</b></div>
|
||||||
<div class="spec"><span>Размер</span><b>~95 МБ</b></div>
|
<div class="spec"><span>Статус</span><b>скоро</b></div>
|
||||||
</div>
|
</div>
|
||||||
<a class="dl" href="Elfisa-macOS.dmg" download>
|
<span class="dl soon">Скоро</span>
|
||||||
<svg viewBox="0 0 24 24"><path d="M12 3v10m0 0 4-4m-4 4-4-4M4 17v2a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
|
||||||
Скачать образ .dmg
|
|
||||||
</a>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card" data-os="linux">
|
<div class="card" data-os="linux">
|
||||||
@ -207,7 +206,7 @@
|
|||||||
<div class="spec"><span>Формат</span><b>.AppImage</b></div>
|
<div class="spec"><span>Формат</span><b>.AppImage</b></div>
|
||||||
<div class="spec"><span>Система</span><b>glibc 2.31+</b></div>
|
<div class="spec"><span>Система</span><b>glibc 2.31+</b></div>
|
||||||
<div class="spec"><span>Разрядность</span><b>x86-64</b></div>
|
<div class="spec"><span>Разрядность</span><b>x86-64</b></div>
|
||||||
<div class="spec"><span>Размер</span><b>~95 МБ</b></div>
|
<div class="spec"><span>Размер</span><b>~38 МБ</b></div>
|
||||||
</div>
|
</div>
|
||||||
<a class="dl" href="Elfisa-Linux-x86_64.AppImage" download>
|
<a class="dl" href="Elfisa-Linux-x86_64.AppImage" download>
|
||||||
<svg viewBox="0 0 24 24"><path d="M12 3v10m0 0 4-4m-4 4-4-4M4 17v2a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
<svg viewBox="0 0 24 24"><path d="M12 3v10m0 0 4-4m-4 4-4-4M4 17v2a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||||
@ -234,9 +233,9 @@
|
|||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function(){
|
(function(){
|
||||||
var files = { windows:"ElfisaPharmacy-Setup.exe", mac:"Elfisa-macOS.dmg", linux:"Elfisa-Linux-x86_64.AppImage" };
|
var files = { windows:"ElfisaPharmacy-Setup.exe", mac:null, linux:"Elfisa-Linux-x86_64.AppImage" };
|
||||||
var labels = { windows:"Скачать для Windows", mac:"Скачать для macOS", linux:"Скачать для Linux" };
|
var labels = { windows:"Скачать для Windows", mac:"Версия для macOS — скоро", linux:"Скачать для Linux" };
|
||||||
var metas = { windows:"Windows 10/11 · 64-бит · ~90 МБ", mac:"macOS 12+ · Apple/Intel · ~95 МБ", linux:"x86-64 · glibc 2.31+ · ~95 МБ" };
|
var metas = { windows:"Windows 10/11 · 64-бит · ~48 МБ", mac:"сборка готовится · выберите систему ниже", linux:"x86-64 · glibc 2.31+ · ~38 МБ" };
|
||||||
|
|
||||||
function detect(){
|
function detect(){
|
||||||
var ua = navigator.userAgent || "";
|
var ua = navigator.userAgent || "";
|
||||||
@ -249,9 +248,12 @@
|
|||||||
|
|
||||||
var os = detect();
|
var os = detect();
|
||||||
var hero = document.getElementById("heroBtn");
|
var hero = document.getElementById("heroBtn");
|
||||||
if (hero){ hero.setAttribute("href", files[os]); }
|
|
||||||
var lbl = document.getElementById("heroLbl"); if(lbl) lbl.textContent = labels[os];
|
var lbl = document.getElementById("heroLbl"); if(lbl) lbl.textContent = labels[os];
|
||||||
var meta = document.getElementById("heroMeta"); if(meta) meta.textContent = metas[os];
|
var meta = document.getElementById("heroMeta"); if(meta) meta.textContent = metas[os];
|
||||||
|
if (hero){
|
||||||
|
if (files[os]){ hero.setAttribute("href", files[os]); hero.setAttribute("download",""); }
|
||||||
|
else { hero.setAttribute("href", "#os"); hero.removeAttribute("download"); hero.classList.add("soon-hero"); }
|
||||||
|
}
|
||||||
|
|
||||||
var card = document.querySelector('.card[data-os="'+os+'"]');
|
var card = document.querySelector('.card[data-os="'+os+'"]');
|
||||||
if (card){ card.classList.add("you"); }
|
if (card){ card.classList.add("you"); }
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user