88 lines
2.7 KiB
PHP
88 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace app\controller\api;
|
|
|
|
use support\Request;
|
|
use app\model\UserPhoneDayLog;
|
|
use app\model\UserPhoneLog;
|
|
use App\Utils\ApiResponseApp;
|
|
use Carbon\Carbon;
|
|
use support\Db;
|
|
use support\Log;
|
|
use Exception;
|
|
use hg\apidoc\annotation as Apidoc;
|
|
|
|
/**
|
|
* @Apidoc\Title("自用测试")
|
|
*/
|
|
class TextController
|
|
{
|
|
protected $noNeedLogin = ['classifyPhoneOnlineHistory', 'get_projectdetailed', 'get_mechanism_list'];
|
|
|
|
/**
|
|
* @Apidoc\Title("1.0 手机号在线历史归类函数")
|
|
* @Apidoc\Url("api/text/classifyPhoneOnlineHistory")
|
|
* @Apidoc\Method("POST")
|
|
*/
|
|
public function classifyPhoneOnlineHistory(Request $request)
|
|
{
|
|
// 计算三天前的日期
|
|
$threeDaysAgo = Carbon::now()->subDays(3)->startOfDay();
|
|
|
|
// 查询三天前的日期列表
|
|
$dates = Db::table('user_phone_log')
|
|
->selectRaw('DATE(created_at) AS date')
|
|
->where('created_at', '<', $threeDaysAgo)
|
|
->groupByRaw('DATE(created_at)')
|
|
->orderBy('date')
|
|
->get();
|
|
|
|
// 遍历每个日期
|
|
foreach ($dates as $v) {
|
|
$date = $v->date;
|
|
|
|
// 使用 Carbon 获取当天的开始和结束时间
|
|
$startOfDay = Carbon::parse($date)->startOfDay();
|
|
$endOfDay = Carbon::parse($date)->endOfDay();
|
|
|
|
// 查询当天的日志记录,并按手机号汇总在线时间
|
|
$logs = UserPhoneLog::whereBetween('created_at', [$startOfDay, $endOfDay])
|
|
->selectRaw('phone, SUM(time) AS total_time')
|
|
->groupBy('phone')
|
|
->get();
|
|
|
|
// 准备批量插入的数据
|
|
$batchData = [];
|
|
foreach ($logs as $log) {
|
|
$batchData[] = [
|
|
'phone' => $log->phone,
|
|
'created_at' => $startOfDay,
|
|
'updated_at' => $startOfDay,
|
|
'time' => $log->total_time,
|
|
];
|
|
}
|
|
|
|
// 开始数据库事务
|
|
Db::beginTransaction();
|
|
try {
|
|
// 批量插入数据到 user_phone_day_log 表
|
|
if (!empty($batchData)) {
|
|
UserPhoneDayLog::insert($batchData);
|
|
}
|
|
|
|
// 删除已处理的日志记录
|
|
UserPhoneLog::whereBetween('created_at', [$startOfDay, $endOfDay])->delete();
|
|
|
|
// 提交事务
|
|
Db::commit();
|
|
} catch (Exception $e) {
|
|
// 发生异常,回滚事务
|
|
Db::rollBack();
|
|
// 记录错误日志
|
|
Log::error("Error processing date {$date}: " . $e->getMessage());
|
|
}
|
|
}
|
|
return ApiResponseApp::success([]);
|
|
}
|
|
}
|