优化代码

This commit is contained in:
Anyon 2022-06-16 19:05:34 +08:00
parent ab8ee66ff4
commit 526c13e8ac
21 changed files with 68 additions and 78 deletions

View File

@ -50,7 +50,7 @@ class OrderClean extends Command
$result->map(function (Model $item) use ($total, &$count) {
$this->queue->message($total, ++$count, "开始取消未支付的订单 {$item['order_no']}");
$item->save(['status' => 0, 'cancel_status' => 1, 'cancel_datetime' => date('Y-m-d H:i:s'), 'cancel_remark' => '自动取消30分钟未完成支付']);
OrderService::instance()->stock($item['order_no']);
OrderService::stock($item['order_no']);
$this->queue->message($total, $count, "完成取消未支付的订单 {$item['order_no']}", 1);
});
} catch (\Exception $exception) {

View File

@ -34,8 +34,7 @@ class UserAmount extends Command
[$total, $count, $error] = [DataUser::mk()->count(), 0, 0];
foreach (DataUser::mk()->field('id')->cursor() as $user) try {
$this->queue->message($total, ++$count, "刷新用户 [{$user['id']}] 余额及返利开始");
UserRebateService::instance()->amount($user['id']);
UserBalanceService::instance()->amount($user['id']);
UserRebateService::amount($user['id']) && UserBalanceService::amount($user['id']);
$this->queue->message($total, $count, "刷新用户 [{$user['id']}] 余额及返利完成", 1);
} catch (\Exception $exception) {
$error++;

View File

@ -228,7 +228,7 @@ class UserTransfer extends Command
'change_desc' => '微信提现打款失败',
]);
// 刷新用户可提现余额
UserRebateService::instance()->amount($item['uuid']);
UserRebateService::amount($item['uuid']);
}
}
}

View File

@ -49,7 +49,7 @@ class Goods extends Controller
// 商品数据处理
$query = ShopGoods::mQuery()->like('name,marks,cateids,payment')->equal('code,vip_entry');
$result = $query->where(['deleted' => 0, 'status' => 1])->order('sort desc,id desc')->page(true, false, false, 10);
if (count($result['list']) > 0) GoodsService::instance()->bindData($result['list']);
if (count($result['list']) > 0) GoodsService::bindData($result['list']);
$this->success('获取商品数据', $result);
}

View File

