<?php
namespace app\api\controller;
use think\exception\ValidateException;
use app\api\model\SignIn as SignInModel;
use utils\Locker;
use think\facade\Db;
class SignIn extends Common{
/**
*@description 签到
*@buildcode(true)
*/
public function addSignIn(){
$postField = 'user_id,username,mobile';
$data = $this->request->only(explode(',',$postField),'post');
$this->validate($data,\app\api\validate\Signin::class);
//分布式锁key 格式如 signIn:1:2025-07-01
$key = sprintf('signIn:%d:%s',$data['user_id'],date('Y-m-d'));
//计算到今日24:00的剩余秒数作为TTL
$midnight = strtotime('tomorrow midnight');
$ttl = $midnight - time();
$locker = new Locker($key,$ttl);
if(!$locker->lock()){
throw new ValidateException("你今日已经签到!");
}
try{
$res = SignInModel::insertGetId($data);
}catch(\Exception $e){
$locker->unLock(); //异常释放锁
throw new ValidateException($e->getMessage());
}
return json(['status'=>200,'msg'=>'签到成功']);
}
}