Compare commits

...

6 Commits

Author SHA1 Message Date
aa40614965 wallet_fix 2024-03-08 01:14:04 +08:00
b14c000bc3 wallet 2024-03-08 00:58:23 +08:00
bebbee4184 更换model目录 2024-03-04 04:28:48 +08:00
f4f61a5f4c fix some problems 2024-03-03 10:15:50 +08:00
1c555934d1 chagne composer 2024-03-03 09:39:48 +08:00
66d88ea2b3 推拉函数与queue 2024-03-03 09:39:06 +08:00
57 changed files with 2675 additions and 587 deletions

View File

@ -2,8 +2,6 @@
namespace App\Cache\Base; namespace App\Cache\Base;
use App\Models\Follow\FollowModel;
//用户缓存用户基础信息等于数据表primary_key为主键 //用户缓存用户基础信息等于数据表primary_key为主键
abstract class TableBaseCache extends BaseCache abstract class TableBaseCache extends BaseCache
{ {

View File

@ -0,0 +1,30 @@
<?php
namespace App\Cache\Lock;
use Illuminate\Support\Facades\Redis;
class BaseLock
{
const TTL = 120;
function setLockNxEx($key, $value)
{
return Redis::client()->set($key, $value, 'EX', self::TTL, 'NX');
}
function setLock($key, $value = '1')
{
return Redis::client()->setex($key, self::TTL , $value);
}
function unLock($key)
{
return Redis::client()->del($key);
}
function checkLock($key)
{
return Redis::client()->get($key);
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Cache\Lock;
class WalletPlatformUserTransactionLock extends BaseLock
{
const WITHDRAW_LOCK_KEY = 'wallet_platform_user_transaction_withdraw_lock:';
public static function getWithdrawKey($id): string
{
return self::WITHDRAW_LOCK_KEY . $id;
}
}

View File

@ -2,7 +2,7 @@
namespace App\Cache\Struct; namespace App\Cache\Struct;
use App\Cache\Base\StructBaseCache; use App\Cache\Base\StructBaseCache;
use App\Models\Customer\CustomerUserExtendModel; use App\Models\Api\Customer\CustomerUserExtendModel;
//用户缓存用户基础信息结构自己组装不完全等于数据表primary_key为主键 //用户缓存用户基础信息结构自己组装不完全等于数据表primary_key为主键
class StructUserCommonCacheUid extends StructBaseCache class StructUserCommonCacheUid extends StructBaseCache

View File

@ -2,7 +2,7 @@
namespace App\Cache\Table; namespace App\Cache\Table;
use App\Cache\Base\TableBaseCache; use App\Cache\Base\TableBaseCache;
use App\Models\Customer\CustomerUserModel; use App\Models\Api\Customer\CustomerUserModel;
//用户缓存用户基础信息结构自己组装不完全等于数据表uid为主键 //用户缓存用户基础信息结构自己组装不完全等于数据表uid为主键
class TableCustomerUserCache extends TableBaseCache class TableCustomerUserCache extends TableBaseCache

View File

@ -2,7 +2,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Customer\CustomerUserExtendModel; use App\Models\Api\Customer\CustomerUserExtendModel;
use Illuminate\Console\Command; use Illuminate\Console\Command;
class DailyCheckUserActiveStatus extends Command class DailyCheckUserActiveStatus extends Command
@ -29,7 +29,7 @@ class DailyCheckUserActiveStatus extends Command
$this->info('每日更新用户活跃状态'); $this->info('每日更新用户活跃状态');
$this->info('开始...'); $this->info('开始...');
$oCustomerUserExtendModelExtend = new CustomerUserExtendModel(); $oCustomerUserExtendModelExtend = new CustomerUserExtendModel();
$oCustomerUserExtendModelExtend->updateUserActiveStatus(); $oCustomerUserExtendModelExtend->updateAllUserActiveStatus();
$this->info('结束...'); $this->info('结束...');
} }
} }

View File

@ -5,4 +5,11 @@ namespace App\Exceptions;
class ModelException extends \Exception class ModelException extends \Exception
{ {
const CODE_WALLET_AMOUNT_ADDR_NOT_FOUND = 10101;
const CODE_WALLET_ADDR_BALANCE_LOW = 10102;
const CODE = [
self::CODE_WALLET_AMOUNT_ADDR_NOT_FOUND => '钱包金额地址不存在',
self::CODE_WALLET_ADDR_BALANCE_LOW => '钱包余额不足',
];
} }

View File

@ -6,7 +6,7 @@ use App\Const\Im;
use App\Const\VrCode; use App\Const\VrCode;
use App\Exceptions\AppException; use App\Exceptions\AppException;
use App\Http\Controllers\Base\CustomerBaseController; use App\Http\Controllers\Base\CustomerBaseController;
use App\Models\Customer\CustomerUserModel; use App\Models\Api\Customer\CustomerUserModel;
use App\Service\AuthService; use App\Service\AuthService;
use App\Service\ImService; use App\Service\ImService;
use App\Service\VrCodeService; use App\Service\VrCodeService;

View File

@ -5,8 +5,7 @@ namespace App\Http\Controllers\Follow;
use App\Exceptions\ModelException; use App\Exceptions\ModelException;
use App\Http\Controllers\Base\BaseController; use App\Http\Controllers\Base\BaseController;
use App\Models\Follow\FollowHistoryModel; use App\Models\Api\Follow\FollowModel;
use App\Models\Follow\FollowModel;
use App\Service\AuthService; use App\Service\AuthService;
use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface; use Psr\Container\NotFoundExceptionInterface;

View File

@ -4,8 +4,54 @@
namespace App\Http\Controllers\Post; namespace App\Http\Controllers\Post;
use App\Http\Controllers\Base\BaseController; use App\Http\Controllers\Base\BaseController;
use App\Service\AuthService;
class PostController extends BaseController class PostController extends BaseController
{ {
//$uid, $content = null, $media = null,$mid = null,$sBachSn = null
public array $validateMethodParams = [
'addPost' => [
'type' => 'required|numeric|max:2',
'content' => 'required|numeric|max:255',
'media' => 'json',
],
'pullPostList' => [
'lastId' => 'numeric|max:10',
'limit' => 'numeric|max:5',
],
];
public function addPost(): \Illuminate\Http\JsonResponse
{
$aParams = request()->only([
'type',
'content',
'media',
]);
if (!in_array($aParams['type'], [\App\Models\Api\Post\PostModel::TYPE_POST, \App\Models\Api\Post\PostModel::TYPE_REPOST])) return $this->error('type params error');
$oAuthService = new AuthService();
$aUser = $oAuthService->getCurrentUser();
$oFollowModel = new \App\Models\Api\Post\PostModel();
$aParams['uid'] = $aUser['id'];
$oFollowModel->addBatchPost([$aParams]);
return $this->success();
}
function pullPostList()
{
$aParams = request()->only([
'lastId',
'limit',
]);
$oAuthService = new AuthService();
$aUser = $oAuthService->getCurrentUser();
$oPostModel = new \App\Models\Api\Post\PostPushBoxModel();
$aPostList = $oPostModel->getPushBoxList($aUser['id'],$aParams['lastId']??0,$aParams['limit']??15);
return $this->success($aPostList);
}
} }

View File

@ -4,7 +4,7 @@ namespace App\Http\Controllers\Sms;
use App\Const\VrCode; use App\Const\VrCode;
use App\Exceptions\AppException; use App\Exceptions\AppException;
use App\Http\Controllers\Base\CustomerBaseController; use App\Http\Controllers\Base\CustomerBaseController;
use App\Models\Customer\CustomerUserModel; use App\Models\Api\Customer\CustomerUserModel;
use App\Service\AuthService; use App\Service\AuthService;
use App\Service\VrCodeService; use App\Service\VrCodeService;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;

View File

@ -3,11 +3,10 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use App\Const\Responses; use App\Const\Responses;
use App\Models\Customer\CustomerUserModel; use App\Models\Api\Customer\CustomerUserModel;
use App\Service\AuthService; use App\Service\AuthService;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
class AuthMiddleware class AuthMiddleware

34
app/Jobs/AddPostQueue.php Normal file
View File

@ -0,0 +1,34 @@
<?php
namespace App\Jobs;
use App\Exceptions\ModelException;
use App\Models\Api\Post\PostPushBoxModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class AddPostQueue implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct()
{
//处理用户的推文推送
}
/**
* Execute the job.
* @throws ModelException
*/
public function handle(array $params): void
{
$oPostPushBoxModel = new PostPushBoxModel();
$oPostPushBoxModel->addPostQueueConsumer($params);
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Jobs;
use App\Models\Api\Customer\CustomerUserExtendModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class UserActiveStatusQueue implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct()
{
//处理用户活跃状态改变后任务
}
/**
* Execute the job.
*/
public function handle(array $params): void
{
$oCustomerUserExtendModel = new CustomerUserExtendModel();
$oCustomerUserExtendModel->activeUserStatusQueueConsumer($params);
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace App\Jobs;
use App\Models\Wallet\PlatformUser\WalletPlatformUserTransactionModel;
use App\Models\Wallet\Wallet\WalletAddrModel;
use App\Models\Wallet\Wallet\WalletAddrTransactionModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class WalletAddrTransactionChangeQueue implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct()
{
//钱包账变队列,用于处理用户和平台账变
}
/**
* Execute the job.
*/
public function handle(array $params): void
{
$wallet_addr_transaction_id = $params['wallet_addr_transaction_id'];
$wallet_addr_transaction_type = $params['wallet_addr_transaction_type'];
$oWalletAddrModel = new WalletAddrModel();
$oWalletAddrModel->walletAddrTransactionChangeConsumer($wallet_addr_transaction_id, $wallet_addr_transaction_type);
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Jobs;
use App\Models\Wallet\PlatformUser\WalletPlatformUserTransactionModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class WalletPlatformUserWithdrawQueue implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct()
{
//处理平台用户提现
}
/**
* Execute the job.
*/
public function handle(array $params): void
{
$id = $params['wallet_platform_user_transaction_id'];
$oWalletPlatformUserTransactionModel = new WalletPlatformUserTransactionModel();
$oWalletPlatformUserTransactionModel->withdrawConsumer($id);
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace App\Models\Api\Base;
use App\Models\Base\BaseModel;
class ApiBaseModel extends BaseModel {
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Models\Api\Comment;
use App\Models\Api\Base\ApiBaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
class PostCommentModel extends ApiBaseModel
{
use SoftDeletes;
protected $table = 'customer_post_comment';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'pid',
'uid',
'content',
'created_at',
'deleted_at',
];
}

View File

@ -1,14 +1,11 @@
<?php <?php
namespace App\Models\Customer; namespace App\Models\Api\Customer;
use App\Cache\Table\TableCustomerUserCache; use App\Models\Api\Base\ApiBaseModel;
use App\Models\Base\CustomerBaseModel;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
class CustomerChangeInfoLogModel extends CustomerBaseModel class CustomerChangeInfoLogModel extends ApiBaseModel
{ {
protected $table = 'customer_change_info_log'; protected $table = 'customer_change_info_log';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
@ -47,4 +44,20 @@ class CustomerChangeInfoLogModel extends CustomerBaseModel
return $this->addItem($aItem); return $this->addItem($aItem);
} }
function addUserActiveStatusLog($uid,$beforeValue,$value,$remark_key): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
$aLogInsert = [
'type' => CustomerChangeInfoLogModel::TYPE_CHANG_USER_ACTIVE_STATUS,
'uid' => $uid,
'column' => CustomerUserExtendModel::COL_IS_ACTIVE,
'before_value' => $beforeValue,
'pid' => CustomerChangeInfoLogModel::PID_SYSTEM,
'value' => $value,
'after_value' => $value,
'remark_key' => $remark_key,
'remark_desc' => CustomerChangeInfoLogModel::REMARK[$remark_key],
];
return $this->addLog($aLogInsert);
}
} }

View File

@ -0,0 +1,19 @@
<?php
namespace App\Models\Api\Customer;
use App\Models\Api\Base\ApiBaseModel;
class CustomerLoginHistoryModel extends ApiBaseModel
{
protected $table = 'customer_login_history';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'status',
'uid',
'device',
'created_at',
];
}

View File