@ -57,7 +57,7 @@ class Address extends Auth
$map = [['uuid', '=', $this->uuid], ['code', '<>', $data['code']]];
DataUserAddress::mk()->where($map)->update(['type' => 0]);
}
$this->success('地址保存成功!', $this->_getAddress($data['code']));
$this->success('地址保存成功!', $this->getAddress($data['code']));
}
/**
@ -98,14 +98,11 @@ class Address extends Auth
$map = [['uuid', '=', $this->uuid], ['code', '<>', $data['code']]];
DataUserAddress::mk()->where($map)->update(['type' => 0]);
}
$this->success('默认设置成功!', $this->_getAddress($data['code']));
$this->success('默认设置成功!', $this->getAddress($data['code']));
}
/**
* 删除收货地址
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function remove()
{
@ -113,9 +110,9 @@ class Address extends Auth
'uuid.value' => $this->uuid,
'code.require' => '地址不能为空!',
]);
$data = DataUserAddress::mk()->where($map)->find();
if (empty($data)) $this->error('需要删除的地址不存在!');
if ($data->save(['deleted' => 1]) !== false) {
$item = DataUserAddress::mk()->where($map)->findOrEmpty();
if ($item->isEmpty()) $this->error('需要删除的地址不存在!');
if ($item->save(['deleted' => 1]) !== false) {
$this->success('删除地址成功!');
} else {
$this->error('删除地址失败!');
@ -127,7 +124,7 @@ class Address extends Auth
* @param string $code
* @return null|array
*/
private function _getAddress(string $code): array
private function getAddress(string $code): array
{
$map = ['code' => $code, 'uuid' => $this->uuid, 'deleted' => 0];
return DataUserAddress::mk()->withoutField('deleted')->where($map)->findOrEmpty()->toArray();

View File

@ -179,7 +179,7 @@ class Order extends Auth
});
// 同步商品库存销量
foreach (array_unique(array_column($items, 'goods_code')) as $code) {
GoodsService::instance()->stock($code);
GoodsService::stock($code);
}
// 触发订单创建事件
$this->app->event->trigger('ShopOrderCreate', $order['order_no']);
@ -382,7 +382,7 @@ class Order extends Auth
'cancel_remark' => '用户主动取消订单',
'cancel_datetime' => date('Y-m-d H:i:s'),
]);
if ($result !== false && OrderService::instance()->stock($order['order_no'])) {
if ($result !== false && OrderService::stock($order['order_no'])) {
// 触发订单取消事件
$this->app->event->trigger('ShopOrderCancel', $order['order_no']);
// 返回处理成功数据

View File

@ -54,7 +54,7 @@ class Transfer extends Auth
$data['charge_rate'] = $chargeRate;
$data['charge_amount'] = $chargeRate * $data['amount'] / 100;
// 检查可提现余额
[$total, $count] = UserRebateService::instance()->amount($this->uuid);
[$total, $count] = UserRebateService::amount($this->uuid);
if ($total - $count < $data['amount']) $this->error('可提现余额不足!');
// 提现方式处理
if ($data['type'] == 'alipay_account') {
@ -90,7 +90,7 @@ class Transfer extends Auth
}
// 写入用户提现数据
if (DataUserTransfer::mk()->insert($data) !== false) {
UserRebateService::instance()->amount($this->uuid);
UserRebateService::amount($this->uuid);
$this->success('提现申请成功');
} else {
$this->error('提现申请失败');
@ -109,7 +109,7 @@ class Transfer extends Auth
$result = $query->like('date,code')->in('status')->order('id desc')->page(true, false, false, 10);
// 统计历史数据
$map = [['uuid', '=', $this->uuid], ['status', '>', 0]];
[$total, $count, $locks] = UserRebateService::instance()->amount($this->uuid);
[$total, $count, $locks] = UserRebateService::amount($this->uuid);
$this->success('获取提现成功', array_merge($result, [
'total' => [
'锁定' => $locks,

View File

@ -72,7 +72,7 @@ class Goods extends Controller
{
$this->marks = ShopGoodsMark::items();
$this->cates = ShopGoodsCate::treeTable();
GoodsService::instance()->bindData($data, false);
GoodsService::bindData($data, false);
}
/**
@ -188,7 +188,7 @@ class Goods extends Controller
protected function _form_result(bool $result)
{
if ($result && $this->request->isPost()) {
GoodsService::instance()->stock(input('code'));
GoodsService::stock(input('code'));
$this->success('商品编辑成功!', 'javascript:history.back()');
}
}
@ -206,7 +206,7 @@ class Goods extends Controller
if ($this->request->isGet()) {
$list = ShopGoods::mk()->where($map)->select()->toArray();
if (empty($list)) $this->error('无效的商品数据,请稍候再试!');
[$this->vo] = GoodsService::instance()->bindData($list);
[$this->vo] = GoodsService::bindData($list);
$this->fetch();
} else {
[$data, $post, $batch] = [[], $this->request->post(), CodeExtend::uniqidDate(12, 'B')];
@ -221,7 +221,7 @@ class Goods extends Controller
}
if (!empty($data)) {
ShopGoodsStock::mk()->insertAll($data);
GoodsService::instance()->stock($map['code']);
GoodsService::stock($map['code']);
$this->success('商品数据入库成功!');
}
}

View File

@ -86,9 +86,9 @@ class Order extends Controller
*/
protected function _index_page_filter(array &$data)
{
UserAdminService::instance()->buildByUid($data);
UserAdminService::instance()->buildByUid($data, 'puid1', 'from');
OrderService::instance()->buildData($data);
UserAdminService::buildByUid($data);
UserAdminService::buildByUid($data, 'puid1', 'from');
OrderService::buildData($data);
foreach ($data as &$vo) {
if (!is_null($vo['payment_type']) and '' != $vo['payment_type']) {
$vo['payment_name'] = PaymentService::name($vo['payment_type']);
@ -138,7 +138,7 @@ class Order extends Controller
$this->success('订单审核通过成功!');
} else {
$this->app->event->trigger('ShopOrderCancel');
OrderService::instance()->stock($data['order_no']);
OrderService::stock($data['order_no']);
$this->success('审核驳回并取消成功!');
}
} else {
@ -177,7 +177,7 @@ class Order extends Controller
'cancel_datetime' => date('Y-m-d H:i:s'),
]);
if ($result !== false) {
OrderService::instance()->stock($order['order_no']);
OrderService::stock($order['order_no']);
$this->app->event->trigger('ShopOrderCancel', $order['order_no']);
$this->success('取消未支付的订单成功!');
} else {

View File

@ -64,7 +64,7 @@ class Admin extends Controller
protected function _page_filter(array &$data)
{
$this->upgrades = BaseUserUpgrade::items();
UserAdminService::instance()->buildByUid($data, 'pid1', 'from');
UserAdminService::buildByUid($data, 'pid1', 'from');
}
/**
@ -120,8 +120,8 @@ class Admin extends Controller
public function unbind()
{
$map = $this->_vali(['id.require' => '用户ID不能为空']);
$user = DataUser::mk()->where($map)->find();
if (empty($user)) $this->error('用户不符合操作要求!');
$user = DataUser::mk()->where($map)->findOrEmpty();
if ($user->isEmpty()) $this->error('用户不符合操作要求!');
// 修改指定用户代理数据
$user->save(['pid0' => 0, 'pid1' => 0, 'pid2' => 0, 'pids' => 1, 'path' => '-', 'layer' => 1]);
// 刷新用户等级及上级等级

View File

@ -32,7 +32,7 @@ class Balance extends Controller
{
$this->title = '余额充值记录';
// 统计用户余额
$this->balance = UserBalanceService::instance()->amount(0);
$this->balance = UserBalanceService::amount(0);
// 现有余额类型
$this->names = DataUserBalance::mk()->group('name')->column('name');
// 创建查询对象
@ -50,7 +50,7 @@ class Balance extends Controller
*/
protected function _index_page_filter(array &$data)
{
UserAdminService::instance()->buildByUid($data);
UserAdminService::buildByUid($data);
$uids = array_unique(array_column($data, 'create_by'));
$users = SystemUser::mk()->whereIn('id', $uids)->column('username', 'id');
$this->upgrades = BaseUserUpgrade::items();
@ -104,7 +104,7 @@ class Balance extends Controller
protected function _form_result(bool $state, array $data)
{
if ($state && isset($data['uuid'])) {
UserBalanceService::instance()->amount($data['uuid']);
UserBalanceService::amount($data['uuid']);
UserUpgradeService::instance()->upgrade($data['uuid']);
}
}
@ -128,7 +128,7 @@ class Balance extends Controller
if ($state) {
$map = [['id', 'in', str2arr(input('id', ''))]];
foreach (DataUserBalance::mk()->where($map)->cursor() as $vo) {
UserBalanceService::instance()->amount($vo['uuid']);
UserBalanceService::amount($vo['uuid']);
UserUpgradeService::instance()->upgrade($vo['uuid']);
}
}

View File

@ -8,7 +8,6 @@ use app\data\model\DataUserRebate;
use app\data\model\ShopOrderItem;
use app\data\service\RebateService;
use app\data\service\UserRebateService;
use app\data\service\UserUpgradeService;
use think\admin\Controller;
/**
@ -31,7 +30,7 @@ class Rebate extends Controller
$this->title = '用户返利管理';
// 统计所有返利
$this->types = RebateService::PRIZES;
$this->rebate = UserRebateService::instance()->amount(0);
$this->rebate = UserRebateService::amount(0);
// 创建查询对象
$query = DataUserRebate::mQuery()->equal('type')->like('name,order_no');
// 会员条件查询

View File

@ -99,7 +99,7 @@ class Transfer extends Controller
*/
protected function _page_filter(array &$data)
{
UserAdminService::instance()->buildByUid($data);
UserAdminService::buildByUid($data);
foreach ($data as &$vo) {
$vo['type_name'] = UserTransferService::instance()->types($vo['type']);
}
@ -175,5 +175,4 @@ class Transfer extends Controller
{
$this->_queue('提现到微信余额定时处理', 'xdata:UserTransfer', 0, [], 0, 50);
}
}

View File

@ -22,16 +22,13 @@ class ExpressService extends Service
* @param string $cityName 城市名称
* @param integer $truckCount 邮费基数
* @return array [邮费金额, 计费基数, 模板编号, 计费描述]
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public static function amount(array $codes, string $provName, string $cityName, int $truckCount = 0): array
{
if (empty($codes)) return [0, $truckCount, '', '邮费模板编码为空!'];
$map = [['status', '=', 1], ['deleted', '=', 0], ['code', 'in', $codes]];
$template = BasePostageTemplate::mk()->where($map)->order('sort desc,id desc')->find();
if (empty($template)) return [0, $truckCount, '', '邮费模板编码无效!'];
$template = BasePostageTemplate::mk()->where($map)->order('sort desc,id desc')->findOrEmpty();
if ($template->isEmpty()) return [0, $truckCount, '', '邮费模板编码无效!'];
$rule = json_decode($template['normal'] ?: '[]', true) ?: [];
foreach (json_decode($template['content'] ?: '[]', true) ?: [] as $item) {
if (isset($item['city']) && is_array($item['city'])) foreach ($item['city'] as $city) {

View File

@ -19,7 +19,7 @@ class NewsService extends Service
* @param string $code 文章编号
* @param array $total 查询统计
*/
public function syncNewsTotal(string $code, array $total = []): void
public static function syncNewsTotal(string $code, array $total = []): void
{
$query = DataNewsXCollect::mk()->field('type,count(1) count');
foreach ($query->where(['code' => $code, 'status' => 2])->group('type')->cursor() as $item) {
@ -35,19 +35,18 @@ class NewsService extends Service
* @param array $list 数据列表
* @return array
*/
public function buildListByUidAndCode(array &$list = []): array
public static function buildListByUidAndCode(array &$list = []): array
{
if (count($list) > 0) {
/*! 绑定文章内容 */
$codes = array_unique(array_column($list, 'code'));
$colls = 'id,code,name,cover,mark,status,deleted,create_at,num_like,num_read,num_comment,num_collect';
$items = DataNewsItem::mk()->whereIn('code', $codes)->column($colls, 'code');
$items = DataNewsItem::mk()->whereIn('code', array_unique(array_column($list, 'code')))->column($colls, 'code');
$marks = DataNewsMark::mk()->where(['status' => 1])->column('name');
foreach ($items as &$vo) $vo['mark'] = str2arr($vo['mark'] ?: '', ',', $marks);
foreach ($list as &$vo) $vo['record'] = $items[$vo['code']] ?? [];
/*! 绑定用户数据 */
$colls = 'id,phone,nickname,username,headimg,status';
UserAdminService::instance()->buildByUid($list, 'uuid', 'user', $colls);
UserAdminService::buildByUid($list, 'uuid', 'user', $colls);
}
return $list;
}

View File

@ -37,7 +37,7 @@ class OrderService extends Service
{
$map = ['order_no' => $orderNo];
$codes = ShopOrderItem::mk()->where($map)->column('goods_code');
foreach (array_unique($codes) as $code) GoodsService::instance()->stock($code);
foreach (array_unique($codes) as $code) GoodsService::stock($code);
return true;
}
@ -136,8 +136,8 @@ class OrderService extends Service
$items = $query->withoutField('id,uuid,status,deleted,create_at')->whereIn('order_no', $nobs)->select()->toArray();
// 关联用户数据
$fields = 'phone,username,nickname,headimg,status,vip_code,vip_name';
UserAdminService::instance()->buildByUid($data, 'uuid', 'user', $fields);
if ($from) UserAdminService::instance()->buildByUid($data, 'puid1', 'from', $fields);
UserAdminService::buildByUid($data, 'uuid', 'user', $fields);
if ($from) UserAdminService::buildByUid($data, 'puid1', 'from', $fields);
foreach ($data as &$vo) {
[$vo['sales'], $vo['truck'], $vo['items']] = [0, $trucks[$vo['order_no']] ?? [], []];
foreach ($items as $it) if ($vo['order_no'] === $it['order_no']) {

View File

@ -76,15 +76,15 @@ class RebateService extends Service
{
// 获取订单数据
$map = ['order_no' => $orderNo, 'payment_status' => 1];
$this->order = ShopOrder::mk()->where($map)->find();
if (empty($this->order)) throw new Exception('订单不存在');
$this->order = ShopOrder::mk()->where($map)->findOrEmpty();
if ($this->order->isEmpty()) throw new Exception('订单不存在');
if ($this->order['payment_type'] === 'balance') return;
if ($this->order['amount_total'] <= 0) throw new Exception('订单金额为零');
if ($this->order['rebate_amount'] <= 0) throw new Exception('订单返利为零');
// 获取用户数据
$map = ['id' => $this->order['uuid'], 'deleted' => 0];
$this->user = DataUser::mk()->where($map)->find();
if (empty($this->user)) throw new Exception('用户不存在');
$this->user = DataUser::mk()->where($map)->findOrEmpty();
if ($this->user->isEmpty()) throw new Exception('用户不存在');
// 获取直接代理数据
if ($this->order['puid1'] > 0) {
$this->from1 = DataUser::mk()->find($this->order['puid1']);
@ -455,6 +455,6 @@ class RebateService extends Service
'order_amount' => $this->order['amount_total'],
]));
// 刷新用户返利统计
UserRebateService::instance()->amount($uuid);
UserRebateService::amount($uuid);
}
}

View File

@ -25,7 +25,7 @@ class UserBalanceService extends Service
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function confirm(string $orderNo): array
public static function confirm(string $orderNo): array
{
$order = ShopOrder::mk()->where([['status', '>=', 4], ['order_no', '=', $orderNo]])->find();
if (empty($order)) throw new Exception('需处理的订单状态异常');
@ -38,7 +38,7 @@ class UserBalanceService extends Service
'amount' => $order['reward_balance'],
], 'code');
return $this->amount($order['uuid']);
return static::amount($order['uuid']);
}
/**
@ -47,7 +47,7 @@ class UserBalanceService extends Service
* @param array $nots 排除的订单
* @return array [total, count]
*/
public function amount(int $uuid, array $nots = []): array
public static function amount(int $uuid, array $nots = []): array
{
if ($uuid > 0) {
$total = abs(DataUserBalance::mk()->whereRaw("uuid='{$uuid}' and amount>0 and deleted=0")->sum('amount'));

View File

@ -93,12 +93,22 @@ class UserTransferService extends Service
return $wsea;
}
/**
* 获取转账类型
* @param string|null $name
* @return array|string
*/
public function types(?string $name = null)
{
return is_null($name) ? $this->types : ($this->types[$name] ?? $name);
}
/**
* 同步刷新用户返利
* @param integer $uuid
* @return array [total, count, audit, locks]
*/
public function amount(int $uuid): array
public static function amount(int $uuid): array
{
if ($uuid > 0) {
$locks = abs(DataUserTransfer::mk()->whereRaw("uuid='{$uuid}' and status=3")->sum('amount'));
@ -114,16 +124,6 @@ class UserTransferService extends Service
return [$total, $count, $audit, $locks];
}
/**
* 获取转账类型
* @param string|null $name
* @return array|string
*/
public function types(?string $name = null)
{
return is_null($name) ? $this->types : ($this->types[$name] ?? $name);
}
/**
* 获取提现配置
* @param ?string $name
@ -147,7 +147,7 @@ class UserTransferService extends Service
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function payment(?string $name = null)
public static function payment(?string $name = null)
{
static $data = [];
if (empty($data)) $data = sysdata('TransferWxpay');

View File

@ -58,7 +58,7 @@ class BalancePyamentService extends PaymentService
// 创建支付行为
$this->createPaymentAction($orderNo, $payTitle, $payAmount);
// 检查能否支付
[$total, $count] = UserBalanceService::instance()->amount($order['uuid'], [$orderNo]);
[$total, $count] = UserBalanceService::amount($order['uuid'], [$orderNo]);
if ($payAmount > $total - $count) throw new Exception("可抵扣余额不足");
try {
// 扣减用户余额
@ -68,7 +68,7 @@ class BalancePyamentService extends PaymentService
'payment_balance' => $payAmount,
]);
// 扣除余额金额
data_save(DataUserBalance::mk(), [
DataUserBalance::mUpdate([
'uuid' => $order['uuid'],
'code' => "KC{$order['order_no']}",
'name' => "账户余额支付",
@ -79,7 +79,7 @@ class BalancePyamentService extends PaymentService
$this->updatePaymentAction($order['order_no'], CodeExtend::uniqidDate(20), $payAmount, '账户余额支付');
});
// 刷新用户余额
UserBalanceService::instance()->amount($order['uuid']);
UserBalanceService::amount($order['uuid']);
return ['code' => 1, 'info' => '余额支付完成'];
} catch (\Exception $exception) {
return ['code' => 0, 'info' => $exception->getMessage()];

View File

@ -30,16 +30,16 @@ if ($app->request->isCli()) {
RebateService::instance()->execute($orderNo);
$app->log->notice("订单 {$orderNo} 支付事件,执行发放余额行为");
UserBalanceService::instance()->confirm($orderNo);
UserBalanceService::confirm($orderNo);
$app->log->notice("订单 {$orderNo} 支付事件,执行用户升级行为");
OrderService::instance()->upgrade($orderNo);
OrderService::upgrade($orderNo);
});
// 注册订单确认支付事件
$app->event->listen('ShopOrderConfirm', function ($orderNo) use ($app) {
$app->log->notice("订单 {$orderNo} 确认事件,执行返利确认行为");
UserRebateService::instance()->confirm($orderNo);
UserRebateService::confirm($orderNo);
});
}