This commit is contained in:
Your Name
2026-03-19 12:19:00 +08:00
parent 7832514f28
commit 7147c8e148
243 changed files with 1662 additions and 437 deletions
@@ -25,6 +25,82 @@ class OrderController extends BaseAdminController
return $this->dataLists(new OrderLists());
}
/**
* @notes 同步企业微信对外收款账单到订单
* 员工直接在企业微信发起收款(未经过后台创建)时,通过此接口拉取并创建订单
* @return \think\response\Json
*/
public function syncWechatWorkBills()
{
$beginStr = $this->request->get('begin_time', date('Y-m-d', strtotime('-7 days')));
$endStr = $this->request->get('end_time', date('Y-m-d'));
$beginTime = strtotime($beginStr . ' 00:00:00');
$endTime = strtotime($endStr . ' 23:59:59');
if ($beginTime >= $endTime) {
return $this->fail('开始时间必须早于结束时间');
}
if ($endTime - $beginTime > 31 * 86400) {
return $this->fail('企业微信接口限制:时间范围不能超过31天');
}
$result = OrderLogic::syncFromWechatWorkBills($beginTime, $endTime);
if (!empty($result['errors']) && $result['created'] === 0 && $result['updated'] === 0) {
return $this->fail(implode('', $result['errors']));
}
return $this->success('同步完成', $result);
}
/**
* @notes 调试:测试企业微信对外收款 API 连接(返回原始响应,用于排查同步为0的问题)
* @return \think\response\Json
*/
public function syncWechatWorkBillsDebug()
{
$beginStr = $this->request->get('begin_time', date('Y-m-d'));
$endStr = $this->request->get('end_time', date('Y-m-d'));
$payeeUserid = trim((string)$this->request->get('payee_userid', ''));
$beginTime = strtotime($beginStr . ' 00:00:00');
$endTime = strtotime($endStr . ' 23:59:59');
$service = new \app\common\service\wechat\WechatWorkExternalPayService();
$config = config('pay.wechat_work', []);
$debug = [
'config_ok' => !empty($config['corp_id']) && !empty($config['external_pay_secret']),
'corp_id' => $config['corp_id'] ? substr($config['corp_id'], 0, 8) . '***' : '(空)',
'time_range' => [$beginStr, $endStr],
'payee_userid' => $payeeUserid ?: '(未指定,查全部)',
'access_token' => $service->getAccessToken() ? '已获取' : '获取失败',
];
$resp = $service->getBillList($beginTime, $endTime, $payeeUserid, '', 100);
$debug['api_errcode'] = $resp['errcode'] ?? -999;
$debug['api_errmsg'] = $resp['errmsg'] ?? '';
$debug['bill_count'] = count($resp['bill_list'] ?? []);
$debug['next_cursor'] = !empty($resp['next_cursor']) ? '有' : '无';
$debug['page1'] = $resp;
if (!empty($resp['next_cursor']) && $debug['bill_count'] === 0) {
$resp2 = $service->getBillList($beginTime, $endTime, $payeeUserid, $resp['next_cursor'], 100);
$debug['page2_errcode'] = $resp2['errcode'] ?? -999;
$debug['page2_bill_count'] = count($resp2['bill_list'] ?? []);
$debug['page2_sample'] = isset($resp2['bill_list'][0]) ? $resp2['bill_list'][0] : null;
}
if ($debug['bill_count'] === 0 && empty($payeeUserid)) {
$admins = \app\common\model\auth\Admin::where('work_wechat_userid', '<>', '')
->whereNull('delete_time')->column('work_wechat_userid', 'id');
$debug['try_payee_userids'] = array_values(array_filter(array_unique($admins)));
$debug['tip'] = '若 try_payee_userids 有值,可传 payee_userid=xxx 重试(如 ?payee_userid=GaoXingLiang';
}
return $this->success('调试信息', $debug);
}
/**
* @notes 今日收益(按角色权限)
* @return \think\response\Json
*/
public function todayRevenue()
{
$result = OrderLogic::todayRevenue($this->adminId, $this->adminInfo);
return $this->data($result);
}
/**
* @notes 订单统计(挂号费/药品费用)
* @return \think\response\Json
@@ -70,14 +146,46 @@ class OrderController extends BaseAdminController
}
/**
* @notes 编辑订单
* @notes 创建企业微信对外收款订单
* 返回 order_no,供员工在企业微信发起收款时作为商户订单号(out_trade_no)使用
* 收款成功后,微信支付回调会自动更新订单为已支付
* @return \think\response\Json
*/
public function createForWechatWork()
{
$params = (new OrderValidate())->post()->goCheck('create');
$params['creator_id'] = $this->adminId;
$result = OrderLogic::createForWechatWork($params);
if (!$result) {
return $this->fail(OrderLogic::getError());
}
return $this->success('创建成功,请在企业微信收款时使用以下订单号', [
'order_no' => $result['order_no'],
'order' => $result['order'],
'tip' => '在企业微信发起对外收款时,将上述订单号填写为「商户订单号」',
]);
}
/**
* @notes 编辑订单(关联患者、订单类型)
* 权限:超管或指定角色组可修改任意订单;其他用户只能修改自己创建的订单
* @return \think\response\Json
*/
public function edit()
{
$params = (new OrderValidate())->post()->goCheck('edit');
$orderId = (int)$params['id'];
$order = \app\common\model\Order::find($orderId);
if (!$order) {
return $this->fail('订单不存在');
}
if (!$this->canEditOrder($order)) {
return $this->fail('无权限修改此订单');
}
$result = OrderLogic::edit((int)$params['id'], $params);
$result = OrderLogic::edit($orderId, $params);
if (!$result) {
return $this->fail(OrderLogic::getError());
}
@@ -85,6 +193,22 @@ class OrderController extends BaseAdminController
return $this->success('编辑成功');
}
/**
* @notes 是否可编辑指定订单(超管或指定角色可编辑任意,否则只能编辑自己创建的)
*/
private function canEditOrder($order): bool
{
if (!empty($this->adminInfo['root']) && $this->adminInfo['root'] == 1) {
return true;
}
$editAllRoles = config('project.order_edit_all_roles', [0, 3]);
$roleIds = \app\common\model\auth\AdminRole::where('admin_id', $this->adminId)->column('role_id');
if (count(array_intersect($roleIds, $editAllRoles)) > 0) {
return true;
}
return (int)$order->creator_id === $this->adminId;
}
/**
* @notes 支付订单
* @return \think\response\Json
@@ -4,11 +4,13 @@ declare(strict_types=1);
namespace app\adminapi\controller\order;
use app\adminapi\logic\order\OrderLogic;
use app\common\model\Order;
use think\response\Xml;
/**
* 微信支付回调控制器
* 支持:1) 预创建订单的支付 2) 员工直接在企业微信发起对外收款(自动创建订单)
* Class WechatNotifyController
* @package app\adminapi\controller\order
*/
@@ -33,24 +35,36 @@ class WechatNotifyController
return $this->xmlResponse('FAIL', '签名验证失败');
}
// 验证金额
$order = Order::where('order_no', $data['out_trade_no'])->find();
$outTradeNo = $data['out_trade_no'] ?? '';
$totalFee = (int)($data['total_fee'] ?? 0);
$amount = $totalFee / 100;
$transactionId = $data['transaction_id'] ?? '';
$order = Order::where('order_no', $outTradeNo)->find();
if (!$order) {
// 订单不存在:员工直接在企业微信发起收款,自动创建订单并标记已支付
if ($data['result_code'] == 'SUCCESS' && $totalFee > 0) {
$newOrder = OrderLogic::createFromCallback($outTradeNo, $amount, $transactionId);
if ($newOrder) {
return $this->xmlResponse('SUCCESS', '支付成功');
}
}
return $this->xmlResponse('FAIL', '订单不存在');
}
if ((int)$data['total_fee'] != (int)($order->amount * 100)) {
if ($totalFee != (int)($order->amount * 100)) {
return $this->xmlResponse('FAIL', '金额不匹配');
}
// 验证交易状态
if ($data['result_code'] == 'SUCCESS') {
// 更新订单状态
// 更新订单状态(支持普通微信支付及企业微信对外收款)
if ($order->status == 1) { // 只有待支付的订单才能更新
$order->status = 2; // 已支付
$order->payment_method = 'wechat';
$order->payment_time = date('Y-m-d H:i:s');
$order->trade_no = $data['transaction_id'];
$order->trade_no = $transactionId;
$order->save();
}
}
@@ -69,6 +69,14 @@ class OrderLists extends BaseAdminDataLists implements ListsSearchInterface
// 权限控制:普通员工只能看自己创建的订单
$this->filterByPermission($where);
// 处理患者关联状态:pending=待关联, associated=已关联
$patientAssociation = $this->params['patient_association'] ?? '';
if ($patientAssociation === 'pending') {
$where[] = ['patient_id', 'null', ''];
} elseif ($patientAssociation === 'associated') {
$where[] = ['patient_id', 'not null', ''];
}
// 处理患者关键词搜索(从诊单表搜索)
if (!empty($this->params['patient_keyword'])) {
$where[] = ['patient_id', 'in', function ($query) {
@@ -106,6 +114,14 @@ class OrderLists extends BaseAdminDataLists implements ListsSearchInterface
// 权限控制:普通员工只能看自己创建的订单
$this->filterByPermission($where);
// 处理患者关联状态
$patientAssociation = $this->params['patient_association'] ?? '';
if ($patientAssociation === 'pending') {
$where[] = ['patient_id', 'null', ''];
} elseif ($patientAssociation === 'associated') {
$where[] = ['patient_id', 'not null', ''];
}
// 处理患者关键词搜索(从诊单表搜索)
if (!empty($this->params['patient_keyword'])) {
$where[] = ['patient_id', 'in', function ($query) {
@@ -6,7 +6,10 @@ namespace app\adminapi\logic\order;
use app\common\model\Order;
use app\common\model\OrderDetail;
use app\common\model\auth\Admin;
use app\common\service\wechat\WechatWorkExternalPayService;
use think\facade\Db;
use think\facade\Log;
/**
* 订单业务逻辑
@@ -49,6 +52,180 @@ class OrderLogic
}
}
/**
* @notes 创建企业微信对外收款订单(参考 https://developer.work.weixin.qq.com/document/path/93665
* 创建后返回 order_no,供员工在企业微信发起收款时作为 out_trade_no 使用
* 收款成功后,微信支付回调会自动更新订单为已支付
* @param array $params patient_id, order_type, amount, creator_id, remark
* @return array|false ['order_no' => '...', 'order' => Order]
*/
public static function createForWechatWork(array $params)
{
$order = self::create($params);
if (!$order) {
return false;
}
return [
'order_no' => $order->order_no,
'order' => $order->toArray(),
];
}
/**
* @notes 从企业微信对外收款账单同步订单(员工直接在企业微信发起收款,未经过后台创建)
* 拉取 get_bill_list 接口的已支付记录,创建或更新本地订单
* @param int $beginTime 开始时间戳(秒)
* @param int $endTime 结束时间戳(秒)
* @return array ['created' => int, 'updated' => int, 'skipped' => int, 'errors' => string[]]
*/
public static function syncFromWechatWorkBills(int $beginTime, int $endTime): array
{
$result = ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errors' => []];
$service = new WechatWorkExternalPayService();
$wechatWorkConfig = config('pay.wechat_work', []);
$defaultCreatorId = $wechatWorkConfig['default_creator_id'] ?? '';
$defaultOrderType = $wechatWorkConfig['default_order_type'] ?? 6;
$payeeUserids = [];
$firstResp = $service->getBillList($beginTime, $endTime, '', '', 100);
if (count($firstResp['bill_list'] ?? []) === 0 && !empty($firstResp['next_cursor'])) {
$admins = Admin::where('work_wechat_userid', '<>', '')->whereNull('delete_time')->column('work_wechat_userid');
$payeeUserids = array_values(array_unique(array_filter($admins)));
}
if (empty($payeeUserids)) {
$payeeUserids = [''];
}
foreach ($payeeUserids as $payeeUserid) {
$cursor = '';
do {
$resp = $service->getBillList($beginTime, $endTime, $payeeUserid, $cursor, 100);
if (($resp['errcode'] ?? -1) !== 0) {
$result['errors'][] = '获取账单失败: ' . ($resp['errmsg'] ?? '未知错误');
break;
}
$billList = $resp['bill_list'] ?? [];
$cursor = $resp['next_cursor'] ?? '';
foreach ($billList as $bill) {
$tradeState = (int)($bill['trade_state'] ?? 0);
if (!in_array($tradeState, [1, 3], true)) {
$result['skipped']++;
continue;
}
$orderNo = (string)($bill['out_trade_no'] ?? $bill['trade_no'] ?? '');
$totalFee = (int)($bill['total_fee'] ?? $bill['total_amount'] ?? 0);
$tradeNo = (string)($bill['transaction_id'] ?? $bill['trade_no'] ?? '');
$payTime = $bill['pay_time'] ?? $bill['time_end'] ?? '';
$billPayeeUserid = (string)($bill['payee_userid'] ?? '');
if (empty($orderNo) || $totalFee <= 0) {
$result['skipped']++;
continue;
}
$amount = round($totalFee / 100, 2);
$orderType = ($amount == 5.00) ? 1 : $defaultOrderType;
$creatorId = 0;
if ($billPayeeUserid) {
$admin = Admin::where('work_wechat_userid', $billPayeeUserid)->whereNull('delete_time')->find();
if ($admin) {
$creatorId = (int)$admin->id;
}
}
$payerExternalUserid = (string)($bill['external_userid'] ?? '');
$order = Order::where('order_no', $orderNo)->find();
if ($order) {
if ($order->status == 1) {
$order->status = 2;
$order->payment_method = 'wechat';
$order->payment_time = $payTime ? (is_numeric($payTime) ? date('Y-m-d H:i:s', (int)$payTime) : $payTime) : date('Y-m-d H:i:s');
$order->trade_no = $tradeNo;
$order->payee_userid = $billPayeeUserid;
$order->payer_external_userid = $payerExternalUserid;
$order->creator_id = $creatorId;
$order->order_type = $orderType;
$order->save();
$result['updated']++;
} else {
$needSave = false;
if ($billPayeeUserid && $creatorId !== $defaultCreatorId && (int)$order->creator_id === $defaultCreatorId) {
$order->payee_userid = $billPayeeUserid;
$order->payer_external_userid = $payerExternalUserid;
$order->creator_id = $creatorId;
$needSave = true;
}
if ($amount == 5.00 && (int)$order->order_type !== 1) {
$order->order_type = 1;
$needSave = true;
}
if ($needSave) {
$order->save();
}
$result['skipped']++;
}
} else {
try {
$order = new Order();
$order->order_no = $orderNo;
$order->patient_id = null;
$order->creator_id = $creatorId;
$order->order_type = $orderType;
$order->amount = $amount;
$order->status = 2;
$order->payment_method = 'wechat';
$order->payment_time = $payTime ? (is_numeric($payTime) ? date('Y-m-d H:i:s', (int)$payTime) : $payTime) : date('Y-m-d H:i:s');
$order->trade_no = $tradeNo;
$order->remark = '企业微信直接收款同步,待关联患者';
$order->payee_userid = $billPayeeUserid;
$order->payer_external_userid = $payerExternalUserid;
$order->save();
$result['created']++;
} catch (\Exception $e) {
$result['errors'][] = "订单 {$orderNo}: " . $e->getMessage();
Log::error("企业微信账单同步创建订单失败: {$orderNo}, " . $e->getMessage());
}
}
}
} while ($cursor);
}
return $result;
}
/**
* @notes 从回调数据创建订单(员工直接在企业微信发起收款时,订单不存在则自动创建)
* @param string $orderNo 商户订单号(out_trade_no
* @param float $amount 金额(元)
* @param string $tradeNo 微信交易号
* @return Order|null
*/
public static function createFromCallback(string $orderNo, float $amount, string $tradeNo = ''): ?Order
{
try {
$wechatWorkConfig = config('pay.wechat_work', []);
$creatorId = $wechatWorkConfig['default_creator_id'] ?? 1;
$orderType = $wechatWorkConfig['default_order_type'] ?? 6;
$order = new Order();
$order->order_no = $orderNo;
$order->patient_id = null; // 待关联,管理员可后续编辑
$order->creator_id = $creatorId;
$order->order_type = $orderType;
$order->amount = $amount;
$order->status = 2; // 已支付
$order->payment_method = 'wechat';
$order->payment_time = date('Y-m-d H:i:s');
$order->trade_no = $tradeNo;
$order->remark = '企业微信直接收款,待关联患者';
$order->save();
return $order;
} catch (\Exception $e) {
return null;
}
}
/**
* @notes 编辑订单
* @param int $id
@@ -67,6 +244,14 @@ class OrderLogic
if (isset($params['remark'])) {
$order->remark = $params['remark'];
}
// 支持关联患者(待关联订单可后续关联)
if (array_key_exists('patient_id', $params)) {
$order->patient_id = $params['patient_id'] ? (int)$params['patient_id'] : null;
}
// 支持修改订单类型
if (isset($params['order_type'])) {
$order->order_type = (int)$params['order_type'];
}
$order->save();
return true;
@@ -190,6 +375,33 @@ class OrderLogic
}
}
/**
* @notes 今日收益(按角色权限:超管/主管看全部,普通员工看自己)
* @param int $adminId 当前管理员ID
* @param array $adminInfo 管理员信息(含 root、role 等)
* @return array ['amount' => string, 'count' => int]
*/
public static function todayRevenue(int $adminId, array $adminInfo = []): array
{
$query = Order::where('status', 2)
->whereBetweenTime('payment_time', date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59')
->whereNull('delete_time');
if (empty($adminInfo['root']) || $adminInfo['root'] != 1) {
$supervisorRoles = config('project.order_edit_all_roles', [0, 3]);
$roleIds = \app\common\model\auth\AdminRole::where('admin_id', $adminId)->column('role_id');
if (count(array_intersect($roleIds, $supervisorRoles)) === 0) {
$query->where('creator_id', $adminId);
}
}
$row = $query->fieldRaw('COUNT(*) as cnt, COALESCE(SUM(amount), 0) as total')->find();
$total = is_object($row) ? ($row->total ?? 0) : ($row['total'] ?? 0);
$cnt = is_object($row) ? ($row->cnt ?? 0) : ($row['cnt'] ?? 0);
return [
'amount' => number_format((float)$total, 2, '.', ''),
'count' => (int)$cnt,
];
}
/**
* @notes 获取订单详情
* @param int $id
@@ -1018,7 +1018,7 @@ class DiagnosisLogic extends BaseLogic
throw new \Exception('小程序配置未设置');
}
$scene = "id={$sceneId}&share_user={$shareUserId}";
$scene = "id={$sceneId}&share_user={$shareUserId}&doctor_id={$doctorId}";
// 调用微信接口生成小程序码
$qrcodeUrl = self::generateWxQrcode($config, $page, $scene);
@@ -16,10 +16,11 @@ class OrderValidate extends BaseValidate
protected $rule = [
'id' => 'require|integer',
'patient_id' => 'require|integer',
'order_type' => 'require|in:1,2,3',
'patient_id_optional' => 'integer',
'order_type' => 'require|in:1,2,3,4,5,6,7',
'amount' => 'require|float',
'status' => 'require|in:1,2,3,4',
'payment_method' => 'in:alipay,wechat',
'payment_method' => 'in:alipay,wechat,wechat_work',
'remark' => 'string|max:500',
'order_no' => 'string|max:50',
'is_supplement' => 'in:0,1',
@@ -37,7 +38,7 @@ class OrderValidate extends BaseValidate
protected $scene = [
'create' => ['patient_id', 'order_type', 'amount'],
'edit' => ['id', 'remark'],
'edit' => ['id'],
'detail' => ['id'],
'pay' => ['payment_method'],
'cancel' => ['id'],