@ -0,0 +1,180 @@
<?php
namespace App\Models\Api\Customer;
use App\Exceptions\ModelException;
use App\Jobs\UserActiveStatusQueue;
use App\Models\Api\Post\PostPushBoxModel;
use App\Models\Api\WebSocket\CustomerWsHistoryModel;
use App\Models\Api\Base\ApiBaseModel;
use App\Structs\QueueUserActiveStatusStruct;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class CustomerUserExtendModel extends ApiBaseModel
{
protected $table = 'customer_user_extend';
protected $primaryKey = 'uid';
protected $fillable = [
'uid',
'is_active',
'fans_num',
'follow_num',
'updated_at',
];
const COL_IS_ACTIVE = 'is_active';
//是否活跃用户
const IS_ACTIVE_YES = 1;
const IS_ACTIVE_NO = 2;
const IS_ACTIVE = [
self::IS_ACTIVE_YES => '活跃',
self::IS_ACTIVE_NO => '不活跃',
];
//增加用户扩展信息
function addExtend($aItem): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
if (empty($aItem['uid'])) throw new ModelException('uid error');
if ($this->findItem($aItem['uid'], ['uid'])) return null; //已存在
$sDateTime = date('Y-m-d H:i:s');
$aItem['updated_at'] = $sDateTime;
return $this->addItem($aItem);
}
//增加当前粉丝总数
function incrFansNum($uid): int
{
$oExtend = $this->findItem($uid, 'uid');
if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid', $uid)->increment('fans_num');
}
//减去当前追随者总数
function decrFansNum($uid): int
{
$oExtend = $this->findItem($uid, 'uid');
if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid', $uid)->decrement('fans_num');
}
//增加当前订阅总数
function incrFollowNum($uid): int
{
$oExtend = $this->findItem($uid, 'uid');
if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid', $uid)->increment('follow_num');
}
//减去当前订阅总数
function decrFollowNum($uid): int
{
$oExtend = $this->findItem($uid, 'uid');
if (!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid', $uid)->decrement('follow_num');
}
//获取用户活跃信息
function getUserActiveListLimit($nowUid, $limit = 500): \Illuminate\Database\Eloquent\Collection|array
{
return $this->newQuery()
->where('id', '>=', $nowUid)
->limit($limit)
->orderBy('id')
->get(['uid', 'is_active']);
}
//检测所有用户活跃状态
function updateAllUserActiveStatus($date = null): void
{
if (empty($date)) $date = Carbon::yesterday()->toDateString();
$oCustomerWsHistoryModel = new CustomerWsHistoryModel();
$aActiveUserIdList = $oCustomerWsHistoryModel->getActiveUserIdList($date); //三日内活跃用户
if (empty($aActiveUserIdList)) return;
$oCustomerChangeInfoLogModel = new CustomerChangeInfoLogModel();
$nowUid = 0;
while (true) {
try {
Db::beginTransaction();
$aUserExtendList = $this->getUserActiveListLimit($nowUid, 500);
if (empty($aUserExtendList)) break;
$nowUid = max($aUserExtendList->pluck('uid')->toArray());
foreach ($aUserExtendList as $oUserExtend) {
if (in_array($oUserExtend->uid, $aActiveUserIdList)) { //在活跃列表中
if ($oUserExtend->is_active == self::IS_ACTIVE_YES) continue; //已经是活跃用户
//变更用户状态
$res = $this->newQuery()->where('uid', $oUserExtend->uid)->update(['is_active' => self::IS_ACTIVE_YES]);
if ($res) {
//记录日志
$oCustomerChangeInfoLogModel->addUserActiveStatusLog($oUserExtend->uid, $oUserExtend->is_active, self::IS_ACTIVE_YES, CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES);
$this->activeUserStatusToQueueProducer($oUserExtend->uid); //投递到消息队列
}
} else { //三日内不活跃
if ($oUserExtend->is_active == self::IS_ACTIVE_NO) continue; //已经是不活跃用户
//变更用户状态
$res = $this->newQuery()->where('uid', $oUserExtend->uid)->update(['is_active' => self::IS_ACTIVE_NO]);
if ($res) {
//记录日志
$oCustomerChangeInfoLogModel->addUserActiveStatusLog($oUserExtend->uid, $oUserExtend->is_active, self::IS_ACTIVE_YES, CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO);
}
}
}
Db::commit();
} catch (\Exception $e) {
Log::error('updateUserActiveStatus error:' . $e->getMessage());
Db::rollBack();
}
}
}
//登录检测用户活跃状态
function updateUserActiveStatus($uid): void
{
try{
Db::beginTransaction();
$oCustomerWsHistoryModel = new CustomerWsHistoryModel();
$aActiveUserId = $oCustomerWsHistoryModel->findActiveUserId($uid, Carbon::yesterday()->toDateString()); //三日内活跃用户
if(empty($aActiveUserId)) return;
$oCustomerUserExtendModel = $this->newQuery()->where('uid', $uid)->first(['uid','is_active']);
if(!$oCustomerUserExtendModel) return;
$oCustomerChangeInfoLogModel = new CustomerChangeInfoLogModel();
$res = $this->newQuery()->where('uid', $uid)->update(['is_active' => self::IS_ACTIVE_YES]);
if ($res) {
//记录日志
$oCustomerChangeInfoLogModel->addUserActiveStatusLog($uid, $oCustomerUserExtendModel->is_active, self::IS_ACTIVE_YES, CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES);
$this->activeUserStatusToQueueProducer($uid); //投递到消息队列
}
Db::commit();
}catch (\Exception $e){
Log::error('updateUserActiveStatus error:' . $e->getMessage());
Db::rollBack();
}
}
//投递到消息队列,处理活跃推送信箱更新问题
function activeUserStatusToQueueProducer($uid): void
{
$params = QueueUserActiveStatusStruct::PARAMS;
$params['uid'] = $uid;
$params['queueCreatedAt'] = date('Y-m-d H:i:s');
UserActiveStatusQueue::dispatch($params)->onQueue(QueueUserActiveStatusStruct::QUEUE_NAME);
}
function activeUserStatusQueueConsumer($params): void
{
$uid = $params['uid'];
$oPostPushBoxModel = new PostPushBoxModel();
$oPostPushBoxModel->pullBigFanMasterPostConsumer($uid);
}
}

View File

@ -1,14 +1,14 @@
<?php <?php
namespace App\Models\Customer; namespace App\Models\Api\Customer;
use App\Cache\Table\TableCustomerUserCache; use App\Cache\Table\TableCustomerUserCache;
use App\Models\Base\CustomerBaseModel; use App\Models\Api\Base\ApiBaseModel;
use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
class CustomerUserModel extends CustomerBaseModel class CustomerUserModel extends ApiBaseModel
{ {
protected $table = 'customer_users'; protected $table = 'customer_users';
protected $primaryKey = 'id'; protected $primaryKey = 'id';

View File

@ -1,10 +1,10 @@
<?php <?php
namespace App\Models\Follow; namespace App\Models\Api\Follow;
use App\Exceptions\ModelException; use App\Exceptions\ModelException;
use App\Models\Base\BaseModel; use App\Models\Api\Base\ApiBaseModel;
class FollowHistoryModel extends BaseModel class FollowHistoryModel extends ApiBaseModel
{ {
protected $table = 'customer_follow_history'; protected $table = 'customer_follow_history';
protected $primaryKey = 'id'; protected $primaryKey = 'id';

View File

@ -1,13 +1,13 @@
<?php <?php
namespace App\Models\Follow; namespace App\Models\Api\Follow;
use App\Exceptions\ModelException; use App\Exceptions\ModelException;
use App\Models\Base\BaseModel; use App\Models\Api\Base\ApiBaseModel;
use App\Models\Customer\CustomerUserExtendModel; use App\Models\Api\Customer\CustomerUserExtendModel;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
class FollowModel extends BaseModel class FollowModel extends ApiBaseModel
{ {
protected $table = 'customer_follow'; protected $table = 'customer_follow';
protected $primaryKey = 'id'; protected $primaryKey = 'id';

View File

@ -1,10 +1,10 @@
<?php <?php
namespace App\Models\Post; namespace App\Models\Api\Post;
use App\Exceptions\ModelException; use App\Exceptions\ModelException;
use App\Models\Base\BaseModel; use App\Models\Api\Base\ApiBaseModel;
class PostHistoryModel extends BaseModel class PostHistoryModel extends ApiBaseModel
{ {
protected $table = 'customer_post_history'; protected $table = 'customer_post_history';
protected $primaryKey = 'id'; protected $primaryKey = 'id';

View File

@ -0,0 +1,209 @@
<?php
namespace App\Models\Api\Post;
use App\Exceptions\ModelException;
use App\Models\Api\Base\ApiBaseModel;
use App\Models\Api\Post\Structs\PostParamsStruct;
use App\Tools\Tools;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\SoftDeletes;
class PostModel extends ApiBaseModel
{
//软删除
use SoftDeletes;
protected $table = 'customer_post';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'uuid',
'post_batch_sn',
'mid',
'uid',
'media',
'content',
'post_params',
'created_at',
'deleted_at',
];
const TYPE_POST = PostPushBoxModel::TYPE_POST;
const TYPE_REPOST = PostPushBoxModel::TYPE_REPOST;
const TYPE = [
self::TYPE_POST => '推文',
self::TYPE_REPOST => '转发',
];
protected function media(): Attribute
{
return Attribute::make(
get: fn(string $value = '') => Tools::JonsDecode($value),
set: fn(array $value = []) => Tools::JonsEncode($value),
);
}
protected function postParams(): Attribute
{
return Attribute::make(
get: fn(string $value = '') => Tools::JonsDecode($value),
set: fn(array $value = []) => Tools::JonsEncode($value),
);
}
/**
* @throws ModelException
*/
function addPost($uid, $type = self::TYPE_POST, $content = null, $media = null, $mid = null, $sBachSn = null): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
if (!in_array($type, [self::TYPE_POST, self::TYPE_REPOST])) throw new ModelException('type params error');
$aPostParams = [];
if($type == self::TYPE_REPOST){
$oRePostModel = $this->findItem($mid);
$aPostParams[PostParamsStruct::REPOST_ORG_USER_ID] = $oRePostModel->uid;
$aPostParams[PostParamsStruct::REPOST_ORG_POST_ID] = $oRePostModel->mid;
}
$uuid = Tools::genUuid();
$bsn = 'BSN_' . ($sBachSn ?? Tools::genUuid());
if (!$content && !$media) throw new ModelException('addPost params error');
$aItem['type'] = $type;
$aItem['uid'] = $uid;
$aItem['uuid'] = $uuid;
$aItem['post_batch_sn'] = $bsn;
$aItem['mid'] = $mid;
$aItem['media'] = $media;
$aItem['content'] = $content;
$aItem['post_params'] = $aPostParams;
$sDateTime = date('Y-m-d H:i:s');
$aItem['created_at'] = $sDateTime;
$res = $this->addItem($aItem);
if ($res) {
$this->pushToQueue(self::TYPE_POST, $res->id);
}
return $res;
}
function addBatchPost(array $aPostList): void
{
$mid = null;
$bsn = 'BSN_' . ($sBachSn ?? Tools::genUuid());
foreach ($aPostList as $aPostItem) {
$oPost = $this->addPost($aPostItem['uid'], $aPostItem['type'], $aPostItem['content'], $aPostItem['media'], $mid, $bsn);
if ($oPost) {
$mid = $oPost->id;
}
}
}
//发送到消息队列处理新增post
function pushToQueue($type, $id): void
{
PostPushBoxModel::addPostQueueProducer(['type' => $type, 'id' => $id]);
}
/**
* @throws ModelException
*/
function delPostById($id)
{
$oPost = $this->findItem($id);
$res = $this->delItem($id);
if ($res) {
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL, $oPost->toArray());
}
return $res;
}
/**
* @throws ModelException
*/
function delPostByUuid($uuid)
{
$oPost = $this->findItemByWhere(['uuid' => $uuid]);
$res = $this->newQuery()->where('uuid', $uuid)->delete();
if ($res) {
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL, $oPost->toArray());
}
return $res;
}
function getPostListByUid($uid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['uid' => $uid]);
}
function getPostById($id): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null
{
return $this->findItem($id);
}
/**
* @throws ModelException
*/
function updatePostById($aItem): bool|int
{
if (!isset($aItem['id'])) throw new ModelException('updatePostById params error');
if (empty($aItem['id'])) throw new ModelException('updatePostById params error');
$oPost = $this->findItem($aItem['id']);
$res = $this->updateItem($aItem);
if ($res) {
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT, $oPost->toArray());
}
return $res;
}
/**
* @throws ModelException
*/
function updatePostByUuid($aItem): bool|int
{
if (!isset($aItem['uuid'])) throw new ModelException('updatePostByUuid params error');
if (empty($aItem['uuid'])) throw new ModelException('updatePostByUuid params error');
$oPost = $this->findItemByWhere(['uuid' => $aItem['uuid']]);
$res = $this->updateItem($aItem, 'uuid');
if ($res) {
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT, $oPost->toArray());
}
return $res;
}
function getPostListByMid($mid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['mid' => $mid]);
}
function getPostListByUidMid($uid, $mid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['uid' => $uid, 'mid' => $mid]);
}
function getPostListByUids($uids, $sDateLimit = null,$cols = ['*'],$offset = null, $limit = null): \Illuminate\Database\Eloquent\Collection|array
{
$oModel = $this->newQuery();
if ($offset) $oModel->offset($offset);
if ($limit) $oModel->limit($offset);
if ($sDateLimit == null) $sDateLimit = date('Y-m-d H:i:s', strtotime('-3 day'));
return $oModel
->where('created_at', $sDateLimit)
->whereIn('uid', $uids)
->orderBy('created_at')
->get($cols);
}
function CountPostListByUids($uids, $sDateLimit = null): int
{
if ($sDateLimit == null) $sDateLimit = date('Y-m-d H:i:s', strtotime('-3 day'));
return $this->newQuery()->where('created_at', $sDateLimit)->whereIn('uid', $uids)->orderBy('created_at')->count();
}
}

View File

