订单列表增加 同步订单

This commit is contained in:
chfei committed 2026-08-19 15:35:42 +08:00
1 parent 4f606c3561
commit cef6300e8e
24 files changed
+2674 -1211

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -1,4 +1,5 @@
using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.Commands;
using _29WxOrderWpf.Common;
using _29WxOrderWpf.Ctrls.BuyerCtrls;
using _29WxOrderWpf.Ctrls.Statistics;
@@ -1936,25 +1937,36 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
int errorCount = 0;
foreach (oms_wei_order_info item in list)
{
var rst = await WxApiBLL.WxSearchAndDropshipCancelAsync(item.Shop, item);
if (rst == "success")
try
{
var ret = await _shipGiftService.Send(item.order_id, giftType);
if (ret)
var rst = await WxApiBLL.WxSearchAndDropshipCancelAsync(item.Shop, item);
if (rst == "success")
{
sucessCount++;
item.gift_order_status = 1;
this.FilterOneOrder(item, true);
var ret = await _shipGiftService.Send(item.order_id, giftType);
if (ret)
{
sucessCount++;
item.gift_order_status = 1;
this.FilterOneOrder(item, true);
}
else
{
errorCount++;
}
}
else
{
errorCount++;
}
}
else
catch (Exception ex)
{
errorCount++;
}
finally
{
item.IsSelect = false;
}
SetProgress(index, count);
BottomMsg = $"礼品单发送进度:{index}/{count}\t\t{item.orderItems.FirstOrDefault()?.title ?? ""}";
@@ -1972,6 +1984,181 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
}
}
/// <summary>
/// 拉取微信订单到任务列表
/// </summary>
public ICommand PullWXOrderCommand => new AsyncDelegateCommand(PullWXOrder);
private async Task PullWXOrder()
{
try
{
var isAfterSales = GlobalConfig.OrderTabHeaderStr.StartsWith("需处理售后单");//是否售后
var selectedShops = GlobalConfig.ShopLoginList.Where(a => a.IsSelect).ToList();
if (selectedShops.Count == 0)
{
selectedShops = GlobalConfig.ShopLoginList.ToList();
}
var selectedOrders = GlobalConfig.lstFilterOrder.Where(a => a.IsSelect).ToList();
int count = selectedOrders.Count;
if (count > 0 && isAfterSales == false)//非售后订单
{
if (BaseMsgWindow.ShowConfirm($"已选取:{count}个订单", "同步订单", MainWindow.Instance, MsgWindowLevel.MEDIUM).DialogResult == false) return;
BottomMsg = $"订单同步进度....";
int index = 1;
int sucessCount = 0;
int errorCount = 0;
foreach (var item in selectedOrders)
{
var ret = await PullWXOrderService.Instance.PullOrderDetailAsync(item.shop_id, item.order_id); ;
if (ret)
{
sucessCount++;
this.GetOrder(item.order_id);
SetProgress(index, count);
item.IsSelect = false;
}
else
{
errorCount++;
}
BottomMsg = $"订单同步进度:{index}/{count}\t\t{item.orderItems.FirstOrDefault()?.title ?? ""}";
index++;
}
BottomMsg = $"订单同步进度完成 成功:{sucessCount} 失败:{errorCount} 总数:{count}";
}
else if (count > 0 && isAfterSales == true)//售后订单
{
if (BaseMsgWindow.ShowConfirm($"已选取:{count}个售后订单", "同步订单", MainWindow.Instance, MsgWindowLevel.MEDIUM).DialogResult == false) return;
//var dictionaryResult = selectedOrders
// .Where(o => o?.refundItems != null)
// .SelectMany(o => o.refundItems
// .Where(item => item != null)
// .Select(item => new { o.shop_id, item.after_sale_order_id }))
// .GroupBy(x => x.shop_id)
// .ToDictionary(
// g => g.Key,
// g => g.Select(x => x.after_sale_order_id).ToArray()
// );
//BottomMsg = $"售后订单同步进度....";
//foreach (var item in dictionaryResult)
//{
// var ret = await PullWXOrderService.Instance.PullAfterSaleOrdersAsync(item.Key, item.Value);
//}
//BottomMsg = $"售后同步任务已发送,等待同步完成";
int index = 1;
int sucessCount = 0;
int errorCount = 0;
BottomMsg = $"售后订单同步进度....";
foreach (KeyValuePair<long, List<oms_wei_order_info>> item in selectedOrders.GroupBy(a => a.shop_id).ToDictionary(a => a.Key, a => a.ToList()))
{
long shopid = item.Key;
string shopName = item.Value.FirstOrDefault()?.shop_name ?? "";
string[] afterSaleOrderIds = item.Value.SelectMany(a => a.refundItems).Where(a => a != null).Select(a => a.after_sale_order_id).ToArray();
var ret = await PullWXOrderService.Instance.PullAfterSaleOrdersAsync(shopid, afterSaleOrderIds);
if (ret)
{
sucessCount++;
SetProgress(index, count);
item.Value.ForEach(a => a.IsSelect = false);
}
else
{
errorCount++;
}
BottomMsg = $"售后订单同步进度:{index}/{count}\t\t{shopName}";
index++;
}
BottomMsg = $"售后同步任务已发送,等待同步完成";
}
else
{
count = selectedShops.Count;
string prefix = $"已选取:{count}个商铺";
if (count == GlobalConfig.ShopLoginList.Count)
{
prefix = "已选取全部商铺";
}
var startTime = dateStart.SelectedDate.Value;
var endTime = dateEnd.SelectedDate.Value;
string msg = "";
if (isAfterSales)
{
msg = $"{prefix}";
}
else
{
msg = $"{prefix}\n\n时间范围:{startTime.ToString("yyyy-MM-dd")}-{endTime.ToString("yyyy-MM-dd")}";
}
if (BaseMsgWindow.ShowConfirm(msg, $"{(isAfterSales ? "售后" : "")}同步订单", MainWindow.Instance, MsgWindowLevel.MEDIUM).DialogResult == false) return;
if ((endTime - startTime).Days > 7)
{
throw new Exception("时间范围最大7天");
}
var ret = false;
if (isAfterSales)
{
ret = await PullWXOrderService.Instance.PullRefundOrderByShopsAsync(selectedShops.Select(a => a.ErpShopId.ParseToLong()).ToArray(), startTime, endTime);
}
else
{
ret = await PullWXOrderService.Instance.PullOrderByShopIdsAndTimeRangeAsync(selectedShops.Select(a => a.ErpShopId.ParseToLong()).ToArray(), startTime, endTime);
}
if (ret)
{
BaseMsgWindow.ShowInfo("同步任务已发送,等待同步完成\n任务详情查看任务列表");
}
else
{
BaseMsgWindow.ShowError("同步任务失败");
}
}
}
catch (Exception ex)
{
BaseMsgWindow.ShowError("同步订单失败\n" + ex.Message, "Error");
}
//var service = PullWXOrderService.Instance;
//foreach (var item in list)
//{
// await service.PullOrderDetailAsync(item.shop_id, item.order_id);
//}
}
private DialogWindow _taskDialog;
public ICommand ShowTaskDialogViewCommand => new DelegateCommand(ShowTaskDialogView);
private void ShowTaskDialogView()
{
if (_taskDialog == null)
{
_taskDialog = new DialogWindow()
{
Title = "任务列表",
Content = new OrderTaskDialogView(),
};
_taskDialog.Closed += (s, e) => _taskDialog = null;
}
_taskDialog.Show();
}
}
public class OrderFilterConfig
@@ -0,0 +1,241 @@
<UserControl
x:Class="_29WxOrderWpf.Ctrls.OrderCtrls.OrderTaskDialogView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:_29WxOrderWpf.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.OrderCtrls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wpf="clr-namespace:_29WxOrderWpf.Common"
xmlns:wpf1="WPFCommon"
d:Background="White"
d:DataContext="{d:DesignInstance Type=local:OrderTaskDialogViewModel}"
d:DesignHeight="600"
d:DesignWidth="1300"
wpf:DialogWindowProperty.Height="600"
wpf:DialogWindowProperty.ResizeMode="CanResizeWithGrip"
wpf:DialogWindowProperty.ShowMinButton="False"
wpf:DialogWindowProperty.Width="1300"
mc:Ignorable="d">
<UserControl.Resources>
<!-- 单元格文字居中 -->
<Style x:Key="CenterCellTextStyle" TargetType="TextBlock">
<Setter Property="TextAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<!-- 面板标题 -->
<Style x:Key="PanelTitleStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="#333333" />
</Style>
<!-- 工具栏按钮 -->
<Style x:Key="ToolBarButtonStyle" TargetType="Button">
<Setter Property="Height" Value="30" />
<Setter Property="Padding" Value="14,0" />
<Setter Property="Margin" Value="6,0,0,0" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Foreground" Value="#333333" />
<Setter Property="Background" Value="White" />
<Setter Property="BorderBrush" Value="#D9D9D9" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border
x:Name="btnBorder"
Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="{TemplateBinding Content}"
ContentStringFormat="{TemplateBinding ContentStringFormat}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="btnBorder" Property="Background" Value="#F0F2F5" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="btnBorder" Property="Background" Value="#E4E7ED" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- 任务状态:int (1=执行中,2=已完成,3=已人为中断) → 中文描述 -->
<converters:OrderTaskStatusConverter x:Key="OrderTaskStatusConverter" />
</UserControl.Resources>
<Grid Background="#F5F7FB">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<!-- ============ 顶部工具栏 ============ -->
<Border
Grid.Row="0"
Padding="14,10"
Background="White"
BorderBrush="#E8EAED"
BorderThickness="0,0,0,1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<TextBlock Style="{StaticResource PanelTitleStyle}" Text="订单同步任务列表" />
<CheckBox
Margin="20,0,0,0"
VerticalAlignment="Center"
Content="查看全部"
IsChecked="{Binding IsShowAll}" />
</StackPanel>
<!--<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button
Command="{Binding ClearFinishedCommand}"
Content="清空已完成"
Style="{StaticResource ToolBarButtonStyle}" />
<Button
Command="{Binding ClearAllCommand}"
Content="清空全部"
Style="{StaticResource ToolBarButtonStyle}" />
</StackPanel>-->
</Grid>
</Border>
<!-- ============ 任务列表 ============ -->
<DataGrid
Grid.Row="1"
Margin="10,10,10,0"
d:ItemsSource="{d:SampleData ItemCount=10}"
AlternatingRowBackground="#FAFAFA"
AutoGenerateColumns="False"
Background="White"
BorderBrush="#E8EAED"
BorderThickness="1"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
CanUserResizeRows="False"
ColumnHeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}"
FontSize="13"
Foreground="#333333"
GridLinesVisibility="Horizontal"
HeadersVisibility="Column"
HorizontalGridLinesBrush="#EEEEEE"
IsReadOnly="True"
ItemsSource="{Binding TasksView}"
RowHeight="40"
ScrollViewer.CanContentScroll="True"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
SelectionMode="Single"
SelectionUnit="FullRow">
<DataGrid.Columns>
<!-- 任务描述 -->
<DataGridTextColumn
Width="1.5*"
MinWidth="120"
Binding="{Binding TaskDescribe}"
ElementStyle="{StaticResource CenterCellTextStyle}"
Header="任务描述" />
<!-- 店铺 -->
<DataGridTextColumn
Width="1*"
MinWidth="100"
Binding="{Binding ShopName}"
ElementStyle="{StaticResource CenterCellTextStyle}"
Header="店铺" />
<!-- 状态 -->
<DataGridTemplateColumn
Width="1*"
MinWidth="60"
Header="状态">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontWeight="Bold"
Text="{Binding Status, Converter={StaticResource OrderTaskStatusConverter}}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="#E6A23C" />
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="2">
<Setter Property="Foreground" Value="#67C23A" />
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="3">
<Setter Property="Foreground" Value="#F56C6C" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!-- 失败原因 -->
<DataGridTextColumn
Width="2*"
MinWidth="150"
Binding="{Binding TaskFailReason}"
ElementStyle="{StaticResource CenterCellTextStyle}"
Header="失败原因" />
<!-- 创建时间 -->
<DataGridTextColumn
Width="2*"
MinWidth="140"
Binding="{Binding CreateTime, StringFormat={}{0:yyyy-MM-dd HH:mm:ss}}"
ElementStyle="{StaticResource CenterCellTextStyle}"
Header="创建时间" />
<!-- 更新时间 -->
<DataGridTextColumn
Width="2*"
MinWidth="140"
Binding="{Binding UpdateTime, StringFormat={}{0:yyyy-MM-dd HH:mm:ss}}"
ElementStyle="{StaticResource CenterCellTextStyle}"
Header="更新时间" />
<!-- 备注 -->
<DataGridTextColumn
Width="2*"
MinWidth="140"
Binding="{Binding Remark}"
ElementStyle="{StaticResource CenterCellTextStyle}"
Header="备注" />
</DataGrid.Columns>
</DataGrid>
<Border
Grid.Row="2"
Padding="10,0"
Background="White">
<Grid VerticalAlignment="Center">
<TextBlock
HorizontalAlignment="Right"
d:Text="距离下次刷新10秒"
Text="{Binding RefreshTime, StringFormat='距离下次刷新:{0}秒'}" />
</Grid>
</Border>
</Grid>
</UserControl>
@@ -0,0 +1,185 @@
using _29WxOrderWpf.Commands;
using _29WxOrderWpf.Services;
using AllBase.Model.MvvmBaseClasses;
using AllBase.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Work.KJDServer.API.Models;
using WPFCommon.Models;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
namespace _29WxOrderWpf.Ctrls.OrderCtrls;
/// <summary>
/// OrderTaskDialogView.xaml 的交互逻辑
/// </summary>
public partial class OrderTaskDialogView : UserControl
{
private readonly OrderTaskDialogViewModel _viewModel;
public OrderTaskDialogView()
{
InitializeComponent();
this.Loaded += OrderTaskDialogView_Loaded;
_viewModel = new OrderTaskDialogViewModel();
DataContext = _viewModel;
}
private async void OrderTaskDialogView_Loaded(object sender, RoutedEventArgs e)
{
await _viewModel.LoadTasks();
}
}
/// <summary>
/// 任务列表 - ViewModel
/// </summary>
public class OrderTaskDialogViewModel : BindableBaseEx, IDisposable
{
private DispatcherTimer _timer;
private const int RefreshIntervals = 10;
private int _timeCount = 0;
private readonly PullWXOrderService _service;
private readonly NotifyCollectionChangedEventHandler _collectionChangedHandler;
public OrderTaskDialogViewModel()
: this(PullWXOrderService.Instance)
{
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromSeconds(1);
_timer.Tick += _timer_Tick;
_timer.Start();
}
private async void _timer_Tick(object sender, EventArgs e)
{
_timeCount++;
if (_timeCount % RefreshIntervals == 0)
{
await LoadTasks();
_timeCount = 0;
}
RefreshTime = RefreshIntervals - _timeCount;
}
public OrderTaskDialogViewModel(PullWXOrderService service)
{
_service = service ?? PullWXOrderService.Instance;
Tasks = _service.Tasks;
_collectionChangedHandler = OnTasksCollectionChanged;
Tasks.CollectionChanged += _collectionChangedHandler;
ClearFinishedCommand = new DelegateCommand(ClearFinished);
ClearAllCommand = new DelegateCommand(ClearAll);
UpdateSummary();
TasksView = CollectionViewSource.GetDefaultView(Tasks);
TasksView.Filter = FilterTaskStatus;
}
public async Task LoadTasks()
{
await _service.GetTaskStatus();
}
private bool FilterTaskStatus(object obj)
{
if (obj is not OrderTask task)
return false;
if (IsShowAll == true)
return true;
return task.Status == 1 || task.Status == 3;
}
/// <summary>任务列表</summary>
public ObservableCollection<OrderTask> Tasks { get; }
public ICollectionView TasksView { get; }
/// <summary>清空已完成/失败任务</summary>
public ICommand ClearFinishedCommand { get; }
/// <summary>清空全部任务</summary>
public ICommand ClearAllCommand { get; }
/// <summary>汇总文字(总数/执行中/成功/失败)</summary>
public string SummaryText
{
get => GetValue<string>();
set => SetValue(value);
}
public int RefreshTime
{
get => GetValue<int>();
set => SetValue(value);
}
public bool IsShowAll
{
get => GetValue<bool>();
set
{
SetValue(value);
TasksView.Refresh();
}
}
private void ClearFinished()
{
_service.ClearFinished();
}
private void ClearAll()
{
if (System.Windows.MessageBox.Show("确定清空全部任务吗?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK)
return;
_service.ClearAll();
}
private void OnTasksCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdateSummary();
}
private void OnTaskPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(OrderTask.Status))
UpdateSummary();
}
private void UpdateSummary()
{
var items = Tasks;
//int running = items.Count(t => t.Status == OrderTask.Running);
//int success = items.Count(t => t.Status == OrderTask.Success);
//int failed = items.Count(t => t.Status == OrderTask.Failed);
//string.Format("任务总数:{0} 执行中:{1} 成功:{2} 失败:{3}",
//items.Length, running, success, failed);
}
public void Dispose()
{
_timer.Stop();
_timer = null;
}
}