Compare commits

...
194 Commits
Author SHA1 Message Date
wule e3f4e34def 添加新扣费选项筛选条件 2026-11-16 13:41:36 +08:00
wule 9e10d29bfe 修改订单读取函数 2026-11-13 19:37:46 +08:00
wule 8008dfb527 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-13 14:48:52 +08:00
wule 4ca9c082a1 新版本号 2026-11-13 14:48:46 +08:00
wule 5f08abec0f Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-13 14:48:12 +08:00
wule b8674a11c5 优化礼物单问题 2026-11-13 14:48:01 +08:00
wule 5ef326d19c 新版本号 2026-11-12 19:09:29 +08:00
wule 2295b0df48 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-12 19:08:40 +08:00
wule 15b8288a98 优化中转仓处理逻辑 2026-11-12 19:08:35 +08:00
chfei d9e8011564 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-12 15:36:28 +08:00
chfei fb8e6a5479 自动读单 增加启动参数控制 2026-11-12 15:36:22 +08:00
wule c7cdf3ff88 新版本号 2026-11-12 11:33:09 +08:00
wule 82165f25a8 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-12 11:31:45 +08:00
wule fe8f9851fe 修改繁体字拍单地址可用逻辑 2026-11-12 11:31:41 +08:00
wule 3d091462c5 新版本号 2026-11-11 18:50:50 +08:00
chfei 78a64aa661 利润统计 增加快递费筛选
快递费 页面支持导出全部
2026-11-11 18:24:46 +08:00
wule 71614f64e4 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-11 17:55:45 +08:00
wule 04a8ba0472 快递费明细页面调整 2026-11-11 17:55:37 +08:00
wule a93ab77028 新版本号 2026-11-11 16:27:05 +08:00
wule d17cb0f139 优化作废按钮显示逻辑 2026-11-11 16:21:32 +08:00
wule 60db6f933d Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-11 14:50:17 +08:00
wule 761e3f102f 读单相关信息查询全部改为异步调用 2026-11-11 14:50:05 +08:00
wule 98531e0344 新版本号 2026-11-10 19:42:02 +08:00
wule ee10fb5ea8 优化名称显示 2026-11-10 19:41:25 +08:00
wule 79b0027b7e 优化读单 2026-11-10 17:33:34 +08:00
wule 344cbb4ac2 过滤订单使用异步方法 优化中转仓额外包裹逻辑 2026-11-10 16:34:57 +08:00
wule 200e5bc8c8 优化更新拍单金额等操作 2026-11-10 13:58:14 +08:00
wule 4b554b55d9 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-10 10:39:15 +08:00
wule dadbb67914 小改动 2026-11-10 10:39:06 +08:00
wule 4e641928be 新版本号 2026-11-09 19:42:22 +08:00
wule 4bbb46304d 修改注释 2026-11-09 19:41:28 +08:00
wule 42ed8fc929 优化订单操作逻辑 2026-11-09 19:00:42 +08:00
wule ba6da5e85f 修复拍单余额查看闪退bug 优化每单拍单金额逻辑 2026-11-09 11:02:04 +08:00
wule ec13db7cc1 新版本号 2026-11-08 15:16:14 +08:00
wule a03f00fcdb 新版本号 2026-11-08 14:41:54 +08:00
wule_5900x 942ca54dd8 繁体地址需要权限才可使用 2026-11-08 14:41:15 +08:00
wule 6e8ff468f8 新版本号 2026-11-07 22:35:56 +08:00
wule_5900x ac93305d5f 1 修复淘宝拍单窗口可能崩溃问题
2 拼多多中转仓拍单随机地址支持随机繁体字
2026-11-07 22:35:03 +08:00
wule 5b9ed01fa1 1可设置是否直发拍单 2优化订单取号状态判断逻辑 2026-11-06 22:20:18 +08:00
wule 9789a4686f 修复退货包裹按钮功能写反的bug 2026-11-06 21:18:36 +08:00
wule 1ee4c99647 修复拍单后不能立即作废的bug 2026-11-06 18:01:18 +08:00
wule 8fc0e404c3 修复拍单后不能立即作废订单的问题 2026-11-06 17:55:46 +08:00
wule c4c54fc03e 新版本号 2026-11-06 17:00:13 +08:00
wule d43cf21afc Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-11-06 16:58:53 +08:00
wule 7ac3c67242 放开淘宝直拍,优化拍单按钮显示逻辑 2026-11-06 16:58:47 +08:00
wule 72c85ca3f1 新版本号 2026-11-06 16:12:24 +08:00
wule 518365a0d3 优化中转仓处理拍单流程 隐藏部分不可用功能 2026-11-06 16:11:23 +08:00
wule 27ac748f33 新版本号 2026-11-05 20:12:16 +08:00
wule 3483c99d37 修复买手退款异常单异常重拍按钮不显示的bug 2026-11-05 19:56:42 +08:00
wule a4bc9a788e 新版本号 2026-11-04 10:07:02 +08:00
wule 8f7e190974 优化订单处理 2026-11-04 10:05:52 +08:00
wule 85259d8335 显示买手退款详情 2026-11-03 13:38:50 +08:00
wule 5777c30048 新版本号 2026-11-02 19:28:16 +08:00
wule c40e591317 1更新上海仓库地址 2修复作废售后单后无法再次创建问题 2026-11-02 19:26:55 +08:00
wule 54986faa50 新版本号 2026-11-01 16:11:09 +08:00
wule_5900x 30808d56e8 优化直发单售后判断逻辑 2026-11-01 16:09:55 +08:00
wule_5900x 679f6cc9e6 修复云仓买手秒退导致直发退货仓无法提交的问题 2026-10-31 16:33:19 +08:00
wule a5889085d4 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-30 20:43:22 +08:00
wule 6d3f9e4118 中转仓详情作废发货包裹功能 2026-10-30 20:43:13 +08:00
wule 96214a54ea 新版本号 2026-10-30 17:33:38 +08:00
wule f167c2585d 修复售后单数量不足10条时漏单问题 2026-10-30 17:33:02 +08:00
wule 671ca453e0 新版本号 2026-10-30 17:12:54 +08:00
wule da01c9f83f 同上一条 2026-10-30 17:11:55 +08:00
wule 70996d5409 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-30 17:11:31 +08:00
wule bf3b6487f0 云仓详情页作废退货包裹功能 2026-10-30 17:11:19 +08:00
wule be8c0bd1e2 新版本号 2026-10-29 20:11:31 +08:00
wule cefea9dc1a Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-29 20:00:19 +08:00
wule 430bf8d574 修复包裹拒收功能报错 2026-10-29 20:00:14 +08:00
wule e08b4797cb 新版本号 2026-10-29 14:06:00 +08:00
wule 679bd39144 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-29 14:05:14 +08:00
wule 1a5f40926b 修改拦截工单链接地址及其他一些改动 2026-10-29 14:05:04 +08:00
wule 6029eda6de 新版本号 2026-10-29 11:32:41 +08:00
wule 9545de7684 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-29 11:31:19 +08:00
wule 6b8557f8b2 修复退货包裹无法创建问题 2026-10-29 11:31:12 +08:00
wule 4b34090cec 新版本号 2026-10-28 14:04:25 +08:00
chfei d76cf5c342 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-28 14:04:02 +08:00
chfei d70b74ee4a 工单 增加图片复制 2026-10-28 14:03:54 +08:00
wule 1172670a7e Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-28 13:21:38 +08:00
wule be0be1866d 新版本号 2026-10-28 13:21:33 +08:00
wule a31b87b512 优化读拼多多买手单 2026-10-28 13:17:51 +08:00
chfei f89670877d Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-27 17:44:45 +08:00
chfei a9f3ed81af 修复 消费记录导出内容格式化错误 2026-10-27 17:44:38 +08:00
wule 5530b4be2d 修复云仓详情按钮不显示的bug 2026-10-27 17:41:53 +08:00
wule adc3649b59 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-27 17:28:03 +08:00
wule 2d788bd8b1 查看云仓数据按钮 2026-10-27 17:27:54 +08:00
wule 3dd65bdccc 新版本号 2026-10-27 17:02:19 +08:00
wule c79758f235 优化淘宝买手售后读取 2026-10-27 17:01:51 +08:00
wule e01d9a4681 优化订单读取 显示中转仓状态 2026-10-27 16:12:27 +08:00
wule 3f618707da 新版本号 2026-10-27 10:21:58 +08:00
wule 8e581196af 注释等小改动 2026-10-27 10:19:49 +08:00
wule cb61749cda 仓库单详情列表 中转仓退货包裹如果没有物流使用买手物流 2026-10-27 10:16:34 +08:00
wule c1352264a9 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-27 10:00:40 +08:00
chfei 61f0fc0edd 修复工单对话列表不能复制bug 2026-10-27 09:11:27 +08:00
wule 279ca6e8e9 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-26 15:27:31 +08:00
wule f8af5730d3 退货包裹批量展示 2026-10-26 15:27:29 +08:00
wule fe50ca114a 新版本号 2026-10-26 14:53:19 +08:00
wule fb7b623a9f Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-26 14:50:49 +08:00
chfei 39cf75fcbb Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-26 14:50:23 +08:00
chfei 26bf67265d 修复 开票出现错误停止开票的bug 2026-10-26 14:50:13 +08:00
wule 37d879c3e5 model更新 2026-10-26 01:45:07 +08:00
wule fda30c824a 1 退货物流信息如果中转表没有从买手单表读取 2仓库详细信息 2026-10-25 22:10:39 +08:00
wule 19f48e9e6f 新版本号 2026-10-24 20:57:37 +08:00
wule e492457516 修复显示作废(显示错误)订单无法作废重拍的问题 2026-10-24 20:56:08 +08:00
wule 04584600c8 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-24 11:26:04 +08:00
wule b466645640 中转订单详情 2026-10-24 11:25:55 +08:00
wule 2186281fb5 新版本号 2026-10-23 19:44:41 +08:00
wule 78d8f79089 新版本号 2026-10-23 19:44:18 +08:00
wule 526b009f5e Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-23 19:43:44 +08:00
wule 13cb427d2f 显示订单读取总页数 2026-10-23 19:43:40 +08:00
wule 941f48c8b8 新版本号 2026-10-23 19:39:27 +08:00
wule bcc934c1ba 优化读单卡顿问题 2026-10-23 19:38:28 +08:00
wule 8e88e0f5d7 新版本号 2026-10-23 13:51:57 +08:00
chfei 102af9a15c Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-23 13:49:28 +08:00
chfei e1daca428c 增加 工单 提示 2026-10-23 13:49:18 +08:00
wule 727ed7b8ec 新版本号 2026-10-23 09:46:06 +08:00
wule 2cb616b50a Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-23 09:45:48 +08:00
wule f8e68a6322 优化自动拍单优惠券逻辑 2026-10-23 09:45:39 +08:00
wule 7471b707f1 新版本号 2026-10-22 20:16:19 +08:00
wule 8ec1b63f8a 小改动 2026-10-22 20:12:45 +08:00
wule a37744b284 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-22 20:07:40 +08:00
wule 3af9a8017a 自动领店铺优惠券 修复平台服务费不显示问题 2026-10-22 20:07:35 +08:00
wule fc83308711 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-22 16:16:30 +08:00
wule e63d6c896c 新版本号 2026-10-22 16:16:24 +08:00
wule 3f3477d3f4 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-22 16:15:49 +08:00
wule 50a0668278 服务器优化 2026-10-22 16:15:42 +08:00
chfei 1803a4e5e9 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-22 09:48:19 +08:00
chfei 6ed2cede16 工单 增加 接收服务端推送的新工单,支持 推送增加消息 2026-10-22 09:48:12 +08:00
wule 2915056795 新版本号 2026-10-21 20:03:25 +08:00
wule 103b2a1a4a 优化订单读取与拍单逻辑 2026-10-21 20:01:53 +08:00
wule e02047ae57 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-21 15:32:32 +08:00
wule a6e8e5b8cd 优化店铺列表展示 2026-10-21 15:31:59 +08:00
wule 12e9defdb5 新版本号 2026-10-21 12:21:17 +08:00
chfei f0f1f1ed9e Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-21 12:17:31 +08:00
chfei 1d5b6ba0e4 工单 修复 微信复制图片上传不展示的bug 2026-10-21 12:17:24 +08:00
wule c7a87cac28 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-21 11:59:19 +08:00
wule 4d7fd2c157 拼多多买手读单优化 2026-10-21 11:59:12 +08:00
chfei 9c62e0c03d Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-21 11:30:47 +08:00
chfei 483d87f57d 增加发票助手 开票过程中错误提示 2026-10-21 11:30:39 +08:00
wule b63dacfe7e 售后单读取 2026-10-20 18:37:48 +08:00
wule c76e5c9663 新版本号 2026-10-20 17:04:58 +08:00
chfei 3affb4a732 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-20 17:03:29 +08:00
chfei cf2efbcb16 工单 优化 ,增加图片 2026-10-20 17:03:23 +08:00
wule af43e6aed5 新版本号 2026-10-20 14:20:28 +08:00
wule 0b94c43fab Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-20 14:14:00 +08:00
wule fd07c9ba40 优化买手单读取 2026-10-20 14:13:55 +08:00
wule 221c0e6648 新版本 2026-10-20 11:35:57 +08:00
chfei bf5a70597c Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-20 11:34:43 +08:00
chfei 6e5dfa92b8 修复 工单第一次连接失败bug
增加工单内log
2026-10-20 10:20:57 +08:00
wule f5c8baef9a 新版本 2026-10-19 19:59:35 +08:00
chfei 324ca0c6e7 优化工单商铺数量限制 2026-10-19 19:58:23 +08:00
chfei f6eef23f96 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-19 19:58:07 +08:00
chfei ddb23544c7 移除工单商铺数量限制 2026-10-19 19:58:01 +08:00
wule 7380763c1d 优化店铺读取 2026-10-19 19:55:26 +08:00
wule 707efc1723 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-19 19:22:09 +08:00
wule f722993c3d 优化店铺读取 2026-10-19 19:22:04 +08:00
wule b7c682ef10 新版本 2026-10-19 18:47:49 +08:00
chfei 62e80d3c75 启动工单 日志修复 2026-10-19 18:45:14 +08:00
chfei f7851320ba 工单修改店铺50个bug 2026-10-19 18:42:17 +08:00
wule 12fe0c26fb 新版本 2026-10-19 18:19:45 +08:00
wule d36774ea18 订单排序,优化异常重拍 2026-10-19 18:18:02 +08:00
chfei fd0ff6771f Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-19 18:05:27 +08:00
chfei e96871a87a 修复工单 推送连接失败bug 2026-10-19 18:05:20 +08:00
wule e04e4e5108 新版本号 2026-10-19 16:12:45 +08:00
wule 06e6fe89bc Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-19 16:11:56 +08:00
wule c868460cd7 修复读单报错跳出问题 2026-10-19 16:11:54 +08:00
wule 7eea26cdda 更新版本 2026-10-19 15:14:03 +08:00
wule e4b1a24ddb Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-19 15:13:22 +08:00
wule b74e4598a7 优化读单 2026-10-19 15:13:18 +08:00
chfei c999a80048 增加日志
工单连接增加日志
2026-10-19 15:09:51 +08:00
chfei 1b0aa81263 工单增加连接失败日志 2026-10-19 14:53:47 +08:00
chfei 8e0cc20649 修复工单Bug 2026-10-19 14:35:25 +08:00
wule 7982f7e348 新版本号 2026-10-19 14:23:21 +08:00
wule 17728c074c 优化图片显示 2026-10-19 14:22:25 +08:00
wule 1d4867ebf2 新版本 2026-10-19 14:10:42 +08:00
wule eb6b1c5651 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-19 13:24:03 +08:00
wule bbac29ac78 继续优化读单 2026-10-19 13:23:50 +08:00
chfei cf15ef194f Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-19 10:18:04 +08:00
chfei a217a74868 更新JSON格式化
增加剪切板helper
2026-10-19 10:17:43 +08:00
wule 3d86e986b0 合并冲突 2026-10-19 09:12:50 +08:00
wule aad92e8f8e 继续优化读单 2026-10-19 09:06:05 +08:00
chfei d3488c98f5 增加 sse服务端测试 2026-10-18 20:36:40 +08:00
chfei fe87aece4e hb 2026-10-18 20:36:25 +08:00
chfei 10bb0803d9 修改工单流程页面,订单列表增加工单按钮 2026-10-18 20:35:47 +08:00
wule 4ed7346aa8 新版本 2026-10-18 17:20:14 +08:00
wule 7df2cc0957 修复关联失败问题 继续优化读单 2026-10-18 17:18:30 +08:00
wule a786ba6ce9 1新版本 2优化图片显示 2026-10-18 14:22:41 +08:00
wule 41b240c066 新版本 2026-10-18 14:00:56 +08:00
wule b6b4693c86 新版本328 2026-10-18 09:39:02 +08:00
wule_5900x 7c5f083784 修复淘宝买手切换卡死问题 2026-10-18 09:36:18 +08:00
wule 52b1e9eb90 Merge branch 'main' of http://git.ts.e57.cn/chfei/29WxOrder 2026-10-18 08:11:08 +08:00
wule 06e45bf587 优化读取订单的展示 2026-10-18 08:09:48 +08:00
wule_5900x bd3bde553b 小修改 2026-10-18 08:08:43 +08:00
chfei 41b12d1284 修改启动项 2026-10-17 18:28:45 +08:00
chfei f9dcae4610 增加工单模块 2026-10-17 18:18:05 +08:00
165 changed files with 30972 additions and 6701 deletions

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
+18
View File
@@ -25,6 +25,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".test", ".test", "{14261B9B
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WXOrder.Test", "test\WXOrder.Test\WXOrder.Test.csproj", "{3790EC79-EA1D-4660-AB0D-EA0DE4FF77B7}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WXOrder.Test", "test\WXOrder.Test\WXOrder.Test.csproj", "{3790EC79-EA1D-4660-AB0D-EA0DE4FF77B7}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OrderSupportTicket", "OrderSupportTicket\OrderSupportTicket.csproj", "{22D31944-2087-437A-B374-C0874E9EC53A}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -117,6 +119,22 @@ Global
{3790EC79-EA1D-4660-AB0D-EA0DE4FF77B7}.Release|x64.Build.0 = Release|Any CPU {3790EC79-EA1D-4660-AB0D-EA0DE4FF77B7}.Release|x64.Build.0 = Release|Any CPU
{3790EC79-EA1D-4660-AB0D-EA0DE4FF77B7}.Release|x86.ActiveCfg = Release|Any CPU {3790EC79-EA1D-4660-AB0D-EA0DE4FF77B7}.Release|x86.ActiveCfg = Release|Any CPU
{3790EC79-EA1D-4660-AB0D-EA0DE4FF77B7}.Release|x86.Build.0 = Release|Any CPU {3790EC79-EA1D-4660-AB0D-EA0DE4FF77B7}.Release|x86.Build.0 = Release|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Debug|x64.ActiveCfg = Debug|x64
{22D31944-2087-437A-B374-C0874E9EC53A}.Debug|x64.Build.0 = Debug|x64
{22D31944-2087-437A-B374-C0874E9EC53A}.Debug|x86.ActiveCfg = Debug|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Debug|x86.Build.0 = Debug|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Release|Any CPU.Build.0 = Release|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Release|x64.ActiveCfg = Release|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Release|x64.Build.0 = Release|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Release|x86.ActiveCfg = Release|Any CPU
{22D31944-2087-437A-B374-C0874E9EC53A}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
+2 -1
View File
@@ -67,11 +67,12 @@
<!-- 资源文件:SDK 样式工程默认不会把图片/图标作为 Resource,这里按原工程显式声明 --> <!-- 资源文件:SDK 样式工程默认不会把图片/图标作为 Resource,这里按原工程显式声明 -->
<ItemGroup> <ItemGroup>
<Resource Include="Resources\**\*" /> <Resource Include="Resources\**\*" />
<None Remove="Ctrls\BuyerCtrls\Resources\pdd_afterorder.js" />
<None Remove="Ctrls\PDDInvoice\Resources\invoice.js" /> <None Remove="Ctrls\PDDInvoice\Resources\invoice.js" />
<None Remove="Ctrls\PDDInvoice\Resources\order.js" /> <None Remove="Ctrls\PDDInvoice\Resources\order.js" />
<Resource Include="29wx.ico" /> <Resource Include="29wx.ico" />
<Resource Include="29_common_icon.ico" /> <Resource Include="29_common_icon.ico" />
<Resource Include="Ctrls\OrderCtrls\Resources\tbAutoAddress.js" /> <Resource Include="Ctrls\BuyerCtrls\Resources\pdd_afterorder.js" />
<Resource Include="Ctrls\PDDInvoice\Resources\invoice.js" /> <Resource Include="Ctrls\PDDInvoice\Resources\invoice.js" />
<Resource Include="Ctrls\PDDInvoice\Resources\order.js" /> <Resource Include="Ctrls\PDDInvoice\Resources\order.js" />
<Resource Include="gear.ico" /> <Resource Include="gear.ico" />
@@ -0,0 +1,90 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net462</TargetFramework>
<RootNamespace>_29WxOrderWpf</RootNamespace>
<AssemblyName>29WxFindOrder</AssemblyName>
<UseWPF>true</UseWPF>
<ApplicationIcon>gear.ico</ApplicationIcon>
<LangVersion>12</LangVersion>
<PlatformTarget>x64</PlatformTarget>
<OutputPath>..\bin\</OutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<PlatformTarget>x64</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\KJD Cef138\Bin\</OutputPath>
<DefineConstants>TRACE;RELEASE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CefSharp.Common" Version="138.0.340" />
<PackageReference Include="CefSharp.Wpf" Version="138.0.340" />
<PackageReference Include="chromiumembeddedframework.runtime.win-x64" Version="138.0.34" />
<PackageReference Include="chromiumembeddedframework.runtime.win-x86" Version="138.0.34" />
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<PackageReference Include="WPFCommon" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Xaml" />
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<Reference Include="NaiBa.Util">
<HintPath>..\DllReference\NaiBa.Util.dll</HintPath>
<Private>true</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AllBase\29WxOrderAllBase.csproj" />
<ProjectReference Include="..\OrderSupportTicket\OrderSupportTicket.csproj" />
<ProjectReference Include="..\Work\29WxOrderWork.csproj" />
<ProjectReference Include="..\WxOrder.Framework\WxOrder.Framework.csproj" />
</ItemGroup>
<!-- 资源文件:SDK 样式工程默认不会把图片/图标作为 Resource,这里按原工程显式声明 -->
<ItemGroup>
<Resource Include="Resources\**\*" />
<None Remove="Ctrls\PDDInvoice\Resources\invoice.js" />
<None Remove="Ctrls\PDDInvoice\Resources\order.js" />
<Resource Include="29wx.ico" />
<Resource Include="29_common_icon.ico" />
<Resource Include="Ctrls\PDDInvoice\Resources\invoice.js" />
<Resource Include="Ctrls\PDDInvoice\Resources\order.js" />
<Resource Include="gear.ico" />
</ItemGroup>
<ItemGroup>
<Compile Update="Ctrls\BuyerCtrls\PddBuyOrderCtrl.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="Views\ChangePickNoView.xaml.cs">
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Folder Include="Common\" />
</ItemGroup>
</Project>
+8 -9
View File
@@ -108,7 +108,7 @@ namespace _29WxOrderWpf
string str = GetExceptionMsg(ex, string.Empty); string str = GetExceptionMsg(ex, string.Empty);
NaiBa.Util.Helper.LogHelper.WriteWithTime("SystemError:" + str); NaiBa.Util.Helper.LogHelper.WriteWithTime("SystemError:" + str);
//BaseMsgForm.ShowError(str, "系统错误"); //BaseMsgForm.ShowError(str, "系统错误");
BaseMsgWindow.ShowError(str, "系统错误"); BaseMsgWindow.ShowError(str, "系统错误", null, MsgWindowLevel.LARGE);
} }
#region 初始化cef #region 初始化cef
@@ -143,8 +143,7 @@ namespace _29WxOrderWpf
} }
#endregion #endregion
//new MainWindow().Show(); new MainWindow().Show();
new OrderSupportTicketWindow().Show();
} }
//static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) //static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
@@ -158,15 +157,15 @@ namespace _29WxOrderWpf
{ {
string str = GetExceptionMsg(e.Exception, e.ToString()); string str = GetExceptionMsg(e.Exception, e.ToString());
NaiBa.Util.Helper.LogHelper.WriteWithTime("SystemError:" + str); NaiBa.Util.Helper.LogHelper.WriteWithTime("SystemError:" + str);
BaseMsgWindow.ShowError(str, "系统错误"); BaseMsgWindow.ShowError(str, "系统错误", null, MsgWindowLevel.LARGE);
} }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{ {
string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString()); string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
NaiBa.Util.Helper.LogHelper.WriteWithTime("SystemError:" + str); NaiBa.Util.Helper.LogHelper.WriteWithTime("SystemError:" + str);
BaseMsgWindow.ShowError(str, "系统错误"); BaseMsgWindow.ShowError(str, "系统错误", null, MsgWindowLevel.LARGE);
} }
/// <summary> /// <summary>
/// 生成自定义异常消息 /// 生成自定义异常消息
@@ -191,8 +190,8 @@ namespace _29WxOrderWpf
} }
sb.AppendLine("***************************************************************"); sb.AppendLine("***************************************************************");
NaiBa.Util.Helper.LogHelper.WriteWithTime("Error:" + sb); NaiBa.Util.Helper.LogHelper.WriteWithTime("Error:" + sb);
BaseMsgWindow.ShowError(sb.ToString(), "系统错误"); BaseMsgWindow.ShowError(sb.ToString(), "系统错误", null, MsgWindowLevel.LARGE);
return sb.ToString(); return sb.ToString();
} }
/// <summary> /// <summary>
@@ -124,8 +124,8 @@ namespace _29WxOrderWpf.BaseWindows
MainWindow.Instance.borderMessage.BorderBrush = Application.Current.Resources["pageColorBrush"] as SolidColorBrush; MainWindow.Instance.borderMessage.BorderBrush = Application.Current.Resources["pageColorBrush"] as SolidColorBrush;
MainWindow.Instance.tbMessage.Foreground = Application.Current.Resources["pageColorBrush"] as SolidColorBrush; MainWindow.Instance.tbMessage.Foreground = Application.Current.Resources["pageColorBrush"] as SolidColorBrush;
} }
if (type.ToLower() == "error") if (type.ToLower() == "err" || type.ToLower() == "error")
{ {
MainWindow.Instance.borderMessage.BorderBrush = Application.Current.Resources["PageWarningBrush"] as SolidColorBrush; MainWindow.Instance.borderMessage.BorderBrush = Application.Current.Resources["PageWarningBrush"] as SolidColorBrush;
MainWindow.Instance.tbMessage.Foreground = Application.Current.Resources["PageWarningBrush"] as SolidColorBrush; MainWindow.Instance.tbMessage.Foreground = Application.Current.Resources["PageWarningBrush"] as SolidColorBrush;
} }
@@ -19,9 +19,9 @@ namespace _29WxOrderWpf.Converters
return 0; return 0;
return listView.ItemContainerGenerator.IndexFromContainer(item) + 1; return listView.ItemContainerGenerator.IndexFromContainer(item) + 1;
} }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@@ -14,8 +14,6 @@ namespace _29WxOrderWpf.Converters
{ {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ {
return Visibility.Collapsed;
if (value == null) if (value == null)
return Visibility.Collapsed; return Visibility.Collapsed;
return !value.ParseToString().Trim().IsNullOrEmpty() ? Visibility.Visible : Visibility.Collapsed; return !value.ParseToString().Trim().IsNullOrEmpty() ? Visibility.Visible : Visibility.Collapsed;
@@ -98,9 +98,9 @@
<Button <Button
x:Name="btnNextBuyer" x:Name="btnNextBuyer"
Grid.Column="8" Grid.Column="8"
Padding="4,0"
Height="24" Height="24"
Margin="4,0,0,0" Margin="4,0,0,0"
Padding="4,0"
Click="btnNextBuyer_Click" Click="btnNextBuyer_Click"
Content="下一个买手" Content="下一个买手"
Style="{StaticResource BasePageButtonStyle}" /> Style="{StaticResource BasePageButtonStyle}" />
@@ -273,7 +273,8 @@
Margin="180,0,0,0" Margin="180,0,0,0"
VerticalAlignment="Center" VerticalAlignment="Center"
Panel.ZIndex="1" Panel.ZIndex="1"
Content="正在操作:" /> d:Content="正在操作:"
Content="{Binding LblMsgStr}" />
<TabControl <TabControl
x:Name="tabOrderType" x:Name="tabOrderType"
@@ -363,6 +364,7 @@
RowHeaderWidth="0" RowHeaderWidth="0"
RowHeight="50" RowHeight="50"
SelectionChanged="dgBuyerOrder_SelectionChanged" SelectionChanged="dgBuyerOrder_SelectionChanged"
SelectionUnit="Cell"
VerticalGridLinesBrush="{StaticResource VerticalGridLinesBrush}"> VerticalGridLinesBrush="{StaticResource VerticalGridLinesBrush}">
<DataGrid.Columns> <DataGrid.Columns>
<DataGridTextColumn <DataGridTextColumn
@@ -381,7 +383,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="0.6*" Width="0.6*"
Binding="{Binding WxSendTypeStr}" Binding="{Binding WxSendTypeStr, Mode=OneWay}"
Header="是否直发"> Header="是否直发">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -393,7 +395,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1.5*" Width="1.5*"
Binding="{Binding order_sn}" Binding="{Binding order_sn, Mode=OneWay}"
Header="拍单订单号"> Header="拍单订单号">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -405,7 +407,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1.5*" Width="1.5*"
Binding="{Binding ShopOrderIdStr}" Binding="{Binding ShopOrderIdStr, Mode=OneWay}"
Header="店铺订单号"> Header="店铺订单号">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -417,7 +419,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="1*"
Binding="{Binding buyerName}" Binding="{Binding buyerName, Mode=OneWay}"
Header="买手名称"> Header="买手名称">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -429,7 +431,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="0.8*" Width="0.8*"
Binding="{Binding OrderTimeStr}" Binding="{Binding OrderTimeStr, Mode=OneWay}"
Header="拍单时间"> Header="拍单时间">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -441,7 +443,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1.8*" Width="1.8*"
Binding="{Binding ProdInfoStr}" Binding="{Binding ProdInfoStr, Mode=OneWay}"
Header="商品信息"> Header="商品信息">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -453,7 +455,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="0.8*" Width="0.8*"
Binding="{Binding AmoutValue}" Binding="{Binding AmoutValue, Mode=OneWay}"
Header="金额"> Header="金额">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -465,7 +467,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="1*"
Binding="{Binding order_status_prompt}" Binding="{Binding order_status_prompt, Mode=OneWay}"
Header="订单状态"> Header="订单状态">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -477,7 +479,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="1*"
Binding="{Binding outExpressCompanyCode}" Binding="{Binding outExpressCompanyCode, Mode=OneWay}"
Header="物流名称"> Header="物流名称">
<!-- outExpressCompanyName --> <!-- outExpressCompanyName -->
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
@@ -490,7 +492,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="1*"
Binding="{Binding tracking_number}" Binding="{Binding tracking_number, Mode=OneWay}"
Header="物流单号"> Header="物流单号">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -502,7 +504,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="1*"
Binding="{Binding sendStatus}" Binding="{Binding sendStatus, Mode=OneWay}"
Header="订单信息"> Header="订单信息">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -532,7 +534,7 @@
Click="btnSendBuyerOrder_Click" Click="btnSendBuyerOrder_Click"
Content="发送" Content="发送"
Foreground="{StaticResource PageLinkBrush}" Foreground="{StaticResource PageLinkBrush}"
Visibility="{Binding TransitWarehouseIdStr, Converter={StaticResource HasTextVisibility}}" /> Visibility="{Binding TransitWarehouseIdStr, Converter={StaticResource HasTextVisibility}, Mode=OneWay}" />
<Button <Button
x:Name="btnSendDirectBuyerOrder" x:Name="btnSendDirectBuyerOrder"
Grid.Row="2" Grid.Row="2"
@@ -545,7 +547,7 @@
Click="btnSendBuyerOrder_Click" Click="btnSendBuyerOrder_Click"
Content="发送" Content="发送"
Foreground="{StaticResource PageLinkBrush}" Foreground="{StaticResource PageLinkBrush}"
Visibility="{Binding WxSendTypeStr, Converter={StaticResource HasTextVisibility}}" /> Visibility="{Binding WxSendTypeStr, Converter={StaticResource HasTextVisibility}, Mode=OneWay}" />
<!-- 直发单直发标注不为空 --> <!-- 直发单直发标注不为空 -->
</Grid> </Grid>
</DataTemplate> </DataTemplate>
@@ -567,11 +569,12 @@
LoadingRow="dgBuyerOrder_LoadingRow" LoadingRow="dgBuyerOrder_LoadingRow"
RowHeaderWidth="0" RowHeaderWidth="0"
RowHeight="50" RowHeight="50"
SelectionUnit="Cell"
VerticalGridLinesBrush="{StaticResource VerticalGridLinesBrush}"> VerticalGridLinesBrush="{StaticResource VerticalGridLinesBrush}">
<DataGrid.Columns> <DataGrid.Columns>
<DataGridTextColumn <DataGridTextColumn
Width="40" Width="40"
Binding="{Binding Header, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}, Mode=FindAncestor}}" Binding="{Binding Header, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}, Mode=FindAncestor}, Mode=OneWay}"
CanUserSort="False" CanUserSort="False"
Header="序列" Header="序列"
IsReadOnly="True"> IsReadOnly="True">
@@ -585,7 +588,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="0.6*" Width="0.6*"
Binding="{Binding WxSendTypeStr}" Binding="{Binding WxSendTypeStr, Mode=OneWay}"
Header="是否直发"> Header="是否直发">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -597,7 +600,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1.5*" Width="1.5*"
Binding="{Binding afterSalesId}" Binding="{Binding afterSalesId, Mode=OneWay}"
Header="售后单号"> Header="售后单号">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -609,7 +612,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1.5*" Width="1.5*"
Binding="{Binding orderSn}" Binding="{Binding orderSn, Mode=OneWay}"
Header="拍单订单号"> Header="拍单订单号">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -621,7 +624,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1.5*" Width="1.5*"
Binding="{Binding ShopOrderIdStr}" Binding="{Binding ShopOrderIdStr, Mode=OneWay}"
Header="店铺订单号"> Header="店铺订单号">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -633,7 +636,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="1*"
Binding="{Binding buyerName}" Binding="{Binding buyerName, Mode=OneWay}"
Header="买手名称"> Header="买手名称">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -645,7 +648,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="0.8*" Width="0.8*"
Binding="{Binding orderDate}" Binding="{Binding orderDate, Mode=OneWay}"
Header="拍单日期"> Header="拍单日期">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -657,7 +660,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1.8*" Width="1.8*"
Binding="{Binding ProdInfoStr}" Binding="{Binding ProdInfoStr, Mode=OneWay}"
Header="商品信息"> Header="商品信息">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -669,7 +672,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="0.8*" Width="0.8*"
Binding="{Binding OrderAmountValue}" Binding="{Binding OrderAmountValue, Mode=OneWay}"
Header="订单金额"> Header="订单金额">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -681,7 +684,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="0.8*" Width="0.8*"
Binding="{Binding RefundAmountValue}" Binding="{Binding RefundAmountValue, Mode=OneWay}"
Header="售后金额"> Header="售后金额">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -693,7 +696,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="1*"
Binding="{Binding AfterSaleStatusStr}" Binding="{Binding AfterSaleStatusStr, Mode=OneWay}"
Header="售后状态"> Header="售后状态">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -705,7 +708,7 @@
</DataGridTextColumn> </DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="1*" Width="1*"
Binding="{Binding sendStatus}" Binding="{Binding sendStatus, Mode=OneWay}"
Header="订单信息"> Header="订单信息">
<DataGridTextColumn.ElementStyle> <DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock"> <Style TargetType="TextBlock">
@@ -720,7 +723,7 @@
<DataTemplate> <DataTemplate>
<Button Grid.Column="1" Grid.Row="2" x:Name="btnSendBuyerOrder" VerticalAlignment="Center" Background="Transparent" HorizontalAlignment="Center" <Button Grid.Column="1" Grid.Row="2" x:Name="btnSendBuyerOrder" VerticalAlignment="Center" Background="Transparent" HorizontalAlignment="Center"
Foreground="{StaticResource PageLinkBrush}" BorderBrush="Transparent" Margin="4,0,0,0" Content="发送" Click="btnSendBuyerOrder_Click" Foreground="{StaticResource PageLinkBrush}" BorderBrush="Transparent" Margin="4,0,0,0" Content="发送" Click="btnSendBuyerOrder_Click"
Visibility="{Binding TransitWarehouseIdStr, Converter={StaticResource HasTextVisibility}}"></Button> Visibility="{Binding TransitWarehouseIdStr, Converter={StaticResource HasTextVisibility}, Mode=OneWay}"></Button>
</DataTemplate> </DataTemplate>
</DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>--> </DataGridTemplateColumn>-->
File diff suppressed because it is too large. Load diff
@@ -18,14 +18,6 @@
<ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Image
Width="24"
Height="24"
Margin="4,0,0,0"
Cursor="Hand"
MouseLeftButtonUp="Image_MouseLeftButtonUp"
Source="{StaticResource imgBuyerOrder}" />
<wpf:SpacingStackPanel <wpf:SpacingStackPanel
@@ -34,7 +26,16 @@
Orientation="Vertical" Orientation="Vertical"
VerticalSpacing="2"> VerticalSpacing="2">
<WrapPanel x:Name="wpPddBuyer"> <WrapPanel x:Name="wpPddBuyer">
<CheckBox
<Image
Width="24"
Height="24"
Margin="4,0,0,0"
Cursor="Hand"
MouseLeftButtonUp="Image_MouseLeftButtonUp"
Source="{StaticResource imgBuyerOrder}" />
<CheckBox
x:Name="chkPddBuyerLogin" x:Name="chkPddBuyerLogin"
Margin="2,2,2,2" Margin="2,2,2,2"
HorizontalAlignment="Left" HorizontalAlignment="Left"
@@ -121,7 +122,16 @@
d:Visibility="Visible" d:Visibility="Visible"
Visibility="Visible"> Visibility="Visible">
<CheckBox <Image
x:Name="imgTb"
Width="24"
Height="24"
Margin="4,0,0,0"
Cursor="Hand"
MouseLeftButtonUp="imgTb_MouseLeftButtonUp"
Source="{StaticResource imgBuyerOrder}" />
<CheckBox
x:Name="chkTbBuyerLogin" x:Name="chkTbBuyerLogin"
Margin="2,2,2,2" Margin="2,2,2,2"
HorizontalAlignment="Left" HorizontalAlignment="Left"
@@ -152,36 +152,47 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
int buyZIndex = 2; int buyZIndex = 2;
private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{ {
if (/*wpPddBuyer.Visibility == Visibility.Visible*/ chkPddBuyerLogin.IsChecked == true) if (MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility != Visibility.Visible)
{ MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
if (MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility != Visibility.Visible) if (Panel.GetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl) < 1)
MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility = Visibility.Visible; Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, 1);
if (Panel.GetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl) < 1)
Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, 1);
else
Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1);
Panel.SetZIndex(MainWindow.Instance.pddBuyerOrderReadCtrl, buyZIndex++);
MainWindow.Instance.pddBuyerOrderReadCtrl.Visibility = Visibility.Visible;
MainWindow.Instance.tbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
}
else if (/*wpTaobaoBuyer.Visibility == Visibility.Visible*/ chkTbBuyerLogin.IsChecked == true)
{
if (MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility != Visibility.Visible)
MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
if (Panel.GetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl) < 1)
Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, 1);
else
Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1);
Panel.SetZIndex(MainWindow.Instance.tbBuyerOrderReadCtrl, buyZIndex++);
MainWindow.Instance.pddBuyerOrderReadCtrl.Visibility = Visibility.Visible;
MainWindow.Instance.tbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
}
else else
{
Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1); Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1);
}
Panel.SetZIndex(MainWindow.Instance.pddBuyerOrderReadCtrl, buyZIndex++);
MainWindow.Instance.pddBuyerOrderReadCtrl.Visibility = Visibility.Visible;
MainWindow.Instance.tbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
//if (/*wpPddBuyer.Visibility == Visibility.Visible*/ chkPddBuyerLogin.IsChecked == true)
//{
// if (MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility != Visibility.Visible)
// MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
// if (Panel.GetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl) < 1)
// Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, 1);
// else
// Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1);
// Panel.SetZIndex(MainWindow.Instance.pddBuyerOrderReadCtrl, buyZIndex++);
// MainWindow.Instance.pddBuyerOrderReadCtrl.Visibility = Visibility.Visible;
// MainWindow.Instance.tbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
//}
//else if (/*wpTaobaoBuyer.Visibility == Visibility.Visible*/ chkTbBuyerLogin.IsChecked == true)
//{
// if (MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility != Visibility.Visible)
// MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
// if (Panel.GetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl) < 1)
// Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, 1);
// else
// Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1);
// Panel.SetZIndex(MainWindow.Instance.tbBuyerOrderReadCtrl, buyZIndex++);
// MainWindow.Instance.pddBuyerOrderReadCtrl.Visibility = Visibility.Visible;
// MainWindow.Instance.tbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
//}
//else
//{
// Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1);
//}
} }
@@ -198,7 +209,6 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
foreach (var orderItem in order.orderItems) foreach (var orderItem in order.orderItems)
{ {
orderItem.UpdateOrderItemBuyButton(); orderItem.UpdateOrderItemBuyButton();
orderItem.SetAbnormalAndDirectBtnVisibility();
} }
} }
} }
@@ -213,7 +223,6 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
foreach (var orderItem in order.orderItems) foreach (var orderItem in order.orderItems)
{ {
orderItem.UpdateOrderItemBuyButton(); orderItem.UpdateOrderItemBuyButton();
orderItem.SetAbnormalAndDirectBtnVisibility();
} }
} }
} }
@@ -324,8 +333,9 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
} }
} }
private void chkBuyerLogin_Click(object sender, RoutedEventArgs e) private async void chkBuyerLogin_Click(object sender, RoutedEventArgs e)
{ {
if (sender == chkPddBuyerLogin) if (sender == chkPddBuyerLogin)
{ {
chkPddBuyerLogin.IsChecked = true; chkPddBuyerLogin.IsChecked = true;
@@ -337,8 +347,11 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
//OrderListCtrl.InitOrderObservableProp(order); //OrderListCtrl.InitOrderObservableProp(order);
foreach (var orderItem in order.orderItems) foreach (var orderItem in order.orderItems)
{ {
orderItem.UpdateOrderItemBuyButton(); await Task.Run(() =>
orderItem.SetAbnormalAndDirectBtnVisibility(); {
orderItem.UpdateOrderItemBuyButton();
orderItem.SetAbnormalAndDirectBtnVisibility();
});
} }
} }
} }
@@ -353,11 +366,28 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
//OrderListCtrl.InitOrderObservableProp(order); //OrderListCtrl.InitOrderObservableProp(order);
foreach (var orderItem in order.orderItems) foreach (var orderItem in order.orderItems)
{ {
orderItem.UpdateOrderItemBuyButton(); await Task.Run(() =>
orderItem.SetAbnormalAndDirectBtnVisibility(); {
orderItem.UpdateOrderItemBuyButton();
orderItem.SetAbnormalAndDirectBtnVisibility();
});
} }
} }
} }
} }
private void imgTb_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility != Visibility.Visible)
MainWindow.Instance.gridTbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
if (Panel.GetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl) < 1)
Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, 1);
else
Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1);
Panel.SetZIndex(MainWindow.Instance.tbBuyerOrderReadCtrl, buyZIndex++);
MainWindow.Instance.pddBuyerOrderReadCtrl.Visibility = Visibility.Visible;
MainWindow.Instance.tbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
}
} }
} }
@@ -0,0 +1,735 @@
<UserControl
x:Class="_29WxOrderWpf.Ctrls.BuyerCtrls.PDDMultiBuyerOrderReadCtrl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.BuyerCtrls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="pddMultiBuyerOrderReadCtrl"
d:DesignHeight="450"
d:DesignWidth="1000"
Loaded="UserControl_Loaded"
mc:Ignorable="d">
<Border
Background="White"
BorderBrush="{StaticResource pageColorBrush}"
BorderThickness="1,1,0,1"
CornerRadius="5,0,0,5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button
x:Name="btnHideAll"
Grid.Row="1"
Width="25"
Height="60"
Margin="-20,0,0,20"
HorizontalAlignment="left"
Click="btnHideAll_Click"
Style="{StaticResource BasePageButtonStyle}">
<TextBlock Margin="0,0,5,0">
关<LineBreak />
闭</TextBlock>
</Button>
<Grid Margin="0,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Image
Width="16"
Height="16"
Margin="12,0,4,0"
Cursor="Hand"
MouseLeftButtonUp="btnHideAll_Click"
Source="{StaticResource imgCloseGray}"
Visibility="Collapsed" />
<WrapPanel Grid.Column="1" VerticalAlignment="Center">
<CheckBox
x:Name="chkAutoReadBuyerOrder"
Margin="6,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
BorderBrush="{StaticResource mainColorBrush}"
Checked="chkAutoReadBuyerOrder_CheckedChanged"
Content="自动读多多买手单"
FontSize="12"
IsChecked="true"
Unchecked="chkAutoReadBuyerOrder_CheckedChanged" />
<CheckBox
x:Name="chkHideNoWxIdOrder"
Margin="6,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
BorderBrush="{StaticResource mainColorBrush}"
Checked="chkHideNoWxIdOrder_CheckedChanged"
Content="隐藏无微信订单的买手单"
FontSize="12"
IsChecked="True"
Unchecked="chkHideNoWxIdOrder_CheckedChanged" />
<CheckBox
x:Name="chkAutoAfterSale"
Margin="6,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
BorderBrush="{StaticResource mainColorBrush}"
Checked="chkAutoAfterSale_Checked"
Content="未发货订单自动售后"
FontSize="12"
IsChecked="True"
Unchecked="chkAutoAfterSale_Checked"
Visibility="Visible" />
<Button
x:Name="btnSearch"
Grid.Column="8"
Width="118"
Height="24"
Margin="4,0,0,0"
Click="btnSearch_Click"
Content="刷新订单"
Style="{StaticResource BasePageButtonStyle}" />
<Button
x:Name="btnNextBuyer"
Grid.Column="8"
Height="24"
Margin="4,0,0,0"
Padding="4,0"
Click="btnNextBuyer_Click"
Content="下一个买手"
Style="{StaticResource BasePageButtonStyle}" />
</WrapPanel>
<TextBox
x:Name="txtFilter"
Grid.Column="2"
Height="28"
Margin="28,0,8,0"
VerticalContentAlignment="Center"
BorderBrush="{StaticResource pageColorBrush}"
BorderThickness="1"
Style="{StaticResource BaseRoundCornerTextBoxStyle}"
TextChanged="txtFilter_TextChanged" />
<Button
x:Name="btnFilter"
Grid.Column="3"
Width="50"
Height="24"
Margin="4,0,8,0"
Click="btnFilter_Click"
Content="过滤"
Style="{StaticResource BasePageButtonStyle}" />
</Grid>
<Grid
x:Name="GridCef"
Grid.Row="1"
Background="LightGray" />
<Grid
Grid.Row="1"
Margin="2,2,0,334"
HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<Border
x:Name="borderPddBuyer"
Width="138"
Background="White"
CornerRadius="0,4,4,0">
<Grid>
<ListBox x:Name="lbPddBuyer">
<!-- 使用自定义属性模板去除ListBox高亮显示框 -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter
Content="{TemplateBinding Content}"
ContentStringFormat="{TemplateBinding ContentStringFormat}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<!--<local:ShopListRowCtrl></local:ShopListRowCtrl>-->
<Border
MinHeight="50"
Margin="0,0,0,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
BorderBrush="{StaticResource ListRowBorderColorBrush}"
BorderThickness="0,0,0,1"
CornerRadius="0">
<Border.Style>
<!-- 鼠标进入或悬停Border时切换颜色(悬停时Border的填充控件必须有填充Border,所在层级不限,仅填充透明Grid则触发器无效) -->
<Style TargetType="Border">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource ListRowHoverBackColorBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<Grid x:Name="gridListItem">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="colCheck" Width="25*" />
<ColumnDefinition x:Name="colBuyerName" Width="100*" />
</Grid.ColumnDefinitions>
<CheckBox
Grid.Column="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Transparent"
Click="CheckBox_Click"
IsChecked="{Binding IsSelect, Mode=TwoWay}" />
<TextBox
x:Name="txtBuyerNick"
Grid.Column="1"
HorizontalContentAlignment="Left"
VerticalContentAlignment="Center"
Background="Transparent"
BorderThickness="0"
Cursor="Hand"
IsReadOnly="True"
Loaded="txtBuyerNick_Loaded"
Text="{Binding buyer_nick}"
TextWrapping="Wrap" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
<Border
Grid.Column="1"
Height="60"
Margin="-2,0,0,0"
VerticalAlignment="Center"
Panel.ZIndex="-1"
Background="{StaticResource pageColorBrush}"
CornerRadius="0,5,5,0"
Cursor="Hand">
<Button
x:Name="btnHideBuyer"
Grid.Column="1"
Width="20"
Height="60"
Margin="0,0,0,0"
Padding="0,0,0,0"
VerticalContentAlignment="Center"
Click="btnHideBuyer_Click"
Content="◀"
Style="{StaticResource BasePageButtonStyle}" />
</Border>
</Grid>
<Grid
Grid.Row="1"
Margin="0"
VerticalAlignment="Bottom"
Background="Transparent"
Visibility="Visible">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Button
x:Name="btnHide"
Width="60"
Height="25"
Margin="0,0,0,-10"
Padding="0,2,0,0"
VerticalContentAlignment="top"
Click="btnHide_Click"
Content="▼"
Style="{StaticResource BasePageButtonStyle}" />
<Grid
x:Name="gridTable"
Grid.Row="1"
Height="330"
Margin="2"
VerticalAlignment="Bottom"
Background="White"
Visibility="Visible">
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label
x:Name="lblMsg"
Margin="180,0,0,0"
VerticalAlignment="Center"
Panel.ZIndex="1"
Content="正在操作:" />
<TabControl
x:Name="tabOrderType"
Grid.Row="1"
Margin="0,-32,0,1"
VerticalAlignment="Stretch">
<TabControl.Resources>
<Style TargetType="{x:Type TabControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabControl}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border
Grid.Row="1"
MinHeight="4"
Background="#f8f8f9"
BorderBrush="#e0e0e0"
BorderThickness="1,1,1,0"
CornerRadius="0,4,0,0">
<ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" />
</Border>
<Border
Margin="0,0,0,0"
HorizontalAlignment="Left"
Background="#e8e8e9"
BorderBrush="#e1e1e1"
BorderThickness="1,1,1,0"
CornerRadius="4,4,0,0">
<TabPanel
x:Name="HeaderPanel"
Background="Transparent"
IsItemsHost="True" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="TabItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<Border
Name="Border"
Margin="-1,-2,-1,0"
BorderThickness="1,1,1,0"
CornerRadius="4,4,0,0">
<ContentPresenter
x:Name="ContentSite"
Margin="10,5"
HorizontalAlignment="Center"
VerticalAlignment="Center"
ContentSource="Header" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Border" Property="Background" Value="#f8f8f9" />
<Setter TargetName="Border" Property="BorderBrush" Value="#e0e0e0" />
<Setter TargetName="Border" Property="Margin" Value="-1,-3,-1,-1" />
<Setter Property="Foreground" Value="{StaticResource pageColorBrush}" />
<Setter Property="Panel.ZIndex" Value="100" />
</Trigger>
<Trigger Property="IsSelected" Value="False">
<Setter TargetName="Border" Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="#999999" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
<TabItem Header="买手订单">
<DataGrid
x:Name="dgBuyerOrder"
Grid.Row="1"
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False"
ColumnHeaderHeight="30"
HorizontalGridLinesBrush="{StaticResource HorizontalGridLinesBrush}"
LoadingRow="dgBuyerOrder_LoadingRow"
RowHeaderWidth="0"
RowHeight="50"
SelectionChanged="dgBuyerOrder_SelectionChanged"
VerticalGridLinesBrush="{StaticResource VerticalGridLinesBrush}">
<DataGrid.Columns>
<DataGridTextColumn
Width="40"
Binding="{Binding Header, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}, Mode=FindAncestor}}"
CanUserSort="False"
Header="序列"
IsReadOnly="True">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="0.6*"
Binding="{Binding WxSendTypeStr}"
Header="是否直发">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1.5*"
Binding="{Binding order_sn}"
Header="拍单订单号">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1.5*"
Binding="{Binding ShopOrderIdStr}"
Header="店铺订单号">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1*"
Binding="{Binding buyerName}"
Header="买手名称">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="0.8*"
Binding="{Binding OrderTimeStr}"
Header="拍单时间">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1.8*"
Binding="{Binding ProdInfoStr}"
Header="商品信息">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="0.8*"
Binding="{Binding AmoutValue}"
Header="金额">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1*"
Binding="{Binding order_status_prompt}"
Header="订单状态">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1*"
Binding="{Binding outExpressCompanyCode}"
Header="物流名称">
<!-- outExpressCompanyName -->
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1*"
Binding="{Binding tracking_number}"
Header="物流单号">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1*"
Binding="{Binding sendStatus}"
Header="订单信息">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTemplateColumn
x:Name="colSendBuyerOrder"
Width="0.6*"
Header="手动发送">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Button
x:Name="btnSendBuyerOrder"
Grid.Row="2"
Grid.Column="1"
Margin="4,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Transparent"
BorderBrush="Transparent"
Click="btnSendBuyerOrder_Click"
Content="发送"
Foreground="{StaticResource PageLinkBrush}"
Visibility="{Binding TransitWarehouseIdStr, Converter={StaticResource HasTextVisibility}}" />
<Button
x:Name="btnSendDirectBuyerOrder"
Grid.Row="2"
Grid.Column="1"
Margin="4,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Transparent"
BorderBrush="Transparent"
Click="btnSendBuyerOrder_Click"
Content="发送"
Foreground="{StaticResource PageLinkBrush}"
Visibility="{Binding WxSendTypeStr, Converter={StaticResource HasTextVisibility}}" />
<!-- 直发单直发标注不为空 -->
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</TabItem>
<TabItem Header="买手售后">
<DataGrid
x:Name="dgBuyerAfterSale"
Grid.Row="1"
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserDeleteRows="False"
ColumnHeaderHeight="30"
HorizontalGridLinesBrush="{StaticResource HorizontalGridLinesBrush}"
LoadingRow="dgBuyerOrder_LoadingRow"
RowHeaderWidth="0"
RowHeight="50"
VerticalGridLinesBrush="{StaticResource VerticalGridLinesBrush}">
<DataGrid.Columns>
<DataGridTextColumn
Width="40"
Binding="{Binding Header, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}, Mode=FindAncestor}}"
CanUserSort="False"
Header="序列"
IsReadOnly="True">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="0.6*"
Binding="{Binding WxSendTypeStr}"
Header="是否直发">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1.5*"
Binding="{Binding afterSalesId}"
Header="售后单号">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1.5*"
Binding="{Binding orderSn}"
Header="拍单订单号">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1.5*"
Binding="{Binding ShopOrderIdStr}"
Header="店铺订单号">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1*"
Binding="{Binding buyerName}"
Header="买手名称">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="0.8*"
Binding="{Binding orderDate}"
Header="拍单日期">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1.8*"
Binding="{Binding ProdInfoStr}"
Header="商品信息">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="0.8*"
Binding="{Binding OrderAmountValue}"
Header="订单金额">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="0.8*"
Binding="{Binding RefundAmountValue}"
Header="售后金额">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1*"
Binding="{Binding AfterSaleStatusStr}"
Header="售后状态">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn
Width="1*"
Binding="{Binding sendStatus}"
Header="订单信息">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="5" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<!--<DataGridTemplateColumn Width="0.6*" Header="手动发送" x:Name="colSendBuyerOrderAfterSale" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Grid.Column="1" Grid.Row="2" x:Name="btnSendBuyerOrder" VerticalAlignment="Center" Background="Transparent" HorizontalAlignment="Center"
Foreground="{StaticResource PageLinkBrush}" BorderBrush="Transparent" Margin="4,0,0,0" Content="发送" Click="btnSendBuyerOrder_Click"
Visibility="{Binding TransitWarehouseIdStr, Converter={StaticResource HasTextVisibility}}"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>-->
</DataGrid.Columns>
</DataGrid>
</TabItem>
</TabControl>
</Grid>
</Grid>
</Grid>
</Border>
</UserControl>
File diff suppressed because it is too large. Load diff
@@ -337,7 +337,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
ManualUpdateBuyOrderCommand = new DelegateCommand(ManualUpdateBuyOrder); ManualUpdateBuyOrderCommand = new DelegateCommand(ManualUpdateBuyOrder);
UpdateTransitWarehouseCommand = new DelegateCommand(UpdateTransitWarehouse); UpdateTransitWarehouseCommand = new DelegateCommand(UpdateTransitWarehouse);
this.txtShopNameVal = orderItem.Shop.ShopAccount; this.txtShopNameVal = orderItem?.ItemOrder?.Shop?.ShopAccount;
this.txtOrderIdVal = orderItem.order_id; this.txtOrderIdVal = orderItem.order_id;
this.txtShopSkuIdVal = orderItem.sku_id; this.txtShopSkuIdVal = orderItem.sku_id;
this.txtShopGoodsIdVal = orderItem.product_id; this.txtShopGoodsIdVal = orderItem.product_id;
@@ -626,11 +626,11 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var pddFrontSkuInfo = new frontSkuInfo3() var pddFrontSkuInfo = new frontSkuInfo3()
{ {
skuId = key.ParseToLong(), skuId = key.ParseToLong(),
skuID = key.ParseToLong(), //skuID = key.ParseToLong(),
goodsId = pddFrontGoods3.goodsId, goodsId = pddFrontGoods3.goodsId,
thumbUrl = thumbUrl, thumbUrl = thumbUrl,
quantity = tbSku2.quantity, //quantity = tbSku2.quantity,
isOnsale = 1, //isOnsale = 1,
spec = taobaoSku?.propPath, // 淘宝格式与拼多多存在差异,包含冒号与父类型id spec = taobaoSku?.propPath, // 淘宝格式与拼多多存在差异,包含冒号与父类型id
specs = pddSpecs, specs = pddSpecs,
price = tbSku2.price.priceMoney.ParseToInt() + 100, price = tbSku2.price.priceMoney.ParseToInt() + 100,
@@ -732,7 +732,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var goods = JsonHelper.DeserializeJsonToObject<pddFrontGoods3Lite>(skuInfo.map_skus); var goods = JsonHelper.DeserializeJsonToObject<pddFrontGoods3Lite>(skuInfo.map_skus);
if (goods == null) if (goods == null)
return; return;
var sku = goods.skus.FirstOrDefault(s => s.skuID.ParseToString() == info.map_sku_id); var sku = goods.skus.FirstOrDefault(s => s.skuId.ParseToString() == info.map_sku_id);
if (sku == null) if (sku == null)
return; return;
@@ -763,7 +763,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var goods = JsonHelper.DeserializeJsonToObject<pddFrontGoods3Lite>(skuInfo.map_skus); var goods = JsonHelper.DeserializeJsonToObject<pddFrontGoods3Lite>(skuInfo.map_skus);
if (goods == null) if (goods == null)
return; return;
var sku = goods.skus.FirstOrDefault(s => s.skuID.ParseToString() == info.map_sku_id); var sku = goods.skus.FirstOrDefault(s => s.skuId.ParseToString() == info.map_sku_id);
if (sku == null) if (sku == null)
return; return;
@@ -829,7 +829,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
} }
else else
{ {
return "获取失败,请关闭拍单窗口重试 " + BaseRegex.GetStringXml(ref sourceCodeRst, "msg", sourceCodeRst); return "溯源码获取失败,请关闭拍单窗口重试 " + BaseRegex.GetStringXml(ref sourceCodeRst, "msg", sourceCodeRst);
} }
} }
@@ -1022,7 +1022,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
/// <summary> /// <summary>
/// 更新拍单成功信息 /// 更新拍单成功信息
/// </summary> /// </summary>
public void ManualUpdateBuyOrder() public async void ManualUpdateBuyOrder()
{ {
if (BuyType == "transit" && txtSourceCodeVal.Trim().Length != 6) if (BuyType == "transit" && txtSourceCodeVal.Trim().Length != 6)
{ {
@@ -1119,24 +1119,18 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var dataStr = JsonHelper.SerializeObject(body); var dataStr = JsonHelper.SerializeObject(body);
//dataStr = "{\"orderNo\":\"3737339733954942720\",\"outOrderNo\":\"2606846854564\",\"buyerAccount\":\"测试\",\"outAmount\":\"2000\",\"purchaserNote\":\"测试\",\"express1Company\":\"\"" + //dataStr = "{\"orderNo\":\"3737339733954942720\",\"outOrderNo\":\"2606846854564\",\"buyerAccount\":\"测试\",\"outAmount\":\"2000\",\"purchaserNote\":\"测试\",\"express1Company\":\"\"" +
// ",\"express1Waybill\":\"\",\"platform\":\"XDYSHC\",\"orderPlatformCode\":\"WEISHOP\"}"; // ",\"express1Waybill\":\"\",\"platform\":\"XDYSHC\",\"orderPlatformCode\":\"WEISHOP\"}";
var exportRst = HttpResponseWXBLL.e57PostResponse(url, dataStr, ""); var exportRst = await HttpResponseWXBLL.e57PostResponseAsync(url, dataStr);
//<AjaxResult><msg>保存成功</msg><code>200</code></AjaxResult> //<AjaxResult><msg>保存成功</msg><code>200</code></AjaxResult>
//<AjaxResult><msg>订单不存在:373733973395494272</msg><code>500</code></AjaxResult> //<AjaxResult><msg>订单不存在:373733973395494272</msg><code>500</code></AjaxResult>
if (!exportRst.ParseToString().Contains("<code>200</code>")) if (!exportRst.ParseToString().Contains("\"code\":200"))
{
await Task.Delay(500);
exportRst = await HttpResponseWXBLL.e57PostResponseAsync(url, dataStr);
}
if (!exportRst.ParseToString().Contains("\"code\":200"))
{ {
string msg = ""; string msg = "";
string code = ""; msg = BaseRegex.GetStringJsonByRegs(ref exportRst, exportRst, "msg");
try
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(exportRst);
code = xmlDoc["AjaxResult"]["code"].InnerText;
msg = xmlDoc["AjaxResult"]["msg"].InnerText;
}
catch
{
msg = exportRst.ParseToString();
}
this.ErrorMsg = "拍单保存失败,服务端返回 " + msg; this.ErrorMsg = "拍单保存失败,服务端返回 " + msg;
Enabled = true; Enabled = true;
return; return;
@@ -1148,10 +1142,13 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
{ {
buyer_account = buyer.buyer_id, buyer_account = buyer.buyer_id,
id = 0, id = 0,
order_void_status = 0,
platform = transit.TransId,
order_no = orderItem.order_id, order_no = orderItem.order_id,
order_sku_id = orderItem.sku_id, order_sku_id = orderItem.sku_id,
out_amount = (txtBuyPriceVal.ParseToDecimal() * 100).ParseToInt(), out_amount = (txtBuyPriceVal.ParseToDecimal() * 100).ParseToInt(),
out_order_no = "tb_" + txtBuyOrderIdVal.Trim(), out_order_no = txtBuyOrderIdVal.Trim(),
order_code = txtBuyOrderIdVal.Trim(),
purchaser_note = body["purchaserNote"].ParseToString(), purchaser_note = body["purchaserNote"].ParseToString(),
created_time = DateTime.Now, created_time = DateTime.Now,
}); });
@@ -1222,6 +1219,11 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
if (BuyType == "direct") if (BuyType == "direct")
{ {
#region 直发拍单 #region 直发拍单
if (orderItem.ItemOrder?.Shop == null)
{
this.ErrorMsg = "缺少店铺信息!";
return;
}
var url = BaseClass.Build29WxObjString("order/wx_get_order_item_ext_info"); var url = BaseClass.Build29WxObjString("order/wx_get_order_item_ext_info");
var data = UserLogin.GetSignaturex(); var data = UserLogin.GetSignaturex();
@@ -1241,8 +1243,8 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
order_id = orderItem.order_id, order_id = orderItem.order_id,
sku_id = orderItem.sku_id, sku_id = orderItem.sku_id,
out_order_id = "tb_" + txtBuyOrderIdVal.Trim(), out_order_id = "tb_" + txtBuyOrderIdVal.Trim(),
shop_app_id = orderItem.Shop.ShopId, shop_app_id = orderItem.ItemOrder?.Shop?.ShopId,
shop_name = orderItem.Shop.ShopAccount, shop_name = orderItem.ItemOrder?.Shop?.ShopAccount,
buy_type = "直发", buy_type = "直发",
}; };
var url1 = BaseClass.Build29WxObjString("order/wx_add_order_item_ext_info"); var url1 = BaseClass.Build29WxObjString("order/wx_add_order_item_ext_info");
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,5 @@
using _29WxOrderWpf.BaseWindows; using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.CefHelper; using _29WxOrderWpf.CefHelper;
using WxOrder.Framework.Commons;
using _29WxOrderWpf.ViewModels; using _29WxOrderWpf.ViewModels;
using AllBase; using AllBase;
using AllBase.Helper; using AllBase.Helper;
@@ -27,6 +26,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using TemuKJD.ToolForms; using TemuKJD.ToolForms;
using Work; using Work;
@@ -338,7 +338,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
ManualUpdateBuyOrderCommand = new DelegateCommand(ManualUpdateBuyOrder); ManualUpdateBuyOrderCommand = new DelegateCommand(ManualUpdateBuyOrder);
UpdateTransitWarehouseCommand = new DelegateCommand(UpdateTransitWarehouse); UpdateTransitWarehouseCommand = new DelegateCommand(UpdateTransitWarehouse);
this.txtShopNameVal = orderItem.Shop.ShopAccount; this.txtShopNameVal = orderItem.ItemOrder?.Shop?.ShopAccount;
this.txtOrderIdVal = orderItem.order_id; this.txtOrderIdVal = orderItem.order_id;
this.txtShopSkuIdVal = orderItem.sku_id; this.txtShopSkuIdVal = orderItem.sku_id;
this.txtShopGoodsIdVal = orderItem.product_id; this.txtShopGoodsIdVal = orderItem.product_id;
@@ -1335,17 +1335,17 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var pddFrontSkuInfo = new frontSkuInfo3() var pddFrontSkuInfo = new frontSkuInfo3()
{ {
skuId = key.ParseToLong(), skuId = key.ParseToLong(),
skuID = key.ParseToLong(), //skuID = key.ParseToLong(),
goodsId = pddFrontGoods3.goodsId, goodsId = pddFrontGoods3.goodsId,
thumbUrl = thumbUrl, thumbUrl = thumbUrl,
quantity = tbSku2.quantity, //quantity = tbSku2.quantity,
isOnsale = 1, //isOnsale = 1,
spec = taobaoSku?.propPath, // 淘宝格式与拼多多存在差异,包含冒号与父类型id spec = taobaoSku?.propPath, // 淘宝格式与拼多多存在差异,包含冒号与父类型id
specs = pddSpecs, specs = pddSpecs,
price = tbSku2.price.priceMoney.ParseToInt() + 100, price = tbSku2.price?.priceMoney.ParseToInt() + 100,
normalPrice = ((tbSku2.price.priceMoney.ParseToInt() + 100) / 100m).ToString("F2"), normalPrice = ((tbSku2.price?.priceMoney.ParseToInt() + 100) / 100m).ParseToDecimal().ToString("F2"),
groupPrice = tbSku2.price.priceText, groupPrice = tbSku2.price?.priceText,
oldGroupPrice = tbSku2.price.priceMoney.ParseToInt(), oldGroupPrice = tbSku2.price?.priceMoney.ParseToInt(),
}; };
pddFrontGoods3.skus.Add(pddFrontSkuInfo); pddFrontGoods3.skus.Add(pddFrontSkuInfo);
} }
@@ -1441,7 +1441,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var goods = JsonHelper.DeserializeJsonToObject<pddFrontGoods3Lite>(skuInfo.map_skus); var goods = JsonHelper.DeserializeJsonToObject<pddFrontGoods3Lite>(skuInfo.map_skus);
if (goods == null) if (goods == null)
return; return;
var sku = goods.skus.FirstOrDefault(s => s.skuID.ParseToString() == info.map_sku_id); var sku = goods.skus.FirstOrDefault(s => s.skuId.ParseToString() == info.map_sku_id);
if (sku == null) if (sku == null)
return; return;
@@ -1472,7 +1472,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var goods = JsonHelper.DeserializeJsonToObject<pddFrontGoods3Lite>(skuInfo.map_skus); var goods = JsonHelper.DeserializeJsonToObject<pddFrontGoods3Lite>(skuInfo.map_skus);
if (goods == null) if (goods == null)
return; return;
var sku = goods.skus.FirstOrDefault(s => s.skuID.ParseToString() == info.map_sku_id); var sku = goods.skus.FirstOrDefault(s => s.skuId.ParseToString() == info.map_sku_id);
if (sku == null) if (sku == null)
return; return;
@@ -1544,7 +1544,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
} }
else else
{ {
return "获取失败,请关闭拍单窗口重试 " + BaseRegex.GetStringXml(ref sourceCodeRst, "msg", sourceCodeRst); return "溯源码获取失败,请关闭拍单窗口重试 " + BaseRegex.GetStringXml(ref sourceCodeRst, "msg", sourceCodeRst);
} }
} }
@@ -1737,9 +1737,9 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
/// <summary> /// <summary>
/// 更新拍单成功信息 /// 更新拍单成功信息
/// </summary> /// </summary>
public void ManualUpdateBuyOrder() public async void ManualUpdateBuyOrder()
{ {
if (BuyType == "transit" && txtSourceCodeVal.Trim().Length != 6) if (BuyType == "transit" && txtSourceCodeVal.ParseToString().Trim().Length != 6)
{ {
ErrorMsg = "溯源码长度错误!"; ErrorMsg = "溯源码长度错误!";
return; return;
@@ -1832,26 +1832,16 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
} }
var url = "https://po.e57.cn/prod-api/api/oms-api/externalProcurement/saveOrUpdate"; var url = "https://po.e57.cn/prod-api/api/oms-api/externalProcurement/saveOrUpdate";
var dataStr = JsonHelper.SerializeObject(body); var dataStr = JsonHelper.SerializeObject(body);
//dataStr = "{\"orderNo\":\"3737339733954942720\",\"outOrderNo\":\"2606846854564\",\"buyerAccount\":\"测试\",\"outAmount\":\"2000\",\"purchaserNote\":\"测试\",\"express1Company\":\"\"" + var exportRst = await HttpResponseWXBLL.e57PostResponseAsync(url, dataStr);
// ",\"express1Waybill\":\"\",\"platform\":\"XDYSHC\",\"orderPlatformCode\":\"WEISHOP\"}"; if (!exportRst.ParseToString().Contains("\"code\":200"))
var exportRst = HttpResponseWXBLL.e57PostResponse(url, dataStr, ""); {
//<AjaxResult><msg>保存成功</msg><code>200</code></AjaxResult> await Task.Delay(500);
//<AjaxResult><msg>订单不存在:373733973395494272</msg><code>500</code></AjaxResult> exportRst = await HttpResponseWXBLL.e57PostResponseAsync(url, dataStr);
if (!exportRst.ParseToString().Contains("<code>200</code>")) }
if (!exportRst.ParseToString().Contains("\"code\":200"))
{ {
string msg = ""; string msg = "";
string code = ""; msg = BaseRegex.GetStringJsonByRegs(ref exportRst, exportRst, "msg");
try
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(exportRst);
code = xmlDoc["AjaxResult"]["code"].InnerText;
msg = xmlDoc["AjaxResult"]["msg"].InnerText;
}
catch (Exception ex)
{
msg = exportRst.ParseToString();
}
this.ErrorMsg = "拍单保存失败,服务端返回 " + msg; this.ErrorMsg = "拍单保存失败,服务端返回 " + msg;
Enabled = true; Enabled = true;
return; return;
@@ -1863,10 +1853,13 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
{ {
buyer_account = buyer.buyer_id, buyer_account = buyer.buyer_id,
id = 0, id = 0,
order_void_status = 0,
platform = transit.TransId,
order_no = orderItem.order_id, order_no = orderItem.order_id,
order_sku_id = orderItem.sku_id, order_sku_id = orderItem.sku_id,
out_amount = (txtBuyPriceVal.ParseToDecimal() * 100).ParseToInt(), out_amount = (txtBuyPriceVal.ParseToDecimal() * 100).ParseToInt(),
out_order_no = "tb_" + txtBuyOrderIdVal.Trim(), out_order_no = "tb_" + txtBuyOrderIdVal.Trim(),
order_code = "tb_" + txtBuyOrderIdVal.Trim(),
purchaser_note = body["purchaserNote"].ParseToString(), purchaser_note = body["purchaserNote"].ParseToString(),
created_time = DateTime.Now, created_time = DateTime.Now,
}); });
@@ -1937,6 +1930,11 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
if (BuyType == "direct") if (BuyType == "direct")
{ {
#region 直发拍单 #region 直发拍单
if (orderItem.ItemOrder?.Shop == null)
{
this.ErrorMsg = "缺少店铺信息!";
return;
}
var url = BaseClass.Build29WxObjString("order/wx_get_order_item_ext_info"); var url = BaseClass.Build29WxObjString("order/wx_get_order_item_ext_info");
var data = UserLogin.GetSignaturex(); var data = UserLogin.GetSignaturex();
@@ -1956,8 +1954,8 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
order_id = orderItem.order_id, order_id = orderItem.order_id,
sku_id = orderItem.sku_id, sku_id = orderItem.sku_id,
out_order_id = "tb_" + txtBuyOrderIdVal.Trim(), out_order_id = "tb_" + txtBuyOrderIdVal.Trim(),
shop_app_id = orderItem.Shop.ShopId, shop_app_id = orderItem.ItemOrder?.Shop?.ShopId,
shop_name = orderItem.Shop.ShopAccount, shop_name = orderItem.ItemOrder?.Shop?.ShopAccount,
buy_type = "直发", buy_type = "直发",
}; };
var url1 = BaseClass.Build29WxObjString("order/wx_add_order_item_ext_info"); var url1 = BaseClass.Build29WxObjString("order/wx_add_order_item_ext_info");
@@ -270,22 +270,6 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
Thread.Sleep(1); Thread.Sleep(1);
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(new Action(() =>
{ {
if (cefShowShopOrderLstWebBrowser == null)
{
cefShowShopOrderLstWebBrowser = WPFCEFBrowser.CreateChromiumWebBrowser("about:blank", false);
LocalResourceRequestHandler resourceRequestHandler = new LocalResourceRequestHandler();
resourceRequestHandler.ResourceLoadCompleteEvent += RequestHandler_ResourceLoadComplete;
resourceRequestHandler.BeforeResourceLoadEvent += RequestHandler_BeforeResourceLoad;
cefShowShopOrderLstWebBrowser.RequestHandler = new LocalRequestHandler(resourceRequestHandler);
var lifeSapnHandler = new LocalLifeSpanHandler(PopWindowType.SelfWindow);
cefShowShopOrderLstWebBrowser.LifeSpanHandler = lifeSapnHandler;
cefShowShopOrderLstWebBrowser.KeyboardHandler = new CefKeyboardHandler();
cefShowShopOrderLstWebBrowser.FrameLoadEnd += CefWebBrowser_FrameLoadEnd;
cefShowShopOrderLstWebBrowser.AddressChanged += CefWebBrowser_AddressChanged;
cefShowShopOrderLstWebBrowser.LoadError += CefWebBrowser_LoadError;
Grid.SetRow(cefShowShopOrderLstWebBrowser, 0);
this.GridCef.Children.Add(cefShowShopOrderLstWebBrowser);
}
if (cefWebBrowser == null) if (cefWebBrowser == null)
{ {
cefWebBrowser = WPFCEFBrowser.CreateChromiumWebBrowser("about:blank", false); cefWebBrowser = WPFCEFBrowser.CreateChromiumWebBrowser("about:blank", false);
@@ -305,6 +289,22 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
if (buyer.wpf_browser == null) if (buyer.wpf_browser == null)
buyer.wpf_browser = cefWebBrowser; buyer.wpf_browser = cefWebBrowser;
if (cefShowShopOrderLstWebBrowser == null)
{
cefShowShopOrderLstWebBrowser = WPFCEFBrowser.CreateChromiumWebBrowser("about:blank", false);
LocalResourceRequestHandler resourceRequestHandler = new LocalResourceRequestHandler();
resourceRequestHandler.ResourceLoadCompleteEvent += RequestHandler_ResourceLoadComplete;
resourceRequestHandler.BeforeResourceLoadEvent += RequestHandler_BeforeResourceLoad;
cefShowShopOrderLstWebBrowser.RequestHandler = new LocalRequestHandler(resourceRequestHandler);
var lifeSapnHandler = new LocalLifeSpanHandler(PopWindowType.SelfWindow);
cefShowShopOrderLstWebBrowser.LifeSpanHandler = lifeSapnHandler;
cefShowShopOrderLstWebBrowser.KeyboardHandler = new CefKeyboardHandler();
cefShowShopOrderLstWebBrowser.FrameLoadEnd += CefWebBrowser_FrameLoadEnd;
cefShowShopOrderLstWebBrowser.AddressChanged += CefWebBrowser_AddressChanged;
cefShowShopOrderLstWebBrowser.LoadError += CefWebBrowser_LoadError;
Grid.SetRow(cefShowShopOrderLstWebBrowser, 0);
this.GridCef.Children.Add(cefShowShopOrderLstWebBrowser);
}
})); }));
} }
} }
@@ -433,52 +433,6 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
return transitOrderList; return transitOrderList;
} }
/// <summary>
/// 读取订单详情信息
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
List<oms_wei_order_info> GetOrderInfo(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<oms_wei_order_info>();
Thread.Sleep(100);
var url1 = BaseClass.Build29WxObjString("order/get_erp_order_list");
var data1 = UserLogin.GetSignaturex();
data1 += "&erp_order_id_in=" + order_ids;
data1 += "&page_size=" + 100;
var html1 = GetHtml.PostUtf8(url1, data1);
if (string.IsNullOrEmpty(html1) || !html1.Contains("\"code\":200"))
html1 = GetHtml.PostUtf8(url1, data1);
if (string.IsNullOrEmpty(html1) || !html1.Contains("\"code\":200"))
{
//BaseMsgWindow.ShowError("订单读取失败 " + BaseRegex.GetStringJson(ref html, "msg"));
//break;
}
List<oms_wei_order_info> orders = new List<oms_wei_order_info>();
try
{
orders = JsonHelper.DeserializeJsonToList<oms_wei_order_info>(JObject.Parse(html1)["data"].ParseToString());
if (orders == null)
orders = new List<oms_wei_order_info>();
var orderItems = OrderListCtrl.GetOrderItemInfo(order_ids);
foreach (var orderItem in orderItems)
{
var order = orders.FirstOrDefault(o => o.order_id == orderItem.order_id);
orderItem.ItemOrder = order;
order.orderItems.Add(orderItem);
}
return orders;
}
catch
{
return new List<oms_wei_order_info>();
}
}
public static List<order_tb_buyer_after_sale> GetOrderAfterSales(string order_ids) public static List<order_tb_buyer_after_sale> GetOrderAfterSales(string order_ids)
{ {
if (order_ids.IsNullOrEmpty()) if (order_ids.IsNullOrEmpty())
@@ -660,9 +614,17 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
oList.Add(o); oList.Add(o);
if (o.order_sn == "tb_5127890185262007919")
{
}
// 售后单放在同一个列表中统一处理 // 售后单放在同一个列表中统一处理
var refundStatus = BaseRegex.GetStringJson(ref orderItemInfoStr, "refundStatus"); var refundStatus = BaseRegex.GetStringJson(ref orderItemInfoStr, "refundStatus");
if (!string.IsNullOrEmpty(refundStatus) && !string.IsNullOrEmpty(orderStatus)) if (refundStatus.IsNullOrEmpty())
{
refundStatus = BaseRegex.GetStringJson(ref shopInfoStr, "tradeTitle") == "交易关闭" ? "退款成功" : "";
}
if ((!string.IsNullOrEmpty(refundStatus) && !string.IsNullOrEmpty(orderStatus)) || refundStatus == "退款成功")
{ {
TbBuyerAfterSaleLiteInfo af = new TbBuyerAfterSaleLiteInfo(); TbBuyerAfterSaleLiteInfo af = new TbBuyerAfterSaleLiteInfo();
af.buyerId = o.buyerId; af.buyerId = o.buyerId;
@@ -724,7 +686,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var out_order_nos = string.Join(",", list.Select(bo => bo.order_sn)); var out_order_nos = string.Join(",", list.Select(bo => bo.order_sn));
// 装载同步单 // 装载同步单
var syncOrderList = OrderListCtrl.GetSyncLogistics(out_order_nos); var syncOrderList = await OrderGetOrderListHelper.GetSyncLogistics(out_order_nos);
foreach (var syncOrder in syncOrderList) foreach (var syncOrder in syncOrderList)
{ {
if (!lstSyncLogistics.Contains(syncOrder)) if (!lstSyncLogistics.Contains(syncOrder))
@@ -746,7 +708,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
var order_id_lst = transitOrderList.Select(ts => ts.order_no).ToList(); var order_id_lst = transitOrderList.Select(ts => ts.order_no).ToList();
order_id_lst.AddRange(orderExtList.Select(ts => ts.order_id)); order_id_lst.AddRange(orderExtList.Select(ts => ts.order_id));
var order_ids = string.Join(",", order_id_lst.Distinct()); var order_ids = string.Join(",", order_id_lst.Distinct());
var orders = GetOrderInfo(order_ids); var orders = await OrderGetOrderListHelper.GetOrderInfo(order_ids);
//var buyerAfterSales = GetOrderAfterSales(order_ids); //var buyerAfterSales = GetOrderAfterSales(order_ids);
@@ -769,7 +731,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
o.buyerId = buyer.buyer_id; o.buyerId = buyer.buyer_id;
o.buyerName = buyer.buyer_name; o.buyerName = buyer.buyer_name;
if (o.order_sn == "tb_5127796188031004903") if (o.order_sn == "tb_5127890185262007919")
{ {
} }
@@ -1095,7 +1057,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
order_id_lst.AddRange(orderExtList.Select(ts => ts.order_id)); order_id_lst.AddRange(orderExtList.Select(ts => ts.order_id));
var order_ids = string.Join(",", order_id_lst.Distinct()); var order_ids = string.Join(",", order_id_lst.Distinct());
var orders = GetOrderInfo(order_ids); var orders = await OrderGetOrderListHelper.GetOrderInfo(order_ids);
foreach (var order in orders) foreach (var order in orders)
{ {
foreach (var orderItem in order.orderItems) foreach (var orderItem in order.orderItems)
@@ -1116,11 +1078,6 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
foreach (TbBuyerAfterSaleLiteInfo af in list) foreach (TbBuyerAfterSaleLiteInfo af in list)
{ {
if (af?.orderSn == "tb_5127796188031004903")
{
}
af.buyerId = buyer.buyer_id; af.buyerId = buyer.buyer_id;
af.buyerName = buyer.buyer_name; af.buyerName = buyer.buyer_name;
@@ -1353,7 +1310,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
if (!lstTbBuyerOrderVoidAfterSaleOrderSn.Contains(orderItem.order_id + orderItem.sku_id)) if (!lstTbBuyerOrderVoidAfterSaleOrderSn.Contains(orderItem.order_id + orderItem.sku_id))
{ {
lstTbBuyerOrderVoidAfterSaleOrderSn.Add(orderItem.order_id + orderItem.sku_id); lstTbBuyerOrderVoidAfterSaleOrderSn.Add(orderItem.order_id + orderItem.sku_id);
OrderListRowItemCtrl.VoidOrder(orderItem, true); await OrderTransitService.VoidOrder(orderItem, null, true);
} }
} }
} }
@@ -1664,13 +1621,13 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
if (btn.DataContext is TbBuyerOrderLiteInfo buyerOrder) if (btn.DataContext is TbBuyerOrderLiteInfo buyerOrder)
{ {
btn.IsEnabled = false; btn.IsEnabled = false;
Task.Run(() => Task.Run(async () =>
{ {
var out_order_nos = buyerOrder.order_sn; var out_order_nos = buyerOrder.order_sn;
var transitOrderList = GetOrderTransitWarehouseInfo(out_order_nos); var transitOrderList = GetOrderTransitWarehouseInfo(out_order_nos);
var order_ids = string.Join(",", transitOrderList.Select(ts => ts.order_no)); var order_ids = string.Join(",", transitOrderList.Select(ts => ts.order_no));
var orders = GetOrderInfo(order_ids); var orders = await OrderGetOrderListHelper.GetOrderInfo(order_ids);
foreach (var order in orders) foreach (var order in orders)
{ {
foreach (var orderItem in order.orderItems) foreach (var orderItem in order.orderItems)
@@ -2008,7 +1965,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
} }
} }
public void SetPickUpNo(TbPickInfo tbPickInfo) public async Task SetPickUpNo(TbPickInfo tbPickInfo)
{ {
List<combine_track_info> orderSnTracks = new List<combine_track_info>(); List<combine_track_info> orderSnTracks = new List<combine_track_info>();
foreach (var combine in tbPickInfo.combine_list) foreach (var combine in tbPickInfo.combine_list)
@@ -2023,8 +1980,8 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
if (orderSnTracks.Count == 0) if (orderSnTracks.Count == 0)
return; return;
//var syncOrderAllList = OrderListCtrl.GetSyncLogistics(string.Join(",", orderSnTracks.Select(o => o.order_sn))); //var syncOrderAllList = OrderGetOrderListHelper.GetSyncLogistics(string.Join(",", orderSnTracks.Select(o => o.order_sn)));
var syncOrderList = OrderListCtrl.GetSyncLogistics(string.Join(",", orderSnTracks.Select(o => o.order_sn)), 1); var syncOrderList = await OrderGetOrderListHelper.GetSyncLogistics(string.Join(",", orderSnTracks.Select(o => o.order_sn)), 1);
foreach (var sOrder in syncOrderList) foreach (var sOrder in syncOrderList)
{ {
var orderSnTrack = orderSnTracks.FirstOrDefault(o => o.order_sn == sOrder.order_id); var orderSnTrack = orderSnTracks.FirstOrDefault(o => o.order_sn == sOrder.order_id);
@@ -2105,7 +2062,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
} }
} }
public void SendAsyncWaybillOrder(TbBuyerOrderLiteInfo order, bool showErrBox = false) public async Task SendAsyncWaybillOrder(TbBuyerOrderLiteInfo order, bool showErrBox = false)
{ {
try try
{ {
@@ -2116,7 +2073,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
} }
// 取最新订单状态 // 取最新订单状态
var wxOrder = GetOrderInfo(order.ShopOrderIdStr).FirstOrDefault(); var wxOrder = (await OrderGetOrderListHelper.GetOrderInfo(order.ShopOrderIdStr)).FirstOrDefault();
if (wxOrder == null) if (wxOrder == null)
throw new Exception("买手单对应微信订单不存在!"); throw new Exception("买手单对应微信订单不存在!");
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == wxOrder.shop_id.ToString()); var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == wxOrder.shop_id.ToString());
@@ -2674,7 +2631,7 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1); Panel.SetZIndex(MainWindow.Instance.gridTbBuyerOrderReadCtrl, -1);
} }
private void CheckBox_Click(object sender, RoutedEventArgs e) private async void CheckBox_Click(object sender, RoutedEventArgs e)
{ {
if (sender is CheckBox chk) if (sender is CheckBox chk)
{ {
@@ -2695,18 +2652,18 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
//t.Wait(); //t.Wait();
foreach (var cook in cookieLst) foreach (var cook in cookieLst)
{ {
var t = WPFCEFBrowser.SetCookieAsync(cook.Domain.Trim('.'), cook.Name + "=" + cook.Value + ";", cefShowShopOrderLstWebBrowser.GetCookieManager(null)); await WPFCEFBrowser.SetCookieAsync(cook.Domain.Trim('.'), cook.Name + "=" + cook.Value + ";", cefShowShopOrderLstWebBrowser.GetCookieManager(null));
t.Wait(5000);
} }
Panel.SetZIndex(this.cefShowShopOrderLstWebBrowser, maxZIndex++); Panel.SetZIndex(this.cefShowShopOrderLstWebBrowser, maxZIndex++);
cefShowShopOrderLstWebBrowser.Load("https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm?");
} }
} }
} }
//if (e.Source) //if (e.Source)
} }
private void txtBuyerNick_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) private async void txtBuyerNick_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{ {
if (sender is TextBox txt) if (sender is TextBox txt)
{ {
@@ -2727,11 +2684,11 @@ namespace _29WxOrderWpf.Ctrls.BuyerCtrls
//t.Wait(); //t.Wait();
foreach (var cook in cookieLst) foreach (var cook in cookieLst)
{ {
var t = WPFCEFBrowser.SetCookieAsync(cook.Domain.Trim('.'), cook.Name + "=" + cook.Value + ";", cefShowShopOrderLstWebBrowser.GetCookieManager(null)); await WPFCEFBrowser.SetCookieAsync(cook.Domain.Trim('.'), cook.Name + "=" + cook.Value + ";", cefShowShopOrderLstWebBrowser.GetCookieManager(null));
t.Wait(5000);
} }
Panel.SetZIndex(this.cefShowShopOrderLstWebBrowser, maxZIndex++); Panel.SetZIndex(this.cefShowShopOrderLstWebBrowser, maxZIndex++);
cefShowShopOrderLstWebBrowser.Load("https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm?");
} }
} }
} }
@@ -0,0 +1,91 @@
using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.Ctrls.BuyerCtrls;
using _29WxOrderWpf.ViewModels;
using AllBase;
using AllBase.Helper;
using AllBase.Model.DBModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using TemuKJD.ToolForms;
using WxOrder.Framework.Commons;
namespace _29WxOrderWpf.Ctrls.OrderCtrls;
internal class OrderBuyerOrdersHelper
{
public static void ShowBuyerOrder(oms_wei_order_item_info orderItem, string buyerAccount, string buyerName, string outOrderId, bool isShowOrderList = false)
{
if (outOrderId.StartsWith("tb_")) // 淘宝买手及订单
{
var buyer = GlobalConfig.TaobaoBuyerLoginList.FirstOrDefault(p => p.buyer_id == buyerAccount || p.buyer_name == buyerName);
if (buyer == null)
{
BaseMsgWindow.ShowError("该订单买手号未在当前账户登录");
return;
}
var url = "";
if (isShowOrderList)
url = "https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm?";
else
url = "https://trade.tmall.com/detail/orderDetail.htm?bizOrderId=" + outOrderId.Replace("tb_", "");
TaobaoBuyOrderCtrl taobaoBuyView = new TaobaoBuyOrderCtrl(GlobalConfig.CurrentTaobaoBuyer, orderItem);
taobaoBuyView.ViewModel.InitUrl = url;
new DialogWindow()
{
Title = "订单查看 - 当前买手 " + buyer.buyer_nick,
Content = taobaoBuyView,
Width = SystemParameters.PrimaryScreenWidth < 1920 ? SystemParameters.PrimaryScreenWidth : SystemParameters.PrimaryScreenWidth * 90 / 100,
Height = SystemParameters.PrimaryScreenHeight * 90 / 100,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
}.ShowDialog();
}
else // 拼多多买手及订单
{
var buyer = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(p => p.buyer_id == buyerAccount || p.buyer_name == buyerName);
if (buyer == null)
{
BaseMsgWindow.ShowError("该订单买手号未在当前账户登录");
return;
}
var url = "";
if (isShowOrderList)
url = "https://mobile.yangkeduo.com/index.html"; /* 订单列表 */
else
url = "https://mobile.yangkeduo.com/order.html?order_sn=" + outOrderId + "&page_from=1&main_orders=1&is_tester=1&refer_page_name=my_order" +
"&refer_page_id=10032_" + BaseClass.DateTimeToTimestampMilliseconds(DateTime.Now) + "_" + Randomx.GetWordNumber(10) + "&refer_page_sn=10032";
// 拍单的时候检测一下买手号
if (buyer.status == "在线")
{
PddMobileLoginViewModel.CheckBuyerLogin(buyer);
}
if (buyer.status != "在线")
{
BaseMsgWindow.ShowError("买手号掉线");
return;
}
PddMobileBuyOrderForm buyOrderForm = new PddMobileBuyOrderForm(MainWindow.Instance.orderListCtrl.FilterOneOrder, StartUp.UpdateBalance, orderItem, buyer, orderItem.PddBuyMap)
{
TitleText = "订单查看 - 当前买手 " + buyer.buyer_nick,
InitUrl = url /* 订单页面 */
};
buyOrderForm.pnlBuy.Visible = false;
//已有拍单关联的控制界面显示隐藏
if (orderItem.PddBuyMap != null)
{
buyOrderForm.pnlBuy.Visible = true;
buyOrderForm.pnlMap.Visible = false;
}
buyOrderForm.ShowDialog();
}
}
}
@@ -0,0 +1,547 @@
using _29WxOrderWpf.BaseWindows;
using AllBase;
using AllBase.Helper;
using AllBase.Model.DBModel;
using NaiBa.Util.Extension;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Work;
namespace _29WxOrderWpf.Ctrls.OrderCtrls;
public class OrderGetOrderListHelper
{
/// <summary>
/// 增量读取全部订单信息
/// </summary>
/// <param name="lastUpdateTime"></param>
/// <returns></returns>
public static async Task GetWxOrder‌IncrementAsync(DateTime? lastUpdateTime)
{
if (lastUpdateTime == null || lastUpdateTime == DateTime.MinValue)
return;
var shopIdList = GlobalConfig.ShopLoginList.Select(s => s.ErpShopId.ToString()).ToList();
var shopIds = string.Join(",", shopIdList);
var existOrderIdList = GlobalConfig.ShopLoginList.Select(s => s.ErpShopId.ToString()).ToList();
var updateOrderList = await GetOrderInfoBase(null, 0, shopIds, lastUpdateTime);
var updateOrderIdList = GlobalConfig.ShopLoginList.Select(s => s.ErpShopId.ToString()).ToList();
var orderIdList = existOrderIdList;
orderIdList.AddRange(updateOrderIdList);
orderIdList = orderIdList.Distinct().ToList();
while(orderIdList.Count > 0 )
{
var orderIdTake = orderIdList.Take(500).ToList();
orderIdList.RemoveAll(o => orderIdTake.Contains(o));
var orderIds = string.Join(",", orderIdTake);
}
}
/// <summary>
/// 读取买手号订单对应的微信店铺订单信息
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<oms_wei_order_info>> GetOrderInfo(string order_ids)
{
return await GetOrderInfoBase(order_ids);
}
/// <summary>
/// 读取订单详情信息
/// </summary>
/// <param name="orderIds"></param>
/// <returns></returns>
static async Task<List<oms_wei_order_info>> GetOrderInfoBase(string orderIds, int pageSize = 100, string shopIds = null, DateTime? beginUpdateTime = null, DateTime? endUpdateTime = null)
{
if (string.IsNullOrEmpty(orderIds))
return new List<oms_wei_order_info>();
Thread.Sleep(100);
try
{
var url = BaseClass.Build29WxObjString("order/get_erp_order_list");
var data = UserLogin.GetSignaturex();
data += "&erp_order_id_in=" + orderIds;
data += "&page_size=" + pageSize;
if (!string.IsNullOrWhiteSpace(shopIds))
data += "&erp_shop_id_in=" + shopIds;
if (beginUpdateTime != null && beginUpdateTime != DateTime.MinValue)
{
var startTime = BaseClass.DateTimeToTimestampSeconds(beginUpdateTime.Value);
data += "&start_time=" + startTime;
}
if (endUpdateTime != null && endUpdateTime != DateTime.MinValue)
{
var endTime = BaseClass.DateTimeToTimestampSeconds(endUpdateTime.Value);
data += "&end_time=" + endTime;
}
var html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
{
throw new Exception("订单读取失败 " + BaseRegex.GetStringJson(ref html, "msg"));
}
List<oms_wei_order_info> orders = new List<oms_wei_order_info>();
orders = JsonHelper.DeserializeJsonToList<oms_wei_order_info>(JObject.Parse(html)["data"].ParseToString());
if (orders == null)
orders = new List<oms_wei_order_info>();
var orderItems = await GetOrderItemInfo(orderIds);
foreach (var orderItem in orderItems)
{
var order = orders.FirstOrDefault(o => o.order_id == orderItem.order_id);
orderItem.ItemOrder = order;
order.orderItems.Add(orderItem);
}
return orders;
}
catch (Exception ex)
{
BaseMsgWindow.ShowAnimateMessage(ex.Message, "Error", 6);
return new List<oms_wei_order_info>();
}
}
/// <summary>
/// 读取订单详情信息
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<oms_wei_order_item_info>> GetOrderItemInfo(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<oms_wei_order_item_info>();
var url = BaseClass.Build29WxObjString("order/get_erp_order_item_list");
var data = UserLogin.GetSignaturex();
data += "&erp_order_id_in=" + order_ids;
data += "&page_size=" + 2500;
var html = await GetHtml.PostUtf8Async(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = await GetHtml.PostUtf8Async(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单详情读取失败 " + BaseRegex.GetStringJson(ref html, "msg"), "Error", 5);
}
List<oms_wei_order_item_info> orderItems = new List<oms_wei_order_item_info>();
try
{
orderItems = JsonHelper.DeserializeJsonToList<oms_wei_order_item_info>(JObject.Parse(html)["data"].ParseToString());
if (orderItems == null)
orderItems = new List<oms_wei_order_item_info>();
}
catch (Exception ex)
{
orderItems = new List<oms_wei_order_item_info>();
BaseMsgWindow.ShowAnimateMessage("订单详情读取失败 " + ex.Message, "Error", 5);
}
return orderItems;
}
/// <summary>
/// 读取售后单
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<oms_wei_refund_info>> GetOrderRefundInfo(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<oms_wei_refund_info>();
Thread.Sleep(100);
var url2 = BaseClass.Build29WxObjString("order/get_erp_refund_list");
var data2 = UserLogin.GetSignaturex();
data2 += "&erp_order_id_in=" + order_ids;
var html2 = await GetHtml.PostUtf8Async(url2, data2);
if (string.IsNullOrEmpty(html2) || !html2.Contains("\"code\":200"))
html2 = await GetHtml.PostUtf8Async(url2, data2);
if (string.IsNullOrEmpty(html2) || !html2.Contains("\"code\":200"))
{
//BaseMsgWindow.ShowError(MainWindow.Instance, "订单读取失败 " + BaseRegex.GetStringJson(ref html, "msg"));
//break;
}
List<oms_wei_refund_info> refunds = new List<oms_wei_refund_info>();
try { refunds = JsonHelper.DeserializeJsonToList<oms_wei_refund_info>(JObject.Parse(html2)["data"].ParseToString()); } catch { }
return refunds;
}
/// <summary>
/// 读取扩展订单信息
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<order_item_ext>> GetOrderItemExts(string order_ids)
{
List<order_item_ext> existOrderExtList = new List<order_item_ext>();
if (!string.IsNullOrEmpty(order_ids))
{
var url = BaseClass.Build29WxObjString("order/wx_get_order_item_ext_info");
var data = UserLogin.GetSignaturex();
data += "&wx_order_id_in=" + order_ids;
var html = await GetHtml.PostUtf8Async(url, data);
if (!html.Contains("\"code\":200"))
html = await GetHtml.PostUtf8Async(url, data);
if (!html.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单扩展信息查询失败 " + BaseRegex.GetStringJson(ref html, "msg"), "Error", 5);
}
try
{
existOrderExtList = JsonHelper.DeserializeJsonToList<order_item_ext>(JsonHelper.JObjectParse(html)["data"].ParseToString());
}
catch
{
}
}
return existOrderExtList;
}
/// <summary>
/// 读取中转仓订单发货包裹信息
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<oms_wei_external_procurement_log_info>> GetTransitWarehouseList(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<oms_wei_external_procurement_log_info>();
var url3 = BaseClass.Build29WxObjString("order/wx_get_transit_order");
var data3 = UserLogin.GetSignaturex();
data3 += "&order_no=" + order_ids;
data3 += "&page_size=5000";
var html3 = await GetHtml.PostUtf8Async(url3, data3);
if (string.IsNullOrEmpty(html3) || !html3.Contains("\"code\":200"))
html3 = await GetHtml.PostUtf8Async(url3, data3);
if (string.IsNullOrEmpty(html3) || !html3.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单读取失败 " + BaseRegex.GetStringJson(ref html3, "msg"), "Error", 5);
}
List<oms_wei_external_procurement_log_info> transitOrderList = new List<oms_wei_external_procurement_log_info>();
try
{
transitOrderList = JsonHelper.DeserializeJsonToList<oms_wei_external_procurement_log_info>(JObject.Parse(html3)["data"].ParseToString());
return transitOrderList;
}
catch
{
}
return new List<oms_wei_external_procurement_log_info>();
}
/// <summary>
/// 读取中转仓额外包裹
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<oms_wei_transfer_extra_package>> GetTransitExtraPackageList(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<oms_wei_transfer_extra_package>();
var url3 = BaseClass.Build29WxObjString("order/wx_get_transfer_extra_package");
var data3 = UserLogin.GetSignaturex();
data3 += "&order_no=" + order_ids;
var html3 = await GetHtml.PostUtf8Async(url3, data3);
if (string.IsNullOrEmpty(html3) || !html3.Contains("\"code\":200"))
html3 = await GetHtml.PostUtf8Async(url3, data3);
if (string.IsNullOrEmpty(html3) || !html3.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单读取失败 " + BaseRegex.GetStringJson(ref html3, "msg"), "Error", 5);
}
List<oms_wei_transfer_extra_package> transitExtraPackageList = new List<oms_wei_transfer_extra_package>();
try
{
transitExtraPackageList = JsonHelper.DeserializeJsonToList<oms_wei_transfer_extra_package>(JObject.Parse(html3)["data"].ParseToString());
return transitExtraPackageList;
}
catch
{
}
return new List<oms_wei_transfer_extra_package>();
}
/// <summary>
/// 读取中转仓退货包裹
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<oms_wei_external_procurement_after_sale_info>> GetTransitWarehouseAfterSaleList(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<oms_wei_external_procurement_after_sale_info>();
// 读取中转仓处理售后单
var url5 = BaseClass.Build29WxObjString("order/wx_get_transit_warehouse_aftersale_list");
var data5 = UserLogin.GetSignaturex();
data5 += "&wx_order_id_in=" + order_ids;
var html5 = await GetHtml.PostUtf8Async(url5, data5);
if (string.IsNullOrEmpty(html5) || !html5.Contains("\"code\":200"))
html5 = await GetHtml.PostUtf8Async(url5, data5);
if (string.IsNullOrEmpty(html5) || !html5.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("云仓售后订单读取失败 " + BaseRegex.GetStringJson(ref html5, "msg"), "Error", 5);
}
List<oms_wei_external_procurement_after_sale_info> transitAfterSaleList = new List<oms_wei_external_procurement_after_sale_info>();
try
{
transitAfterSaleList = JsonHelper.DeserializeJsonToList<oms_wei_external_procurement_after_sale_info>(JObject.Parse(html5)["data"].ParseToString())
.OrderByDescending(p => p.created_time).ToList();
if (transitAfterSaleList != null)
return transitAfterSaleList;
}
catch
{
}
return new List<oms_wei_external_procurement_after_sale_info>();
}
/// <summary>
/// 读取退货仓包裹
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<distrib_return_order_info>> GetTransitReturnOrderList(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<distrib_return_order_info>();
// 读取退货仓包裹
var url5 = BaseClass.Build29WxObjString("order/wx_get_erp_return_order_list");
var data5 = UserLogin.GetSignaturex();
data5 += "&erp_order_id_in=" + order_ids;
var html5 = await GetHtml.PostUtf8Async(url5, data5);
if (string.IsNullOrEmpty(html5) || !html5.Contains("\"code\":200"))
html5 = await GetHtml.PostUtf8Async(url5, data5);
if (string.IsNullOrEmpty(html5) || !html5.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("云仓分销退货订单读取失败 " + BaseRegex.GetStringJson(ref html5, "msg"), "Error", 5);
}
List<distrib_return_order_info> transitAfterSaleList = new List<distrib_return_order_info>();
try
{
transitAfterSaleList = JsonHelper.DeserializeJsonToList<distrib_return_order_info>(JObject.Parse(html5)["data"].ParseToString())
.OrderByDescending(p => p.created_at).ToList();
if (transitAfterSaleList != null)
return transitAfterSaleList;
}
catch
{
}
return new List<distrib_return_order_info>();
}
/// <summary>
/// 读取多多买手单
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<order_pdd_buyer_order>> GetPddBuyerOrders(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<order_pdd_buyer_order>();
var url4 = BaseClass.Build29WxObjString("order/wx_get_buyer_order_list");
var data4 = UserLogin.GetSignaturex();
data4 += "&wx_order_id_in=" + order_ids;
var html4 = await GetHtml.PostUtf8Async(url4, data4);
if (string.IsNullOrEmpty(html4) || !html4.Contains("\"code\":200"))
html4 = await GetHtml.PostUtf8Async(url4, data4);
if (string.IsNullOrEmpty(html4) || !html4.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单读取失败(买手) " + BaseRegex.GetStringJson(ref html4, "msg"), "Error", 5);
}
List<order_pdd_buyer_order> pddBuyerOrders = new List<order_pdd_buyer_order>();
try
{
pddBuyerOrders = JsonHelper.DeserializeJsonToList<order_pdd_buyer_order>(JObject.Parse(html4)["data"].ParseToString())
.OrderByDescending(p => p.TransitCreateTime).ToList();
return pddBuyerOrders;
}
catch
{
}
return new List<order_pdd_buyer_order>();
}
/// <summary>
/// 读取淘宝买手单
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<order_pdd_buyer_order>> GetTbBuyerOrders(string order_ids)
{
if (string.IsNullOrEmpty(order_ids))
return new List<order_pdd_buyer_order>();
var url4 = BaseClass.Build29WxObjString("order/wx_get_tb_buyer_order_list");
var data4 = UserLogin.GetSignaturex();
data4 += "&wx_order_id_in=" + order_ids;
var html4 = await GetHtml.PostUtf8Async(url4, data4);
if (string.IsNullOrEmpty(html4) || !html4.Contains("\"code\":200"))
html4 = await GetHtml.PostUtf8Async(url4, data4);
if (string.IsNullOrEmpty(html4) || !html4.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单读取失败(买手) " + BaseRegex.GetStringJson(ref html4, "msg"), "Error", 5);
}
List<order_pdd_buyer_order> pddBuyerOrders = new List<order_pdd_buyer_order>();
try
{
pddBuyerOrders = JsonHelper.DeserializeJsonToList<order_pdd_buyer_order>(JObject.Parse(html4)["data"].ParseToString())
.OrderByDescending(p => p.TransitCreateTime).ToList();
return pddBuyerOrders;
}
catch
{
}
return new List<order_pdd_buyer_order>();
}
/// <summary>
/// 读取多多售后
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<order_pdd_buyer_after_sale>> GetPddBuyerAfterSales(string order_ids)
{
var url6 = BaseClass.Build29WxObjString("order/wx_get_buyer_after_sale_list");
var data6 = UserLogin.GetSignaturex();
data6 += "&wx_order_id_in=" + order_ids;
List<order_pdd_buyer_after_sale> pddBuyerAfterSales = new List<order_pdd_buyer_after_sale>();
if (!string.IsNullOrEmpty(order_ids))
{
var html6 = await GetHtml.PostUtf8Async(url6, data6);
if (string.IsNullOrEmpty(html6) || !html6.Contains("\"code\":200"))
html6 = await GetHtml.PostUtf8Async(url6, data6);
if (string.IsNullOrEmpty(html6) || !html6.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单读取失败(买手售后) " + BaseRegex.GetStringJson(ref html6, "msg"), "Error", 6);
return new List<order_pdd_buyer_after_sale>();
}
try
{
pddBuyerAfterSales = JsonHelper.DeserializeJsonToList<order_pdd_buyer_after_sale>(JObject.Parse(html6)["data"].ParseToString()).OrderByDescending(p => p.TransitCreateTime).ToList();
return pddBuyerAfterSales;
}
catch
{
}
}
return new List<order_pdd_buyer_after_sale>();
}
/// <summary>
/// 读取淘宝售后
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<order_pdd_buyer_after_sale>> GetTbBuyerAfterSales(string order_ids)
{
var url6 = BaseClass.Build29WxObjString("order/wx_get_tb_buyer_after_sale_list");
var data6 = UserLogin.GetSignaturex();
data6 += "&wx_order_id_in=" + order_ids;
List<order_pdd_buyer_after_sale> pddBuyerAfterSales = new List<order_pdd_buyer_after_sale>();
if (!string.IsNullOrEmpty(order_ids))
{
var html6 = await GetHtml.PostUtf8Async(url6, data6);
if (string.IsNullOrEmpty(html6) || !html6.Contains("\"code\":200"))
html6 = await GetHtml.PostUtf8Async(url6, data6);
if (string.IsNullOrEmpty(html6) || !html6.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单读取失败(买手售后) " + BaseRegex.GetStringJson(ref html6, "msg"), "Error", 6);
return new List<order_pdd_buyer_after_sale>();
}
try
{
pddBuyerAfterSales = JsonHelper.DeserializeJsonToList<order_pdd_buyer_after_sale>(JObject.Parse(html6)["data"].ParseToString()).OrderByDescending(p => p.TransitCreateTime).ToList();
return pddBuyerAfterSales;
}
catch
{
}
}
return new List<order_pdd_buyer_after_sale>();
}
/// <summary>
/// 读取同步单信息
/// </summary>
/// <param name="buyer_order_ids"></param>
/// <param name="not_upload_pickup_status"></param>
/// <returns></returns>
public static async Task<List<yh_sync_logistics>> GetSyncLogistics(string buyer_order_ids, int? not_upload_pickup_status = null)
{
var url6 = BaseClass.Build29WxObjString("order/wx_get_sync_waybill");
var data6 = UserLogin.GetSignaturex();
data6 += "&order_id=" + buyer_order_ids;
if (not_upload_pickup_status != null)
data6 += "&not_upload_pickup_status=" + not_upload_pickup_status;
List<yh_sync_logistics> pddBuyerAfterSales = new List<yh_sync_logistics>();
if (!string.IsNullOrEmpty(buyer_order_ids))
{
var html6 = await GetHtml.PostUtf8Async(url6, data6);
if (string.IsNullOrEmpty(html6) || !html6.Contains("\"code\":200"))
html6 = await GetHtml.PostUtf8Async(url6, data6);
if (string.IsNullOrEmpty(html6) || !html6.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("订单读取失败(买手售后) " + BaseRegex.GetStringJson(ref html6, "msg"), "Error", 6);
return new List<yh_sync_logistics>();
}
try
{
pddBuyerAfterSales = JsonHelper.DeserializeJsonToList<yh_sync_logistics>(JObject.Parse(html6)["data"].ParseToString()).OrderByDescending(p => p.id).ToList();
return pddBuyerAfterSales;
}
catch (Exception ex)
{
}
}
return new List<yh_sync_logistics>();
}
/// <summary>
/// 读取店铺物流信息
/// </summary>
/// <param name="order_ids"></param>
/// <returns></returns>
public static async Task<List<oms_wei_ewaybill_path>> GetEWaybillPath(string order_ids)
{
List<oms_wei_ewaybill_path> oms_wei_ewaybill_path_list = null;
if (!string.IsNullOrEmpty(order_ids))
{
try
{
var url = BaseClass.Build29WxObjString("order/wx_get_erp_ewaybill_path_latest_list");
var data = UserLogin.GetSignaturex();
data += "&erp_order_id_in=" + order_ids;
var html = await GetHtml.PostUtf8Async(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = await GetHtml.PostUtf8Async(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
{
BaseMsgWindow.ShowAnimateMessage("物流查询失败 " + BaseRegex.GetStringJson(ref html, "msg"), "Error", 6);
}
else
{
oms_wei_ewaybill_path_list = JsonHelper.DeserializeJsonToList<oms_wei_ewaybill_path>(JObject.Parse(html)["data"].ParseToString()).OrderByDescending(p => p.update_time).ToList();
return oms_wei_ewaybill_path_list;
}
}
catch
{
}
}
return new List<oms_wei_ewaybill_path>();
}
}
@@ -1,6 +1,5 @@
using _29WxOrderWpf.BaseWindows; using _29WxOrderWpf.BaseWindows;
using WxOrder.Framework.Commons; using WxOrder.Framework.Commons;
using WxOrder.Framework.Commons;
using _29WxOrderWpf.Ctrls.PDDInvoice; using _29WxOrderWpf.Ctrls.PDDInvoice;
using _29WxOrderWpf.Ctrls.Statistics; using _29WxOrderWpf.Ctrls.Statistics;
using _29WxOrderWpf.Services; using _29WxOrderWpf.Services;
@@ -30,7 +29,7 @@ public partial class OrderListCtrl
{ {
if (_statisticsDialog == null) if (_statisticsDialog == null)
{ {
_statisticsDialog =new ShopRevenueStatisticsView(); _statisticsDialog = new ShopRevenueStatisticsView();
_statisticsDialog.Closed += (s, e) => _statisticsDialog = null; _statisticsDialog.Closed += (s, e) => _statisticsDialog = null;
} }
_statisticsDialog.Show(); _statisticsDialog.Show();
@@ -159,7 +158,7 @@ public partial class OrderListCtrl
if (ret) if (ret)
{ {
sucessCount++; sucessCount++;
this.GetOrder(item.order_id); await this.GetOrder(item.order_id);
SetProgress(index, count); SetProgress(index, count);
item.IsSelect = false; item.IsSelect = false;
} }
@@ -310,7 +309,7 @@ public partial class OrderListCtrl
private void ShowPDDInvoiceDialog() private void ShowPDDInvoiceDialog()
{ {
var view = new PDDInvoiceView(); var view = new PDDInvoiceView();
DialogService.Show(view); DialogService.ShowOrActivateWindow(view);
} }
#endregion #endregion
} }
@@ -269,11 +269,14 @@
Margin="2,0" Margin="2,0"
HorizontalAlignment="Left" HorizontalAlignment="Left"
VerticalAlignment="Center" VerticalAlignment="Center"
d:Opacity="0.5"
d:Visibility="Visible"
BorderBrush="{StaticResource mainColorBrush}" BorderBrush="{StaticResource mainColorBrush}"
Click="chkSyncDirectOrderWaybill_Click" Click="chkSyncDirectOrderWaybill_Click"
Content="同步物流单" Content="同步物流单"
FontSize="12" FontSize="12"
IsChecked="False" /> IsChecked="False"
Visibility="Collapsed" />
</WrapPanel> </WrapPanel>
<wpf:SpacingStackPanel Grid.Column="13" HorizontalSpacing="5"> <wpf:SpacingStackPanel Grid.Column="13" HorizontalSpacing="5">
@@ -688,11 +691,11 @@
</TabItem> </TabItem>
<TabItem <TabItem
MinWidth="60" MinWidth="60"
d:Header="异常需重拍"
Background="Transparent" Background="Transparent"
BorderBrush="Transparent" BorderBrush="Transparent"
Foreground="#FFEE0099" Foreground="#FFEE0099"
d:Header="异常需重拍" Header="{Binding AbnormalTabTxt}"
Header="{Binding AbnormalTabTxt}"
SizeChanged="TabItem_SizeChanged" /> SizeChanged="TabItem_SizeChanged" />
<TabItem <TabItem
MinWidth="60" MinWidth="60"
@@ -875,11 +878,11 @@
</TabItem> </TabItem>
<TabItem <TabItem
MinWidth="60" MinWidth="60"
d:Header="需处理售后单"
Background="#FF6666" Background="#FF6666"
BorderBrush="Transparent" BorderBrush="Transparent"
Foreground="#FF2222" Foreground="#FF2222"
d:Header="需处理售后单" Header="{Binding EmergencyManualReturnOrderTabTxt}"
Header="{Binding EmergencyManualReturnOrderTabTxt}"
SizeChanged="TabItem_SizeChanged"> SizeChanged="TabItem_SizeChanged">
<Border <Border
Margin="4,0,4,4" Margin="4,0,4,4"
@@ -1154,11 +1157,11 @@
</TabItem> </TabItem>
<TabItem <TabItem
MinWidth="60" MinWidth="60"
d:Header="退货仓自动售后单"
Background="Transparent" Background="Transparent"
BorderBrush="Transparent" BorderBrush="Transparent"
Foreground="#FF7744" Foreground="#FF7744"
d:Header="退货仓自动售后单" Header="{Binding EmergencyDistribReturnOrderTabTxt}"
Header="{Binding EmergencyDistribReturnOrderTabTxt}"
SizeChanged="TabItem_SizeChanged"> SizeChanged="TabItem_SizeChanged">
<Border <Border
Margin="4,0,4,4" Margin="4,0,4,4"
@@ -1290,11 +1293,11 @@
</TabItem> </TabItem>
<TabItem <TabItem
MinWidth="60" MinWidth="60"
d:Header="售后完成单"
Background="Transparent" Background="Transparent"
BorderBrush="Transparent" BorderBrush="Transparent"
Foreground="#FFaa77" Foreground="#FFaa77"
d:Header="售后完成单" Header="{Binding RefundTabTxt}"
Header="{Binding RefundTabTxt}"
SizeChanged="TabItem_SizeChanged"> SizeChanged="TabItem_SizeChanged">
<Border <Border
Margin="4,0,4,4" Margin="4,0,4,4"
@@ -1382,10 +1385,10 @@
</TabItem> </TabItem>
<TabItem <TabItem
MinWidth="60" MinWidth="60"
d:Header="全部订单"
Background="Transparent" Background="Transparent"
BorderBrush="Transparent" BorderBrush="Transparent"
d:Header="全部订单" Header="{Binding AllOrderTabTxt}"
Header="{Binding AllOrderTabTxt}"
SizeChanged="TabItem_SizeChanged" /> SizeChanged="TabItem_SizeChanged" />
<!--<TabItem Header="发货异常"> <!--<TabItem Header="发货异常">
<Grid Background="#FFE5E5E5"/> <Grid Background="#FFE5E5E5"/>
@@ -1416,7 +1419,8 @@
CanUserReorderColumns="False" CanUserReorderColumns="False"
ColumnDisplayIndexChanged="dgOrderHeader_ColumnDisplayIndexChanged" ColumnDisplayIndexChanged="dgOrderHeader_ColumnDisplayIndexChanged"
ColumnHeaderHeight="{Binding ElementName=lstTitle, Path=ActualHeight}" ColumnHeaderHeight="{Binding ElementName=lstTitle, Path=ActualHeight}"
LayoutUpdated="dgOrderHeader_LayoutUpdated"> LayoutUpdated="dgOrderHeader_LayoutUpdated"
Sorting="dgOrderHeader_Sorting">
<DataGrid.Columns> <DataGrid.Columns>
<DataGridTextColumn <DataGridTextColumn
Width="38" Width="38"
@@ -1463,9 +1467,20 @@
Header="店铺单号" Header="店铺单号"
HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" /> HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" />
<DataGridTextColumn <DataGridTextColumn
x:Name="dgHeaderTime"
Width="90*" Width="90*"
Header="交易时间" Header="交易时间 ▼"
HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" /> HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}">
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<!-- 设置 Cursor 为 Hand -->
<TextBlock
x:Name="tbHeaderTimeTxt"
Cursor="Hand"
Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.ColumnHeaderTitle}" />
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
<DataGridTextColumn <DataGridTextColumn
Width="65*" Width="65*"
Header="利润" Header="利润"
@@ -1497,11 +1512,14 @@
Grid.Row="4" Grid.Row="4"
Margin="7,0,7,0" Margin="7,0,7,0"
HorizontalContentAlignment="Stretch" HorizontalContentAlignment="Stretch"
AlternationCount="1000000"
BorderThickness="0" BorderThickness="0"
ScrollViewer.CanContentScroll="True" ScrollViewer.CanContentScroll="True"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
VirtualizingPanel.ScrollUnit="Pixel" VirtualizingPanel.ScrollUnit="Pixel"
VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.IsVirtualizing="True"
><!--VirtualizingStackPanel.VirtualizationMode="Recycling"--> VirtualizingStackPanel.VirtualizationMode="Recycling">
<!-- VirtualizingStackPanel.VirtualizationMode="Recycling" -->
<!-- 使用自定义属性模板去除ListBox高亮显示框 --> <!-- 使用自定义属性模板去除ListBox高亮显示框 -->
<ListBox.ItemContainerStyle> <ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem"> <Style TargetType="ListBoxItem">
File diff suppressed because it is too large. Load diff
@@ -43,8 +43,32 @@
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="6" /> <RowDefinition Height="6" />
<RowDefinition Height="auto" /> <RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="6" /> <RowDefinition Height="6" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<local:OrderListRowItemCtrl
Grid.Row="1"
DataContext="{Binding orderItem}"
Visibility="{Binding OrderItemVisibility}" />
<!--<local:OrderListRowItemCtrl
Grid.Row="2"
DataContext="{Binding orderItem2}"
Visibility="{Binding OrderItemVisibility}" />
<local:OrderListRowItemCtrl
Grid.Row="3"
DataContext="{Binding orderItem2}"
Visibility="{Binding OrderItemVisibility}" />
<local:OrderListRowItemCtrl
Grid.Row="4"
DataContext="{Binding orderItem3}"
Visibility="{Binding OrderItemVisibility}" />
<local:OrderListRowItemCtrl
Grid.Row="5"
DataContext="{Binding orderItem4}"
Visibility="{Binding OrderItemVisibility}" />-->
<!--<ItemsControl Grid.Row="1" ItemsSource="{Binding orderItems}"> <!--<ItemsControl Grid.Row="1" ItemsSource="{Binding orderItems}">
<ItemsControl.ItemTemplate> <ItemsControl.ItemTemplate>
<DataTemplate> <DataTemplate>
@@ -52,6 +76,19 @@
</DataTemplate> </DataTemplate>
</ItemsControl.ItemTemplate> </ItemsControl.ItemTemplate>
</ItemsControl>--> </ItemsControl>-->
<!--<ListBox
Grid.Row="1"
ItemsSource="{Binding orderItems}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling">
<ListBox.ItemTemplate>
<DataTemplate>
<local:OrderListRowItemCtrl DataContext="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>-->
<!--<TextBlock Text="{Binding ProductName}" Margin="20,0,0,0"/>--> <!--<TextBlock Text="{Binding ProductName}" Margin="20,0,0,0"/>-->
</Grid> </Grid>
</Border> </Border>
@@ -41,22 +41,22 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
private async void OrderListRowCtrl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) private async void OrderListRowCtrl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{ {
await Task.Run(() => { Thread.Sleep(1); }); //await Task.Run(() => { Thread.Sleep(1); });
if (this.DataContext is oms_wei_order_info order && this.IsArrangeValid) //if (this.DataContext is oms_wei_order_info order)
{ //{
int index = 0; // int index = 0;
foreach (var orderItem in order.orderItems) // foreach (var orderItem in order.orderItems)
{ // {
gridChildOrder.RowDefinitions.Insert(gridChildOrder.RowDefinitions.Count - 1, new RowDefinition() { Height = GridLength.Auto }); // gridChildOrder.RowDefinitions.Insert(gridChildOrder.RowDefinitions.Count - 1, new RowDefinition() { Height = GridLength.Auto });
index++; // index++;
var rowItem = new OrderListRowItemCtrl() { DataContext = orderItem, Name = "rowItem" + index }; // var rowItem = new OrderListRowItemCtrl() { DataContext = orderItem, Name = "rowItem" + index };
Grid.SetRow(rowItem, index); // Grid.SetRow(rowItem, index);
this.gridChildOrder.Children.Add(rowItem); // this.gridChildOrder.Children.Add(rowItem);
if (index >= 5) // if (index >= 5)
break; // break;
} // }
} //}
} }
private void CheckBox_Click(object sender, RoutedEventArgs e) private void CheckBox_Click(object sender, RoutedEventArgs e)
@@ -7,7 +7,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:uc="clr-namespace:_29WxOrderWpf.UserControls" xmlns:uc="clr-namespace:_29WxOrderWpf.UserControls"
d:DesignHeight="50" d:DesignHeight="50"
d:DesignWidth="800" d:DesignWidth="850"
mc:Ignorable="d"> mc:Ignorable="d">
<Border Background="{StaticResource ListRowBorderColorBrush}" CornerRadius="12,12,0,0"> <Border Background="{StaticResource ListRowBorderColorBrush}" CornerRadius="12,12,0,0">
@@ -26,6 +26,7 @@
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="20" /> <ColumnDefinition Width="20" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<TextBox <TextBox
@@ -39,7 +40,7 @@
Foreground="{Binding OrderBuyTypeColor}" Foreground="{Binding OrderBuyTypeColor}"
IsReadOnly="True" IsReadOnly="True"
Text="{Binding OrderBuyType}" Text="{Binding OrderBuyType}"
Visibility="{Binding OrderBuyType, Converter={StaticResource HasTextVisibility}}" /> Visibility="{Binding OrderBuyTypeVisibility}" />
<TextBox <TextBox
Grid.Column="1" Grid.Column="1"
Margin="8,8,-4,8" Margin="8,8,-4,8"
@@ -158,7 +159,7 @@
BorderThickness="0" BorderThickness="0"
FontSize="7" FontSize="7"
FontWeight="Bold" FontWeight="Bold"
Foreground="{Binding Shop.LoginStatusStr, Converter={StaticResource statusToColorBrushConverter}}" Foreground="{Binding Shop.LoginStatusStrColor}"
IsReadOnly="True" IsReadOnly="True"
Text="{Binding Shop.LoginStatusStr}" Text="{Binding Shop.LoginStatusStr}"
WaterMark="店铺状态" /> WaterMark="店铺状态" />
@@ -167,6 +168,7 @@
Grid.Column="6" Grid.Column="6"
Margin="4,8,4,8" Margin="4,8,4,8"
VerticalAlignment="Center" VerticalAlignment="Center"
d:Text="店铺名称"
Background="Transparent" Background="Transparent"
BorderThickness="0" BorderThickness="0"
Cursor="Hand" Cursor="Hand"
@@ -205,13 +207,27 @@
Background="Transparent" Background="Transparent"
BorderThickness="0" BorderThickness="0"
FontSize="14" FontSize="14"
Foreground="Gray" Foreground="#FF8888"
IsReadOnly="True" IsReadOnly="True"
Text="{Binding OrderDiffItemCountStr}"
WaterMark="该订单共有 1 条不同商品记录" /> WaterMark="该订单共有 1 条不同商品记录" />
<TextBlock <TextBlock
Grid.Column="11" Grid.Column="11"
Margin="10" Margin="0,0,8,0"
HorizontalAlignment="Right"
Cursor="Hand"
FontSize="20"
FontWeight="Bold"
Foreground="{StaticResource mainColorBrush}"
MouseLeftButtonUp="TextBlock_MouseLeftButtonUp"
Style="{StaticResource TextBlockIcon}"
Text="{StaticResource txt-arrow_sync}"
ToolTip="刷新订单状态" />
<!-- Foreground="{Binding ElementName=b_gift, Path=BorderBrush}" -->
<TextBlock
Grid.Column="12"
Margin="0,0,8,0"
VerticalAlignment="Center" VerticalAlignment="Center"
d:Text="仅退款/退货退款" d:Text="仅退款/退货退款"
Foreground="Gray" Foreground="Gray"
@@ -219,9 +235,8 @@
<Border <Border
x:Name="borderFlag" x:Name="borderFlag"
Grid.Column="12" Grid.Column="13"
Width="auto" Width="auto"
Height="15"
Margin="2" Margin="2"
VerticalAlignment="Center" VerticalAlignment="Center"
Background="Transparent" Background="Transparent"
@@ -229,12 +244,19 @@
MouseLeftButtonDown="borderFlag_MouseLeftButtonDown"> MouseLeftButtonDown="borderFlag_MouseLeftButtonDown">
<!--<Path Margin="0,0,0,0" Fill="{StaticResource FlagGrayBrush}" Data="M 0,0 L 1,0 L 1,1 L 10,1 L 7,4 L 10,7 L 1,7 L 1,12 L 0,12 Z" Stretch="Uniform" />--> <!--<Path Margin="0,0,0,0" Fill="{StaticResource FlagGrayBrush}" Data="M 0,0 L 1,0 L 1,1 L 10,1 L 7,4 L 10,7 L 1,7 L 1,12 L 0,12 Z" Stretch="Uniform" />-->
<WrapPanel VerticalAlignment="Center"> <WrapPanel VerticalAlignment="Center">
<Button
Width="60"
Height="22"
Margin="0,0,10,0"
Click="btn_createOrderSupportTicket"
Content="创建工单"
Style="{StaticResource BasePageButtonStyle}" />
<TextBlock <TextBlock
VerticalAlignment="Center" VerticalAlignment="Center"
FontSize="12" FontSize="12"
Foreground="Gray" Foreground="Gray"
Text="隐藏标记" /> Text="隐藏标记" />
<Path <Path
Width="15" Width="15"
Height="15" Height="15"
Margin="2,0,0,0" Margin="2,0,0,0"
@@ -242,9 +264,9 @@
Data="M 0,0 L 1,0 L 1,1 L 10,1 L 7,4 L 10,7 L 1,7 L 1,12 L 0,12 Z" Data="M 0,0 L 1,0 L 1,1 L 10,1 L 7,4 L 10,7 L 1,7 L 1,12 L 0,12 Z"
Fill="{Binding ColourFlagBrush}" Fill="{Binding ColourFlagBrush}"
Stretch="Uniform" /> Stretch="Uniform" />
<!--ColourFlagBrush--> <!-- ColourFlagBrush -->
<!--Fill="{Binding colour_flag, Converter={StaticResource flagColorConverter}}"--> <!-- Fill="{Binding colour_flag, Converter={StaticResource flagColorConverter}}" -->
</WrapPanel> </WrapPanel>
</Border> </Border>
@@ -3,6 +3,7 @@ using AllBase;
using AllBase.Helper; using AllBase.Helper;
using AllBase.Model.DBModel; using AllBase.Model.DBModel;
using NaiBa.Util.Extension; using NaiBa.Util.Extension;
using OrderSupportTicket.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -25,43 +26,45 @@ using Work._29Tools.Forms.ShopForms;
namespace _29WxOrderWpf.Ctrls.OrderCtrls namespace _29WxOrderWpf.Ctrls.OrderCtrls
{ {
/// <summary> /// <summary>
/// OrderListRowHeaderCtrl.xaml 的交互逻辑 /// OrderListRowHeaderCtrl.xaml 的交互逻辑
/// </summary> /// </summary>
public partial class OrderListRowHeaderCtrl : UserControl public partial class OrderListRowHeaderCtrl : UserControl
{ {
public OrderListRowHeaderCtrl() public static DateTime LastRefreshTime = DateTime.Now.AddSeconds(-5);
{
InitializeComponent();
this.DataContextChanged += OrderListRowHeaderCtrl_DataContextChanged;
txtOrderId.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtOrderId_MouseLeftButtonUp), true);
txtShopName.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtShopName_MouseLeftButtonUp), true);
}
private void txtShopName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) public OrderListRowHeaderCtrl()
{ {
if (this.DataContext is oms_wei_order_info order) InitializeComponent();
{ this.DataContextChanged += OrderListRowHeaderCtrl_DataContextChanged;
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == order.shop_id.ParseToString()); txtOrderId.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtOrderId_MouseLeftButtonUp), true);
if (shop != null) txtShopName.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtShopName_MouseLeftButtonUp), true);
{ }
WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop);
ShopBLL.CheckShopLogin(shop);
if (shop.LoginStatus == "登录成功")
{
// 在线直接进店
shopLoginForm.openType = EnumOpenType.manage;
shopLoginForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
shopLoginForm.InitUrl = "https://store.weixin.qq.com/shop/home";
shopLoginForm.Show();
}
else
{
// 掉线登录
shopLoginForm.openType = EnumOpenType.login;
shopLoginForm.ShowDialog();
if (shop.LoginStatus == "登录成功") private void txtShopName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (this.DataContext is oms_wei_order_info order)
{
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == order.shop_id.ParseToString());
if (shop != null)
{
WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop);
ShopBLL.CheckShopLogin(shop);
if (shop.LoginStatus == "登录成功")
{
// 在线直接进店
shopLoginForm.openType = EnumOpenType.manage;
shopLoginForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
shopLoginForm.InitUrl = "https://store.weixin.qq.com/shop/home";
shopLoginForm.Show();
}
else
{
// 掉线登录
shopLoginForm.openType = EnumOpenType.login;
shopLoginForm.ShowDialog();
if (shop.LoginStatus == "登录成功")
{ {
shop.Is29Supplier = false; shop.Is29Supplier = false;
for (int i = 0; i < 100; i++) for (int i = 0; i < 100; i++)
@@ -83,86 +86,86 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
break; break;
} }
foreach (var ord in GlobalConfig.lstFilterOrder.Where(o => o.shop_id.ParseToString() == shop.ErpShopId).ToList()) foreach (var ord in GlobalConfig.lstFilterOrder.Where(o => o.shop_id.ParseToString() == shop.ErpShopId).ToList())
{ {
// 更新代发管理情况 // 更新代发管理情况
foreach (var orderItem in ord.orderItems) foreach (var orderItem in ord.orderItems)
Dispatcher.Invoke(new Action(() => { orderItem.UpdateOrderItemBuyButton(); })); Dispatcher.Invoke(new Action(() => { orderItem.UpdateOrderItemBuyButton(); }));
} }
} }
} }
} }
} }
} }
private void txtOrderId_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) private void txtOrderId_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{ {
if (this.DataContext is oms_wei_order_info order) if (this.DataContext is oms_wei_order_info order)
{ {
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == order.shop_id.ParseToString()); var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == order.shop_id.ParseToString());
if (shop != null) if (shop != null)
{ {
WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop); WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop);
shopLoginForm.openType = EnumOpenType.manage; shopLoginForm.openType = EnumOpenType.manage;
shopLoginForm.WindowState = System.Windows.Forms.FormWindowState.Maximized; shopLoginForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
{ {
shopLoginForm.InitUrl = "https://store.weixin.qq.com/shop/order/detail?orderid=" + order.order_id; shopLoginForm.InitUrl = "https://store.weixin.qq.com/shop/order/detail?orderid=" + order.order_id;
} }
shopLoginForm.Show(); shopLoginForm.Show();
} }
} }
} }
private void OrderListRowHeaderCtrl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) private void OrderListRowHeaderCtrl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{ {
if (this.DataContext is oms_wei_order_info order) if (this.DataContext is oms_wei_order_info order)
{ {
if (order.orderItems.Count > 5) if (order.orderItems.Count > 5)
{ {
txtCount.Text = "该订单共计 " + order.orderItems.Count + " 件商品"; //txtCount.Text = "该订单共计 " + order.orderItems.Count + " 件商品";
} }
} }
} }
private void Path_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) private void Path_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{ {
//var orderId = ((sender as Border)?.Tag).ParseToString(); //var orderId = ((sender as Border)?.Tag).ParseToString();
if (this.DataContext is oms_wei_order_info order) if (this.DataContext is oms_wei_order_info order)
{ {
try try
{ {
//Clipboard.SetText(order.order_id); // 复制成功,但会报错,改为SetDataObject //Clipboard.SetText(order.order_id); // 复制成功,但会报错,改为SetDataObject
Clipboard.SetDataObject(order.order_id); Clipboard.SetDataObject(order.order_id);
BaseMsgWindow.ShowAnimateMessage("复制成功"); BaseMsgWindow.ShowAnimateMessage("复制成功");
} }
catch (Exception ex) catch (Exception ex)
{ {
BaseMsgWindow.ShowError("复制失败 " + ex.Message); BaseMsgWindow.ShowError("复制失败 " + ex.Message);
} }
} }
} }
private void pathShop_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) private void pathShop_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{ {
if (this.DataContext is oms_wei_order_info order) if (this.DataContext is oms_wei_order_info order)
{ {
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == order.shop_id.ParseToString()); var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == order.shop_id.ParseToString());
if (shop != null) if (shop != null)
{ {
try try
{ {
Clipboard.SetDataObject(shop.ShopAccount); Clipboard.SetDataObject(shop.ShopAccount);
BaseMsgWindow.ShowAnimateMessage("复制成功"); BaseMsgWindow.ShowAnimateMessage("复制成功");
} }
catch (Exception ex) catch (Exception ex)
{ {
BaseMsgWindow.ShowError("复制失败 " + ex.Message); BaseMsgWindow.ShowError("复制失败 " + ex.Message);
} }
} }
} }
} }
private void borderFlag_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) private void borderFlag_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{ {
@@ -199,5 +202,55 @@ namespace _29WxOrderWpf.Ctrls.OrderCtrls
}); });
} }
} }
} /// <summary>
/// 创建工单
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btn_createOrderSupportTicket(object sender, RoutedEventArgs e)
{
if (!(this.DataContext is oms_wei_order_info order))
return;
var shop = order.Shop
?? GlobalConfig.ShopLoginList.FirstOrDefault(
s => s.ErpShopId == order.shop_id.ParseToString());
var appId = shop?.ShopId?.Trim();
if (string.IsNullOrWhiteSpace(appId)
|| string.IsNullOrWhiteSpace(order.order_id))
{
BaseMsgWindow.ShowAnimateMessage(
"订单缺少店铺 APPID 或订单号,无法创建工单",
"Error",
5);
return;
}
var ticketOrder = TicketOrderOption.FromWechatOrder(order, appId);
try
{
await MainWindow.Instance.CreateOrderSupportTicketAsync(ticketOrder);
}
catch (Exception ex)
{
BaseMsgWindow.ShowError("打开工单窗口失败:" + ex.Message);
}
}
private async void TextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (!(this.DataContext is oms_wei_order_info order))
return;
if (LastRefreshTime > DateTime.Now.AddSeconds(-5))
{
BaseMsgWindow.ShowAnimateMessage("操作太快了请稍候再点击", "Error", 5);
return;
}
LastRefreshTime = DateTime.Now;
await Task.Run(async () => { await MainWindow.Instance.orderListCtrl.GetOrder(order.order_id); });
}
}
} }
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,85 @@
<UserControl
x:Class="_29WxOrderWpf.Ctrls.OrderCtrls.OrderTransitListCtrl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
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="WPFCommon"
d:DesignHeight="450"
d:DesignWidth="800"
Background="White"
Foreground="DimGray"
Loaded="OrderTransitListCtrl_Loaded"
mc:Ignorable="d">
<UserControl.Resources>
<Style BasedOn="{StaticResource TitleContentBaseStyle}" TargetType="wpf:TitleContent">
<Setter Property="Placement" Value="Left" />
<Setter Property="TitleVerticalAlignment" Value="Center" />
<Setter Property="LeftTitlePadding" Value="0,0,0,0" />
</Style>
<Style TargetType="wpf:SpacingStackPanel">
<Setter Property="Margin" Value="3,0" />
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Height="30" Orientation="Horizontal">
<TextBlock
Margin="10,0,0,0"
VerticalAlignment="Center"
Text="店铺:" />
<TextBox
VerticalContentAlignment="Center"
d:Text="音诉云仓"
Background="Transparent"
BorderThickness="0"
Foreground="DimGray"
IsReadOnly="True"
Text="{Binding ShopNameStr}" />
<TextBlock
Margin="10,0,0,0"
VerticalAlignment="Center"
Text="订单号:" />
<TextBox
VerticalContentAlignment="Center"
d:Text="3700000000000000"
Background="Transparent"
BorderThickness="0"
Foreground="DimGray"
IsReadOnly="True"
Text="{Binding OrderIdStr}" />
</StackPanel>
<ListBox
x:Name="lbxTransitList"
Grid.Row="4"
Margin="7,0,7,0"
HorizontalContentAlignment="Stretch"
BorderThickness="0">
<!-- 使用自定义属性模板去除ListBox高亮显示框 -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter
Content="{TemplateBinding Content}"
ContentStringFormat="{TemplateBinding ContentStringFormat}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<!-- 此处绑定将数据源传递给子自定义控件 -->
<local:OrderTransitListDetailCtrl DataContext="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
@@ -0,0 +1,64 @@
using AllBase.Model.DBModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace _29WxOrderWpf.Ctrls.OrderCtrls;
/// <summary>
/// OrderTransitListCtrl.xaml 的交互逻辑
/// </summary>
public partial class OrderTransitListCtrl : UserControl
{
OrderTransitListCtrlViewModel ViewModel;
public OrderTransitListCtrl(oms_wei_order_item_transit_model transitInfo)
{
InitializeComponent();
UpdateViewModel(transitInfo);
}
public void UpdateViewModel(oms_wei_order_item_transit_model transitInfo)
{
ViewModel = new OrderTransitListCtrlViewModel(transitInfo);
ViewModel.RequestClose += ViewModel_RequestClose;
DataContext = ViewModel;
this.lbxTransitList.ItemsSource = ViewModel.TransitInfo.OrderItemTransitDetailList;
}
private void ViewModel_RequestClose()
{
Window parentWindow = Window.GetWindow(this);
if (this.IsLoaded && parentWindow != null)
parentWindow.Close();
}
private void OrderTransitListCtrl_Loaded(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
if (parentWindow != null)
{
parentWindow.Closed += ChangeWaybillView_Closed;
}
ViewModel.Start();
}
private void ChangeWaybillView_Closed(object sender, EventArgs e)
{
ViewModel.Stop();
}
}
@@ -0,0 +1,62 @@
using AllBase.Model.DBModel;
using AllBase.Model.MvvmBaseClasses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _29WxOrderWpf.Ctrls.OrderCtrls;
public class OrderTransitListCtrlViewModel : PropertyNotifyObject
{
private volatile bool _isWindowLoaded = false;
public oms_wei_order_item_transit_model TransitInfo
{
get { return this.GetValue(x => x.TransitInfo); }
set { this.SetValue(x => x.TransitInfo, value); }
}
public oms_wei_order_item_info OrderItem
{
get { return this.GetValue(x => x.OrderItem); }
set { this.SetValue(x => x.OrderItem, value); }
}
public string OrderIdStr
{
get { return this.GetValue(x => x.OrderIdStr); }
set { this.SetValue(x => x.OrderIdStr, value); }
}
public string ShopNameStr
{
get { return this.GetValue(x => x.ShopNameStr); }
set { this.SetValue(x => x.ShopNameStr, value); }
}
/// <summary>请求关闭窗口</summary>
public event Action RequestClose;
public OrderTransitListCtrlViewModel(oms_wei_order_item_transit_model transitInfo)
{
TransitInfo = transitInfo;
OrderItem = transitInfo?.OrderItem;
OrderIdStr = OrderItem?.order_id;
ShopNameStr = OrderItem?.ItemOrder?.Shop?.ShopAccount;
}
/// <summary>
/// 窗口加载完成时调用
/// </summary>
public void Start()
{
_isWindowLoaded = true;
}
/// <summary>
/// 窗口关闭时调用,停止后台任务
/// </summary>
public void Stop()
{
_isWindowLoaded = false;
}
}
@@ -0,0 +1,411 @@
<UserControl
x:Class="_29WxOrderWpf.Ctrls.OrderCtrls.OrderTransitListDetailCtrl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
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="WPFCommon"
d:DesignHeight="280"
d:DesignWidth="1200"
Background="White"
mc:Ignorable="d">
<UserControl.Resources>
<Style BasedOn="{StaticResource TitleContentBaseStyle}" TargetType="wpf:TitleContent">
<Setter Property="Placement" Value="Left" />
<Setter Property="TitleVerticalAlignment" Value="Center" />
<Setter Property="LeftTitlePadding" Value="0,0,0,0" />
</Style>
<Style TargetType="wpf:SpacingStackPanel">
<Setter Property="Margin" Value="3,0" />
</Style>
</UserControl.Resources>
<Border
MinHeight="50"
Margin="5"
BorderBrush="#8087CEEB"
BorderThickness="1"
CornerRadius="10">
<Grid Opacity="{Binding Opacity}">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Background="#5087CEEB" CornerRadius="8,8,0,0">
<StackPanel MinHeight="30" Orientation="Horizontal">
<TextBlock
Margin="10,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="仓库订单号" />
<TextBox
VerticalContentAlignment="Center"
d:Text="261008-123456789012345"
Background="Transparent"
BorderThickness="0"
Foreground="DimGray"
IsReadOnly="True"
Text="{Binding OrderCode}" />
<TextBlock
Margin="10,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
d:Text="发货包裹"
FontWeight="Bold"
Foreground="{Binding TransitTypeStrColor}"
Text="{Binding TransitTypeStr}" />
<TextBox
VerticalContentAlignment="Center"
d:Text="ABCDEF1"
Background="Transparent"
BorderThickness="0"
Foreground="DimGray"
IsReadOnly="True"
Text="{Binding SourceCode}" />
</StackPanel>
</Border>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<Border
Margin="0,10"
BorderBrush="LightSkyBlue"
BorderThickness="0,0,1,0">
<wpf:SpacingStackPanel
Margin="10,10"
VerticalAlignment="Center"
Orientation="Vertical"
VerticalSpacing="4">
<wpf:TitleContent Title="交易单号:" Foreground="#FF666666">
<TextBox
d:Text="371234567890123456"
Background="Transparent"
BorderThickness="0"
Foreground="#FF888888"
IsReadOnly="True"
Text="{Binding WxOrderId}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="采购账户:" Foreground="#FF666666">
<WrapPanel>
<TextBox
x:Name="txtOutOrderBuyer"
d:Text="张三"
Background="Transparent"
BorderThickness="0"
Cursor="Hand"
Foreground="#AA0000FF"
IsReadOnly="True"
Tag="{Binding OutBuyerId}"
Text="{Binding OutBuyerName}"
TextWrapping="Wrap" />
<Border
x:Name="borderTransitBuyerRefundStatus"
Height="auto"
MinWidth="30"
Margin="2,0,0,0"
HorizontalAlignment="Center"
d:Background="{StaticResource PageOkBrush}"
d:BorderBrush="{StaticResource PageOkBrush}"
Background="{Binding TransitDetailRefundStatusBackColor}"
BorderBrush="{Binding TransitDetailRefundStatusBackColor}"
BorderThickness="1"
CornerRadius="2"
Visibility="{Binding TransitDetailRefundStatusStrVisibility}">
<TextBlock
x:Name="txtRefundStatus"
MinWidth="20"
Padding="0"
VerticalAlignment="Center"
d:Text="退货成功"
Background="Transparent"
Foreground="White"
Text="{Binding TransitDetailRefundStatusStr}" />
</Border>
</WrapPanel>
</wpf:TitleContent>
<wpf:TitleContent Title="采购单号:" Foreground="#FF666666">
<TextBox
x:Name="txtOutOrderId"
d:Text="261008-1234567890123456"
Background="Transparent"
BorderThickness="0"
Cursor="Hand"
Foreground="#AA0000FF"
IsReadOnly="True"
Text="{Binding OutOrderId}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="下单时间:" Foreground="#FF666666">
<TextBox
d:Text="26-10-07 10:33:33"
Background="Transparent"
BorderThickness="0"
Foreground="#FF888888"
IsReadOnly="True"
Text="{Binding WxOrderCreateTimeStr}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="添加时间:" Foreground="#FF666666">
<TextBox
d:Text="26-10-07 18:33:33"
Background="Transparent"
BorderThickness="0"
Foreground="#FF888888"
IsReadOnly="True"
Text="{Binding TransitAddTimeStr}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="创建时间:" Foreground="#FF666666">
<TextBox
d:Text="26-10-08 00:33:33"
Background="Transparent"
BorderThickness="0"
Foreground="#FF888888"
IsReadOnly="True"
Text="{Binding CreateTimeStr}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<!--<wpf:TitleContent Title="店铺名称:">
<TextBox
d:Text="芥麦亚"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding ShopName}"
TextWrapping="Wrap" />
</wpf:TitleContent>-->
</wpf:SpacingStackPanel>
</Border>
<Border
Grid.Column="1"
Margin="0,10"
BorderBrush="LightSkyBlue"
BorderThickness="0,0,1,0"
Opacity="0.5">
<wpf:SpacingStackPanel
Margin="10,10"
VerticalAlignment="Center"
Orientation="Vertical"
VerticalSpacing="4">
<wpf:TitleContent
Title="{Binding WarehouseName}"
d:Title="上海仓"
FontWeight="Bold">
<WrapPanel>
<TextBox
d:Text="已出仓"
Background="Transparent"
BorderThickness="0"
FontWeight="Normal"
IsReadOnly="True"
Text="{Binding WarehouseStatus}"
TextWrapping="Wrap" />
</WrapPanel>
</wpf:TitleContent>
<wpf:TitleContent Title="入库单号:">
<TextBox
d:Text="JTSD-JT12345678901122"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding UpperWaybill}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="出库单号:">
<TextBox
d:Text="YD-3111111555555123"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding DownWaybill}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="货架号:">
<TextBox
d:Text="EB3021"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding ShelfCodeStr}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="货架记录时间:">
<TextBox
d:Text="26-10-08 00:33:33"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding ShelfTimeStr}"
TextWrapping="Wrap" />
</wpf:TitleContent>
</wpf:SpacingStackPanel>
</Border>
<Border
Grid.Column="2"
Margin="0,10"
BorderBrush="LightSkyBlue"
BorderThickness="0,0,1,0"
Opacity="0.5">
<wpf:SpacingStackPanel
Margin="10,10"
VerticalAlignment="Center"
Orientation="Vertical"
VerticalSpacing="4">
<wpf:TitleContent Title="作废状态:" FontWeight="Bold">
<TextBox
d:Text="已作废"
Background="Transparent"
BorderThickness="0"
FontWeight="Normal"
IsReadOnly="True"
Text="{Binding TransitVoidStatus}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="拒收状态:" FontWeight="Bold">
<TextBox
d:Text="拒收失败"
Background="Transparent"
BorderThickness="0"
FontWeight="Normal"
IsReadOnly="True"
Text="{Binding TransitRejectStatus}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="拦截状态:" FontWeight="Bold">
<TextBox
d:Text="已拦截"
Background="Transparent"
BorderThickness="0"
FontWeight="Normal"
IsReadOnly="True"
Text="{Binding TransitReturnStatus}"
TextWrapping="Wrap" />
</wpf:TitleContent>
</wpf:SpacingStackPanel>
</Border>
<Border
Grid.Column="3"
Margin="0,10"
BorderBrush="LightSkyBlue"
BorderThickness="0,0,1,0"
Opacity="0.5">
<wpf:SpacingStackPanel
Margin="10,10"
VerticalAlignment="Center"
Orientation="Vertical"
VerticalSpacing="4">
<wpf:TitleContent Title="到仓时间:">
<TextBox
d:Text="26-10-07 10:33:33"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding InboundTimeStr}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="取号时间:">
<TextBox
d:Text="26-10-08 00:33:33"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding PickUpTimeStr}"
TextWrapping="Wrap" />
</wpf:TitleContent>
<wpf:TitleContent Title="出仓时间:">
<TextBox
d:Text="26-10-07 10:33:33"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Text="{Binding OutboundTimeStr}"
TextWrapping="Wrap" />
</wpf:TitleContent>
</wpf:SpacingStackPanel>
</Border>
<Border Grid.Column="4">
<wpf:SpacingStackPanel
Grid.Column="8"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Vertical"
VerticalSpacing="5">
<Button
x:Name="btnVoidPackage"
MinWidth="38"
MinHeight="20"
Margin="0,0,0,0"
Padding="2"
HorizontalAlignment="Center"
d:Visibility="Visible"
Click="btnVoidPackage_Click"
Style="{StaticResource BasePageButtonLightStyle}"
Visibility="{Binding VoidPackageBtnVisibility}">
作废包裹
</Button>
<Button
x:Name="btnAddEditTransitWarehouseReject_New"
MinWidth="38"
MinHeight="20"
Margin="0,0,0,0"
Padding="2"
HorizontalAlignment="Center"
d:Visibility="Visible"
Click="btnAddEditTransitWarehouseReject_Click"
Style="{StaticResource BasePageButtonLightStyle}"
Visibility="{Binding RejectPackageBtnVisibility}">
<!--<TextBlock>
云仓拒收<LineBreak />
退回总店</TextBlock>-->
云仓拒收退回总店
</Button>
<Button
x:Name="btnAddEditTransitWarehouseAfterSale_n1"
MinWidth="38"
MinHeight="20"
Margin="0,0,0,0"
Padding="2"
Click="btnAddEditTransitWarehouseAfterSale_Click"
Style="{StaticResource BasePageButtonLightStyle}"
Visibility="{Binding ReturnPackageBtnVisibility}">
拒收失败转寄总店
</Button>
<Button
x:Name="btnAddEditTransitWarehouseAfterSale_n2"
MinWidth="38"
MinHeight="20"
Margin="0,0,0,0"
Padding="2"
Click="btnAddEditTransitWarehouseAfterSale_Click"
Style="{StaticResource BasePageButtonLightStyle}"
Visibility="{Binding InterceptPackageBtnVisibility}">
出库拦截退回仓库
</Button>
<Button
x:Name="btnTransitExtraPackages"
Height="20"
MinWidth="38"
Margin="0,0,0,0"
Padding="2"
HorizontalAlignment="Center"
d:Visibility="Visible"
Click="btnTransitExtraPackages_Click"
Content="滞留补发买家"
FontSize="11"
Style="{StaticResource BasePageButtonLightStyle}"
Visibility="{Binding ExtraPackagesBtnVisibility}" />
</wpf:SpacingStackPanel>
</Border>
</Grid>
</Grid>
</Border>
</UserControl>
@@ -0,0 +1,246 @@
using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.Views;
using AllBase;
using AllBase.Helper;
using AllBase.Model.DBModel;
using NaiBa.Util.Extension;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 Work;
using Work._29Tools.BLL;
using WxOrder.Framework.Commons;
namespace _29WxOrderWpf.Ctrls.OrderCtrls;
/// <summary>
/// OrderTransitListDetailCtrl.xaml 的交互逻辑
/// </summary>
public partial class OrderTransitListDetailCtrl : UserControl
{
public OrderTransitListDetailCtrl()
{
InitializeComponent();
this.txtOutOrderId.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtOutOrderId_MouseLeftButtonUp), true);
this.txtOutOrderBuyer.AddHandler(TextBox.MouseUpEvent, new MouseButtonEventHandler(txtOutOrderId_MouseLeftButtonUp), true);
}
/// <summary> 作废包裹 </summary>
private async void btnVoidPackage_Click(object sender, RoutedEventArgs e)
{
if (this.DataContext is oms_wei_order_item_transit_detail_info transitDetailInfo)
{
btnVoidPackage.IsEnabled = false;
var orderItem = transitDetailInfo.oms_wei_order_item_info;
var transitOrder = transitDetailInfo.oms_wei_external_procurement_log_info;
var returnOrder = transitDetailInfo.oms_wei_external_procurement_after_sale_info;
var extOrder = transitDetailInfo.oms_wei_transfer_extra_package;
// 作废发货包裹
if (transitOrder != null)
{
transitOrder = orderItem.ItemTransitOrders.FirstOrDefault(t => t.order_code == transitOrder.order_code) ?? transitOrder;
await OrderTransitService.VoidOrder(orderItem, transitOrder);
}
// 作废退货包裹
else if (returnOrder != null)
{
try
{
var voidResult = await OrderTransitService.VoidAfterSalePackage(orderItem, returnOrder);
if (!string.IsNullOrEmpty(voidResult))
BaseMsgWindow.ShowInfo(voidResult);
}
catch (Exception ex)
{
BaseMsgWindow.ShowError(ex.Message);
}
}
// 作废额外包裹
else if (extOrder != null)
{
try
{
var voidResult = await OrderTransitService.VoidExtraPackage(orderItem, extOrder);
if (!string.IsNullOrEmpty(voidResult))
BaseMsgWindow.ShowInfo(voidResult);
}
catch (Exception ex)
{
BaseMsgWindow.ShowError(ex.Message);
}
}
RefreshListCtrl(orderItem);
btnVoidPackage.IsEnabled = true;
}
}
/// <summary> 拒收包裹 </summary>
private async void btnAddEditTransitWarehouseReject_Click(object sender, RoutedEventArgs e)
{
if (this.DataContext is oms_wei_order_item_transit_detail_info transitDetailInfo)
{
btnAddEditTransitWarehouseReject_New.IsEnabled = false;
var orderItem = transitDetailInfo.oms_wei_order_item_info;
var transitOrder = transitDetailInfo.oms_wei_external_procurement_log_info;
var returnOrder = transitDetailInfo.oms_wei_external_procurement_after_sale_info;
var extOrder = transitDetailInfo.oms_wei_transfer_extra_package;
// 拒收发货包裹
if (transitOrder != null)
{
try
{
var rejectRst = await OrderTransitService.RejectTransitOrder(orderItem, transitOrder);
if (!string.IsNullOrEmpty(rejectRst))
BaseMsgWindow.ShowInfo(rejectRst);
}
catch (Exception ex)
{
BaseMsgWindow.ShowError(ex.Message);
}
}
// 拒收额外包裹(额外包裹暂不支持多件商品发货,故暂不存在拒收功能)
else if (extOrder != null)
{
}
RefreshListCtrl(orderItem);
btnAddEditTransitWarehouseReject_New.IsEnabled = true;
}
}
private void btnAddEditTransitWarehouseAfterSale_Click(object sender, RoutedEventArgs e)
{
if (this.DataContext is oms_wei_order_item_transit_detail_info transitDetailInfo)
{
btnAddEditTransitWarehouseAfterSale_n1.IsEnabled = false;
btnAddEditTransitWarehouseAfterSale_n2.IsEnabled = false;
var orderItem = transitDetailInfo.oms_wei_order_item_info;
var transitOrder = transitDetailInfo.oms_wei_external_procurement_log_info;
var returnOrder = transitDetailInfo.oms_wei_external_procurement_after_sale_info;
var extOrder = transitDetailInfo.oms_wei_transfer_extra_package;
if (transitOrder != null)
{
bool isOutWarehouse = sender == btnAddEditTransitWarehouseAfterSale_n2;
OrderListRowItemCtrl.ShowReturnPackageWindow(orderItem, transitDetailInfo, isOutWarehouse);
}
else if (extOrder != null)
{
bool isOutWarehouse = sender == btnAddEditTransitWarehouseAfterSale_n2;
OrderListRowItemCtrl.ShowReturnPackageWindow(orderItem, transitDetailInfo, isOutWarehouse);
}
RefreshListCtrl(orderItem);
btnAddEditTransitWarehouseAfterSale_n1.IsEnabled = true;
btnAddEditTransitWarehouseAfterSale_n2.IsEnabled = true;
}
}
private void btnTransitExtraPackages_Click(object sender, RoutedEventArgs e)
{
// 滞留补发买家(补发包裹)
if (this.DataContext is oms_wei_order_item_transit_detail_info transitDetailInfo)
{
var orderItem = transitDetailInfo.oms_wei_order_item_info;
var transitOrder = transitDetailInfo.oms_wei_external_procurement_log_info;
var returnOrder = transitDetailInfo.oms_wei_external_procurement_after_sale_info;
var extOrder = transitDetailInfo.oms_wei_transfer_extra_package;
if (transitOrder != null)
{
// 不是中转仓,直接返回
if (transitOrder == null)
{
BaseMsgWindow.ShowError("非中转仓订单不支持补发!");
return;
}
TransitExtraPackagesView transitExtraPackagesView = new TransitExtraPackagesView(orderItem.ItemOrder, orderItem, transitOrder);
new DialogWindow()
{
Title = "滞留补发买家",
Content = transitExtraPackagesView,
}.ShowDialog();
}
RefreshListCtrl(orderItem);
}
}
public void RefreshListCtrl(oms_wei_order_item_info orderItem)
{
// 更新列表
if (FindParent<OrderTransitListCtrl>(this) is OrderTransitListCtrl transitListCtrl)
{
oms_wei_order_item_transit_model transitInfo = new oms_wei_order_item_transit_model()
{
OrderItem = GlobalConfig.lstOrder.FirstOrDefault(o => o.order_id == orderItem?.order_id)?.orderItems.FirstOrDefault(oi => oi.sku_id == orderItem?.sku_id),
};
transitListCtrl.UpdateViewModel(transitInfo);
}
}
/// <summary>
/// 查找指定类型的父级控件
/// </summary>
/// <typeparam name="T">目标父控件类型</typeparam>
/// <param name="child">起始子控件</param>
/// <returns>找到的父控件,未找到则返回 null</returns>
public static T FindParent<T>(DependencyObject child) where T : DependencyObject
{
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
if (parentObject == null) return null;
if (parentObject is T parent)
{
return parent;
}
else
{
// 递归继续向上查找
return FindParent<T>(parentObject);
}
}
private void txtOutOrderId_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (this.DataContext is oms_wei_order_item_transit_detail_info transitDetailInfo && transitDetailInfo.oms_wei_order_item_info is oms_wei_order_item_info orderItem)
{
var buyerId = txtOutOrderBuyer.Tag as string;
var buyerName = txtOutOrderBuyer.Text;
var outOrderId = txtOutOrderId.Text;
if (string.IsNullOrEmpty(buyerName) || string.IsNullOrEmpty(outOrderId))
{
return;
}
bool isShowOrderList = sender == txtOutOrderBuyer;
OrderBuyerOrdersHelper.ShowBuyerOrder(orderItem, buyerId, buyerName, outOrderId, isShowOrderList);
}
}
}
@@ -0,0 +1,351 @@
using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.Ctrls.BuyerCtrls;
using _29WxOrderWpf.ViewModels;
using _29WxOrderWpf.Views;
using AllBase;
using AllBase.Helper;
using AllBase.Model.DBModel;
using AllBase.Model.Result;
using NaiBa.Util.Extension;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Work;
using Work._29Tools.BLL;
using WxOrder.Framework.Commons;
namespace _29WxOrderWpf.Ctrls.OrderCtrls;
internal class OrderTransitService
{
/// <summary>
/// 作废中转仓发货包裹
/// </summary>
/// <param name="orderItem"></param>
/// <param name="isSilent"></param>
/// <param name="UpdateOrderBeforeVoid">作废前是否更新服务端订单状态</param>
public static async Task VoidOrder(oms_wei_order_item_info orderItem, oms_wei_external_procurement_log_info transitOrder = null, bool isSilent = false, bool UpdateOrderBeforeVoid = true)
{
if (!isSilent)
{
if (BaseMsgWindow.ShowConfirm("确定作废当前包裹吗?").DialogResult == false)
return;
}
// 作废前查询订单状态
var orderId = orderItem.order_id;
var skuId = orderItem.sku_id;
if (UpdateOrderBeforeVoid)
await Task.Run(async() => { await MainWindow.Instance.orderListCtrl.GetOrder(orderId); });
var newOrder = GlobalConfig.lstOrder.FirstOrDefault(or => or.order_id == orderId);
if (newOrder?.orderItems.Count == 1)
orderItem = newOrder?.orderItems?.FirstOrDefault();
else
orderItem = newOrder?.orderItems?.FirstOrDefault(oi => oi.sku_id == skuId);
if (orderItem == null)
{
if (!isSilent)
BaseMsgWindow.ShowError("订单查询失败,请重试");
return;
}
if (transitOrder == null)
transitOrder = orderItem.ItemTransitOrder ?? orderItem.ItemTransitOrderWithVoid;
if (transitOrder == null)
{
if (!isSilent)
BaseMsgWindow.ShowError("要作废的中转订单不存在,请确认后重试");
return;
}
// 先作废后申请买手退款
// 订单作废接口(作废重拍)
//postman request POST 'http://localhost:8088/oms-api/external_procurement/discardOrder' \
// --header 'Content-Type: application/json' \
// --body '{
// "orderNo":"12334534534",
// "outOrderNo":"12312312"
//}' 成功返回code:0 失败返回code:1
string url2 = "https://po.e57.cn/prod-api/api/oms-api/external_procurement/discardOrder";
var data2 = new JObject();
data2["orderNo"] = orderItem.order_id;
//data2["outOrderNo"] = transitOrder.out_order_no;
data2["outOrderNo"] = transitOrder.order_code;
var dataStr2 = JsonHelper.SerializeObject(data2);
var discardRst = await HttpResponseWXBLL.e57PostResponseAsync(url2, dataStr2);
if (discardRst.Contains("\"code\":0") || discardRst.Contains("\"code\":200"))
{
//MainWindow.Instance.orderListCtrl.GetOrder(orderId);
// 修改为在买手退款流程后提示作废信息
}
else
{
var msg = BaseRegex.GetStringJsonByRegs(ref discardRst, discardRst, "msg");
if (!isSilent)
BaseMsgWindow.ShowInfo("订单作废失败,服务端返回 " + msg);
return;
}
#region 处理买手售后
if (transitOrder.out_order_no.ParseToString().StartsWith("tb_")) // 淘宝买手售后
{
if (!isSilent)
BaseMsgWindow.ShowError("淘宝买手暂不支持自动售后,作废后请手动申请售后");
else
transitOrder.refund_status = "淘宝买手暂不支持自动售后,作废后需手动申请售后";
}
else // 拼多多买手售后
{
bool noBuyer = false;
var buyer = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(b => b.buyer_id == transitOrder.buyer_account || b.buyer_name == transitOrder.buyer_account);
if (buyer == null)
{
if (!isSilent)
if (BaseMsgWindow.ShowConfirm("拍单买手不存在,点击确定直接作废中转单并手动取消买手单,点击取消登录买手后重试").DialogResult != true)
return;
noBuyer = true;
}
// 检测一下买手号
if (GlobalConfig.CurrentPddBuyer.status == "在线")
{
await Task.Run(() =>
{
PddMobileLoginViewModel.CheckBuyerLogin(GlobalConfig.CurrentPddBuyer);
});
}
if (GlobalConfig.CurrentPddBuyer.status != "在线")
{
if (!isSilent)
if (BaseMsgWindow.ShowConfirm("买手号掉线,点击确定直接作废中转单并手动取消买手单,点击取消登录买手后重试").DialogResult != true)
return;
noBuyer = true;
}
if (!noBuyer)
{
PddBuyerOrderLiteInfo order = null;
order = PDDBuyerOrderReadCtrl.lstPddBuyerOrderInfoLite.FirstOrDefault(o => o.order_sn == transitOrder.out_order_no);
if (order == null)
order = new PddBuyerOrderLiteInfo()
{
order_status_prompt = "待发货",
order_amount = transitOrder.out_amount,
order_sn = transitOrder.out_order_no
};
PDDBuyerOrderReadCtrl.lstPddBuyerOrderInfoLite.Add(order);
var pddAfterRst = "";
await Task.Run(() =>
{
pddAfterRst = PDDBuyerOrderReadCtrl.SimPddAfterSale(buyer, order);
});
if (pddAfterRst.Contains("\"after_sales_status\":1") || pddAfterRst.Contains("该订单已全额退款") || pddAfterRst.Contains("订单未付款"))
{
// 保存退款成功状态
order.order_status_prompt = pddAfterRst.Contains("订单未付款") ? "订单未付款" : "退款成功";
// 中转仓订单买手号售后信息 存到服务端
var refundRst = PDDBuyerOrderReadCtrl.SendTransitAfterSaleE57(order);
if (refundRst.Contains("<code>0</code>") || refundRst.Contains("<code>200</code>"))
{
order.sendStatus = "退款成功 买手退款信息更新成功";
}
else
{
var msg = BaseRegex.GetStringXml(ref refundRst, "msg");
order.sendStatus = "退款成功 买手退款信息更新失败,服务端返回 " + msg;
}
NaiBa.Util.Helper.ConfigHelper.SaveConfig("pdd_buyer_order_list", PDDBuyerOrderReadCtrl.lstPddBuyerOrderInfoLite);
}
else
{
if (!isSilent)
if (BaseMsgWindow.ShowConfirm("买手退款失败,点击确定直接作废中转单并手动取消买手单,点击取消稍候重试").DialogResult != true)
return;
}
}
}
#endregion
#region 更新拍单余额
StartUp.UpdateBalance();
#endregion
#region 立即更新订单
transitOrder = orderItem.ItemTransitOrders.FirstOrDefault(o => o.order_code == transitOrder.order_code) ?? transitOrder;
transitOrder.order_void_status = 1;
orderItem.SetOrderItemTextProperty();
#endregion
#region 重新过滤订单
OrderListCtrl.InitOrderItemObservableProp(orderItem);
MainWindow.Instance.orderListCtrl.FilterOrders();
if (!isSilent)
BaseMsgWindow.ShowInfo("订单作废成功,请重新拍单");
#endregion
}
/// <summary>
/// 作废售后包裹
/// </summary>
/// <param name="returnOrder"></param>
/// <returns></returns>
public static async Task<string> VoidAfterSalePackage(oms_wei_order_item_info orderItem, oms_wei_external_procurement_after_sale_info returnOrder)
{
string typeStr = returnOrder?.pack_type == 1 ? "作废分销发货退货包裹" : "作废额外包裹退货包裹";
string msg = $@"确定{typeStr}吗?";
if (BaseMsgWindow.ShowConfirm(msg, typeStr, null, MsgWindowLevel.MEDIUM, 300).DialogResult != true)
return "";
string url2 = "https://po.e57.cn/prod-api/api/oms-api/external_procurement/orders/interceptReturn";
var data = new JObject();
data["externalOrderNo"] = returnOrder.external_order_no;
data["orderNo"] = returnOrder.order_no; // 订单编号
data["orderCode"] = returnOrder.order_code;
data["packType"] = returnOrder.pack_type; /* 1作废分销发货退货包裹 2作废额外包裹退货包裹 */
var dataStr2 = JsonHelper.SerializeObject(data);
var voidRst = await HttpResponseWXBLL.e57PostResponseAsync(url2, dataStr2);
if (voidRst.Contains("\"code\":0") || voidRst.Contains("\"code\":200"))
{
StartUp.UpdateBalance();
returnOrder.order_void_status = 1;
orderItem.SetOrderItemTextProperty();
return typeStr + "成功!";
}
else
{
throw new Exception(typeStr + "失败,服务端返回:" + BaseRegex.GetStringJsonByRegs(ref voidRst, voidRst, "msg"));
}
}
/// <summary>
/// 作废额外包裹
/// </summary>
/// <param name="orderItem"></param>
/// <param name="extraOrder"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static async Task<string> VoidExtraPackage(oms_wei_order_item_info orderItem, oms_wei_transfer_extra_package extraOrder)
{
string typeStr = "作废额外包裹";
string msg = $@"确定{typeStr}吗?";
if (BaseMsgWindow.ShowConfirm(msg, typeStr, null, MsgWindowLevel.MEDIUM, 300).DialogResult != true)
return "";
var data = new JObject();
data["batchId"] = extraOrder.batchId;
data["orderCode"] = extraOrder.order_code;
var dataStr = JsonHelper.SerializeObject(data);
var url = "https://po.e57.cn/prod-api/api/oms-api/external_procurement/extraOrders/void";
var voidRst = await HttpResponseWXBLL.e57PostResponseAsync(url, dataStr);
if (BaseRegex.GetStringJson(ref voidRst, "code") != "0" && BaseRegex.GetStringJson(ref voidRst, "code") != "200")
{
throw new Exception("作废额外包裹失败,服务端返回:" + BaseRegex.GetStringJsonByRegs(ref voidRst, voidRst, "msg"));
}
StartUp.UpdateBalance();
extraOrder.order_void_status = 1;
orderItem.SetOrderItemTextProperty();
//MainWindow.Instance.orderListCtrl.FilterOneOrder(orderItem.order_id);
return "作废额外包裹成功!";
}
/// <summary>
/// 云仓申请拒收退回总店
/// </summary>
/// <param name="orderItem"></param>
public static async Task<string> RejectTransitOrder(oms_wei_order_item_info orderItem, oms_wei_external_procurement_log_info _itemTransitOrder)
{
string msg = $@"
        云仓拒收退回总店
说  明:店铺产生售后,拒收成功,货物会原物流退回总店。
拒收条件:(总店物流没到云仓/未签收前)。顺丰/京东无法
     拒收,直接总店申请仅退款让总店拦截。
收  费:免费";
if (BaseMsgWindow.ShowConfirm(msg, "云仓拒收退回总店", null, MsgWindowLevel.LARGE, 300).DialogResult != true)
return "";
orderItem.ItemTransitOrders = await OrderGetOrderListHelper.GetTransitWarehouseList(orderItem.order_id);
orderItem.PddBuyerOrders = (await OrderGetOrderListHelper.GetPddBuyerOrders(orderItem.order_id)).Where(o => o.wx_send_type == 0).ToList();
orderItem.PddBuyerOrders.AddRange((await OrderGetOrderListHelper.GetTbBuyerOrders(orderItem.order_id)).Where(o => o.wx_send_type == 0).ToList());
OrderListCtrl.InitOrderItemObservableProp(orderItem);
var itemTransitOrder = orderItem.ItemTransitOrders.FirstOrDefault(o => o.order_code == _itemTransitOrder?.order_code && o.out_order_no == _itemTransitOrder?.out_order_no);
if (itemTransitOrder == null)
itemTransitOrder = _itemTransitOrder;
//if (itemTransitOrder?.warehouse_status == 3) { BaseMsgWindow.ShowError("商品已拒收或拦截!"); return; }
//if (itemTransitOrder?.warehouse_status == 2) { BaseMsgWindow.ShowError("商品已出库,请选择退回中转仓!"); return; }
//if (string.IsNullOrEmpty(orderItem.PddBuyerOrder?.order_sn)) { BaseMsgWindow.ShowError("商品未出单,请直接去拼多多买手申请退款"); return; }
if (itemTransitOrder?.has_reject == 1 || itemTransitOrder?.has_reject == 3)
{
//BaseMsgWindow.ShowAnimateMessage("已申请拒收", "Msg", 3);
return "已申请过拒收";
}
// 中转仓拒收(已产生物流)
string url = "https://po.e57.cn/prod-api/api/oms-api/external_procurement/orders/rejectApply";
var dataObj = new JObject();
dataObj["orderCode"] = itemTransitOrder?.order_code;
dataObj["orderId"] = orderItem.order_id;
dataObj["logisticsExpressCode"] = orderItem.PddBuyerOrder?.order_sn;
var data = JsonHelper.SerializeObject(dataObj);
var html = HttpResponseWXBLL.e57PostResponse(url, data, "");
int rejectStatus = 0;
if (html.Contains("<code>0</code>") || html.Contains("<code>200</code>"))
{
rejectStatus = 1;
//BaseMsgWindow.ShowAnimateMessage("申请成功", "Msg", 3);
}
else
{
rejectStatus = 2;
var err = BaseRegex.GetStringXmlByRegs(ref html, html, "msg");
//BaseMsgWindow.ShowAnimateMessage("申请失败", "Error", 3);
throw new Exception("申请失败" + err);
}
url = BaseClass.Build29WxObjString("order/wx_update_transit_order_reject_status");
data = UserLogin.GetSignaturex();
data += "&order_no=" + orderItem.order_id;
data += "&order_sku_id=" + orderItem.sku_id;
data += "&has_reject=" + rejectStatus;
html = await GetHtml.PostUtf8Async(url, data);
itemTransitOrder.has_reject = rejectStatus;
OrderListCtrl.InitOrderItemObservableProp(orderItem);
return "申请成功";
}
/// <summary>
/// 申请拒收后查询拒收状态
/// </summary>
/// <param name="orderItem"></param>
/// <param name="upperWaybill"></param>
public static void ShowRejectTransitOrder(oms_wei_order_item_info orderItem, string upperWaybill)
{
BaiduGetWaybillInfoView buyerLoginForm = new BaiduGetWaybillInfoView(orderItem);
buyerLoginForm.ViewModel.InitUrl = "https://www.baidu.com/s?ie=UTF-8&wd=" + upperWaybill;
new DialogWindow()
{
Width = 1280,
Height = 800,
Title = "物流拒收查询",
Content = buyerLoginForm,
}.Show();
return;
}
}
@@ -63,13 +63,18 @@ public class PddBrowserOrderInvoiceViewModel : BindableBaseEx
set set
{ {
SetValue(value); SetValue(value);
base.RaisePropertyChanged(nameof(InvoiceStatusText)); InvoiceStatusText = value ? "已提交申请" : "待开票";
} }
} }
public int Quantity => order_Goods?.Sum(a => a.goods_number.Value) ?? 0; public int Quantity => order_Goods?.Sum(a => a.goods_number.Value) ?? 0;
private string _invoiceStatusText = "待开票";
/// <summary> 发票状态文案:已开票 / 待开票 </summary> /// <summary> 发票状态文案:已开票 / 待开票 </summary>
public string InvoiceStatusText => IsInvoiced ? "已提交申请" : "待开票"; public string InvoiceStatusText
{
get => _invoiceStatusText;
set => SetValue(ref _invoiceStatusText, value);
}
public DateTime OrderTime public DateTime OrderTime
@@ -2,6 +2,8 @@
using CefSharp; using CefSharp;
using CefSharp.Handler; using CefSharp.Handler;
using CefSharp.Wpf; using CefSharp.Wpf;
using Newtonsoft.Json.Linq;
using NPOI.XWPF.UserModel;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -11,6 +13,7 @@ using System.Threading.Tasks;
using System.Windows.Controls; using System.Windows.Controls;
using Work._29Tools.CefTools; using Work._29Tools.CefTools;
using Work.BaseForms; using Work.BaseForms;
using WxOrder.Framework.Commons;
using WxOrder.Framework.Helpers; using WxOrder.Framework.Helpers;
namespace _29WxOrderWpf.Ctrls.PDDInvoice.ViewModels; namespace _29WxOrderWpf.Ctrls.PDDInvoice.ViewModels;
@@ -29,11 +32,10 @@ public partial class PDDInvoiceViewModel
BrowserDetailZIndex = -1; BrowserDetailZIndex = -1;
BrowserDetail = WPFCEFBrowser.CreateChromiumWebBrowser("about:blank", false); BrowserDetail = WPFCEFBrowser.CreateChromiumWebBrowser("about:blank", false);
LocalResourceRequestHandler resourceRequestHandler = new LocalResourceRequestHandler();
LocalResourceRequestHandler detailResourceRequestHandler = new LocalResourceRequestHandler(); LocalResourceRequestHandler detailResourceRequestHandler = new LocalResourceRequestHandler();
detailResourceRequestHandler.ResourceLoadCompleteEvent += DetailRequestHandler_ResourceLoadComplete; detailResourceRequestHandler.ResourceLoadCompleteEvent += DetailRequestHandler_ResourceLoadComplete;
BrowserDetail.RequestHandler = new LocalRequestHandler(resourceRequestHandler); BrowserDetail.RequestHandler = new LocalRequestHandler(detailResourceRequestHandler);
BrowserDetail.LifeSpanHandler = new LocalLifeSpanHandler(PopWindowType.SelfWindow); BrowserDetail.LifeSpanHandler = new LocalLifeSpanHandler(PopWindowType.SelfWindow);
BrowserDetail.KeyboardHandler = new KeyboardHandler(); BrowserDetail.KeyboardHandler = new KeyboardHandler();
BrowserDetail.LoadingStateChanged += BrowserDetail_LoadingStateChanged; BrowserDetail.LoadingStateChanged += BrowserDetail_LoadingStateChanged;
@@ -68,12 +70,17 @@ public partial class PDDInvoiceViewModel
string html = await b.GetBrowser().GetSourceAsync(); string html = await b.GetBrowser().GetSourceAsync();
if (html.Contains("window.rawData")) if (html.Contains("window.rawData"))
{ {
await ExecuteInvoiceApplyScriptAsync(b, orderSN); if (html.Contains("\"hasApplied\":true,"))
{
_currentInvoiceTcs?.TrySetResult(new Result<bool> { Data = true });
return;
}
await ExecuteInvoiceApplyScriptAsync(b);
} }
else else
{ {
// 页面异常(未渲染出发票表单)时直接判定失败,避免批量开票长时间等待 // 页面异常(未渲染出发票表单)时直接判定失败,避免批量开票长时间等待
_currentInvoiceTcs?.TrySetResult(false); _currentInvoiceTcs?.TrySetResult(new Result<bool> { Data = false });
} }
} }
}); });
@@ -85,54 +92,40 @@ public partial class PDDInvoiceViewModel
/// 单张申请模式保持原有行为;批量开票模式下轮询脚本写入的 /// 单张申请模式保持原有行为;批量开票模式下轮询脚本写入的
/// <c>window.__invoiceApplyResult</c>,完成后通过 <see cref="_currentInvoiceTcs"/> 回传结果。 /// <c>window.__invoiceApplyResult</c>,完成后通过 <see cref="_currentInvoiceTcs"/> 回传结果。
/// </summary> /// </summary>
private async Task ExecuteInvoiceApplyScriptAsync(ChromiumWebBrowser b, string orderSn) private async Task ExecuteInvoiceApplyScriptAsync(ChromiumWebBrowser b)
{ {
string content = ResourceHelper.GetResourceText("/Ctrls/PDDInvoice/Resources/invoice.js", "29WxFindOrder"); string content = ResourceHelper.GetResourceText("/Ctrls/PDDInvoice/Resources/invoice.js", "29WxFindOrder");
content = content.Replace("{公司}", Config.Title); content = content.Replace("{公司}", Config.Title);
content = content.Replace("{税号}", Config.TaxNo); content = content.Replace("{税号}", Config.TaxNo);
if (string.IsNullOrEmpty(content)) return; if (string.IsNullOrEmpty(content)) return;
await b.EvaluateScriptAsync(content); await b.EvaluateScriptAsync(content);//执行js
if (_currentInvoiceTcs == null)
{
var temp = Orders?.FirstOrDefault(a => a.order_sn == orderSn);
if (temp != null) temp.IsInvoiced = true;
return; // 单张申请模式:保持原有行为
}
// 捕获当前 TCS,避免批量循环超时进入下一个订单后,迟到的轮询误触发新订单的结果
var tcs = _currentInvoiceTcs;
// 检查是否注入成功 // 检查是否注入成功
if (await IsInstalledDetailAsync(b) == false) if (await IsInstalledDetailAsync(b) == false)
{ {
IsBatchInvoicing = false; IsBatchInvoicing = false;
BaseMsgForm.ShowError("JS错误,开票失败"); BaseMsgForm.ShowError("JS错误,开票失败");
tcs.TrySetResult(false); _currentInvoiceTcs.TrySetResult(new Result<bool> { Data = false });
return; return;
} }
//for (int i = 0; i < 120; i++)//循环获取结果
//{
// await Task.Delay(500);
// try
for (int i = 0; i < 120; i++) // {
{ // var res = await b.EvaluateScriptAsync("window.__invoiceApplyResult");
await Task.Delay(500); // if (res.Success && res.Result != null)
try // {
{ // _currentInvoiceTcs.TrySetResult(Convert.ToBoolean(res.Result));
var res = await b.EvaluateScriptAsync("window.__invoiceApplyResult"); // return;
if (res.Success && res.Result != null) // }
{ // }
tcs.TrySetResult(Convert.ToBoolean(res.Result)); // catch
return; // {
} // }
} //}
catch //_currentInvoiceTcs.TrySetResult(false);
{
}
}
tcs.TrySetResult(false);
} }
@@ -151,9 +144,38 @@ public partial class PDDInvoiceViewModel
private void DetailRequestHandler_ResourceLoadComplete(object sender, string url, string postData, string responseData, IRequest request) private void DetailRequestHandler_ResourceLoadComplete(object sender, string url, string postData, string responseData, IRequest request)
{ {
if (url.StartsWith("https://mobile.yangkeduo.com/transac_return_compensation.html")) if (url.StartsWith("https://mobile.yangkeduo.com/proxy/api/api/order/invoice/apply"))
{ {
var obj = JObject.Parse(responseData);
bool isSuccess = obj.Value<bool?>("result") == true;
if (isSuccess)
{
_currentInvoiceTcs.TrySetResult(new Result<bool> { Data = true });
}
else
{
string errMsg = obj.Value<string>("error_msg");
_currentInvoiceTcs.TrySetResult(new Result<bool> { Data = false, Msg = errMsg });
}
return;
//{"order_sn":"260921-458426969742556","mall_id":697300659,"trigger_status":1,"business_type":1,"payer_name":"合肥弘贸电子商务有限公司","invoice_kind":0,"invoice_type":0,"letter_head_id":"690562059266556","letterhead_snapshot_id":"SI298036413700604","paper_certificate_url":"","entrust_certify_url":"","source":1,"anti_content":"0asAfoyqYiPs6gd2J0WQ9QOUtOrZ44_LwPI3lrN83FY_wympvl577D6QppXrSLrHJn8eNWv8uXBTdg6_iPUC1aDYt-JuCI1dMpKg2wsf65KUBPzEhRU8pGAbTnWhcJ29ooVcncR90coLgWQiLJ0Xjo0Y4aHEJnnk2lr2PRkY2Kj9ibYc9QW-i2Mr23mjyQMQIahwAhEX-xjSVJEd35qSDQo9VrbY0Fb4kiiL0tHoKEQqmgMcn1BIH9LQB30NJ9s857b25NDDXQyuIT9hR2fCiRoY-96khLJ8QI6wqNL8Q406RBojM6oYsKqEGEFNn7Qyr4N3q-FELBTkkmyToyzs4cM1iUKl3Zaqe0MtFefxmZcLUj3FFxQ6GdAAfKO2WlAkwx7QuMppG7UtkEpRuNjrkojzegy1jaIBWzPrzevvx3egES52PIHEFZASpZ2gNPXaDGSbVGu8shqGDmXuu94aWgXxEE3CzPfVcUZooGs40ThX0ouQF7IFTKM6-NSsk8ZrVjEHdWO1-EE_SCngMCC1vFeAr1g5NvaUCC_87CibfVcWPe5lhgRaq6dKfSAYDoT_bA0nPm6wSDZSxAQbSk-1JZC-O6OpFqXcrkKVUZk0atnozQtKlf1cxcyCl_EkEMnpwZll4g3jEKUxLK_XCIUz0TjDUbF1dpZOsWd39crq7VktSKKZ32b_e0sk6ZkvAf5F7GKwfvfy6RX5YbcrCcpfsjJqaXNGy2G2Y_Oj0iPcpgaXv0zmJjkB217RMtwxBybZnjdOMIlGJWUFls4unwncEvdy4Udgi7EdgB_MXwgn2zGa1_wHKltF7n37wKjKBKlysnfv8mFfqzH3Jv7L4jj9cCQ7P5Fb3E8KQ9J","payer_register_no":"91340103MAKBDKB764","payer_phone":"","payer_account":"","payer_address":"","payer_bank":""}
//{"server_time":1792493897,"result":true}
/*
{
"server_time": 1792493128,
"error_code": 17003,
"error_msg": "商家已与您协商开票,如有需要,请联系商家"
}*/
} }
} }
} }
@@ -1,7 +1,5 @@
using _29WxOrderWpf.BaseWindows; using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.CefHelper; using _29WxOrderWpf.CefHelper;
using WxOrder.Framework.Commons;
using WxOrder.Framework.Commons;
using _29WxOrderWpf.Ctrls.Statistics; using _29WxOrderWpf.Ctrls.Statistics;
using AllBase; using AllBase;
using AllBase.Helper; using AllBase.Helper;
@@ -14,6 +12,7 @@ using CefSharp.Wpf;
using NaiBa.Util.Extension; using NaiBa.Util.Extension;
using Newtonsoft.Json; using Newtonsoft.Json;
using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.X509;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
@@ -37,6 +36,8 @@ using WPFCommon.Converters;
using WPFCommon.Helpers; using WPFCommon.Helpers;
using WPFCommon.Models; using WPFCommon.Models;
using WxOrder.Framework.Commons; using WxOrder.Framework.Commons;
using WxOrder.Framework.Commons;
using WxOrder.Framework.Commons;
using WxOrder.Framework.Commons.Dialogs; using WxOrder.Framework.Commons.Dialogs;
using WxOrder.Framework.Helpers; using WxOrder.Framework.Helpers;
@@ -284,7 +285,7 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
public ICommand ResetCommand => new DelegateCommand(ResetSearch); public ICommand ResetCommand => new DelegateCommand(ResetSearch);
public ICommand OpenInvoiceCommand => new DelegateCommand<PddBrowserOrderInvoiceViewModel>(OpenInvoice); public ICommand OpenInvoiceCommand => new AsyncDelegateCommand<PddBrowserOrderInvoiceViewModel>(OpenInvoice);
public ICommand ShowInvoiceCommand => new DelegateCommand<PddBrowserOrderInvoiceViewModel>(ShowInvoice); public ICommand ShowInvoiceCommand => new DelegateCommand<PddBrowserOrderInvoiceViewModel>(ShowInvoice);
@@ -434,7 +435,7 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
} }
/// <summary> 当前正在批量处理的订单,页面脚本执行完成后通过它回传结果 </summary> /// <summary> 当前正在批量处理的订单,页面脚本执行完成后通过它回传结果 </summary>
private TaskCompletionSource<bool> _currentInvoiceTcs; private TaskCompletionSource<Result<bool>> _currentInvoiceTcs;
public ICommand BatchInvoiceCommand => new AsyncDelegateCommand(BatchInvoice); public ICommand BatchInvoiceCommand => new AsyncDelegateCommand(BatchInvoice);
@@ -471,8 +472,19 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
//Config.TaxNo = TaxNo; //Config.TaxNo = TaxNo;
//Config.MaxAmount = MaxAmount; //Config.MaxAmount = MaxAmount;
//NaiBa.Util.Helper.ConfigHelper.SaveConfig(ConfigPath, Config); //NaiBa.Util.Helper.ConfigHelper.SaveConfig(ConfigPath, Config);
try
{
await BatchInvoiceAsync(targets);
}
catch (Exception ex)
{
BaseMsgWindow.ShowError("批量开票异常:" + ex.Message);
await BatchInvoiceAsync(targets); }
finally
{
BaseMsgWindow.ShowInfo(BottomMsg);
}
} }
public ICommand StopBatchInvoiceCommand => new AsyncDelegateCommand(StopBatchInvoice); public ICommand StopBatchInvoiceCommand => new AsyncDelegateCommand(StopBatchInvoice);
@@ -541,12 +553,12 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
} }
else else
{ {
_currentInvoiceTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); _currentInvoiceTcs = new TaskCompletionSource<Result<bool>>(TaskCreationOptions.RunContinuationsAsynchronously);
BrowserDetail.Load($"https://mobile.yangkeduo.com/transac_return_compensation.html?_t_timestamp=transac_modify_invoice&order_sn={order.order_sn}"); BrowserDetail.Load($"https://mobile.yangkeduo.com/transac_return_compensation.html?_t_timestamp=transac_modify_invoice&order_sn={order.order_sn}");
// 等待页面脚本执行完成(最长 60 秒) // 等待页面脚本执行完成(最长 60 秒)
var done = await Task.WhenAny(_currentInvoiceTcs.Task, Task.Delay(TimeSpan.FromSeconds(60))); Task done = await Task.WhenAny(_currentInvoiceTcs.Task, Task.Delay(TimeSpan.FromSeconds(10)));
ok = done == _currentInvoiceTcs.Task && _currentInvoiceTcs.Task.Result; ok = done == _currentInvoiceTcs.Task && _currentInvoiceTcs.Task.Result.Data;
} }
if (ok) if (ok)
{ {
@@ -562,6 +574,10 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
} }
else else
{ {
if (_currentInvoiceTcs.Task.IsCompleted)
{
order.InvoiceStatusText = _currentInvoiceTcs.Task.Result.Msg;
}
fail++; fail++;
} }
ProgressValue = success + fail; ProgressValue = success + fail;
@@ -580,7 +596,7 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
catch (Exception ex) catch (Exception ex)
{ {
fail = targets.Count - success; fail = targets.Count - success;
BaseMsgWindow.ShowError("批量开票异常:" + ex.Message); throw ex;
} }
finally finally
{ {
@@ -588,7 +604,6 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
ProgressMaximum = targets.Count; ProgressMaximum = targets.Count;
ProgressValue = targets.Count; ProgressValue = targets.Count;
IsBatchInvoicing = false; IsBatchInvoicing = false;
BaseMsgWindow.ShowInfo(BottomMsg);
} }
} }
/// <summary> /// <summary>
@@ -642,7 +657,7 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
/// 申请开票 /// 申请开票
/// </summary> /// </summary>
/// <param name="order"></param> /// <param name="order"></param>
private void OpenInvoice(PddBrowserOrderInvoiceViewModel order) private async Task OpenInvoice(PddBrowserOrderInvoiceViewModel order)
{ {
SelectedOrder = order; SelectedOrder = order;
if (string.IsNullOrEmpty(Config.Title) || string.IsNullOrEmpty(Config.TaxNo)) if (string.IsNullOrEmpty(Config.Title) || string.IsNullOrEmpty(Config.TaxNo))
@@ -650,8 +665,19 @@ public partial class PDDInvoiceViewModel : BindableBaseEx, IDialogAware, IDispos
BaseMsgWindow.ShowError("未填写公司或税号"); BaseMsgWindow.ShowError("未填写公司或税号");
return; return;
} }
BrowserDetail.Load($"https://mobile.yangkeduo.com/transac_return_compensation.html?_t_timestamp=transac_modify_invoice&order_sn={order.order_sn}");
ShowOrderBrowserDetail(); ShowOrderBrowserDetail();
//BrowserDetail.Load($"https://mobile.yangkeduo.com/transac_return_compensation.html?_t_timestamp=transac_modify_invoice&order_sn={order.order_sn}");
try
{
await BatchInvoiceAsync(new List<PddBrowserOrderInvoiceViewModel>
{
order
});
}
catch (Exception ex)
{
BaseMsgWindow.ShowError("开票异常:" + ex.Message);
}
} }
private void ShowInvoice(PddBrowserOrderInvoiceViewModel order) private void ShowInvoice(PddBrowserOrderInvoiceViewModel order)
+95 -50
View File
@@ -1,51 +1,96 @@
<Window <Window
x:Class="_29WxOrderWpf.Ctrls.Settings.SettingsView" x:Class="_29WxOrderWpf.Ctrls.Settings.SettingsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.Settings" xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.Settings"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="[vm ]clr-namespace:_29WxOrderWpf.ViewModels" xmlns:vm="clr-namespace:_29WxOrderWpf.ViewModels"
xmlns:wpf="WPFCommon" xmlns:wpf="WPFCommon"
Title="设置" Title="设置"
Width="800" Width="800"
Height="450" Height="450"
d:DataContext="{d:DesignInstance Type=vm:SettingViewModel}" d:DataContext="{d:DesignInstance Type=vm:SettingViewModel}"
ResizeMode="NoResize" ResizeMode="NoResize"
ShowInTaskbar="False" ShowInTaskbar="False"
WindowStartupLocation="CenterScreen" WindowStartupLocation="CenterScreen"
WindowState="Normal" WindowState="Normal"
mc:Ignorable="d"> mc:Ignorable="d">
<Border BorderBrush="#e8eaed" BorderThickness="1"> <Border BorderBrush="#e8eaed" BorderThickness="1">
<TabControl <TabControl
ItemContainerStyle="{StaticResource SideTabItem}" ItemContainerStyle="{StaticResource SideTabItem}"
Style="{StaticResource SideTabControl}" Style="{StaticResource SideTabControl}"
TabStripPlacement="Left"> TabStripPlacement="Left">
<TabItem Header="发货"> <TabItem Header="拍单">
<StackPanel> <StackPanel>
<Border Style="{StaticResource SettingRow}"> <Border Style="{StaticResource SettingRow}">
<Grid> <Grid Visibility="{Binding ShowEnablePddTransitTraditionalAddress}">
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<StackPanel> <StackPanel>
<TextBlock Style="{StaticResource SettingTitle}" Text="礼品单发送" /> <TextBlock Style="{StaticResource SettingTitle}" Text="云仓拍单" />
<TextBlock Style="{StaticResource SettingDesc}" Text="超出6元自动改为礼品二(实物)" /> <TextBlock Style="{StaticResource SettingDesc}" Text="多多云仓拍单随机繁体详细地址" />
</StackPanel> </StackPanel>
<CheckBox <CheckBox
Grid.Column="1" Grid.Column="1"
VerticalAlignment="Center" VerticalAlignment="Center"
IsChecked="{Binding AutoSwitchGiftType}" d:Visibility="Visible"
IsChecked="{Binding SwitchEnablePddTransitTraditionalAddress}"
Style="{StaticResource ToggleSwitch}" /> Style="{StaticResource ToggleSwitch}" />
</Grid> </Grid>
</Border> </Border>
</StackPanel> <Border Style="{StaticResource SettingRow}">
</TabItem> <Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Style="{StaticResource SettingTitle}" Text="直发拍单" />
<TextBlock Style="{StaticResource SettingDesc}" Text="允许直发拍单" />
</StackPanel>
<CheckBox
Grid.Column="1"
VerticalAlignment="Center"
d:Visibility="Visible"
IsChecked="{Binding SwitchEnableDirectBuy}"
Style="{StaticResource ToggleSwitch}" />
</Grid>
</Border>
</StackPanel>
</TabItem>
<!-- ========== 外观 ========== --> <TabItem Header="发货">
<!-- <StackPanel>
<Border Style="{StaticResource SettingRow}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Style="{StaticResource SettingTitle}" Text="礼品单发送" />
<TextBlock Style="{StaticResource SettingDesc}" Text="超出6元自动改为礼品二(实物)" />
</StackPanel>
<CheckBox
Grid.Column="1"
VerticalAlignment="Center"
d:Visibility="Visible"
IsChecked="{Binding AutoSwitchGiftType}"
IsEnabled="False"
Opacity="0.5"
Style="{StaticResource ToggleSwitch}"
Visibility="Collapsed" />
</Grid>
</Border>
</StackPanel>
</TabItem>
<!-- ========== 外观 ========== -->
<!--
<TabItem Header="外观" Tag="🎨"> <TabItem Header="外观" Tag="🎨">
<StackPanel <StackPanel
MaxWidth="720" MaxWidth="720"
@@ -110,8 +155,8 @@
</TabItem> </TabItem>
--> -->
<!-- ========== 账户 ========== --> <!-- ========== 账户 ========== -->
<!-- <!--
<TabItem Header="账户" Tag="👤"> <TabItem Header="账户" Tag="👤">
<StackPanel <StackPanel
MaxWidth="720" MaxWidth="720"
@@ -157,8 +202,8 @@
</TabItem> </TabItem>
--> -->
<!-- ========== 隐私 ========== --> <!-- ========== 隐私 ========== -->
<!-- <!--
<TabItem Header="隐私" Tag="🔒"> <TabItem Header="隐私" Tag="🔒">
<StackPanel <StackPanel
MaxWidth="720" MaxWidth="720"
@@ -208,8 +253,8 @@
</TabItem> </TabItem>
--> -->
<!-- ========== 关于 ========== --> <!-- ========== 关于 ========== -->
<!-- <!--
<TabItem Header="关于" Tag="{StaticResource txt-table_stack_above}"> <TabItem Header="关于" Tag="{StaticResource txt-table_stack_above}">
<StackPanel <StackPanel
MaxWidth="720" MaxWidth="720"
@@ -247,6 +292,6 @@
</StackPanel> </StackPanel>
</TabItem>--> </TabItem>-->
</TabControl> </TabControl>
</Border> </Border>
</Window> </Window>
@@ -1,5 +1,6 @@
using _29WxOrderWpf.ViewModels; using _29WxOrderWpf.ViewModels;
using AllBase; using AllBase;
using AllBase.Helper;
using AllBase.Model.Config; using AllBase.Model.Config;
using Newtonsoft.Json; using Newtonsoft.Json;
using System; using System;
@@ -44,6 +45,15 @@ public partial class SettingsView : Window
var setting = vm.ToConfig(); var setting = vm.ToConfig();
BaseClass.Setting = setting; BaseClass.Setting = setting;
NaiBa.Util.Helper.ConfigHelper.SaveConfig(SettingViewModel.SettingFileName, JsonConvert.SerializeObject(setting)); NaiBa.Util.Helper.ConfigHelper.SaveConfig(SettingViewModel.SettingFileName, JsonConvert.SerializeObject(setting));
foreach (var order in GlobalConfig.lstOrder)
{
foreach (var orderItem in order.orderItems)
{
orderItem.UpdateOrderItemBuyButton();
orderItem.SetAbnormalAndDirectBtnVisibility();
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
+350 -321
View File
@@ -1,327 +1,356 @@
<UserControl <UserControl
x:Class="_29WxOrderWpf.Ctrls.ShopCtrls.ShopListCtrl" x:Class="_29WxOrderWpf.Ctrls.ShopCtrls.ShopListCtrl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.ShopCtrls" xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.ShopCtrls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="shopListCtrl" x:Name="shopListCtrl"
d:DesignHeight="450" d:DesignHeight="450"
d:DesignWidth="800" d:DesignWidth="800"
Loaded="shopListCtrl_Loaded" Loaded="shopListCtrl_Loaded"
mc:Ignorable="d"> mc:Ignorable="d">
<Grid Background="{StaticResource ListCtrlBackColorBrush}"> <Grid Background="{StaticResource ListCtrlBackColorBrush}">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="40" /> <RowDefinition Height="40" />
<RowDefinition Height="40" /> <RowDefinition Height="40" />
<RowDefinition Height="*" /> <RowDefinition Height="*" />
<RowDefinition Height="40" /> <RowDefinition Height="40" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid x:Name="gridSearch"> <Grid x:Name="gridSearch">
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<TextBlock <TextBlock
Grid.Column="0" Grid.Column="0"
Margin="6,0,0,0" Margin="6,0,0,0"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Center" VerticalAlignment="Center"
Text="店名" /> Text="店名" />
<Border <Border
Grid.Column="1" Grid.Column="1"
Height="26" Height="26"
Margin="4" Margin="4"
BorderBrush="{StaticResource mainColorBrush}" BorderBrush="{StaticResource mainColorBrush}"
BorderThickness="1" BorderThickness="1"
CornerRadius="4"> CornerRadius="4">
<TextBox <TextBox
x:Name="txtShopName" x:Name="txtShopName"
Margin="3,0" Margin="3,0"
VerticalContentAlignment="Center" VerticalContentAlignment="Center"
Style="{StaticResource BaseTextBoxStyle}" /> Style="{StaticResource BaseTextBoxStyle}" />
</Border> </Border>
<TextBlock <TextBlock
Grid.Column="2" Grid.Column="2"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Center" VerticalAlignment="Center"
Text="分组" /> Text="分组" />
<Border <Border
Grid.Column="3" Grid.Column="3"
Height="26" Height="26"
Margin="4" Margin="4"
BorderBrush="{StaticResource mainColorBrush}" BorderBrush="{StaticResource mainColorBrush}"
BorderThickness="1" BorderThickness="1"
CornerRadius="4"> CornerRadius="4">
<ComboBox <ComboBox
x:Name="cmbGroup" x:Name="cmbGroup"
Margin="3,0" Margin="3,0"
VerticalContentAlignment="Center" VerticalContentAlignment="Center"
SelectionChanged="cmbGroup_SelectionChanged" SelectionChanged="cmbGroup_SelectionChanged"
Style="{StaticResource BaseComboBoxStyle}" /> Style="{StaticResource BaseComboBoxStyle}" />
</Border> </Border>
<TextBlock <TextBlock
Grid.Column="4" Grid.Column="4"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Center" VerticalAlignment="Center"
Text="备注" /> Text="备注" />
<Border <Border
Grid.Column="5" Grid.Column="5"
Height="26" Height="26"
Margin="4" Margin="4"
BorderBrush="{StaticResource mainColorBrush}" BorderBrush="{StaticResource mainColorBrush}"
BorderThickness="1" BorderThickness="1"
CornerRadius="4"> CornerRadius="4">
<ComboBox <ComboBox
x:Name="cmbNotes" x:Name="cmbNotes"
Margin="3,0" Margin="3,0"
VerticalContentAlignment="Center" VerticalContentAlignment="Center"
SelectionChanged="cmbNotes_SelectionChanged" SelectionChanged="cmbNotes_SelectionChanged"
Style="{StaticResource BaseComboBoxStyle}" /> Style="{StaticResource BaseComboBoxStyle}" />
</Border> </Border>
<Button <Button
x:Name="btnSearch" x:Name="btnSearch"
Grid.Row="4" Grid.Row="4"
Grid.Column="6" Grid.Column="6"
Height="26" Height="26"
Click="btnSearch_Click" Click="btnSearch_Click"
Content=" 搜索 " Content=" 搜索 "
Style="{StaticResource BasePageButtonStyle}" /> Style="{StaticResource BasePageButtonStyle}" />
<Button <Button
x:Name="btnRestore" x:Name="btnRestore"
Grid.Row="4" Grid.Row="4"
Grid.Column="7" Grid.Column="7"
Height="26" Height="26"
Margin="4,0,6,0" Margin="4,0,6,0"
Click="btnRestore_Click" Click="btnRestore_Click"
Content=" 还原 " Content=" 还原 "
Style="{StaticResource BasePageButtonLightStyle}" /> Style="{StaticResource BasePageButtonLightStyle}" />
</Grid> </Grid>
<Grid <Grid
x:Name="lstTitle" x:Name="lstTitle"
Grid.Row="1" Grid.Row="1"
Margin="4,0" Margin="4,0"
Background="{StaticResource ListHeadBackColorBrush}"> Background="{StaticResource ListHeadBackColorBrush}">
<Border BorderBrush="{StaticResource ListHeadBorderColorBrush}" BorderThickness="0,0,1,0"> <Border BorderBrush="{StaticResource ListHeadBorderColorBrush}" BorderThickness="0,0,1,0">
<DataGrid <DataGrid
x:Name="dgShopHeader" x:Name="dgShopHeader"
Grid.ColumnSpan="100" Grid.ColumnSpan="100"
Margin="0,0,18,0" Margin="0,0,18,0"
AutoGenerateColumns="False" AutoGenerateColumns="False"
BorderThickness="0" BorderThickness="0"
CanUserReorderColumns="False" CanUserReorderColumns="False"
ColumnDisplayIndexChanged="dgShopHeader_ColumnDisplayIndexChanged" ColumnDisplayIndexChanged="dgShopHeader_ColumnDisplayIndexChanged"
ColumnHeaderHeight="{Binding ElementName=lstTitle, Path=ActualHeight}" ColumnHeaderHeight="{Binding ElementName=lstTitle, Path=ActualHeight}"
LayoutUpdated="dgShopHeader_LayoutUpdated"> LayoutUpdated="dgShopHeader_LayoutUpdated">
<DataGrid.Columns> <DataGrid.Columns>
<DataGridTemplateColumn <DataGridTemplateColumn
x:Name="colSelectAll" x:Name="colSelectAll"
Width="50" Width="50"
Header="选择" Header="选择"
HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}"> HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}">
<DataGridTemplateColumn.HeaderTemplate> <DataGridTemplateColumn.HeaderTemplate>
<DataTemplate> <DataTemplate>
<Grid Width="14" Height="14"> <Grid Width="14" Height="14">
<!--<CheckBox x:Name="headerCheckBox" BorderThickness="0" IsChecked="{Binding DataContext.AreAllSelected, RelativeSource={RelativeSource AncestorType=DataGrid}, UpdateSourceTrigger=PropertyChanged}" Checked="HeaderCheckBox_Checked" Unchecked="HeaderCheckBox_Unchecked"/>--> <!--<CheckBox x:Name="headerCheckBox" BorderThickness="0" IsChecked="{Binding DataContext.AreAllSelected, RelativeSource={RelativeSource AncestorType=DataGrid}, UpdateSourceTrigger=PropertyChanged}" Checked="HeaderCheckBox_Checked" Unchecked="HeaderCheckBox_Unchecked"/>-->
<CheckBox <CheckBox
x:Name="chkSelectAll" x:Name="chkSelectAll"
BorderThickness="0" BorderThickness="0"
Checked="ChkSelectAll_Checked" Checked="ChkSelectAll_Checked"
IsChecked="False" IsChecked="False"
IsThreeState="True" IsThreeState="True"
Loaded="ChkSelectAll_Loaded" Loaded="ChkSelectAll_Loaded"
Unchecked="ChkSelectAll_Unchecked" /> Unchecked="ChkSelectAll_Unchecked" />
<Border <Border
Width="14" Width="14"
Height="14" Height="14"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Center" VerticalAlignment="Center"
Background="Transparent" Background="Transparent"
BorderBrush="{StaticResource mainColorBrush}" BorderBrush="{StaticResource mainColorBrush}"
BorderThickness="1" BorderThickness="1"
IsHitTestVisible="False" /> IsHitTestVisible="False" />
</Grid> </Grid>
</DataTemplate> </DataTemplate>
</DataGridTemplateColumn.HeaderTemplate> </DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellTemplate>
<DataTemplate> <DataTemplate>
<!--<CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center"/>--> <!--<CheckBox IsChecked="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center"/>-->
<CheckBox HorizontalAlignment="Center" VerticalAlignment="Center" /> <CheckBox HorizontalAlignment="Center" VerticalAlignment="Center" />
</DataTemplate> </DataTemplate>
</DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> </DataGridTemplateColumn>
<DataGridTextColumn <DataGridTextColumn
Width="100*" Width="50*"
Header="AppId" Header="序号"
HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" /> HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" />
<DataGridTextColumn <DataGridTextColumn
Width="100*" Width="100*"
Header="店铺名称" Header="AppId"
HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" /> HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" />
<DataGridTextColumn <DataGridTextColumn
Width="100*" Width="100*"
Header="分组" Header="店铺编号"
HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" /> HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" />
<DataGridTextColumn <DataGridTextColumn
Width="82*" Width="100*"
Header=" 备注" Header="店铺名称"
HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" /> HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" />
</DataGrid.Columns> <DataGridTextColumn
</DataGrid> Width="100*"
</Border> Header="分组"
</Grid> HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" />
<!--<ListBox Grid.Row="2" x:Name="lbxShop" ItemsSource="{Binding GlobalConfig.ShopLoginList}" BorderThickness="0" Margin="4,0,4,4">--> <DataGridTextColumn
<ListBox Width="82*"
x:Name="lbxShop" Header=" 备注"
Grid.Row="2" HeaderStyle="{StaticResource BaseDataGridColumnHeaderStyle}" />
Margin="4,0,4,4" </DataGrid.Columns>
BorderThickness="0" </DataGrid>
SelectionMode="Extended"> </Border>
<!-- 使用自定义属性模板去除ListBox高亮显示框 --> </Grid>
<ListBox.ItemContainerStyle> <!--<ListBox Grid.Row="2" x:Name="lbxShop" ItemsSource="{Binding GlobalConfig.ShopLoginList}" BorderThickness="0" Margin="4,0,4,4">-->
<Style TargetType="ListBoxItem"> <ListBox
<Setter Property="Template"> x:Name="lbxShop"
<Setter.Value> Grid.Row="2"
<ControlTemplate TargetType="ListBoxItem"> Margin="4,0,4,4"
<ContentPresenter BorderThickness="0"
Content="{TemplateBinding Content}" SelectionMode="Extended">
ContentStringFormat="{TemplateBinding ContentStringFormat}" <!-- 使用自定义属性模板去除ListBox高亮显示框 -->
ContentTemplate="{TemplateBinding ContentTemplate}" /> <ListBox.ItemContainerStyle>
</ControlTemplate> <Style TargetType="ListBoxItem">
</Setter.Value> <Setter Property="Template">
</Setter> <Setter.Value>
</Style> <ControlTemplate TargetType="ListBoxItem">
</ListBox.ItemContainerStyle> <ContentPresenter
<ListBox.ItemTemplate> Content="{TemplateBinding Content}"
<DataTemplate> ContentStringFormat="{TemplateBinding ContentStringFormat}"
<!--<local:ShopListRowCtrl></local:ShopListRowCtrl>--> ContentTemplate="{TemplateBinding ContentTemplate}" />
<Border </ControlTemplate>
MinHeight="50" </Setter.Value>
Margin="0,0,0,0" </Setter>
HorizontalAlignment="Stretch" </Style>
VerticalAlignment="Stretch" </ListBox.ItemContainerStyle>
BorderBrush="{StaticResource ListRowBorderColorBrush}" <ListBox.ItemTemplate>
BorderThickness="0,0,0,1" <DataTemplate>
CornerRadius="0"> <!--<local:ShopListRowCtrl></local:ShopListRowCtrl>-->
<Border.Style> <Border
<!-- 鼠标进入或悬停Border时切换颜色(悬停时Border的填充控件必须有填充Border,所在层级不限,仅填充透明Grid则触发器无效) --> MinHeight="50"
<Style TargetType="Border"> Margin="0,0,0,0"
<Style.Triggers> HorizontalAlignment="Stretch"
<Trigger Property="IsMouseOver" Value="True"> VerticalAlignment="Stretch"
<Setter Property="Background" Value="{StaticResource ListRowHoverBackColorBrush}" /> BorderBrush="{StaticResource ListRowBorderColorBrush}"
</Trigger> BorderThickness="0,0,0,1"
</Style.Triggers> CornerRadius="0">
</Style> <Border.Style>
</Border.Style> <!-- 鼠标进入或悬停Border时切换颜色(悬停时Border的填充控件必须有填充Border,所在层级不限,仅填充透明Grid则触发器无效) -->
<Style TargetType="Border">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource ListRowHoverBackColorBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<Grid x:Name="gridListItem"> <Grid x:Name="gridListItem">
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<!--<ColumnDefinition Width="{Binding colShopIdWidth,RelativeSource={RelativeSource AncestorType={x:Type local:ShopListCtrl}}}" ></ColumnDefinition>--> <!--<ColumnDefinition Width="{Binding colShopIdWidth,RelativeSource={RelativeSource AncestorType={x:Type local:ShopListCtrl}}}" ></ColumnDefinition>-->
<ColumnDefinition x:Name="colCheck" Width="100*" /> <ColumnDefinition x:Name="colCheck" Width="50*" />
<ColumnDefinition x:Name="colShopId" Width="100*" /> <ColumnDefinition x:Name="colIndex" Width="50*" />
<ColumnDefinition x:Name="colShopName" Width="100*" /> <ColumnDefinition x:Name="colAppId" Width="100*" />
<ColumnDefinition x:Name="colGroupName" Width="100*" /> <ColumnDefinition x:Name="colShopId" Width="100*" />
<ColumnDefinition x:Name="colNotes" Width="100*" /> <ColumnDefinition x:Name="colShopName" Width="100*" />
</Grid.ColumnDefinitions> <ColumnDefinition x:Name="colGroupName" Width="100*" />
<CheckBox <ColumnDefinition x:Name="colNotes" Width="100*" />
Grid.Column="0" </Grid.ColumnDefinitions>
HorizontalAlignment="Center" <CheckBox
VerticalAlignment="Center" Grid.Column="0"
Background="Transparent" HorizontalAlignment="Center"
Click="CheckBox_Click" VerticalAlignment="Center"
IsChecked="{Binding IsSelect, Mode=TwoWay}" Background="Transparent"
Tag="{Binding ShopId}" /> Click="CheckBox_Click"
<TextBox IsChecked="{Binding IsSelect, Mode=TwoWay}"
Grid.Column="1" Tag="{Binding ShopId}" />
HorizontalContentAlignment="Center" <TextBox
VerticalContentAlignment="Center" Grid.Column="1"
Background="Transparent" HorizontalContentAlignment="Center"
BorderThickness="0" VerticalContentAlignment="Center"
IsReadOnly="True" Background="Transparent"
Tag="{Binding ShopId}" BorderThickness="0"
Text="{Binding ShopId}" IsReadOnly="True"
TextWrapping="Wrap" /> Text="{Binding Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Converter={StaticResource listBoxIndexConverter}}"
<TextBox TextWrapping="Wrap" />
Grid.Column="2" <TextBox
HorizontalContentAlignment="Center" Grid.Column="2"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center"
Background="Transparent" VerticalContentAlignment="Center"
BorderThickness="0" Background="Transparent"
IsReadOnly="True" BorderThickness="0"
Tag="{Binding ShopId}" IsReadOnly="True"
Text="{Binding ShopAccount}" Tag="{Binding ShopId}"
TextWrapping="Wrap" /> Text="{Binding ShopId}"
<TextBox TextWrapping="Wrap" />
Grid.Column="3" <TextBox
HorizontalContentAlignment="Center" Grid.Column="3"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center"
Background="Transparent" VerticalContentAlignment="Center"
BorderThickness="0" Background="Transparent"
IsReadOnly="True" BorderThickness="0"
Tag="{Binding ShopId}" IsReadOnly="True"
Text="{Binding GroupName}" Tag="{Binding ErpShopId}"
TextWrapping="Wrap" /> Text="{Binding ErpShopId}"
<TextBox TextWrapping="Wrap" />
Grid.Column="4" <TextBox
HorizontalContentAlignment="Center" Grid.Column="4"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center"
Background="Transparent" VerticalContentAlignment="Center"
BorderThickness="0" Background="Transparent"
IsReadOnly="True" BorderThickness="0"
Tag="{Binding ShopId}" IsReadOnly="True"
Text="{Binding Notes}" Tag="{Binding ShopId}"
TextWrapping="Wrap" /> Text="{Binding ShopAccount}"
</Grid> TextWrapping="Wrap" />
</Border> <TextBox
</DataTemplate> Grid.Column="5"
</ListBox.ItemTemplate> HorizontalContentAlignment="Center"
</ListBox> VerticalContentAlignment="Center"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Tag="{Binding ShopId}"
Text="{Binding GroupName}"
TextWrapping="Wrap" />
<TextBox
Grid.Column="6"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
Tag="{Binding ShopId}"
Text="{Binding Notes}"
TextWrapping="Wrap" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid x:Name="gridRefreshOrSelect" Grid.Row="3"> <Grid x:Name="gridRefreshOrSelect" Grid.Row="3">
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" /> <ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Button <Button
x:Name="btnRefreshShop" x:Name="btnRefreshShop"
Grid.Row="4" Grid.Row="4"
Grid.Column="0" Grid.Column="0"
Height="26" Height="26"
Margin="6,0,0,0" Margin="6,0,0,0"
Click="btnRefreshShop_Click" Click="btnRefreshShop_Click"
Content=" 刷新店铺 " Content=" 刷新店铺 "
Style="{StaticResource BasePageButtonStyle}" /> Style="{StaticResource BasePageButtonStyle}" />
<Button <Button
x:Name="btnApplySelectShop" x:Name="btnApplySelectShop"
Grid.Row="4" Grid.Row="4"
Grid.Column="6" Grid.Column="6"
Height="26" Height="26"
Click="btnApplySelectShop_Click" Click="btnApplySelectShop_Click"
Content=" 确定 " Content=" 确定 "
Style="{StaticResource BasePageButtonStyle}" /> Style="{StaticResource BasePageButtonStyle}" />
<Button <Button
x:Name="btnCancelSelectShop" x:Name="btnCancelSelectShop"
Grid.Row="4" Grid.Row="4"
Grid.Column="7" Grid.Column="7"
Height="26" Height="26"
Margin="4,0,6,0" Margin="4,0,6,0"
Click="btnCancelSelectShop_Click" Click="btnCancelSelectShop_Click"
Content=" 取消 " Content=" 取消 "
Style="{StaticResource BasePageButtonLightStyle}" /> Style="{StaticResource BasePageButtonLightStyle}" />
</Grid> </Grid>
</Grid> </Grid>
</UserControl> </UserControl>
@@ -23,6 +23,10 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Models
/// 空/Null 表示全部店铺(服务层会取全部店铺的 ErpShopId)。 /// 空/Null 表示全部店铺(服务层会取全部店铺的 ErpShopId)。
/// </summary> /// </summary>
public List<string> ShopIds { get; set; } public List<string> ShopIds { get; set; }
/// <summary>
/// 是否统计快递费用
/// </summary>
public bool StatPackages { get; set; }
} }
/// <summary> /// <summary>
@@ -111,6 +115,10 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Models
/// 被拒绝金额(分) /// 被拒绝金额(分)
/// </summary> /// </summary>
public long RejectedRefund { get; set; } public long RejectedRefund { get; set; }
/// <summary>
/// 包裹费用
/// </summary>
public long PackageAmount { get; set; }
} }
/// <summary> /// <summary>
@@ -199,6 +207,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Models
/// </summary> /// </summary>
public int UnrefundedAmount { get; set; } public int UnrefundedAmount { get; set; }
public long PackageAmount { get; set; }
/// <summary> /// <summary>
/// 买手订单信息(一个订单号对应多个买手订单) /// 买手订单信息(一个订单号对应多个买手订单)
/// </summary> /// </summary>
@@ -288,6 +297,10 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Models
public decimal BuyerRefundSuccessedAmount { get; set; } public decimal BuyerRefundSuccessedAmount { get; set; }
/// <summary>买手号剩余退款金额(尚未成功退款的金额,元)</summary> /// <summary>买手号剩余退款金额(尚未成功退款的金额,元)</summary>
public decimal BuyerRefundRemainingAmount => BuyerRefundAmount - BuyerRefundSuccessedAmount; public decimal BuyerRefundRemainingAmount => BuyerRefundAmount - BuyerRefundSuccessedAmount;
/// <summary>
/// 包裹费用
/// </summary>
public decimal PackageAmount { get; set; }
} }
/// <summary> /// <summary>
@@ -355,6 +368,10 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Models
/// <summary>平均利润率(利润 / 采购金额,百分数,如 12.34 表示 12.34%)</summary> /// <summary>平均利润率(利润 / 采购金额,百分数,如 12.34 表示 12.34%)</summary>
public decimal AverageProfitRate { get; set; } public decimal AverageProfitRate { get; set; }
/// <summary>
/// 包裹费用
/// </summary>
public decimal PackageAmount { get; set; }
} }
/// <summary> /// <summary>
@@ -6,6 +6,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:_29WxOrderWpf.Ctrls.Statistics.ViewModels" xmlns:vm="clr-namespace:_29WxOrderWpf.Ctrls.Statistics.ViewModels"
xmlns:wpf="WPFCommon"
d:DataContext="{d:DesignInstance Type=vm:ShopRevenueStatisticsViewModel, d:DataContext="{d:DesignInstance Type=vm:ShopRevenueStatisticsViewModel,
IsDesignTimeCreatable=True}" IsDesignTimeCreatable=True}"
mc:Ignorable="d"> mc:Ignorable="d">
@@ -48,9 +49,9 @@
Width="110" Width="110"
Height="32" Height="32"
VerticalContentAlignment="Center" VerticalContentAlignment="Center"
BorderThickness="1"
DisplayMemberPath="Text" DisplayMemberPath="Text"
IsReadOnly="True" IsReadOnly="True"
BorderThickness="1"
ItemsSource="{Binding TimeRangeOptions}" ItemsSource="{Binding TimeRangeOptions}"
SelectedItem="{Binding SelectedTimeRange, Mode=TwoWay}" SelectedItem="{Binding SelectedTimeRange, Mode=TwoWay}"
Style="{StaticResource RoundedComboBox}" /> Style="{StaticResource RoundedComboBox}" />
@@ -60,9 +61,10 @@
FontSize="14" FontSize="14"
Foreground="#666666" Foreground="#666666"
Text="日期" /> Text="日期" />
<DatePicker BorderBrush="{StaticResource pageColorBrush}" <DatePicker
Height="32" Height="32"
VerticalContentAlignment="Center" VerticalContentAlignment="Center"
BorderBrush="{StaticResource pageColorBrush}"
SelectedDate="{Binding StartDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> SelectedDate="{Binding StartDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock <TextBlock
Margin="6,0" Margin="6,0"
@@ -70,9 +72,10 @@
FontSize="14" FontSize="14"
Foreground="#666666" Foreground="#666666"
Text="~" /> Text="~" />
<DatePicker BorderBrush="{StaticResource pageColorBrush}" <DatePicker
Height="32" Height="32"
VerticalContentAlignment="Center" VerticalContentAlignment="Center"
BorderBrush="{StaticResource pageColorBrush}"
SelectedDate="{Binding EndDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> SelectedDate="{Binding EndDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock <TextBlock
Margin="14,0,6,0" Margin="14,0,6,0"
@@ -95,6 +98,14 @@
ItemsSource="{Binding ShopOptions}" ItemsSource="{Binding ShopOptions}"
SelectedItem="{Binding SelectedShop, Mode=TwoWay}" SelectedItem="{Binding SelectedShop, Mode=TwoWay}"
Style="{StaticResource BaseComboBoxStyle}" />--> Style="{StaticResource BaseComboBoxStyle}" />-->
<wpf:TitleContent
Title="去除快递费"
Margin="10,0,0,0"
VerticalContentAlignment="Center"
Placement="Left"
TitleVerticalAlignment="Center">
<CheckBox IsChecked="{Binding StatPackages}" Style="{StaticResource ToggleSwitch}" />
</wpf:TitleContent>
<Button <Button
Height="32" Height="32"
Margin="18,0,0,0" Margin="18,0,0,0"
@@ -108,7 +108,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Services
decimal buyerPaymentAmount = ToYuan(list.Sum(a => a.TotalPurchase)); decimal buyerPaymentAmount = ToYuan(list.Sum(a => a.TotalPurchase));
decimal buyerRefundAmount = ToYuan(list.Sum(a => a.TotalRefund)); decimal buyerRefundAmount = ToYuan(list.Sum(a => a.TotalRefund));
decimal buyerRefundSuccessedAmount = ToYuan(list.Sum(a => a.DoneRefund)); decimal buyerRefundSuccessedAmount = ToYuan(list.Sum(a => a.DoneRefund));
decimal packageAmount = ToYuan(list.Sum(a => a.PackageAmount));
int validOrderCount = list.Sum(a => a.OrderCount); // 新接口 OrderCount 不含退款订单 int validOrderCount = list.Sum(a => a.OrderCount); // 新接口 OrderCount 不含退款订单
int refundOrderCount = list.Sum(a => a.RefundOrderCount); int refundOrderCount = list.Sum(a => a.RefundOrderCount);
int totalOrderCount = validOrderCount + refundOrderCount; int totalOrderCount = validOrderCount + refundOrderCount;
@@ -128,6 +128,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Services
BuyerPaymentAmount = buyerPaymentAmount, BuyerPaymentAmount = buyerPaymentAmount,
BuyerRefundAmount = buyerRefundAmount, BuyerRefundAmount = buyerRefundAmount,
BuyerRefundSuccessedAmount = buyerRefundSuccessedAmount, BuyerRefundSuccessedAmount = buyerRefundSuccessedAmount,
PackageAmount = packageAmount
}; };
} }
@@ -248,7 +249,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Services
decimal profit = ToYuan(list.Sum(a => a.ProfitAmount)); decimal profit = ToYuan(list.Sum(a => a.ProfitAmount));
decimal buyerPaymentAmount = ToYuan(list.Sum(a => a.TotalPurchase)); decimal buyerPaymentAmount = ToYuan(list.Sum(a => a.TotalPurchase));
int orderCount = list.Sum(a => a.OrderCount); int orderCount = list.Sum(a => a.OrderCount);
decimal packageAmount = ToYuan(list.Sum(a => a.PackageAmount));
return new ShopStatisticsItem return new ShopStatisticsItem
{ {
ShopName = ResolveShopName(shopId), ShopName = ResolveShopName(shopId),
@@ -260,7 +261,8 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Services
PlatformFeeTotal = ToYuan(list.Sum(a => a.PlatformFee)), PlatformFeeTotal = ToYuan(list.Sum(a => a.PlatformFee)),
Commission = 0m, // 新接口无“达人佣金”字段,保留占位 Commission = 0m, // 新接口无“达人佣金”字段,保留占位
AvgOrderAmount = orderCount == 0 ? 0m : salesAmount / orderCount, AvgOrderAmount = orderCount == 0 ? 0m : salesAmount / orderCount,
AverageProfitRate = buyerPaymentAmount == 0m ? 0m : profit / buyerPaymentAmount * 100m AverageProfitRate = buyerPaymentAmount == 0m ? 0m : profit / buyerPaymentAmount * 100m,
PackageAmount = packageAmount
}; };
} }
@@ -385,7 +387,13 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Services
// 顺序请求:签名中的 time/code 由当前时间生成,并发请求有被判重复签名的风险。 // 顺序请求:签名中的 time/code 由当前时间生成,并发请求有被判重复签名的风险。
var summaryStats = await RequestStatsAsync(query, ShopStatsGroupType.Summary); var summaryStats = await RequestStatsAsync(query, ShopStatsGroupType.Summary);
var trend = await RequestTrendAsync(query); var trend = await RequestTrendAsync(query);
if (query.StatPackages)
{
foreach (var item in summaryStats)
{
item.ProfitAmount -= item.PackageAmount;
}
}
return new ShopRevenueStatisticsResult return new ShopRevenueStatisticsResult
{ {
Summary = ShopStatsAggregator.GetSummary(summaryStats), Summary = ShopStatsAggregator.GetSummary(summaryStats),
@@ -399,7 +407,13 @@ namespace _29WxOrderWpf.Ctrls.Statistics.Services
{ {
// 按天/周/月粒度取数;接口不返回整段汇总,卡片由返回的周期记录在客户端合计 // 按天/周/月粒度取数;接口不返回整段汇总,卡片由返回的周期记录在客户端合计
var stats = await RequestStatsAsync(query, ToGroupType(periodType)); var stats = await RequestStatsAsync(query, ToGroupType(periodType));
if (query.StatPackages)
{
foreach (var item in stats)
{
item.ProfitAmount -= item.PackageAmount;
}
}
return new ShopPeriodStatisticsResult return new ShopPeriodStatisticsResult
{ {
Summary = ShopStatsAggregator.GetSummary(stats), Summary = ShopStatsAggregator.GetSummary(stats),
@@ -274,30 +274,32 @@
</TabItem> </TabItem>
</TabControl> </TabControl>
<!-- helper --> <!-- helper -->
<Border
Margin="0,20,30,0"
Padding="10"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Background="{StaticResource pageColorBrush}"
BorderThickness="1"
Cursor="Hand"
MouseLeftButtonDown="help_mouseLeftButtonDown">
<WrapPanel>
<TextBlock
Margin="0,0,10,0"
Foreground="White"
Style="{StaticResource TextBlockIcon}"
Text="{StaticResource txt-chat_help}" />
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontWeight="Black"
Foreground="White"
Text="利润计算逻辑" />
</WrapPanel>
</Border>
<WrapPanel
Margin="0,20,30,0"
HorizontalAlignment="Right"
VerticalAlignment="Top">
<Border
Padding="10"
Background="{StaticResource pageColorBrush}"
BorderThickness="1"
Cursor="Hand"
MouseLeftButtonDown="help_mouseLeftButtonDown">
<WrapPanel>
<TextBlock
Margin="0,0,10,0"
Foreground="White"
Style="{StaticResource TextBlockIcon}"
Text="{StaticResource txt-chat_help}" />
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontWeight="Black"
Foreground="White"
Text="利润计算逻辑" />
</WrapPanel>
</Border>
</WrapPanel>
<!-- Popup 弹出层 --> <!-- Popup 弹出层 -->
<Popup <Popup
x:Name="InfoPopup" x:Name="InfoPopup"
@@ -157,7 +157,11 @@
Binding="{Binding ProfitAmount, Converter={StaticResource FenToYuanConverter}, StringFormat={}¥{0:N2}}" Binding="{Binding ProfitAmount, Converter={StaticResource FenToYuanConverter}, StringFormat={}¥{0:N2}}"
ElementStyle="{StaticResource CenterCellTextStyle}" ElementStyle="{StaticResource CenterCellTextStyle}"
Header="利润" /> Header="利润" />
<DataGridTextColumn
Width="*"
Binding="{Binding PackageAmount, Converter={StaticResource FenToYuanConverter}, StringFormat={}¥{0:N2}}"
ElementStyle="{StaticResource CenterCellTextStyle}"
Header="快递费" />
<!-- 买手订单:一笔买手订单占一行,不合并 --> <!-- 买手订单:一笔买手订单占一行,不合并 -->
<DataGridTextColumn <DataGridTextColumn
Width="1.6*" Width="1.6*"
@@ -166,7 +166,10 @@ class ShopOrderDetailRow : BindableBaseEx
/// 利润 /// 利润
/// </summary> /// </summary>
public long ProfitAmount { get; set; } public long ProfitAmount { get; set; }
/// <summary>
/// 包裹费用
/// </summary>
public long PackageAmount { get; set; }
/// <summary> /// <summary>
/// 平台佣金 /// 平台佣金
/// </summary> /// </summary>
@@ -246,6 +249,7 @@ class ShopOrderDetailRow : BindableBaseEx
OrderPrice = item.OrderPrice, OrderPrice = item.OrderPrice,
OrderRefundAmount = item.OrderRefundAmount, OrderRefundAmount = item.OrderRefundAmount,
ProfitAmount = item.ProfitAmount, ProfitAmount = item.ProfitAmount,
PackageAmount = item.PackageAmount,
PlatformFee = item.PlatformFee, PlatformFee = item.PlatformFee,
OutAmount = item.OutAmount, OutAmount = item.OutAmount,
UnrefundedAmount = item.UnrefundedAmount, UnrefundedAmount = item.UnrefundedAmount,
@@ -411,7 +415,7 @@ class ShowOrderDialogViewModel : BindableBaseEx
bool includeRemark = _detailType == ShopOrderDetailType.BuyerUnrefunded; bool includeRemark = _detailType == ShopOrderDetailType.BuyerUnrefunded;
// 表头 // 表头
List<string> headers = ["店名", "订单", "创建时间", "金额", "退款金额", "平台费用", "利润", "买手单号", "外采金额", "买手退款", "退款状态"]; List<string> headers = ["店名", "订单", "创建时间", "金额", "退款金额", "平台费用", "利润","快递费", "买手单号", "外采金额", "买手退款", "退款状态"];
if (includeRemark) if (includeRemark)
headers.Add("备注"); headers.Add("备注");
sb.AppendLine(string.Join("\t", headers)); sb.AppendLine(string.Join("\t", headers));
@@ -428,6 +432,7 @@ class ShowOrderDialogViewModel : BindableBaseEx
(item.OrderRefundAmount / 100m).ToString("0.00"), (item.OrderRefundAmount / 100m).ToString("0.00"),
(item.PlatformFee / 100m).ToString("0.00"), (item.PlatformFee / 100m).ToString("0.00"),
(item.ProfitAmount / 100m).ToString("0.00"), (item.ProfitAmount / 100m).ToString("0.00"),
(item.PackageAmount / 100m).ToString("0.00"),
CsvEscape(item.OutOrderSn), CsvEscape(item.OutOrderSn),
(item.BuyerOutAmount / 100m).ToString("0.00"), (item.BuyerOutAmount / 100m).ToString("0.00"),
(item.BuyerRefundAmount / 100m).ToString("0.00"), (item.BuyerRefundAmount / 100m).ToString("0.00"),
@@ -177,7 +177,11 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
#endregion #endregion
#region 查询条件 #region 查询条件
public bool StatPackages
{
get { return this.GetValue(x => x.StatPackages); }
set { this.SetValue(x => x.StatPackages, value); }
}
/// <summary>时间范围选项</summary> /// <summary>时间范围选项</summary>
public ObservableCollection<TimeRangeOption> TimeRangeOptions { get; } public ObservableCollection<TimeRangeOption> TimeRangeOptions { get; }
@@ -455,20 +459,20 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
EndDate = now; EndDate = now;
break; break;
case "week": case "week":
{ {
int diff = today.DayOfWeek == DayOfWeek.Sunday ? 6 : (int)today.DayOfWeek - 1; int diff = today.DayOfWeek == DayOfWeek.Sunday ? 6 : (int)today.DayOfWeek - 1;
StartDate = today.AddDays(-diff); StartDate = today.AddDays(-diff);
EndDate = now; EndDate = now;
} }
break; break;
case "lastweek": case "lastweek":
{ {
int diff = today.DayOfWeek == DayOfWeek.Sunday ? 6 : (int)today.DayOfWeek - 1; int diff = today.DayOfWeek == DayOfWeek.Sunday ? 6 : (int)today.DayOfWeek - 1;
var thisWeekStart = today.AddDays(-diff); var thisWeekStart = today.AddDays(-diff);
StartDate = thisWeekStart.AddDays(-7); StartDate = thisWeekStart.AddDays(-7);
EndDate = thisWeekStart.AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59); EndDate = thisWeekStart.AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
} }
break; break;
case "last2weeks": case "last2weeks":
StartDate = today.AddDays(-13); StartDate = today.AddDays(-13);
EndDate = now; EndDate = now;
@@ -482,12 +486,12 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
EndDate = now; EndDate = now;
break; break;
case "lastmonth": case "lastmonth":
{ {
var firstOfThisMonth = new DateTime(today.Year, today.Month, 1); var firstOfThisMonth = new DateTime(today.Year, today.Month, 1);
StartDate = firstOfThisMonth.AddMonths(-1); StartDate = firstOfThisMonth.AddMonths(-1);
EndDate = firstOfThisMonth.AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59); EndDate = firstOfThisMonth.AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
} }
break; break;
case "last3months": case "last3months":
StartDate = new DateTime(today.Year, today.Month, 1).AddMonths(-2); StartDate = new DateTime(today.Year, today.Month, 1).AddMonths(-2);
EndDate = now; EndDate = now;
@@ -541,6 +545,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
StartDate = StartDate, StartDate = StartDate,
EndDate = EndDate, EndDate = EndDate,
ShopIds = BuildSelectedShopIds(), ShopIds = BuildSelectedShopIds(),
StatPackages = StatPackages
}; };
} }
@@ -61,6 +61,11 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
InitializeAsync(); InitializeAsync();
} }
public bool StatPackages
{
get { return this.GetValue(x => x.StatPackages); }
set { this.SetValue(x => x.StatPackages, value); }
}
#region 查询条件 #region 查询条件
@@ -288,6 +293,7 @@ namespace _29WxOrderWpf.Ctrls.Statistics.ViewModels
StartDate = StartDate, StartDate = StartDate,
EndDate = EndDate, EndDate = EndDate,
ShopIds = BuildSelectedShopIds(), ShopIds = BuildSelectedShopIds(),
StatPackages = StatPackages,
}; };
} }
+63 -22
View File
@@ -60,6 +60,47 @@
Grid.Column="2" Grid.Column="2"
HorizontalAlignment="Right" HorizontalAlignment="Right"
VerticalAlignment="Center"> VerticalAlignment="Center">
<Button
x:Name="btOrderSupport"
Click="bt_showOrderSupport"
IsEnabled="False"
Style="{StaticResource IconButtonStyle}"
ToolTip="客户工单">
<Grid Width="30" Height="30">
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="22"
Foreground="{StaticResource mainColorLightBrush}"
Style="{StaticResource TextBlockIcon}"
Text="{StaticResource txt-alert}" />
<Border
x:Name="borderOrderSupportUnread"
Height="16"
MinWidth="16"
Padding="4,0"
HorizontalAlignment="Right"
VerticalAlignment="Top"
d:Visibility="Visible"
Background="#E53935"
CornerRadius="8"
Visibility="Collapsed">
<TextBlock
x:Name="tbOrderSupportUnread"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="10"
FontWeight="Bold"
Foreground="White"
Text="0" />
</Border>
</Grid>
</Button>
<Border
Width="1"
Height="20"
Margin="10,0"
Background="#b893b2" />
<Button Click="bt_setting" Style="{StaticResource IconButtonStyle}"> <Button Click="bt_setting" Style="{StaticResource IconButtonStyle}">
<TextBlock <TextBlock
FontSize="22" FontSize="22"
@@ -141,31 +182,31 @@
Background="#7F000000" Background="#7F000000"
MouseLeftButtonUp="gridPddBuyerOrderReadCtrl_MouseLeftButtonUp" MouseLeftButtonUp="gridPddBuyerOrderReadCtrl_MouseLeftButtonUp"
Visibility="Hidden"> Visibility="Hidden">
<Border <Border
Height="auto" Height="auto"
Margin="0,50,0,0" Margin="0,50,0,0"
HorizontalAlignment="Right" HorizontalAlignment="Right"
Background="White" Background="White"
CornerRadius="10"> CornerRadius="10">
<Grid> <Grid>
<buyerctrls:PDDBuyerOrderReadCtrl <buyerctrls:PDDBuyerOrderReadCtrl
x:Name="pddBuyerOrderReadCtrl" x:Name="pddBuyerOrderReadCtrl"
Grid.Column="1" Grid.Column="1"
Width="1200" Width="1200"
HorizontalAlignment="Right" HorizontalAlignment="Right"
Panel.ZIndex="-1" Panel.ZIndex="-1"
d:Visibility="Visible" d:Visibility="Visible"
Visibility="Collapsed" /> Visibility="Collapsed" />
<buyerctrls:TbBuyerOrderReadCtrl <buyerctrls:TbBuyerOrderReadCtrl
x:Name="tbBuyerOrderReadCtrl" x:Name="tbBuyerOrderReadCtrl"
Grid.Column="1" Grid.Column="1"
Width="1200" Width="1200"
HorizontalAlignment="Right" HorizontalAlignment="Right"
Panel.ZIndex="-1" Panel.ZIndex="-1"
d:Visibility="Collapsed" d:Visibility="Collapsed"
Visibility="Collapsed" /> Visibility="Collapsed" />
</Grid> </Grid>
</Border> </Border>
</Grid> </Grid>
<buyerctrls:PDDBuyerSelectCtrl <buyerctrls:PDDBuyerSelectCtrl
x:Name="pddBuyerSelectCtrl" x:Name="pddBuyerSelectCtrl"
@@ -181,8 +222,8 @@
Background="#7F000000" Background="#7F000000"
Visibility="Hidden"> Visibility="Hidden">
<Border <Border
Width="500" Width="850"
Height="600" Height="650"
Background="White" Background="White"
CornerRadius="4"> CornerRadius="4">
<shopctrls:ShopListCtrl <shopctrls:ShopListCtrl
+514 -304
View File
@@ -14,6 +14,9 @@ using CefSharp;
using NaiBa.Util; using NaiBa.Util;
using NaiBa.Util.Extension; using NaiBa.Util.Extension;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using OrderSupportTicket.Models;
using OrderSupportTicket.Services;
using OrderSupportTicket.Views;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
@@ -41,249 +44,267 @@ using System.Xml.Linq;
using Work; using Work;
using Work._29Tools.BLL; using Work._29Tools.BLL;
using Work._29Tools.Forms.UserForms; using Work._29Tools.Forms.UserForms;
using WxOrder.Framework.Commons;
using WxOrder.Framework.Commons.Dialogs;
using WxOrder.Framework.Helpers;
using static System.Windows.Forms.VisualStyles.VisualStyleElement; using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
namespace _29WxOrderWpf namespace _29WxOrderWpf
{ {
/// <summary> /// <summary>
/// MainWindow.xaml 的交互逻辑 /// MainWindow.xaml 的交互逻辑
/// </summary> /// </summary>
public partial class MainWindow : BaseWindow, INotifyPropertyChanged public partial class MainWindow : BaseWindow, INotifyPropertyChanged
{ {
public static MainWindow Instance { get; private set; } public static MainWindow Instance { get; private set; }
public static readonly object _orderLock = new object();
public event PropertyChangedEventHandler PropertyChanged; private readonly TicketRealtimeMonitor _ticketMonitor = TicketRealtimeMonitor.Current;
public string Balance { get { return "快递余额:" + BaseClass.Balance.ToString("0.00"); } set { OnPropertyChanged("Balance"); } } private readonly WorkOrderUnreadService _workOrderUnreadService = new WorkOrderUnreadService();
private TicketClientOptions _ticketOptions;
private OrderSupportTicketView _orderSupportView;
public MainWindow() public event PropertyChangedEventHandler PropertyChanged;
{ public string Balance { get { return "快递余额:" + BaseClass.Balance.ToString("0.00"); } set { OnPropertyChanged("Balance"); } }
InitializeComponent();
this.DataContext = this;
Instance = this;
gridUser.Visibility = Visibility.Collapsed; public MainWindow()
} {
InitializeComponent();
this.DataContext = this;
Instance = this;
private void Window_Loaded(object sender, RoutedEventArgs e) gridUser.Visibility = Visibility.Collapsed;
{
GlobalConfig.Dispatcher = this.Dispatcher;
lblDebug.Visibility = Visibility.Collapsed;
ucWindowBox.SetWindowMax(); _ticketMonitor.NewMessageReceived += OnTicketNewMessageReceived;
this.Title = BaseClass.ToolName; _ticketMonitor.UnreadCountChanged += OnTicketUnreadCountChanged;
Closed += MainWindow_Closed;
}
new Thread(AutoAntiGrabbingMechanism).Start(); // 反抓包 private void Window_Loaded(object sender, RoutedEventArgs e)
{
GlobalConfig.Dispatcher = this.Dispatcher;
lblDebug.Visibility = Visibility.Collapsed;
#region 弹出登录窗口 ucWindowBox.SetWindowMax();
LoginWindow loginWindow = new LoginWindow(App.args); this.Title = BaseClass.ToolName;
loginWindow.Owner = this;
loginWindow.ShowDialog();
#endregion
if (loginWindow.IsLogin) new Thread(AutoAntiGrabbingMechanism).Start(); // 反抓包
{
lblVersion.Content = BaseClass.ToolName + " V" + BaseClass.Varsion + " - " + BaseClass.NickName;
//shopListCtrl.Visibility = Visibility.Visible; #region 弹出登录窗口
orderListCtrl.Visibility = Visibility.Visible; LoginWindow loginWindow = new LoginWindow(App.args);
loginWindow.Owner = this;
loginWindow.ShowDialog();
#endregion
if (loginWindow.IsLogin)
{
lblVersion.Content = BaseClass.ToolName + " V" + BaseClass.Varsion + " - " + BaseClass.NickName;
//shopListCtrl.Visibility = Visibility.Visible;
orderListCtrl.Visibility = Visibility.Visible;
pddBuyerOrderReadCtrl.Visibility = Visibility.Visible; pddBuyerOrderReadCtrl.Visibility = Visibility.Visible;
tbBuyerOrderReadCtrl.Visibility = Visibility.Visible; tbBuyerOrderReadCtrl.Visibility = Visibility.Visible;
pddBuyerSelectCtrl.Visibility = Visibility.Visible; pddBuyerSelectCtrl.Visibility = Visibility.Visible;
Task.Run(() => Task.Run(async () =>
{ {
GetServerShop(); GetServerShop();
await StartTicketRealtimeMonitor();//启动工单监控
GetShopSupplier(GlobalConfig.ShopLoginList.ToList()); GetShopSupplier(GlobalConfig.ShopLoginList.ToList());
}); });
Task.Run(() => Task.Run(() =>
{ {
GetPddBuyer(); GetPddBuyer();
GetTaobaoBuyer(); GetTaobaoBuyer();
}); });
} }
} }
protected virtual void OnPropertyChanged(string propertyName) protected virtual void OnPropertyChanged(string propertyName)
{ {
if (this.PropertyChanged != null)//有改变 if (this.PropertyChanged != null)//有改变
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
} }
#region 反抓包功能 #region 反抓包功能
private void AutoAntiGrabbingMechanism() private void AutoAntiGrabbingMechanism()
{ {
while (true) while (true)
{ {
#if DEBUG #if DEBUG
#else #else
AntiGrabbingMechanism(); AntiGrabbingMechanism();
#endif #endif
try { Thread.Sleep(3000); } catch { } try { Thread.Sleep(3000); } catch { }
} }
} }
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)] [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)] [return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process); internal static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process);
private List<string> _AntiProcesses = "WINRAR,WIRESHARK,FIDDLER,HTTPDEBUGGERPRO,IEHTTPANALYZER,CHARLES,HTTPWATCH,SMARTSNIFF,MINISNIFFER,PROXIFIER,HTTP ANALYZER,SNIFFER,WSOCKEXPERT,IPANALYSE,ANALYZER,HTTP ANALYZER STAND-ALONE EDITION".Split(',').ToList(); private List<string> _AntiProcesses = "WINRAR,WIRESHARK,FIDDLER,HTTPDEBUGGERPRO,IEHTTPANALYZER,CHARLES,HTTPWATCH,SMARTSNIFF,MINISNIFFER,PROXIFIER,HTTP ANALYZER,SNIFFER,WSOCKEXPERT,IPANALYSE,ANALYZER,HTTP ANALYZER STAND-ALONE EDITION".Split(',').ToList();
private void AntiGrabbingMechanism() private void AntiGrabbingMechanism()
{ {
//Gate 1 - Anti Proxy //Gate 1 - Anti Proxy
if (IsUseSystemProxy()) if (IsUseSystemProxy())
{ {
LockUserAndKillProcess(); LockUserAndKillProcess();
} }
//Gate 2 - Anti Special Processes //Gate 2 - Anti Special Processes
System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcesses(); System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process process in processList) foreach (System.Diagnostics.Process process in processList)
{ {
try try
{ {
if (_AntiProcesses.Contains(process.ProcessName.ToUpper())) if (_AntiProcesses.Contains(process.ProcessName.ToUpper()))
{ {
process.Kill(); process.Kill();
LockUserAndKillProcess(); LockUserAndKillProcess();
} }
if (process.MainWindowTitle.Contains("正在捕获")) if (process.MainWindowTitle.Contains("正在捕获"))
{ {
process.Kill(); process.Kill();
LockUserAndKillProcess(); LockUserAndKillProcess();
} }
if (!IsWin23App(process)) if (!IsWin23App(process))
{ {
continue; continue;
} }
if (process.MainModule?.FileVersionInfo.FileDescription != null) if (process.MainModule?.FileVersionInfo.FileDescription != null)
{ {
foreach (string antiProcess in _AntiProcesses) foreach (string antiProcess in _AntiProcesses)
{ {
if (process.MainModule.FileVersionInfo.FileDescription.ToUpper().Contains(antiProcess)) if (process.MainModule.FileVersionInfo.FileDescription.ToUpper().Contains(antiProcess))
{ {
process.Kill(); process.Kill();
LockUserAndKillProcess(); LockUserAndKillProcess();
} }
} }
} }
} }
catch (Exception e) catch (Exception e)
{ {
} }
} }
} }
private void LockUserAndKillProcess() private void LockUserAndKillProcess()
{ {
string url = BaseClass.BuildObjString("user&act=add_user_lock"); string url = BaseClass.BuildObjString("user&act=add_user_lock");
string data = UserLogin.GetSignaturex("", ""); string data = UserLogin.GetSignaturex("", "");
string html = GetHtml.PostUtf8(url, data); string html = GetHtml.PostUtf8(url, data);
Process.GetCurrentProcess().Kill(); Process.GetCurrentProcess().Kill();
} }
public static bool IsUseSystemProxy() public static bool IsUseSystemProxy()
{ {
BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic; BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic;
IWebProxy systemWebProxy = WebRequest.GetSystemWebProxy(); IWebProxy systemWebProxy = WebRequest.GetSystemWebProxy();
FieldInfo field1 = systemWebProxy.GetType().GetField("webProxy", bindingAttr); FieldInfo field1 = systemWebProxy.GetType().GetField("webProxy", bindingAttr);
if (field1 != (FieldInfo)null) if (field1 != (FieldInfo)null)
{ {
WebProxy webProxy = field1.GetValue((object)systemWebProxy) as WebProxy; WebProxy webProxy = field1.GetValue((object)systemWebProxy) as WebProxy;
FieldInfo field2 = webProxy.GetType().GetField("_ProxyHostAddresses", bindingAttr); FieldInfo field2 = webProxy.GetType().GetField("_ProxyHostAddresses", bindingAttr);
if (field2 != (FieldInfo)null) if (field2 != (FieldInfo)null)
{ {
Hashtable hashtable = field2.GetValue((object)webProxy) as Hashtable; Hashtable hashtable = field2.GetValue((object)webProxy) as Hashtable;
if (hashtable != null && hashtable.Count > 0) if (hashtable != null && hashtable.Count > 0)
return true; return true;
} }
} }
return false; return false;
} }
public bool IsWin23App(Process process) public bool IsWin23App(Process process)
{ {
if (Environment.Is64BitOperatingSystem) if (Environment.Is64BitOperatingSystem)
{ {
IntPtr processHandle; IntPtr processHandle;
bool retVal; bool retVal;
try try
{ {
processHandle = Process.GetProcessById(process.Id).Handle; processHandle = Process.GetProcessById(process.Id).Handle;
} }
catch catch
{ {
return false; return false;
} }
return IsWow64Process(processHandle, out retVal) && retVal; return IsWow64Process(processHandle, out retVal) && retVal;
} }
return true; return true;
} }
#endregion #endregion
private void BaseWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) private void BaseWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{ {
if (BaseMsgWindow.ShowConfirm("是否关闭软件?", "退出微信小店订单管理").DialogResult == true) if (BaseMsgWindow.ShowConfirm("是否关闭软件?", "退出微信小店订单管理").DialogResult == true)
Process.GetCurrentProcess().Kill(); {
else _ticketMonitor.Dispose();
e.Cancel = true; Process.GetCurrentProcess().Kill();
} }
else
e.Cancel = true;
}
#region 读取微信店铺 #region 读取微信店铺
public bool isReadShop { get; set; } = false; public bool isReadShop { get; set; } = false;
public bool hasReadShop { get; set; } = false; public bool hasReadShop { get; set; } = false;
public void GetServerShop() public void GetServerShop()
{ {
if (isReadShop) if (isReadShop)
return; return;
var tList = new ConcurrentList<Task>(); var tList = new ConcurrentList<Task>();
List<ShopLoginInfo> list = new List<ShopLoginInfo>(); List<ShopLoginInfo> list = new List<ShopLoginInfo>();
Dispatcher.Invoke(new Action(() => List<ShopLoginInfo> listTmp = new List<ShopLoginInfo>();
{ //Dispatcher.Invoke(new Action(() =>
})); //{
isReadShop = true; //}));
int page = 0; isReadShop = true;
while (true) int page = 0;
{ while (true)
page++; {
var url = BaseClass.Build29WxObjString("shop/get_shop_list"); Thread.Sleep(1);
var data = UserLogin.GetSignaturex() + "&page=" + page;
data += "&is_get_erp_shop_id=true";
var html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html)
|| !html.Contains("shop_id") || !html.Contains("shop_account") || !html.Contains("login_pass"))
{
break;
}
var jArr = JObject.Parse(html)["data"]; page++;
if (jArr.Count() == 0) var url = BaseClass.Build29WxObjString("shop/get_shop_list");
break; var data = UserLogin.GetSignaturex() + "&page=" + page + "&page_size=100";
data += "&is_get_erp_shop_id=true";
var html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html)
|| !html.Contains("shop_id") || !html.Contains("shop_account") || !html.Contains("login_pass"))
{
break;
}
foreach (JObject jObj in jArr) var jArr = JObject.Parse(html)["data"];
{ if (jArr.Count() == 0)
var shop = ShopBLL.DeserializationShop(jObj); break;
var shopExist = list.LastOrDefault(l => l.ShopId == shop.ShopId); foreach (JObject jObj in jArr)
while (shopExist != null) {
{ var shop = ShopBLL.DeserializationShop(jObj);
shop.Is29Supplier = shopExist.Is29Supplier;
shop.IsSelect = shopExist.IsSelect; var shopExist = list.LastOrDefault(l => l.ShopId == shop.ShopId);
shop.IsFilter = shopExist.IsFilter; while (shopExist != null)
list.Remove(shopExist); {
shop.Is29Supplier = shopExist.Is29Supplier;
shop.IsSelect = shopExist.IsSelect;
shop.IsFilter = shopExist.IsFilter;
list.Remove(shopExist);
shopExist = list.LastOrDefault(l => l.ShopId == shop.ShopId); shopExist = list.LastOrDefault(l => l.ShopId == shop.ShopId);
} }
list.Add(shop); list.Add(shop);
if (!GlobalConfig.ShopLoginList.Any(s => s.ShopId == shop.ShopId && !shop.is_point_shop_expire)) if (!listTmp.Any(s => s.ShopId == shop.ShopId && !shop.is_point_shop_expire))
{ {
Dispatcher.Invoke(new Action(() => listTmp.Add(shop);
{
GlobalConfig.ShopLoginList.Add(shop);
}));
Task.Run(() => Task.Run(() =>
{ {
@@ -318,11 +339,17 @@ namespace _29WxOrderWpf
break; break;
} }
foreach (var order in GlobalConfig.lstFilterOrder.Where(o => o.shop_id.ParseToString() == shop.ErpShopId).ToList()) List<oms_wei_order_info> orders;
lock (_orderLock)
{
orders = GlobalConfig.lstFilterOrder.Where(o => o.shop_id.ParseToString() == shop.ErpShopId).ToList();
}
foreach (var order in orders)
{ {
// 更新代发管理情况 // 更新代发管理情况
foreach (var orderItem in order.orderItems) foreach (var orderItem in order.orderItems)
Dispatcher.Invoke(new Action(() => { orderItem.UpdateOrderItemBuyButton(); })); orderItem.UpdateOrderItemBuyButton();
//Dispatcher.Invoke(new Action(() => { orderItem.UpdateOrderItemBuyButton(); }));
} }
} }
} }
@@ -332,27 +359,34 @@ namespace _29WxOrderWpf
})); }));
}); });
} }
} }
}
Dispatcher.Invoke(new Action(() =>
{
foreach (var shop in GlobalConfig.ShopLoginList.Where(s => !list.Any(ss => ss.ShopId == s.ShopId)).ToList())
{
GlobalConfig.ShopLoginList.Remove(shop);
}
foreach (var shop in GlobalConfig.ShopLoginList.Where(s => s.is_point_shop_expire).ToList())
{
GlobalConfig.ShopLoginList.Remove(shop);
}
}));
isReadShop = false;
hasReadShop = true;
while (tList.Where(ta => !ta.IsFaulted && !ta.IsCompleted).Count() >= 1)
{
tList.RemoveAll(ta => ta.IsFaulted || ta.IsCompleted || ta.IsCanceled); Thread.Sleep(100);
} }
}
Dispatcher.Invoke(new Action(() =>
{
GlobalConfig.ShopLoginList = new AllBase.Util.ObservableCollectionThreadSafe<ShopLoginInfo>(list);
shopListCtrl.lbxShop.ItemsSource = GlobalConfig.ShopLoginList;
foreach (var shop in GlobalConfig.ShopLoginList.Where(s => !list.Any(ss => ss.ShopId == s.ShopId)).ToList())
{
GlobalConfig.ShopLoginList.Remove(shop);
}
foreach (var shop in GlobalConfig.ShopLoginList.Where(s => s.is_point_shop_expire).ToList())
{
GlobalConfig.ShopLoginList.Remove(shop);
}
}));
isReadShop = false;
hasReadShop = true;
Task.Run(() =>
{
while (tList.Where(ta => !ta.IsFaulted && !ta.IsCompleted).Count() >= 1)
{
tList.RemoveAll(ta => ta.IsFaulted || ta.IsCompleted || ta.IsCanceled); Thread.Sleep(100);
}
});
}
public void GetShopSupplier(List<ShopLoginInfo> shops) public void GetShopSupplier(List<ShopLoginInfo> shops)
{ {
@@ -369,7 +403,7 @@ namespace _29WxOrderWpf
var jArr = JsonHelper.JObjectParse(rst)["list"] as JArray; var jArr = JsonHelper.JObjectParse(rst)["list"] as JArray;
// appid "wx7809625286c28f2f" name "百川日用"; // appid "wx7809625286c28f2f" name "百川日用";
if (jArr.Any(aa => aa["appid"].ParseToString() == "wx7809625286c28f2f" && aa["status"].ParseToInt() == 1)) if (jArr.Any(aa => aa["appid"].ParseToString() == "wx7809625286c28f2f" && aa["status"].ParseToInt() == 1))
//if (rst.Contains("wx7809625286c28f2f") || rst.Contains("百川日用")) //if (rst.Contains("wx7809625286c28f2f") || rst.Contains("百川日用"))
continue; continue;
rst = new WxApiBLL().SetShopSupplier(shop, "wx7809625286c28f2f", "4431685489938137094"); rst = new WxApiBLL().SetShopSupplier(shop, "wx7809625286c28f2f", "4431685489938137094");
@@ -392,83 +426,83 @@ namespace _29WxOrderWpf
/// 读取拼多多买手 /// 读取拼多多买手
/// </summary> /// </summary>
public void GetPddBuyer() public void GetPddBuyer()
{ {
if (isGetPddBuyer) if (isGetPddBuyer)
return; return;
isGetPddBuyer = true; isGetPddBuyer = true;
//var ids = dgvBuyer.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colSelect"].Value.ParseToBool() == true).Select(s => s.Cells["colBuyerId"].Value.ParseToString()).ToList(); //var ids = dgvBuyer.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colSelect"].Value.ParseToBool() == true).Select(s => s.Cells["colBuyerId"].Value.ParseToString()).ToList();
//Invoke(new Action(() => { pbLoading.Visible = true; })); //Invoke(new Action(() => { pbLoading.Visible = true; }));
try try
{ {
var url = BaseClass.Build29PDDObjString("user/get_buyer"); var url = BaseClass.Build29PDDObjString("user/get_buyer");
var data = UserLogin.GetSignaturex(); var data = UserLogin.GetSignaturex();
data += "&page_size=200"; data += "&page_size=200";
var result = GetHtml.PostUtf8(url, data); var result = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(result) || !result.Contains("\"code\":200")) if (string.IsNullOrEmpty(result) || !result.Contains("\"code\":200"))
result = GetHtml.PostUtf8(url, data); result = GetHtml.PostUtf8(url, data);
if (result.Contains("\"code\":200")) if (result.Contains("\"code\":200"))
{ {
List<BuyerLoginInfo> loginInfoLst = JsonHelper.DeserializeJsonToList<BuyerLoginInfo>(JsonHelper.JObjectParse(result)["data"].ParseToString()); List<BuyerLoginInfo> loginInfoLst = JsonHelper.DeserializeJsonToList<BuyerLoginInfo>(JsonHelper.JObjectParse(result)["data"].ParseToString());
foreach (var buyer in GlobalConfig.PDDBuyerLoginList.Where(bu => !loginInfoLst.Any(b => b.buyer_id == bu.buyer_id)).ToList()) foreach (var buyer in GlobalConfig.PDDBuyerLoginList.Where(bu => !loginInfoLst.Any(b => b.buyer_id == bu.buyer_id)).ToList())
{ {
Dispatcher.Invoke(new Action(() => { GlobalConfig.PDDBuyerLoginList.Remove(buyer); })); Dispatcher.Invoke(new Action(() => { GlobalConfig.PDDBuyerLoginList.Remove(buyer); }));
} }
foreach (var b in loginInfoLst) foreach (var b in loginInfoLst)
{ {
Dispatcher.Invoke(new Action(() => Dispatcher.Invoke(new Action(() =>
{ {
var buyer = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(bu => bu.buyer_id == b.buyer_id); var buyer = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(bu => bu.buyer_id == b.buyer_id);
if (buyer == null) if (buyer == null)
GlobalConfig.PDDBuyerLoginList.Add(b); GlobalConfig.PDDBuyerLoginList.Add(b);
else else
{ {
buyer.add_time = b.add_time; buyer.add_time = b.add_time;
buyer.buyer_id = b.buyer_id; buyer.buyer_id = b.buyer_id;
buyer.buyer_name = b.buyer_name; buyer.buyer_name = b.buyer_name;
buyer.buyer_nick = b.buyer_nick; buyer.buyer_nick = b.buyer_nick;
buyer.cookie = b.cookie; buyer.cookie = b.cookie;
buyer.mdy_time = b.mdy_time; buyer.mdy_time = b.mdy_time;
buyer.notes = b.notes; buyer.notes = b.notes;
buyer.status = b.status; buyer.status = b.status;
buyer.user_name = b.user_name; buyer.user_name = b.user_name;
} }
})); }));
} }
//Invoke(new Action(() => //Invoke(new Action(() =>
//{ //{
//dgvBuyer.Rows.Clear(); //dgvBuyer.Rows.Clear();
//cmbBuyer.Items.Clear(); //cmbBuyer.Items.Clear();
//})); //}));
foreach (var buyer in GlobalConfig.PDDBuyerLoginList) foreach (var buyer in GlobalConfig.PDDBuyerLoginList)
{ {
//Invoke(new Action(() => //Invoke(new Action(() =>
//{ //{
//BindBuyer(buyer, "", ids); //BindBuyer(buyer, "", ids);
//cmbBuyer.Items.Add(buyer.buyer_nick); //cmbBuyer.Items.Add(buyer.buyer_nick);
//})); //}));
} }
} }
} }
catch catch
{ {
} }
//Invoke(new Action(() => //Invoke(new Action(() =>
//{ //{
// pbLoading.Visible = false; // pbLoading.Visible = false;
//})); //}));
isGetPddBuyer = false; isGetPddBuyer = false;
hasGetPddBuyer = true; hasGetPddBuyer = true;
} }
#endregion #endregion
#region 读取拼多多买手号 #region 读取拼多多买手号
@@ -537,18 +571,18 @@ namespace _29WxOrderWpf
#endregion #endregion
private void lblBalance_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) private void lblBalance_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{ {
WXGetBalanceQrCodeForm balanceQrCodeForm = new WXGetBalanceQrCodeForm(StartUp.UpdateBalance); WXGetBalanceQrCodeForm balanceQrCodeForm = new WXGetBalanceQrCodeForm(StartUp.UpdateBalance);
balanceQrCodeForm.ShowDialog(); balanceQrCodeForm.ShowDialog();
} }
private void gridPddBuyerOrderReadCtrl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) private void gridPddBuyerOrderReadCtrl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{ {
//if (Panel.GetZIndex(MainWindow.Instance.gridPddBuyerOrderReadCtrl) < 1) //if (Panel.GetZIndex(MainWindow.Instance.gridPddBuyerOrderReadCtrl) < 1)
// Panel.SetZIndex(MainWindow.Instance.gridPddBuyerOrderReadCtrl, 1); // Panel.SetZIndex(MainWindow.Instance.gridPddBuyerOrderReadCtrl, 1);
//else //else
// Panel.SetZIndex(MainWindow.Instance.gridPddBuyerOrderReadCtrl, -1); // Panel.SetZIndex(MainWindow.Instance.gridPddBuyerOrderReadCtrl, -1);
} }
private void gridTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) private void gridTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{ {
@@ -571,5 +605,181 @@ namespace _29WxOrderWpf
view.ShowDialog(); view.ShowDialog();
} }
}
private void bt_showOrderSupport(object sender, RoutedEventArgs e)
{
OpenOrderSupportTicket(_ticketMonitor.LatestNotification);
_ticketMonitor.MarkAllRead();
}
private async Task StartTicketRealtimeMonitor()
{
try
{
var options = GetTicketOptions().Clone();
await _ticketMonitor.Start(options);
UpdateOrderSupportBadge();
_ = LoadHistoricalTicketUnreadAsync(options);
this.Dispatcher.Invoke(() =>
{
btOrderSupport.IsEnabled = true;
});
}
catch (Exception ex)
{
NLogger.Instance.Error("TicketRealtimeStartError:" + ex);
}
}
/// <summary>
/// 启动后根据服务端工单列表和历史缓存补齐未读角标。
/// </summary>
private async Task LoadHistoricalTicketUnreadAsync(TicketClientOptions options)
{
try
{
var unreadByTicket = await _workOrderUnreadService
.GetUnreadByTicketAsync(options);
_ticketMonitor.MergeUnread(unreadByTicket);
}
catch (Exception ex)
{
NLogger.Instance.Error("TicketUnreadLoadError:" + ex);
}
}
private TicketClientOptions GetTicketOptions()
{
if (_ticketOptions != null)
return _ticketOptions;
_ticketOptions = new TicketClientOptions
{
UserName = BaseClass.UserName,
AppIds = GlobalConfig.ShopLoginList.Select(a => a.ShopId).ToList(),
Orders = []
};
//OrderSupportTicketView
// .CreateDefaultOptions(BaseClass.UserName)
// .Clone();
return _ticketOptions;
}
private void OpenOrderSupportTicket(TicketRealtimeNotification notification)
{
var view = EnsureOrderSupportView();
view.ViewModel.ShowHistory();
if (notification != null)
{
view.OpenTicket(
notification.AppId,
notification.WechatOrderId);
}
// DialogService 会复用同类型的已打开窗口,避免重复创建。
DialogService.ShowOrActivateWindow(view);
}
/// <summary>
/// 从订单行打开工单页面。若左侧列表已有相同订单号的工单,直接定位到该工单;
/// 否则在同一个工单页面中进入新建工单状态。
/// </summary>
public async Task CreateOrderSupportTicketAsync(TicketOrderOption order)
{
if (order == null)
return;
var view = EnsureOrderSupportView();
await view.ViewModel.InitializeAsync();
var existing = view.ViewModel.FindTicketByOrderId(order.OrderId);
if (existing != null)
{
view.ViewModel.ApplyOrderInfo(order);
view.OpenTicket(existing.AppId, existing.WechatOrderId);
}
else
{
view.OpenNewTicket(order);
}
DialogService.ShowOrActivateWindow(view);
}
private OrderSupportTicketView EnsureOrderSupportView()
{
if (_orderSupportView == null)
{
_orderSupportView = new OrderSupportTicketView(
new TicketService(
new TicketApiService(),
_ticketMonitor.RealtimeService,
ownsRealtime: false),
GetTicketOptions().Clone());
}
return _orderSupportView;
}
private void OnTicketNewMessageReceived(
object sender,
TicketInboxMessageEventArgs e)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(new Action(
() => OnTicketNewMessageReceived(sender, e)));
return;
}
var notification = e?.Notification;
if (notification == null)
return;
UpdateOrderSupportBadge();
}
private void OnTicketUnreadCountChanged(
object sender,
TicketUnreadCountChangedEventArgs e)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(new Action(
() => OnTicketUnreadCountChanged(sender, e)));
return;
}
UpdateOrderSupportBadge(e?.UnreadCount ?? 0);
}
private void UpdateOrderSupportBadge()
{
UpdateOrderSupportBadge(_ticketMonitor.UnreadCount);
}
private void UpdateOrderSupportBadge(int unreadCount)
{
if (borderOrderSupportUnread == null)
return;
this.Dispatcher.Invoke(() =>
{
borderOrderSupportUnread.Visibility = unreadCount > 0
? Visibility.Visible
: Visibility.Collapsed;
tbOrderSupportUnread.Text = unreadCount > 99
? "99+"
: unreadCount.ToString();
btOrderSupport.ToolTip = unreadCount > 0
? $"客户工单({unreadCount} 条未读消息)"
: "客户工单";
});
}
private void MainWindow_Closed(object sender, EventArgs e)
{
_ticketMonitor.NewMessageReceived -= OnTicketNewMessageReceived;
_ticketMonitor.UnreadCountChanged -= OnTicketUnreadCountChanged;
}
}
} }
@@ -1,14 +0,0 @@
<Window
x:Class="_29WxOrderWpf.OrderSupportTicketWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:_29WxOrderWpf"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ost="clr-namespace:OrderSupportTicket.Views;assembly=OrderSupportTicket"
Title="OrderSupportTicketWindow"
Width="800"
Height="650"
mc:Ignorable="d">
<ost:OrderSupportTicketView />
</Window>
@@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Shapes;
namespace _29WxOrderWpf;
/// <summary>
/// OrderSupportTicketWindow.xaml 的交互逻辑
/// </summary>
public partial class OrderSupportTicketWindow : Window
{
public OrderSupportTicketWindow()
{
InitializeComponent();
}
}
+2 -2
View File
@@ -7,11 +7,11 @@ using System.Windows;
// 有关程序集的一般信息由以下 // 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改 // 控制。更改这些特性值可修改
// 与程序集关联的信息。 // 与程序集关联的信息。
[assembly: AssemblyTitle("29供应连-微信小店订单管理")] [assembly: AssemblyTitle("29供应链-微信小店订单管理")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")] [assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("29供应连-微信小店订单管理")] [assembly: AssemblyProduct("29供应链-微信小店订单管理")]
[assembly: AssemblyCopyright("Copyright © 2026")] [assembly: AssemblyCopyright("Copyright © 2026")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
+2 -1
View File
@@ -43,8 +43,9 @@ public class ShipGiftService : SingleInstance<ShipGiftService>
giftAmount = 1.55m; giftAmount = 1.55m;
} }
if (BaseClass.Setting.AutoSwitchGiftType && (item.product_price ?? 0) > 6 * 1000) if (BaseClass.Setting.AutoSwitchGiftType && (item.product_price ?? 0) > 6 * 100)
{ {
giftType = GiftType._160;
giftAmount = 1.6m; giftAmount = 1.6m;
} }
decimal amount = giftAmount + BaseClass.OemGiftAmount; decimal amount = giftAmount + BaseClass.OemGiftAmount;
+9 -2
View File
@@ -23,6 +23,7 @@ namespace _29WxOrderWpf
GlobalConfig.BuyConfig = ConfigHelper.LoadConfig<BuyConfig>("buy_config_260708"); GlobalConfig.BuyConfig = ConfigHelper.LoadConfig<BuyConfig>("buy_config_260708");
if (GlobalConfig.BuyConfig == null) if (GlobalConfig.BuyConfig == null)
GlobalConfig.BuyConfig = new BuyConfig(); GlobalConfig.BuyConfig = new BuyConfig();
GlobalConfig.BuyConfig.IsSyncDirectBuyOrderWaybill = false;
GlobalConfig.lstWXShopTokenInfo = ConfigHelper.LoadConfig<ConcurrentList<WXShopTokenInfo>>("wx_shop_token_list"); GlobalConfig.lstWXShopTokenInfo = ConfigHelper.LoadConfig<ConcurrentList<WXShopTokenInfo>>("wx_shop_token_list");
if (GlobalConfig.lstWXShopTokenInfo == null) if (GlobalConfig.lstWXShopTokenInfo == null)
@@ -37,7 +38,8 @@ namespace _29WxOrderWpf
BaseClass.Setting = NaiBa.Util.Helper.ConfigHelper.LoadConfig<SettingConfig>(SettingViewModel.SettingFileName); BaseClass.Setting = NaiBa.Util.Helper.ConfigHelper.LoadConfig<SettingConfig>(SettingViewModel.SettingFileName);
if (BaseClass.Setting==null) BaseClass.Setting = new SettingConfig(); if (BaseClass.Setting == null) BaseClass.Setting = new SettingConfig();
BaseClass.Setting.AutoSwitchGiftType = true;
new WxOrder.Framework.Startup(); new WxOrder.Framework.Startup();
} }
@@ -59,7 +61,12 @@ namespace _29WxOrderWpf
{ {
BaseClass.Balance = BaseRegex.GetDecimalJson(ref html, "balance"); BaseClass.Balance = BaseRegex.GetDecimalJson(ref html, "balance");
MainWindow.Instance.Balance = BaseClass.Balance.ToString("0.00"); MainWindow.Instance.Balance = BaseClass.Balance.ToString("0.00");
}
// 更新下每单扣费金额
BaseClass.PostagePerOrder = Math.Max(2.2m, BaseRegex.GetDecimalJson(ref html, "postage_per_order"));
BaseClass.RefundPostagePerOrder = Math.Max(2.5m, BaseRegex.GetDecimalJson(ref html, "refund_postage_per_order"));
BaseClass.OemGiftAmount = BaseRegex.GetDecimalJson(ref html, "gift_oem_amount_per_order");
}
} }
} }
} }
@@ -81,7 +81,7 @@ namespace _29WxOrderWpf.ViewModels
{ {
IsChangeingPickNo = false; IsChangeingPickNo = false;
string orderId = OrderItem.order_id; string orderId = OrderItem.order_id;
ShopLoginInfo shop = OrderItem.Shop; ShopLoginInfo shop = OrderItem.ItemOrder.Shop;
if (string.IsNullOrEmpty(PickNo)) if (string.IsNullOrEmpty(PickNo))
{ {
BaseMsgWindow.ShowInfo("取件码不能为空"); BaseMsgWindow.ShowInfo("取件码不能为空");
+22 -1
View File
@@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows;
using WPFCommon.Models; using WPFCommon.Models;
namespace _29WxOrderWpf.ViewModels; namespace _29WxOrderWpf.ViewModels;
@@ -26,15 +27,35 @@ public class SettingViewModel : BindableBaseEx
get => GetValue<bool>(); get => GetValue<bool>();
set => SetValue(value); set => SetValue(value);
} }
public bool SwitchEnableDirectBuy
{
get => GetValue<bool>();
set => SetValue(value);
}
public bool SwitchEnablePddTransitTraditionalAddress
{
get => GetValue<bool>();
set => SetValue(value);
}
public Visibility ShowEnablePddTransitTraditionalAddress
{
get => GetValue<Visibility>();
set => SetValue(value);
}
public void Assign(SettingConfig config) public void Assign(SettingConfig config)
{ {
AutoSwitchGiftType = config.AutoSwitchGiftType; AutoSwitchGiftType = config.AutoSwitchGiftType;
SwitchEnableDirectBuy = config.SwitchEnableDirectBuy;
SwitchEnablePddTransitTraditionalAddress = config.SwitchEnablePddTransitTraditionalAddress;
ShowEnablePddTransitTraditionalAddress = config.ShowEnablePddTransitTraditionalAddress ? Visibility.Visible : Visibility.Collapsed;
} }
public SettingConfig ToConfig() public SettingConfig ToConfig()
{ {
return new SettingConfig return new SettingConfig
{ {
AutoSwitchGiftType = AutoSwitchGiftType AutoSwitchGiftType = AutoSwitchGiftType,
SwitchEnableDirectBuy = SwitchEnableDirectBuy,
SwitchEnablePddTransitTraditionalAddress = SwitchEnablePddTransitTraditionalAddress,
}; };
} }
} }
+15 -12
View File
@@ -345,18 +345,20 @@ namespace _29WxOrderWpf.ViewModels
// cef138必须init后方可设置或删除cookie // cef138必须init后方可设置或删除cookie
while (!CefWebBrowser.IsBrowserInitialized || !CefWebBrowser.GetBrowser().MainFrame.IsValid) while (_isWindowLoaded && (!CefWebBrowser.IsBrowserInitialized || !CefWebBrowser.GetBrowser().MainFrame.IsValid))
await Task.Delay(20); await Task.Delay(20);
//await WPFCEFBrowser.DeleteCookieAsync(CefWebBrowser.GetCookieManager(null)); //await WPFCEFBrowser.DeleteCookieAsync(CefWebBrowser.GetCookieManager(null));
//cef 138 如果没有设置RequestContext 可能为空,直接getCookieManager //cef 138 如果没有设置RequestContext 可能为空,直接getCookieManager
//await WPFCEFBrowser.SetCookieAsync(JsonHelper.SerializeObject(cookieLst), CefWebBrowser.GetCookieManager(null)); //await WPFCEFBrowser.SetCookieAsync(JsonHelper.SerializeObject(cookieLst), CefWebBrowser.GetCookieManager(null));
if (OpenType != EnumOpenType.login) if (OpenType != EnumOpenType.login)
{
foreach (var cook in cookieLst) foreach (var cook in cookieLst)
{ {
await WPFCEFBrowser.SetCookieAsync(cook.Domain.Trim('.'), cook.Name + "=" + cook.Value + ";", CefWebBrowser.GetCookieManager(null)); if (_isWindowLoaded)
//t.Wait(5000); await WPFCEFBrowser.SetCookieAsync(cook.Domain.Trim('.'), cook.Name + "=" + cook.Value + ";", CefWebBrowser.GetCookieManager(null));
} }
}
//根据登录的具体店铺设置local storage //根据登录的具体店铺设置local storage
if (!string.IsNullOrEmpty(buyer?.buyer_id)) if (!string.IsNullOrEmpty(buyer?.buyer_id))
@@ -369,9 +371,9 @@ namespace _29WxOrderWpf.ViewModels
} }
if (!string.IsNullOrEmpty(InitUrl)) if (!string.IsNullOrEmpty(InitUrl))
CefWebBrowser.Load(InitUrl); CefWebBrowser?.Load(InitUrl);
else else
CefWebBrowser.Load(buyerMainUrl); CefWebBrowser?.Load(buyerMainUrl);
//不是登录的话就此返回 //不是登录的话就此返回
if (OpenType != EnumOpenType.login) if (OpenType != EnumOpenType.login)
@@ -381,14 +383,14 @@ namespace _29WxOrderWpf.ViewModels
for (int i = 0; i < 50; i++) for (int i = 0; i < 50; i++)
{ {
if (CefWebBrowser.IsLoading) if (CefWebBrowser?.IsLoading == true)
await Task.Delay(100); await Task.Delay(100);
} }
await Task.Delay(Randomx.GetId(1500, 2000)); await Task.Delay(Randomx.GetId(1500, 2000));
if (!_isWindowLoaded) if (!_isWindowLoaded)
return; return;
while (!CefWebBrowser.Address?.StartsWith(buyerLoginUrl) ?? false) while (!CefWebBrowser?.Address?.StartsWith(buyerLoginUrl) ?? false)
{ {
await Task.Delay(1000); await Task.Delay(1000);
if (!_isWindowLoaded) if (!_isWindowLoaded)
@@ -396,8 +398,7 @@ namespace _29WxOrderWpf.ViewModels
} }
} }
} });
);
} }
@@ -426,7 +427,7 @@ namespace _29WxOrderWpf.ViewModels
sb.Append("(function(){"); sb.Append("(function(){");
sb.Append("CefSharp.BindObjectAsync('shopObj');"); sb.Append("CefSharp.BindObjectAsync('shopObj');");
sb.Append("})();"); sb.Append("})();");
CefWebBrowser.GetBrowser().MainFrame.EvaluateScriptAsync(sb.ToString()); CefWebBrowser?.GetBrowser().MainFrame.EvaluateScriptAsync(sb.ToString());
} }
private bool RequestHandler_BeforeResourceLoad(object sender, string url, string postData, IRequest request) private bool RequestHandler_BeforeResourceLoad(object sender, string url, string postData, IRequest request)
@@ -489,6 +490,8 @@ namespace _29WxOrderWpf.ViewModels
{ {
Thread.Sleep(2000); Thread.Sleep(2000);
if (!_isWindowLoaded)
return;
//List<Cookie> cookieList = WPFCEFBrowser.GetCookieList(shopCookieHead, CefWebBrowser.GetCookieManager(null)); //List<Cookie> cookieList = WPFCEFBrowser.GetCookieList(shopCookieHead, CefWebBrowser.GetCookieManager(null));
List<Cookie> cookieList = WPFCEFBrowser.GetCookieList("", CefWebBrowser.GetCookieManager(null)); List<Cookie> cookieList = WPFCEFBrowser.GetCookieList("", CefWebBrowser.GetCookieManager(null));
@@ -555,9 +558,9 @@ namespace _29WxOrderWpf.ViewModels
if (CefWebBrowser != null) if (CefWebBrowser != null)
{ {
if (Address != "about:blank") if (Address != "about:blank")
CefWebBrowser.Load(Address); CefWebBrowser?.Load(Address);
else else
CefWebBrowser.Load(buyerMainUrl); CefWebBrowser?.Load(buyerMainUrl);
} }
} }
@@ -40,6 +40,11 @@ namespace _29WxOrderWpf.ViewModels
get { return this.GetValue(x => x.OrderItem); } get { return this.GetValue(x => x.OrderItem); }
set { this.SetValue(x => x.OrderItem, value); } set { this.SetValue(x => x.OrderItem, value); }
} }
public oms_wei_external_procurement_log_info TransitOrder
{
get { return this.GetValue(x => x.TransitOrder); }
set { this.SetValue(x => x.TransitOrder, value); }
}
public string purchaserNote public string purchaserNote
{ {
get { return this.GetValue(x => x.purchaserNote); } get { return this.GetValue(x => x.purchaserNote); }
@@ -98,7 +103,12 @@ namespace _29WxOrderWpf.ViewModels
public void AddExtraPackages() public void AddExtraPackages()
{ {
var transitOrder = OrderItem.ItemTransitOrder ?? OrderItem.ItemTransitOrderWithVoid; if (TransitOrder == null)
{
//TransitOrder = OrderItem.ItemTransitOrder ?? OrderItem.ItemTransitOrderWithVoid;
BaseMsgWindow.ShowError("未找到云仓发货包裹,请确认包裹存在");
return;
}
var transitExtraOrder = OrderItem.ItemTransitExtraOrders.FirstOrDefault(t => t.order_void_status != 1); var transitExtraOrder = OrderItem.ItemTransitExtraOrders.FirstOrDefault(t => t.order_void_status != 1);
if (transitExtraOrder != null) if (transitExtraOrder != null)
{ {
@@ -113,20 +123,20 @@ namespace _29WxOrderWpf.ViewModels
body["postage"] = ((basePostage + BaseClass.PostagePerOrderDiff) * 100).ParseToInt().ParseToString(); body["postage"] = ((basePostage + BaseClass.PostagePerOrderDiff) * 100).ParseToInt().ParseToString();
body["packType"] = "2"; body["packType"] = "2";
body["batchId"] = transitOrder.order_code + "-" + ((OrderItem.ItemTransitExtraOrders?.Count).ParseToInt() + 1); body["batchId"] = TransitOrder.order_code + "-" + ((OrderItem.ItemTransitExtraOrders?.Count).ParseToInt() + 1);
body["orderNo"] = OrderItem.order_id; body["orderNo"] = OrderItem.order_id;
body["orderCode"] = transitOrder.order_code; body["orderCode"] = TransitOrder.order_code;
// 未出库填上游物流,已出库填下游物流 // 未出库填上游物流,已出库填下游物流
if (transitOrder.warehouse_status != 2) if (TransitOrder.warehouse_status != 2)
{ {
body["logisticsCode"] = transitOrder.express_1_company; body["logisticsCode"] = TransitOrder.express_1_company;
body["logisticsExpressCode"] = transitOrder.express_1_waybill; body["logisticsExpressCode"] = TransitOrder.express_1_waybill;
} }
else else
{ {
body["logisticsCode"] = transitOrder.express_2_company; body["logisticsCode"] = TransitOrder.express_2_company;
body["logisticsExpressCode"] = transitOrder.express_2_waybill; body["logisticsExpressCode"] = TransitOrder.express_2_waybill;
} }
body["accountUser"] = BaseClass.UserName; body["accountUser"] = BaseClass.UserName;
@@ -142,7 +152,7 @@ namespace _29WxOrderWpf.ViewModels
// <AjaxResult><msg>创建额外包裹异常: 用户账户余额不足,需至少 2.20 元用于中转仓取号, userId:17333276316, balance:0.85</msg><code>2</code></AjaxResult> // <AjaxResult><msg>创建额外包裹异常: 用户账户余额不足,需至少 2.20 元用于中转仓取号, userId:17333276316, balance:0.85</msg><code>2</code></AjaxResult>
if (BaseRegex.GetStringXml(ref rst, "code") != "0" && BaseRegex.GetStringXml(ref rst, "code") != "200") if (BaseRegex.GetStringXml(ref rst, "code") != "0" && BaseRegex.GetStringXml(ref rst, "code") != "200")
{ {
BaseMsgWindow.ShowError(BaseRegex.GetStringXml(ref rst, "msg")); BaseMsgWindow.ShowError("服务端返回:" + BaseRegex.GetStringXml(ref rst, "msg"));
return; return;
} }
@@ -156,7 +166,7 @@ namespace _29WxOrderWpf.ViewModels
// <AjaxResult><msg>额外信息已保存</msg><code>200</code></AjaxResult> // <AjaxResult><msg>额外信息已保存</msg><code>200</code></AjaxResult>
if (BaseRegex.GetStringXml(ref rst, "code") != "0" && BaseRegex.GetStringXml(ref rst, "code") != "200") if (BaseRegex.GetStringXml(ref rst, "code") != "0" && BaseRegex.GetStringXml(ref rst, "code") != "200")
{ {
BaseMsgWindow.ShowError(BaseRegex.GetStringXml(ref rst, "msg")); BaseMsgWindow.ShowError("服务端返回:" + BaseRegex.GetStringXml(ref rst, "msg"));
return; return;
} }
+6 -1
View File
@@ -39,10 +39,15 @@ public partial class ChangeWaybillView : UserControl
private void ChangeWaybillView_Loaded(object sender, RoutedEventArgs e) private void ChangeWaybillView_Loaded(object sender, RoutedEventArgs e)
{ {
Window parentWindow = Window.GetWindow(this);
if (parentWindow != null)
{
parentWindow.Closed += ChangeWaybillView_Closed;
}
ViewModel.Start(); ViewModel.Start();
} }
private void ChangeWaybillView_Closed(object sender, RoutedEventArgs e) private void ChangeWaybillView_Closed(object sender, EventArgs e)
{ {
ViewModel.Stop(); ViewModel.Stop();
} }
@@ -28,11 +28,11 @@ public partial class TransitExtraPackagesView : UserControl
/// </summary> /// </summary>
public TransitExtraPackagesViewModel ViewModel { get; } public TransitExtraPackagesViewModel ViewModel { get; }
public TransitExtraPackagesView(oms_wei_order_info _order, oms_wei_order_item_info _orderItem) public TransitExtraPackagesView(oms_wei_order_info _order, oms_wei_order_item_info _orderItem, oms_wei_external_procurement_log_info transitOrder = null)
{ {
InitializeComponent(); InitializeComponent();
ViewModel = new TransitExtraPackagesViewModel(_order, _orderItem); ViewModel = new TransitExtraPackagesViewModel(_order, _orderItem) { TransitOrder = transitOrder };
ViewModel.RequestClose += ViewModel_RequestClose; ViewModel.RequestClose += ViewModel_RequestClose;
DataContext = ViewModel; DataContext = ViewModel;
} }
@@ -44,7 +44,7 @@ namespace _29WxOrderWpf.Windows.LoginWindows
if (!string.IsNullOrEmpty(BaseClass.ProgramName)) if (!string.IsNullOrEmpty(BaseClass.ProgramName))
{ {
lblAppName.Content = BaseClass.ProgramName; lblAppName.Content = BaseClass.ProgramName;
MainWindow.Instance.lblAppName.Content = lblAppName.Content; MainWindow.Instance.lblAppName.Content = BaseClass.ProgramName.Contains("-微信小店订单管理") ? BaseClass.ProgramName : BaseClass.ProgramName + "-微信小店订单管理";
} }
this.Title = "用户登录"; this.Title = "用户登录";
@@ -288,15 +288,15 @@
Visibility="Collapsed" /> Visibility="Collapsed" />
<Button <Button
x:Name="btnAdd" x:Name="btnAdd"
Grid.Row="9" Grid.Row="8"
Grid.Column="1" Grid.Column="1"
MinWidth="48" MinWidth="48"
Padding="4" Padding="4"
HorizontalAlignment="Left" HorizontalAlignment="Left"
Click="btnAdd_Click" Click="btnAddReturnPackage_Click"
Content="添 加" Content="添 加"
IsEnabled="False" IsEnabled="False"
Style="{StaticResource BasePageButtonStyle}" /> Style="{StaticResource BasePageButtonStyle}" Height="28" Margin="0,53,0,0" Grid.RowSpan="2" VerticalAlignment="Top" />
<Image <Image
x:Name="imgLoading" x:Name="imgLoading"
Grid.Row="9" Grid.Row="9"
@@ -29,108 +29,180 @@ namespace _29WxOrderWpf.Windows.OrderWindows
/// </summary> /// </summary>
public partial class TransitAfterSaleWindow : BaseWindow public partial class TransitAfterSaleWindow : BaseWindow
{ {
public int PackType { get; set; }
public oms_wei_order_item_info OrderItem { get; set; } public oms_wei_order_item_info OrderItem { get; set; }
public oms_wei_order_item_transit_detail_info TransitInfo { get; set; }
public oms_wei_external_procurement_log_info TransitOrder { get; set; } = null;
public oms_wei_transfer_extra_package ExtraPackage { get; set; } = null;
public TransitAfterSaleWindow(oms_wei_order_item_info orderItem) public TransitAfterSaleWindow(oms_wei_order_item_info orderItem, oms_wei_order_item_transit_detail_info _transitInfo)
{ {
InitializeComponent(); InitializeComponent();
if (orderItem != null) if (orderItem != null)
OrderItem = orderItem; OrderItem = orderItem;
} if (_transitInfo != null)
TransitInfo = _transitInfo;
if (_transitInfo?.oms_wei_external_procurement_log_info != null)
TransitOrder = _transitInfo?.oms_wei_external_procurement_log_info;
else if (_transitInfo?.oms_wei_transfer_extra_package != null)
ExtraPackage = _transitInfo?.oms_wei_transfer_extra_package;
PackType = _transitInfo?.TransitTypeStr == "额外包裹" ? 2 : 1;
}
private void mainGrid_Loaded(object sender, RoutedEventArgs e) private void mainGrid_Loaded(object sender, RoutedEventArgs e)
{ {
} }
private async void TransitAfterSaleWindow_Loaded(object sender, RoutedEventArgs e) private async void TransitAfterSaleWindow_Loaded(object sender, RoutedEventArgs e)
{ {
btnAdd.IsEnabled = true; btnAdd.IsEnabled = true;
foreach (var warehouse in TransitWarehouseData.TransitWarehouseList) foreach (var warehouse in TransitWarehouseData.TransitWarehouseList)
{ {
this.cmbWareHouse.Items.Add(warehouse.TransName); this.cmbWareHouse.Items.Add(warehouse.TransName);
} }
if (OrderItem != null) if (OrderItem != null && TransitInfo != null)
{ {
this.cmbWareHouse.Text = TransitWarehouseData.TransitWarehouseList.FirstOrDefault(t => t.TransId == OrderItem.ItemTransitOrderWithVoid?.platform)?.TransName;
this.txtExpressName.Text = OrderItem.ItemTransitOrder?.express_2_company ?? OrderItem.ItemTransitOrderWithVoid?.express_2_company;
this.txtWarehouseWaybill.Text = OrderItem.ItemTransitOrder?.express_2_waybill ?? OrderItem.ItemTransitOrderWithVoid?.express_2_waybill;
if (OrderItem.ItemTransitOrderAfterSale != null) if (ExtraPackage != null)
{ {
btnAdd.IsEnabled = false; // 获取额外包裹对应的发货包裹或者发货包裹本身
var _transitOrder = OrderItem.ItemTransitOrders.FirstOrDefault(t => t.order_code == ExtraPackage?.order_code);
this.txtUser.Text = OrderItem.ItemTransitOrderAfterSale.recipient_name; this.cmbWareHouse.Text = TransitWarehouseData.TransitWarehouseList.FirstOrDefault(t => t.TransId == _transitOrder?.platform)?.TransName;
this.txtMobile.Text = OrderItem.ItemTransitOrderAfterSale.recipient_phone; this.txtExpressName.Text = string.IsNullOrWhiteSpace(ExtraPackage.real_logistics_code) ? ExtraPackage.logistics_code : ExtraPackage?.real_logistics_code;
this.txtDetailAddress.Text = OrderItem.ItemTransitOrderAfterSale.refund_detail_address; this.txtWarehouseWaybill.Text = string.IsNullOrWhiteSpace(ExtraPackage?.real_logistics_express_code) ? ExtraPackage?.logistics_express_code : ExtraPackage?.real_logistics_express_code;
//this.txtAddress.Text = OrderItem.ItemTransitOrderAfterSale.refund_province + "/" + OrderItem.ItemTransitOrderAfterSale.refund_city + "/" + OrderItem.ItemTransitOrderAfterSale.refund_county;
this.txtProvince.Text = OrderItem.ItemTransitOrderAfterSale.refund_province; var transitAfterSale = OrderItem.ItemTransitOrderAfterSales?.OrderByDescending(t => t.id)?.FirstOrDefault(t => t.order_code == ExtraPackage.order_code && t.order_void_status != 1 && t.pack_type == PackType);
this.txtCity.Text = OrderItem.ItemTransitOrderAfterSale.refund_city; if (transitAfterSale != null)
this.txtCounty.Text = OrderItem.ItemTransitOrderAfterSale.refund_county;
}
else
{
// 需要手动申请售后的,先去申请售后再提交拦截退回总店
if (!string.IsNullOrEmpty(OrderItem.ItemTransitOrderWithVoid?.out_order_no) && OrderItem.PddBuyerAfterSaleAddressStr.IsNullOrEmpty() &&
OrderItem.TransitRefundStatusStr.Contains("需手动申请售后") || OrderItem.TransitRefundStatusStr.Contains("待用户发货"))
{ {
btnAdd.IsEnabled = false; btnAdd.IsEnabled = false;
imgLoading.Visibility = Visibility.Visible;
await MainWindow.Instance.orderListCtrl.DoBuyerRefend(new List<oms_wei_order_item_info>() { OrderItem });
var order = GlobalConfig.lstOrder.FirstOrDefault(o => o.order_id == OrderItem.order_id);
if (order != null)
{
var orderItemTmp = order.orderItems.FirstOrDefault(oi => oi.sku_id == OrderItem.sku_id);
if (orderItemTmp != null)
OrderItem = orderItemTmp;
}
btnAdd.IsEnabled = true;
}
if (OrderItem.PddBuyerAfterSale?.orderSn == OrderItem.ItemTransitOrder?.out_order_no && !string.IsNullOrEmpty(OrderItem.PddBuyerAfterSale?.afterSaleAddress)) this.txtUser.Text = transitAfterSale.recipient_name;
this.txtMobile.Text = transitAfterSale.recipient_phone;
this.txtDetailAddress.Text = transitAfterSale.refund_detail_address;
//this.txtAddress.Text = transitAfterSale.refund_province + "/" + transitAfterSale.refund_city + "/" + transitAfterSale.refund_county;
this.txtProvince.Text = transitAfterSale.refund_province;
this.txtCity.Text = transitAfterSale.refund_city;
this.txtCounty.Text = transitAfterSale.refund_county;
}
else
{ {
txtAddressAnalysis.Text = OrderItem.PddBuyerAfterSale?.afterSaleAddress; var pddBuyerAfterSale = OrderItem.PddBuyerAfterSales.FirstOrDefault(af => af.orderSn == _transitOrder?.out_order_no);
btnAddressAnalysis_Click(null, null);
// 需要手动申请售后的,先去申请售后再提交拦截退回总店
if (!string.IsNullOrEmpty(_transitOrder?.out_order_no) && !string.IsNullOrEmpty(pddBuyerAfterSale?.afterSaleAddress) &&
(_transitOrder.refund_status.ParseToString().Contains("需手动申请售后") || _transitOrder.refund_status.ParseToString().Contains("待用户发货")))
{
btnAdd.IsEnabled = false;
imgLoading.Visibility = Visibility.Visible;
await MainWindow.Instance.orderListCtrl.DoBuyerRefend(new List<oms_wei_order_item_info>() { OrderItem });
var order = GlobalConfig.lstOrder.FirstOrDefault(o => o.order_id == OrderItem.order_id);
if (order != null)
{
var orderItemTmp = order.orderItems.FirstOrDefault(oi => oi.sku_id == OrderItem.sku_id);
if (orderItemTmp != null)
OrderItem = orderItemTmp;
}
btnAdd.IsEnabled = true;
}
pddBuyerAfterSale = OrderItem.PddBuyerAfterSales.FirstOrDefault(af => af.orderSn == _transitOrder?.out_order_no);
if (!string.IsNullOrEmpty(pddBuyerAfterSale?.afterSaleAddress))
{
txtAddressAnalysis.Text = pddBuyerAfterSale?.afterSaleAddress;
btnAddressAnalysis_Click(null, null);
}
} }
} }
imgLoading.Visibility = Visibility.Collapsed; else if(TransitOrder != null)
// 如果提交过工单,则显示已提交工单及提交时间。
var workOrderInfo = await GetWorkOrder();
var issueType = BaseRegex.GetStringJson(ref workOrderInfo, "issueType");
var createTime = BaseRegex.GetStringJson(ref workOrderInfo, "createdAt").ParseToString().ParseToDateTime();
if (!string.IsNullOrEmpty(issueType))
{ {
lblWorkOrderMsg.Content = "已提交工单(" + createTime.ParseToString() + ")"; this.cmbWareHouse.Text = TransitWarehouseData.TransitWarehouseList.FirstOrDefault(t => t.TransId == TransitOrder?.platform)?.TransName;
this.txtExpressName.Text = string.IsNullOrWhiteSpace(TransitOrder?.express_2_waybill) ? TransitOrder?.express_1_company : TransitOrder?.express_2_company;
this.txtWarehouseWaybill.Text = string.IsNullOrWhiteSpace(TransitOrder?.express_2_waybill) ? TransitOrder?.express_1_waybill : TransitOrder?.express_2_waybill;
if (this.txtExpressName.Text.IsNullOrEmpty() || this.txtWarehouseWaybill.Text.IsNullOrEmpty())
{
this.txtExpressName.Text = OrderItem.PddBuyerOrders.FirstOrDefault(p => p.order_sn == TransitOrder?.out_order_no)?.outExpressCompanyCode;
this.txtWarehouseWaybill.Text = OrderItem.PddBuyerOrders.FirstOrDefault(p => p.order_sn == TransitOrder?.out_order_no)?.tracking_number;
if (!string.IsNullOrWhiteSpace(this.txtExpressName.Text) && !string.IsNullOrWhiteSpace(this.txtWarehouseWaybill.Text))
{
// 没物流信息的仓库单手动更新买手物流信息
JObject data = new JObject();
data["orderNo"] = OrderItem.order_id;
data["orderCode"] = TransitOrder?.order_code;
data["logisticsExpressCode"] = this.txtWarehouseWaybill.Text;
data["logisticsExpressCompany"] = this.txtExpressName.Text;
var updateTransitExpressUrl = "https://po.e57.cn/prod-api/api/oms-api/external_procurement/orders/updateLogisticsExpressCode";
var updateTransitExpressStr = JsonHelper.SerializeObject(data);
var updateTransitExpressRst = HttpResponseWXBLL.e57PostResponse(updateTransitExpressUrl, updateTransitExpressStr, "");
}
}
var transitAfterSale = OrderItem.ItemTransitOrderAfterSales?.OrderByDescending(t => t.id)?.FirstOrDefault(t => t.order_code == TransitOrder.order_code && t.order_void_status != 1 && t.pack_type == PackType);
if (transitAfterSale != null)
{
btnAdd.IsEnabled = false;
this.txtUser.Text = transitAfterSale.recipient_name;
this.txtMobile.Text = transitAfterSale.recipient_phone;
this.txtDetailAddress.Text = transitAfterSale.refund_detail_address;
//this.txtAddress.Text = transitAfterSale.refund_province + "/" + transitAfterSale.refund_city + "/" + transitAfterSale.refund_county;
this.txtProvince.Text = transitAfterSale.refund_province;
this.txtCity.Text = transitAfterSale.refund_city;
this.txtCounty.Text = transitAfterSale.refund_county;
}
else
{
// 需要手动申请售后的,先去申请售后再提交拦截退回总店
if (!string.IsNullOrEmpty(TransitOrder?.out_order_no) && OrderItem.PddBuyerAfterSaleAddressStr.IsNullOrEmpty() &&
(TransitOrder.refund_status.ParseToString().Contains("需手动申请售后") || TransitOrder.refund_status.ParseToString().Contains("待用户发货")))
{
btnAdd.IsEnabled = false;
imgLoading.Visibility = Visibility.Visible;
await MainWindow.Instance.orderListCtrl.DoBuyerRefend(new List<oms_wei_order_item_info>() { OrderItem });
var order = GlobalConfig.lstOrder.FirstOrDefault(o => o.order_id == OrderItem.order_id);
if (order != null)
{
var orderItemTmp = order.orderItems.FirstOrDefault(oi => oi.sku_id == OrderItem.sku_id);
if (orderItemTmp != null)
OrderItem = orderItemTmp;
}
btnAdd.IsEnabled = true;
}
if (OrderItem.PddBuyerAfterSale?.orderSn == TransitOrder?.out_order_no && !string.IsNullOrEmpty(OrderItem.PddBuyerAfterSale?.afterSaleAddress))
{
txtAddressAnalysis.Text = OrderItem.PddBuyerAfterSale?.afterSaleAddress;
btnAddressAnalysis_Click(null, null);
}
}
} }
} }
//if (OrderItem?.ItemTransitOrder?.warehouse_status != 0 && OrderItem?.ItemTransitOrder?.warehouse_status != 1) // 如果提交过工单,则显示已提交工单及提交时间。
////if (OrderItem?.ItemTransitOrderWithVoid?.warehouse_status != 0 && OrderItem?.ItemTransitOrderWithVoid?.warehouse_status != 1) var workOrderInfo = await GetWorkOrder();
//{ var issueType = BaseRegex.GetStringJson(ref workOrderInfo, "issueType");
// btnAdd.IsEnabled = false; var createTime = BaseRegex.GetStringJson(ref workOrderInfo, "createdAt").ParseToString().ParseToDateTime();
// //BaseMsgWindow.ShowError("当前订单仓库状态不支持售后,请联系买家直接退回总店!"); if (!string.IsNullOrEmpty(issueType))
// lblMsg.Content = "当前订单仓库状态不支持售后,请联系买家直接退回总店!"; {
// return; lblWorkOrderMsg.Content = "已提交工单(" + createTime.ParseToString() + ")";
//} }
imgLoading.Visibility = Visibility.Collapsed;
}
if ((OrderItem?.ItemTransitOrder?.warehouse_status).ParseToInt() < 1) private async void btnAddReturnPackage_Click(object sender, RoutedEventArgs e)
{
//btnAdd.IsEnabled = false;
//lblMsg.Content = "当前订单仓库状态不支持拦截退回总店,建议联系买家直接退回总店!";
}
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{ {
if (string.IsNullOrEmpty(lblWorkOrderMsg.Content.ParseToString())) if (string.IsNullOrEmpty(lblWorkOrderMsg.Content.ParseToString()))
{ {
var workOrder = AddWorkOrder(); // 后续为独立创建工单
// 创建拦截退货包裹工单
var workOrder = await AddWorkOrderAsync();
if (!workOrder.Contains("\"success\":true")) if (!workOrder.Contains("\"success\":true"))
{ {
BaseMsgWindow.ShowError("中转拦截包裹添加失败," + BaseRegex.GetStringJson(ref workOrder, "message"), "", this); BaseMsgWindow.ShowError("拦截工单添加失败," + BaseRegex.GetStringJson(ref workOrder, "message"), "", this);
return; return;
} }
} }
@@ -151,7 +223,7 @@ namespace _29WxOrderWpf.Windows.OrderWindows
JObject data = new JObject(); JObject data = new JObject();
data["orderNo"] = OrderItem.order_id; data["orderNo"] = OrderItem.order_id;
data["orderCode"] = OrderItem.ItemTransitOrderWithVoid?.order_code; data["orderCode"] = TransitOrder?.order_code ?? ExtraPackage?.batchId; /* 发货单填写发货单code,额外包裹填写额外包裹新单号 */
data["refundProvince"] = txtProvince.Text.Trim(); data["refundProvince"] = txtProvince.Text.Trim();
data["refundCity"] = txtCity.Text.Trim(); data["refundCity"] = txtCity.Text.Trim();
data["refundCounty"] = txtCounty.Text.Trim(); data["refundCounty"] = txtCounty.Text.Trim();
@@ -160,6 +232,7 @@ namespace _29WxOrderWpf.Windows.OrderWindows
data["recipientPhone"] = txtMobile.Text.Trim(); data["recipientPhone"] = txtMobile.Text.Trim();
data["account_user"] = BaseClass.UserName; data["account_user"] = BaseClass.UserName;
data["accountUser"] = BaseClass.UserName; data["accountUser"] = BaseClass.UserName;
data["packType"] = PackType; /* 1正常发货拦截退回,2额外包裹拦截退回, */
//data["platform"] = "WEISHOP"; //data["platform"] = "WEISHOP";
if (GlobalConfig.BuyConfig.IsUseAppBalance) if (GlobalConfig.BuyConfig.IsUseAppBalance)
@@ -174,20 +247,19 @@ namespace _29WxOrderWpf.Windows.OrderWindows
var getTransitAfterSaleUrl = "https://po.e57.cn/prod-api/api/oms-api/external_procurement/createReturnPackage"; var getTransitAfterSaleUrl = "https://po.e57.cn/prod-api/api/oms-api/external_procurement/createReturnPackage";
var getTransitAfterSaleStr = JsonHelper.SerializeObject(data); var getTransitAfterSaleStr = JsonHelper.SerializeObject(data);
var getTransitAfterSaleRst = HttpResponseWXBLL.e57PostResponse(getTransitAfterSaleUrl, getTransitAfterSaleStr, ""); var getTransitAfterSaleRst = await HttpResponseWXBLL.e57PostResponseAsync(getTransitAfterSaleUrl, getTransitAfterSaleStr);
if (!getTransitAfterSaleRst.ParseToString().Contains("<code>200</code>") && !getTransitAfterSaleRst.ParseToString().Contains("<code>0</code>")) if (!getTransitAfterSaleRst.ParseToString().Contains("\"code\":0") && !getTransitAfterSaleRst.ParseToString().Contains("\"code\":200"))
{ {
string msg = BaseRegex.GetStringXml(ref getTransitAfterSaleRst, "msg"); string msg = BaseRegex.GetStringJsonByRegs(ref getTransitAfterSaleRst, getTransitAfterSaleRst, "msg");
if (msg.IsNullOrEmpty()) BaseMsgWindow.ShowError("拦截退货包裹添加失败,服务端返回 " + msg, "", this);
msg = getTransitAfterSaleRst;
BaseMsgWindow.ShowError("中转售后添加失败,服务端返回 " + msg, "", this);
} }
else else
{ {
//<AjaxResult><msg>创建退货包裹成功</msg><code>0</code></AjaxResult> //<AjaxResult><msg>创建退货包裹成功</msg><code>0</code></AjaxResult>
MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id); await MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id);
Task.Run(() => { MainWindow.Instance.orderListCtrl.FilterOrders(); }); //MainWindow.Instance.orderListCtrl.FilterOrders();
BaseMsgWindow.ShowInfo("添加退货包裹成功", "", this); StartUp.UpdateBalance();
BaseMsgWindow.ShowInfo("添加拦截退货包裹成功", "", this);
this.Close(); this.Close();
} }
} }
@@ -247,30 +319,28 @@ namespace _29WxOrderWpf.Windows.OrderWindows
{ {
} }
public string AddWorkOrder() public async Task<string> AddWorkOrderAsync()
{ {
if (OrderItem.ItemTransitOrder?.warehouse_status == 3) if (TransitOrder?.warehouse_status == 3)
return "\"success\":true,\"message\":\"已到仓,无需拦截工单\"";
if (OrderItem.ItemTransitOrderWithVoid?.warehouse_status == 3)
return "\"success\":true,\"message\":\"已到仓,无需拦截工单\""; return "\"success\":true,\"message\":\"已到仓,无需拦截工单\"";
string url = HttpResponseTransitWorkOrderBLL.WorkOrderUrl + "/api/open/v1/customer-work-orders/intercept-return-cloud-warehouse-after-outbound"; string url = HttpResponseTransitWorkOrderBLL.WorkOrderUrl + "/api/open/v1/customer-work-orders/intercept-return-cloud-warehouse-after-outbound";
JObject obj = new JObject(); JObject obj = new JObject();
obj["appId"] = this.OrderItem.Shop?.ShopId; obj["appId"] = this.OrderItem.ItemOrder?.Shop?.ShopId;
obj["wechatOrderNo"] = this.OrderItem.order_id; obj["wechatOrderNo"] = this.OrderItem.order_id;
//obj["purchaseOrderNo"] = this.OrderItem.PddBuyerAfterSale?.orderSn; //obj["purchaseOrderNo"] = this.OrderItem.PddBuyerAfterSale?.orderSn;
obj["purchaseOrderNo"] = OrderItem.ItemTransitOrderWithVoid?.order_code; obj["purchaseOrderNo"] = TransitOrder?.order_code;
obj["creator"] = BaseClass.UserName; obj["creator"] = BaseClass.UserName;
obj["remark"] = "客户要求拦截并退回云仓"; obj["remark"] = "客户要求拦截并退回云仓";
var rst = HttpResponseTransitWorkOrderBLL.PostResponse(this.OrderItem.Shop, url, JsonHelper.SerializeObject(obj), ""); var rst = await HttpResponseTransitWorkOrderBLL.PostResponseAsync(this.OrderItem.ItemOrder?.Shop, url, JsonHelper.SerializeObject(obj), "");
return rst; return rst;
} }
public async Task<string> GetWorkOrder() public async Task<string> GetWorkOrder()
{ {
string url = HttpResponseTransitWorkOrderBLL.WorkOrderUrl + "/api/open/v1/customer-work-orders?wechatOrderNo=" + this.OrderItem.order_id; string url = HttpResponseTransitWorkOrderBLL.WorkOrderUrl + "/api/open/v1/customer-work-orders?wechatOrderNo=" + this.OrderItem.order_id;
var rst = await HttpResponseTransitWorkOrderBLL.GetResponseAsync(this.OrderItem.Shop, url, ""); var rst = await HttpResponseTransitWorkOrderBLL.GetResponseAsync(this.OrderItem.ItemOrder?.Shop, url, "");
return rst; return rst;
} }
} }
@@ -130,7 +130,7 @@ namespace _29WxOrderWpf.Windows.OrderWindows
} }
} }
private void btnAdd_Click(object sender, RoutedEventArgs e) private async void btnAdd_Click(object sender, RoutedEventArgs e)
{ {
if (OrderItem?.ItemOrder?.OrderBuyType == "云仓" && (OrderItem?.ItemTransitOrder?.warehouse_status).ParseToInt() < 1) if (OrderItem?.ItemOrder?.OrderBuyType == "云仓" && (OrderItem?.ItemTransitOrder?.warehouse_status).ParseToInt() < 1)
{ {
@@ -199,7 +199,7 @@ namespace _29WxOrderWpf.Windows.OrderWindows
(jObj["orderDetailsList"] as JArray).Add(jItemObj); (jObj["orderDetailsList"] as JArray).Add(jItemObj);
var returnOrders = OrderListCtrl.GetTransitReturnOrderList(OrderItem.order_id); var returnOrders = await OrderGetOrderListHelper.GetTransitReturnOrderList(OrderItem.order_id);
OrderItem.DistribReturnOrderInfos = returnOrders; OrderItem.DistribReturnOrderInfos = returnOrders;
if (btnAdd.Content.ToString() == "添 加" && OrderItem.DistribReturnOrderInfo == null) if (btnAdd.Content.ToString() == "添 加" && OrderItem.DistribReturnOrderInfo == null)
{ {
@@ -211,18 +211,18 @@ namespace _29WxOrderWpf.Windows.OrderWindows
string msg = BaseRegex.GetStringXml(ref getTransitAfterSaleRst, "msg"); string msg = BaseRegex.GetStringXml(ref getTransitAfterSaleRst, "msg");
if (msg.IsNullOrEmpty()) if (msg.IsNullOrEmpty())
msg = getTransitAfterSaleRst; msg = getTransitAfterSaleRst;
BaseMsgWindow.ShowError("中转仓退货订单添加失败,服务端返回 " + msg); BaseMsgWindow.ShowError("订单 " + OrderItem.order_id + " 中转仓退货订单添加失败,服务端返回 " + msg);
return; return;
} }
} }
returnOrders = OrderListCtrl.GetTransitReturnOrderList(OrderItem.order_id); returnOrders = await OrderGetOrderListHelper.GetTransitReturnOrderList(OrderItem.order_id);
OrderItem.DistribReturnOrderInfos = returnOrders; OrderItem.DistribReturnOrderInfos = returnOrders;
var orderCode = OrderItem.DistribReturnOrderInfo.order_code; var orderCode = OrderItem.DistribReturnOrderInfo.order_code;
if (string.IsNullOrEmpty(orderCode)) if (string.IsNullOrEmpty(orderCode))
{ {
BaseMsgWindow.ShowError("中转仓退货订单创建失败,售后单获取失败"); BaseMsgWindow.ShowError("订单 " + OrderItem.order_id + " 中转仓退货订单创建失败,售后单获取失败");
MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id); await MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id);
return; return;
} }
var createReturnOrderUrl = "https://po.e57.cn/prod-api/api/oms-api/api/distribution/returns/createReturnOrder"; var createReturnOrderUrl = "https://po.e57.cn/prod-api/api/oms-api/api/distribution/returns/createReturnOrder";
@@ -239,17 +239,17 @@ namespace _29WxOrderWpf.Windows.OrderWindows
if (msg.IsNullOrEmpty()) if (msg.IsNullOrEmpty())
msg = createReturnOrderRst; msg = createReturnOrderRst;
BaseMsgWindow.ShowError("中转仓退货订单创建失败,服务端返回 " + msg); BaseMsgWindow.ShowError("中转仓退货订单创建失败,服务端返回 " + msg);
MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id); await MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id);
return; return;
} }
MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id); await MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id);
StartUp.UpdateBalance(); StartUp.UpdateBalance();
BaseMsgWindow.ShowInfo("中转仓退货订单创建成功", "", this); BaseMsgWindow.ShowInfo("中转仓退货订单创建成功", "", this);
this.Close(); this.Close();
} }
public static void AddReturnOrder(oms_wei_order_item_info OrderItem) public static async Task AddReturnOrder(oms_wei_order_item_info OrderItem)
{ {
// 订单不存在或已作废的,直接返回 // 订单不存在或已作废的,直接返回
if (OrderItem == null || OrderItem.ItemRefund == null) if (OrderItem == null || OrderItem.ItemRefund == null)
@@ -325,7 +325,7 @@ namespace _29WxOrderWpf.Windows.OrderWindows
(jObj["orderDetailsList"] as JArray).Add(jItemObj); (jObj["orderDetailsList"] as JArray).Add(jItemObj);
var returnOrders = OrderListCtrl.GetTransitReturnOrderList(OrderItem.order_id); var returnOrders = await OrderGetOrderListHelper.GetTransitReturnOrderList(OrderItem.order_id);
OrderItem.DistribReturnOrderInfos = returnOrders; OrderItem.DistribReturnOrderInfos = returnOrders;
if (OrderItem.DistribReturnOrderInfo == null) if (OrderItem.DistribReturnOrderInfo == null)
{ {
@@ -337,18 +337,18 @@ namespace _29WxOrderWpf.Windows.OrderWindows
string msg = BaseRegex.GetStringXml(ref getTransitAfterSaleRst, "msg"); string msg = BaseRegex.GetStringXml(ref getTransitAfterSaleRst, "msg");
if (msg.IsNullOrEmpty()) if (msg.IsNullOrEmpty())
msg = getTransitAfterSaleRst; msg = getTransitAfterSaleRst;
BaseMsgWindow.ShowAnimateMessage("中转仓退货订单添加失败,服务端返回 " + msg, "Error", 5); BaseMsgWindow.ShowAnimateMessage("订单 " + OrderItem.order_id + " 中转仓退货订单添加失败,服务端返回 " + msg, "Error", 5);
return; return;
} }
} }
returnOrders = OrderListCtrl.GetTransitReturnOrderList(OrderItem.order_id); returnOrders = await OrderGetOrderListHelper.GetTransitReturnOrderList(OrderItem.order_id);
OrderItem.DistribReturnOrderInfos = returnOrders; OrderItem.DistribReturnOrderInfos = returnOrders;
var orderCode = OrderItem.DistribReturnOrderInfo.order_code; var orderCode = OrderItem.DistribReturnOrderInfo.order_code;
if (string.IsNullOrEmpty(orderCode)) if (string.IsNullOrEmpty(orderCode))
{ {
BaseMsgWindow.ShowAnimateMessage("中转仓退货订单创建失败,售后单获取失败", "Error", 5); BaseMsgWindow.ShowAnimateMessage("订单 " + OrderItem.order_id + " 中转仓退货订单创建失败,售后单获取失败", "Error", 5);
MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id); await MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id);
return; return;
} }
var createReturnOrderUrl = "https://po.e57.cn/prod-api/api/oms-api/api/distribution/returns/createReturnOrder"; var createReturnOrderUrl = "https://po.e57.cn/prod-api/api/oms-api/api/distribution/returns/createReturnOrder";
@@ -363,16 +363,16 @@ namespace _29WxOrderWpf.Windows.OrderWindows
string msg = BaseRegex.GetStringXml(ref createReturnOrderRst, "msg"); string msg = BaseRegex.GetStringXml(ref createReturnOrderRst, "msg");
if (msg.IsNullOrEmpty()) if (msg.IsNullOrEmpty())
msg = createReturnOrderRst; msg = createReturnOrderRst;
BaseMsgWindow.ShowAnimateMessage("中转仓退货订单创建失败,服务端返回 " + msg, "Error", 5); BaseMsgWindow.ShowAnimateMessage("订单 " + OrderItem.order_id + " 中转仓退货订单创建失败,服务端返回 " + msg, "Error", 5);
MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id); await MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id);
return; return;
} }
//MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id); //MainWindow.Instance.orderListCtrl.GetOrder(OrderItem.order_id);
returnOrders = OrderListCtrl.GetTransitReturnOrderList(OrderItem.order_id); returnOrders = await OrderGetOrderListHelper.GetTransitReturnOrderList(OrderItem.order_id);
OrderItem.DistribReturnOrderInfos = returnOrders; OrderItem.DistribReturnOrderInfos = returnOrders;
StartUp.UpdateBalance(); StartUp.UpdateBalance();
BaseMsgWindow.ShowAnimateMessage("中转仓退货订单创建成功", "Msg", 2); BaseMsgWindow.ShowAnimateMessage("订单 " + OrderItem.order_id + " 中转仓退货订单创建成功", "Msg", 2);
} }
private void btnAddressAnalysis_Click(object sender, RoutedEventArgs e) private void btnAddressAnalysis_Click(object sender, RoutedEventArgs e)
+1
View File
@@ -46,6 +46,7 @@
<!-- Framework assemblies not already implied by UseWindowsForms/UseWPF --> <!-- Framework assemblies not already implied by UseWindowsForms/UseWPF -->
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Management" /> <Reference Include="System.Management" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Web.Services" /> <Reference Include="System.Web.Services" />
</ItemGroup> </ItemGroup>
+13 -2
View File
@@ -37,9 +37,19 @@ namespace AllBase
/// 版本ID /// 版本ID
/// </summary> /// </summary>
public static int VersionCount = 327; public static int VersionCount = 392;
public static string ServerUrl { get; set; } = "http://1.13.195.131:9000"; //public static string ServerUrl { get; set; } = "http://1.13.195.131:9000";
public static string ServerUrl
{
get
{
var url = "http://1.13.195.131:9000";
//if (Randomx.GetId(3) < 2)
// url = "http://119.45.29.75:9000";
return url;
}
}
public static string DebugUrl { get; set; } = "http://localhost:9000"; public static string DebugUrl { get; set; } = "http://localhost:9000";
@@ -594,6 +604,7 @@ namespace AllBase
public static string PassWordBak { get; set; } public static string PassWordBak { get; set; }
public static string Mobile { get; set; } public static string Mobile { get; set; }
public static bool AllowTraditionalBuyAddress { get; set; }
public static string ParentAuthority { get; set; } public static string ParentAuthority { get; set; }
public static string ForbiddenPage { get; set; } public static string ForbiddenPage { get; set; }
public static string UserAuthority { get; set; } public static string UserAuthority { get; set; }
+4 -4
View File
@@ -20,10 +20,10 @@ namespace AllBase.Helper
{ {
public class GlobalConfig public class GlobalConfig
{ {
/// <summary> /// <summary>
/// 颜色等图形元素需要在主线程操作 /// 颜色等图形元素需要在主线程操作
/// </summary> /// </summary>
public static Dispatcher Dispatcher { get; set; } public static Dispatcher Dispatcher { get; set; }
/// <summary> /// <summary>
/// 店铺列表 /// 店铺列表
/// </summary> /// </summary>
+93 -5
View File
@@ -1,10 +1,14 @@
using System; using CefSharp.DevTools.IO;
using System;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
@@ -385,11 +389,11 @@ namespace AllBase
} }
} }
public static BitmapImage LoadBitmipImageFromUrl(string url) public static BitmapImage LoadBitmipImageFromUrl(string url, int? width = null, int? height = null)
{ {
BitmapImage bitmap = new BitmapImage(); BitmapImage bitmap = new BitmapImage();
try try
{ {
using (WebClient webClient = new WebClient()) using (WebClient webClient = new WebClient())
{ {
@@ -398,15 +402,99 @@ namespace AllBase
{ {
stream.Position = 0; // 重置流的位置到开始处 stream.Position = 0; // 重置流的位置到开始处
bitmap.BeginInit(); bitmap.BeginInit();
bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat; if (width != null && height != null)
{
bitmap.DecodePixelWidth = width.Value;
bitmap.DecodePixelHeight = height.Value;
}
bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
bitmap.CacheOption = BitmapCacheOption.OnLoad; // 或者使用 BitmapCacheOption.OnLoad 以减少内存使用 bitmap.CacheOption = BitmapCacheOption.OnLoad; // 或者使用 BitmapCacheOption.OnLoad 以减少内存使用
bitmap.UriSource = null; // 清除可能的旧UriSource,防止缓存问题 bitmap.UriSource = null; // 清除可能的旧UriSource,防止缓存问题
bitmap.StreamSource = stream; bitmap.StreamSource = stream;
bitmap.EndInit(); bitmap.EndInit();
bitmap.Freeze(); // 防止后续更改,提高性能 bitmap.Freeze(); // 防止后续更改,提高性能
} }
} }
}
catch (Exception ex)
{
// 处理异常,例如打印错误信息或设置一个默认图片等
//Console.WriteLine("Error loading image: " + ex.Message);
return null;
} }
return bitmap;
}
public static async Task<BitmapImage> LoadBitmipImageFromUrlAsync(string url, int? width = null, int? height = null)
{
BitmapImage bitmap = new BitmapImage();
try
{
//using (WebClient webClient = new WebClient())
//{
//webClient.DownloadDataCompleted += (sender, e) =>
//{
// if (e.Cancelled)
// {
// //Console.WriteLine("下载已取消");
// bitmap = null;
// }
// else if (e.Error != null)
// {
// //Console.WriteLine("下载出错: " + e.Error.Message);
// bitmap = null;
// }
// else
// {
// byte[] data = (byte[])e.Result;
// //string text = System.Text.Encoding.UTF8.GetString(data);
// //Console.WriteLine(text);
// // 下载图片数据到内存流
// using (MemoryStream stream = new MemoryStream(data))
// {
// stream.Position = 0; // 重置流的位置到开始处
// bitmap.BeginInit();
// if (width != null && height != null)
// {
// bitmap.DecodePixelWidth = width.Value;
// bitmap.DecodePixelHeight = height.Value;
// }
// bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
// bitmap.CacheOption = BitmapCacheOption.OnLoad; // 或者使用 BitmapCacheOption.OnLoad 以减少内存使用
// bitmap.UriSource = null; // 清除可能的旧UriSource,防止缓存问题
// bitmap.StreamSource = stream;
// bitmap.EndInit();
// bitmap.Freeze(); // 防止后续更改,提高性能
// }
// }
//};
//await webClient.DownloadDataAsync(new Uri(url));
//}
using (HttpClient client = new HttpClient())
{
// 下载图片数据到内存流
using (MemoryStream stream = new MemoryStream(await client.GetByteArrayAsync(url)))
{
stream.Position = 0; // 重置流的位置到开始处
bitmap.BeginInit();
if (width != null && height != null)
{
bitmap.DecodePixelWidth = width.Value;
//bitmap.DecodePixelHeight = height.Value;
}
bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
bitmap.CacheOption = BitmapCacheOption.OnLoad; // 或者使用 BitmapCacheOption.OnLoad 以减少内存使用
bitmap.UriSource = null; // 清除可能的旧UriSource,防止缓存问题
bitmap.StreamSource = stream;
bitmap.EndInit();
bitmap.Freeze(); // 防止后续更改,提高性能
}
}
}
catch (Exception ex) catch (Exception ex)
{ {
// 处理异常,例如打印错误信息或设置一个默认图片等 // 处理异常,例如打印错误信息或设置一个默认图片等
+15
View File
@@ -15,4 +15,19 @@ public class SettingConfig
/// </summary> /// </summary>
public bool AutoSwitchGiftType { get; set; } = true; public bool AutoSwitchGiftType { get; set; } = true;
#endregion #endregion
#region 拍单
/// <summary>
/// 允许直发拍单
/// </summary>
public bool SwitchEnableDirectBuy { get; set; } = false;
/// <summary>
/// 拼多多仓库订单使用随机繁体字
/// </summary>
public bool SwitchEnablePddTransitTraditionalAddress { get; set; } = false;
/// <summary>
/// 是否显示使用随机繁体字配置(不显示则不可使用繁体字)
/// </summary>
public bool ShowEnablePddTransitTraditionalAddress { get; set; } = false;
#endregion
} }
+10 -2
View File
@@ -58,8 +58,16 @@ namespace AllBase.Model.DBModel
public string LoginStatusStr public string LoginStatusStr
{ {
get { return this.GetValue(x => x.LoginStatusStr); } get { return this.GetValue(x => x.LoginStatusStr); }
set { this.SetValue(x => x.LoginStatusStr, value); } set { this.SetValue(x => x.LoginStatusStr, value);
} //LoginStatusStrColor = value == "在线" ? new SolidColorBrush(Color.FromRgb(50, 180, 50)) : new SolidColorBrush(Color.FromRgb(255, 50, 50));
LoginStatusStrColor = value == "在线" ? GlobalConfig.GreenTextBrush : GlobalConfig.RedTextBrush;
}
}
public SolidColorBrush LoginStatusStrColor
{
get { return this.GetValue(x => x.LoginStatusStrColor); }
set { this.SetValue(x => x.LoginStatusStrColor, value); }
}
public string LoginStatus public string LoginStatus
{ {
get { return this.GetValue(x => x.LoginStatus); } get { return this.GetValue(x => x.LoginStatus); }
+73 -7
View File
@@ -39,18 +39,81 @@ namespace AllBase.Model.DBModel
public int district_id { get; set; } public int district_id { get; set; }
public string province_name { get;set; } public string province_name { get;set; }
public string city_name { get; set; } public string city_name { get; set; }
} public string district_name { get; set; }
}
public class TransitWarehouseData public class TransitWarehouseData
{ {
public static string TransitWarehouseDataStr = @" public static Dictionary<string, string> dicWarehouseIdName = new Dictionary<string, string>()
{
{ "XDYBJC", "北京仓" },
{ "XDYGZC", "广州仓" },
{ "XDYWHC", "武汉2仓" },
{ "XDYSHANDC", "山东2仓" },
{ "XDYSHC", "上海新仓" },
{ "XDYSZC", "深圳仓" },
{ "XDYYWC", "义乌仓" },
{ "XDYJJC", "晋江仓" },
{ "XDYCDC", "成都仓" },
{ "XDYCHONGQC", "重庆2仓" },
{ "XDYHEBC", "哈尔滨仓" },
{ "XDYXA", "西安仓" },
{ "XDYGYC", "贵阳仓" },
{ "XDYKMC", "昆明仓" },
{ "XDYSSC", "河北仓" },
{ "XDYZZC", "郑州仓" },
{ "XDYFJSSC", "福建仓" },
};
public static string TransitWarehouseDataStr = @"
XDYBJC ;北京仓 ;胡萍 ;18565773752 ;北京市顺义区光明街道滨河小区七区1号楼 ;2 ;52 ;511 ;北京市 ;北京市 ;顺义区 ;光明街道 ;滨河小区七区1号楼108室 XDYBJC ;北京仓 ;胡萍 ;18565773752 ;北京市顺义区光明街道滨河小区七区1号楼 ;2 ;52 ;511 ;北京市 ;北京市 ;顺义区 ;光明街道 ;滨河小区七区1号楼108室
XDYGZC ;广州仓 ;何外华 ;13826339849 ;广州市增城区朱村街道育山一路68号国际物流园 ;6 ;76 ;702 ;广东省 ;广州市 ;增城区 ;朱村街道 ;育山一路68号国际物流园 XDYGZC ;广州仓 ;何外华 ;13826339849 ;广州市增城区朱村街道育山一路68号国际物流园 ;6 ;76 ;702 ;广东省 ;广州市 ;增城区 ;朱村街道 ;育山一路68号国际物流园
XDYWHC ;武汉2仓 ;杨先生 ;13044121071 ;湖北省武汉市江汉区民族街道沿江大道轮渡龙王庙码头 ;13 ;180 ;1546 ;湖北省 ;武汉市 ;江汉区 ;民族街道 ;沿江大道轮渡龙王庙码头 XDYWHC ;武汉2仓 ;杨先生 ;13044121071 ;湖北省武汉市江汉区民族街道沿江大道轮渡龙王庙码头 ;13 ;180 ;1546 ;湖北省 ;武汉市 ;江汉区 ;民族街道 ;沿江大道轮渡龙王庙码头
XDYSHANDC ;山东2仓 ;鸿鹄小申 ;13044121239 ;山东省临沂市费县南外环东转盘往东200米顺通快递有限公司(仓库二楼) ;22 ;292 ;2415 ;山东省 ;临沂市 ;费县 ;费城街道 ;南外环东转盘往东200米顺通快递有限公司(仓库二楼) XDYSHANDC ;山东2仓 ;鸿鹄小申 ;13044121239 ;山东省临沂市费县南外环东转盘往东200米顺通快递有限公司(仓库二楼) ;22 ;292 ;2415 ;山东省 ;临沂市 ;费县 ;费城街道 ;南外环东转盘往东200米顺通快递有限公司(仓库二楼)
XDYSHC ;上海新仓 ;纪先生 ;13044121150 ;上海市上海市普陀区真如镇街道真北路2653弄T区 ;25 ;321 ;2709 ;上海市 ;上海市 ;普陀区 ;真如镇街道 ;真北路2653弄T区 XDYSHC ;上海新仓 ;纪先生 ;13044121150 ;上海市徐汇区徐家汇街道虹桥路616号A座 ;25 ;321 ;2706 ;上海市 ;上海市 ;徐汇区 ;徐家汇街道 ;虹桥路616号A座
XDYSZC ;深圳仓 ;峰峰 ;15343351331 ;广东省东莞市凤岗镇浸校塘东良巷逸乐轩E栋5号楼 ;6 ;79 ;732 ;广东省 ;东莞市 ;凤岗镇 ;凤岗街道 ;浸校塘东良巷逸乐轩E栋5号楼"; XDYSZC ;深圳仓 ;峰峰 ;15343351331 ;广东省东莞市凤岗镇浸校塘东良巷逸乐轩E栋5号楼 ;6 ;79 ;732 ;广东省 ;东莞市 ;凤岗镇 ;凤岗街道 ;浸校塘东良巷逸乐轩E栋5号楼
//XDYYWC ;义乌仓 ;小田 ;19058117371 ;浙江省义乌市后宅街道金城高尔夫二期别墅区401栋 ;31 ;386 ;3409 ;浙江省 ;金华市 ;义乌市 ;后宅街道 ;金城高尔夫二期别墅区401栋 XDYYWC ;义乌仓 ;小田 ;19058117371 ;浙江省金华市义乌市后宅街道金城高尔夫二期别墅区401栋 ;31 ;386 ;3409 ;浙江省 ;金华市 ;义乌市 ;后宅街道 ;金城高尔夫二期别墅区401栋
XDYFJSSC ;福建仓 ;小张 ;13799125513 ;福建省泉州市晋江市青阳街道中堡电商园一栋 ;4 ;58 ;568 ;福建省 ;泉州市 ;晋江市 ;青阳街道 ;中堡电商园一栋";
public static Dictionary<char, List<char>> dicChineseNumberChar = new Dictionary<char, List<char>>()
{
{ '1', new List<char> { '一', '壹' } },
{ '2', new List<char> { '二', '贰' } },
{ '3', new List<char> { '三', '叁' } },
{ '4', new List<char> { '四', '肆' } },
{ '5', new List<char> { '五', '伍' } },
{ '6', new List<char> { '六', '陆' } },
{ '7', new List<char> { '七', '柒' } },
{ '8', new List<char> { '八', '捌' } },
{ '9', new List<char> { '九', '玖' } },
{ '0', new List<char> { '零', '〇' } },
{ '一', new List<char> { '壹' } },
{ '二', new List<char> { '贰' } },
{ '三', new List<char> { '叁' } },
{ '四', new List<char> { '肆' } },
{ '五', new List<char> { '伍' } },
{ '六', new List<char> { '陆' } },
{ '七', new List<char> { '柒' } },
{ '八', new List<char> { '捌' } },
{ '九', new List<char> { '玖' } },
{ '零', new List<char> { '〇' } },
};
// public static string TransitWarehouseDataStrTraditional = @"
//XDYBJC ;北京仓 ;胡萍 ;18565773752 ;北京市順義區光明街道濱河小區七區一號樓 ;2 ;52 ;511 ;北京市 ;北京市 ;顺义区 ;光明街道 ;濱河小區七區一號樓一零八室
//XDYGZC ;广州仓 ;何外华 ;13826339849 ;廣州市增城區朱村街道育山一路六八號國際物流園 ;6 ;76 ;702 ;广东省 ;广州市 ;增城区 ;朱村街道 ;育山一路六八號國際物流園
//XDYWHC ;武汉2仓 ;杨先生 ;13044121071 ;湖北省武漢市江漢區民族街道沿江大道輪渡龍王廟碼頭 ;13 ;180 ;1546 ;湖北省 ;武汉市 ;江汉区 ;民族街道 ;沿江大道輪渡龍王廟碼頭
//XDYSHANDC ;山东2仓 ;鸿鹄小申 ;13044121239 ;山東省臨沂市費縣南外環東轉盤往東二零零米順通快遞有限公司(倉庫二樓) ;22 ;292 ;2415 ;山东省 ;临沂市 ;费县 ;費城街道 ;南外環東轉盤往東二零零米順通快遞有限公司(倉庫二樓)
//XDYSHC ;上海新仓 ;纪先生 ;13044121150 ;上海市徐匯區徐家匯街道虹橋路六一六號A座 ;25 ;321 ;2706 ;上海市 ;上海市 ;徐汇区 ;徐家匯街道 ;虹橋路六一六號A座
//XDYSZC ;深圳仓 ;峰峰 ;15343351331 ;廣東省東莞市鳳崗鎮浸校塘東良巷逸樂軒E棟五號樓 ;6 ;79 ;732 ;广东省 ;东莞市 ;凤岗镇 ;鳳崗街道 ;浸校塘東良巷逸樂軒E棟五號樓
//XDYYWC ;义乌仓 ;小田 ;19058117371 ;浙江省金华市义乌市後宅街道金城高爾夫二期別墅區四零一棟 ;31 ;386 ;3409 ;浙江省 ;金华市 ;义乌市 ;後宅街道 ;金城高爾夫二期別墅區四零一棟
//XDYFJSSC ;福建仓 ;小张 ;13799125513 ;福建省泉州市晋江市青陽街道中堡電商園一棟 ;4 ;58 ;568 ;福建省 ;泉州市 ;晋江市 ;青陽街道 ;中堡電商園一棟";
//XDYSHC ;上海新仓 ;纪先生 ;13044121150 ;上海市上海市徐汇区徐家汇街道虹桥路616号A座 ;25 ;321 ;2706 ;上海市 ;上海市 ;徐汇区 ;徐家汇街道 ;虹桥路616号A座
//XDYSHC ;上海新仓 ;纪先生 ;13044121150 ;上海市上海市普陀区真如镇街道真北路2653弄T区 ;25 ;321 ;2709 ;上海市 ;上海市 ;普陀区 ;真如镇街道 ;真北路2653弄T区
//XDYFJSSC 石狮仓 福建省/泉州市/晋江市青阳街道中堡电商园一栋
//XDYYWC ;义乌仓 ;小田 ;19058117371 ;浙江省金华市义乌市北苑街道西站大道妈妈商贸18号库39号楼誉达 ;31 ;386 ;3409 ;浙江省 ;金华市 ;义乌市 ;北苑街道 ;西站大道妈妈商贸18号库39号楼誉达 //XDYYWC ;义乌仓 ;小田 ;19058117371 ;浙江省金华市义乌市北苑街道西站大道妈妈商贸18号库39号楼誉达 ;31 ;386 ;3409 ;浙江省 ;金华市 ;义乌市 ;北苑街道 ;西站大道妈妈商贸18号库39号楼誉达
//XDYJJC ;晋江仓 ;安群 ;19905951984 ;福建省泉州市南安市霞美镇温山村431号鸿鹄大厦 ;4 ;58 ;569 ;福建省 ;泉州市 //XDYJJC ;晋江仓 ;安群 ;19905951984 ;福建省泉州市南安市霞美镇温山村431号鸿鹄大厦 ;4 ;58 ;569 ;福建省 ;泉州市
//XDYCDC ;成都仓 ;谢春虹 ;15828201479 ;四川省资阳市乐至县仙鹤大道桑都街15-19号仓库(不要放驿站,送到仓库) ;26 ;340 ;2898 ;四川省 ;资阳市 //XDYCDC ;成都仓 ;谢春虹 ;15828201479 ;四川省资阳市乐至县仙鹤大道桑都街15-19号仓库(不要放驿站,送到仓库) ;26 ;340 ;2898 ;四川省 ;资阳市
@@ -74,7 +137,7 @@ XDYSZC ;深圳仓 ;峰峰 ;15343351331 ;广东省东莞市凤岗镇浸
static List<TransitWarehouseParam> transitWarehouseList = null; static List<TransitWarehouseParam> transitWarehouseList = null;
public static List<TransitWarehouseParam> TransitWarehouseList public static List<TransitWarehouseParam> TransitWarehouseList
{ {
get get
{ {
@@ -100,6 +163,7 @@ XDYSZC ;深圳仓 ;峰峰 ;15343351331 ;广东省东莞市凤岗镇浸
district_id = arr[7].Trim().ParseToInt(), district_id = arr[7].Trim().ParseToInt(),
province_name = arr[8].Trim(), province_name = arr[8].Trim(),
city_name = arr[9].Trim(), city_name = arr[9].Trim(),
district_name = arr[10].Trim(),
}; };
transitWarehouseList.Add(tw); transitWarehouseList.Add(tw);
} }
@@ -111,5 +175,7 @@ XDYSZC ;深圳仓 ;峰峰 ;15343351331 ;广东省东莞市凤岗镇浸
{ {
} }
} }
}
static List<TransitWarehouseParam> transitWarehouseTList = null;
}
} }
@@ -97,5 +97,26 @@ namespace AllBase.Model.DBModel
/// 下游快递公司编码 /// 下游快递公司编码
/// </summary> /// </summary>
public string downstream_express_code { get; set; } public string downstream_express_code { get; set; }
} /// <summary>
/// 订单初始费用(分)
/// </summary>
public int? postage { get; set; }
public DateTime? pickup_time { get; set; }
/// <summary>
/// 货架号
/// </summary>
public string location_code { get; set; }
/// <summary>
/// 货架写入时间
/// </summary>
public DateTime? location_write_time { get; set; }
/// <summary>
/// 1商品退货包裹2额外退货包裹
/// </summary>
public int? pack_type { get; set; }
/// <summary>
/// 作废状态 1作废成功 2作废失败
/// </summary>
public int? order_void_status { get; set; }
}
} }
@@ -13,24 +13,55 @@ namespace AllBase.Model.DBModel
public class oms_wei_external_procurement_log_info : PropertyNotifyObject public class oms_wei_external_procurement_log_info : PropertyNotifyObject
{ {
public string OutOrderNumStr public string OutOrderNumStr
{ {
get { return out_order_no; } get {
set { } if (this.order_no == "3739906242901888256")
} {
}
return this.GetValue(x => x.OutOrderNumStr);
}
set { this.SetValue(x => x.OutOrderNumStr, value); }
}
public string OutOrderBuyerStr public string OutOrderBuyerStr
{ {
get { return this.GetValue(x => x.OutOrderBuyerStr); } get { return this.GetValue(x => x.OutOrderBuyerStr); }
set { this.SetValue(x => x.OutOrderBuyerStr, value); } set { this.SetValue(x => x.OutOrderBuyerStr, value); }
} }
public string OutOrderBuyerIdStr
{
get { return this.GetValue(x => x.OutOrderBuyerIdStr); }
set { this.SetValue(x => x.OutOrderBuyerIdStr, value); }
}
public void SetOutOrderBuyerStr() public void SetOutOrderBuyerStr()
{ {
OutOrderBuyerStr = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(b => b.buyer_id == buyer_account)?.buyer_name ?? if (!out_order_no.ParseToString().StartsWith("tb_"))
GlobalConfig.TaobaoBuyerLoginList.FirstOrDefault(b => b.buyer_id == buyer_account)?.buyer_name ?? buyer_account; {
var buyer = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(b => b.buyer_id == buyer_account);
OutOrderBuyerStr = buyer?.buyer_name ?? buyer_account;
OutOrderBuyerIdStr = buyer?.buyer_id ?? buyer_account;
}
else
{
var buyer = GlobalConfig.TaobaoBuyerLoginList.FirstOrDefault(b => b.buyer_id == buyer_account);
OutOrderBuyerStr = buyer?.buyer_name ?? buyer_account;
OutOrderBuyerIdStr = buyer?.buyer_id ?? buyer_account;
}
} }
public long id { get; set; } public long id { get; set; }
public string out_order_no { get; set; } public string out_order_no
{
get { return this.GetValue(x => x.out_order_no); }
set
{
if (this.order_no == "3739906242901888256")
{
}
this.SetValue(x => x.out_order_no, value); OutOrderNumStr = value;
}
}
public string order_no { get; set; } public string order_no { get; set; }
public string order_sku_id { get; set; } public string order_sku_id { get; set; }
public string buyer_account { get; set; } public string buyer_account { get; set; }
@@ -127,5 +158,29 @@ namespace AllBase.Model.DBModel
/// 拦截退回操作信息/回调信息 /// 拦截退回操作信息/回调信息
/// </summary> /// </summary>
public string intercept_return_info { get; set; } public string intercept_return_info { get; set; }
/// <summary>
/// 是否手动发货:0自动发货,1手动发货
/// </summary>
public int is_manual_shipment { get; set; }
/// <summary>
/// 手动发货处理状态:0未处理,1成功,2失败
/// </summary>
public int? manual_shipment_status { get; set; }
/// <summary>
/// 货架号
/// </summary>
public string location_code { get; set; }
/// <summary>
/// 货架写入时间
/// </summary>
public DateTime? location_write_time { get; set; }
/// <summary>
/// 虚拟快递单号
/// </summary>
public string virtual_waybill_no { get; set; }
/// <summary>
/// 虚拟快递公司
/// </summary>
public string virtual_express_company { get; set; }
} }
} }
+95 -32
View File
@@ -13,6 +13,7 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Media; using System.Windows.Media;
using static System.Windows.Forms.VisualStyles.VisualStyleElement; using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
@@ -28,13 +29,27 @@ namespace AllBase.Model.DBModel
public ShopLoginInfo Shop public ShopLoginInfo Shop
{ {
get { return this.GetValue(x => x.Shop); } get { return this.GetValue(x => x.Shop); }
set { this.SetValue(x => x.Shop, value); } set { this.SetValue(x => x.Shop, value); if (!(Shop?.ShopAccount).IsNullOrEmpty()) shop_name = Shop?.ShopAccount; }
}
public int Index
{
get { return GlobalConfig.lstFilterOrder.IndexOf(this) + 1; }
}
public string OrderDiffItemCountStr
{
get { return this.GetValue(x => x.OrderDiffItemCountStr); }
set { this.SetValue(x => x.OrderDiffItemCountStr, value); }
} }
public string OrderBuyType public string OrderBuyType
{ {
get { return this.GetValue(x => x.OrderBuyType); } get { return this.GetValue(x => x.OrderBuyType); }
set { this.SetValue(x => x.OrderBuyType, value); } set { this.SetValue(x => x.OrderBuyType, value); OrderBuyTypeVisibility = string.IsNullOrWhiteSpace(value) ? Visibility.Collapsed : Visibility.Visible; }
}
public Visibility OrderBuyTypeVisibility
{
get { return this.GetValue(x => x.OrderBuyTypeVisibility); }
set { this.SetValue(x => x.OrderBuyTypeVisibility, value); }
} }
public SolidColorBrush OrderBuyTypeColor public SolidColorBrush OrderBuyTypeColor
{ {
@@ -43,6 +58,31 @@ namespace AllBase.Model.DBModel
} }
public ObservableCollection<oms_wei_order_item_info> orderItems { get; set; } = new ObservableCollection<oms_wei_order_item_info>(); public ObservableCollection<oms_wei_order_item_info> orderItems { get; set; } = new ObservableCollection<oms_wei_order_item_info>();
public oms_wei_order_item_info orderItem
{
get { return this.GetValue(x => x.orderItem); }
set { this.SetValue(x => x.orderItem, value); }
}
public oms_wei_order_item_info orderItem2
{
get { return this.GetValue(x => x.orderItem2); }
set { this.SetValue(x => x.orderItem2, value); }
}
public oms_wei_order_item_info orderItem3
{
get { return this.GetValue(x => x.orderItem3); }
set { this.SetValue(x => x.orderItem3, value); }
}
public oms_wei_order_item_info orderItem4
{
get { return this.GetValue(x => x.orderItem4); }
set { this.SetValue(x => x.orderItem4, value); }
}
public oms_wei_order_item_info orderItem5
{
get { return this.GetValue(x => x.orderItem5); }
set { this.SetValue(x => x.orderItem5, value); }
}
public ObservableCollection<oms_wei_refund_info> refundItems { get; set; } = new ObservableCollection<oms_wei_refund_info>(); public ObservableCollection<oms_wei_refund_info> refundItems { get; set; } = new ObservableCollection<oms_wei_refund_info>();
@@ -136,6 +176,8 @@ namespace AllBase.Model.DBModel
//状态10 待付款;20 待发货;21 部分发货;30 待收货;100 完成;200 全部商品售后之后,订单取消;250 未付款用户主动取消或超时未付款订单自动取消; //状态10 待付款;20 待发货;21 部分发货;30 待收货;100 完成;200 全部商品售后之后,订单取消;250 未付款用户主动取消或超时未付款订单自动取消;
if (status == 10) if (status == 10)
orderStatusStr = "待付款"; orderStatusStr = "待付款";
else if (status == 20)
orderStatusStr = "待发货";
else if (status == 21) else if (status == 21)
orderStatusStr = "部分发货"; orderStatusStr = "部分发货";
else if (status == 30) else if (status == 30)
@@ -377,12 +419,24 @@ namespace AllBase.Model.DBModel
get { return this.GetValue(x => x.IsSelect); } get { return this.GetValue(x => x.IsSelect); }
set { this.SetValue(x => x.IsSelect, value); } set { this.SetValue(x => x.IsSelect, value); }
} }
public bool is_visible { get; set; } = true; public Visibility OutAccountStrVisibility
{
get { return this.GetValue(x => x.OutAccountStrVisibility); }
set { this.SetValue(x => x.OutAccountStrVisibility, value); }
}
//public bool is_visible { get; set; } = true;
public long id { get; set; } public long id { get; set; }
public long shop_id { get; set; } public long shop_id
public string shop_name { get; set; } {
get { return this.GetValue(x => x.shop_id); }
set { this.SetValue(x => x.shop_id, value); }
}
public string shop_name
{
get { return this.GetValue(x => x.shop_name); }
set { this.SetValue(x => x.shop_name, value); }
}
/// <summary> /// <summary>
/// 商户ID /// 商户ID
/// </summary> /// </summary>
@@ -407,7 +461,11 @@ namespace AllBase.Model.DBModel
/// <summary> /// <summary>
/// 状态10 待付款;20 待发货;21 部分发货;30 待收货;100 完成;200 全部商品售后之后,订单取消;250 未付款用户主动取消或超时未付款订单自动取消; /// 状态10 待付款;20 待发货;21 部分发货;30 待收货;100 完成;200 全部商品售后之后,订单取消;250 未付款用户主动取消或超时未付款订单自动取消;
/// </summary> /// </summary>
public int? status { get; set; } public int? status
{
get { return this.GetValue(x => x.status); }
set { this.SetValue(x => x.status, value); SetOrderStatusStr(); }
}
/// <summary> /// <summary>
/// 售后信息json /// 售后信息json
/// </summary> /// </summary>
@@ -639,7 +697,11 @@ namespace AllBase.Model.DBModel
/// <summary> /// <summary>
/// 外采账户 /// 外采账户
/// </summary> /// </summary>
public string out_account { get; set; } public string out_account
{
get { return this.GetValue(x => x.out_account); }
set { this.SetValue(x => x.out_account, value); OutAccountStrVisibility = string.IsNullOrWhiteSpace(value) ? Visibility.Collapsed : Visibility.Visible; }
}
/// <summary> /// <summary>
/// 外采订单号 /// 外采订单号
/// </summary> /// </summary>
@@ -691,27 +753,25 @@ namespace AllBase.Model.DBModel
public void SetOrderTextProperty() public void SetOrderTextProperty()
{ {
SetOrderStatusStr();
Shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == shop_id.ParseToString()); Shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ErpShopId == shop_id.ParseToString());
if (this.orderItems.Any(oi => oi.OrderItemExt?.buy_type == "直发") && this.orderItems.Any(oi => oi.ItemTransitOrderWithVoid != null)) if (this.orderItems.Any(oi => oi.OrderItemExt?.buy_type == "直发") && this.orderItems.Any(oi => oi.ItemTransitOrderWithVoid != null))
{ {
OrderBuyType = "云改直"; OrderBuyType = "云改直";
OrderBuyTypeColor = GlobalConfig.PurpleBrush190; OrderBuyTypeColor = GlobalConfig.PurpleBrush190;
} }
else if (this.orderItems.Any(oi => oi.OrderItemExt?.buy_type == "直发")) else if (this.orderItems.Any(oi => oi.OrderItemExt?.buy_type == "直发"))
{ {
OrderBuyType = "直发"; OrderBuyType = "直发";
OrderBuyTypeColor = GlobalConfig.RedTextBrush205; OrderBuyTypeColor = GlobalConfig.RedTextBrush205;
} }
else if (this.orderItems.Any(oi => oi.ItemTransitOrderWithVoid != null)) else if (this.orderItems.Any(oi => oi.ItemTransitOrderWithVoid != null))
{ {
OrderBuyType = "云仓"; OrderBuyType = "云仓";
OrderBuyTypeColor = GlobalConfig.GreenTextBrush; OrderBuyTypeColor = GlobalConfig.GreenTextBrush;
} }
else else
OrderBuyType = ""; OrderBuyType = "";
if (this.orderItems.Any(oi => oi.ItemRefund?.type == "REFUND")) if (this.orderItems.Any(oi => oi.ItemRefund?.type == "REFUND"))
this.RefundTypeStr = "仅退款"; this.RefundTypeStr = "仅退款";
@@ -744,8 +804,15 @@ namespace AllBase.Model.DBModel
SetDeliveryDeadlineStr(); SetDeliveryDeadlineStr();
SetStatusBoxColor(); SetStatusBoxColor();
SetOutExpressNo(); SetOutExpressNo();
SetShipDoneTimeStr(); SetShipDoneTimeStr();
SetColorBrush(); SetColorBrush();
orderItem = orderItems.FirstOrDefault() != null ? orderItems.FirstOrDefault() : new oms_wei_order_item_info() { OrderItemVisibility = Visibility.Collapsed };
orderItem2 = orderItems.Count > 1 ? orderItems[1] : new oms_wei_order_item_info() { OrderItemVisibility = Visibility.Collapsed };
orderItem3 = orderItems.Count > 2 ? orderItems[2] : new oms_wei_order_item_info() { OrderItemVisibility = Visibility.Collapsed };
orderItem4 = orderItems.Count > 3 ? orderItems[3] : new oms_wei_order_item_info() { OrderItemVisibility = Visibility.Collapsed };
orderItem5 = orderItems.Count > 4 ? orderItems[4] : new oms_wei_order_item_info() { OrderItemVisibility = Visibility.Collapsed };
OrderDiffItemCountStr = orderItems.Count > 1 ? "该订单共有 " + orderItems.Count + " 个不同的商品规格" : "";
} }
public void SetColorBrush() public void SetColorBrush()
@@ -766,10 +833,6 @@ namespace AllBase.Model.DBModel
public bool GetIsWaitBuy() public bool GetIsWaitBuy()
{ {
if (order_id == "3738686976228742912")
{
}
if (status != 20 && status != 21) if (status != 20 && status != 21)
return false; return false;
if (refundItems?.Any(r => r.IsRefund) == true) if (refundItems?.Any(r => r.IsRefund) == true)
@@ -851,7 +914,7 @@ namespace AllBase.Model.DBModel
return true; return true;
// 订单无售后或者售后关闭,有未作废的仓库单且仓库单买手信息为退款成功 // 订单无售后或者售后关闭,有未作废的仓库单且仓库单买手信息为退款成功
if (orderItems.Any(oi => oi.refund_status <= 1 && oi.ItemTransitOrder != null && oi.ItemTransitOrder.refund_status == "买手退款成功")) if (orderItems.Any(oi => oi.refund_status <= 1 && oi.ItemTransitOrderWithVoid != null && oi.ItemTransitOrderWithVoid.refund_status == "买手退款成功"))
return true; return true;
// 取号异常或无法调用发货也放在异常单(异常需重拍) // 取号异常或无法调用发货也放在异常单(异常需重拍)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,801 @@
using AllBase.Helper;
using AllBase.Model.MvvmBaseClasses;
using NaiBa.Util.Extension;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace AllBase.Model.DBModel;
public class oms_wei_order_item_transit_model : PropertyNotifyObject
{
public oms_wei_order_item_info OrderItem
{
get { return this.GetValue(x => x.OrderItem); }
set
{
this.SetValue(x => x.OrderItem, value);
GetOrderItemTransitList();
}
}
public ObservableCollection<oms_wei_order_item_transit_detail_info> OrderItemTransitDetailList
{
get { return this.GetValue(x => x.OrderItemTransitDetailList); }
private set { this.SetValue(x => x.OrderItemTransitDetailList, value); }
}
private bool isGetLatestPackageInfo = false;
public oms_wei_order_item_transit_model (bool _isGetLatestPackage = false)
{
isGetLatestPackageInfo = _isGetLatestPackage;
}
void GetOrderItemTransitList()
{
List<oms_wei_order_item_transit_detail_info> transitDetailList =
[
.. GetOrderItemTransitDetailList(),
.. GetOrderItemTransitAftersaleList(),
.. GetOrderItemTransitExtraList(),
];
this.OrderItemTransitDetailList = new ObservableCollection<oms_wei_order_item_transit_detail_info>(transitDetailList);
}
/// <summary>
/// 获取发货包裹对应信息列表
/// </summary>
/// <returns></returns>
List<oms_wei_order_item_transit_detail_info> GetOrderItemTransitDetailList()
{
if (OrderItem == null || OrderItem.ItemOrder == null)
{
return new List<oms_wei_order_item_transit_detail_info>();
}
List<oms_wei_order_item_transit_detail_info> detailList = new List<oms_wei_order_item_transit_detail_info>();
foreach (var transitOrder in OrderItem.ItemTransitOrders ?? new List<oms_wei_external_procurement_log_info>())
{
try
{
var transitDetail = new oms_wei_order_item_transit_detail_info()
{
oms_wei_order_item_info = OrderItem,
oms_wei_external_procurement_log_info = transitOrder,
ShopName = OrderItem.ItemOrder.shop_name,
TransitTypeStr = "发货包裹",
OrderCode = transitOrder.order_code,
SourceCode = transitOrder.random_code,
WxOrderId = transitOrder.order_no,
WxOrderSkuId = transitOrder.order_sku_id,
WxOrderThumbImg = OrderItem.thumb_img,
WxOrderCreateTime = OrderItem.ItemOrder.CreateDateTime,
TransitAddTimeStr = transitOrder.created_time.ToString("yyyy-MM-dd HH:mm:ss"),
OutOrderId = transitOrder.out_order_no,
OutBuyerName = transitOrder.OutOrderBuyerStr,
//UpperWaybill = transitOrder.express_1_waybill != transitOrder.virtual_waybill_no ? "" : (transitOrder.express_1_company + "-" + transitOrder.express_1_waybill).Trim('-'),
UpperWaybill = transitOrder.pre_allocated_order_no != 1 && transitOrder.pre_allocated_order_no != 3 ? "" : (transitOrder.express_1_company + "-" + transitOrder.express_1_waybill).Trim('-'),
DownWaybill = (transitOrder.express_2_company + "-" + transitOrder.express_2_waybill).Trim('-'),
BuyRefundStatus = transitOrder.refund_status,
CreateTime = transitOrder.created_time == DateTime.MinValue ? null : transitOrder.created_time,
PickUpTime = transitOrder.pickup_time == DateTime.MinValue ? null : transitOrder.pickup_time,
InboundTime = transitOrder.inbound_time,
OutboundTime = transitOrder.outbound_time,
WarehouseId = transitOrder.platform,
WarehouseName = TransitWarehouseData.dicWarehouseIdName.ContainsKey(transitOrder.platform) ? TransitWarehouseData.dicWarehouseIdName[transitOrder.platform] : transitOrder.platform,
ShelfCodeStr = transitOrder.location_code,
ShelfTimeStr = transitOrder.location_write_time == null ? "" : transitOrder.location_write_time.Value.ToString("yyyy-MM-dd HH:mm:ss"),
};
if (!transitDetail.OutOrderId.StartsWith("tb_"))
transitDetail.OutBuyerId = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(b => b.buyer_id == transitOrder.buyer_account)?.buyer_id ?? "";
else
transitDetail.OutBuyerId = GlobalConfig.TaobaoBuyerLoginList.FirstOrDefault(b => b.buyer_id == transitOrder.buyer_account)?.buyer_id ?? "";
// 中转仓订单创建状态 0 未使用,1 已创建,2 创建失败,3 处理中(业务方根据此字段处理中转流程)
if (transitOrder.transfer_warehouse_status == 0)
transitDetail.TransitStatus = "未使用";
if (transitOrder.transfer_warehouse_status == 1)
transitDetail.TransitStatus = "已创建";
else if (transitOrder.transfer_warehouse_status == 2)
transitDetail.TransitStatus = "创建失败";
else if (transitOrder.transfer_warehouse_status == 3)
transitDetail.TransitStatus = "创建中";
else if (transitOrder.transfer_warehouse_status == 4)
transitDetail.TransitStatus = "取号失败";
// 中转仓入库状态 0: 未入库, 1: 已入库, 2: 已出库, 3: 拦截到仓
if (transitOrder.transfer_warehouse_status == 4)
transitDetail.WarehouseStatus = "取号失败";
else if ((transitOrder.raw_message.ParseToString().Contains("取号异常") || transitOrder.raw_message.ParseToString().Contains("无法调用")) && transitOrder.transfer_warehouse_status != 1)
transitDetail.WarehouseStatus = transitOrder.raw_message.Contains("超出派送范围") ? "取号异常(超区)" : "取号异常";
else if (transitOrder.pickup_time > DateTime.MinValue == false)
transitDetail.WarehouseStatus = "未取号";
else if (transitOrder.warehouse_status == null || transitOrder.warehouse_status == 0)
transitDetail.WarehouseStatus = "未入库";
else if (transitOrder.warehouse_status == 1)
transitDetail.WarehouseStatus = "已入库";
else if (transitOrder.warehouse_status == 2)
transitDetail.WarehouseStatus = "已出库";
else if (transitOrder.warehouse_status == 3)
transitDetail.WarehouseStatus = "已拦截到仓";
if (transitOrder.order_void_status == 1)
transitDetail.TransitVoidStatus = "已作废";
//else if (transitOrder.order_void_status == 2)
// transitDetail.TransitVoidStatus = "作废失败";
if (transitOrder?.has_reject == 1)
transitDetail.TransitRejectStatus = "已申请拒收";
if (transitOrder?.has_reject == 2)
transitDetail.TransitRejectStatus = "申请失败";
if (transitOrder?.has_reject == 3)
transitDetail.TransitRejectStatus = "申请成功";
if (transitOrder?.has_reject == 5)
transitDetail.TransitRejectStatus = "已取消拒收";
if (transitOrder?.has_reject == 99)
transitDetail.TransitRejectStatus = "拒收成功";
var wayBillId = transitOrder.express_2_waybill ?? transitOrder.express_1_waybill;
var transitAfterSaleOrder = /* 取未作废的退货包裹,如果取不到,就取第一个退货包裹 */
OrderItem.ItemTransitOrderAfterSales.FirstOrDefault(a => a.order_code == transitOrder.order_code && a.refund_waybill == wayBillId && a.order_void_status != 1 && a.pack_type == 1) ??
OrderItem.ItemTransitOrderAfterSales.FirstOrDefault(a => a.order_code == transitOrder.order_code && a.refund_waybill == wayBillId && a.pack_type == 1);
if (transitAfterSaleOrder != null)
transitDetail.TransitReturnStatus = "已申请拦截";
if (transitAfterSaleOrder != null && transitAfterSaleOrder.order_void_status == 1)
transitDetail.TransitReturnStatus = "拦截作废";
else if (transitAfterSaleOrder != null && (transitOrder.intercept_return_status == 1 || !string.IsNullOrEmpty(transitAfterSaleOrder?.downstream_waybill)))
transitDetail.TransitReturnStatus = "拦截成功";
else if (transitAfterSaleOrder != null && transitOrder.intercept_return_status == 2)
transitDetail.TransitReturnStatus = "拦截失败";
transitDetail.TransitDetailRefundStatusStr = GetTransitBuyerRefundStatusStr(OrderItem, transitOrder);
//transitDetail.VoidPackageBtnVisibility = !(transitDetail.InboundTime > DateTime.MinValue) && transitOrder.order_void_status != 1 ? Visibility.Visible : Visibility.Collapsed; /* 作废发货包裹按钮 */
//transitDetail.RejectPackageBtnVisibility = !(transitDetail.InboundTime > DateTime.MinValue) ? Visibility.Visible : Visibility.Collapsed; /* 拒收发货包裹按钮 */
//transitDetail.ReturnPackageBtnVisibility = transitDetail.InboundTime > DateTime.MinValue && !(transitDetail.OutboundTime > DateTime.MinValue) &&
// !OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 1 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) &&
// !OrderItem.ItemTransitExtraOrders.Any(af => af.pack_type == "1" && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
// Visibility.Visible : Visibility.Collapsed; /* 退货包裹按钮 */
//transitDetail.InterceptPackageBtnVisibility = transitDetail.OutboundTime > DateTime.MinValue &&
// !OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 1 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) &&
// !OrderItem.ItemTransitExtraOrders.Any(af => af.pack_type == "1" && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
// Visibility.Visible : Visibility.Collapsed; /* 拦截退货包裹按钮 */
//transitDetail.ExtraPackagesBtnVisibility = transitDetail.InboundTime > DateTime.MinValue && !(transitDetail.OutboundTime > DateTime.MinValue) && !(transitDetail.CreateTime > DateTime.Now.AddDays(-4)) &&
// !OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 1 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) &&
// !OrderItem.ItemTransitExtraOrders.Any(af => af.pack_type == "1" && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
// Visibility.Visible : Visibility.Collapsed; /* 额外发货包裹按钮 */
transitDetail.VoidPackageBtnVisibility = transitOrder.warehouse_status == 0 && transitOrder.order_void_status != 1 ? Visibility.Visible : Visibility.Collapsed; /* 作废发货包裹按钮 */
transitDetail.RejectPackageBtnVisibility = OrderItem?.ItemOrder?.GetIsWaitBuy() != true && transitOrder.warehouse_status == 0 ? Visibility.Visible : Visibility.Collapsed; /* 拒收发货包裹按钮 */
transitDetail.ReturnPackageBtnVisibility = (transitOrder.warehouse_status == 1 || transitOrder.warehouse_status == 3 || !transitOrder.location_code.IsNullOrEmpty()) &&
!OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 1 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) &&
!OrderItem.ItemTransitExtraOrders.Any(af => af.pack_type == "1" && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
Visibility.Visible : Visibility.Collapsed; /* 发回退货包裹按钮 */
transitDetail.InterceptPackageBtnVisibility = transitOrder.warehouse_status == 2 &&
!OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 1 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) &&
!OrderItem.ItemTransitExtraOrders.Any(af => af.pack_type == "2" && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
Visibility.Visible : Visibility.Collapsed; /* 拦截退货包裹按钮 */
transitDetail.ExtraPackagesBtnVisibility = ((transitOrder.warehouse_status == 0 || transitOrder.warehouse_status == 1 || transitOrder.warehouse_status == 3 || !transitOrder.location_code.IsNullOrEmpty()) &&
!(transitDetail.CreateTime > DateTime.Now.AddDays(-2)) &&
!OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 1 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) &&
!OrderItem.ItemTransitExtraOrders.Any(af => af.pack_type == "2" && af.order_code == transitDetail.OrderCode && af.order_void_status != 1)) ||
OrderItem._itemOrderIsAbnormal == true ?
Visibility.Visible : Visibility.Collapsed; /* 额外发货包裹按钮 */
//transitDetail.VoidPackageBtnVisibility = Visibility.Visible; /* 作废发货包裹按钮 */
//transitDetail.RejectPackageBtnVisibility = Visibility.Visible; /* 拒收发货包裹按钮 */
//transitDetail.ReturnPackageBtnVisibility = Visibility.Visible; /* 退货包裹按钮 */
//transitDetail.InterceptPackageBtnVisibility = Visibility.Visible; /* 拦截退货包裹按钮 */
//transitDetail.ExtraPackagesBtnVisibility = Visibility.Visible; /* 额外发货包裹按钮 */
detailList.Add(transitDetail);
}
catch (Exception ex)
{
}
}
return detailList;
}
/// <summary>
/// 获取退货包裹对应信息列表
/// </summary>
/// <returns></returns>
List<oms_wei_order_item_transit_detail_info> GetOrderItemTransitAftersaleList()
{
if (OrderItem == null || OrderItem.ItemOrder == null)
{
return new List<oms_wei_order_item_transit_detail_info>();
}
List<oms_wei_order_item_transit_detail_info> detailList = new List<oms_wei_order_item_transit_detail_info>();
foreach (var transitAftersaleOrder in OrderItem.ItemTransitOrderAfterSales ?? new List<oms_wei_external_procurement_after_sale_info>())
{
try
{
var transitOrder = OrderItem.ItemTransitOrders?.FirstOrDefault(t => t.order_code == transitAftersaleOrder.order_code);
var transitDetail = new oms_wei_order_item_transit_detail_info()
{
oms_wei_order_item_info = OrderItem,
oms_wei_external_procurement_after_sale_info = transitAftersaleOrder,
ShopName = OrderItem.ItemOrder.shop_name,
TransitTypeStr = "退货包裹", /* 拦截退回 */
OrderCode = transitAftersaleOrder.order_code + " / " + transitAftersaleOrder.external_order_no,
SourceCode = transitOrder?.random_code,
WxOrderId = transitAftersaleOrder.order_no,
WxOrderSkuId = transitOrder?.order_sku_id,
WxOrderThumbImg = OrderItem.thumb_img,
WxOrderCreateTime = OrderItem.ItemOrder.CreateDateTime,
TransitAddTimeStr = transitAftersaleOrder.created_time == null ? "" : transitAftersaleOrder.created_time.Value.ToString("yyyy-MM-dd HH:mm:ss"),
OutOrderId = transitOrder?.out_order_no,
OutBuyerName = transitOrder?.OutOrderBuyerStr,
UpperWaybill = (transitAftersaleOrder.return_express_company + "-" + transitAftersaleOrder.refund_waybill).Trim('-'),
DownWaybill = (transitAftersaleOrder.downstream_express_code + "-" + transitAftersaleOrder.downstream_waybill).Trim('-'),
BuyRefundStatus = transitOrder.refund_status,
CreateTime = transitAftersaleOrder.created_time,
PickUpTime = transitAftersaleOrder.pickup_time,
InboundTime = transitAftersaleOrder.inbound_time,
OutboundTime = transitAftersaleOrder.outbound_time,
WarehouseId = transitOrder?.platform,
WarehouseName = TransitWarehouseData.dicWarehouseIdName.ContainsKey(transitOrder?.platform) ? TransitWarehouseData.dicWarehouseIdName[transitOrder?.platform] : transitOrder?.platform,
ShelfCodeStr = transitAftersaleOrder.location_code,
ShelfTimeStr = transitAftersaleOrder.location_write_time == null ? "" : transitAftersaleOrder.location_write_time.Value.ToString("yyyy-MM-dd HH:mm:ss"),
};
if (!transitDetail.OutOrderId.StartsWith("tb_"))
transitDetail.OutBuyerId = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(b => b.buyer_id == transitOrder?.buyer_account)?.buyer_id ?? "";
else
transitDetail.OutBuyerId = GlobalConfig.TaobaoBuyerLoginList.FirstOrDefault(b => b.buyer_id == transitOrder?.buyer_account)?.buyer_id ?? "";
// 退货包裹处理状态,0未处理,1处理中,2已完成,9异常
if (transitAftersaleOrder.status == 0)
transitDetail.TransitStatus = "未处理";
if (transitAftersaleOrder.status == 1)
transitDetail.TransitStatus = "处理中";
else if (transitAftersaleOrder.status == 2)
transitDetail.TransitStatus = "已完成";
else if (transitAftersaleOrder.status == 9)
transitDetail.TransitStatus = "异常";
// 退货包裹入库状态 1=入库 2=出库
if (transitAftersaleOrder.warehouse_status == null || transitAftersaleOrder.warehouse_status == 0)
transitDetail.WarehouseStatus = "未入库";
else if (transitAftersaleOrder.warehouse_status == 1)
transitDetail.WarehouseStatus = "已入库";
else if (transitAftersaleOrder.warehouse_status == 2)
transitDetail.WarehouseStatus = "已出库";
else if (transitAftersaleOrder.warehouse_status == 3)
transitDetail.WarehouseStatus = "已拦截到仓";
// 售后作废状态
if (transitAftersaleOrder.order_void_status == 1)
transitDetail.TransitVoidStatus = "已作废";
//else if (transitOrder.order_void_status == 2)
// transitDetail.TransitVoidStatus = "作废失败";
//transitDetail.VoidPackageBtnVisibility = !(transitDetail.InboundTime > DateTime.MinValue) && transitAftersaleOrder.order_void_status != 1 ? Visibility.Visible : Visibility.Collapsed; /* 作废退货包裹 */
transitDetail.VoidPackageBtnVisibility = /*(transitAftersaleOrder.warehouse_status == null || transitAftersaleOrder.warehouse_status == 0 || transitAftersaleOrder.warehouse_status == 1 || transitAftersaleOrder.warehouse_status == 3) &&*/
transitAftersaleOrder.order_void_status != 1 ? Visibility.Visible : Visibility.Collapsed; /* 作废退货包裹 */
//transitDetail.VoidPackageBtnVisibility = Visibility.Visible;
// 售后表没有拒收和拒收状态功能
// 售后表没有拦截和拦截状态功能
// 主表或者额外包裹表的售后状态在主表显示
detailList.Add(transitDetail);
}
catch (Exception ex)
{
}
}
return detailList;
}
/// <summary>
/// 获取额外包裹对应信息列表
/// </summary>
/// <returns></returns>
List<oms_wei_order_item_transit_detail_info> GetOrderItemTransitExtraList()
{
if (OrderItem == null || OrderItem.ItemOrder == null)
{
return new List<oms_wei_order_item_transit_detail_info>();
}
List<oms_wei_order_item_transit_detail_info> detailList = new List<oms_wei_order_item_transit_detail_info>();
foreach (var transitExtraOrder in OrderItem.ItemTransitExtraOrders ?? new List<oms_wei_transfer_extra_package>())
{
try
{
var transitOrder = OrderItem.ItemTransitOrders?.FirstOrDefault(t => t.order_code == transitExtraOrder.order_code);
var transitDetail = new oms_wei_order_item_transit_detail_info()
{
oms_wei_order_item_info = OrderItem,
oms_wei_transfer_extra_package = transitExtraOrder, // 额外包裹
ShopName = OrderItem.ItemOrder.shop_name,
TransitTypeStr = "额外包裹",
OrderCode = transitExtraOrder.order_code + " / " + transitExtraOrder.batchId,
SourceCode = transitOrder?.random_code,
WxOrderId = transitExtraOrder.order_no,
WxOrderSkuId = transitOrder?.order_sku_id,
WxOrderThumbImg = OrderItem.thumb_img,
WxOrderCreateTime = OrderItem.ItemOrder.CreateDateTime,
TransitAddTimeStr = transitExtraOrder.created_time == null ? "" : transitExtraOrder.created_time.Value.ToString("yyyy-MM-dd HH:mm:ss"),
OutOrderId = transitOrder?.out_order_no,
OutBuyerName = transitOrder?.OutOrderBuyerStr,
UpperWaybill = (transitExtraOrder.logistics_code + "-" + transitExtraOrder.logistics_express_code).Trim('-'),
DownWaybill = (transitExtraOrder.real_logistics_code + "-" + transitExtraOrder.real_logistics_express_code).Trim('-'),
BuyRefundStatus = transitOrder.refund_status,
CreateTime = transitExtraOrder.created_time,
PickUpTime = transitExtraOrder.pickup_time,
InboundTime = transitExtraOrder.inbound_time,
OutboundTime = transitExtraOrder.outbound_time,
WarehouseId = transitOrder?.platform,
WarehouseName = TransitWarehouseData.dicWarehouseIdName.ContainsKey(transitOrder?.platform) ? TransitWarehouseData.dicWarehouseIdName[transitOrder?.platform] : transitOrder?.platform,
ShelfCodeStr = transitExtraOrder.location_code,
ShelfTimeStr = transitExtraOrder.location_write_time == null ? "" : transitExtraOrder.location_write_time.Value.ToString("yyyy-MM-dd HH:mm:ss"),
};
if (!transitDetail.OutOrderId.StartsWith("tb_"))
transitDetail.OutBuyerId = GlobalConfig.PDDBuyerLoginList.FirstOrDefault(b => b.buyer_id == transitOrder?.buyer_account)?.buyer_id ?? "";
else
transitDetail.OutBuyerId = GlobalConfig.TaobaoBuyerLoginList.FirstOrDefault(b => b.buyer_id == transitOrder?.buyer_account)?.buyer_id ?? "";
// 额外包裹处理状态,0 未使用,1 已创建,2 创建失败
if (transitExtraOrder.transfer_warehouse_status == 0)
transitDetail.TransitStatus = "未使用";
if (transitExtraOrder.transfer_warehouse_status == 1)
transitDetail.TransitStatus = "已创建";
else if (transitExtraOrder.transfer_warehouse_status == 2)
transitDetail.TransitStatus = "创建失败";
else if (transitExtraOrder.transfer_warehouse_status == 3)
transitDetail.TransitStatus = "处理中";
// 额外包裹入库状态 1=入库 2=出库
if (transitExtraOrder.warehouse_status == null || transitExtraOrder.warehouse_status == 0)
transitDetail.WarehouseStatus = "未入库";
else if (transitExtraOrder.warehouse_status == 1)
transitDetail.WarehouseStatus = "已入库";
else if (transitExtraOrder.warehouse_status == 2)
transitDetail.WarehouseStatus = "已出库";
else if (transitExtraOrder.warehouse_status == 3)
transitDetail.WarehouseStatus = "已拦截到仓";
// 额外包裹作废状态
if (transitExtraOrder.order_void_status == 1)
transitDetail.TransitVoidStatus = "已作废";
//else if (transitExtraOrder.order_void_status == 2)
// transitDetail.TransitVoidStatus = "作废失败";
if (transitExtraOrder?.has_reject == 1)
transitDetail.TransitRejectStatus = "已申请拒收";
if (transitExtraOrder?.has_reject == 2)
transitDetail.TransitRejectStatus = "申请失败";
if (transitExtraOrder?.has_reject == 3)
transitDetail.TransitRejectStatus = "申请成功";
if (transitExtraOrder?.has_reject == 5)
transitDetail.TransitRejectStatus = "已取消拒收";
if (transitExtraOrder?.has_reject == 99)
transitDetail.TransitRejectStatus = "拒收成功";
// 额外包裹拦截状态暂时没有,待补充
var wayBillId = transitExtraOrder.logistics_express_code ?? transitExtraOrder.real_logistics_express_code;
var transitAfterSaleOrder = /* 取未作废的退货包裹,如果取不到,就取第一个退货包裹 */
OrderItem.ItemTransitOrderAfterSales.FirstOrDefault(a => a.order_code == transitExtraOrder.order_code && a.refund_waybill == wayBillId && a.order_void_status != 1 && a.pack_type == 2) ??
OrderItem.ItemTransitOrderAfterSales.FirstOrDefault(a => a.order_code == transitExtraOrder.order_code && a.refund_waybill == wayBillId && a.pack_type == 2);
if (transitAfterSaleOrder != null)
transitDetail.TransitReturnStatus = "已申请拦截";
if (transitAfterSaleOrder != null && transitAfterSaleOrder.order_void_status == 1)
transitDetail.TransitReturnStatus = "拦截作废";
if (transitAfterSaleOrder != null && transitExtraOrder.intercept_return_status == 1 || !string.IsNullOrEmpty(transitAfterSaleOrder?.downstream_waybill))
transitDetail.TransitReturnStatus = "拦截成功";
else if (transitAfterSaleOrder != null && transitExtraOrder.intercept_return_status == 2)
transitDetail.TransitReturnStatus = "拦截失败";
//transitDetail.VoidPackageBtnVisibility = !(transitDetail.InboundTime > DateTime.MinValue) && transitExtraOrder.order_void_status != 1 ? Visibility.Visible : Visibility.Collapsed; /* 作废额外包裹 */
//transitDetail.ReturnPackageBtnVisibility = transitDetail.InboundTime > DateTime.MinValue && !(transitDetail.OutboundTime > DateTime.MinValue) &&
// transitExtraOrder.pack_type == "1" && !OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 2 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
// Visibility.Visible : Visibility.Collapsed; /* 退货包裹按钮 */
//transitDetail.InterceptPackageBtnVisibility = transitDetail.OutboundTime > DateTime.MinValue &&
// transitExtraOrder.pack_type == "1" && !OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 2 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
// Visibility.Visible : Visibility.Collapsed; /* 拦截退货包裹按钮 */
transitDetail.VoidPackageBtnVisibility = (transitExtraOrder.warehouse_status == null || transitExtraOrder.warehouse_status == 0 || transitExtraOrder.warehouse_status == 1 || transitExtraOrder.warehouse_status == 3) &&
transitExtraOrder.order_void_status != 1 ? Visibility.Visible : Visibility.Collapsed; /* 作废额外包裹 */
// 额外包裹在仓库只能作废,出仓以后才能拦截退回
//transitDetail.ReturnPackageBtnVisibility = (transitExtraOrder.warehouse_status == 1 || transitExtraOrder.warehouse_status == 3 || !transitExtraOrder.location_code.IsNullOrEmpty()) &&
// transitExtraOrder.pack_type == "2" && !OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 2 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
// Visibility.Visible : Visibility.Collapsed; /* 退货包裹按钮 */
transitDetail.InterceptPackageBtnVisibility = (transitExtraOrder.warehouse_status == 2 || transitExtraOrder.outbound_time > DateTime.MinValue || !transitExtraOrder.real_logistics_express_code.IsNullOrEmpty()) &&
transitExtraOrder.pack_type == "2" && !OrderItem.ItemTransitOrderAfterSales.Any(af => af.pack_type == 2 && af.order_code == transitDetail.OrderCode && af.order_void_status != 1) ?
Visibility.Visible : Visibility.Collapsed; /* 拦截退货包裹按钮 */
//transitDetail.VoidPackageBtnVisibility = Visibility.Visible; /* 作废额外包裹 */
//transitDetail.ReturnPackageBtnVisibility = Visibility.Visible; /* 退货包裹按钮 */
//transitDetail.InterceptPackageBtnVisibility = Visibility.Visible; /* 拦截退货包裹按钮 */
detailList.Add(transitDetail);
}
catch (Exception ex)
{
}
}
return detailList;
}
public static string GetTransitBuyerRefundStatusStr(oms_wei_order_item_info orderItem, oms_wei_external_procurement_log_info itemTransitOrder)
{
if (!string.IsNullOrEmpty(itemTransitOrder?.refund_status))
{
var pddBuyerAfterSale = orderItem.PddBuyerAfterSales.FirstOrDefault(af => af.orderSn == itemTransitOrder.out_order_no);
// 店铺售后又取消的,如果是买手还没申请售后,不显示需手动申请售后文字
if (itemTransitOrder.refund_status.Contains("需手动申请售后") && orderItem.refund_status <= 1)
return "";
// 显示售后金额(如果有)
else if (itemTransitOrder.refund_status.EndsWith("买手退款成功"))
{
if (pddBuyerAfterSale?.refundAmount != null)
return itemTransitOrder.refund_status + "(¥" + pddBuyerAfterSale.refundAmount * 0.01m + ")";
else
return itemTransitOrder.refund_status + "(退款金额待获取)";
}
else if (!itemTransitOrder.refund_status.Contains("需手动申请售后") && !itemTransitOrder.refund_status.Contains("已超过可申请售后的时间"))
return "已申请售后 " + itemTransitOrder.refund_status.Replace("申请收到,", "");
else
return itemTransitOrder.refund_status;
}
return "";
}
}
/// <summary>
/// 包裹相关信息
/// </summary>
public class oms_wei_order_item_transit_detail_info : PropertyNotifyObject
{
public oms_wei_order_item_transit_detail_info()
{
Opacity = 1m;
VoidPackageBtnVisibility = Visibility.Collapsed;
RejectPackageBtnVisibility = Visibility.Collapsed;
ReturnPackageBtnVisibility = Visibility.Collapsed;
InterceptPackageBtnVisibility = Visibility.Collapsed;
ExtraPackagesBtnVisibility = Visibility.Collapsed;
}
public oms_wei_order_item_info oms_wei_order_item_info { get; set; }
public oms_wei_external_procurement_log_info oms_wei_external_procurement_log_info { get; set; } /* 发货包裹 */
public oms_wei_external_procurement_after_sale_info oms_wei_external_procurement_after_sale_info { get; set; } /* 退货包裹 */
public oms_wei_transfer_extra_package oms_wei_transfer_extra_package { get; set; } /* 额外包裹 */
public decimal Opacity
{
get { return this.GetValue(x => x.Opacity); }
set { this.SetValue(x => x.Opacity, value); }
}
public string ShopName
{
get { return this.GetValue(x => x.ShopName); }
set { this.SetValue(x => x.ShopName, value); }
}
/// <summary> 仓库类型: 发货包裹 退货包裹 额外包裹 </summary>
public string TransitTypeStr
{
get { return this.GetValue(x => x.TransitTypeStr); }
set
{
this.SetValue(x => x.TransitTypeStr, value);
TransitTypeStrColor = GlobalConfig.PurpleBrush;
if (value == "退货包裹")
TransitTypeStrColor = GlobalConfig.RedBrush;
else if (value == "额外包裹")
TransitTypeStrColor = GlobalConfig.GreenBrush;
}
}
public SolidColorBrush TransitTypeStrColor
{
get { return this.GetValue(x => x.TransitTypeStrColor); }
set { this.SetValue(x => x.TransitTypeStrColor, value); }
}
/// <summary> 仓库订单号 </summary>
public string OrderCode
{
get { return this.GetValue(x => x.OrderCode); }
set { this.SetValue(x => x.OrderCode, value); }
}
public string SourceCode
{
get { return this.GetValue(x => x.SourceCode); }
set { this.SetValue(x => x.SourceCode, value); }
}
public string WarehouseId
{
get { return this.GetValue(x => x.WarehouseId); }
set { this.SetValue(x => x.WarehouseId, value); }
}
public string WarehouseName
{
get { return this.GetValue(x => x.WarehouseName); }
set { this.SetValue(x => x.WarehouseName, value); }
}
public DateTime? CreateTime
{
get { return this.GetValue(x => x.CreateTime); }
set { this.SetValue(x => x.CreateTime, value); CreateTimeStr = value == null ? null : value.Value.ToString("yyyy-MM-dd HH:mm:ss"); }
}
public string CreateTimeStr
{
get { return this.GetValue(x => x.CreateTimeStr); }
set { this.SetValue(x => x.CreateTimeStr, value); }
}
/// <summary> 取号时间((中转单)创建时间) </summary>
public DateTime? PickUpTime
{
get { return this.GetValue(x => x.PickUpTime); }
set { this.SetValue(x => x.PickUpTime, value); PickUpTimeStr = value == null ? "" : value.Value.ToString("yyyy-MM-dd HH:mm:ss"); }
}
public string PickUpTimeStr
{
get { return this.GetValue(x => x.PickUpTimeStr); }
set { this.SetValue(x => x.PickUpTimeStr, value); }
}
/// <summary> 微信订单号(交易单号) </summary>
public string WxOrderId
{
get { return this.GetValue(x => x.WxOrderId); }
set { this.SetValue(x => x.WxOrderId, value); }
}
public string WxOrderSkuId
{
get { return this.GetValue(x => x.WxOrderSkuId); }
set { this.SetValue(x => x.WxOrderSkuId, value); }
}
/// <summary> 微信订单创建时间(支付时间) </summary>
public DateTime WxOrderCreateTime
{
get { return this.GetValue(x => x.WxOrderCreateTime); }
set { this.SetValue(x => x.WxOrderCreateTime, value); WxOrderCreateTimeStr = value.ToString("yyyy-MM-dd HH:mm:ss"); }
}
public string WxOrderCreateTimeStr
{
get { return this.GetValue(x => x.WxOrderCreateTimeStr); }
set { this.SetValue(x => x.WxOrderCreateTimeStr, value); }
}
/// <summary>
/// 添加记录时间
/// </summary>
public string TransitAddTimeStr
{
get { return this.GetValue(x => x.TransitAddTimeStr); }
set { this.SetValue(x => x.TransitAddTimeStr, value); }
}
public string WxOrderThumbImg
{
get { return this.GetValue(x => x.WxOrderThumbImg); }
set { this.SetValue(x => x.WxOrderThumbImg, value); }
}
public string OutOrderId
{
get { return this.GetValue(x => x.OutOrderId); }
set { this.SetValue(x => x.OutOrderId, value); }
}
public string OutBuyerId
{
get { return this.GetValue(x => x.OutBuyerId); }
set { this.SetValue(x => x.OutBuyerId, value); }
}
public string OutBuyerName
{
get { return this.GetValue(x => x.OutBuyerName); }
set { this.SetValue(x => x.OutBuyerName, value); }
}
/// <summary> 中转状态 </summary>
public string TransitStatus
{
get { return this.GetValue(x => x.TransitStatus); }
set { this.SetValue(x => x.TransitStatus, value); }
}
/// <summary> 仓库状态文本: 未入库 已入库 已出库 拦截到仓</summary>
public string WarehouseStatus
{
get { return this.GetValue(x => x.WarehouseStatus); }
set { this.SetValue(x => x.WarehouseStatus, value); }
}
/// <summary> 作废状态 </summary>
public string TransitVoidStatus
{
get { return this.GetValue(x => x.TransitVoidStatus); }
set { this.SetValue(x => x.TransitVoidStatus, value); if (value == "已作废") this.Opacity = 0.6m; }
}
/// <summary> 拒收状态 </summary>
public string TransitRejectStatus
{
get { return this.GetValue(x => x.TransitRejectStatus); }
set { this.SetValue(x => x.TransitRejectStatus, value); }
}
/// <summary> 拦截退回状态 </summary>
public string TransitReturnStatus
{
get { return this.GetValue(x => x.TransitReturnStatus); }
set { this.SetValue(x => x.TransitReturnStatus, value); }
}
/// <summary> 买手退货状态 </summary>
public string BuyRefundStatus
{
get { return this.GetValue(x => x.BuyRefundStatus); }
set { this.SetValue(x => x.BuyRefundStatus, value); }
}
public string UpperWaybill
{
get { return this.GetValue(x => x.UpperWaybill); }
set { this.SetValue(x => x.UpperWaybill, value); UpperWaybillVisibility = string.IsNullOrEmpty(value) ? Visibility.Collapsed : Visibility.Visible; }
}
public Visibility UpperWaybillVisibility
{
get { return this.GetValue(x => x.UpperWaybillVisibility); }
private set { this.SetValue(x => x.UpperWaybillVisibility, value); }
}
public string DownWaybill
{
get { return this.GetValue(x => x.DownWaybill); }
set { this.SetValue(x => x.DownWaybill, value); DownWaybillVisibility = string.IsNullOrEmpty(value) ? Visibility.Collapsed : Visibility.Visible; }
}
public Visibility DownWaybillVisibility
{
get { return this.GetValue(x => x.DownWaybillVisibility); }
set { this.SetValue(x => x.DownWaybillVisibility, value); }
}
public DateTime? InboundTime
{
get { return this.GetValue(x => x.InboundTime); }
set { this.SetValue(x => x.InboundTime, value); InboundTimeStr = value == null ? "" : value.Value.ToString("yyyy-MM-dd HH:mm:ss"); }
}
public string InboundTimeStr
{
get { return this.GetValue(x => x.InboundTimeStr); }
set { this.SetValue(x => x.InboundTimeStr, value); }
}
public DateTime? OutboundTime
{
get { return this.GetValue(x => x.OutboundTime); }
set { this.SetValue(x => x.OutboundTime, value); OutboundTimeStr = value == null ? "" : value.Value.ToString("yyyy-MM-dd HH:mm:ss"); }
}
public string OutboundTimeStr
{
get { return this.GetValue(x => x.OutboundTimeStr); }
set { this.SetValue(x => x.OutboundTimeStr, value); }
}
public string ShelfCodeStr
{
get { return this.GetValue(x => x.ShelfCodeStr); }
set { this.SetValue(x => x.ShelfCodeStr, value); }
}
public string ShelfTimeStr
{
get { return this.GetValue(x => x.ShelfTimeStr); }
set { this.SetValue(x => x.ShelfTimeStr, value); }
}
public Visibility VoidPackageBtnVisibility
{
get { return this.GetValue(x => x.VoidPackageBtnVisibility); }
set { this.SetValue(x => x.VoidPackageBtnVisibility, value); }
}
public Visibility RejectPackageBtnVisibility
{
get { return this.GetValue(x => x.RejectPackageBtnVisibility); }
set { this.SetValue(x => x.RejectPackageBtnVisibility, value); }
}
/// <summary>
/// 直接退回包裹
/// </summary>
public Visibility ReturnPackageBtnVisibility
{
get { return this.GetValue(x => x.ReturnPackageBtnVisibility); }
set { this.SetValue(x => x.ReturnPackageBtnVisibility, value); }
}
/// <summary>
/// 拦截退回包裹
/// </summary>
public Visibility InterceptPackageBtnVisibility
{
get { return this.GetValue(x => x.InterceptPackageBtnVisibility); }
set { this.SetValue(x => x.InterceptPackageBtnVisibility, value); }
}
public Visibility ExtraPackagesBtnVisibility
{
get { return this.GetValue(x => x.ExtraPackagesBtnVisibility); }
set { this.SetValue(x => x.ExtraPackagesBtnVisibility, value); }
}
public string TransitDetailRefundStatusStr
{
get { return this.GetValue(x => x.TransitDetailRefundStatusStr); }
set
{
this.SetValue(x => x.TransitDetailRefundStatusStr, value);
TransitDetailRefundStatusStrVisibility = string.IsNullOrWhiteSpace(value) ? Visibility.Collapsed : Visibility.Visible;
if (value.Contains("退款成功"))
TransitDetailRefundStatusBackColor = GlobalConfig.GreenBrush;
else if (value.Contains("需手动申请售后") || value.Contains("已超过可申请售后的时间") || value.Contains("退款失败"))
TransitDetailRefundStatusBackColor = GlobalConfig.RedBrush;
else
TransitDetailRefundStatusBackColor = GlobalConfig.LightOrangeBrush;
}
}
public Visibility TransitDetailRefundStatusStrVisibility
{
get { return this.GetValue(x => x.TransitDetailRefundStatusStrVisibility); }
set { this.SetValue(x => x.TransitDetailRefundStatusStrVisibility, value); }
}
/// <summary> 中转仓买手售后字段文字显示背景颜色 </summary>
public SolidColorBrush TransitDetailRefundStatusBackColor
{
get { return this.GetValue(x => x.TransitDetailRefundStatusBackColor); }
set { this.SetValue(x => x.TransitDetailRefundStatusBackColor, value); }
}
}
+33 -33
View File
@@ -15,8 +15,8 @@ namespace AllBase.Model.DBModel
{ {
public string RefundStatusStr public string RefundStatusStr
{ {
get { return this.GetValue(x => x.status); } get { return this.GetValue(x => x.RefundStatusStr); }
set { this.SetValue(x => x.status, value); RefundStatusStrVisibility = RefundStatusStr.IsNullOrEmpty() ? Visibility.Collapsed : Visibility.Visible; } set { this.SetValue(x => x.RefundStatusStr, value); RefundStatusStrVisibility = RefundStatusStr.IsNullOrEmpty() ? Visibility.Collapsed : Visibility.Visible; }
} }
public Visibility RefundStatusStrVisibility public Visibility RefundStatusStrVisibility
{ {
@@ -52,8 +52,8 @@ namespace AllBase.Model.DBModel
} }
public Visibility AfterSaleOrderIdVisibility public Visibility AfterSaleOrderIdVisibility
{ {
get { return this.GetValue(x => x.ReasonTextStrVisibility); } get { return this.GetValue(x => x.AfterSaleOrderIdVisibility); }
set { this.SetValue(x => x.ReasonTextStrVisibility, value); } set { this.SetValue(x => x.AfterSaleOrderIdVisibility, value); }
} }
public long id { get; set; } public long id { get; set; }
@@ -61,7 +61,7 @@ namespace AllBase.Model.DBModel
public string after_sale_order_id public string after_sale_order_id
{ {
get { return this.GetValue(x => x.after_sale_order_id); } get { return this.GetValue(x => x.after_sale_order_id); }
set { this.SetValue(x => x.after_sale_order_id, value); ReasonTextStrVisibility = value.IsNullOrEmpty() ? Visibility.Collapsed : Visibility.Visible; } set { this.SetValue(x => x.after_sale_order_id, value); AfterSaleOrderIdVisibility = value.IsNullOrEmpty() ? Visibility.Collapsed : Visibility.Visible; }
} }
/// <summary> /// <summary>
/// 售后单当前状态,参考: /// 售后单当前状态,参考:
@@ -88,36 +88,36 @@ namespace AllBase.Model.DBModel
{ {
get { return this.GetValue(x => x.status); } get { return this.GetValue(x => x.status); }
set set
{ {
this.SetValue(x => x.status, value); if (order_id == "3739902323987233280")
this.RefundStatusStr = "售后状态读取失败";
if (value == "USER_CANCELD") this.RefundStatusStr = "用户取消申请";
else if (value == "MERCHANT_PROCESSING") this.RefundStatusStr = "商家受理中";
else if (value == "MERCHANT_REJECT_REFUND") this.RefundStatusStr = "商家拒绝退款";
else if (value == "MERCHANT_REJECT_RETURN") this.RefundStatusStr = "商家拒绝退货退款";
else if (value == "USER_WAIT_RETURN") this.RefundStatusStr = "待买家退货";
else if (value == "RETURN_CLOSED") this.RefundStatusStr = "退货退款关闭";
else if (value == "MERCHANT_WAIT_RECEIPT") this.RefundStatusStr = "待商家收货";
else if (value == "MERCHANT_OVERDUE_REFUND") this.RefundStatusStr = "商家逾期未退款";
else if (value == "MERCHANT_REFUND_SUCCESS") this.RefundStatusStr = "退款完成";
else if (value == "MERCHANT_RETURN_SUCCESS") this.RefundStatusStr = "退货退款完成";
else if (value == "PLATFORM_REFUNDING") this.RefundStatusStr = "平台退款中";
else if (value == "PLATFORM_REFUND_FAIL") this.RefundStatusStr = "平台退款失败";
else if (value == "USER_WAIT_CONFIRM") this.RefundStatusStr = "待用户确认";
else if (value == "MERCHANT_REFUND_RETRY_FAIL") this.RefundStatusStr = "商家打款失败,客服关闭售后";
else if (value == "MERCHANT_FAIL") this.RefundStatusStr = "售后关闭";
else if (value == "USER_WAIT_CONFIRM_UPDATE") this.RefundStatusStr = "待用户处理商家协商";
else if (value == "USER_WAIT_HANDLE_MERCHANT_AFTER_SALE") this.RefundStatusStr = "待用户处理商家代发起的售后申请";
else if (value == "WAIT_PACKAGE_INTERCEPT") this.RefundStatusStr = "物流拦截中";
else if (value == "USER_WAIT_RECEIPT") this.RefundStatusStr = "换货商品已发货";
else this.RefundStatusStr = value;
//MERCHANT_EXCHANGE_SUCCESS
if (order_id == "3738189148379849472")
{ {
} }
this.SetValue(x => x.status, value);
this.RefundStatusStr = "售后状态读取失败";
if (status == "USER_CANCELD") this.RefundStatusStr = "用户取消申请";
else if (status == "MERCHANT_PROCESSING") this.RefundStatusStr = "商家受理中";
else if (status == "MERCHANT_REJECT_REFUND") this.RefundStatusStr = "商家拒绝退款";
else if (status == "MERCHANT_REJECT_RETURN") this.RefundStatusStr = "商家拒绝退货退款";
else if (status == "USER_WAIT_RETURN") this.RefundStatusStr = "待买家退货";
else if (status == "RETURN_CLOSED") this.RefundStatusStr = "退货退款关闭";
else if (status == "MERCHANT_WAIT_RECEIPT") this.RefundStatusStr = "待商家收货";
else if (status == "MERCHANT_OVERDUE_REFUND") this.RefundStatusStr = "商家逾期未退款";
else if (status == "MERCHANT_REFUND_SUCCESS") this.RefundStatusStr = "退款完成";
else if (status == "MERCHANT_RETURN_SUCCESS") this.RefundStatusStr = "退货退款完成";
else if (status == "PLATFORM_REFUNDING") this.RefundStatusStr = "平台退款中";
else if (status == "PLATFORM_REFUND_FAIL") this.RefundStatusStr = "平台退款失败";
else if (status == "USER_WAIT_CONFIRM") this.RefundStatusStr = "待用户确认";
else if (status == "MERCHANT_REFUND_RETRY_FAIL") this.RefundStatusStr = "商家打款失败,客服关闭售后";
else if (status == "MERCHANT_FAIL") this.RefundStatusStr = "售后关闭";
else if (status == "USER_WAIT_CONFIRM_UPDATE") this.RefundStatusStr = "待用户处理商家协商";
else if (status == "USER_WAIT_HANDLE_MERCHANT_AFTER_SALE") this.RefundStatusStr = "待用户处理商家代发起的售后申请";
else if (status == "WAIT_PACKAGE_INTERCEPT") this.RefundStatusStr = "物流拦截中";
else if (status == "USER_WAIT_RECEIPT") this.RefundStatusStr = "换货商品已发货";
else this.RefundStatusStr = status;
//MERCHANT_EXCHANGE_SUCCESS
List<string> refundStrLst = new List<string>() { "商家受理中", "待买家退货", "待商家收货", "商家逾期未退款", "退款完成", "退货退款完成", "平台退款中", "待用户确认", List<string> refundStrLst = new List<string>() { "商家受理中", "待买家退货", "待商家收货", "商家逾期未退款", "退款完成", "退货退款完成", "平台退款中", "待用户确认",
"待用户处理商家协商", "待用户处理商家代发起的售后申请", "物流拦截中"}; "待用户处理商家协商", "待用户处理商家代发起的售后申请", "物流拦截中"};
@@ -207,7 +207,7 @@ namespace AllBase.Model.DBModel
set set
{ {
this.SetValue(x => x.reason_text, value); this.SetValue(x => x.reason_text, value);
ReasonTextStr = string.IsNullOrEmpty(reason_text) ? string.Empty : "售后原因:" + reason_text; ReasonTextStr = string.IsNullOrEmpty(reason_text) ? string.Empty : ("售后原因:" + reason_text);
} }
} }
/// <summary> /// <summary>
@@ -9,25 +9,58 @@ namespace AllBase.Model.DBModel;
public class oms_wei_transfer_extra_package : PropertyNotifyObject public class oms_wei_transfer_extra_package : PropertyNotifyObject
{ {
public long id { get; set; } // 主键ID /// <summary>
public string batchId { get; set; } // 新订单号 /// 主键ID
public string order_no { get; set; } // 平台订单号 /// </summary>
public string buyer_account { get; set; } // '买家账号', public long id { get; set; }
public int? out_amount { get; set; } // '外部金额(分)', /// <summary>
public string purchaser_note { get; set; } // '采购人备注' /// 新订单号
public string logistics_code { get; set; } // '快递公司', /// </summary>
public string logistics_express_code { get; set; } // '快递单号', public string batchId { get; set; }
public string real_logistics_code // '出库快递公司', /// <summary>
/// 平台订单号
/// </summary>
public string order_no { get; set; }
/// <summary>
/// 买家账号
/// </summary>
public string buyer_account { get; set; }
/// <summary>
/// 外部金额(分)
/// </summary>
public int? out_amount { get; set; }
/// <summary>
/// 采购人备注
/// </summary>
public string purchaser_note { get; set; }
/// <summary>
/// 快递公司
/// </summary>
public string logistics_code { get; set; }
/// <summary>
/// 快递单号
/// </summary>
public string logistics_express_code { get; set; }
/// <summary>
/// 出库快递公司
/// </summary>
public string real_logistics_code
{ {
get { return this.GetValue(x => x.real_logistics_code); } get { return this.GetValue(x => x.real_logistics_code); }
set { this.SetValue(x => x.real_logistics_code, value); } set { this.SetValue(x => x.real_logistics_code, value); }
} }
public string real_logistics_express_code // '出库单号', /// <summary>
/// 出库单号
/// </summary>
public string real_logistics_express_code
{ {
get { return this.GetValue(x => x.real_logistics_express_code); } get { return this.GetValue(x => x.real_logistics_express_code); }
set { this.SetValue(x => x.real_logistics_express_code, value); } set { this.SetValue(x => x.real_logistics_express_code, value); }
} }
public string refund_status { get; set; } // '买手退款状态', /// <summary>
/// 买手退款状态
/// </summary>
public string refund_status { get; set; }
public DateTime? pickup_time { get; set; } // '取号时间', public DateTime? pickup_time { get; set; } // '取号时间',
public int? transfer_warehouse_status { get; set; } // '中转仓状态:0 未使用,1 已创建,2 创建失败', public int? transfer_warehouse_status { get; set; } // '中转仓状态:0 未使用,1 已创建,2 创建失败',
public string raw_message { get; set; } // '原始消息/请求体', public string raw_message { get; set; } // '原始消息/请求体',
@@ -44,8 +77,55 @@ public class oms_wei_transfer_extra_package : PropertyNotifyObject
public int? postage { get; set; } // '订单初始费用(分)', public int? postage { get; set; } // '订单初始费用(分)',
public int? retry_acquire_success { get; set; } // '重试取号是否成功 0=未尝试/未重试 1=成功 2=失败', public int? retry_acquire_success { get; set; } // '重试取号是否成功 0=未尝试/未重试 1=成功 2=失败',
public int? over_weight_fee { get; set; } // '超重费用', public int? over_weight_fee { get; set; } // '超重费用',
public string pack_type { get; set; } // '中转仓额外包裹类型 1商品2额外3礼品4退货', /// <summary>
/// 中转仓额外包裹类型 1商品2额外3礼品4退货
/// </summary>
public string pack_type { get; set; }
public DateTime? rejected_time { get; set; } // '拒收时间', public DateTime? rejected_time { get; set; } // '拒收时间',
public int? has_reject { get; set; } // DEFAULT NULL, public int? has_reject { get; set; } // DEFAULT NULL,
public DateTime? blocked_arrival_time { get; set; } public DateTime? blocked_arrival_time { get; set; }
/// <summary>
/// 货架号
/// </summary>
public string location_code { get; set; }
/// <summary>
/// 货架写入时间
/// </summary>
public DateTime? location_write_time { get; set; }
/// <summary>
/// 外采单号
/// </summary>
public string out_order_no { get; set; }
/// <summary>
/// 商品skuId
/// </summary>
public string out_sku_id { get; set; }
/// <summary>
/// 拦截退回状态:0未处理,1已退回成功,2退回失败(或其它业务码)
/// </summary>
public int? intercept_return_status { get; set; }
/// <summary>
/// 拦截退回时间
/// </summary>
public DateTime? intercept_return_time { get; set; }
/// <summary>
/// 拦截退回操作信息(回调/失败信息/备注等)
/// </summary>
public string intercept_return_info { get; set; }
/// <summary>
/// 拦截改地址状态:0未处理,1修改成功,2修改失败(或其它业务码)
/// </summary>
public int? intercept_address_status { get; set; }
/// <summary>
/// 拦截改地址时间
/// </summary>
public DateTime? intercept_address_time { get; set; }
/// <summary>
/// 拦截改地址操作信息(回调/失败信息/备注等)
/// </summary>
public string intercept_address_info { get; set; }
/// <summary>
/// 是否有退货:0 无退货,1 有退货
/// </summary>
public int? has_return { get; set; }
} }
+33 -15
View File
@@ -69,23 +69,41 @@ namespace AllBase.Model.DBModel
public enum EnumOrderPaymentType public enum EnumOrderPaymentType
{ {
充值 = 1, //变动类型,1:充值,2:采购花费,3:产品退款到账,4:运费退款到账,5:采购收款,6:产品退款扣除,7:运费退款扣除, 16:礼物单话费,20:中转仓扣费支出,23:中转仓退款收入,24:中转仓超重扣费支出,26 退货包裹扣费支出30支付宝充值;31 云仓退货支出33 分销退货包裹超重花费32 分销退货包裹发货花费退款34 礼物单退费35 额外包裹创建36 额外包裹作废37 额外订单超重支出38 退货包裹作废返还55 同步物流支出
//采购花费 = 2,
//产品退款到账 = 3, 充值 = 1,
//运费退款到账 = 4, //采购花费 = 2,
//采购收款 = 5, //产品退款到账 = 3,
//产品退款扣除 = 6, //运费退款到账 = 4,
//运费退款扣除 = 7, //采购收款 = 5,
礼物单支出 = 16, //产品退款扣除 = 6,
中转仓扣费支出 = 20, //运费退款扣除 = 7,
中转仓作废收入 = 23, 礼物单支出 = 16,
中转仓超重支出 = 24,
发货包裹扣费支出 = 20,
发货包裹作废返还 = 23,
发货包裹超重支出 = 24,
退货包裹扣费支出 = 26, 退货包裹扣费支出 = 26,
支付宝在线充值 = 30, 退货包裹超重支出 = 28,
云仓退货支出 = 31, 退货包裹作废返还 = 38,
支付宝在线充值 = 30,
退货仓退货支出 = 31,
退货仓作废返还 = 32,
退货仓超重支出 = 33,
礼物单退费 = 34, 礼物单退费 = 34,
额外订单创建 = 35,
额外订单作废 = 36, 额外包裹创建支出 = 35,
额外包裹作废返还 = 36,
额外包裹超重支出 = 37,
额外包裹退货拦截创建支出 = 39,
额外包裹退货拦截作废返还 = 40,
额外包裹退货拦截超重支出 = 41,
同步物流 = 55, 同步物流 = 55,
} }
+18 -18
View File
@@ -185,13 +185,13 @@ namespace AllBase.Model.Result
get { return this.GetValue(x => x.thumbUrl); } get { return this.GetValue(x => x.thumbUrl); }
set { this.SetValue(x => x.thumbUrl, value); } set { this.SetValue(x => x.thumbUrl, value); }
} // "https://t00img.yangkeduo.com/t10img/images/2018-06-09/5c7746a3608e75a2b65926f4ed0f34cb.jpeg", } // "https://t00img.yangkeduo.com/t10img/images/2018-06-09/5c7746a3608e75a2b65926f4ed0f34cb.jpeg",
public int? initQuantity { get; set; } // 0, //public int? initQuantity { get; set; } // 0,
public int? quantity { get; set; } // 1000, //public int? quantity { get; set; } // 1000,
public int? limitQuantity { get; set; } // 999999, //public int? limitQuantity { get; set; } // 999999,
public int? soldQuantity { get; set; } // 0, //public int? soldQuantity { get; set; } // 0,
public int? hotSale { get; set; } // 1, //public int? hotSale { get; set; } // 1,
public int? defaultQuantity { get; set; } // 100, //public int? defaultQuantity { get; set; } // 100,
public int? isOnsale { get; set; } // 1, //public int? isOnsale { get; set; } // 1,
public string spec { get; set; } // "677094835", public string spec { get; set; } // "677094835",
[JsonIgnore] [JsonIgnore]
public string SpecNameStr public string SpecNameStr
@@ -216,17 +216,17 @@ namespace AllBase.Model.Result
public string normalPrice { get; set; } // "14.5", public string normalPrice { get; set; } // "14.5",
public string groupPrice { get; set; } // "13.5", public string groupPrice { get; set; } // "13.5",
public int? oldGroupPrice { get; set; } // 1350, public int? oldGroupPrice { get; set; } // 1350,
public int? marketPrice { get; set; } // 0, //public int? marketPrice { get; set; } // 0,
public int? weight { get; set; } // 2500, //public int? weight { get; set; } // 2500,
public List<yellowLabelListInfo> yellowLabelList { get; set; } //public List<yellowLabelListInfo> yellowLabelList { get; set; }
public int? previewPriority { get; set; } // 0, //public int? previewPriority { get; set; } // 0,
public int? startTime { get; set; } // 0, //public int? startTime { get; set; } // 0,
public int? endTime { get; set; } // 0, //public int? endTime { get; set; } // 0,
public int? staticLimitQuantity { get; set; } // 999999, //public int? staticLimitQuantity { get; set; } // 999999,
public string attribute { get; set; } // "{\"skuPreSaleTime\":0}", //public string attribute { get; set; } // "{\"skuPreSaleTime\":0}",
public string normalSavePrice { get; set; } // "1", //public string normalSavePrice { get; set; } // "1",
public long? skuID { get; set; } // 28790184768, //public long? skuID { get; set; } // 28790184768,
public string skuExpansionPrice { get; set; } // "0" //public string skuExpansionPrice { get; set; } // "0"
} }
public class yellowLabelListInfo public class yellowLabelListInfo
@@ -267,6 +267,7 @@ namespace AllBase.Model.Result
var detailPage = listItemExtraVO.navToDetailPageUrl; var detailPage = listItemExtraVO.navToDetailPageUrl;
return BaseRegex.GetStringQuery(ref detailPage, "order_sn"); return BaseRegex.GetStringQuery(ref detailPage, "order_sn");
} }
set { }
} }
public int? tbOrderDate { get; set; } public int? tbOrderDate { get; set; }
public int? orderDate { get { return tbOrderDate ?? orderSn.Split('-').FirstOrDefault().ParseToInt(); } } public int? orderDate { get { return tbOrderDate ?? orderSn.Split('-').FirstOrDefault().ParseToInt(); } }
+31
View File
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace AllBase.Util;
public class ChineseStringConverter
{
private const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
private const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int LCMapString(int Locale, int dwMapFlags, string lpSrcStr, int cchSrc, [Out] string lpDestStr, int cchDest);
public static string ToSimplified(string source)
{
string target = new string(' ', source.Length);
LCMapString(0x0800, LCMAP_SIMPLIFIED_CHINESE, source, source.Length, target, source.Length);
return target;
}
public static string ToTraditional(string source)
{
string target = new string(' ', source.Length);
LCMapString(0x0800, LCMAP_TRADITIONAL_CHINESE, source, source.Length, target, source.Length);
return target;
}
}
@@ -0,0 +1,121 @@
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace OrderSupportTicket.Behaviors;
/// <summary>
/// 仅承载视图交互:列表点击命令、消息列表滚动到底部。
/// </summary>
public static class ListBoxInteractionBehavior
{
public static readonly DependencyProperty SelectedItemCommandProperty =
DependencyProperty.RegisterAttached(
"SelectedItemCommand",
typeof(ICommand),
typeof(ListBoxInteractionBehavior),
new PropertyMetadata(null, OnSelectedItemCommandChanged));
public static readonly DependencyProperty ScrollVersionProperty =
DependencyProperty.RegisterAttached(
"ScrollVersion",
typeof(int),
typeof(ListBoxInteractionBehavior),
new PropertyMetadata(0, OnScrollVersionChanged));
public static void SetSelectedItemCommand(DependencyObject element, ICommand value)
{
element.SetValue(SelectedItemCommandProperty, value);
}
public static ICommand GetSelectedItemCommand(DependencyObject element)
{
return (ICommand)element.GetValue(SelectedItemCommandProperty);
}
public static void SetScrollVersion(DependencyObject element, int value)
{
element.SetValue(ScrollVersionProperty, value);
}
public static int GetScrollVersion(DependencyObject element)
{
return (int)element.GetValue(ScrollVersionProperty);
}
private static void OnSelectedItemCommandChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if (!(d is ListBox listBox))
return;
listBox.PreviewMouseLeftButtonUp -= OnPreviewMouseLeftButtonUp;
listBox.PreviewKeyUp -= OnPreviewKeyUp;
if (e.NewValue is ICommand)
{
listBox.PreviewMouseLeftButtonUp += OnPreviewMouseLeftButtonUp;
listBox.PreviewKeyUp += OnPreviewKeyUp;
}
}
private static void OnPreviewMouseLeftButtonUp(
object sender,
MouseButtonEventArgs e)
{
ExecuteForSelectedItem(sender as ListBox);
}
private static void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter && e.Key != Key.Space)
return;
ExecuteForSelectedItem(sender as ListBox);
}
private static void ExecuteForSelectedItem(ListBox listBox)
{
if (listBox == null || listBox.SelectedItem == null)
return;
var command = GetSelectedItemCommand(listBox);
if (command != null && command.CanExecute(listBox.SelectedItem))
command.Execute(listBox.SelectedItem);
}
private static void OnScrollVersionChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if (!(d is ListBox listBox))
return;
listBox.Dispatcher.BeginInvoke(
new Action(() =>
{
var scrollViewer = FindVisualChild<ScrollViewer>(listBox);
if (scrollViewer != null)
scrollViewer.ScrollToEnd();
}),
DispatcherPriority.Background);
}
private static T FindVisualChild<T>(DependencyObject parent)
where T : DependencyObject
{
if (parent == null)
return null;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T match)
return match;
var nested = FindVisualChild<T>(child);
if (nested != null)
return nested;
}
return null;
}
}
@@ -0,0 +1,115 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace LaunchDarkly.EventSource
{
internal static class AsyncHelpers
{
// General-purpose timeout logic that uses a timed CancellationToken instead of
// Task.Delay. The cancellationToken that is passed in is for explicitly cancelling
// the operation from elsewhere; DoWithTimeout wraps this to create a token that can
// also be cancelled by a timeout, and passes that token to taskFn.
//
// This method will only work if taskFn actually responds to the cancellation token
// by throwing an OperationCanceledException. If taskFn ignores the token, timeouts
// will not happen.
internal static async Task<T> DoWithTimeout<T>(
TimeSpan timeout,
CancellationToken cancellationToken,
Func<CancellationToken, Task<T>> taskFn
)
{
using (var timeoutCancellation = new CancellationTokenSource(timeout))
{
using (var combinedCancellation = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken, timeoutCancellation.Token))
{
Task<T> task = null;
try
{
task = taskFn(combinedCancellation.Token);
var result = await task;
return result;
}
catch (AggregateException e) when (e.InnerException is OperationCanceledException)
{
if (cancellationToken.IsCancellationRequested)
{
throw e.InnerException;
}
throw new ReadTimeoutException();
}
catch (OperationCanceledException)
{
if (cancellationToken.IsCancellationRequested)
{
throw;
}
throw new ReadTimeoutException();
}
}
}
// We never need to call SuppressExceptions(task) in this method, because the act
// of awaiting the task - whether it completes normally or throws an exception -
// makes it "observed". The timeout isn't happening in a different task, it's
// causing this task to throw an OperationCanceledException, after which point it
// can't generate any other exceptions.
}
// Take a task that can't be terminated early with a CancellationToken, and wrap it in a task
// that can. If you cancel the wrapped task, the inner task will still continue, but we're
// assuming that in these situations we'll eventually be closing the underlying socket which
// will terminate any pending I/O.
internal static Task<T> AllowCancellation<T>(Task<T> originalTask, CancellationToken cancellationToken)
{
var cancellableTask = originalTask.ContinueWith(
completedTask => completedTask.GetAwaiter().GetResult(),
cancellationToken,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default
);
// Now, if originalTask either completes successfully or fails with an exception, anyone who
// was waiting on cancellableTask will get the result or the exception.
//
// But if cancellationToken gets cancelled, cancellableTask will stop and throw an
// OperationCancelledException, just as cancellable I/O operation normally would. The
// caller is no longer blocked - even though originalTask may still be executing.
//
// Normally it would be a problem that originalTask could still be hanging around, but
// in our case if things are getting cancelled it means the connection is going to be
// closed soon, causing any lingering I/O tasks that use that connection to fail. We
// just need to use SuppressExceptions to make sure those failures are discarded rather
// than causing an "unobserved exception" situation.
cancellableTask.ContinueWith(
completedTask =>
{
SuppressExceptions(originalTask);
},
TaskContinuationOptions.OnlyOnCanceled
);
return cancellableTask;
}
/// <summary>
/// Adds a continuation to a task so that if the task throws an uncaught exception, the exception
/// is not "unobserved" (which can be a fatal error in some versions of .NET). We must do this
/// whenever we're going to discard a task without awaiting it, if there's any possibility that
/// it could throw an exception.
/// </summary>
/// <param name="task">a task we are not going to await</param>
internal static void SuppressExceptions(Task task)
{
task.ContinueWith(
t =>
{
// Simply accessing the Exception property makes this exception observed.
var e = t.Exception;
},
TaskContinuationOptions.OnlyOnFaulted
);
}
}
}
@@ -0,0 +1,179 @@
using System;
using System.IO;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// Internal implementation of a buffered text line parser for UTF-8 data.
/// </summary>
/// <remarks>
/// <para>
/// This is used as follows. 1. The caller puts some data into the byte buffer. 2. The caller
/// calls ScanToEndOfLine; if it returns true, the <c>lineOut</c> parameter is set to point
/// to the content of the line (not including the line ending character(s)). If it returns
/// false, put more data into the buffer and try again.
/// </para>
/// <para>
/// Since in UTF-8 all multi-byte characters use values greater than 127 for all of their
/// bytes, this logic doesn't need to do any UTF-8 decoding or even know how many bytes are
/// in a character; it just looks for the line-ending sequences CR, LF, or CR+LF.
/// </para>
/// </remarks>
internal struct ByteArrayLineScanner
{
private readonly byte[] _buffer;
private readonly int _capacity;
private int _count;
private int _startPos;
public byte[] Buffer => _buffer;
public int Capacity => _capacity;
public int Count => _count;
public int Available => _capacity - _count;
private MemoryStream _partialLine;
public ByteArrayLineScanner(int capacity)
{
_buffer = new byte[capacity];
_capacity = capacity;
_count = 0;
_partialLine = null;
_startPos = 0;
}
/// <summary>
/// The caller calls this method after having already added <c>count</c> more bytes at the
/// end of the buffer. We do it this way instead of having an <c>AddBytes(byte[], int)</c>
/// method because we don't want to allocate a second buffer just to be the destination for
/// a read operation.
/// </summary>
/// <param name="count">number of bytes added</param>
public void AddedBytes(int count)
{
_count += count;
}
/// <summary>
/// Searches for the next line ending and, if successful, provides the line data.
/// </summary>
/// <param name="lineOut">if successful, this is set to point to the bytes for the line
/// <i>not</i> including any CR/LF; whenever possible this is a reference to the underlying
/// buffer, not a copy, so the caller should read/copy it before doing anything else to the
/// buffer</param>
/// <returns>true if a full line was read, false if we need more data first</returns>
public bool ScanToEndOfLine(out Utf8ByteSpan lineOut)
{
if (_startPos == _count)
{
_startPos = _count = 0;
lineOut = new Utf8ByteSpan();
return false;
}
if (_startPos == 0 && _partialLine != null && _partialLine.Position > 0
&& _partialLine.GetBuffer()[_partialLine.Position - 1] == '\r')
{
// This is an edge case where the very last byte we previously saw was a CR, and we didn't know
// whether the next byte would be LF or not, but we had to dump the buffer into _partialLine
// because it was completely full. So, now we can return the line that's already in _partialLine,
// but if the first byte in the buffer is LF we should skip past it.
if (_buffer[_startPos] == '\n')
{
_startPos++;
}
lineOut = new Utf8ByteSpan(_partialLine.GetBuffer(), 0,
(int)_partialLine.Position - 1); // don't include the CR
_partialLine = null;
return true;
}
int startedAt = _startPos, pos = _startPos;
while (pos < _count)
{
var b = _buffer[pos];
if (b == '\n') // LF by itself terminates a line
{
_startPos = pos + 1; // next line will start after the LF
break;
}
if (b == '\r')
{
if (pos < (_count - 1))
{
_startPos = pos + 1; // next line will start after the CR--
if (_buffer[pos + 1] == '\n') // --unless there was an LF right after that
{
_startPos++;
}
break;
}
else
{
// CR by itself and CR+LF are both valid line endings in SSE, so if the very
// last character we saw was a CR, we can't know when the line is fully read
// until we've gotten more data. So we'll need to treat this as an incomplete
// line.
pos++;
break;
}
}
pos++;
}
if (pos == _count) // we didn't find a line terminator
{
lineOut = new Utf8ByteSpan();
if (_count < _capacity)
{
// There's still room in the buffer, so we'll re-scan the line once they add more bytes
return false;
}
// We need to dump the incomplete line into _partialLine so we can make room in the buffer
var partialCount = pos - _startPos;
if (_partialLine is null)
{
_partialLine = new MemoryStream(partialCount);
}
_partialLine.Write(_buffer, _startPos, partialCount);
// Clear the main buffer
_startPos = _count = 0;
return false;
}
if (_partialLine != null && _partialLine.Position > 0)
{
_partialLine.Write(_buffer, startedAt, pos - startedAt);
lineOut = new Utf8ByteSpan(_partialLine.GetBuffer(), 0, (int)_partialLine.Position);
_partialLine = null;
// If there are still bytes in the main buffer, move them over to make more room. It's
// safe for us to do this before the caller has looked at lineOut, because lineOut is now
// a reference to the separate _partialLine buffer, not to the main buffer.
if (_startPos < _count)
{
System.Buffer.BlockCopy(_buffer, _startPos, _buffer, 0, _count - _startPos);
}
_count -= _startPos;
_startPos = 0;
}
else
{
lineOut = new Utf8ByteSpan(_buffer, startedAt, pos - startedAt);
if (_startPos == _count)
{
// If we've scanned all the data in the buffer, reset _startPos and _count to indicate
// that the entire buffer is available for the next read. It's safe for us to do this
// before the caller has looked at lineOut, because we're not actually modifying any
// bytes in the buffer. It's the caller's responsibility not to modify the buffer
// until it has already done whatever needs to be done with the lineOut data.
_startPos = _count = 0;
}
}
return true;
}
}
}
@@ -0,0 +1,28 @@
using System;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// Provides data recieved in the EventSource <see cref="EventSource.CommentReceived"/> event.
/// </summary>
/// <seealso cref="System.EventArgs" />
public class CommentReceivedEventArgs : EventArgs
{
/// <summary>
/// Gets the comment received in the Server Sent Event.
/// </summary>
/// <value>
/// The comment.
/// </value>
public string Comment { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CommentReceivedEventArgs"/> class.
/// </summary>
/// <param name="comment">The comment received in the Server Sent Event.</param>
public CommentReceivedEventArgs(string comment)
{
Comment = comment;
}
}
}
@@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using WxOrder.Framework.Helpers;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// An immutable class containing configuration properties for <see cref="EventSource"/>.
/// </summary>
/// <seealso cref="EventSource.EventSource(Configuration)"/>
/// <seealso cref="ConfigurationBuilder"/>
public sealed class Configuration
{
#region Constants
/// <summary>
/// The default value for <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/>:
/// one second.
/// </summary>
public static readonly TimeSpan DefaultInitialRetryDelay = TimeSpan.FromSeconds(1);
/// <summary>
/// The default value for <see cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/>:
/// 30 seconds.
/// </summary>
public static readonly TimeSpan DefaultMaxRetryDelay = TimeSpan.FromSeconds(30);
/// <summary>
/// The default value for <see cref="ConfigurationBuilder.ResponseStartTimeout(TimeSpan)"/>:
/// 10 seconds.
/// </summary>
public static readonly TimeSpan DefaultResponseStartTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// Obsolete name for <see cref="DefaultResponseStartTimeout"/>.
/// </summary>
[Obsolete("Use DefaultResponseStartTimeout")]
public static readonly TimeSpan DefaultConnectionTimeout = DefaultResponseStartTimeout;
/// <summary>
/// The default value for <see cref="ConfigurationBuilder.ReadTimeout(TimeSpan)"/>:
/// 5 minutes.
/// </summary>
public static readonly TimeSpan DefaultReadTimeout = TimeSpan.FromMinutes(5);
/// <summary>
/// The default value for <see cref="ConfigurationBuilder.BackoffResetThreshold(TimeSpan)"/>:
/// one minute.
/// </summary>
public static readonly TimeSpan DefaultBackoffResetThreshold = TimeSpan.FromMinutes(1);
/// <summary>
/// The logger name that will be used if you specified a logging implementation but did not
/// provide a specific logger instance.
/// </summary>
/// <seealso cref="ConfigurationBuilder.LogAdapter(ILogAdapter)"/>
public const string DefaultLoggerName = "EventSource";
#endregion
#region Public Properties
/// <summary>
/// The amount of time a connection must stay open before the EventSource resets its backoff delay.
/// </summary>
/// <remarks>
/// A connection that stays open for at least this long also discards any temporary bounds set
/// by <see cref="IEventSource.SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>.
/// </remarks>
/// <seealso cref="ConfigurationBuilder.BackoffResetThreshold(TimeSpan)"/>
public TimeSpan BackoffResetThreshold { get; }
/// <summary>
/// Obsolete name for <see cref="ResponseStartTimeout"/>.
/// </summary>
[Obsolete("Use ResponseStartTimeout")]
public TimeSpan ConnectionTimeout => ResponseStartTimeout;
/// <summary>
/// The HttpClient that will be used as the HTTP client, or null for a new HttpClient.
/// </summary>
/// <seealso cref="ConfigurationBuilder.HttpClient(HttpClient)"/>
public HttpClient HttpClient { get; }
/// <summary>
/// The HttpMessageHandler that will be used for the HTTP client, or null for the default handler.
/// </summary>
/// <seealso cref="ConfigurationBuilder.HttpMessageHandler(HttpMessageHandler)"/>
public HttpMessageHandler HttpMessageHandler { get; }
/// <summary>
/// Delegate hook invoked before an HTTP request has been performed.
/// </summary>
/// <seealso cref="ConfigurationBuilder.HttpRequestModifier(Action{HttpRequestMessage})"/>
public Action<HttpRequestMessage> HttpRequestModifier { get; }
/// <summary>
/// The initial amount of time to wait before attempting to reconnect to the EventSource API.
/// </summary>
/// <seealso cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/>
public TimeSpan InitialRetryDelay { get; }
/// <summary>
/// Gets the last event identifier.
/// </summary>
/// <seealso cref="ConfigurationBuilder.LastEventId(string)"/>
public string LastEventId { get; }
/// <summary>
/// The logger to be used for all EventSource log output.
/// </summary>
/// <remarks>
/// This is never null; if logging is not configured, it will be <c>LaunchDarkly.Logging.Logs.None</c>.
/// </remarks>
/// <seealso cref="ConfigurationBuilder.Logger(Logger)"/>
public ILogger Logger { get; }
/// <summary>
/// The maximum amount of time to wait before attempting to reconnect.
/// </summary>
/// <seealso cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/>
public TimeSpan MaxRetryDelay { get; }
/// <summary>
/// The HTTP method that will be used when connecting to the EventSource API.
/// </summary>
/// <seealso cref="ConfigurationBuilder.Method(HttpMethod)"/>
public HttpMethod Method { get; }
/// <summary>
/// Whether to use UTF-8 byte arrays internally if possible when reading the stream.
/// </summary>
/// <seealso cref="ConfigurationBuilder.PreferDataAsUtf8Bytes(bool)"/>
public bool PreferDataAsUtf8Bytes { get; }
/// <summary>
/// The timeout when reading from the EventSource API.
/// </summary>
/// <seealso cref="ConfigurationBuilder.ReadTimeout(TimeSpan)"/>
public TimeSpan ReadTimeout { get; }
/// <summary>
/// A factory for HTTP request body content, if the HTTP method is one that allows a request body.
/// is one that allows a request body. This is in the form of a factory function because the request
/// may need to be sent more than once.
/// </summary>
/// <seealso cref="ConfigurationBuilder.RequestBodyFactory(Func{HttpContent})"/>
public Func<HttpContent> RequestBodyFactory { get; }
/// <summary>
/// The request headers to be sent with each EventSource HTTP request.
/// </summary>
/// <seealso cref="ConfigurationBuilder.RequestHeader(string, string)"/>
/// <seealso cref="ConfigurationBuilder.RequestHeaders(IDictionary{string, string})"/>
public IDictionary<string, string> RequestHeaders { get; }
/// <summary>
/// The maximum amount of time to wait between starting an HTTP request and receiving the response
/// headers.
/// </summary>
/// <seealso cref="ConfigurationBuilder.ResponseStartTimeout(TimeSpan)"/>
public TimeSpan ResponseStartTimeout { get; }
/// <summary>
/// Gets the <see cref="System.Uri"/> used when connecting to an EventSource API.
/// </summary>
public Uri Uri { get; }
#endregion
#region Internal Constructor
internal Configuration(ConfigurationBuilder builder)
{
Uri = builder._uri;
var logger = builder._logger;
BackoffResetThreshold = builder._backoffResetThreshold;
HttpClient = builder._httpClient;
HttpMessageHandler = (builder._httpClient != null) ? null : builder._httpMessageHandler;
InitialRetryDelay = builder._initialRetryDelay;
LastEventId = builder._lastEventId;
Logger = logger;
MaxRetryDelay = builder._maxRetryDelay;
Method = builder._method;
PreferDataAsUtf8Bytes = builder._preferDataAsUtf8Bytes;
ReadTimeout = builder._readTimeout;
RequestHeaders = new Dictionary<string, string>(builder._requestHeaders);
ResponseStartTimeout = builder._responseStartTimeout;
RequestBodyFactory = builder._requestBodyFactory;
HttpRequestModifier = builder._httpRequestModifier;
}
#endregion
#region Public Methods
/// <summary>
/// Provides a new <see cref="ConfigurationBuilder"/> for constructing a configuration.
/// </summary>
/// <param name="uri">the EventSource URI</param>
/// <returns>a new builder instance</returns>
/// <exception cref="ArgumentNullException">if the URI is null</exception>
public static ConfigurationBuilder Builder(Uri uri) =>
new ConfigurationBuilder(uri);
#endregion
}
}
@@ -0,0 +1,412 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using WxOrder.Framework.Helpers;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// A standard Builder pattern for constructing a <see cref="Configuration"/> instance.
/// </summary>
/// <remarks>
/// <para>
/// Initialize a builder by calling <c>new ConfigurationBuilder(uri)</c> or
/// <c>Configuration.Builder(uri)</c>. The URI is always required; all other properties
/// are set to defaults. Use the builder's setter methods to modify any desired properties;
/// setter methods can be chained. Then call <c>Build()</c> to construct the final immutable
/// <c>Configuration</c>.
/// </para>
/// <para>
/// All setter methods will throw <c>ArgumentException</c> if called with an invalid value,
/// so it is never possible for <c>Build()</c> to fail.
/// </para>
/// </remarks>
public class ConfigurationBuilder
{
#region Private Fields
internal readonly Uri _uri;
internal TimeSpan _initialRetryDelay = Configuration.DefaultInitialRetryDelay;
internal TimeSpan _backoffResetThreshold = Configuration.DefaultBackoffResetThreshold;
internal string _lastEventId;
internal ILogger _logger;
internal IDictionary<string, string> _requestHeaders = new Dictionary<string, string>();
internal HttpMessageHandler _httpMessageHandler;
internal HttpClient _httpClient;
internal TimeSpan _maxRetryDelay = Configuration.DefaultMaxRetryDelay;
internal HttpMethod _method = HttpMethod.Get;
internal bool _preferDataAsUtf8Bytes = false;
internal TimeSpan _readTimeout = Configuration.DefaultReadTimeout;
internal Func<HttpContent> _requestBodyFactory;
internal TimeSpan _responseStartTimeout = Configuration.DefaultResponseStartTimeout;
internal Action<HttpRequestMessage> _httpRequestModifier;
#endregion
#region Constructor
internal ConfigurationBuilder(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
this._uri = uri;
}
#endregion
#region Public Methods
/// <summary>
/// Constructs a <see cref="Configuration"/> instance based on the current builder properies.
/// </summary>
/// <returns>the configuration</returns>
public Configuration Build() =>
new Configuration(this);
/// <summary>
/// Obsolete name for <see cref="ResponseStartTimeout(TimeSpan)"/>.
/// </summary>
/// <param name="responseStartTimeout">the timeout</param>
/// <returns>the builder</returns>
[Obsolete("Use ResponseStartTimeout")]
public ConfigurationBuilder ConnectionTimeout(TimeSpan responseStartTimeout) =>
ResponseStartTimeout(responseStartTimeout);
/// <summary>
/// Sets a delegate hook invoked before an HTTP request is performed. This may be useful if you
/// want to modify some properties of the request that EventSource doesn't already have an option for.
/// </summary>
/// <param name="httpRequestModifier">code that will be called with the request before it is sent</param>
/// <returns>the builder</returns>
public ConfigurationBuilder HttpRequestModifier(Action<HttpRequestMessage> httpRequestModifier)
{
this._httpRequestModifier = httpRequestModifier;
return this;
}
/// <summary>
/// Sets the initial amount of time to wait before attempting to reconnect to the EventSource API.
/// </summary>
/// <remarks>
/// <para>
/// If the connection fails more than once, the retry delay will increase from this value using
/// a backoff algorithm.
/// </para>
/// <para>
/// A server-directed reconnection time received via the SSE <c>retry:</c> field supersedes
/// this value, as do bounds installed by
/// <see cref="IEventSource.SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>.
/// </para>
/// <para>
/// The default value is <see cref="Configuration.DefaultInitialRetryDelay"/>. Negative values
/// are changed to zero.
/// </para>
/// <para>
/// The actual duration of each delay will vary slightly because there is a random jitter
/// factor to avoid clients all reconnecting at once.
/// </para>
/// </remarks>
/// <param name="initialRetryDelay">the initial retry delay</param>
/// <returns>the builder</returns>
/// <seealso cref="MaxRetryDelay(TimeSpan)"/>
public ConfigurationBuilder InitialRetryDelay(TimeSpan initialRetryDelay)
{
_initialRetryDelay = FiniteTimeSpan(initialRetryDelay);
return this;
}
/// <summary>
/// Sets the maximum amount of time to wait before attempting to reconnect.
/// </summary>
/// <remarks>
/// <para>
/// <c>EventSource</c> uses an exponential backoff algorithm (with random jitter) so that
/// the delay between reconnections starts at <see cref="InitialRetryDelay(TimeSpan)"/> but
/// increases with each subsequent attempt. <c>MaxRetryDelay</c> sets a limit on how long
/// the delay can be.
/// </para>
/// <para>
/// The default value is <see cref="Configuration.DefaultMaxRetryDelay"/>. Negative values
/// are changed to zero.
/// </para>
/// </remarks>
/// <param name="maxRetryDelay">the maximum retry delay</param>
/// <returns>the builder</returns>
/// <seealso cref="InitialRetryDelay(TimeSpan)"/>
public ConfigurationBuilder MaxRetryDelay(TimeSpan maxRetryDelay)
{
_maxRetryDelay = FiniteTimeSpan(maxRetryDelay);
return this;
}
/// <summary>
/// Sets the amount of time a connection must stay open before the EventSource resets its backoff delay.
/// </summary>
/// <remarks>
/// <para>
/// If a connection fails before the threshold has elapsed, the delay before reconnecting will be greater
/// than the last delay; if it fails after the threshold, the delay will start over at the initial minimum
/// value. This prevents long delays from occurring on connections that are only rarely restarted.
/// </para>
/// <para>
/// A connection that stays open for at least this long also discards any bounds set by
/// <see cref="IEventSource.SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>, restoring
/// <see cref="InitialRetryDelay(TimeSpan)"/> and <see cref="MaxRetryDelay(TimeSpan)"/>. A
/// server-directed reconnection time received via the SSE <c>retry:</c> field is not
/// discarded.
/// </para>
/// <para>
/// The default value is <see cref="Configuration.DefaultBackoffResetThreshold"/>. Negative
/// values are changed to zero.
/// </para>
/// </remarks>
/// <param name="backoffResetThreshold">the threshold time</param>
/// <returns>the builder</returns>
public ConfigurationBuilder BackoffResetThreshold(TimeSpan backoffResetThreshold)
{
_backoffResetThreshold = FiniteTimeSpan(backoffResetThreshold);
return this;
}
/// <summary>
/// Sets the maximum amount of time EventSource will wait between starting an HTTP request and
/// receiving the response headers.
/// </summary>
/// <remarks>
/// <para>
/// This is the same as the <c>Timeout</c> property in .NET's <c>HttpClient</c>. The default value is
/// <see cref="Configuration.DefaultConnectionTimeout"/>.
/// </para>
/// <para>
/// It is <i>not</i> the same as a TCP connection timeout. A connection timeout would include only the
/// time of establishing the connection, not the time it takes for the server to prepare the beginning
/// of the response. .NET does not consistently support a connection timeout, but if you are using .NET
/// Core or .NET 5+ you can implement it by using <c>SocketsHttpHandler</c> as your
/// <see cref="HttpMessageHandler(System.Net.Http.HttpMessageHandler)"/> and setting the
/// <c>ConnectTimeout</c> property there.
/// </para>
/// </remarks>
/// <param name="responseStartTimeout">the timeout</param>
/// <returns></returns>
public ConfigurationBuilder ResponseStartTimeout(TimeSpan responseStartTimeout)
{
_responseStartTimeout = TimeSpanCanBeInfinite(responseStartTimeout);
return this;
}
/// <summary>
/// Sets the timeout when reading from the EventSource API.
/// </summary>
/// <remarks>
/// <para>
/// The connection will be automatically dropped and restarted if the server sends no data within
/// this interval. This prevents keeping a stale connection that may no longer be working. It is common
/// for SSE servers to send a simple comment line (":") as a heartbeat to prevent timeouts.
/// </para>
/// <para>
/// The default value is <see cref="Configuration.DefaultReadTimeout"/>.
/// </para>
/// </remarks>
public ConfigurationBuilder ReadTimeout(TimeSpan readTimeout)
{
_readTimeout = TimeSpanCanBeInfinite(readTimeout);
return this;
}
/// <summary>
/// Sets the last event identifier.
/// </summary>
/// <remarks>
/// Setting this value will cause EventSource to add a "Last-Event-ID" header in its HTTP request.
/// This normally corresponds to the <see cref="MessageEvent.LastEventId"/> field of a previously
/// received event.
/// </remarks>
/// <param name="lastEventId">the event identifier</param>
/// <returns>the builder</returns>
public ConfigurationBuilder LastEventId(string lastEventId)
{
_lastEventId = lastEventId;
return this;
}
/// <summary>
/// Sets a custom logger to be used for all EventSource log output.
/// </summary>
/// <remarks>
/// <para>
/// This uses the <c>Logger</c> type from the <c>LaunchDarkly.Logging</c> library,
/// which provides several basic implementations such as <c>Logs.ToConsole</c> and an integration
/// with the .NET Core logging framework. For more about this and about adapters to other logging
/// frameworks, see <a href="https://github.com/launchdarkly/dotnet-logging"><c>LaunchDarkly.Logging</c></a>.
/// </para>
/// <para>
/// If you don't specify <see cref="LogAdapter(ILogAdapter)"/> or <see cref="Logger(Logging.Logger)"/>,
/// EventSource will not do any logging.
/// </para>
/// </remarks>
/// <example>
/// using LaunchDarkly.Logging;
///
/// // Define a logger that sends output to the console (standard output), suppressing
/// // Debug messages, and using a logger name of "EventStream"
/// var logger = Logs.ToConsole.Level(LogLevel.Info).Logger("EventStream");
/// var config = new ConfigurationBuilder(uri).
/// Logger(logger).
/// Build();
/// </example>
/// <param name="logger">a <c>LaunchDarkly.Logging.Logger</c> instance</param>
/// <returns>the builder</returns>
public ConfigurationBuilder Logger(ILogger logger)
{
_logger = logger;
return this;
}
/// <summary>
/// Specifies whether to use UTF-8 byte arrays internally if possible when
/// reading the stream.
/// </summary>
/// <remarks>
/// As described in <see cref="MessageEvent"/>, in some applications it may be
/// preferable to store and process event data as UTF-8 byte arrays rather than
/// strings. By default, <c>EventSource</c> will use the <c>string</c> type when
/// processing the event stream; if you then use <see cref="MessageEvent.DataUtf8Bytes"/>
/// to get the data, it will be converted to a byte array as needed. However, if
/// you set <c>PreferDataAsUtf8Bytes</c> to <see langword="true"/>, the event data
/// will be stored internally as a UTF-8 byte array so that if you read
/// <see cref="MessageEvent.DataUtf8Bytes"/>, you will get the same array with no
/// extra copying or conversion. Therefore, for greatest efficiency you should set
/// this to <see langword="true"/> if you intend to process the data as UTF-8. Note
/// that Server-Sent Event streams always use UTF-8 encoding, as required by the
/// SSE specification.
/// </remarks>
/// <param name="preferDataAsUtf8Bytes">true if you intend to request the event
/// data as UTF-8 bytes</param>
/// <returns>the builder</returns>
public ConfigurationBuilder PreferDataAsUtf8Bytes(bool preferDataAsUtf8Bytes)
{
_preferDataAsUtf8Bytes = preferDataAsUtf8Bytes;
return this;
}
/// <summary>
/// Sets the request headers to be sent with each EventSource HTTP request.
/// </summary>
/// <param name="headers">the headers (null is equivalent to an empty dictionary)</param>
/// <returns>the builder</returns>
public ConfigurationBuilder RequestHeaders(IDictionary<string, string> headers)
{
_requestHeaders = headers is null ? new Dictionary<string, string>() :
new Dictionary<string, string>(headers);
return this;
}
/// <summary>
/// Adds a request header to be sent with each EventSource HTTP request.
/// </summary>
/// <param name="name">the header name</param>
/// <param name="value">the header value </param>
/// <returns>the builder</returns>
public ConfigurationBuilder RequestHeader(string name, string value)
{
if (name != null)
{
_requestHeaders[name] = value;
}
return this;
}
/// <summary>
/// Sets the <c>HttpMessageHandler</c> that will be used for the HTTP client, or null for the default handler.
/// </summary>
/// <remarks>
/// If you have specified a custom HTTP client instance with <see cref="HttpClient"/>, then
/// <see cref="HttpMessageHandler(HttpMessageHandler)"/> is ignored.
/// </remarks>
/// <param name="handler">the message handler implementation</param>
/// <returns>the builder</returns>
public ConfigurationBuilder HttpMessageHandler(HttpMessageHandler handler)
{
this._httpMessageHandler = handler;
return this;
}
/// <summary>
/// Specifies that EventSource should use a specific HttpClient instance for HTTP requests.
/// </summary>
/// <remarks>
/// <para>
/// Normally, EventSource creates its own HttpClient and disposes of it when you dispose of the
/// EventSource. If you provide your own HttpClient using this method, you are responsible for
/// managing the HttpClient's lifecycle-- EventSource will not dispose of it.
/// </para>
/// <para>
/// EventSource will not modify this client's properties, so if you call <see cref="HttpMessageHandler"/>
/// or <see cref="ConnectionTimeout"/>, those methods will be ignored.
/// </para>
/// </remarks>
/// <param name="client">an HttpClient instance, or null to use the default behavior</param>
/// <returns>the builder</returns>
public ConfigurationBuilder HttpClient(HttpClient client)
{
this._httpClient = client;
return this;
}
/// <summary>
/// Sets the HTTP method that will be used when connecting to the EventSource API.
/// </summary>
/// <remarks>
/// By default, this is <see cref="HttpMethod.Get"/>.
/// </remarks>
public ConfigurationBuilder Method(HttpMethod method)
{
this._method = method ?? throw new ArgumentNullException(nameof(method));
return this;
}
/// <summary>
/// Sets a factory for HTTP request body content, if the HTTP method is one that allows a request body.
/// </summary>
/// <remarks>
/// This is in the form of a factory function because the request may need to be sent more than once.
/// </remarks>
/// <param name="factory">the factory function, or null for none</param>
/// <returns>the builder</returns>
public ConfigurationBuilder RequestBodyFactory(Func<HttpContent> factory)
{
this._requestBodyFactory = factory;
return this;
}
/// <summary>
/// Equivalent <see cref="RequestBodyFactory(Func{HttpContent})"/>, but for content
/// that is a simple string.
/// </summary>
/// <param name="bodyString">the content</param>
/// <param name="contentType">the Content-Type header</param>
/// <returns>the builder</returns>
public ConfigurationBuilder RequestBody(string bodyString, string contentType)
{
return RequestBodyFactory(() => new StringContent(bodyString, Encoding.UTF8, contentType));
}
#endregion
#region Private methods
// Canonicalizes the value so all negative numbers become InfiniteTimeSpan
private static TimeSpan TimeSpanCanBeInfinite(TimeSpan t) =>
t < TimeSpan.Zero ? Timeout.InfiniteTimeSpan : t;
// Replaces all negative times with zero
private static TimeSpan FiniteTimeSpan(TimeSpan t) =>
t < TimeSpan.Zero ? TimeSpan.Zero : t;
#endregion
}
}
@@ -0,0 +1,53 @@
namespace LaunchDarkly.EventSource
{
/// <summary>
/// An internal class used to hold static values used when processing Server Sent Events.
/// </summary>
internal static class Constants
{
/// <summary>
/// The HTTP header name for Accept.
/// </summary>
internal static string AcceptHttpHeader = "Accept";
/// <summary>
/// The HTTP header name for the last event identifier.
/// </summary>
internal static string LastEventIdHttpHeader = "Last-Event-ID";
/// <summary>
/// The HTTP header value for the Content Type.
/// </summary>
internal static string EventStreamContentType = "text/event-stream";
/// <summary>
/// The event type name for a Retry in a Server Sent Event.
/// </summary>
internal static string RetryField = "retry";
/// <summary>
/// The largest reconnection time honored from a Server Sent Event retry field.
/// </summary>
internal const long MaxServerDirectedRetryDelayMillis = 3_600_000;
/// <summary>
/// The identifier field name in a Server Sent Event.
/// </summary>
internal static string IdField = "id";
/// <summary>
/// The event type field name in a Server Sent Event.
/// </summary>
internal static string EventField = "event";
/// <summary>
/// The data field name in a Server Sent Event.
/// </summary>
internal static string DataField = "data";
/// <summary>
/// The message field name in a Server Sent Event.
/// </summary>
internal static string MessageField = "message";
}
}
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// An internal class containing helper methods to parse Server Sent Event data.
/// </summary>
internal static class EventParser
{
/// <summary>
/// The result returned by <see cref="ParseLineString(string)"/> or <see cref="ParseLineUtf8Bytes(Utf8ByteSpan)"/>.
/// </summary>
internal struct Result
{
internal string FieldName { get; set; } // null means it's a comment
internal string ValueString { get; set; }
internal Utf8ByteSpan ValueBytes { get; set; }
internal string GetValueAsString() => ValueString is null ? ValueBytes.GetString() : ValueString;
internal bool IsComment => FieldName is null;
internal bool IsDataField => FieldName == "data";
internal bool IsEventField => FieldName == "event";
internal bool IsIdField => FieldName == "id";
internal bool IsRetryField => FieldName == "retry";
}
/// <summary>
/// Attempts to parse a single non-empty line of SSE content that was read as a string. Empty lines
/// should not be not passed to this method.
/// </summary>
/// <param name="line">a line that was read from the stream, not including any trailing CR/LF</param>
/// <returns>a <see cref="Result"/> containing the parsed field or comment; <c>ValueString</c> will
/// be set rather than <c>ValueBytes</c></returns>
internal static Result ParseLineString(string line)
{
var colonPos = line.IndexOf(':');
if (colonPos == 0) // comment
{
return new Result { ValueString = line };
}
if (colonPos < 0) // field name without a value - assume empty value
{
return new Result { FieldName = line, ValueString = "" };
}
int valuePos = colonPos + 1;
if (valuePos < line.Length && line[valuePos] == ' ')
{
valuePos++; // trim a single leading space from the value, if present
}
return new Result
{
FieldName = line.Substring(0, colonPos),
ValueString = line.Substring(valuePos)
};
}
/// <summary>
/// Attempts to parse a single non-empty line of SSE content that was read as UTF-8 bytes. Empty lines
/// should not be not passed to this method.
/// </summary>
/// <param name="line">a line that was read from the stream, not including any trailing CR/LF</param>
/// <returns>a <see cref="Result"/> containing the parsed field or comment; <c>ValueBytes</c>
/// will be set rather than <c>ValueString</c></returns>
public static Result ParseLineUtf8Bytes(Utf8ByteSpan line)
{
if (line.Length > 0 && line.Data[line.Offset] == ':') // comment
{
return new Result { ValueBytes = line };
}
int colonPos = 0;
for (; colonPos < line.Length && line.Data[line.Offset + colonPos] != ':'; colonPos++) { }
string fieldName = Encoding.UTF8.GetString(line.Data, line.Offset, colonPos);
if (colonPos == line.Length) // field name without a value - assume empty value
{
return new Result {
FieldName = fieldName,
ValueBytes = new Utf8ByteSpan()
};
}
int valuePos = colonPos + 1;
if (valuePos < line.Length && line.Data[line.Offset + valuePos] == ' ')
{
valuePos++; // trim a single leading space from the value, if present
}
return new Result
{
FieldName = fieldName,
ValueBytes = new Utf8ByteSpan(line.Data, line.Offset + valuePos, line.Length - valuePos)
};
}
}
}
@@ -0,0 +1,518 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using WxOrder.Framework.Helpers;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// Provides an EventSource client for consuming Server-Sent Events. Additional details on the Server-Sent Events spec
/// can be found at https://html.spec.whatwg.org/multipage/server-sent-events.html
/// </summary>
public class EventSource : IEventSource, IDisposable
{
#region Private Fields
private readonly Configuration _configuration;
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
private List<string> _eventDataStringBuffer;
private MemoryStream _eventDataUtf8ByteBuffer;
private string _eventName;
private string _lastEventId;
private readonly ExponentialBackoffWithDecorrelation _backOff;
private readonly TimeSpan _configuredInitialRetryDelay;
private readonly TimeSpan _configuredMaxRetryDelay;
private CancellationTokenSource _currentRequestToken;
private readonly CancellationTokenSource _shutdownTokenSource = new CancellationTokenSource();
private static readonly TimeSpan MaxSleepTime = TimeSpan.FromMilliseconds(int.MaxValue);
private readonly Stopwatch _connectionTimer = new Stopwatch();
private ReadyState _readyState;
#endregion
#region Public Events
/// <inheritdoc/>
public event EventHandler<StateChangedEventArgs> Opened;
/// <inheritdoc/>
public event EventHandler<StateChangedEventArgs> Closed;
/// <inheritdoc/>
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
/// <inheritdoc/>
public event EventHandler<CommentReceivedEventArgs> CommentReceived;
/// <inheritdoc/>
public event EventHandler<ExceptionEventArgs> Error;
#endregion Public Events
#region Public Properties
/// <inheritdoc/>
public ReadyState ReadyState
{
get
{
lock (this)
{
return _readyState;
}
}
private set
{
lock (this)
{
_readyState = value;
}
}
}
internal TimeSpan BackOffDelay
{
get;
private set;
}
// Exposed for tests, so that retry-bounds behavior can be asserted directly
internal ExponentialBackoffWithDecorrelation BackOff => _backOff;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="EventSource" /> class.
/// </summary>
/// <param name="configuration">the configuration</param>
public EventSource(Configuration configuration)
{
_readyState = ReadyState.Raw;
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_logger = _configuration.Logger;
_configuredInitialRetryDelay = _configuration.InitialRetryDelay;
_configuredMaxRetryDelay = _configuration.MaxRetryDelay;
_backOff = new ExponentialBackoffWithDecorrelation(_configuredInitialRetryDelay,
_configuredMaxRetryDelay);
_httpClient = _configuration.HttpClient ?? CreateHttpClient();
}
/// <summary>
/// Shortcut for initializing an <see cref="EventSource"/> with only a stream URI
/// and no custom properties.
/// </summary>
/// <param name="uri">the stream URI</param>
/// <exception cref="ArgumentNullException">if the URI is null</exception>
public EventSource(Uri uri) : this(Configuration.Builder(uri).Build()) { }
#endregion
#region Public Methods
/// <inheritdoc/>
public async Task StartAsync()
{
bool firstTime = true;
while (ReadyState != ReadyState.Shutdown)
{
if (!firstTime)
{
if (_connectionTimer.IsRunning)
{
if (_connectionTimer.Elapsed >= _configuration.BackoffResetThreshold)
{
// Sustained healthy operation reverts any temporary bounds and resets
// n. Reverting takes precedence over bounds that were
// set during the preceding fault window.
ClearTemporaryRetryDelayBounds();
_backOff.ResetBackoffN();
}
_connectionTimer.Reset();
}
await MaybeWaitWithBackOff();
}
firstTime = false;
CancellationTokenSource newRequestTokenSource = null;
CancellationToken cancellationToken;
lock (this)
{
if (_readyState == ReadyState.Shutdown)
{
// in case Close() was called in between the previous ReadyState check and the creation of the new token
return;
}
newRequestTokenSource = new CancellationTokenSource();
_currentRequestToken?.Dispose();
_currentRequestToken = newRequestTokenSource;
}
if (ReadyState == ReadyState.Connecting || ReadyState == ReadyState.Open)
{
throw new InvalidOperationException(string.Format(Resources.ErrorAlreadyStarted, ReadyState));
}
SetReadyState(ReadyState.Connecting);
cancellationToken = newRequestTokenSource.Token;
try
{
await ConnectToEventSourceAsync(cancellationToken);
// ConnectToEventSourceAsync normally doesn't return, unless it detects that the request has been cancelled.
Close(ReadyState.Closed);
}
catch (Exception e)
{
_logger.Error(e.Message);
CancelCurrentRequest();
// If the user called Close(), ReadyState = Shutdown, so errors are irrelevant.
if (ReadyState != ReadyState.Shutdown)
{
Exception realException = e;
if (realException is AggregateException ae && ae.InnerExceptions.Count == 1)
{
realException = ae.InnerException;
}
if (realException is OperationCanceledException oe)
{
// This exception could either be the result of us explicitly cancelling a request, in which case we don't
// need to do anything else, or it could be that the request timed out.
if (oe.CancellationToken.IsCancellationRequested)
{
realException = null;
}
else
{
realException = new TimeoutException();
}
}
if (realException != null)
{
OnError(new ExceptionEventArgs(realException));
}
Close(ReadyState.Closed);
}
}
}
}
private async Task MaybeWaitWithBackOff()
{
TimeSpan sleepTime = _backOff.GetNextBackOff();
if (sleepTime > MaxSleepTime)
{
// Task.Delay throws for anything above the platform timer ceiling, and this method
// runs outside the reconnect loop's exception handling, so an unclamped value
// would fault StartAsync and stop the stream permanently.
sleepTime = MaxSleepTime;
}
if (sleepTime > TimeSpan.Zero)
{
_logger.Info(string.Format("Waiting {0} milliseconds before reconnecting...", sleepTime.TotalMilliseconds));
BackOffDelay = sleepTime;
try
{
await Task.Delay(sleepTime, _shutdownTokenSource.Token);
}
catch (OperationCanceledException)
{
// Cancellation happened during the wait, likely intentional close
_logger.Debug("Backoff wait interrupted by shutdown");
}
}
}
/// <inheritdoc/>
public void Restart(bool resetBackoffDelay)
{
lock (this)
{
if (_readyState != ReadyState.Open)
{
return;
}
if (resetBackoffDelay)
{
_backOff.ResetBackoffN();
}
}
CancelCurrentRequest();
}
/// <inheritdoc/>
public void SetTemporaryRetryDelayBounds(TimeSpan initialDelay, TimeSpan maxDelay)
{
_backOff.SetBounds(initialDelay, maxDelay);
}
/// <inheritdoc/>
public void ClearTemporaryRetryDelayBounds()
{
_backOff.SetBounds(_configuredInitialRetryDelay, _configuredMaxRetryDelay);
}
/// <summary>
/// Closes the connection to the SSE server. The <c>EventSource</c> cannot be reopened after this.
/// </summary>
public void Close()
{
if (ReadyState != ReadyState.Shutdown)
{
Close(ReadyState.Shutdown);
}
CancelCurrentRequest();
_shutdownTokenSource.Cancel();
// do not dispose httpClient if it is user provided
if (_configuration.HttpClient == null)
{
_httpClient.Dispose();
}
}
/// <summary>
/// Equivalent to calling <see cref="Close()"/>.
/// </summary>
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
#endregion
#region Private Methods
private HttpClient CreateHttpClient()
{
var client = _configuration.HttpMessageHandler is null ?
new HttpClient() :
new HttpClient(_configuration.HttpMessageHandler, false);
client.Timeout = _configuration.ResponseStartTimeout;
return client;
}
private void CancelCurrentRequest()
{
CancellationTokenSource requestTokenSource = null;
lock (this)
{
requestTokenSource = _currentRequestToken;
_currentRequestToken = null;
}
if (requestTokenSource != null)
{
_logger.Debug("Cancelling current request");
requestTokenSource.Cancel();
requestTokenSource.Dispose();
}
}
internal virtual EventSourceService GetEventSourceService(Configuration configuration)
{
return new EventSourceService(configuration, _httpClient, _logger);
}
private async Task ConnectToEventSourceAsync(CancellationToken cancellationToken)
{
_eventDataStringBuffer = null;
_eventDataUtf8ByteBuffer = null;
var svc = GetEventSourceService(_configuration);
svc.ConnectionOpened += (o, e) =>
{
_connectionTimer.Restart();
SetReadyState(ReadyState.Open, OnOpened, e.Headers);
};
svc.ConnectionClosed += (o, e) => { SetReadyState(ReadyState.Closed, OnClosed); };
await svc.GetDataAsync(
ProcessResponseLineString,
ProcessResponseLineUtf8,
_lastEventId,
cancellationToken
);
}
private void Close(ReadyState state)
{
_logger.Debug(string.Format("Close({0}) - state was {1}", state, ReadyState));
SetReadyState(state, OnClosed);
}
private void ProcessResponseLineString(string content)
{
if (content == null)
{
// StreamReader may emit a null if the stream has been closed; there's nothing to
// be done at this level in that case
return;
}
if (content.Length == 0)
{
DispatchEvent();
}
else
{
HandleParsedLine(EventParser.ParseLineString(content));
}
}
private void ProcessResponseLineUtf8(Utf8ByteSpan content)
{
if (content.Length == 0)
{
DispatchEvent();
}
else
{
HandleParsedLine(EventParser.ParseLineUtf8Bytes(content));
}
}
private void SetReadyState(ReadyState state, Action<StateChangedEventArgs> action = null,
IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers = null)
{
lock (this)
{
if (_readyState == state || _readyState == ReadyState.Shutdown)
{
return;
}
_readyState = state;
}
if (action != null)
{
action(new StateChangedEventArgs(state, headers));
}
}
private void HandleParsedLine(EventParser.Result result)
{
if (result.IsComment)
{
OnCommentReceived(new CommentReceivedEventArgs(result.GetValueAsString()));
}
else if (result.IsDataField)
{
if (result.ValueString != null)
{
if (_eventDataStringBuffer is null)
{
_eventDataStringBuffer = new List<string>(2);
}
_eventDataStringBuffer.Add(result.ValueString);
_eventDataStringBuffer.Add("\n");
}
else
{
if (_eventDataUtf8ByteBuffer is null)
{
_eventDataUtf8ByteBuffer = new MemoryStream(result.ValueBytes.Length + 1);
}
_eventDataUtf8ByteBuffer.Write(result.ValueBytes.Data, result.ValueBytes.Offset, result.ValueBytes.Length);
_eventDataUtf8ByteBuffer.WriteByte((byte)'\n');
}
}
else if (result.IsEventField)
{
_eventName = result.GetValueAsString();
}
else if (result.IsIdField)
{
_lastEventId = result.GetValueAsString();
}
else if (result.IsRetryField)
{
if (long.TryParse(result.GetValueAsString(), out var retry))
{
// Clamp while the value is still an integer.
var millis = Math.Max(0,
Math.Min(retry, Constants.MaxServerDirectedRetryDelayMillis));
_backOff.SetServerDirectedMinDelay(TimeSpan.FromMilliseconds(millis));
}
}
}
private void DispatchEvent()
{
var name = _eventName ?? Constants.MessageField;
_eventName = null;
MessageEvent message;
if (_eventDataStringBuffer != null)
{
if (_eventDataStringBuffer.Count == 0)
{
return;
}
// remove last item which is always a trailing newline
_eventDataStringBuffer.RemoveAt(_eventDataStringBuffer.Count - 1);
var dataString = string.Concat(_eventDataStringBuffer);
message = new MessageEvent(name, dataString, _lastEventId, _configuration.Uri);
_eventDataStringBuffer.Clear();
}
else
{
if (_eventDataUtf8ByteBuffer is null || _eventDataUtf8ByteBuffer.Length == 0)
{
return;
}
var dataSpan = new Utf8ByteSpan(_eventDataUtf8ByteBuffer.GetBuffer(), 0,
(int)_eventDataUtf8ByteBuffer.Length - 1); // remove trailing newline
message = new MessageEvent(name, dataSpan, _lastEventId, _configuration.Uri);
// We've now taken ownership of the original buffer; null out the previous
// reference to it so a new one will be created next time
_eventDataUtf8ByteBuffer = null;
}
_logger.Debug(string.Format("Received event \"{0}\"", name));
OnMessageReceived(new MessageReceivedEventArgs(message));
}
private void OnOpened(StateChangedEventArgs e) =>
Opened?.Invoke(this, e);
private void OnClosed(StateChangedEventArgs e) =>
Closed?.Invoke(this, e);
private void OnMessageReceived(MessageReceivedEventArgs e) =>
MessageReceived?.Invoke(this, e);
private void OnCommentReceived(CommentReceivedEventArgs e) =>
CommentReceived?.Invoke(this, e);
private void OnError(ExceptionEventArgs e) =>
Error?.Invoke(this, e);
#endregion
}
}
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// Event arguments for the EventSourceService opened event.
/// </summary>
internal class EventSourceOpenedEventArgs: EventArgs
{
/// <summary>
/// Construct new event arguments.
/// </summary>
/// <param name="headers">headers from the HTTP response</param>
public EventSourceOpenedEventArgs(IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers)
{
Headers = headers;
}
/// <summary>
/// Response headers from the underlying HTTP request.
/// </summary>
public IEnumerable<KeyValuePair<string,IEnumerable<string>>> Headers { get; }
}
}
@@ -0,0 +1,290 @@
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using WxOrder.Framework.Helpers;
using static LaunchDarkly.EventSource.AsyncHelpers;
namespace LaunchDarkly.EventSource
{
internal class EventSourceService
{
#region Private Fields
// Must be >= 4096 to bypass Xamarin.Android.Net.AndroidMessageHandler's
// BufferedStream-4096 small-count code path, which stalls SSE reads for
// ~60 s waiting for the next server keepalive. See SDK-2755.
private const int ReadBufferSize = 8192;
private readonly Configuration _configuration;
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
private const string UserAgentProduct = "DotNetClient";
internal static readonly string UserAgentVersion = ((AssemblyInformationalVersionAttribute)typeof(EventSource)
.GetTypeInfo()
.Assembly
.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)))
.InformationalVersion;
#endregion
#region Public Events
/// <summary>
/// Occurs when the connection to the EventSource API has been opened.
/// </summary>
public event EventHandler<EventSourceOpenedEventArgs> ConnectionOpened;
/// <summary>
/// Occurs when the connection to the EventSource API has been closed.
/// </summary>
public event EventHandler<EventArgs> ConnectionClosed;
#endregion
#region Constructors
internal EventSourceService(Configuration configuration, HttpClient httpClient, ILogger logger)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
#endregion
#region Public Methods
/// <summary>
/// Initiates the request to the EventSource API and parses Server Sent Events received by the API.
/// </summary>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> A task that represents the work queued to execute in the ThreadPool.</returns>
public async Task GetDataAsync(
Action<string> processResponseLineString,
Action<Utf8ByteSpan> processResponseLineUTF8,
string lastEventId,
CancellationToken cancellationToken
)
{
cancellationToken.ThrowIfCancellationRequested();
await ConnectToEventSourceApi(processResponseLineString, processResponseLineUTF8, lastEventId, cancellationToken);
}
#endregion
#region Private Methods
private async Task ConnectToEventSourceApi(
Action<string> processResponseLineString,
Action<Utf8ByteSpan> processResponseLineUTF8,
string lastEventId,
CancellationToken cancellationToken
)
{
_logger.Debug(string.Format("Making {0} request to EventSource URI {1}",
_configuration.Method ?? HttpMethod.Get,
_configuration.Uri));
var request = CreateHttpRequestMessage(_configuration.Uri, lastEventId);
this._configuration.HttpRequestModifier?.Invoke(request);
using (var response = await _httpClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken).ConfigureAwait(false))
{
_logger.Debug(string.Format("Response status: {0}", (int)response.StatusCode));
ValidateResponse(response);
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
var encoding = DetectEncoding(response);
if (encoding != Encoding.UTF8)
{
throw new EventSourceServiceCancelledException(
string.Format(Resources.ErrorWrongEncoding, encoding.HeaderName));
}
OnConnectionOpened(response.Headers);
if (_configuration.PreferDataAsUtf8Bytes)
{
_logger.Debug("Reading UTF-8 stream without string conversion");
await ProcessResponseFromUtf8StreamAsync(processResponseLineUTF8, stream, cancellationToken);
}
else
{
_logger.Debug("Reading stream with string conversion");
using (var reader = new StreamReader(stream, Encoding.UTF8,
detectEncodingFromByteOrderMarks: true, bufferSize: ReadBufferSize))
{
await ProcessResponseFromReaderAsync(processResponseLineString, reader, cancellationToken);
}
}
}
OnConnectionClosed();
}
}
private Encoding DetectEncoding(HttpResponseMessage response)
{
var charset = response.Content.Headers.ContentType?.CharSet;
if (charset != null)
{
try
{
return Encoding.GetEncoding(charset);
}
catch (ArgumentException) { }
}
return Encoding.UTF8;
}
protected virtual async Task ProcessResponseFromReaderAsync(
Action<string> processResponse,
StreamReader reader,
CancellationToken cancellationToken
)
{
while (!cancellationToken.IsCancellationRequested)
{
var line = await DoWithTimeout(_configuration.ReadTimeout, cancellationToken,
token => AllowCancellation(reader.ReadLineAsync(), token));
if (line == null)
{
// this means the stream is done, i.e. the connection was closed
return;
}
processResponse(line);
}
}
protected async Task ProcessResponseFromUtf8StreamAsync(
Action<Utf8ByteSpan> processResponseLine,
Stream stream,
CancellationToken cancellationToken
)
{
var lineScanner = new ByteArrayLineScanner(ReadBufferSize);
while (!cancellationToken.IsCancellationRequested)
{
// Note that even though Stream.ReadAsync has an overload that takes a CancellationToken, that
// does not actually work for network sockets (https://stackoverflow.com/questions/12421989/networkstream-readasync-with-a-cancellation-token-never-cancels).
// So we must use AsyncHelpers.AllowCancellation to wrap it in a cancellable task.
int bytesRead = await DoWithTimeout(_configuration.ReadTimeout, cancellationToken,
token => AllowCancellation(stream.ReadAsync(lineScanner.Buffer, lineScanner.Count, lineScanner.Available), token));
if (bytesRead == 0)
{
cancellationToken.ThrowIfCancellationRequested();
return;
}
lineScanner.AddedBytes(bytesRead);
while (lineScanner.ScanToEndOfLine(out var lineSpan))
{
processResponseLine(lineSpan);
}
}
}
private HttpRequestMessage CreateHttpRequestMessage(Uri uri, string lastEventId)
{
var request = new HttpRequestMessage(_configuration.Method ?? HttpMethod.Get, uri);
// Add all headers provided in the Configuration Headers. This allows a consumer to provide any request headers to the EventSource API
if (_configuration.RequestHeaders != null)
{
foreach (var item in _configuration.RequestHeaders)
{
try
{
request.Headers.Add(item.Key, item.Value);
}
catch (FormatException)
{
// Avoid showing the Authorization header value in the exception message
if (item.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase))
{
throw new FormatException("The Authorization header is invalid.");
}
throw;
}
}
}
// Add the request body, if any.
if (_configuration.RequestBodyFactory != null)
{
HttpContent requestBody = _configuration.RequestBodyFactory();
if (requestBody != null)
{
request.Content = requestBody;
}
}
// If the lastEventId was provided, include it as a header to the API request.
if (!string.IsNullOrWhiteSpace(lastEventId))
{
request.Headers.Remove(Constants.LastEventIdHttpHeader);
request.Headers.Add(Constants.LastEventIdHttpHeader, lastEventId);
}
// If we haven't set the LastEventId header and if the EventSource Configuration was provided with a LastEventId,
// include it as a header to the API request.
if (!string.IsNullOrWhiteSpace(_configuration.LastEventId) && !request.Headers.Contains(Constants.LastEventIdHttpHeader))
request.Headers.Add(Constants.LastEventIdHttpHeader, _configuration.LastEventId);
if (request.Headers.UserAgent.Count == 0)
request.Headers.UserAgent.ParseAdd(UserAgentProduct + "/" + UserAgentVersion);
// Add the Accept Header if it wasn't provided in the Configuration
if (!request.Headers.Contains(Constants.AcceptHttpHeader))
request.Headers.Add(Constants.AcceptHttpHeader, Constants.EventStreamContentType);
request.Headers.ExpectContinue = false;
request.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true };
return request;
}
private void ValidateResponse(HttpResponseMessage response)
{
// Any non-2xx response status is an error. A 204 (no content) is also an error.
if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NoContent)
{
throw new EventSourceServiceUnsuccessfulResponseException((int)response.StatusCode, response.Headers);
}
if (response.Content == null)
{
throw new EventSourceServiceCancelledException(Resources.ErrorEmptyResponse);
}
if (response.Content.Headers.ContentType.MediaType != Constants.EventStreamContentType)
{
throw new EventSourceServiceCancelledException(
string.Format(Resources.ErrorWrongContentType, response.Content.Headers.ContentType));
}
}
private void OnConnectionOpened(HttpHeaders headers)
{
ConnectionOpened?.Invoke(this, new EventSourceOpenedEventArgs(headers));
}
private void OnConnectionClosed()
{
ConnectionClosed?.Invoke(this, EventArgs.Empty);
}
#endregion
}
}
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// General superclass for exceptions that caused the EventSource to disconnect or fail to establish
/// a connection.
/// </summary>
public class EventSourceServiceCancelledException : Exception
{
#region Public Constructors
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="message">the exception message</param>
public EventSourceServiceCancelledException(string message) : base(message) { }
/// <summary>
/// Creates a new instance with an inner exception.
/// </summary>
/// <param name="message">the exception message</param>
/// <param name="innerException">the inner exception</param>
public EventSourceServiceCancelledException(string message, Exception innerException) :
base(message, innerException)
{ }
#endregion
}
}
@@ -0,0 +1,51 @@
using System.Collections.Generic;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// Indicates that the EventSource was able to establish an HTTP connection, but received a
/// non-successful status code.
/// </summary>
public class EventSourceServiceUnsuccessfulResponseException : EventSourceServiceCancelledException
{
#region Public Properties
/// <summary>
/// The HTTP status code of the response.
/// </summary>
public int StatusCode { get; }
/// <summary>
/// The HTTP headers from the response.
/// </summary>
public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Headers { get; }
#endregion
#region Public Constructors
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="statusCode">the HTTP status code of the response</param>
public EventSourceServiceUnsuccessfulResponseException(int statusCode) :
this(statusCode, new Dictionary<string, IEnumerable<string>>())
{
}
/// <summary>
/// Creates a new instance with headers.
/// </summary>
/// <param name="statusCode">the HTTP status code of the response</param>
/// <param name="headers">the HTTP headers from the response</param>
public EventSourceServiceUnsuccessfulResponseException(int statusCode, IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers) :
base(string.Format(Resources.ErrorHttpStatus, statusCode))
{
StatusCode = statusCode;
Headers = headers ?? new Dictionary<string, IEnumerable<string>>();
}
#endregion
}
}
@@ -0,0 +1,28 @@
using System;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// Provides exception data raised in the EventSource <see cref="EventSource.Error" /> event.
/// </summary>
/// <seealso cref="System.EventArgs" />
public class ExceptionEventArgs : EventArgs
{
/// <summary>
/// Gets the <see cref="System.Exception"/> that represents the error that occurred.
/// </summary>
/// <value>
/// The exception.
/// </value>
public Exception Exception { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionEventArgs"/> class.
/// </summary>
/// <param name="ex">A <see cref="System.Exception"/> that represents the error that occurred.</param>
public ExceptionEventArgs(Exception ex)
{
Exception = ex;
}
}
}
@@ -0,0 +1,206 @@
using System;
namespace LaunchDarkly.EventSource
{
internal sealed class ExponentialBackoffWithDecorrelation
{
private readonly object _lock = new object();
private readonly Random _randomSource;
private TimeSpan _minimumDelay;
private TimeSpan _maximumDelay;
private int _backoffN;
private TimeSpan? _serverDirectedMinDelay;
public ExponentialBackoffWithDecorrelation(TimeSpan minimumDelay, TimeSpan maximumDelay)
: this(minimumDelay, maximumDelay, new Random())
{
}
/// <summary>
/// Constructs an instance with a caller-supplied <see cref="Random"/>, so that tests can
/// make jitter deterministic.
/// </summary>
internal ExponentialBackoffWithDecorrelation(TimeSpan minimumDelay, TimeSpan maximumDelay,
Random randomSource)
{
_minimumDelay = NonNegative(minimumDelay);
_maximumDelay = NonNegative(maximumDelay);
_randomSource = randomSource ?? new Random();
}
/// <summary>
/// Gets the next backoff duration, advancing n.
/// </summary>
public TimeSpan GetNextBackOff()
{
lock (_lock)
{
long unjittered = GetUnjitteredMillisecondsForN(_backoffN);
// Random.Next takes an int bound. 2^31 milliseconds is far longer than any
// reconnect delay we would use, so saturating here cannot affect a realistic
// delay.
int jitterBound = (int)Math.Min(unjittered, int.MaxValue);
long delayMillis = unjittered / 2
+ (jitterBound > 0 ? _randomSource.Next(jitterBound) / 2 : 0);
_backoffN++;
return TimeSpan.FromMilliseconds(delayMillis);
}
}
/// <summary>
/// Returns the delay in whole milliseconds for a given backoff <c>n</c>, before jitter is
/// applied: <c>minimumDelay * 2^n</c>, limited to the maximum.
/// </summary>
/// <remarks>
/// <para>
/// The caller must hold the lock. This reads the bounds without taking it because it is the
/// inner core of <see cref="GetNextBackOff"/>, which already holds it; taking it here would
/// only be a re-entrant acquisition on the hot path. Anything needing a synchronized read of
/// the bounds on its own should use the accessors below, which take the lock themselves.
/// </para>
/// <para>
/// <c>n</c> is compared against the ceiling rather than used to compute a value that is
/// then clamped, so no intermediate ever exceeds the maximum. That matters because
/// <c>n</c> is unbounded: a long outage keeps incrementing it, and computing
/// <c>minimumDelay * 2^n</c> directly would overflow.
/// </para>
/// </remarks>
internal long GetUnjitteredMillisecondsForN(int n)
{
long min = (_serverDirectedMinDelay ?? _minimumDelay).Ticks
/ TimeSpan.TicksPerMillisecond;
long max = _maximumDelay.Ticks / TimeSpan.TicksPerMillisecond;
if (min <= 0 || max <= 0)
{
return 0;
}
if (n <= 0)
{
return min > max ? max : min;
}
// Shifting the ceiling down cannot overflow, whereas shifting the minimum up can.
// The n >= 63 test is required rather than defensive: C# masks a 64-bit shift count
// to its low 6 bits, so `max >> 64` would silently mean `max >> 0`.
if (n >= 63 || min > (max >> n))
{
return max;
}
return min << n;
}
/// <summary>
/// Applies a server-directed reconnection time received via the SSE <c>retry:</c> field,
/// replacing the minimum delay used to compute subsequent backoffs.
/// </summary>
/// <remarks>
/// <para>
/// The override takes precedence over both the configured minimum and any minimum
/// installed by <see cref="SetBounds"/>. It is sticky: it survives bounds changes and
/// <see cref="ResetBackoffN"/>, and is replaced only by a later server-directed value.
/// </para>
/// <para>
/// The maximum is never affected, so the ceiling that bounds reconnection keeps applying.
/// </para>
/// <para>
/// n resets, so the next attempt uses the directed value itself rather than continuing to
/// double from wherever the progression had reached.
/// </para>
/// <para>
/// Negative values become zero. No upper bound is applied here; a caller taking a value
/// from an untrusted source is responsible for capping it first.
/// </para>
/// </remarks>
/// <param name="minDelay">the server-directed reconnection time</param>
public void SetServerDirectedMinDelay(TimeSpan minDelay)
{
var value = NonNegative(minDelay);
lock (_lock)
{
_serverDirectedMinDelay = value;
_backoffN = 0;
}
}
/// <summary>
/// Replaces the delay bounds.
/// </summary>
/// <remarks>
/// If the new bounds differ from the current ones, n resets so that the
/// next delay starts from the new minimum. If they are the same, this does nothing, which
/// makes repeated calls with identical values idempotent -- a caller that reapplies the
/// same bounds on every failure will not pin the delay at the minimum.
/// </remarks>
/// <param name="minimumDelay">the new minimum delay; negative values become zero</param>
/// <param name="maximumDelay">the new maximum delay; negative values become zero</param>
public void SetBounds(TimeSpan minimumDelay, TimeSpan maximumDelay)
{
var min = NonNegative(minimumDelay);
var max = NonNegative(maximumDelay);
lock (_lock)
{
if (min == _minimumDelay && max == _maximumDelay)
{
return;
}
_minimumDelay = min;
_maximumDelay = max;
_backoffN = 0;
}
}
/// <summary>
/// Resets n so the next delay starts from the current minimum, without
/// changing the bounds.
/// </summary>
public void ResetBackoffN()
{
lock (_lock)
{
_backoffN = 0;
}
}
// Accessors for tests.
internal int GetBackoffN()
{
lock (_lock)
{
return _backoffN;
}
}
internal TimeSpan? GetServerDirectedMinDelay()
{
lock (_lock)
{
return _serverDirectedMinDelay;
}
}
internal TimeSpan GetMinimumDelay()
{
lock (_lock)
{
return _minimumDelay;
}
}
internal TimeSpan GetMaximumDelay()
{
lock (_lock)
{
return _maximumDelay;
}
}
// Matches the clamping behavior of ConfigurationBuilder's retry-delay setters: a negative
// duration becomes zero rather than throwing.
private static TimeSpan NonNegative(TimeSpan t) => t < TimeSpan.Zero ? TimeSpan.Zero : t;
}
}
@@ -0,0 +1,160 @@
using System;
using System.Threading.Tasks;
namespace LaunchDarkly.EventSource
{
/// <summary>
/// This interface defines the public members of <see cref="EventSource"/>.
/// </summary>
public interface IEventSource
{
#region Public Events
/// <summary>
/// Occurs when the connection to the EventSource API has been opened.
/// </summary>
event EventHandler<StateChangedEventArgs> Opened;
/// <summary>
/// Occurs when the connection to the EventSource API has been closed.
/// </summary>
event EventHandler<StateChangedEventArgs> Closed;
/// <summary>
/// Occurs when a Server Sent Event from the EventSource API has been received.
/// </summary>
event EventHandler<MessageReceivedEventArgs> MessageReceived;
/// <summary>
/// Occurs when a comment has been received from the EventSource API.
/// </summary>
event EventHandler<CommentReceivedEventArgs> CommentReceived;
/// <summary>
/// Occurs when an error has happened when the EventSource is open and processing Server Sent Events.
/// </summary>
event EventHandler<ExceptionEventArgs> Error;
#endregion Public Events
#region Public Properties
/// <summary>
/// Gets the state of the EventSource connection.
/// </summary>
ReadyState ReadyState { get; }
#endregion
#region Public Methods
/// <summary>
/// Initiates a connection to the SSE server and begins parsing events.
/// </summary>
/// <returns>a <see cref="Task"/> that will be completed only when the
/// <c>EventSource</c> is closed</returns>
/// <exception cref="InvalidOperationException">if the method was called again after the
/// stream connection was already active</exception>
Task StartAsync();
/// <summary>
/// Triggers the same "close and retry" behavior as if an error had been encountered on the stream.
/// </summary>
/// <remarks>
/// <para>
/// If the stream is currently active, this closes the connection, waits for some amount of time
/// as determined by the usual backoff behavior (and <paramref name="resetBackoffDelay"/>), and
/// then attempts to reconnect. If the stream is not yet connected, is already waiting to
/// reconnect, or has been permanently shut down, this has no effect.
/// </para>
/// <para>
/// The method returns immediately without waiting for the reconnection to happen. You will
/// receive <see cref="Closed"/> and <see cref="Opened"/> events when it does happen (or an
/// <see cref="Error"/> event if the new connection attempt fails).
/// </para>
/// </remarks>
/// <param name="resetBackoffDelay">true if the delay before reconnection should be reset to
/// the lowest level of the currently active bounds, which could be the temporary bounds if
/// <see cref="SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/> is in effect; false if it
/// should increase according to the usual exponential backoff logic</param>
void Restart(bool resetBackoffDelay);
/// <summary>
/// Temporarily replaces the bounds used to compute reconnection delays.
/// </summary>
/// <remarks>
/// <para>
/// The configured <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/> and
/// <see cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/> normally govern the
/// exponential backoff between reconnection attempts. This method installs different
/// bounds at runtime, so a caller can slow reconnection down without reconfiguring or
/// recreating the <c>EventSource</c>.
/// </para>
/// <para>
/// The bounds are <i>temporary</i>: they remain in effect until either a connection stays
/// open for at least
/// <see cref="ConfigurationBuilder.BackoffResetThreshold(TimeSpan)"/>, at which point the
/// configured bounds are restored automatically, or
/// <see cref="ClearTemporaryRetryDelayBounds"/> is called.
/// </para>
/// <para>
/// Changing the bounds resets the backoff level, so the next delay is computed from the new
/// <paramref name="initialDelay"/> rather than continuing to grow from where it left off.
/// Calling this with bounds that are already in effect does nothing, so it is safe to call
/// repeatedly.
/// </para>
/// <para>
/// Negative values are changed to zero. If <paramref name="initialDelay"/> is greater than
/// <paramref name="maxDelay"/>, delays are limited to <paramref name="maxDelay"/>. No
/// argument causes this method to throw, and no argument can cause a later reconnect to
/// fail.
/// </para>
/// <para>
/// A server-directed reconnection time received via the SSE <c>retry:</c> field supersedes
/// <paramref name="initialDelay"/>, and the configured
/// <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/> along with it. Such a
/// value does not affect <paramref name="maxDelay"/>, so the ceiling set here continues to
/// bound reconnection.
/// </para>
/// <para>
/// It is safe to call this from any thread, including from an
/// <see cref="Error"/> handler.
/// </para>
/// </remarks>
/// <param name="initialDelay">the lowest delay to use while these bounds are in effect,
/// unless a server-directed <c>retry:</c> value supersedes it</param>
/// <param name="maxDelay">the highest delay to use while these bounds are in effect</param>
/// <seealso cref="ClearTemporaryRetryDelayBounds"/>
void SetTemporaryRetryDelayBounds(TimeSpan initialDelay, TimeSpan maxDelay);
/// <summary>
/// Discards any bounds installed by
/// <see cref="SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>, restoring the configured
/// <see cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/> and, unless a server-directed
/// <c>retry:</c> value is in effect, the configured
/// <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/>.
/// </summary>
/// <remarks>
/// <para>
/// Restoring the configured bounds resets the backoff level. If no temporary bounds
/// are in effect this does nothing. The count of reconnection attempts is not reset.
/// Calling this is not required as the configured bounds are also restored automatically
/// after a connection stays open for
/// <see cref="ConfigurationBuilder.BackoffResetThreshold(TimeSpan)"/>.
/// </para>
/// <para>
/// A server-directed reconnection time received via the SSE <c>retry:</c> field is not
/// discarded and continues to supersede
/// <see cref="ConfigurationBuilder.InitialRetryDelay(TimeSpan)"/>, so the configured
/// minimum may not be the one actually in use afterwards. Only a later <c>retry:</c> value
/// replaces it. <see cref="ConfigurationBuilder.MaxRetryDelay(TimeSpan)"/> is unaffected
/// and is always restored.
/// </para>
/// </remarks>
/// <seealso cref="SetTemporaryRetryDelayBounds(TimeSpan, TimeSpan)"/>
void ClearTemporaryRetryDelayBounds();
/// <summary>
/// Closes the connection to the SSE server. The <c>EventSource</c> cannot be reopened after this.
/// </summary>
void Close();
#endregion
}
}
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more