@ -0,0 +1,256 @@
<?php
namespace App\Models\Api\Post;
use App\Exceptions\ModelException;
use App\Jobs\AddPostQueue;
use App\Models\Api\Base\ApiBaseModel;
use App\Models\Api\Comment\PostCommentModel;
use App\Models\Api\Customer\CustomerUserExtendModel;
use App\Models\Api\Follow\FollowModel;
use App\Models\Api\Post\Structs\PostParamsStruct;
use App\Structs\QueueAddPostStruct;
use App\Tools\CollectOffsetLimit;
use App\Tools\Tools;
use Illuminate\Database\Eloquent\Casts\Attribute;
class PostPushBoxModel extends ApiBaseModel
{
protected $table = 'customer_post_push_box';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'uid',
'pid',
'puuid',
'post_params',
'is_like',
'is_repost',
'is_bookmark',
'is_read',
'post_created_at',
'created_at',
'deleted_at',
];
const TYPE_POST = 1;
const TYPE_REPOST = 2;
const TYPE_COMMENT = 3;
const TYPE = [
self::TYPE_POST => '推文',
self::TYPE_REPOST => '转发',
self::TYPE_COMMENT => '评论',
];
const IS_LIKE_DEFAULT = 1;
const IS_LIKE_YES = 2;
const IS_LIKE_NO = 3;
const IS_LIKE = [
self::IS_LIKE_DEFAULT => '默认',
self::IS_LIKE_YES => '喜欢',
self::IS_LIKE_NO => '不喜欢',
];
const IS_REPOST_DEFAULT = 1;
const IS_REPOST_YES = 2;
const IS_REPOST = [
self::IS_REPOST_DEFAULT => '默认',
self::IS_REPOST_YES => '已转发',
];
const IS_BOOKMARK_DEFAULT = 1;
const IS_BOOKMARK_YES = 2;
const IS_BOOKMARK = [
self::IS_BOOKMARK_DEFAULT => '默认',
self::IS_BOOKMARK_YES => '已收藏',
];
const IS_READ_NO = 1;
const IS_READ_YES = 2;
const IS_READ = [
self::IS_READ_NO => '默认',
self::IS_READ_YES => '已收藏',
];
protected function postParams(): Attribute
{
return Attribute::make(
get: fn(string $value = '') => Tools::JonsDecode($value),
set: fn(array $value = []) => Tools::JonsEncode($value),
);
}
public static function addPostQueueProducer(array $params): void
{
AddPostQueue::dispatch($params)->onQueue(QueueAddPostStruct::QUEUE_NAME);
}
/**
* 提交后调用事件,在消费队列跑推送
* @throws ModelException
*/
function addPostQueueConsumer(array $params)
{
if (empty($params)) return false;
if (isset($params['id'])) return false;
if (isset($params['type'])) return false;
$id = $params['id'];
$type = $params['type'];
if (!in_array($type, [self::TYPE_POST, self::TYPE_REPOST, self::TYPE_COMMENT])) return false;
if (empty($id)) return false;
$oPostModel = new PostModel();
$oPost = null;
$aPostParams = [];
//判断推送类型
if ($type == self::TYPE_POST) {
$postId = $id;
} elseif ($type == self::TYPE_REPOST) {
$postId = $id;
$oRePostModel = $oPostModel->findItem($id);
if (!$oRePostModel) return false;
$aPostParams[PostParamsStruct::REPOST_ORG_USER_ID] = $oRePostModel->uid;
$aPostParams[PostParamsStruct::REPOST_ORG_POST_ID] = $oRePostModel->mid;
} elseif ($type == self::TYPE_COMMENT) {
$oPostCommentModel = new PostCommentModel();
$oPostCommentModel = $oPostCommentModel->findItem($id);
if (!$oPostCommentModel) return false;
$postId = $oPostCommentModel->pid;
$aPostParams[PostParamsStruct::COMMENT_ID] = $oPostCommentModel->id;
$aPostParams[PostParamsStruct::COMMENT_USER_ID] = $oPostCommentModel->uid;
$aPostParams[PostParamsStruct::COMMENT_POST_ID] = $oPostCommentModel->pid;
$aPostParams[PostParamsStruct::COMMENT_CONTEXT] = $oPostCommentModel->content;
$aPostParams[PostParamsStruct::COMMENT_CONTEXT_CREATE_TIME] = $oPostCommentModel->created_at;
} else {
throw new ModelException('type error');
}
if ($postId) $oPost = $oPostModel->findItem($postId);
if (!$oPost) throw new ModelException('post not found');
$iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000));
//查询粉丝数
$CustomerUserExtendModel = new CustomerUserExtendModel();
$CustomerUserExtend = $CustomerUserExtendModel->findItem($oPost->uid);
if (!$CustomerUserExtend) throw new ModelException('user extend not found');
//粉丝数少于$iConfigFansPushLimit的用户走写扩散流程所有粉丝信箱插入一条
$bSendMode = $CustomerUserExtend->fans_num < $iConfigFansPushLimit;
$iTotalCount = $this->countSendFans($bSendMode, $oPost->uid); //计算发送总数
$aPost = $oPost->toArray();
if (empty($aPost)) return false;
$aPost['post_params'] = $aPostParams;
//分批发送
$oCollectOffsetLimit = new CollectOffsetLimit();
$oCollectOffsetLimit->setITotalCount($iTotalCount)->runWhile(function ($offset, $limit) use ($aPost, $bSendMode) {
$oFollowList = $this->getFansListWithPage($bSendMode, $aPost['uid'], $offset, $limit);
if(empty($oFollowList)) return;
$this->sendPostToBox($aPost, $oFollowList);
});
}
function getFansListWithPage($bAllFans, $uid, $offset = 0, $limit = 2000): \Illuminate\Database\Eloquent\Collection|array|\Illuminate\Support\Collection
{
$oFollowModel = new FollowModel();
//粉丝数少于$iConfigFansPushLimit的用户走写扩散流程所有粉丝信箱插入一条
if ($bAllFans) {
$oFollowList = $oFollowModel->getFansList($uid, ['uid'], $offset, $limit); //获取所有粉丝列表
} else { //读扩散流程(只针对活跃粉丝信箱插入一条)
//获取活跃粉丝列表
//@活跃粉丝数量过大需要分批处理
$oFollowList = $oFollowModel->getActiveFansUidList($uid, ['a.uid'], $offset, $limit);
}
return $oFollowList;
}
function countSendFans($bAllFans, $uid): int
{
$oFollowModel = new FollowModel();
if ($bAllFans) {
$iCount = $oFollowModel->getFansCount($uid); //获取所有粉丝列表
} else { //读扩散流程(只针对活跃粉丝信箱插入一条)
//获取活跃粉丝列表
$iCount = $oFollowModel->getActiveFansUidListCount($uid);
}
return $iCount;
}
//发送到推送信箱
function sendPostToBox($aPost, $oFollowList): void
{
if (!$oFollowList) return;
foreach ($oFollowList as $oFollow) {
$aItem['uid'] = $oFollow->uid;
$aItem['pid'] = $aPost['id'];
$aItem['puuid'] = $aPost['uuid'];
$aItem['post_created_at'] = $aPost['created_at'];
$this->addItemWithCreateTime($aItem);
}
}
/**
* 拉取推送信箱列表
* @param $uid
* @param $last_id //上次最后一条id
* @param $limit
* @return \Illuminate\Database\Eloquent\Collection|array
*/
function getPushBoxList($uid, $last_id = 0, $limit = 20, $cols = ['*']): \Illuminate\Database\Eloquent\Collection|array
{
//活跃用户直接拉取未读消息
return $this->newQuery()
->where('uid', $uid)
// ->where('id', '>', $last_id)
->where('is_read', self::IS_READ_NO)
->orderBy('created_at', 'desc')
->limit($limit)
->get($cols);
//非活跃用户拉取大v消息在用户状态更新时已经调用过此处不用在做处理
}
//非活跃拉取已跟随大v最新文章。
//放在用户状态更新时调用
function pullBigFanMasterPostConsumer($uid)
{
//获取文章和转发文章
//获取大v定义粉丝数,获取大于该粉丝数的大v文章
$iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000));
$oFollowModel = new FollowModel();
$oFollowList = $oFollowModel->getFollowListWithFansLimit($uid, $iConfigFansPushLimit, ['a.follow_uid']);
if ($oFollowList->isEmpty()) return null;
$aFollowList = $oFollowList->toArray();
$aFollowUid = array_column($aFollowList, 'follow_uid');
$oPostModel = new PostModel();
//分批发送到信箱
//@@大v评论拉取到自己信箱
$iTotalCount = $oPostModel->CountPostListByUids($aFollowUid);
$oCollectOffsetLimit = new CollectOffsetLimit();
$oCollectOffsetLimit->setITotalCount($iTotalCount)->runWhile(function ($offset, $limit) use ($oPostModel,$aFollowUid,$uid) {
$oPostList = $oPostModel->getPostListByUids($aFollowUid,null,['*'],$offset, $limit);
if(empty($oPostList)) return;
$this->sendPostToBoxByUid($oPostList->toArray(), $uid);
});
}
function sendPostToBoxByUid(array $oPostList, $uid): void
{
foreach ($oPostList as $oPost) {
$aItem['type'] = $oPost->type;
$aItem['uid'] = $uid;
$aItem['pid'] = $oPost->id;
$aItem['puuid'] = $oPost->uuid;
$aItem['post_params'] = $oPost->post_params;
$aItem['post_created_at'] = $oPost->created_at;
$this->addItemWithCreateTime($aItem);
}
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Models\Api\Post\Structs;
class PostParamsStruct{
const REPOST_ORG_USER_ID = 'repostOrgUserId';
const REPOST_ORG_USERNAME = 'repostOrgUsername';
const REPOST_ORG_USER_NICKNAME = 'repostOrgUserNickname';
const REPOST_ORG_POST_ID = 'repostOrgPostId'; //原推文id
const COMMENT_ID = 'CommentId';
const COMMENT_USER_ID = 'CommentUserId';
const COMMENT_USERNAME = 'CommentUsername';
const COMMENT_POST_ID = 'CommentPostId';
const COMMENT_CONTEXT= 'CommentContext';
const COMMENT_CONTEXT_CREATE_TIME= 'CommentContextCreateTime';
}

View File

@ -1,15 +1,12 @@
<?php <?php
namespace App\Models\WebSocket; namespace App\Models\Api\WebSocket;
use App\Cache\Table\TableCustomerUserCache; use App\Models\Api\Base\ApiBaseModel;
use App\Models\Base\CustomerBaseModel;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class CustomerWsHistoryModel extends CustomerBaseModel class CustomerWsHistoryModel extends ApiBaseModel
{ {
protected $table = 'customer_ws_history'; protected $table = 'customer_ws_history';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
@ -46,4 +43,17 @@ class CustomerWsHistoryModel extends CustomerBaseModel
->toArray(); ->toArray();
} }
//获取判断用户是否活跃
//@需要加入缓存-缓存时间为3天
function findActiveUserId($uid, $date, $days = 3): array
{
return $this->newQuery()
->where('uid', $uid)
->where('event', self::EVENT_ON_CONNECT)
->where('status', self::STATUS_SUCCESS)
->whereBetween(DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d')"), [Carbon::parse($date)->subDays($days - 1)->toDateString(), Carbon::parse($date)->toDateString()])
->first(['uid'])
->toArray();
}
} }

View File

@ -2,9 +2,7 @@
namespace App\Models\Base; namespace App\Models\Base;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
class BaseModel extends Model class BaseModel extends Model
{ {
@ -27,6 +25,14 @@ class BaseModel extends Model
return $this->newQuery()->create($aItem); return $this->newQuery()->create($aItem);
} }
function addItemWithCreateTime($aItem,$col = 'created_at'): Model|\Illuminate\Database\Eloquent\Builder|bool
{
$aItem = $this->checkColInFill($aItem);
if (empty($aItem)) return false;
$aItem[$col] = date('Y-m-d H:i:s');
return $this->newQuery()->create($aItem);
}
function delItem($id) function delItem($id)
{ {
return $this->newQuery()->where($this->primaryKey, $id)->delete(); return $this->newQuery()->where($this->primaryKey, $id)->delete();

View File

@ -1,7 +0,0 @@
<?php
namespace App\Models\Base;
class CustomerBaseModel extends BaseModel {
}

View File

@ -1,23 +0,0 @@
<?php
namespace App\Models\Customer;
use App\Cache\Table\TableCustomerUserCache;
use App\Models\Base\CustomerBaseModel;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
class CustomerLoginHistoryModel extends CustomerBaseModel
{
protected $table = 'customer_login_history';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'status',
'uid',
'device',
'created_at',
];
}

View File

@ -1,154 +0,0 @@
<?php
namespace App\Models\Customer;
use App\Exceptions\ModelException;
use App\Models\Base\CustomerBaseModel;
use App\Models\WebSocket\CustomerWsHistoryModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class CustomerUserExtendModel extends CustomerBaseModel
{
protected $table = 'customer_user_extend';
protected $primaryKey = 'uid';
protected $fillable = [
'uid',
'is_active',
'fans_num',
'follow_num',
'updated_at',
];
const COL_IS_ACTIVE = 'is_active';
//是否活跃用户
const IS_ACTIVE_YES = 1;
const IS_ACTIVE_NO = 2;
const IS_ACTIVE = [
self::IS_ACTIVE_YES => '活跃',
self::IS_ACTIVE_NO => '不活跃',
];
//增加用户扩展信息
function addExtend($aItem): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
if(empty($aItem['uid'])) throw new ModelException('uid error');
if($this->findItem($aItem['uid'],['uid'])) return null; //已存在
$sDateTime = date('Y-m-d H:i:s');
$aItem['updated_at'] = $sDateTime;
return $this->addItem($aItem);
}
//增加当前粉丝总数
function incrFansNum($uid): int
{
$oExtend = $this->findItem($uid,'uid');
if(!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid',$uid)->increment('fans_num');
}
//减去当前追随者总数
function decrFansNum($uid): int
{
$oExtend = $this->findItem($uid,'uid');
if(!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid',$uid)->decrement('fans_num');
}
//增加当前订阅总数
function incrFollowNum($uid): int
{
$oExtend = $this->findItem($uid,'uid');
if(!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid',$uid)->increment('follow_num');
}
//减去当前订阅总数
function decrFollowNum($uid): int
{
$oExtend = $this->findItem($uid,'uid');
if(!$oExtend) throw new ModelException('user extend not found');
return $this->newQuery()->where('uid',$uid)->decrement('follow_num');
}
//获取用户活跃信息
function getUserActiveListLimit($nowUid, $limit = 500): \Illuminate\Database\Eloquent\Collection|array
{
return $this->newQuery()
->where('id', '>=', $nowUid)
->limit($limit)
->orderBy('id')
->get(['uid', 'is_active']);
}
//检测所有用户活跃状态
function updateUserActiveStatus($date = null): void
{
if(empty($date)) $date = Carbon::yesterday()->toDateString();
$oCustomerWsHistoryModel = new CustomerWsHistoryModel();
$aActiveUserIdList = $oCustomerWsHistoryModel->getActiveUserIdList($date); //三日内活跃用户
if(empty($aActiveUserIdList)) return;
$oCustomerChangeInfoLogModel = new CustomerChangeInfoLogModel();
$nowUid = 0;
while (true){
try{
Db::beginTransaction();
$aUserList = $this->getUserActiveListLimit($nowUid, 500);
if(empty($aUserList)) break;
$nowUid = max($aUserList->pluck('uid')->toArray());
foreach ($aUserList as $oUser){
$isChanged = false;
$aLogInsert = [
'type' => CustomerChangeInfoLogModel::TYPE_CHANG_USER_ACTIVE_STATUS,
'uid' => $oUser->uid,
'column' => self::COL_IS_ACTIVE,
'before_value' => $oUser->is_active,
'pid' => CustomerChangeInfoLogModel::PID_SYSTEM,
];
if(in_array($oUser->uid, $aActiveUserIdList)){ //在活跃列表中
if($oUser->is_active == self::IS_ACTIVE_YES) continue; //已经是活跃用户
//变更用户状态
$res = $this->newQuery()->where('uid',$oUser->uid)->update(['is_active'=>self::IS_ACTIVE_YES]);
if($res) {
$isChanged = true;
$aLogInsert['value'] = self::IS_ACTIVE_YES;
$aLogInsert['after_value'] = self::IS_ACTIVE_YES;
$aLogInsert['remark_key'] = CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES;
$aLogInsert['remark_desc'] = CustomerChangeInfoLogModel::REMARK[CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_YES];
}
}else{ //三日内不活跃
if($oUser->is_active == self::IS_ACTIVE_NO) continue; //已经是不活跃用户
//变更用户状态
$res = $this->newQuery()->where('uid',$oUser->uid)->update(['is_active'=>self::IS_ACTIVE_NO]);
if($res) {
$isChanged = true;
$aLogInsert['value'] = self::IS_ACTIVE_NO;
$aLogInsert['after_value'] = self::IS_ACTIVE_NO;
$aLogInsert['remark_key'] = CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO;
$aLogInsert['remark_desc'] = CustomerChangeInfoLogModel::REMARK[CustomerChangeInfoLogModel::REMARK_DAILY_CHECK_USER_ACTIVE_STATUS_NO];
}
}
if($isChanged){ //有变化插入日志
$oCustomerChangeInfoLogModel->addLog($aLogInsert);
}
}
Db::commit();
}catch (\Exception $e){
Log::error('updateUserActiveStatus error:'.$e->getMessage());
Db::rollBack();
}
}
}
}

View File

@ -1,133 +0,0 @@
<?php
namespace App\Models\Post;
use App\Exceptions\ModelException;
use App\Models\Base\BaseModel;
use App\Tools\Tools;
use Illuminate\Database\Eloquent\SoftDeletes;
class PostModel extends BaseModel
{
//软删除
use SoftDeletes;
protected $table = 'customer_post';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'uuid',
'mid',
'uid',
'media',
'content',
'created_at',
'deleted_at',
];
/**
* @throws ModelException
*/
function addPost($uid, $content = null, $media = null): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
if(!$content && !$media) throw new ModelException('addPost params error');
$aItem['uid'] = $uid;
$aItem['uuid'] = Tools::genUuid();
$aItem['media'] = $media;
$aItem['content'] = $content;
$sDateTime = date('Y-m-d H:i:s');
$aItem['created_at'] = $sDateTime;
$res = $this->addItem($aItem);
if($res){
}
return $res;
}
/**
* @throws ModelException
*/
function delPostById($id)
{
$oPost = $this->findItem($id);
$res = $this->delItem($id);
if($res){
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL,$oPost->toArray());
}
return $res;
}
/**
* @throws ModelException
*/
function delPostByUuid($uuid)
{
$oPost = $this->findItemByWhere(['uuid'=>$uuid]);
$res = $this->newQuery()->where('uuid', $uuid)->delete();
if($res){
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_DEL,$oPost->toArray());
}
return $res;
}
function getPostListByUid($uid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['uid'=>$uid]);
}
function getPostById($id): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null
{
return $this->findItem($id);
}
/**
* @throws ModelException
*/
function updatePostById($aItem): bool|int
{
if(!isset($aItem['id'])) throw new ModelException('updatePostById params error');
if(empty($aItem['id'])) throw new ModelException('updatePostById params error');
$oPost = $this->findItem($aItem['id']);
$res = $this->updateItem($aItem);
if($res){
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT,$oPost->toArray());
}
return $res;
}
/**
* @throws ModelException
*/
function updatePostByUuid($aItem): bool|int
{
if(!isset($aItem['uuid'])) throw new ModelException('updatePostByUuid params error');
if(empty($aItem['uuid'])) throw new ModelException('updatePostByUuid params error');
$oPost = $this->findItemByWhere(['uuid'=>$aItem['uuid']]);
$res = $this->updateItem($aItem,'uuid');
if($res){
$oPostHistoryModel = new PostHistoryModel();
$oPostHistoryModel->addPostHistory(PostHistoryModel::METHOD_EDIT,$oPost->toArray());
}
return $res;
}
function getPostListByMid($mid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['mid'=>$mid]);
}
function getPostListByUidMid($uid,$mid): \Illuminate\Database\Eloquent\Collection|array
{
return $this->getItemsByWhere(['uid'=>$uid,'mid'=>$mid]);
}
function getPostListByUids($uids,$sDateLimit = null): \Illuminate\Database\Eloquent\Collection|array
{
if($sDateLimit == null) $sDateLimit = date('Y-m-d H:i:s',strtotime('-3 day'));
return $this->newQuery()->where('created_at',$sDateLimit)->whereIn('uid',$uids)->get();
}
}

