| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498 |
- <?php
- /**
- * 积分拓客
- */
- namespace addons\ScoreExpansion\common\logic;
- use addons\Redpack\common\enums\RedpackEnum;
- use addons\Redpack\common\models\Redpack;
- use addons\Redpack\common\models\RedpackTask;
- use addons\ScoreExpansion\common\enums\ScoreExpansionEnum;
- use addons\ScoreExpansion\common\models\ScoreExpansion;
- use addons\ScoreExpansion\common\models\ScoreExpansionGoodsSetting;
- use addons\ScoreExpansion\common\models\ScoreExpansionRateTask;
- use addons\ScoreExpansion\common\models\ScoreExpansionTask;
- use addons\ScoreExpansion\common\models\ScoreExpansionWallet;
- use addons\ScoreExpansion\common\models\ScoreExpansionWalletLog;
- use addons\ScoreExpansion\common\services\SettingService;
- use addons\Store\common\models\StoreOrder;
- use common\models\order\OrderDetail;
- use common\enums\AddonsEnum;
- use common\enums\RedisKeyEnum;
- use common\enums\StatusEnum;
- use common\models\common\AddonsSetting;
- use common\models\mall\Mall;
- use common\models\order\Order;
- use common\traits\ErrorTrait;
- use yii\db\Exception;
- use Yii;
- use yii\db\Expression;
- use yii\redis\Connection;
- class FrozenToActiveLogic
- {
- use ErrorTrait;
- /**
- * 执行冻结转激活积分之前进行记录
- * @Author: ltm
- * @DateTime: 2022/3/24 0024 11:07
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $data
- * @return string
- */
- public static function FrozenToActive()
- {
- //查询当天是否执行过
- $time = time();
- $date = date("Y-m-d");
- $find_data = ScoreExpansionTask::find()->where(['day' => $date])->orderBy('id desc')->one();
- $executed_ids = [];
- if (!empty($find_data['content'])) {
- $executed_ids = json_decode($find_data['content']);
- }
- $where = [
- 'or',
- [//查询未过期商城
- 'and',
- ['=', 'status', StatusEnum::ENABLED],
- ['>', 'expired_at', time()],
- ],
- [//查询永久商城
- 'and',
- ['=', 'status', StatusEnum::ENABLED],
- ['=', 'expired_at', StatusEnum::DISABLED],
- ],
- ];
- // 遍历所有商城
- $mall_ids = Mall::find()->where($where)->select('id')->column();
- $mall_execute_ids = array_diff($mall_ids, $executed_ids);
- if (empty($mall_execute_ids)) return true;
- // 当前开启配置的商城
- $open_mall_ids = self::getOpenRedpackMall($mall_execute_ids);
- $mall_config_time = self::getMallConfigtime($mall_execute_ids); //获取开启积分拓客设置定时时间
- $mall_config = self::getMallConfignum($mall_execute_ids); //获取需要进行任务商城积分转换比率
- $order_detail = self::carryOutAppraiseSetting($mall_execute_ids);//批量处理超时未评价的订单
- // 配置service
- $settingService = new SettingService([]);
- // 执行冻结积分进行激活
- $is_execute = false;
- foreach ($open_mall_ids as $k => $v) {
- // 获取配置,如果今天不激活积分则跳过
- $settingService->mall_id = $v;
- $inactiveDates = $settingService->getSetting()['inactive_dates'] ?? [];
- if (is_array($inactiveDates) && in_array($date, $inactiveDates)) {
- Yii::$app->custom->logs('【积分拓客】今日不激活', ['mall_id' => $v, 'inactive_dates' => $inactiveDates]);
- continue;
- }
- // 判断后台冻结转激活开关是否开启end
- if (!empty($mall_config_time['activation_time'][$v])) {
- $activation_time = $mall_config_time['activation_time'][$v];
- $activation_time = strtotime($activation_time);
- if ($time >= $activation_time && $time < $activation_time + 1800) {
- if (!$executed_ids || !in_array($v, $executed_ids)) {
- $res = self::redpackexecute($v);
- if ($res) {
- $executed_ids[] = $v;
- if ($find_data) {
- $add_data['id'] = $find_data->id;
- }
- if ($executed_ids) {
- $add_data['content'] = json_encode($executed_ids, true);
- $add_data['day'] = date("Y-m-d");
- $res = ScoreExpansionTask::setData($add_data, $is_execute, $find_data);
- }
- }
- }
- }
- }
- }
- //更新活动的活动时间
- self::changeactivetime();
- return true;
- }
- /**
- * 修改每日活动时间
- * @Author: ltm
- * @DateTime: 2022/3/25 0025 10:35
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $data
- * @return string
- */
- public static function changeactivetime()
- {
- $where = [
- 'and',
- ['time_type' => '1'],
- ['status' => StatusEnum::ENABLED],
- ];
- $redis = \Yii::$app->redis;
- $update_time = $redis->get(ScoreExpansionEnum::REDIS_SCORE_EXPANSION_STAK_KEY);
- $daytime = strtotime(date("Y-m-d"));
- $last_execute_time = strtotime(date('Y-m-d'));
- if (!$update_time || $update_time < $last_execute_time) {
- $model = ScoreExpansion::find()->select('time_type,mall_id,start_time,end_time,day_award,award,id')->where($where);
- foreach ($model->batch(500) as $data) {
- foreach ($data as $key => $value) {
- $params['start_time'] = $daytime + strtotime(date("Y-m-d H:i:s", $value['start_time'])) - strtotime(date("Y-m-d", $value['start_time']));
- $params['end_time'] = $daytime + strtotime(date("Y-m-d H:i:s", $value['end_time'])) - strtotime(date("Y-m-d", $value['end_time']));
- $params['id'] = $value['id'];
- $params['mall_id'] = $value['mall_id'];
- $params['award'] = $value['day_award'];//每日总奖金每日凌晨将被覆盖
- $update = ScoreExpansion::setData($params);
- }
- }
- //更新标记执行过时间
- self::setRedpackTaskStatus(time());
- }
- }
- /**
- * @Author: ltm
- * @DateTime: 2022/3/25 0025 14:01
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $data
- * @return string
- */
- public static function setRedpackTaskStatus($data)
- {
- $config = \Yii::$app->getComponents()['redis'];
- unset($config['class']);
- $redis = new Connection($config);
- $redis->set(ScoreExpansionEnum::REDIS_SCORE_EXPANSION_STAK_KEY, $data);
- $redis->close();
- }
- /**
- * 执行冻结积分转激活
- * @Author: ltm
- * @DateTime: 2022/3/24 0024 14:48
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $data
- * @return string
- */
- public static function redpackexecute($mall_id)
- {
- //获取用户记录
- $where = [
- 'and',
- ['mall_id' => $mall_id],
- ['status' => StatusEnum::ENABLED],
- ['>', 'frozen_integral', 0],
- ];
- $model = ScoreExpansionWallet::find()->select('frozen_integral,total_frozen_integral,total_integral,mall_id,user_id,id')->where($where);
- // 设置服务
- $service = new SettingService(['mall_id' => $mall_id]);
- //冻结积分转激活积分
- $text = ScoreExpansionEnum::getRedpackText(ScoreExpansionEnum::WALLET_INTEGRAL_FROZEN, $mall_id) . '转' . ScoreExpansionEnum::getRedpackText(ScoreExpansionEnum::WALLET_INTEGRAL, $mall_id);
- foreach ($model->asArray()->batch(500) as $walletdata) {
- foreach ($walletdata as $value) {
- // 计算积分 等比例
- if ($service->isEqualEatio()) {
- $calculate_money = bcdiv(bcmul($value['total_frozen_integral'], $service->getActivationNum(), 2), 100, 2);
- $money = sprintf("%.2f", substr(sprintf("%.3f", $calculate_money), 0, -1));
- }
- // 计算积分 递减
- if ($service->isDecrement()) {
- $calculate_money = bcdiv(bcmul($value['frozen_integral'], $service->getActivationNum(), 2), 100, 2);
- $money = sprintf("%.2f", substr(sprintf("%.3f", $calculate_money), 0, -1));
- }
- // 固定金额
- if ($service->isFixed()) {
- $money = bcmul($service->getActivationNum(), 1, 2);
- }
- // 小于一分钱,则不转出
- if ($money < 0.01) continue;
- // 判断当前用户冻结积分是否足以抵扣转换金额,不足则转换金额默认为当前冻结积分
- if ($value['frozen_integral'] < $money) {
- $money = $value['frozen_integral'];
- }
- $t = Yii::$app->db->beginTransaction();
- try {
- // 因为积分计算出当积分不足时,会只扣除剩余部分。但是转换发放又是全部。所以需要进行判断用户剩余积分是否充足。不足的话,则不执行
- if ($money > 0) {
- // 扣除冻结积分
- $res = ScoreExpansionWallet::setData([
- 'mall_id' => $mall_id,
- 'user_id' => $value['user_id'],
- 'is_frozen' => true,
- 'is_deduct' => true,
- 'integral' => -$money,
- 'from_type' => ScoreExpansionEnum::FROM_FROZEN_TO_ACTIVE,
- 'desc' => $text,
- ]);
- if ($res === false) throw new Exception('执行失败');
- // 转激活积分
- $res = ScoreExpansionWallet::setData([
- 'mall_id' => $mall_id,
- 'user_id' => $value['user_id'],
- 'is_frozen' => false,
- 'is_deduct' => true,
- 'integral' => $money,
- 'from_type' => ScoreExpansionEnum::FROM_FROZEN_TO_ACTIVE,
- 'desc' => $text,
- ]);
- }
- $t->commit();
- } catch (\Exception $e) {
- $t->rollBack();
- echo '冻结积分转激活积分失败,' . $e->getMessage() . ',行数:' . $e->getLine(), 'file:' . $e->getFile();
- }
- }
- }
- return true;
- }
- /**
- * 获取已经开启冻结积分转激活积分商城配置
- *
- * @param array $mall_ids
- * @return array
- */
- public static function getOpenRedpackMall(array $mall_ids)
- {
- //获取开启的商城ID
- $where[] = ['in', 'mall_id', $mall_ids];
- $where[] = ['name' => "frozen_status"];
- $where[] = ['value' => 1];
- $where[] = ['addons_name' => AddonsEnum::ADDONS_NAME_SCORE_EXPANSION];
- $redpack_config = AddonsSetting::lists(['where' => $where], true);
- if ($redpack_config) {
- $ids = array_column($redpack_config, 'mall_id');
- }
- return $ids ?? [];
- }
- /**
- *
- * @Author: ltm
- * @DateTime: 2022/3/24 0024 10:51
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $data
- * @return string
- */
- public static function getMallConfigtime($mall_ids)
- {
- //获取开启时间
- $where[] = ['in', 'mall_id', $mall_ids];
- $where[] = ['name' => "activation_time"];
- $where[] = ['addons_name' => AddonsEnum::ADDONS_NAME_SCORE_EXPANSION];
- $redpack_config = AddonsSetting::lists(['where' => $where, 'select' => 'value,mall_id'], true);
- if ($redpack_config) {
- $list['activation_time'] = array_column($redpack_config, 'value', 'mall_id');
- }
- return $list;
- }
- /**
- *
- * @Author: ltm
- * @DateTime: 2022/3/24 0024 10:51
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $data
- * @return array
- */
- public static function getMallConfignum($mall_ids)
- {
- //获取转换比率
- $where[] = ['in', 'mall_id', $mall_ids];
- $where[] = ['name' => "activation_num"];
- $where[] = ['addons_name' => AddonsEnum::ADDONS_NAME_SCORE_EXPANSION];
- $redpack_config = AddonsSetting::lists(['where' => $where, 'select' => 'value,mall_id'], true);
- $list = [];
- if ($redpack_config) {
- $list['activation_num'] = array_column($redpack_config, 'value', 'mall_id');
- }
- return $list;
- }
- /**
- * 订单确认收货但未完成评价,n天后,扣减冻结积分 + 到激活积分
- */
- public static function carryOutAppraiseSetting($mall_ids)
- {
- //查询定时任务表查看未执行的任务
- //Order
- $orderSource = Order::tableName();
- $orderTaskList = ScoreExpansionRateTask::find()->where(['is_work' => 0,'source_table'=>$orderSource])->indexBy('order_id')->orderBy(['id' => SORT_DESC])->asArray()->all();
- $orderIds = array_column($orderTaskList, 'order_id');
- $order_select = "id,mall_id,is_comment,sign_time,user_id";
- //StoreOrder
- if (class_exists(StoreOrder::class)) {
- $storeOrderSource = StoreOrder::tableName();
- $storeOrderTaskList = ScoreExpansionRateTask::find()->where(['is_work' => 0,'source_table'=>$storeOrderSource])->indexBy('order_id')->orderBy(['id' => SORT_DESC])->asArray()->all();
- $storeOrderIds = array_column($storeOrderTaskList, 'order_id');
- }
- //获取配置
- foreach ($mall_ids as $mall_id) {
- $service = new SettingService(['mall_id' => $mall_id]);
- $config = $service->getSetting();
- if ($config['change_activation_integral'] != 0) continue;
- $time_limit = $config['time_limit'] ?? 0;//超过这个时间限制将扣除积分
- //查询所有订单商品表判断是否评价
- $orderList = Order::find()->select($order_select)
- ->where(['in', 'id', $orderIds])
- ->andWhere(['mall_id' => $mall_id])
- ->andWhere(['in', 'order_status', [3, 4]])//3已收货 4已完成
- // ->andWhere(['is_comment' => 0])//订单评价
- ->orderBy(['id' => SORT_DESC])
- ->asArray()
- ->all();
- foreach ($orderList as $order) {
- //拿到商品计算价格
- //20230406-------
- $source_table = $orderTaskList[$order['id']]['source_table'];
- $log_list = ScoreExpansionWalletLog::find()
- ->where(['integral_wallet_type' => ScoreExpansionEnum::WALLET_INTEGRAL_FROZEN, 'source_table_id' => $order['id'], 'change_type' => 'add','source_table'=>$source_table])
- ->asArray()
- ->all();
- if (empty($log_list)) continue;
- foreach ($log_list as $item) {
- // 计算可赠送的红包金额
- $money = $item['change_num'];
- if ($money <= 0) continue;
- //判断冻结积分是否足够
- $thisWallet = ScoreExpansionWallet::findOne(['mall_id' => $item['mall_id'], 'user_id' => $item['user_id']]);
- if (empty($thisWallet) || $thisWallet->frozen_integral <= $money) {
- continue;
- }
- if ($item['integral_wallet_type'] == ScoreExpansionEnum::WALLET_INTEGRAL_FROZEN) {
- //判断当前时间 大于扣减
- $end_time = $order['sign_time'] + ($time_limit * 1 * 24 * 60 * 60);
- $time = time();
- if ($time >= $end_time) {
- //扣减冻结积分
- $activationWallet = ScoreExpansionWallet::setData([
- 'mall_id' => $item['mall_id'],
- 'user_id' => $item['user_id'],
- 'is_frozen' => true,
- 'integral' => -$money,
- 'source_table' => Order::tableName(),
- 'source_table_id' => $order['id'],
- 'from_type' => ScoreExpansionEnum::FROM_GOODS_REVIEWS,
- 'desc' => '未在规定时间内完成评价,自动转换扣减冻结积分',
- ]);
- if ($activationWallet == false) throw new Exception(ScoreExpansionWallet::getStaticError());
- //---
- // 增加激活积分
- $frozenWallet = ScoreExpansionWallet::setData([
- 'mall_id' => $item['mall_id'],
- 'user_id' => $item['user_id'],
- 'is_frozen' => false,
- 'integral' => $money,
- 'source_table' => Order::tableName(),
- 'source_table_id' => $order['id'],
- 'from_type' => ScoreExpansionEnum::FROM_GOODS_REVIEWS,
- 'desc' => '未在规定时间内完成评价,自动转换增加激活积分',
- ]);
- if ($frozenWallet == false) throw new Exception(ScoreExpansionWallet::getStaticError());
- //---
- //修改定时任务状态
- $task = ScoreExpansionRateTask::findOne(['order_id' => $order['id'],'source_table'=>$source_table]);
- $task->is_work = 1;
- if (!$task->save()) {
- throw new Exception(ScoreExpansionRateTask::getStaticError());
- }
- }
- }
- }
- }
- if(!empty($storeOrderIds)){
- $storeOrderList = StoreOrder::find()->select($order_select)
- ->where(['in', 'id', $storeOrderIds])
- ->andWhere(['mall_id' => $mall_id])
- ->andWhere(['in', 'order_status', [3, 4]])//3已收货 4已完成
- // ->andWhere(['is_comment' => 0])//订单评价
- ->orderBy(['id' => SORT_DESC])
- ->asArray()
- ->all();
- if(!empty($storeOrderList)){
- foreach ($storeOrderList as $storeOrder) {
- //拿到商品计算价格
- //20230406-------
- $source_table = $storeOrderTaskList[$storeOrder['id']]['source_table'];
- $log_list = ScoreExpansionWalletLog::find()
- ->where(['integral_wallet_type' => ScoreExpansionEnum::WALLET_INTEGRAL_FROZEN, 'source_table_id' => $storeOrder['id'], 'change_type' => 'add','source_table'=>$source_table])
- ->asArray()
- ->all();
- if (empty($log_list)) continue;
- foreach ($log_list as $item) {
- // 计算可赠送的红包金额
- $money = $item['change_num'];
- if ($money <= 0) continue;
- //判断冻结积分是否足够
- $thisWallet = ScoreExpansionWallet::findOne(['mall_id' => $item['mall_id'], 'user_id' => $item['user_id']]);
- if (empty($thisWallet) || $thisWallet->frozen_integral <= $money) {
- continue;
- }
- if ($item['integral_wallet_type'] == ScoreExpansionEnum::WALLET_INTEGRAL_FROZEN) {
- //判断当前时间 大于扣减
- $end_time = $storeOrder['sign_time'] + ($time_limit * 1 * 24 * 60 * 60);
- $time = time();
- if ($time >= $end_time) {
- //扣减冻结积分
- $storeActivationWallet = ScoreExpansionWallet::setData([
- 'mall_id' => $item['mall_id'],
- 'user_id' => $item['user_id'],
- 'is_frozen' => true,
- 'integral' => -$money,
- 'source_table' => $storeOrderSource,
- 'source_table_id' => $storeOrder['id'],
- 'from_type' => ScoreExpansionEnum::FROM_GOODS_REVIEWS,
- 'desc' => '未在规定时间内完成评价,自动转换扣减冻结积分',
- ]);
- if ($storeActivationWallet == false) throw new Exception(ScoreExpansionWallet::getStaticError());
- //---
- // 增加激活积分
- $storeFrozenWallet = ScoreExpansionWallet::setData([
- 'mall_id' => $item['mall_id'],
- 'user_id' => $item['user_id'],
- 'is_frozen' => false,
- 'integral' => $money,
- 'source_table' => $storeOrderSource,
- 'source_table_id' => $storeOrder['id'],
- 'from_type' => ScoreExpansionEnum::FROM_GOODS_REVIEWS,
- 'desc' => '未在规定时间内完成评价,自动转换增加激活积分',
- ]);
- if ($storeFrozenWallet == false) throw new Exception(ScoreExpansionWallet::getStaticError());
- //---
- //修改定时任务状态
- $task = ScoreExpansionRateTask::findOne(['order_id' => $storeOrder['id'],'source_table'=>$source_table]);
- $task->is_work = 1;
- if (!$task->save()) {
- throw new Exception(ScoreExpansionRateTask::getStaticError());
- }
- }
- }
- }
- }
- }
- }
- }
- return true;
- }
- }
|