123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace app\common\command;
- use app\common\model\FlowLogs;
- use app\common\model\User;
- use app\common\model\UserTraffic;
- use think\console\Command;
- use think\console\Input;
- use think\console\Output;
- use think\Db;
- use think\Exception;
- class SettlementTraffic extends Command
- {
- protected function configure()
- {
- $this->setName('settlement')->setDescription('后台统计用户流量使用, 并扣除相关流量');
- }
-
- protected function execute(Input $input, Output $output)
- {
- $dateTime = time() - 5;
-
- $data = FlowLogs::where('created_at', '<=', $dateTime)
- ->field('username, sum(bytes) as bytes')
- ->group('username')
- ->select()->toArray();
-
- $userNames = array_column($data, 'username');
- $users = collection(User::whereIn('username', $userNames)->field('id, username')->select())->toArray();
- $userNameMapId = array_column($users, 'id', 'username');
- Db::startTrans();
- try {
- foreach ($data as $datum) {
- if (!$this->usedTraffic($userNameMapId[$datum['username']], $datum['bytes'], $dateTime)) {
- throw new Exception('统计用户使用流量失败');
- }
- }
-
- FlowLogs::where('created_at', '<=', $dateTime)->delete();
-
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- }
- }
-
- protected function usedTraffic($uid, $bytes, $dateTime)
- {
- $usable = UserTraffic::where('uid', $uid)
- ->where('is_usable', '1')
- ->where('start_time', '<', $dateTime)
- ->where('expired_time', '>', $dateTime)
- ->order('expired_time', 'ASC')
- ->select();
- if (empty($usable)) {
- return true;
- }
- foreach ($usable as $item) {
- if ($bytes == 0) break;
- if ($item->traffic > bcadd($item->used, $bytes)) {
- $item->setInc('used', $bytes);
- } else {
- $bytes = bcsub($bytes, bcsub($item->traffic, $item->used));
- $item->used = $item->traffic;
- $item->is_usable = 0;
- $item->save();
- }
- }
- return true;
- }
- }
|