View File

@ -1,181 +0,0 @@
<?php
namespace App\Models\Post;
use App\Exceptions\ModelException;
use App\Models\Base\BaseModel;
use App\Models\Customer\CustomerUserExtendModel;
use App\Models\Follow\FollowModel;
use App\Tools\CollectOffsetLimit;
class PostPushBoxModel extends BaseModel
{
protected $table = 'customer_post_push_box';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'uid',
'pid',
'puuid',
'is_like',
'is_repost',
'is_bookmark',
'is_read',
'created_at',
'created_box_at',
'deleted_at',
];
const IS_LIKE_DEFAULT = 1;
const IS_LIKE_YES = 2;
const IS_LIKE_NO = 3;
const IS_LIKE = [
self::IS_LIKE_DEFAULT => '默认',
self::IS_LIKE_YES => '喜欢',
self::IS_LIKE_NO => '不喜欢',
];
const IS_REPOST_DEFAULT = 1;
const IS_REPOST_YES = 2;
const IS_REPOST = [
self::IS_REPOST_DEFAULT => '默认',
self::IS_REPOST_YES => '已转发',
];
const IS_BOOKMARK_DEFAULT = 1;
const IS_BOOKMARK_YES = 2;
const IS_BOOKMARK = [
self::IS_BOOKMARK_DEFAULT => '默认',
self::IS_BOOKMARK_YES => '已收藏',
];
const IS_READ_DEFAULT = 1;
const IS_READ_YES = 2;
const IS_READ = [
self::IS_READ_DEFAULT => '默认',
self::IS_READ_YES => '已收藏',
];
/**
* 提交后调用事件
* @throws ModelException
*/
function newPostPushTask($id = null, $uuid = null)
{
$oPostModel = new PostModel();
$oPost = null;
if ($id) $oPost = $oPostModel->findItem($id);
if ($uuid) $oPost = $oPostModel->findItemByWhere(['uuid' => $uuid]);
if (!$oPost) throw new ModelException('post not found');
$iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000));
//查询粉丝数
$CustomerUserExtendModel = new CustomerUserExtendModel();
$CustomerUserExtend = $CustomerUserExtendModel->findItem($oPost->uid);
if (!$CustomerUserExtend) throw new ModelException('user extend not found');
//粉丝数少于$iConfigFansPushLimit的用户走写扩散流程所有粉丝信箱插入一条
$bSendMode = $CustomerUserExtend->fans_num < $iConfigFansPushLimit;
$iTotalCount = $this->countSendFans($bSendMode, $oPost->uid); //计算发送总数
//分批发送
$oCollectOffsetLimit = new CollectOffsetLimit();
$oCollectOffsetLimit->setITotalCount($iTotalCount)->runWhile(function ($offset, $limit) use ($oPost, $bSendMode) {
$oFollowList = $this->getFansListWithPage($bSendMode, $oPost->uid, $offset, $limit);
$this->sendPostToBox($oPost, $oFollowList);
});
}
function getFansListWithPage($bAllFans, $uid, $offset = 0, $limit = 2000): \Illuminate\Database\Eloquent\Collection|array|\Illuminate\Support\Collection
{
$oFollowModel = new FollowModel();
//粉丝数少于$iConfigFansPushLimit的用户走写扩散流程所有粉丝信箱插入一条
if ($bAllFans) {
$oFollowList = $oFollowModel->getFansList($uid, ['uid'], $offset, $limit); //获取所有粉丝列表
} else { //读扩散流程(只针对活跃粉丝信箱插入一条)
//获取活跃粉丝列表
//@活跃粉丝数量过大需要分批处理
$oFollowList = $oFollowModel->getActiveFansUidList($uid, ['a.uid'], $offset, $limit);
}
return $oFollowList;
}
function countSendFans($bAllFans, $uid): int
{
$oFollowModel = new FollowModel();
if ($bAllFans) {
$iCount = $oFollowModel->getFansCount($uid); //获取所有粉丝列表
} else { //读扩散流程(只针对活跃粉丝信箱插入一条)
//获取活跃粉丝列表
$iCount = $oFollowModel->getActiveFansUidListCount($uid);
}
return $iCount;
}
//发送到推送信箱
function sendPostToBox($oPost, $oFollowList): void
{
if (!$oFollowList) return;
$date = date('Y-m-d H:i:s');
foreach ($oFollowList as $oFollow) {
$aItem['uid'] = $oFollow->uid;
$aItem['pid'] = $oPost->id;
$aItem['puuid'] = $oPost->uuid;
$aItem['created_at'] = $oPost->created_at;
$aItem['created_box_at'] = $date;
$this->addItem($aItem);
}
}
/**
* 拉取推送信箱列表
* @param $uid
* @param $last_id //上次最后一条id
* @param $limit
* @return \Illuminate\Database\Eloquent\Collection|array
*/
function getPushBoxList($uid, $last_id = 0, $limit = 20): \Illuminate\Database\Eloquent\Collection|array
{
//活跃用户直接拉取未读消息
return $this->newQuery()->where('uid', $uid)->where('id', '>', $last_id)->where('is_read', self::IS_READ_DEFAULT)->orderBy('created_at', 'desc')->limit($limit)->get();
//非活跃用户拉取大v消息在用户状态更新时已经调用过此处不用在做处理
}
//非活跃拉取已跟随大v最新文章。
//放在用户状态更新时调用
function pullBigFanMasterPost($uid)
{
//获取大v定义粉丝数,获取大于该粉丝数的大v文章
$iConfigFansPushLimit = intval(env('CONFIG_FANS_PUSH_LIMIT', 2000));
//@此处需针对大量数据进行分批获取
$oFollowModel = new FollowModel();
$oFollowList = $oFollowModel->getFollowListWithFansLimit($uid,$iConfigFansPushLimit,['a.follow_uid']);
if ($oFollowList->isEmpty()) return null;
$aFollowList = $oFollowList->toArray();
$aFollowUid = array_column($aFollowList,'follow_uid');
$oPostModel = new PostModel();
$oPostList = $oPostModel->getPostListByUids($aFollowUid);
//将推文发送到信箱
$this->sendPostToBoxByUid($oPostList,$uid);
}
function sendPostToBoxByUid($oPostList, $uid): void
{
$date = date('Y-m-d H:i:s');
foreach ($oPostList as $oPost) {
$aItem['uid'] = $uid;
$aItem['pid'] = $oPost->id;
$aItem['puuid'] = $oPost->uuid;
$aItem['created_at'] = $oPost->created_at;
$aItem['created_box_at'] = $date;
$this->addItem($aItem);
}
}
}

View File

@ -1,45 +0,0 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}

View File

@ -0,0 +1,9 @@
<?php
namespace App\Models\Wallet\Base;
use App\Models\Base\BaseModel;
class WalletBaseModel extends BaseModel {
}

View File

@ -0,0 +1,125 @@
<?php
namespace App\Models\Wallet\Platform;
use App\Exceptions\ModelException;
use App\Models\Wallet\Base\WalletBaseModel;
use App\Models\Wallet\Wallet\WalletCurrencyModel;
use App\Tools\Math;
use App\Tools\Times;
use App\Tools\Tools;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class WalletPlatformBalanceModel extends WalletBaseModel
{
protected $table = 'wallet_platform_balance';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'platform_id',
'currency_id',
'currency_code',
'total_amount',
'frozen_amount',
'available_amount',
'created_at',
'updated_at',
];
const TYPE_ADD = 1;
const TYPE_DEC = 2;
const TYPE = [
self::TYPE_ADD => '加',
self::TYPE_DEC => '减',
];
function newPlatformBalance($platform_id, $currency_code): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
$resModel = $this->findItemByWhere(['platform_id' => $platform_id, 'currency_code' => $currency_code]);
if ($resModel) return $resModel;
$oWalletCurrencyModel = new WalletCurrencyModel();
$resWalletCurrencyModel = $oWalletCurrencyModel->findByCode($currency_code);
if (!$resWalletCurrencyModel) throw new ModelException('currency_code error');
$insert = [
'platform_id' => $platform_id,
'currency_id' => $oWalletCurrencyModel->id,
'currency_code' => $oWalletCurrencyModel->code,
'created_at' => Times::getNowDateTime(),
'updated_at' => Times::getNowDateTime(),
];
return $this->addItem($insert);
}
function findPlatformBalance($platform_id, $currency_code): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|null
{
return $this->findItemByWhere(['platform_id' => $platform_id, 'currency_code' => $currency_code]);
}
function findPlatformBalanceOrCreate($platform_id, $currency_code): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|bool|array|null
{
$resModel = $this->findItemByWhere(['platform_id' => $platform_id, 'currency_code' => $currency_code]);
if (!$resModel) { //不存在就创建一个
$resModel = $this->newPlatformBalance($platform_id, $currency_code);
}
return $resModel;
}
//增加平台余额
function incAvailableBalance($id, $amount): bool
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['total_amount', 'available_amount']);
if (!$oModel) throw new ModelException('找不到id');
$oModel->frozen_amount = Db::raw('total_amount + ' . $amount);
$oModel->available_amount = Db::raw('available_amount + ' . $amount);
return $oModel->save();
}
//扣除平台余额
function decAvailableBalance($id, $amount): bool
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['total_amount', 'available_amount']);
if (!$oModel) throw new ModelException('找不到id');
$oModel->frozen_amount = Db::raw('total_amount - ' . $amount);
$oModel->available_amount = Db::raw('available_amount - ' . $amount);
return $oModel->save();
}
function decFrozenAmountById($id, $amount): int
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['total_amount', 'frozen_amount']);
if (!$oModel) throw new ModelException('找不到id');
$oModel->frozen_amount = Db::raw('frozen_amount - ' . $amount);
$oModel->total_amount = Db::raw('total_amount - ' . $amount);
return $oModel->save();
}
function unFrozenAmountById($id, $amount): int
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['frozen_amount', 'available_amount']);
if (!$oModel) throw new ModelException('找不到id');
$oModel->frozen_amount = Db::raw('frozen_amount - ' . $amount);
$oModel->available_amount = Db::raw('available_amount + ' . $amount);
return $oModel->save();
}
function frozenAmountById($id, $amount): int
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['frozen_amount', 'available_amount']);
if (!$oModel) throw new ModelException('找不到id');
$oModel->frozen_amount = Db::raw('frozen_amount + ' . $amount);
$oModel->available_amount = Db::raw('available_amount - ' . $amount);
return $oModel->save();
}
}

View File

