完成了基本调整调整

This commit is contained in:
2026-09-18 20:55:21 +08:00
parent 864187e105
commit 57e0854a0e
56 changed files with 3122 additions and 105 deletions
@@ -3,6 +3,7 @@ declare (strict_types=1);
namespace app\store\controller;
use app\common\model\qyt\Enterprise as EnterpriseModel;
use app\store\controller\Controller;
use app\store\model\Partners as PartnersModel;
use app\store\model\partners\Order as OrderModel;
@@ -40,15 +41,47 @@ class Partners extends Controller
$newList = [];
$OrderModel = new OrderModel();
$date = date("Y-m-d");
// 企油通企业:口径与下单时 Enterprise::resolve 一致(绑定且启用 -> 用绑定的;否则 -> 默认企业)
$bindIds = array_filter(array_map('intval', array_column($list['data'], 'qyt_enterprise_id')));
$enterprises = $bindIds
? array_column(EnterpriseModel::whereIn('enterprise_id', $bindIds)
->field('enterprise_id,company_name,passageway,is_enable')->select()->toArray(), null, 'enterprise_id')
: [];
$default = EnterpriseModel::getDefault();
foreach ($list['data'] as $val){
$val['day_money'] =$OrderModel->getOrderTotalPrice($date, $date, $val);
$val['total_money'] =$OrderModel->getOrderTotalPrice(null, null, $val);
$val = array_merge($val, $this->enterpriseInfo((int)$val['qyt_enterprise_id'], $enterprises, $default));
$newList[] = $val;
}
$list['data'] = $newList;
return $this->renderSuccess(['list'=>$list,'user'=>$this->store['user']]);
}
/**
* 合作商实际使用的企油通企业
* qyt_enterprise_source:bind 绑定 / default 未绑定走默认 / invalid 绑定的企业已停用或删除(实际走默认)/ none 无可用企业
*/
private function enterpriseInfo(int $bindId, array $enterprises, $default): array
{
$bound = $bindId > 0 ? ($enterprises[$bindId] ?? null) : null;
if ($bound && (int)$bound['is_enable'] === 1) {
$source = 'bind';
$use = $bound;
} else {
$source = $bindId > 0 ? 'invalid' : 'default';
$use = $default ? $default->toArray() : null;
!$use && $source = $bindId > 0 ? 'invalid' : 'none';
}
return [
'qyt_enterprise_source' => $source,
// 绑定失效时也把原绑定企业名带出来,便于排查
'qyt_bind_name' => $bound['company_name'] ?? '',
'qyt_enterprise_name' => $use['company_name'] ?? '',
'qyt_enterprise_channel' => isset($use['passageway']) ? ($use['passageway'] === 'pingan' ? '平安银行' : '支付宝企业码') : '',
];
}
/**
* 获取所有商户
* @return mixed
@@ -16,7 +16,9 @@ namespace app\store\controller\partners;
use app\common\service\PartnersBalance;
use app\common\service\QueueService;
use app\common\model\qyt\Enterprise as EnterpriseModel;
use app\common\service\QytInvoice;
use app\common\service\QytOil;
use app\common\service\QytRefund;
use app\store\controller\Controller;
use app\store\model\order\QrCode as QrCodeModel;
use app\store\model\partners\Order as OrderModel;
@@ -66,8 +68,12 @@ class Order extends Controller
if (!$order) {
return $this->renderError('订单不存在');
}
if ($order['use_status'] != 0) {
return $this->renderError('该单已加油核销');
// 一单可以分多次加油:没加完的单继续给加油地址
if ((int) $order['refund_status'] === 2) {
return $this->renderError('该单已退款,不能再加油');
}
if ((float) $order['used_amount'] + 0.005 >= (float) $order['total_price']) {
return $this->renderError('该单金额已全部加油');
}
if ($order['oil_status'] != 1) {
return $this->renderError('该单尚未发放成功,无法获取加油地址');
@@ -193,12 +199,120 @@ class Order extends Controller
if ($order['use_status'] != 1) {
return $this->renderError('该单未加油核销,无可回调内容');
}
(new QueueService())->push('notify_queue', json_encode([
'order_id' => $orderId,
'type' => 'sub',
'optType' => 'add_oil',
'retry_count' => 0,
], 320));
return $this->renderSuccess('已重新推送加油结果');
// 每笔加油单独通知:优先补推还没通知成功的;都通知过了就全部重推一遍(下游按 shareNo 去重)
$ids = Db::name('qyt_consume')->where('order_id', $orderId)->where('notify_status', 0)->order('id')->column('id');
$all = !$ids;
$all && $ids = Db::name('qyt_consume')->where('order_id', $orderId)->order('id')->column('id');
$queue = new QueueService();
if (!$ids) {
// 没有消费流水(改造前的历史单),按旧口径推一次
$queue->push('notify_queue', json_encode(['order_id' => $orderId, 'optType' => 'add_oil', 'retry_count' => 0], 320));
return $this->renderSuccess('已重新推送加油结果');
}
foreach ($ids as $consumeId) {
$queue->push('notify_queue', json_encode([
'order_id' => $orderId,
'optType' => 'add_oil',
'consume_id' => (int) $consumeId,
'retry_count' => 0,
], 320));
}
return $this->renderSuccess(($all ? '已重新推送全部 ' : '已补推未通知的 ') . count($ids) . ' 笔加油结果');
}
// ================================================================
// 退款(整单全额:7.17 查凭证 + 7.16 调低额度)
// ================================================================
/**
* 发起退款
*/
public function refund(): Json
{
$orderId = (int) $this->request->param('orderId');
$reason = trim((string) $this->request->param('reason', ''));
if (!Db::name('partners_order')->where('order_id', $orderId)->count()) {
return $this->renderError('订单不存在');
}
$res = QytRefund::apply($orderId, 'admin', $this->operator(), $reason);
return $res['ok'] ? $this->renderSuccess($res['data'], $res['message']) : $this->renderError($res['message']);
}
/**
* 确认「待人工确认」的退款:向企油通取证(7.13 流水 + 7.17 凭证)
*/
public function refundConfirm(): Json
{
$res = QytRefund::confirm((int) $this->request->param('orderId'));
return $this->decided($res) ? $this->renderSuccess($res['data'], $res['message']) : $this->renderError($res['message']);
}
/**
* 人工判定「待人工确认」的退款
* result = success / failed,remark 必填(判定依据)
*/
public function refundResolve(): Json
{
$result = (string) $this->request->param('result');
if (!in_array($result, ['success', 'failed'], true)) {
return $this->renderError('判定结果不合法');
}
$res = QytRefund::resolve(
(int) $this->request->param('orderId'),
$result === 'success',
$this->operator(),
(string) $this->request->param('remark', '')
);
return $this->decided($res) ? $this->renderSuccess($res['data'], $res['message']) : $this->renderError($res['message']);
}
/**
* 订单的退款流水
*/
public function refundLog(): Json
{
$list = Db::name('qyt_refund')
->where('order_id', (int) $this->request->param('orderId'))
->field('refund_id,refund_no,source,operator,reason,amount,quota_id,total_before,available_before,total_after,available_after,status,message,create_time,update_time')
->order('refund_id', 'desc')
->select()->toArray();
foreach ($list as &$row) {
$row['status_text'] = QytRefund::STATUS_TEXT[(int) $row['status']] ?? '';
$row['create_time_text'] = date('Y-m-d H:i:s', (int) $row['create_time']);
}
return $this->renderSuccess(compact('list'));
}
// ================================================================
// 发票(7.14,按「企业 + 消费月份 + 司机」关联)
// ================================================================
public function invoice(): Json
{
$order = Db::name('partners_order')->where('order_id', (int) $this->request->param('orderId'))->find();
if (!$order) {
return $this->renderError('订单不存在');
}
if ((int) $order['use_status'] !== 1) {
return $this->renderError('该订单还没有加油记录,暂无发票');
}
$res = QytInvoice::forOrder($order, (bool) $this->request->param('refresh', 0));
return $res['ok'] ? $this->renderSuccess($res, $res['message']) : $this->renderError($res['message']);
}
/**
* 取证 / 人工判定是否得出了结论:退款成功,或明确判定为「未生效」都算请求成功,
* 由返回的 refundStatus 区分;状态不符、取证失败、仍无法判定才算失败
*/
private function decided(array $res): bool
{
return $res['ok']
|| ($res['status'] === QytRefund::FAILED && $res['reason'] === QytRefund::REASON_UPSTREAM);
}
/** 当前后台操作人 */
private function operator(): string
{
return (string) ($this->store['user']['user_name'] ?? 'admin');
}
}
@@ -0,0 +1,195 @@
<?php
// +----------------------------------------------------------------------
// | 后台 · 企油通司机管理
// +----------------------------------------------------------------------
// | list() 司机档案 + 从订单实时汇总的累计发放 / 已退款 / 订单数
// | detail() 档案、涉及企业、最近订单(发放失败原因里能看到二要素核验结果)
// | upstream() 实时查企油通:balance 7.12 钱包余额 / wallet 7.13 钱包流水 / voucher 7.17 支付凭证
// |
// | 身份证号全程只在后端使用,返回前端一律打码。
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\store\controller\qyt;
use app\common\model\qyt\Enterprise as EnterpriseModel;
use app\common\service\QytOil;
use app\common\service\QytRefund;
use app\store\controller\Controller;
use think\facade\Db;
use think\response\Json;
class Driver extends Controller
{
public function list(): Json
{
$param = $this->request->param();
$keyword = trim((string) ($param['keyword'] ?? ''));
$query = Db::name('qyt_driver')->where('store_id', $this->storeId);
if ($keyword !== '') {
if (preg_match('/^\d{17}[\dXx]$/', $keyword)) {
$query->where('id_card', strtoupper($keyword));
} elseif (preg_match('/^1\d{10}$/', $keyword)) {
$query->where('mobile', $keyword);
} else {
$query->whereLike('name', '%' . $keyword . '%');
}
}
if (isset($param['conflict']) && $param['conflict'] !== '' && (int) $param['conflict'] >= 0) {
$query->where('conflict', (int) $param['conflict']);
}
$list = $query->order('last_order_time', 'desc')->paginate(15)->toArray();
$stats = $this->stats(array_column($list['data'], 'id_card'));
foreach ($list['data'] as &$row) {
$row = $this->formatDriver($row, $stats[$row['id_card']] ?? []);
}
return $this->renderSuccess(compact('list'));
}
public function detail(int $driverId): Json
{
$driver = $this->findDriver($driverId);
if (!$driver) {
return $this->renderError('司机不存在');
}
$stats = $this->stats([$driver['id_card']]);
// 涉及过的企业(上游查询要按企业查)
$entIds = Db::name('partners_order')->where('store_id', $this->storeId)
->where('id_card', $driver['id_card'])->where('qyt_enterprise_id', '>', 0)
->group('qyt_enterprise_id')->column('qyt_enterprise_id');
$enterprises = $entIds
? EnterpriseModel::whereIn('enterprise_id', $entIds)
->field('enterprise_id,company_name,passageway,status')->select()->toArray()
: [];
$orders = Db::name('partners_order')->where('store_id', $this->storeId)->where('id_card', $driver['id_card'])
->field('order_id,oilCardNo,partners_order_no,total_price,driver_name,mobile,oil_status_zsy,oil_text,use_status,refund_status,refund_text,qyt_enterprise_id,create_time')
->order('order_id', 'desc')->limit(20)->select()->toArray();
foreach ($orders as &$o) {
$o['mobile'] = QytOil::maskMobile((string) $o['mobile']);
$o['refund_status_text'] = QytRefund::STATUS_TEXT[(int) $o['refund_status']] ?? '';
$o['create_time_text'] = date('Y-m-d H:i:s', (int) $o['create_time']);
}
return $this->renderSuccess([
'detail' => $this->formatDriver($driver, $stats[$driver['id_card']] ?? []),
'enterprises' => $enterprises,
'orders' => $orders,
]);
}
/**
* 实时查企油通
* type: balance 7.12 / wallet 7.13 / voucher 7.17
*/
public function upstream(int $driverId, int $enterpriseId, string $type = 'balance', int $page = 1): Json
{
$driver = $this->findDriver($driverId);
if (!$driver) {
return $this->renderError('司机不存在');
}
$enterprise = EnterpriseModel::detail($enterpriseId);
if (!$enterprise) {
return $this->renderError('企业不存在');
}
$qyt = QytOil::forEnterprise($enterprise);
$mobile = (string) $driver['mobile'];
$idCard = (string) $driver['id_card'];
$page = max(1, $page);
switch ($type) {
case 'balance':
$res = $qyt->driverBalanceQuery($mobile, $idCard, $page, 20);
break;
case 'wallet':
$res = $qyt->driverWalletQuery($mobile, $idCard, $page, 20);
break;
case 'voucher':
$res = $qyt->getVoucherList($mobile, $idCard, $page, 20);
break;
default:
return $this->renderError('查询类型不合法');
}
if ($res['code'] !== '00') {
return $this->renderError('企油通返回:' . ($res['message'] ?: '查询失败'));
}
$data = (array) $res['data'];
// 7.12 / 7.13 金额是「分」,统一转成元再给前端;7.17 本来就是元
if ($type === 'balance' || $type === 'wallet') {
foreach (['totalGrantAmount', 'availableBalance'] as $k) {
isset($data[$k]) && $data[$k . 'Yuan'] = QytOil::fenToYuan($data[$k]);
}
foreach (['list', 'transactionDetails'] as $listKey) {
foreach ((array) ($data[$listKey] ?? []) as $i => $item) {
foreach (['total_amount', 'available_amount', 'amount'] as $k) {
if (isset($item[$k]) && is_numeric($item[$k])) {
$data[$listKey][$i][$k . '_yuan'] = QytOil::fenToYuan((int) $item[$k]);
}
}
}
}
}
return $this->renderSuccess(['type' => $type, 'data' => QytOil::maskDeep($data)]);
}
// ================================================================
private function findDriver(int $driverId): ?array
{
$row = Db::name('qyt_driver')->where('store_id', $this->storeId)->where('driver_id', $driverId)->find();
return $row ?: null;
}
/**
* 从订单实时汇总,按身份证号分组
*/
private function stats(array $idCards): array
{
if (!$idCards) {
return [];
}
$rows = Db::name('partners_order')
->where('store_id', $this->storeId)
->whereIn('id_card', $idCards)
->fieldRaw('id_card,'
. ' COUNT(*) AS order_num,'
. ' SUM(IF(oil_status_zsy = 2, total_price, 0)) AS grant_amount,'
. ' SUM(IF(refund_status = 2, refund_amount, 0)) AS refund_amount,'
. ' SUM(IF(use_status = 1, 1, 0)) AS used_num,'
. ' SUM(used_amount) AS used_amount,'
. ' SUM(IF(oil_status_zsy = 3, 1, 0)) AS fail_num,'
. ' SUM(IF(oil_status_zsy = 1, 1, 0)) AS pending_num')
->group('id_card')
->select()->toArray();
return array_column($rows, null, 'id_card');
}
private function formatDriver(array $row, array $stat): array
{
$grant = round((float) ($stat['grant_amount'] ?? 0), 2);
$refund = round((float) ($stat['refund_amount'] ?? 0), 2);
$out = [
'driver_id' => (int) $row['driver_id'],
'name' => $row['name'],
'mobile' => $row['mobile'],
'id_card_mask' => QytOil::maskIdCard((string) $row['id_card']),
'conflict' => (int) $row['conflict'],
'conflict_text' => $row['conflict_text'],
'last_order_time_text' => $row['last_order_time'] ? date('Y-m-d H:i:s', (int) $row['last_order_time']) : '',
'order_num' => (int) ($stat['order_num'] ?? 0),
'used_num' => (int) ($stat['used_num'] ?? 0),
'fail_num' => (int) ($stat['fail_num'] ?? 0),
'pending_num' => (int) ($stat['pending_num'] ?? 0),
'grant_amount' => number_format($grant, 2, '.', ''),
'refund_amount' => number_format($refund, 2, '.', ''),
'used_amount' => number_format((float) ($stat['used_amount'] ?? 0), 2, '.', ''),
// 本地口径的净发放额,仅供参考;真实可用额度以企油通 7.12 为准
'net_amount' => number_format($grant - $refund, 2, '.', ''),
];
return $out;
}
}
@@ -234,6 +234,25 @@ class Enterprise extends Controller
return $this->renderSuccess("同步完成:新增 {$added} 家,更新 {$updated} 家");
}
/**
* 7.11 企业账户余额(仅平安银行通道;银行侧实时查询,勿高频调用)
*/
public function balance(int $enterpriseId): Json
{
$model = EnterpriseModel::detail($enterpriseId);
if (!$model) {
return $this->renderError('企业不存在');
}
$res = QytOil::forEnterprise($model)->distributable();
if ($res['code'] !== '00') {
return $this->renderError('企油通返回:' . ($res['message'] ?: '查询失败'));
}
return $this->renderSuccess([
'balance' => QytOil::fenToYuan($res['data']['balance'] ?? 0),
'available_balance' => QytOil::fenToYuan($res['data']['available_balance'] ?? 0),
], '查询成功');
}
/** 记录同步结果 */
private function saveSync($model, string $text): void
{
@@ -0,0 +1,71 @@
<?php
// +----------------------------------------------------------------------
// | 后台 · 企油通发票管理(7.14)
// +----------------------------------------------------------------------
// | list() 发票记录(按 企业 + 通道 + 月份 + 司机手机号 维度)
// | sync() 同步:指定企业则同步该企业(可带司机手机号);不指定则批量同步所有启用企业的当月全量
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\store\controller\qyt;
use app\common\model\qyt\Enterprise as EnterpriseModel;
use app\common\service\QytInvoice;
use app\store\controller\Controller;
use think\facade\Db;
use think\response\Json;
class Invoice extends Controller
{
public function list(): Json
{
$param = $this->request->param();
$query = Db::name('qyt_invoice');
!empty($param['qyt_enterprise_id']) && $query->where('qyt_enterprise_id', (int) $param['qyt_enterprise_id']);
!empty($param['month']) && $query->where('month', (string) $param['month']);
!empty($param['mobile']) && $query->where('mobile', trim((string) $param['mobile']));
if (isset($param['has_invoice']) && $param['has_invoice'] !== '' && (int) $param['has_invoice'] >= 0) {
(int) $param['has_invoice'] === 1 ? $query->where('invoice_count', '>', 0) : $query->where('invoice_count', 0);
}
$list = $query->order(['month' => 'desc', 'invoice_id' => 'desc'])->paginate(15)->toArray();
$names = EnterpriseModel::column('company_name', 'enterprise_id');
foreach ($list['data'] as &$row) {
$row = QytInvoice::format($row);
$row['company_name'] = $names[$row['qyt_enterprise_id']] ?? '(企业已删除)';
}
return $this->renderSuccess(compact('list'));
}
public function sync(): Json
{
$month = trim((string) $this->request->param('month'));
$mobile = trim((string) $this->request->param('mobile', ''));
$enterpriseId = (int) $this->request->param('enterpriseId', 0);
if ($enterpriseId > 0) {
$enterprise = EnterpriseModel::detail($enterpriseId);
if (!$enterprise) {
return $this->renderError('企业不存在');
}
$res = QytInvoice::sync($enterprise, $month, $mobile);
return $res['ok'] ? $this->renderSuccess($res['row'], $res['message']) : $this->renderError($res['message']);
}
// 批量:所有启用企业的该月全量
$ok = $fail = 0;
$errors = [];
foreach (EnterpriseModel::where('is_enable', 1)->select() as $enterprise) {
$res = QytInvoice::sync($enterprise, $month, '');
if ($res['ok']) {
$ok++;
} else {
$fail++;
$errors[] = $enterprise['company_name'] . ':' . $res['message'];
}
}
$message = "批量同步完成:成功 {$ok} 家,失败 {$fail} 家" . ($errors ? '(' . implode(';', array_slice($errors, 0, 3)) . ')' : '');
return $fail && !$ok ? $this->renderError($message) : $this->renderSuccess([], $message);
}
}
@@ -79,6 +79,8 @@ class Order extends OrderModel
'oil_status' => -1, // 分油(发放)状态
'oil_status_zsy' => -1, // 企油通发放态 0未提交 1发放中 2成功 3失败
'use_status' => -1, // 加油核销状态
'refund_status' => -1, // 退款状态 0未退款 1退款中 2已退款 3退款失败 4待人工确认
'id_card' => '', // 司机身份证号(从司机管理跳转过来时使用)
'betweenTime' => [] // 起止时间
]);
// 检索查询条件
@@ -100,6 +102,10 @@ class Order extends OrderModel
$params['oil_status_zsy'] > -1 && $filter[] = ['oil_status_zsy', '=', (int)$params['oil_status_zsy']];
// 加油核销状态
$params['use_status'] > -1 && $filter[] = ['use_status', '=', (int)$params['use_status']];
// 退款状态
$params['refund_status'] > -1 && $filter[] = ['order.refund_status', '=', (int)$params['refund_status']];
// 司机身份证号(精确匹配)
!empty($params['id_card']) && $filter[] = ['order.id_card', '=', strtoupper(trim((string)$params['id_card']))];
// 起止时间
if (!empty($params['betweenTime'])) {
$times = between_time($params['betweenTime']);