| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813 |
- <?php
- namespace addons\Coupon\console\controllers;
- use addons\Coupon\AddonConfig;
- use addons\Boss\common\logic\CommissionLogLogic;
- use addons\Coupon\common\enums\AddonsCouponEnum;
- use addons\Coupon\common\models\AddonsCoupon;
- use addons\Coupon\common\models\AddonsCouponGoodStatistics;
- use addons\Coupon\common\models\AddonsCouponRemind;
- use addons\Coupon\common\models\AddonsCouponShareLog;
- use addons\Coupon\common\models\AddonsCouponStatistics;
- use addons\Coupon\common\models\AddonsCouponUseLog;
- use addons\Coupon\common\models\AddonsCouponUserRelate;
- use common\enums\OrderStatusEnum;
- use common\enums\StatusEnum;
- use common\helpers\LockHelper;
- use common\helpers\wechat\WechatTemplate;
- use common\models\mall\Mall;
- use common\models\mall\MallAddons;
- use common\models\order\Order;
- use common\models\order\OrderDetail;
- use common\models\order\OrderMarketing;
- use yii\console\Controller;
- use yii\console\ExitCode;
- class CouponCrontabController extends Controller
- {
- /**
- * 自动更新优惠券状态,定时器调用执行
- *
- */
- // 0 */1 * * * *
- public function actionUpdateCouponStatus()
- {
- try {
- // \Yii::error('自动更新优惠券状态任务开始执行 ... ');
- // \Yii::getLogger()->flush(true);
- echo ' 自动更新优惠券状态任务开始执行 ... ' . PHP_EOL;
- // 获取当前系统所有可用的 mall_id
- $malls = Mall::getEnableMallList();
- $mall_ids = array_column($malls, 'id');
- echo ' 获取到的 mall_id => ' . implode(', ', $mall_ids) . PHP_EOL;
- foreach ($mall_ids as $mall_id) {
- echo '开始更新商城的优惠券:mall_id => ' . $mall_id . PHP_EOL;
- $obj = new AddonConfig();
- $name = ($obj->info)['name'];
- $is_install = MallAddons::isInstall($mall_id, $name);
- if (!$is_install) continue;
- // 更新优惠券主表
- $lock_name_main = 'qimall:update_coupon_status:main:mall_id:' . $mall_id;
- $lock_val_main = md5($lock_name_main);
- $lock_main = LockHelper::lock($lock_name_main, $lock_val_main, 60);
- $lock_main && self::updateMainCoupons($mall_id);
- LockHelper::uLock($lock_name_main, $lock_val_main);
- // 更新会员已经领取的优惠券的状态
- $lock_name_user = 'qimall:update_coupon_status:user:mall_id:' . $mall_id;
- $lock_val_user = md5($lock_name_user);
- $lock_user = LockHelper::lock($lock_name_user, $lock_val_user, 60);
- $lock_user && self::updateUserCoupons($mall_id);
- LockHelper::uLock($lock_name_user, $lock_val_user);
- }
- echo ' 自动更新优惠券状态任务执行完毕 ... ' . PHP_EOL;
- return ExitCode::OK;
- } catch (\Exception $e) {
- LockHelper::uLock($lock_name_main, $lock_val_main);
- LockHelper::uLock($lock_name_user, $lock_val_user);
- $errmsg = ' 自动更新优惠券状态任务执行出错, errmsg => ' . $e->getMessage() . ', file: ' . $e->getFile() . ', line: ' . $e->getLine();
- echo $errmsg . PHP_EOL;
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- return false;
- }
- }
- /**
- * 优惠券相关统计,定时器调用执行
- *
- */
- // 0 */3 * * * *
- public function actionCouponStatistics()
- {
- // \Yii::error('优惠券相关统计任务开始执行 ... ');
- // \Yii::getLogger()->flush(true);
- try {
- echo ' 优惠券相关统计任务开始执行 ... ' . PHP_EOL;
- // 获取当前系统所有可用的 mall_id
- $malls = Mall::getEnableMallList();
- $mall_ids = array_column($malls, 'id');
- echo ' 获取到的 mall_id => ' . implode(', ', $mall_ids) . PHP_EOL;
- foreach ($mall_ids as $mall_id) {
- echo '开始更新商城的优惠券:mall_id => ' . $mall_id . PHP_EOL;
- // $mall_id = 5;
- $obj = new AddonConfig();
- $name = ($obj->info)['name'];
- $is_install = MallAddons::isInstall($mall_id, $name);
- if (!$is_install) continue;
- $lock_name = 'qimall:coupon_statistics:mall_id:' . $mall_id;
- $lock_val = md5($lock_name);
- $lock = LockHelper::lock($lock_name, $lock_val, 60);
- if ($lock) {
- // 优惠券相关数量
- self::statNumber($mall_id);
- // 订单使用相关统计
- self::statOrder($mall_id);
- // 计算优惠券使用率
- self::calUseProbability($mall_id);
- }
- LockHelper::uLock($lock_name, $lock_val);
- }
- echo ' 优惠券相关统计任务执行完毕' . PHP_EOL;
- return ExitCode::OK;
- } catch (\Exception $e) {
- LockHelper::uLock($lock_name, $lock_val);
- $errmsg = $e->getMessage() . ', file: ' . $e->getFile() . ', line: ' . $e->getLine();
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- return false;
- }
- }
- /**
- * 统计商品使用优惠券相关数据,定时器调用执行
- *
- */
- // 0 */3 * * * *
- public function actionCouponGoodStat()
- {
- // \Yii::error('统计商品使用优惠券相关数据任务开始执行 ...');
- // \Yii::getLogger()->flush(true);
- try {
- echo ' 统计商品使用优惠券相关数据任务开始执行 ... ' . PHP_EOL;
- // 获取当前系统所有可用的 mall_id
- $malls = Mall::getEnableMallList();
- $mall_ids = array_column($malls, 'id');
- echo ' 获取到的 mall_id => ' . implode(', ', $mall_ids) . PHP_EOL;
- foreach ($mall_ids as $mall_id) {
- echo ' 开始更新商城的优惠券:mall_id => ' . $mall_id . PHP_EOL;
- // $mall_id = 5;
- $obj = new AddonConfig();
- $name = ($obj->info)['name'];
- $is_install = MallAddons::isInstall($mall_id, $name);
- if (!$is_install) {
- echo ' 未安装优惠券应用' . PHP_EOL;
- continue;
- }
- $lock_name = 'qimall:coupon_good_stat:mall_id:' . $mall_id;
- $lock_val = md5($lock_name);
- $lock = LockHelper::lock($lock_name, $lock_val, 60);
- if ($lock) {
- // 统计使用优惠券购买商品相关数量
- self::statBookNumber($mall_id);
- } else {
- echo ' 获取锁失败' . PHP_EOL;
- }
- LockHelper::uLock($lock_name, $lock_val);
- }
- echo ' 统计商品使用优惠券相关数据任务执行完毕' . PHP_EOL;
- return ExitCode::OK;
- } catch (\Exception $e) {
- LockHelper::uLock($lock_name, $lock_val);
- $errmsg = $e->getMessage() . ', file: ' . $e->getFile() . ', line: ' . $e->getLine();
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- return false;
- }
- }
- /**
- * 优惠券过期前提醒,定时器调用执行
- */
- // 0 0 */4 * * *
- public function actionExpireRemind()
- {
- try {
- // 获取当前系统所有可用的 mall_id
- $malls = Mall::getEnableMallList();
- $mall_ids = array_column($malls, 'id');
- echo ' 获取到的 mall_id => ' . implode(', ', $mall_ids) . PHP_EOL;
- foreach ($mall_ids as $mall_id) {
- echo '开始更新商城的优惠券:mall_id => ' . $mall_id . PHP_EOL;
- // $mall_id = 5;
- $obj = new AddonConfig();
- $name = ($obj->info)['name'];
- $is_install = MallAddons::isInstall($mall_id, $name);
- if (!$is_install) continue;
- $page = 1;
- $limit = 500;
- do {
- $offset = ($page - 1) * $limit;
- $page++;
- $reminds = AddonsCouponRemind::find()
- ->where(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'send_status' => 1])
- ->limit($limit)
- ->offset($offset)
- ->all();
- if (!empty($reminds)) {
- foreach ($reminds as $remind) {
- $coupon = AddonsCoupon::findOne(['id' => $remind->coupon_id, 'mall_id' => $mall_id, 'is_remind' => 1]);
- if (empty($coupon)) continue;
- $time_node = $remind->remind_days * 86400;
- if ($time_node > $remind->expire_time) {
- // 现在到优惠券过期的时间小于三天,发消息提醒
- $params = [
- 'mall_id' => $mall_id,
- 'user_id' => $remind->user_id,
- 'first' => '您已经领取的优惠券',
- 'keywords' => [
- 'keyword1' => $coupon->name,
- ],
- 'remark' => '即将过期,请尽快使用。'
- ];
- self::sendWechatMessage($params);
- }
- // 睡眠 1s,防止腾讯封禁
- sleep(1);
- }
- }
- } while ($reminds);
- }
- echo ' 发送过期提醒任务执行完毕 ... ' . PHP_EOL;
- return true;
- } catch (\Exception $e) {
- $errmsg = $e->getMessage() . ', file: ' . $e->getFile() . ', line: ' . $e->getLine();
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- return false;
- }
- }
- /**
- * @name:
- * @msg: 更新优惠券主表中的状态
- * @param {int} $mall_id
- * @return {*}
- */
- private static function updateMainCoupons(int $mall_id)
- {
- // $query = AddonsCoupon::find()->where(['mall_id' => $mall_id, 'status' => 1, 'expire_type' => 2])->andWhere(['!=', 'coupon_status', 4]);
- $curr_time = time();
- $receiving_ids = [];
- $finished_receive_ids = [];
- $page = 1;
- $limit = 500;
- do {
- $offset = ($page - 1) * $limit;
- $page++;
- $coupons = AddonsCoupon::find()
- ->where(['mall_id' => $mall_id, 'status' => 1, 'expire_type' => 2])
- ->andWhere(['!=', 'coupon_status', 4])
- ->limit($limit)
- ->offset($offset)
- ->all();
- if (!empty($coupons)) {
- foreach ($coupons as $coupon) {
- if ($coupon->begin_at <= $curr_time && $coupon->end_at > $curr_time) {
- // 优惠券领取中
- $receiving_ids[] = $coupon->id;
- } elseif ($coupon->end_at <= $curr_time) {
- $finished_receive_ids[] = $coupon->id;
- }
- }
- }
- } while ($coupons);
- if (!empty($receiving_ids)) {
- $res = AddonsCoupon::updateAll(['coupon_status' => 2], ['id' => $receiving_ids, 'mall_id' => $mall_id]);
- if ($res === false) {
- \Yii::error('更新优惠券状态失败:res => ' . var_export($res, true) . ', mall_id => ' . $mall_id . ', receiving_ids => ' . var_export($receiving_ids, true) . ', errmsg => ' . AddonsCoupon::getStaticError());
- \Yii::getLogger()->flush(true);
- }
- }
- if (!empty($finished_receive_ids)) {
- $res = AddonsCoupon::updateAll(['coupon_status' => 3], ['id' => $finished_receive_ids, 'mall_id' => $mall_id]);
- $res_remaind = AddonsCouponRemind::updateAll(['send_status' => 3], ['coupon_id' => $finished_receive_ids, 'mall_id' => $mall_id]);
- $res_uc = AddonsCouponUserRelate::updateAll(['coupon_status' => 3], ['coupon_id' => $finished_receive_ids, 'mall_id' => $mall_id]);
- if ($res === false || $res_remaind === false || $res_uc === false) {
- \Yii::error('更新优惠券状态失败:res => ' . var_export($res, true) . ', res_remaind => ' . var_export($res_remaind, true) . ', res_uc => ' . var_export($res_uc, true) . ', mall_id => ' . $mall_id . ', finished_receive_ids => ' . var_export($finished_receive_ids, true) . ', ac_errmsg => ' . AddonsCoupon::getStaticCodeError() . ', cr_errmsg => ' . AddonsCouponRemind::getStaticError() . ', cu_errmsg => ' . AddonsCouponUserRelate::getStaticError());
- \Yii::getLogger()->flush(true);
- }
- }
- }
- /**
- * @name:
- * @msg: 更新会员已经领取的优惠券的状态
- * @param {int} $mall_id
- * @return {*}
- */
- private static function updateUserCoupons(int $mall_id)
- {
- $time = time();
- /* $query = AddonsCouponUserRelate::find()
- ->where(['mall_id' => $mall_id, 'is_use' => 0, 'status' => 1, 'is_force_failure' => 0, 'coupon_status' => AddonsCouponEnum::STATUS_RECEIVING])
- ->andWhere(['or', ['is_giving' => 0], ['is_giving' => 1, 'giving_status' => 1]])
- ->andWhere(['<=', 'end_time', $time]);
- foreach ($query->each(500) as $user_coupon) {
- $user_coupon->coupon_status = AddonsCouponEnum::STATUS_EXPIRED;
- $user_coupon->updated_at = $time;
- $res = $user_coupon->save();
- if (!$res) {
- $errmsg = ' 更新优惠券状态失败:res => ' . var_export($res, true) . ', mall_id => ' . $mall_id . ', id => ' . $user_coupon->id;
- echo $errmsg . PHP_EOL;
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- }
- } */
- $page = 1;
- $limit = 500;
- do {
- $offset = ($page - 1) * $limit;
- $page++;
- $user_coupons = AddonsCouponUserRelate::find()
- ->where(['mall_id' => $mall_id, 'is_use' => 0, 'status' => 1, 'is_force_failure' => 0, 'coupon_status' => AddonsCouponEnum::STATUS_RECEIVING])
- ->andWhere(['or', ['is_giving' => 0], ['is_giving' => 1, 'giving_status' => 1]])
- ->andWhere(['<=', 'end_time', $time])
- ->limit($limit)
- ->offset($offset)
- ->all();
- if (!empty($user_coupons)) {
- foreach ($user_coupons as $user_coupon) {
- $user_coupon->coupon_status = AddonsCouponEnum::STATUS_EXPIRED;
- $user_coupon->updated_at = $time;
- $res = $user_coupon->save();
- if (!$res) {
- $errmsg = ' 更新优惠券状态失败:res => ' . var_export($res, true) . ', mall_id => ' . $mall_id . ', id => ' . $user_coupon->id;
- echo $errmsg . PHP_EOL;
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- }
- }
- }
- } while ($user_coupons);
- }
- /**
- * @name:
- * @msg: 统计商品使用优惠券相关数据
- * @param {int} $mall_id
- * @param {string} $type
- * @param {string} $field
- * @return {*}
- */
- private static function statBookNumber(int $mall_id)
- {
- $stat_datas = $booking_users = $payed_users = $booking_number = [];
- $page = 1;
- $limit = 500;
- do {
- $offset = ($page - 1) * $limit;
- $page++;
- $coupons = AddonsCoupon::find()->where(['mall_id' => $mall_id, 'status' => 1])->limit($limit)->offset($offset)->all();
- if (!empty($coupons)) {
- $coupon_ids = array_column($coupons, 'id');
- if (empty($coupon_ids)) continue;
- $coupon_use_log = AddonsCouponUseLog::find()
- ->select('order_id,coupon_id,user_coupon_id')
- ->where(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'coupon_id' => $coupon_ids])
- ->asArray()
- ->indexBy('order_id')
- ->all();
- $order_ids = array_column($coupon_use_log, 'order_id');
- $orders = Order::find()
- ->where(['id' => $order_ids, 'status' => StatusEnum::ENABLED])
- ->asArray()
- ->indexBy('id')
- ->all();
- if (empty($orders)) continue;
- $order_details = OrderDetail::find()
- ->where(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'order_id' => array_column($orders, 'id')])
- ->all();
- foreach ($order_details as $detail) {
- $coupon_id = $coupon_use_log[$detail->order_id]['coupon_id'] ?? 0;
- $key_order_number = $coupon_id . '_' . $detail['goods_id'];
- // 下单数量
- $booking_number[$key_order_number][] = $detail->order_id;
- // 支付数量
- $pay_status = $orders[$detail->order_id]['pay_status'] ?? OrderStatusEnum::NOT_PAY;
- if ($pay_status == OrderStatusEnum::PAY) $payed_number[$key_order_number][] = $detail->order_id;
- // 下单总人数
- $booking_users[$key_order_number][] = $detail->user_id;
- // 购买总人数
- if ($pay_status == OrderStatusEnum::PAY) $payed_users[$key_order_number][] = $detail->user_id;
- }
- }
- } while ($coupons);
- // var_dump($booking_number, $payed_number, $booking_users, $payed_users);exit;
- if (!empty($booking_number)) {
- foreach ($booking_number as $key => $order_ids) {
- $stat_datas[$key]['booking_number'] = count(array_values(array_unique($order_ids)));
- }
- }
- if (!empty($payed_number)) {
- foreach ($payed_number as $key => $order_ids) {
- $stat_datas[$key]['payed_number'] = count(array_values(array_unique($order_ids)));
- }
- }
- if (!empty($booking_users)) {
- foreach ($booking_users as $key => $users) {
- $stat_datas[$key]['booking_user_number'] = count(array_values(array_unique($users)));
- }
- }
- if (!empty($payed_users)) {
- foreach ($payed_users as $key => $users) {
- $stat_datas[$key]['buyed_user_number'] = count(array_values(array_unique($users)));
- }
- }
- // var_dump($stat_datas);exit;
- if (empty($stat_datas)) {
- echo ' stat_datas is empty, stat_datas => ' . var_export($stat_datas, true) . PHP_EOL;
- return;
- }
- self::updateCouponGoodStat($stat_datas, $mall_id);
- }
- /**
- * @name:
- * @msg: 更新优惠券商品统计表
- * @param {array} $data
- * @param {int} $mall_id
- * @param {*} $field
- * @return {*}
- */
- private static function updateCouponGoodStat(array $data, int $mall_id)
- {
- if (!empty($data)) {
- foreach ($data as $key => $dv) {
- $keys = explode('_', $key);
- $coupon_good_stat = AddonsCouponGoodStatistics::findOne(['mall_id' => $mall_id, 'coupon_id' => $keys[0], 'good_id' => $keys[1]]);
- if (empty($coupon_good_stat)) {
- $coupon_good_stat = new AddonsCouponGoodStatistics();
- $data = [
- 'mall_id' => $mall_id,
- 'coupon_id' => $keys[0] ?? 0,
- 'good_id' => $keys[1] ?? 0,
- 'created_at' => time(),
- ];
- $coupon_good_stat->attributes = $data;
- }
- // dd($coupon_good_stat);
- foreach ($dv as $dk => $val) {
- $coupon_good_stat->$dk = $val;
- }
- $res = $coupon_good_stat->save();
- if (!$res) {
- $errmsg = ' 插入/更新已领取数量失败, res => ' . $res . ', data => ' . var_export($data, true);
- echo $errmsg . PHP_EOL;
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- }
- }
- }
- }
- /**
- * @name:
- * @msg: 统计数量
- * @param {int} $mall_id
- * @param {array} $conditions
- * @param {string} $field
- * @return {*}
- */
- private static function statNumber(int $mall_id)
- {
- echo ' 统计相关数量 ... ' . PHP_EOL;
- $user_coupons = [];
- /* $used_query = AddonsCouponUserRelate::find()->where(['mall_id' => $mall_id, 'status' => 1]);
- foreach ($used_query->batch(500) as $use_coupon) {
- $coupon_id = $use_coupon->coupon_id;
- $coupon_id == 187 && var_dump($coupon_id);
- // 统计已领取数量
- if (!isset($user_coupons[$coupon_id]['received_number'])) $user_coupons[$coupon_id]['received_number'] = 0;
- $user_coupons[$coupon_id]['received_number'] += 1;
- // 统计已使用数量
- if (!isset($user_coupons[$coupon_id]['used_number'])) $user_coupons[$coupon_id]['used_number'] = 0;
- $use_coupon->is_use == 1 && $user_coupons[$coupon_id]['used_number'] += 1;
- // 统计优惠券被转赠的次数
- if (!isset($user_coupons[$coupon_id]['giveing_times'])) $user_coupons[$coupon_id]['giveing_times'] = 0;
- $use_coupon->is_giving == 1 && $user_coupons[$coupon_id]['giveing_times'] += 1;
- // 记录领取会员id
- $received_user_ids[$coupon_id][] = $use_coupon->user_id;
- // 记录使用会员id
- $use_coupon->is_use == 1 && $used_user_ids[$coupon_id][] = $use_coupon->user_id;
- // 记录转赠优惠券的会员id
- $use_coupon->is_giving == 1 && $giving_user_ids[$coupon_id][] = $use_coupon->user_id;
- } */
- $page = 1;
- $limit = 500;
- do {
- $offset = ($page - 1) * $limit;
- $page++;
- $use_coupons = AddonsCouponUserRelate::find()->where(['mall_id' => $mall_id, 'status' => 1])->limit($limit)->offset($offset)->all();
- if (!empty($use_coupons)) {
- foreach ($use_coupons as $key => $use_coupon) {
- $coupon_id = $use_coupon->coupon_id;
- // 统计已领取数量
- if (!isset($user_coupons[$coupon_id]['received_number'])) $user_coupons[$coupon_id]['received_number'] = 0;
- $user_coupons[$coupon_id]['received_number'] += 1;
- // 统计已使用数量
- if (!isset($user_coupons[$coupon_id]['used_number'])) $user_coupons[$coupon_id]['used_number'] = 0;
- $use_coupon->is_use == 1 && $user_coupons[$coupon_id]['used_number'] += 1;
- // 统计优惠券被转赠的次数
- if (!isset($user_coupons[$coupon_id]['giveing_times'])) $user_coupons[$coupon_id]['giveing_times'] = 0;
- $use_coupon->is_giving == 1 && $user_coupons[$coupon_id]['giveing_times'] += 1;
- // 记录领取会员id
- $received_user_ids[$coupon_id][] = $use_coupon->user_id;
- // 记录使用会员id
- $use_coupon->is_use == 1 && $used_user_ids[$coupon_id][] = $use_coupon->user_id;
- // 记录转赠优惠券的会员id
- $use_coupon->is_giving == 1 && $giving_user_ids[$coupon_id][] = $use_coupon->user_id;
- }
- }
- } while ($use_coupons);
- // 统计领取会员数量
- if (!empty($received_user_ids)) {
- foreach ($received_user_ids as $coupon_id => $user_ids) {
- $counts = count(array_flip(array_flip($user_ids)));
- $user_coupons[$coupon_id]['receive_user_number'] = $counts;
- }
- }
- // 统计用券会员数量
- if (!empty($used_user_ids)) {
- foreach ($used_user_ids as $coupon_id => $user_ids) {
- $counts = count(array_flip(array_flip($user_ids)));
- $user_coupons[$coupon_id]['use_user_number'] = $counts;
- }
- }
- // 统计转赠优惠券的会员数量
- if (!empty($giving_user_ids)) {
- foreach ($giving_user_ids as $coupon_id => $user_ids) {
- $counts = count(array_flip(array_flip($user_ids)));
- $user_coupons[$coupon_id]['giving_user_number'] = $counts;
- }
- }
- !empty($user_coupons) && self::updateCouponStat($user_coupons, $mall_id);
- echo ' 统计相关数量完成 ... ' . PHP_EOL;
- }
- /**
- * @name:
- * @msg: 统计订单相关数据
- * @param int $mall_id
- * @param string $type 统计类型,total_discount:累计优惠总金额;total_number:使用优惠券支付的订单总数量;total_real_payed:使用优惠券后实际支付的总金额;total_payed:使用优惠券支付的订单原价总金额
- * @param string $field
- * @return {*}
- */
- private static function statOrder($mall_id)
- {
- echo ' 统计订单相关数据 ... ' . PHP_EOL;
- $stat_datas = [];
- $page = 1;
- $limit = 500;
- do {
- $offset = ($page - 1) * $limit;
- $page++;
- $coupons = AddonsCoupon::find()->where(['mall_id' => $mall_id, 'status' => 1])->limit($limit)->offset($offset)->all();
- if (!empty($coupons)) {
- $coupon_ids = array_column($coupons, 'id');
- $coupon_use_log = AddonsCouponUseLog::find()
- ->select('order_id,coupon_id,user_coupon_id')
- ->where(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'coupon_id' => $coupon_ids])
- ->asArray()
- ->indexBy('user_coupon_id')
- ->all();
- // var_dump($coupon_use_log);
- $order_ids = array_column($coupon_use_log, 'order_id');
- if (empty($order_ids)) continue;
- $orders = Order::find()
- ->where(['id' => $order_ids, 'status' => StatusEnum::ENABLED, 'mall_id' => $mall_id])
- ->asArray()
- ->indexBy('id')
- ->all();
- $order_details = OrderDetail::find()
- ->where(['order_id' => $order_ids, 'mall_id' => $mall_id, 'status' => StatusEnum::ENABLED])
- ->asArray()
- ->indexBy('id')
- ->all();
- $order_detail_ids = array_column($order_details, 'id');
- $order_marketings = OrderMarketing::find()
- ->where(['order_detail_id' => $order_detail_ids, 'status' => StatusEnum::ENABLED])
- ->all();
- if (empty($order_marketings)) continue;
- foreach ($order_marketings as $marketing) {
- if (empty($marketing->user_coupon_id)) continue;
- $user_coupon_info = json_decode($marketing->user_coupon_id, true);
- foreach ($user_coupon_info as $user_coupon_id => $discount_money) {
- $coupon_id = $coupon_use_log[$user_coupon_id]['coupon_id'] ?? 0;
- // 累计优惠总金额
- if (!isset($stat_datas[$coupon_id]['total_discount_amount'])) $stat_datas[$coupon_id]['total_discount_amount'] = 0;
- $stat_datas[$coupon_id]['total_discount_amount'] = bcadd($stat_datas[$coupon_id]['total_discount_amount'], $discount_money, 2);
- // 优惠券下单总数量
- if (!isset($stat_datas[$coupon_id]['use_order_number'])) $stat_datas[$coupon_id]['use_order_number'] = 0;
- $stat_datas[$coupon_id]['use_order_number'] += 1;
- // 实际支付总金额
- if (!isset($stat_datas[$coupon_id]['total_use_coupon_payed_amount'])) $stat_datas[$coupon_id]['total_use_coupon_payed_amount'] = 0;
- $pay_money = $orders[$order_details[$marketing->order_detail_id]['order_id']]['pay_money'] ?? 0;
- $stat_datas[$coupon_id]['total_use_coupon_payed_amount'] = bcadd($stat_datas[$coupon_id]['total_use_coupon_payed_amount'], $pay_money, 2);
- // 用券总金额:未使用优惠券时订单的实际总金额(是计算了积分抵扣、会员价等等的优惠之后的价格)
- if (!isset($stat_datas[$coupon_id]['total_payed_amount'])) $stat_datas[$coupon_id]['total_payed_amount'] = 0;
- // $original_goods_price = $orders[$order_details[$marketing->order_detail_id]['order_id']]['original_goods_price'] ?? 0;
- // $stat_datas[$coupon_id]['total_payed_amount'] = bcadd($stat_datas[$coupon_id]['total_payed_amount'], $original_goods_price);
- $no_coupon_payed_amount = ($orders[$order_details[$marketing->order_detail_id]['order_id']]['pay_money'] ?? 0) + $discount_money;
- $stat_datas[$coupon_id]['total_payed_amount'] = bcadd($stat_datas[$coupon_id]['total_payed_amount'], $no_coupon_payed_amount);
- }
- }
- }
- } while ($coupons);
- // var_dump($stat_datas);
- if (!empty($stat_datas)) {
- self::updateCouponStat($stat_datas, $mall_id);
- }
- echo ' 订单相关数据统计完成 ... ' . PHP_EOL;
- }
- /**
- * @name:
- * @msg: 更新 jxmall_coupon_statistics 表数据
- * @param {array} $data 统计得到的结果
- * @param {int} $mall_id
- * @param {string} $field 更新字段名
- * @return {*}
- */
- private static function updateCouponStat(array $data, int $mall_id)
- {
- if (!empty($data)) {
- foreach ($data as $coupon_id => $dv) {
- $coupon_stat = AddonsCouponStatistics::findOne(['mall_id' => $mall_id, 'coupon_id' => $coupon_id]);
- if (empty($coupon_stat)) {
- $coupon_stat = new AddonsCouponStatistics();
- $data = [
- 'mall_id' => $mall_id,
- 'coupon_id' => $coupon_id,
- 'created_at' => time()
- ];
- $coupon_stat->attributes = $data;
- }
- foreach ($dv as $key => $value) {
- $coupon_stat->$key = $value;
- }
- // var_dump($coupon_stat);
- $res = $coupon_stat->save();
- if (!$res) {
- $errmsg = ' 插入/更新已领取数量失败, res => ' . $res . ', data => ' . var_export($data, true);
- echo $errmsg . PHP_EOL;
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- }
- }
- }
- }
- /**
- * @name:
- * @msg: 计算优惠券使用率
- * @param {int} $mall_id
- * @return {*}
- */
- private static function calUseProbability(int $mall_id)
- {
- /* $query = AddonsCouponStatistics::find()->where(['mall_id' => $mall_id]);
- foreach ($query->each(500) as $coupon_stat) {
- $coupon_stat->use_probability = bcdiv($coupon_stat->used_number, $coupon_stat->received_number, 2);
- $res = $coupon_stat->save();
- if (!$res) {
- $errmsg = ' 计算&更新优惠券使用率出错:res => ' . var_export($res, true) . ', errmsg => ' . $coupon_stat->getErrorMessage() . ', mall_id => ' . $mall_id . ', coupon_id => ' . $coupon_stat->coupon_id;
- echo $errmsg . PHP_EOL;
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- }
- } */
- $page = 1;
- $limit = 500;
- do {
- $offset = ($page - 1) * $limit;
- $page++;
- $coupon_stats = AddonsCouponStatistics::find()->where(['mall_id' => $mall_id])->limit($limit)->offset($offset)->all();
- if (!empty($coupon_stats)) {
- foreach ($coupon_stats as $coupon_stat) {
- if (empty($coupon_stat->received_number)) continue;
- $coupon_stat->use_probability = bcdiv($coupon_stat->used_number, $coupon_stat->received_number, 2);
- $res = $coupon_stat->save();
- if (!$res) {
- $errmsg = ' 计算&更新优惠券使用率出错:res => ' . var_export($res, true) . ', errmsg => ' . $coupon_stat->getErrorMessage() . ', mall_id => ' . $mall_id . ', coupon_id => ' . $coupon_stat->coupon_id;
- echo $errmsg . PHP_EOL;
- \Yii::error($errmsg);
- \Yii::getLogger()->flush(true);
- }
- }
- }
- } while ($coupon_stats);
- }
- private static function sendWechatMessage(array $params)
- {
- $wechat = new WechatTemplate($params['mall_id']);
- //商城是否开启推送模板消息
- if ($wechat->is_logging() === false) {
- return;
- }
- //用户是否开启模板消息
- if ($wechat->is_notice($params['user_id']) === false) {
- return;
- }
- //是否公众号用户
- if ($wechat->is_platform_wechat($params['user_id']) === false) {
- return;
- }
- $platform = $wechat->getPlatForm();
- $h5_domain = \Yii::$app->services->setting->mall->get($params['mall_id'], 'basic.web_url');
- if (empty($h5_domain)) {
- $h5_domain = \Yii::$app->request->hostInfo;
- } else {
- $h5_domain = substr($h5_domain, 0, strpos($h5_domain, '?'));
- }
- $url = 'pages/user/coupon/coupon';
- $h5_url = $h5_domain . $url;
- $send_data = [
- 'first' => $params['first'],
- 'remark' => $params['remark'],
- ];
- if (!empty($params['keywords'])) {
- foreach ($params['keywords'] as $key => $val) {
- $send_data[$key] = $val;
- }
- }
- $temp_key = WechatTemplate::ORDER_CREATE;
- $wechat->sendTemplate($params['user_id'], $temp_key, $h5_url, $send_data, $url);
- }
- public function actionGivingExpire()
- {
- $malls = Mall::getEnableMallList();
- foreach ($malls as $mall) {
- $i = 1;
- $page_size = 1000;
- while ($list = AddonsCouponShareLog::find()
- ->where(['mall_id' => $mall['id']])
- ->andWhere(['receive_user_id' => 0])
- ->offset(($i - 1) * $page_size)
- ->limit($page_size)->all()) {
- $coupon_id = array_column($list, 'coupon_id');
- $user_coupon_ids = array_column($list, 'user_coupon_id');
- $coupon_list = AddonsCoupon::lists([
- 'where' => [
- ['id' => $coupon_id]
- ],
- 'index' => 'id'
- ]);
- $coupon_user_relate_list = AddonsCouponUserRelate::lists([
- 'where' => [
- ['id' => $user_coupon_ids]
- ],
- 'index' => 'id'
- ],false);
- foreach ($list as $item) {
- if (!empty($coupon_list[$item['coupon_id']]['giving_expire'])) {
- $giving_expire = abs($coupon_list[$item['coupon_id']]['giving_expire']);
- $time = time();
- $created_at = $item['created_at'];
- $res = AddonsCouponShareLog::find()->where(['user_coupon_id'=>$item['user_coupon_id']])
- ->andWhere(['<>','receive_user_id',0])->one();
- if(empty($res)){
- if (($time - $created_at) > ($giving_expire * 24 * 3600)) {
- if (isset($coupon_user_relate_list[$item['user_coupon_id']])){
- $coupon_user_relate_model = $coupon_user_relate_list[$item['user_coupon_id']];
- $coupon_user_relate_model->is_giving = 0;
- $coupon_user_relate_model->giving_status = 0;
- $res = $coupon_user_relate_model->save();
- if($res){
- var_dump('user_coupon_id:'.$item['user_coupon_id'].'退回成功');
- }
- $res = $item->delete();
- if($res){
- \Yii::error('id:'.$item['id'].'删除分享记录成功');
- }
- }
- }
- }
- }
- }
- $i++;
- }
- }
- }
- }
|