@ -0,0 +1,247 @@
<?php
namespace App\Models\Wallet\Platform;
use App\Exceptions\ModelException;
use App\Models\Wallet\Base\WalletBaseModel;
use App\Models\Wallet\Wallet\WalletCurrencyModel;
use App\Tools\Math;
use App\Tools\Times;
use App\Tools\Tools;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class WalletPlatformBalanceTransactionModel extends WalletBaseModel
{
protected $table = 'wallet_platform_balance_transaction';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'status',
'platform_id',
'currency_id',
'currency_code',
'currency_type',
'from_wallet_addr_id',
'from_user_transaction_id',
'from_uid',
'wallet_addr',
'from_wallet_transaction_id',
'received_amount',
'entered_amount',
'fee_amount',
'before_total_amount',
'after_total_amount',
'desc_key',
'desc',
'remark',
'sign',
'created_at',
'updated_at',
];
const TYPE_USER_RECHARGE = 1;
const TYPE_USER_WITHDRAW = 2;
const TYPE_ADMIN_ADD = 3;
const TYPE_ADMIN_DEC = 4;
const TYPE = [
self::TYPE_USER_RECHARGE => '用户充值',
self::TYPE_USER_WITHDRAW => '用户提现',
self::TYPE_ADMIN_ADD => '管理员加',
self::TYPE_ADMIN_DEC => '管理员减',
];
const STATUS_WAITING_QUEUE = 1;
const STATUS_CHAIN_WAITING_CALLBACK = 2;
const STATUS_SUCCESS = 3;
const STATUS_FAIL = 4;
const STATUS = [
self::STATUS_WAITING_QUEUE => '等待队列',
self::STATUS_CHAIN_WAITING_CALLBACK => '链上等待回调',
self::STATUS_SUCCESS => '成功',
self::STATUS_FAIL => '失败',
];
function addPlatformTransaction(
$type,
$status,
$received_amount,
$entered_amount,
$platform_id,
$currency_code,
$from_uid = '',
$from_user_transaction_id = '',
$from_wallet_addr_id = '',
$wallet_addr = '',
$desc_key = '',
$desc = '',
$remark = '',
): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
$received_amount = abs($received_amount);
$entered_amount = abs($entered_amount);
$oWalletPlatformBalanceModel = new WalletPlatformBalanceModel();
$oWalletCurrencyModel = new WalletCurrencyModel();
$resWalletPlatformBalanceModel = $oWalletPlatformBalanceModel->findPlatformBalance($platform_id, $currency_code);
if (!$resWalletPlatformBalanceModel) throw new ModelException('platform balance not found');
$resWalletCurrencyModel = $oWalletCurrencyModel->findByCode($currency_code);
if (!$resWalletCurrencyModel) throw new ModelException('currency_code error');
if (in_array($type, [self::TYPE_ADMIN_DEC, self::TYPE_USER_WITHDRAW])) {
if (Math::bcComp($resWalletPlatformBalanceModel->available_amount, $received_amount) == -1) throw new ModelException('platform balance not enough');
}
//提现费率计算
$fee_amount = 0;
if ($type == self::TYPE_USER_WITHDRAW) {
$fee_amount = $oWalletCurrencyModel->computeTransferRate($received_amount, $oWalletCurrencyModel->transfer_rate);
$entered_amount = Math::bcSub($received_amount, $fee_amount);
}
if($type == self::TYPE_USER_RECHARGE){
$fee_amount = Math::bcSub($received_amount, $entered_amount);
}
$insert = [
'type' => $type,
'status' => $status,
'platform_id' => $platform_id,
'currency_id' => $resWalletPlatformBalanceModel->currency_id,
'currency_code' => $resWalletPlatformBalanceModel->currency_code,
'currency_type' => $resWalletPlatformBalanceModel->currency_type,
'from_wallet_addr_id' => $from_wallet_addr_id,
'from_user_transaction_id' => $from_user_transaction_id,
'from_uid' => $from_uid,
'wallet_addr' => $wallet_addr,
'received_amount' => $received_amount,
'entered_amount' => $entered_amount,
'fee_amount' => $fee_amount,
'before_total_amount' => $resWalletPlatformBalanceModel->total_amount,
'after_total_amount' => Math::bcAdd($resWalletPlatformBalanceModel->total_amount, $entered_amount),
'desc_key' => $desc_key,
'desc' => $desc,
'remark' => $remark,
];
// $insert['sign'] = '';
$insert['created_at'] = Times::getNowDateTime();
$insert['updated_at'] = Times::getNowDateTime();
return $this->addItem($insert);
}
//增加提现账变并且冻结平台金额
function newWithdrawPlatformTransaction(
$amount,
$platform_id,
$currency_code,
$uid,
): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
try {
Db::beginTransaction();
$resModel = $this->addPlatformTransaction(self::TYPE_USER_WITHDRAW, self::STATUS_WAITING_QUEUE, $amount,$amount, $platform_id, $currency_code,$uid);
if(!$resModel) throw new ModelException('addPlatformTransaction error');
$oWalletPlatformBalanceModel = new WalletPlatformBalanceModel();
$res = $oWalletPlatformBalanceModel->findPlatformBalance($platform_id,$currency_code);
if (!$res) throw new ModelException('findPlatformBalance error');
$res = $oWalletPlatformBalanceModel->frozenAmountById($oWalletPlatformBalanceModel->id, $amount); //变更平台余额
if (!$res) throw new ModelException('frozenAmountById error');
Db::commit();
return $resModel;
}catch (\Exception $e) {
Db::rollBack();
Log::error('newWithdrawPlatformTransaction', ['code' => $e->getCode(), 'error' => $e->getMessage()]);
return false;
}
}
//成功提现处理
function withdrawSuccByUserTransactionId($user_transaction_id, $remark = ''): bool
{
try{
Db::beginTransaction();
$resModel = $this->findItemByWhere(['from_user_transaction_id' => $user_transaction_id, 'type' => self::TYPE_USER_WITHDRAW]);
if (!$resModel) return false;
if (!in_array($resModel->status, [self::STATUS_WAITING_QUEUE, self::STATUS_CHAIN_WAITING_CALLBACK])) return false;
$resModel->status = self::STATUS_SUCCESS;
if(!empty($remark)) $resModel->remark = $remark;
$resModel->updated_at = Times::getNowDateTime();
$res = $resModel->save();
if(!$res) throw new ModelException('save error');
//扣除平台冻结余额
$oWalletPlatformBalanceModel = new WalletPlatformBalanceModel();
$resWalletPlatformBalanceModel = $oWalletPlatformBalanceModel->findPlatformBalance($resModel->platform_id, $resModel->currency_code);
if (!$resWalletPlatformBalanceModel) throw new ModelException('platform balance not found');
$res = $oWalletPlatformBalanceModel->decFrozenAmountById($resWalletPlatformBalanceModel->id, $resModel->received_amount);
if (!$res) throw new ModelException('incBalance error');
Db::commit();
return true;
}catch (\Exception $e){
Db::rollBack();
Log::error('withdrawSuccByUserTransactionIdErr', ['code' => $e->getCode(), 'error' => $e->getMessage()]);
return false;
}
}
//失败提现处理
function withdrawErrByUserTransactionId($user_transaction_id, $remark = ''): bool
{
try {
Db::beginTransaction();
$resModel = $this->findItemByWhere(['from_user_transaction_id' => $user_transaction_id, 'type' => self::TYPE_USER_WITHDRAW]);
if (!$resModel) throw new ModelException('user transaction not found');
if (!in_array($resModel->status, [self::STATUS_WAITING_QUEUE, self::STATUS_CHAIN_WAITING_CALLBACK])) throw new ModelException('status error');
//更改账变状态
$resModel->status = self::STATUS_FAIL;
if(!empty($remark)) $resModel->remark = $remark;
$res = $resModel->save();
if (!$res) throw new ModelException('save error');
//解冻平台余额
$oWalletPlatformBalanceModel = new WalletPlatformBalanceModel();
$resWalletPlatformBalanceModel = $oWalletPlatformBalanceModel->findPlatformBalance($resModel->platform_id, $resModel->currency_code);
if (!$resWalletPlatformBalanceModel) throw new ModelException('platform balance not found');
$res = $oWalletPlatformBalanceModel->unFrozenAmountById($resWalletPlatformBalanceModel->id, $resModel->received_amount);
if (!$res) throw new ModelException('incBalance error');
Db::commit();
return true;
} catch (\Exception $e) {
Db::rollBack();
Log::error('withdrawErrByUserTransactionIdErr', ['code' => $e->getCode(), 'error' => $e->getMessage()]);
return false;
}
}
function newRechargePlatformTransaction(
$resWalletAddrTransactionModel,
$resWalletPlatformUserTransactionModel,
$amount,
$platform_id,
$currency_code,
): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
try {
Db::beginTransaction();
$resModel = $this->addPlatformTransaction(self::TYPE_USER_RECHARGE, self::STATUS_SUCCESS, $amount,$amount, $platform_id, $currency_code,$resWalletPlatformUserTransactionModel->uid,$resWalletPlatformUserTransactionModel->id,$resWalletAddrTransactionModel->wallet_addr_id,$resWalletAddrTransactionModel->wallet_addr);
if(!$resModel) throw new ModelException('addPlatformTransaction error');
$oWalletPlatformBalanceModel = new WalletPlatformBalanceModel();
$resWalletPlatformBalanceModel = $oWalletPlatformBalanceModel->findPlatformBalance($platform_id,$currency_code);
if (!$resWalletPlatformBalanceModel) throw new ModelException('findPlatformBalance error');
$res = $oWalletPlatformBalanceModel->incAvailableBalance($resWalletPlatformBalanceModel->id, $amount); //变更平台余额
if (!$res) throw new ModelException('frozenAmountById error');
Db::commit();
return $resModel;
}catch (\Exception $e) {
Db::rollBack();
Log::error('newWithdrawPlatformTransaction', ['code' => $e->getCode(), 'error' => $e->getMessage()]);
return false;
}
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Models\Wallet\Platform;
use App\Exceptions\ModelException;
use App\Models\Wallet\Base\WalletBaseModel;
use App\Tools\Times;
use App\Tools\Tools;
use Illuminate\Support\Facades\DB;
class WalletPlatformModel extends WalletBaseModel
{
protected $table = 'wallet_platform';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'name',
'code',
'appid',
'secret',
'notify_ip',
'created_at',
];
const CODE_CYCLE = 'CYCLE';
function addPlatform(string $name, string $code): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
$insert = [
'name' => $name,
'code' => $code,
'created_at' => Times::getNowDateTime(),
];
try {
Db::beginTransaction();
$resModel = $this->addItem($insert);
if(!$resModel) throw new ModelException('添加失败');
$appid_key = $resModel->id . $resModel->name . $resModel->code;
$resModel->appid = Tools::getMd5($appid_key);
$resModel->secret = Tools::generateRandStr(32);
$res = $resModel->save();
if(!$res) throw new ModelException('添加appid失败');
Db::commit();
}catch (\Exception $e) {
Db::rollBack();
throw $e;
}
return $resModel;
}
//@@给平台下发用户信息
static function userTransactionNotifyToPlatform($user_transaction_id)
{
}
}

View File

@ -0,0 +1,351 @@
<?php
namespace App\Models\Wallet\PlatformUser;
use App\Cache\Lock\WalletPlatformUserTransactionLock;
use App\Exceptions\ModelException;
use App\Jobs\UserActiveStatusQueue;
use App\Jobs\WalletPlatformUserWithdrawQueue;
use App\Models\Wallet\Base\WalletBaseModel;
use App\Models\Wallet\Platform\WalletPlatformBalanceModel;
use App\Models\Wallet\Platform\WalletPlatformBalanceTransactionModel;
use App\Models\Wallet\Wallet\WalletAddrModel;
use App\Models\Wallet\Wallet\WalletAddrTransactionModel;
use App\Models\Wallet\Wallet\WalletCurrencyModel;
use App\Structs\QueueUserActiveStatusStruct;
use App\Structs\QueueWalletPlatformUserWithdrawStruct;
use App\Tools\Math;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class WalletPlatformUserTransactionModel extends WalletBaseModel
{
protected $table = 'wallet_platform_user_transaction';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'platform_id',
'uid',
'currency_id',
'currency_code',
'currency_type',
'from_wallet_addr_id',
'wallet_addr',
'from_wallet_transaction_id',
'received_amount',
'entered_amount',
'fee_amount',
'desc_key',
'desc',
'remark',
'sign',
'platform_notify_status',
'created_at',
'updated_at',
];
const TYPE_RECHARGE = 1;
const TYPE_WITHDRAW = 2;
const TYPE = [
self::TYPE_RECHARGE => '充值',
self::TYPE_WITHDRAW => '提现',
];
const STATUS_WAITING_QUEUE = 1;
const STATUS_CODE_PROCESSING = 2;
const STATUS_CHAIN_WAITING = 3;
const STATUS_SUCCESS = 4;
const STATUS_FAIL = 5;
const STATUS = [
self::STATUS_WAITING_QUEUE => '等待队列',
self::STATUS_CODE_PROCESSING => '程序处理中',
self::STATUS_CHAIN_WAITING => '链上等待',
self::STATUS_SUCCESS => '成功',
self::STATUS_FAIL => '失败',
];
const DESC_KEY_NOT_FOUND_WITHDRAW_AMOUNT_WALLET_ADDR = 'notFoundWithdrawAmountWalletAddr';
const DESC_KEY_WITHDRAW_WALLET_AMOUNT_LOW = 'withdrawWalletAmountLow';
const DESC_KEY_WITHDRAW_CALL_CHAIN_WRONG = 'withdrawCallChainWrong';
const DESC = [
self::DESC_KEY_NOT_FOUND_WITHDRAW_AMOUNT_WALLET_ADDR => '未找到足额提现金额钱包地址',
self::DESC_KEY_WITHDRAW_WALLET_AMOUNT_LOW => '提现钱包金额不足',
self::DESC_KEY_WITHDRAW_CALL_CHAIN_WRONG => '提现调用链上接口失败',
];
//请求提现发起
function withdrawFirst($amount, $platform_id, $uid, $currency_code, $desc_key = null, $remark = ''): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
try {
Db::beginTransaction();
$amount = abs($amount);
//检查平台余额
$oWalletPlatformBalanceModel = new WalletPlatformBalanceModel();
$resWalletPlatformBalanceModel = $oWalletPlatformBalanceModel->findPlatformBalance($platform_id, $currency_code);
if (!$resWalletPlatformBalanceModel) throw new ModelException('platform_id or currency_code error');
if (Math::bcComp($resWalletPlatformBalanceModel->available_amount, $amount) == -1) throw new ModelException('platform balance not enough');
//冻结平台余额并增加账变
$oWalletPlatformBalanceTransactionModel = new WalletPlatformBalanceTransactionModel();
$resWalletPlatformBalanceTransactionModel = $oWalletPlatformBalanceTransactionModel->newWithdrawPlatformTransaction($amount, $platform_id, $currency_code,$uid);
if (!$resWalletPlatformBalanceTransactionModel) throw new ModelException('newWithdrawPlatformTransaction error');
//根据币种计算费率
$oWalletCurrencyModel = new WalletCurrencyModel();
$oWalletCurrencyModel = $oWalletCurrencyModel->findByCode($currency_code);
if (!$oWalletCurrencyModel) throw new ModelException('currency_code error');
$fee_amount = $oWalletCurrencyModel->computeTransferRate($amount, $oWalletCurrencyModel->transfer_rate);
//预计费率计算
if ($fee_amount <= 0) throw new ModelException('fee_amount error');
$desc = isset(self::DESC[$desc_key]) ? self::DESC[$desc_key] : '';
$resModel = $this->addWithdrawTransaction($platform_id, $uid, $oWalletCurrencyModel, $amount, $fee_amount, $desc_key, $desc, $remark);
if (!$resModel) throw new ModelException('addItem error');
$oWalletPlatformBalanceTransactionModel->updateItem([
'id' => $resWalletPlatformBalanceTransactionModel->id,
'from_user_transaction_id' => $resModel->id,
]);
$this->putWithdrawToQueue($resModel->id); //投递到队列处理
Db::commit();
Log::info('newWithdrawSucc', ['platform_id' => $platform_id, 'uid' => $uid, 'currency_code' => $currency_code, 'amount' => $amount]);
return $resModel;
} catch (\Exception $e) {
Db::rollBack();
Log::error('newWithdrawErr', ['platform_id' => $platform_id, 'uid' => $uid, 'currency_code' => $currency_code, 'amount' => $amount, 'msg' => $e->getMessage()]);
return false;
}
}
function addWithdrawTransaction($platform_id, $uid, $oWalletCurrencyModel, $amount, $fee_amount, $desc_key = null, $desc = '', $remark = ''): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
$insert = [
'type' => self::TYPE_WITHDRAW,
'status' => self::STATUS_WAITING_QUEUE,
'platform_id' => $platform_id,
'uid' => $uid,
'currency_id' => $oWalletCurrencyModel->id,
'currency_code' => $oWalletCurrencyModel->code,
'currency_type' => $oWalletCurrencyModel->type,
'received_amount' => abs($amount),
// 'entered_amount' => abs($entered_amount),
'fee_amount' => abs($fee_amount),
'desc_key' => $desc_key ?? '',
'desc' => $desc,
'remark' => $remark,
'created_at' => date('Y-m-d H:i:s'),
];
return $this->addItem($insert);
}
function addRechargeTransaction($resWalletAddrTransactionModel,$platform_id, $uid, $oWalletCurrencyModel, $amount, $desc_key = null, $desc = '', $remark = ''): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
$amount = abs($amount);
$insert = [
'type' => self::TYPE_RECHARGE,
'status' => self::STATUS_SUCCESS, //充提成功
'platform_id' => $platform_id,
'uid' => $uid,
'currency_id' => $oWalletCurrencyModel->id,
'currency_code' => $oWalletCurrencyModel->code,
'currency_type' => $oWalletCurrencyModel->type,
'from_wallet_addr_id' => $resWalletAddrTransactionModel->wallet_addr_id,
'wallet_addr' => $resWalletAddrTransactionModel->wallet_addr,
'from_wallet_transaction_id' => $resWalletAddrTransactionModel->id,
'received_amount' => $amount,
'entered_amount' => $amount,
'desc_key' => $desc_key ?? '',
'desc' => $desc,
'remark' => $remark,
'created_at' => date('Y-m-d H:i:s'),
];
return $this->addItem($insert);
}
function addTransactionWithPlatformBalance($resWalletAddrTransactionModel,$platform_id, $uid, $oWalletCurrencyModel, $amount, $desc_key = null, $desc = '', $remark = '')
{
try {
Db::beginTransaction();
$resModel = $this->addRechargeTransaction($resWalletAddrTransactionModel,$platform_id, $uid, $oWalletCurrencyModel, $amount, $desc_key, $desc, $remark);
if(!$resModel) throw new ModelException('addRechargeTransaction error');
$oWalletPlatformBalanceTransactionModel = new WalletPlatformBalanceTransactionModel();
$res = $oWalletPlatformBalanceTransactionModel->newRechargePlatformTransaction($resWalletAddrTransactionModel,$resModel,$amount, $platform_id, $oWalletCurrencyModel->code);
if(!$res) throw new ModelException('newRechargePlatformTransaction error');
Db::commit();
return true;
}catch (\Exception $e) {
Db::rollBack();
Log::error('addTransactionWithBalance', ['platform_id' => $platform_id, 'uid' => $uid, 'amount' => $amount, 'msg' => $e->getMessage()]);
return false;
}
}
//@@投递到rabbitmq队列处理
function putWithdrawToQueue($wallet_platform_user_transaction_id): void
{
$params = [
'wallet_platform_user_transaction_id' => $wallet_platform_user_transaction_id,
];
WalletPlatformUserWithdrawQueue::dispatch($params)->onQueue(QueueWalletPlatformUserWithdrawStruct::QUEUE_NAME);
}
//处理用户提现队列,发起链上提现
function withdrawConsumer($id): void
{
//@新增任务处理表
//查询前先检查redis中锁
$oWalletPlatformUserTransactionLock = new WalletPlatformUserTransactionLock();
$isLock = $oWalletPlatformUserTransactionLock->checkLock($oWalletPlatformUserTransactionLock->getWithdrawKey($id));
if ($isLock) return; //有锁就跳过
//加锁
$isLock = $oWalletPlatformUserTransactionLock->setLock($oWalletPlatformUserTransactionLock->getWithdrawKey($id));
if (!$isLock) return; //加锁失败
//查询任务
$resWalletPlatformUserTransactionModel = $this->findItem($id);
if (!$resWalletPlatformUserTransactionModel) throw new ModelException('id error');
if ($resWalletPlatformUserTransactionModel->type != self::TYPE_WITHDRAW) throw new ModelException('type error');
if ($resWalletPlatformUserTransactionModel->status != self::STATUS_WAITING_QUEUE) throw new ModelException('status error');
$resWalletPlatformUserTransactionModel->status = self::STATUS_CODE_PROCESSING;
$resWalletPlatformUserTransactionModel->save();
//获取提现地址
$oWalletAddrModel = new WalletAddrModel();
try {
$resWalletAddrModel = $oWalletAddrModel->findWithdrawAddrWithAmount($resWalletPlatformUserTransactionModel->received_amount, $resWalletPlatformUserTransactionModel->currency_code);
if (!$resWalletAddrModel) throw new ModelException('not found withdraw amount wallet addr');
} catch (ModelException $e) { //未找到足额提现金额钱包地址
$code = $e->getCode();
$msg = $e->getMessage();
$resWalletPlatformUserTransactionModel->status = self::STATUS_FAIL;
if ($code == ModelException::CODE_WALLET_AMOUNT_ADDR_NOT_FOUND) { //未找到足额提现金额钱包地址
$resWalletPlatformUserTransactionModel->desc_key = self::DESC_KEY_NOT_FOUND_WITHDRAW_AMOUNT_WALLET_ADDR;
$resWalletPlatformUserTransactionModel->desc = self::DESC[self::DESC_KEY_NOT_FOUND_WITHDRAW_AMOUNT_WALLET_ADDR];
}
if ($code == ModelException::CODE_WALLET_ADDR_BALANCE_LOW) { //提现钱包金额不足
$resWalletPlatformUserTransactionModel->desc_key = self::DESC_KEY_WITHDRAW_WALLET_AMOUNT_LOW;
$resWalletPlatformUserTransactionModel->desc = self::DESC[self::DESC_KEY_WITHDRAW_WALLET_AMOUNT_LOW];
}
$resWalletPlatformUserTransactionModel->save();
$this->withdrawFailUnLock($id); //解锁
return;
}
try {
$resWalletPlatformUserTransactionModel->from_wallet_addr_id = $resWalletAddrModel->id;
$resWalletPlatformUserTransactionModel->wallet_addr = $resWalletAddrModel->addr;
$resWalletPlatformUserTransactionModel->save();
//增加钱包账变
$oWalletAddrTransactionModel = new WalletAddrTransactionModel();
$resWalletAddrTransactionModel = $oWalletAddrTransactionModel->newPlatformUserWithdraw(
$resWalletAddrModel->id,
$resWalletPlatformUserTransactionModel->entered_amount,
$resWalletPlatformUserTransactionModel->id
);
if (!$resWalletAddrTransactionModel) {
$this->withdrawFailUnLock($id); //解锁
return;
}
//调用链上接口
$resChain = $oWalletAddrModel->callWalletAddrChainTransferApi($resWalletPlatformUserTransactionModel->id, $resWalletAddrModel->id);
if (!$resChain) { //链上提现失败
$resWalletPlatformUserTransactionModel->status = self::STATUS_FAIL;
$resWalletPlatformUserTransactionModel->desc_key = self::DESC_KEY_WITHDRAW_CALL_CHAIN_WRONG;
$resWalletPlatformUserTransactionModel->desc = self::DESC[self::DESC_KEY_WITHDRAW_CALL_CHAIN_WRONG];
$resWalletPlatformUserTransactionModel->save();
//解冻钱包余额
$oWalletAddrTransactionModel->platformUserWithdrawCallback($resWalletAddrTransactionModel->id, $resWalletAddrTransactionModel->received_amount, WalletAddrTransactionModel::STATUS_FAIL);
$this->withdrawFailUnLock($id); //解锁
return;
}
$resWalletPlatformUserTransactionModel->status = self::STATUS_CHAIN_WAITING;
$resWalletPlatformUserTransactionModel->save();
$this->withdrawFailUnLock($id); //解锁
} catch (\Exception $e) {
Log::error('withdrawConsumer', ['id' => $id, 'msg' => $e->getMessage()]);
$this->withdrawFailUnLock($id); //解锁
}
}
//用户提现失败解锁并返还平台余额
function withdrawFailUnLock($id): void
{
//返还用户余额
$oWalletPlatformBalanceTransactionModel = new WalletPlatformBalanceTransactionModel();
$oWalletPlatformBalanceTransactionModel->withdrawErrByUserTransactionId($id);
//解锁
$oWalletPlatformUserTransactionLock = new WalletPlatformUserTransactionLock();
$oWalletPlatformUserTransactionLock->unLock($oWalletPlatformUserTransactionLock->getWithdrawKey($id));
}
//提现链上回调监听
function listenWithdrawCallback($wallet_addr_transaction_id): void
{
Log::info('listenWithdrawCallback', ['wallet_addr_transaction_id' => $wallet_addr_transaction_id]);
//查找钱包账变
$oWalletAddrTransactionModel = new WalletAddrTransactionModel();
$resWalletAddrTransactionModel = $oWalletAddrTransactionModel->findItem($wallet_addr_transaction_id);
if (!$resWalletAddrTransactionModel) throw new ModelException('wallet_addr_transaction_id error');
if ($resWalletAddrTransactionModel->type !== WalletAddrTransactionModel::TYPE_TRANSFER) throw new ModelException('wallet_addr_transaction_type error');
if (!in_array($resWalletAddrTransactionModel->status, [WalletAddrTransactionModel::STATUS_SUCCESS, WalletAddrTransactionModel::STATUS_FAIL])) throw new ModelException('status error');
if ($resWalletAddrTransactionModel->status == WalletAddrTransactionModel::STATUS_SUCCESS) $status = self::STATUS_SUCCESS;
if ($resWalletAddrTransactionModel->status == WalletAddrTransactionModel::STATUS_FAIL) $status = self::STATUS_FAIL;
if (empty($resWalletAddrTransactionModel->platform_user_transaction_id)) throw new ModelException('platform_user_transaction_id error');
$id = $resWalletAddrTransactionModel->platform_user_transaction_id;
if (!in_array($status, [self::STATUS_SUCCESS, self::STATUS_FAIL])) throw new ModelException('status error');
$resWalletPlatformUserTransactionModel = $this->findItem($id);
if (!$resWalletPlatformUserTransactionModel) throw new ModelException('id error');
if ($resWalletPlatformUserTransactionModel->type != self::TYPE_WITHDRAW) throw new ModelException('type error');
if ($resWalletPlatformUserTransactionModel->status != self::STATUS_CHAIN_WAITING) throw new ModelException('status error');
//用户账变处理
$resWalletPlatformUserTransactionModel->status = $status;
$resWalletPlatformUserTransactionModel->save();
//平台余额和账变处理
$oWalletPlatformBalanceTransactionModel = new WalletPlatformBalanceTransactionModel();
if ($status == self::STATUS_SUCCESS) { //成功
$oWalletPlatformBalanceTransactionModel->withdrawSuccByUserTransactionId($id);
} else { //失败
$oWalletPlatformBalanceTransactionModel->withdrawErrByUserTransactionId($id);
}
}
function listenRechargeCallback($wallet_addr_transaction_id): void
{
Log::info('listenRechargeCallback', ['wallet_addr_transaction_id' => $wallet_addr_transaction_id]);
//查找钱包账变
$oWalletAddrTransactionModel = new WalletAddrTransactionModel();
$resWalletAddrTransactionModel = $oWalletAddrTransactionModel->findItem($wallet_addr_transaction_id);
if (!$resWalletAddrTransactionModel) throw new ModelException('wallet_addr_transaction_id error');
if ($resWalletAddrTransactionModel->type !== WalletAddrTransactionModel::TYPE_RECHARGE) throw new ModelException('wallet_addr_transaction_type error');
if (!in_array($resWalletAddrTransactionModel->status, [WalletAddrTransactionModel::STATUS_SUCCESS, WalletAddrTransactionModel::STATUS_FAIL])) throw new ModelException('status error');
if ($resWalletAddrTransactionModel->status == WalletAddrTransactionModel::STATUS_SUCCESS) $status = self::STATUS_SUCCESS;
if ($resWalletAddrTransactionModel->status == WalletAddrTransactionModel::STATUS_FAIL) $status = self::STATUS_FAIL;
if ($status != self::STATUS_SUCCESS) throw new ModelException('status not success');
$oWalletCurrencyModel = new WalletCurrencyModel();
$resWalletCurrencyModel = $oWalletCurrencyModel->findItem($resWalletAddrTransactionModel->currency_id);
//查找用户绑定钱包地址
$oWalletPlatformUserWalletAddrModel = new WalletPlatformUserWalletAddrModel();
$resWalletPlatformUserWalletAddrModel = $oWalletPlatformUserWalletAddrModel->findByWalletAddrId($resWalletAddrTransactionModel->wallet_addr_id);
if (!$resWalletPlatformUserWalletAddrModel) throw new ModelException('找不到wallet_addr_id绑定用户');
//给用户增加账变/平台增加账变增加余额
$this->addTransactionWithPlatformBalance(
$resWalletAddrTransactionModel,
$resWalletPlatformUserWalletAddrModel->platform_id,
$resWalletPlatformUserWalletAddrModel->uid,
$resWalletCurrencyModel,
$resWalletAddrTransactionModel->received_amount,
);
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace App\Models\Wallet\PlatformUser;
use App\Exceptions\ModelException;
use App\Models\Wallet\Base\WalletBaseModel;
class WalletPlatformUserWalletAddrHistoryModel extends WalletBaseModel
{
protected $table = 'wallet_platform_user_wallet_addr';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'desc',
'platform_id',
'uid',
'username',
'nickname',
'wallet_addr_id',
'wallet_addr',
'currency_id',
'currency_code',
'created_at',
];
const TYPE_BIND = 1;
const TYPE_UNBIND = 2;
const TYPE = [
self::TYPE_BIND => '绑定',
self::TYPE_UNBIND => '解绑',
];
function addUserWalletAddrHistory($aItem,$type,$desc = ''): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|array|null
{
if(!in_array($type,self::TYPE)) throw new ModelException('type error');
unset($aItem['id']);//去掉id(主键)
$aItem['type'] = $type;
$aItem['desc'] = $desc;
$sDateTime = date('Y-m-d H:i:s');
$aItem['created_at'] = $sDateTime;
return $this->addItem($aItem);
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace App\Models\Wallet\PlatformUser;
use App\Exceptions\ModelException;
use App\Models\Wallet\Base\WalletBaseModel;
use App\Models\Wallet\Wallet\WalletAddrModel;
use App\Tools\Times;
use Illuminate\Support\Facades\DB;
class WalletPlatformUserWalletAddrModel extends WalletBaseModel
{
protected $table = 'wallet_platform_user_wallet_addr';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'platform_id',
'uid',
'username',
'nickname',
'wallet_addr_id',
'wallet_addr',
'currency_id',
'currency_code',
'created_at',
];
//根据平台用户生成新充值地址,或者解绑旧有地址
function genUserWalletAddr($platform_id, $uid, $currency_code,$mode = WalletPlatformUserWalletAddrHistoryModel::TYPE_BIND): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
//先删除原有地址
$resOldModel = $this->findUserWalletAddr($platform_id, $uid, $currency_code);
if($mode == WalletPlatformUserWalletAddrHistoryModel::TYPE_BIND && $resOldModel){ //默认检测是否已经绑定过
throw new ModelException('已经绑定过地址');
}
try {
DB::beginTransaction();
//从钱包地址表取值
$walletAddrModel = new WalletAddrModel();
$oWalletPlatformUserWalletAddrHistoryModel = new WalletPlatformUserWalletAddrHistoryModel();
$walletAddrModel = $walletAddrModel->findUnusedAddrPutUsing($currency_code);
if(!$walletAddrModel) throw new ModelException('获取新地址失败');
if($mode == WalletPlatformUserWalletAddrHistoryModel::TYPE_UNBIND){
if($resOldModel){
$res = $this->delItem($resOldModel->id);
if(!$res) throw new ModelException('删除原有地址失败');
$res = $oWalletPlatformUserWalletAddrHistoryModel->addUserWalletAddrHistory($resOldModel->toArray(),WalletPlatformUserWalletAddrHistoryModel::TYPE_UNBIND);
if(!$res) throw new ModelException('增加历史绑定地址失败');
}
}
$insert = [
'platform_id' => $platform_id,
'uid' => $uid,
'wallet_addr_id' => $walletAddrModel->id,
'wallet_addr' => $walletAddrModel->addr,
'currency_id' => $walletAddrModel->currency_id,
'currency_code' => $walletAddrModel->currency_code,
'created_at' => Times::getNowDateTime(),
];
$resModel = $this->addItem($insert);
if($resModel) $oWalletPlatformUserWalletAddrHistoryModel->addUserWalletAddrHistory($resModel->toArray(),WalletPlatformUserWalletAddrHistoryModel::TYPE_BIND);
DB::commit();
}catch (\Exception $e) {
DB::rollBack();
throw $e;
}
return $resModel;
}
function findUserWalletAddr($platform_id, $uid, $currency_code): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null
{
return $this->findItemByWhere(['platform_id' => $platform_id, 'uid' => $uid, 'currency_code' => $currency_code]);
}
function findByWalletAddrId($wallet_addr_id): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Builder|array|null
{
return $this->findItemByWhere(['from_wallet_addr_id' => $wallet_addr_id]);
}
}

View File

@ -0,0 +1,312 @@
<?php
namespace App\Models\Wallet\Wallet;
use App\Exceptions\ModelException;
use App\Jobs\WalletAddrTransactionChangeQueue;
use App\Models\Wallet\Base\WalletBaseModel;
use App\Models\Wallet\Platform\WalletPlatformBalanceTransactionModel;
use App\Models\Wallet\Platform\WalletPlatformModel;
use App\Models\Wallet\PlatformUser\WalletPlatformUserTransactionModel;
use App\Models\Wallet\PlatformUser\WalletPlatformUserWalletAddrModel;
use App\Structs\QueueWalletAddrTransactionChangeStruct;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class WalletAddrModel extends WalletBaseModel
{
protected $table = 'wallet_addr';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'role',
'type',
'use_status',
'addr',
'secret',
'desc_key',
'desc',
'remark',
'currency_id',
'currency_code',
'total_amount',
'frozen_amount',
'available_amount',
'recharge_num',
'recharge_amount',
'withdraw_num',
'withdraw_amount',
'created_at',
'updated_at',
];
const ROLE_USER = 1;
const ROLE_SYSTEM = 2;
const ROLE = [
self::ROLE_USER => '用户',
self::ROLE_SYSTEM => '系统',
];
const TYPE_CASH = 1;
const TYPE_CRYPTO_COIN = 2;
const TYPE = [
self::TYPE_CASH => '现金',
self::TYPE_CRYPTO_COIN => '加密货币',
];
const USE_STATUS_UNUSED = 1;
const USE_STATUS_USING = 2;
const USE_STATUS_USED = 3;
const USE_STATUS = [
self::USE_STATUS_UNUSED => '未使用',
self::USE_STATUS_USING => '使用中',
self::USE_STATUS_USED => '已使用',
];
const DESC_KEY_USER_RECHARGE = 'userRecharge';
const DESC_KEY_USER_WITHDRAW = 'userWithdraw';
const DESC = [
self::DESC_KEY_USER_RECHARGE => '用户充值',
self::DESC_KEY_USER_WITHDRAW => '用户提现',
];
function addAddr($addr, $secret, $currency_code = WalletCurrencyModel::CODE_USDT_TRC20, $desc_key = '', $desc = '', $remark = '', $available_amount = 0, $role = self::ROLE_USER, $type = self::TYPE_CRYPTO_COIN, $use_status = self::USE_STATUS_UNUSED): int
{
$oWalletCurrencyModel = (new WalletCurrencyModel())->findByCode($currency_code, ['id', 'code']);
if (!$oWalletCurrencyModel) throw new ModelException('币种不存在');
return $this->newQuery()->insertGetId([
'role' => $role,
'type' => $type,
'use_status' => $use_status,
'addr' => $addr,
'secret' => $secret,
'desc_key' => $desc_key,
'desc' => $desc,
'remark' => $remark,
'currency_id' => $oWalletCurrencyModel->id,
'currency_code' => $oWalletCurrencyModel->code,
'total_amount' => $available_amount,
'available_amount' => $available_amount,
'created_at' => date('Y-m-d H:i:s'),
]);
}
function findAddr($currency_code = WalletCurrencyModel::CODE_USDT_TRC20, $use_status = self::USE_STATUS_UNUSED): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|null
{
return $this->newQuery()->where('currency_code', $currency_code)->where('use_status', $use_status)->first();
}
function findUnusedAddrPutUsing($currency_code = WalletCurrencyModel::CODE_USDT_TRC20): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|null
{
$resModel = $this->newQuery()->where('currency_code', $currency_code)->where('use_status', self::USE_STATUS_UNUSED)->first();
if (!$resModel) {
//@@获取不到地址就发送到队列生成新地址
$this->makeNewWalletAddr($currency_code);
throw new ModelException('获取地址失败');
}
$resModel->use_status = self::USE_STATUS_USING;
$resModel->save();
return $resModel;
}
function makeNewWalletAddr($currency_code = WalletCurrencyModel::CODE_USDT_TRC20)
{
}
function changeUseStatus($id, $use_status): int
{
return $this->newQuery()->where('id', $id)->update(['use_status' => $use_status]);
}
function incAvailableAmount($id, $amount): int
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['total_amount', 'available_amount']);
if (!$oModel) throw new ModelException('找不到wallet_addr_id');
$oModel->frozen_amount = Db::raw('available_amount + ' . $amount);
$oModel->total_amount = Db::raw('total_amount + ' . $amount);
return $oModel->save();
}
function decAvailableAmount($id, $amount): int
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['total_amount', 'available_amount']);
if (!$oModel) throw new ModelException('找不到wallet_addr_id');
$oModel->frozen_amount = Db::raw('available_amount - ' . $amount);
$oModel->total_amount = Db::raw('total_amount - ' . $amount);
return $oModel->save();
}
function decFrozenAmountById($id, $amount): int
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['total_amount', 'frozen_amount']);
if (!$oModel) throw new ModelException('找不到wallet_addr_id');
$oModel->frozen_amount = Db::raw('frozen_amount - ' . $amount);
$oModel->total_amount = Db::raw('total_amount - ' . $amount);
return $oModel->save();
}
function unFrozenAmountById($id, $amount): int
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['frozen_amount', 'available_amount']);
if (!$oModel) throw new ModelException('找不到wallet_addr_id');
$oModel->frozen_amount = Db::raw('frozen_amount - ' . $amount);
$oModel->available_amount = Db::raw('available_amount + ' . $amount);
return $oModel->save();
}
function frozenAmountById($id, $amount): int
{
$amount = abs($amount);
$oModel = $this->newQuery()->where('id', $id)->first(['frozen_amount', 'available_amount']);
if (!$oModel) throw new ModelException('找不到wallet_addr_id');
$oModel->frozen_amount = Db::raw('frozen_amount + ' . $amount);
$oModel->available_amount = Db::raw('available_amount - ' . $amount);
return $oModel->save();
}
/**
* 充值回调监听
* @throws ModelException
*/
function walletAddrTransactionChangeConsumer($wallet_addr_transaction_id,$wallet_addr_transaction_type): void
{
Log::info('walletAddrTransactionChangeConsumer', ['wallet_addr_transaction_id' => $wallet_addr_transaction_id,]);
$oWalletPlatformUserTransactionModel = new WalletPlatformUserTransactionModel();
if($wallet_addr_transaction_type == WalletAddrTransactionModel::TYPE_RECHARGE){
$oWalletPlatformUserTransactionModel->listenRechargeCallback($wallet_addr_transaction_id);
}
if($wallet_addr_transaction_type == WalletAddrTransactionModel::TYPE_TRANSFER){
$oWalletPlatformUserTransactionModel->listenWithdrawCallback($wallet_addr_transaction_id);
}
}
//提现链上回调监听
function listenWalletAddrCallback($chain_sn, $token, $type, $addr, $amount, $status): void
{
//@@新增表记录每个地址的监听消息
Log::info('listenWalletAddrCallbackParams', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status]);
if (!in_array($type, [WalletAddrTransactionModel::TYPE_RECHARGE, WalletAddrTransactionModel::TYPE_TRANSFER])) {
Log::error('listenWalletAddrCallbackErr', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'error' => 'type类型错误']);
throw new ModelException('type类型错误');
}
//充值不成功默认不处理
if($type == WalletAddrTransactionModel::TYPE_RECHARGE && $status != WalletAddrTransactionModel::STATUS_SUCCESS){
Log::error('listenWalletAddrCallbackStatus', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'error' => '充值失败']);
throw new ModelException('链上充值失败');
}
try {
Db::beginTransaction();
$oWalletCurrencyModel = (new WalletCurrencyModel())->findByToken($token);
if (!$oWalletCurrencyModel) {
Log::error('listenWalletAddrCallbackErr', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'error' => '币种不存在']);
throw new ModelException('币种不存在');
}
//查找钱包地址
$resModel = $this->findItemByWhere([
'currency_id' => $oWalletCurrencyModel->id,
'addr' => $addr,
]);
if (!$resModel) {
Log::error('listenWalletAddrCallbackErr', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'error' => '地址不存在']);
throw new ModelException('地址不存在');
}
if ($type == WalletAddrTransactionModel::TYPE_RECHARGE) { //充值到账
$res = $this->incAvailableAmount($resModel->id, $amount);
} else { //提现到账
//查询账变表提现记录中是否存在
$oWalletAddrTransactionModel = new WalletAddrTransactionModel();
$resWalletAddrTransactionModel = $oWalletAddrTransactionModel->findItemByWhere([
'wallet_addr_id' => $resModel->id,
'type' => WalletAddrTransactionModel::TYPE_TRANSFER,
'block_sn' => $chain_sn,
]);
if ($resWalletAddrTransactionModel->status != WalletAddrTransactionModel::STATUS_WAITING_CHAIN_CALLBACK) { //已经处理过
Log::error('listenWalletAddrCallbackErr', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'wallet_addr_id' => $resModel->id, 'wallet_transaction_id' => $resWalletAddrTransactionModel->id, 'error' => '该提现条目已经处理过']);
throw new ModelException('该提现条目已经处理过');
}
if ($resWalletAddrTransactionModel) { //存在就扣除冻结金额
$res = $resWalletAddrTransactionModel->platformUserWithdrawCallback($resModel->id,$amount,$status);
} else { //未找到就直接扣除余额
$res = $this->decAvailableAmount($resModel->id, $amount);
}
}
if (!$res) {
Log::error('listenWalletAddrCallbackErr', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'wallet_addr_id' => $resModel->id, 'error' => '修改地址余额失败']);
throw new ModelException('修改地址余额失败');
}
if ($type == WalletAddrTransactionModel::TYPE_TRANSFER && $resWalletAddrTransactionModel) { //提现已有账变,修改账变状态即可
$res = $oWalletAddrTransactionModel->updateItem([
'id' => $resWalletAddrTransactionModel->id,
'status' => $status,
]);
if (!$res) {
Log::error('listenWalletAddrCallbackErr', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'wallet_addr_id' => $resModel->id, 'wallet_transaction_id' => $resWalletAddrTransactionModel->id, 'error' => '修改账变状态失败']);
throw new ModelException('修改账变状态失败');
}
} else { //充值和未记录的转账,增加到钱包账变记录
$oWalletAddrTransactionModel = new WalletAddrTransactionModel();
$res = $oWalletAddrTransactionModel->addTransaction($resModel->id, $type, WalletAddrTransactionModel::ROLE_SYSTEM, $status, $amount);
if (!$res) {
Log::error('listenWalletAddrCallbackErr', ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'wallet_addr_id' => $resModel->id, 'error' => '增加到钱包账变记录失败']);
throw new ModelException('增加到钱包账变记录失败');
}
}
//成功记录日志
$log = ['token' => $token, 'addr' => $addr, 'amount' => $amount, 'status' => $status, 'wallet_addr_id' => $resModel->id, 'info' => '监听钱包处理成功'];
if (isset($resWalletAddrTransactionModel) && $resWalletAddrTransactionModel->id) $log['wallet_transaction_id'] = $resWalletAddrTransactionModel->id;
Log::info('listenWalletAddrCallbackSucc', $log);
//投递到钱包账变队列
self::putWalletAddrTransactionChangeQueue($resWalletAddrTransactionModel->id, $resWalletAddrTransactionModel->type);
Db::commit();
} catch (\Exception $e) {
Db::rollBack();
throw $e;
}
}
static function putWalletAddrTransactionChangeQueue($wallet_addr_transaction_id, $type): void
{
WalletAddrTransactionChangeQueue::dispatch([
'wallet_addr_transaction_id_id' => $wallet_addr_transaction_id,
'wallet_addr_transaction_type' => $type,
])->onQueue(QueueWalletAddrTransactionChangeStruct::QUEUE_NAME);
}
function findWithdrawAddrWithAmount($amount, $currency_code = WalletCurrencyModel::CODE_USDT_TRC20): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|null
{
//获取当前系统使用中的热钱包
$oModel = $this->findItemByWhere([
'currency_code' => $currency_code,
'use_status' => self::USE_STATUS_USING,
'role' => self::ROLE_SYSTEM,
['available_amount', '>=', $amount]
]);
if (!$oModel) throw new ModelException(ModelException::CODE[ModelException::CODE_WALLET_AMOUNT_ADDR_NOT_FOUND], ModelException::CODE_WALLET_AMOUNT_ADDR_NOT_FOUND);
if ($oModel->available_amount < $amount) throw new ModelException(ModelException::CODE[ModelException::CODE_WALLET_ADDR_BALANCE_LOW], ModelException::CODE_WALLET_ADDR_BALANCE_LOW);
return $oModel;
}
//@@调用链上接口,发起转账,要返回链上交易订单号用于追踪并更新到数据库
function callWalletAddrChainTransferApi($id, $wallet_addr_id): bool
{
return true;
}
}

View File

@ -0,0 +1,208 @@
<?php
namespace App\Models\Wallet\Wallet;
use App\Exceptions\ModelException;
use App\Models\Wallet\Base\WalletBaseModel;
use App\Models\Wallet\Platform\WalletPlatformBalanceModel;
use App\Tools\Math;
use App\Tools\Times;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class WalletAddrTransactionModel extends WalletBaseModel
{
protected $table = 'wallet_addr_transaction';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'block_sn',
'type',
'role',
'wallet_addr_id',
'currency_id',
'currency_code',
'received_amount',
'entered_amount',
'fee_amount',
'before_total_amount',
'after_total_amount',
'desc_key',
'desc',
'remark',
'platform_user_transaction_id',
'sign',
'created_at',
];
const TYPE_RECHARGE = 1;
const TYPE_TRANSFER = 2;
const TYPE_FROZEN = 3;
const TYPE_UN_FROZEN = 4;
const TYPE = [
self::TYPE_RECHARGE => '充值',
self::TYPE_TRANSFER => '转账',
self::TYPE_FROZEN => '冻结',
self::TYPE_UN_FROZEN => '解冻',
];
const ROLE_USER = 1;
const ROLE_SYSTEM = 2;
const ROLE_ADMIN = 3;
const ROLE_OTHER = 4;
const ROLE = [
self::ROLE_USER => '用户操作',
self::ROLE_SYSTEM => '系统操作',
self::ROLE_ADMIN => '管理员操作',
self::ROLE_OTHER => '其他操作',
];
const STATUS_WAITING_CHAIN_CALLBACK = 1;
const STATUS_SUCCESS = 2;
const STATUS_FAIL = 3;
const STATUS = [
self::STATUS_WAITING_CHAIN_CALLBACK => '等待链回调',
self::STATUS_SUCCESS => '成功',
self::STATUS_FAIL => '失败',
];
const DESC_KEY_WITHDRAW_FROZEN = 'withdrawFrozen';
const DESC_KEY_WITHDRAW_UN_FROZEN = 'withdrawUnFrozen';
const DESC_KEY_WITHDRAW_DETECT = 'withdrawDetect';
const DESC = [
self::DESC_KEY_WITHDRAW_FROZEN => '提现冻结',
self::DESC_KEY_WITHDRAW_UN_FROZEN => '提现解冻',
self::DESC_KEY_WITHDRAW_DETECT => '提现成功扣除',
];
//@@钱包账变处理
function addTransaction(
$wallet_addr_id,
$type,
$role,
$status,
$received_amount,
$entered_amount = null,
$fee_amount = null,
$desc_key = '',
$remark = '',
$platform_user_transaction_id = null,
): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
$entered_amount = abs($entered_amount);
$oWalletAddrModel = new WalletAddrModel();
$resWalletAddrModel = $oWalletAddrModel->findItem($wallet_addr_id);
$received_amount = abs($received_amount);
if (empty($fee_amount)) $fee_amount = 0;
if (empty($entered_amount)) $entered_amount = Math::bcSub($received_amount, $fee_amount);
$desc = '';
if (!empty($desc_key) && isset(self::DESC[$desc_key])) $desc = self::DESC[$desc_key];
if ($type == self::TYPE_RECHARGE) { //充值
$after_total_amount = Math::bcAdd($oWalletAddrModel->total_amount, $entered_amount);
} elseif ($type == self::TYPE_TRANSFER) { //转账
$after_total_amount = Math::bcSub($oWalletAddrModel->total_amount, $entered_amount);
} elseif (in_array($type, [self::TYPE_FROZEN, self::TYPE_UN_FROZEN])) { //冻结/解冻
$after_total_amount = $oWalletAddrModel->total_amount;
} else {
throw new ModelException('未知类型');
}
$insert = [
'type' => $type,
'role' => $role,
'status' => $status,
'currency_id' => $resWalletAddrModel->currency_id,
'currency_code' => $resWalletAddrModel->currency_code,
'received_amount' => $received_amount,
'entered_amount' => $entered_amount,
'fee_amount' => $fee_amount,
'before_total_amount' => $oWalletAddrModel->total_amount,
'after_total_amount' => $after_total_amount,
'desc_key' => $desc_key,
'desc' => $desc,
'remark' => $remark,
'platform_user_transaction_id' => $platform_user_transaction_id,
];
// $insert['sign'] = '';
$insert['created_at'] = Times::getNowDateTime();
return $this->addItem($insert);
}
//用户发起提现
function newPlatformUserWithdraw(
$wallet_addr_id,
$received_amount,
$platform_user_transaction_id,
): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|bool
{
try {
Db::beginTransaction();
//查询钱包
$oWalletAddrModel = new WalletAddrModel();
$resWalletAddrModel = $oWalletAddrModel->findItem($wallet_addr_id);
if (!$resWalletAddrModel) return false;
if (Math::bcComp($resWalletAddrModel->available_amount, $received_amount) == -1) throw new ModelException('余额不足');
//冻结钱包余额
$res = $oWalletAddrModel->frozenAmountById($wallet_addr_id, $received_amount);
if (!$res) throw new ModelException('钱包余额冻结失败');
//增加钱包账变
$res = $this->addTransaction(
$wallet_addr_id,
$type = self::TYPE_TRANSFER,
$role = self::ROLE_USER,
$status = self::STATUS_WAITING_CHAIN_CALLBACK,
$received_amount,
$entered_amount = null,
$fee_amount = null,
$desc_key = '',
$remark = '',
$platform_user_transaction_id,
);
if (!$res) throw new ModelException('钱包账变失败');
Db::commit();
return $res;
} catch (\Exception $e) {
Db::rollBack();
Log::error('newPlatformUserWithdraw', ['wallet_addr_id' => $wallet_addr_id, 'received_amount' => $received_amount, 'platform_user_transaction_id' => $platform_user_transaction_id, 'msg' => $e->getMessage()]);
return false;
}
}
function platformUserWithdrawCallback($wallet_transaction_id, $amount, $status)
{
if (!in_array($status, [self::STATUS_SUCCESS, self::STATUS_FAIL])) throw new ModelException('提现状态错误');
$resModel = $this->findItem($wallet_transaction_id);
if (!$resModel) throw new ModelException('钱包账变不存在');
$oWalletAddrModel = new WalletAddrModel();
try {
Db::beginTransaction();
if ($status == self::STATUS_SUCCESS) {
$res = $oWalletAddrModel->decFrozenAmountById($resModel->wallet_addr_id, $amount);
if (!$res) throw new ModelException('扣除冻结失败');
} else if ($status == WalletAddrTransactionModel::STATUS_FAIL) { //失败就解冻金额
$resModel->status = WalletAddrTransactionModel::STATUS_FAIL;
$res = $resModel->save();
if (!$res) throw new ModelException('更新状态失败');
$res = $oWalletAddrModel->unFrozenAmountById($resModel->id, $resModel->received_amount);
if (!$res) throw new ModelException('解冻失败');
}
Db::commit();
return true;
} catch (\Exception $e) {
Db::rollBack();
Log::error('platformUserWithdrawCallback', ['wallet_transaction_id' => $wallet_transaction_id, 'amount' => $amount, 'status' => $status, 'msg' => $e->getMessage()]);
return false;
}
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Models\Wallet\Wallet;
use App\Models\Wallet\Base\WalletBaseModel;
use App\Tools\Math;
class WalletCurrencyModel extends WalletBaseModel
{
protected $table = 'wallet_currency';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'type',
'name',
'code',
'token',
'transfer_rate',
'desc',
'created_at',
];
const CODE_USDT_TRC20 = 'USDT_TRC20';
function findByCode($code,$columns = ['*']): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|null
{
return $this->newQuery()->where('code',$code)->first($columns);
}
function findByToken($token,$columns = ['*']): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder|null
{
return $this->newQuery()->where('token',$token)->first($columns);
}
function computeTransferRate($amount,$rate): string
{
if(empty($amount)) return 0;
if(empty($rate)) return 0;
return Math::bcMul(abs($amount),$rate,Math::SCALE_4);
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\Models\Wallet\Wallet;
use App\Models\Wallet\Base\WalletBaseModel;
class WalletSettingModel extends WalletBaseModel
{
protected $table = 'wallet_setting';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'name',
'value',
'created_at',
'updated_at',
];
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Structs;
class QueueAddPostStruct
{
const QUEUE_NAME = 'queue_add_post';
const PARAMS = [
'type'=>'',
'id'=>'',
];
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Structs;
class QueueUserActiveStatusStruct
{
const QUEUE_NAME = 'queue_user_active_status';
const PARAMS = [
'uid'=>'',
'queueCreatedAt'=>'',
];
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Structs;
class QueueWalletAddrTransactionChangeStruct
{
const QUEUE_NAME = 'queue_wallet_addr_transaction_change';
const PARAMS = [
'wallet_addr_transaction_id'=>'',
'wallet_addr_transaction_type'=>'',
];
}

View File

@ -0,0 +1,11 @@
<?php
namespace App\Structs;
class QueueWalletPlatformUserWithdrawStruct
{
const QUEUE_NAME = 'wallet_platform_user_transaction_id';
const PARAMS = [
'id'=>'',
];
}

View File

@ -5,7 +5,7 @@ namespace App\Tools;
class CollectOffsetLimit class CollectOffsetLimit
{ {
private $offset = 0; private $offset = 0;
private $limit = 2000; private $limit = 1000;
private $page = 0; private $page = 0;
private $iTotalCount = null; private $iTotalCount = null;
@ -34,7 +34,7 @@ class CollectOffsetLimit
{ {
$this->countPage(); $this->countPage();
if($this->iTotalCount === null) $this->iTotalCount = $this->fCountFun; if($this->iTotalCount === null) $this->iTotalCount = $this->fCountFun;
if($this->iTotalCount === 0 | $this->page === 0) return []; if($this->iTotalCount === 0 || $this->page === 0) return [];
for( $iPage = 1; $iPage <= $this->page; $iPage++){ for( $iPage = 1; $iPage <= $this->page; $iPage++){
$this->offset = ($iPage - 1) * $this->limit; $this->offset = ($iPage - 1) * $this->limit;
$fun($this->offset,$this->limit); $fun($this->offset,$this->limit);

31
app/Tools/Math.php Normal file
View File

@ -0,0 +1,31 @@
<?php
namespace App\Tools;
class Math
{
const SCALE = 8;
const SCALE_4 = 4;
const SCALE_6= 6;
static function bcMul($a1,$a2,$scale = self::SCALE): string
{
return bcmul($a1,$a2,$scale);
}
static function bcSub($a1,$a2,$scale = self::SCALE): string
{
return bcsub($a1,$a2,$scale);
}
static function bcAdd($a1,$a2,$scale = self::SCALE): string
{
return bcadd($a1,$a2,$scale);
}
static function bcComp($a1,$a2,$scale = self::SCALE): string
{
return bccomp($a1,$a2,$scale);
}
}

12
app/Tools/Times.php Normal file
View File

@ -0,0 +1,12 @@
<?php
namespace App\Tools;
class Times
{
//获取当前时间
public static function getNowDateTime($format = 'Y-m-d H:i:s'): string
{
return date($format);
}
}

View File

@ -51,6 +51,21 @@ class Tools
return Str::orderedUuid(); return Str::orderedUuid();
} }
static function JonsEncode(array $aData): string
{
return json_encode($aData, JSON_UNESCAPED_UNICODE);
}
static function JonsDecode(string $aData): string
{
return json_decode($aData, JSON_UNESCAPED_UNICODE);
}
static function getMd5($value,$salt = ''): string
{
return md5(md5($value.$salt));
}
} }

View File

@ -2,14 +2,19 @@
"name": "laravel/laravel", "name": "laravel/laravel",
"type": "project", "type": "project",
"description": "The skeleton application for the Laravel framework.", "description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"], "keywords": [
"laravel",
"framework"
],
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": "^8.1", "php": "^8.1",
"easyswoole/spl": "^2.1",
"guzzlehttp/guzzle": "^7.8", "guzzlehttp/guzzle": "^7.8",
"laravel/framework": "^10.10", "laravel/framework": "^10.10",
"laravel/sanctum": "^3.3", "laravel/sanctum": "^3.3",
"laravel/tinker": "^2.8" "laravel/tinker": "^2.8",
"ext-bcmath": "*"
}, },
"require-dev": { "require-dev": {
"fakerphp/faker": "^1.9.1", "fakerphp/faker": "^1.9.1",

57
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "04667de44913e2c1bc4de60fd5fa0d04", "content-hash": "779c2c416d83ff65448d583b525c3691",
"packages": [ "packages": [
{ {
"name": "brick/math", "name": "brick/math",
@ -434,6 +434,61 @@
], ],
"time": "2023-08-10T19:36:49+00:00" "time": "2023-08-10T19:36:49+00:00"
}, },
{
"name": "easyswoole/spl",
"version": "2.1.1",
"source": {
"type": "git",
"url": "https://github.com/easy-swoole/spl.git",
"reference": "365679df769e48e5c6d2e073d214ade3d26dbe38"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/easy-swoole/spl/zipball/365679df769e48e5c6d2e073d214ade3d26dbe38",
"reference": "365679df769e48e5c6d2e073d214ade3d26dbe38",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-json": "*",
"ext-simplexml": "*",
"php": ">=8.1.0"
},
"require-dev": {
"easyswoole/phpunit": "^1.0",
"easyswoole/swoole-ide-helper": "^1.0"
},
"type": "library",
"autoload": {
"psr-4": {
"EasySwoole\\Spl\\": "src/",
"EasySwoole\\Spl\\Test\\": "test/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "YF",
"email": "291323003@qq.com"
}
],
"description": "php stander lib",
"homepage": "https://www.easyswoole.com/",
"keywords": [
"async",
"easyswoole",
"framework",
"swoole"
],
"support": {
"issues": "https://github.com/easy-swoole/spl/issues",
"source": "https://github.com/easy-swoole/spl/tree/2.1.1"
},
"time": "2023-04-12T14:51:47+00:00"
},
{ {
"name": "egulias/email-validator", "name": "egulias/email-validator",
"version": "4.0.2", "version": "4.0.2",