| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790 |
- <?php
- namespace addons\BusinessBonus\common\models;
- use addons\BusinessBonus\common\enums\BusinessBonusEnums;
- use addons\IssueCoupons\common\models\IssueCouponsRule;
- use addons\Mch\common\models\Mch;
- use addons\Store\common\enums\StoreEnum;
- use addons\Store\common\models\Store;
- use addons\Store\common\models\StoreOrderDetail;
- use addons\Store\common\models\StoreSettings;
- use addons\Mch\common\models\MchSettings;
- use common\components\export\CsvTool;
- use common\enums\AddonsEnum;
- use common\enums\DownloadEnum;
- use common\enums\StatusEnum;
- use common\models\common\Download;
- use common\models\order\OrderDetail;
- use common\enums\UserWalletEnum;
- use common\models\user\User;
- use services\common\UserWalletService;
- use addons\Store\common\models\StoreGoods;
- use Yii;
- use yii\db\Exception;
- /**
- * This is the model class for table "{{%addons_business_bonus_reward}}".
- *
- * @property int $id updated_at
- * @property int|null $mall_id 商城ID
- * @property int|null $user_id 会员ID
- * @property int|null order_id 订单ID
- * @property string|null $order_no 订单号
- * @property int|null $settle_type 结算依据:1订单金额,2利润金额
- * @property float|null $settle_amount 结算金额
- * @property float|null $bonus_rate 分红比例,5%,填5
- * @property float|null $bonus_amount 分红金额
- * @property int|null $bonus_status 结算状态:0待结算,1已结算
- * @property int|null $bonus_time 分红时间
- * @property int|null $settle_time 结算时间,跑任务用
- * @property int|null $bonus_type 分红类型:1招商分红
- * @property int|null $from_type 来源类型:1门店,2多商户
- * @property int|null $store_id 门店、多商户的ID
- * @property int|null $status 状态:-1删除,0禁用,1启用
- * @property int|null $created_at 创建时间
- * @property int|null $updated_at 更新时间
- */
- class BusinessBonusReward extends \common\models\base\BaseActiveRecord
- {
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%addons_business_bonus_reward}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['mall_id', 'user_id', 'order_id', 'settle_base_on', 'bonus_status', 'bonus_time', 'settle_time', 'bonus_type', 'from_type', 'store_id', 'status', 'created_at', 'updated_at'], 'integer'],
- [['settle_amount', 'bonus_rate', 'bonus_amount'], 'number'],
- [['order_no'], 'string', 'max' => 32],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'updated_at',
- 'mall_id' => '商城ID',
- 'user_id' => '会员ID',
- 'order_id' => '订单ID',
- 'order_no' => '订单号',
- 'settle_base_on' => '结算依据:1订单金额,2利润金额',
- 'settle_amount' => '结算金额',
- 'bonus_rate' => '分红比例,5%,填5',
- 'bonus_amount' => '分红金额',
- 'bonus_status' => '结算状态:0待结算,1已结算',
- 'bonus_time' => '分红时间',
- 'settle_time' => '结算时间,跑任务用',
- 'bonus_type' => '分红类型:1招商分红',
- 'from_type' => '来源类型:1门店,2多商户',
- 'store_id' => '门店、多商户的ID',
- 'status' => '状态:-1删除,0禁用,1启用',
- 'created_at' => '创建时间',
- 'updated_at' => '更新时间',
- ];
- }
- /**
- * 数据设置
- */
- public static function setData(array $params)
- {
- try{
- if (!isset($params['mall_id']) || empty($params['mall_id'])) throw new Exception('缺少商城ID');
- if (isset($params['id']) && !empty($params['id'])) {
- $model = self::findOne(['id' => $params['id'], 'mall_id' => $params['mall_id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
- if(empty($model)) throw new Exception('分红记录不存在或已删除');
- } else {
- $model = new self();
- $model->loadDefaultValues();
- $model->mall_id = $params['mall_id'];
- }
- if (!$model->load($params,'') || !$model->save()) throw new Exception($model->getErrorMessage());
- return $model;
- }catch(Exception $e){
- self::setStaticError($e->getMessage());
- return false;
- }
- }
- /**
- * 关联用户
- * @return \yii\db\ActiveQuery
- */
- public function getUser()
- {
- return $this->hasOne(User::class, ['id' => 'user_id'])->select('id,mobile,nickname,avatar_url,parent_id,username');
- }
- /**
- * 结算门店(或多商户)订单分红
- * 注意:调用此方法必须用try {} catch() {} 和 事务,会抛出异常
- */
- public static function settleStoreOrderReward($store_order, $config, $store_type)
- {
- if ($store_type == BusinessBonusEnums::STORE_TYPE_STORE) { // 门店
- $from_type = BusinessBonusEnums::FROM_TYPE_STORE;
- } else { // 多商户
- $from_type = BusinessBonusEnums::FROM_TYPE_MCH;
- }
- // 防止重发 当结算方式改变后,有可能会再次执行
- $is_repeact = self::getOne([
- ['=', 'mall_id', $store_order['mall_id']],
- ['=', 'order_id', $store_order['id']],
- ['=', 'from_type', $from_type],
- ], true);
- if ($is_repeact) {
- self::setStaticError('该订单已发放分红');
- return false;
- }
- $detail_where = [];
- $detail_where['where'][] = ['order_id' => $store_order['id']];
- $detail_where['select'] = 'order_id,goods_id,goods_name,cost_price,goods_price,price,num,original_goods_price';
- if ($store_type == BusinessBonusEnums::STORE_TYPE_STORE) {
- $store_order_detail = StoreOrderDetail::lists($detail_where);
- } else {
- $store_order_detail = OrderDetail::lists($detail_where);
- }
- if (!$store_order_detail) {
- self::setStaticError('订单商品不存在');
- return false;
- }
- $goods_cost = 0; // 商品成本总价
- foreach ($store_order_detail as $detail) {
- $goods_cost += ($detail['cost_price'] * $detail['num']);
- }
- $settle_base_on = $config['settle_base_on'] ?? BusinessBonusEnums::SETTLE_BASE_ON_PAY;
- // 利润金额 = 实付金额 - 运费 - 退款金额 - 商品成本
- $order_earn = $store_order['pay_money'] - $store_order['shipping_money'] - $store_order['refund_money'] - $goods_cost;
- $settle_amount = 0; // 结算金额
- // 结算依据:订单金额(不包括运费和抵扣金额)
- if ($settle_base_on == BusinessBonusEnums::SETTLE_BASE_ON_PAY) {
- // 实付金额本身不包含抵扣金额
- // 订单金额 = 实付金额 - 运费 - 退款金额
- $settle_amount = $store_order['pay_money'] - $store_order['shipping_money'] - $store_order['refund_money'];
- }
- // 结算依据:利润金额(订单最终价格-成本)负数取0
- else if ($settle_base_on == BusinessBonusEnums::SETTLE_BASE_ON_EARN) {
- // 利润金额 = 实付金额 - 运费 - 退款金额 - 商品成本
- $settle_amount = $order_earn;
- }
- //结算依据:商品售价
- else if ($settle_base_on == BusinessBonusEnums::SETTLE_BASE_ON_GOODS_PRICE) {
- $goods_price = 0;
- foreach ($store_order_detail as $detail) {
- if ($store_type == BusinessBonusEnums::STORE_TYPE_STORE) {
- $storeGoods = StoreGoods::getOne([['id' => $detail['goods_id']]], true, ['extra']);
- if(!empty($storeGoods['extra']['is_alone_settle'])){
- $goods_price += $storeGoods['extra']['alone_settle_price'] * $detail['num'];
- }else{
- $goods_price += $detail['original_goods_price'];
- }
- } else {
- $goods_price += $detail['original_goods_price'];
- }
- }
- $settle_amount = $goods_price;
- } else if ($settle_base_on == BusinessBonusEnums::SETTLE_BASE_ON_SERVICE_CHARGE) {
- $settle_amount = self::computeServiceCharge($store_order, $store_type);
- }
- if ($settle_amount <= 0) {
- self::setStaticError('结算金额小于等于0');
- return false;
- }
- if ($store_type == BusinessBonusEnums::STORE_TYPE_STORE) {
- // 门店信息
- $store_info = Store::findOne(['id' => $store_order['store_id']]);
- } else {
- // 商户信息
- $store_info = Mch::findOne(['id' => $store_order['mch_id']]);
- }
- if (!$store_info) {
- self::setStaticError('门店或商户不存在');
- return false;
- }
- // 查找门店店主的上级是否是招商员
- $store_user = User::findOne(['id' => $store_info['user_id']]);
- if ($store_user['parent_id'] <= 0) {
- self::setStaticError('门店店主推荐人不存在');
- return false;
- }
- $parent_business_user = BusinessBonusUser::getOne([
- ['=', 'mall_id', $store_user['mall_id']],
- ['=', 'user_id', $store_user['parent_id']],
- ['>', 'status', StatusEnum::DISABLED], // 禁用后不给予奖励
- ], true);
- if (!$parent_business_user) {
- self::setStaticError('门店店主推荐人不是招商员或已禁用');
- return false;
- }
- if ($store_info['created_at'] < $parent_business_user['register_time']) {
- self::setStaticError('推荐人成为招商员之前门店或商户已存在,不予奖励');
- return false;
- }
- // 获取分红比例
- $business_level = BusinessBonusLevel::getOne([
- ['=', 'mall_id', $store_user['mall_id']],
- ['=', 'level', $parent_business_user['business_bonus_level']],
- ['>', 'status', StatusEnum::DISABLED], // 禁用的等级不给予奖励
- ], true);
- if (!$business_level) {
- self::setStaticError('招商员等级不存在或已禁用');
- return false;
- }
- // 计算出分红金额
- $bonus_amount = $settle_amount * $business_level['bonus_rate'] / 100;
- if ($bonus_amount < 0.01) { // 只精确2位数
- self::setStaticError('分红金额小于0.01');
- return false;
- }
- // 结算周期
- $settle_circle = $config['settle_circle'] ?? BusinessBonusEnums::SETTLE_CIRCLE_DAY;
- if ($settle_circle == BusinessBonusEnums::SETTLE_CIRCLE_DAY) { // 一天 (凌晨)
- $settle_time = strtotime ('tomorrow');
- } else if ($settle_circle == BusinessBonusEnums::SETTLE_CIRCLE_WEEK) { // 一周 (下周一)
- $settle_time = strtotime('next Monday');
- } else { // 一个月 (下月1号)
- $settle_time = strtotime('midnight first day of next month');
- }
- // 保存数据
- $settle_base_on = 1;
- $reward_data = [
- 'mall_id' => $store_user['mall_id'],
- 'user_id' => $parent_business_user['user_id'],
- 'order_id' => $store_order['id'],
- 'order_no' => $store_order['order_no'],
- 'settle_base_on' => $settle_base_on,
- 'settle_amount' => $settle_amount,
- 'bonus_rate' => $business_level['bonus_rate'],
- 'bonus_amount' => $bonus_amount,
- 'bonus_status' => BusinessBonusEnums::BONUS_STATUS_TODO,
- 'bonus_time' => 0,
- 'settle_time' => $settle_time, // 预结算时间
- 'bonus_type' => BusinessBonusEnums::BONUS_TYPE_BUSINESS,
- 'from_type' => $from_type,
- 'store_id' => $store_info['id'],
- 'status' => StatusEnum::ENABLED
- ];
- // 门店统计
- $store_data = [
- 'mall_id' => $store_user['mall_id'],
- 'store_id' => $store_info['id'],
- 'store_type' => $store_type,
- 'store_user_id' => $store_info['user_id'],
- 'business_user_id' => $parent_business_user['user_id'],
- 'history_income' => $store_order['pay_money'], // 累计收入
- 'history_earn' => $order_earn, // 累计利润
- 'store_created_at' => $store_info['created_at']
- ];
- $user_data = [
- 'id' => $parent_business_user['id'],
- 'mall_id' => $store_user['mall_id'],
- ];
- $store_exist = BusinessBonusStore::findOne(['mall_id' => $store_data['mall_id'], 'store_id' => $store_data['store_id'], 'store_type' => $store_data['store_type'], 'status' => [StatusEnum::DISABLED, StatusEnum::ENABLED]]);
- if (!$store_exist) {
- if ($store_type == BusinessBonusEnums::STORE_TYPE_STORE) {
- $user_data['store_number'] = 1;
- } else {
- $user_data['mch_number'] = 1;
- }
- }
- // 调用方法必须用try {} catch() {}
- $res = self::setData($reward_data);
- if ($res == false) throw new Exception(self::getStaticError());
- $res = BusinessBonusStore::setData($store_data);
- if ($res == false) throw new Exception(BusinessBonusStore::getStaticError());
- if (isset($user_data['mch_number']) || isset($user_data['store_number'])) {
- $res = BusinessBonusUser::setData($user_data);
- if ($res == false) throw new Exception(BusinessBonusUser::getStaticError());
- }
- return true;
- }
- public static function settleStoreOrderRewardByCashierOrder($store_order, $config, $store_type)
- {
- $from_type = BusinessBonusEnums::FROM_TYPE_STORE_CASHIER;
- // 防止重发 当结算方式改变后,有可能会再次执行
- $is_repeact = self::getOne([
- ['=', 'mall_id', $store_order['mall_id']],
- ['=', 'order_id', $store_order['id']],
- ['=', 'from_type', $from_type],
- ], true);
- if ($is_repeact) {
- self::setStaticError('该订单已发放分红');
- return false;
- }
- // 结算依据:订单实际支付金额
- $settle_amount = $store_order['pay_money'];
- if ($settle_amount <= 0) {
- self::setStaticError('结算金额小于等于0');
- return false;
- }
- $order_earn = $settle_amount;
- // 门店信息
- $store_info = Store::findOne(['id' => $store_order['store_id']]);
- if (!$store_info) {
- self::setStaticError('门店或商户不存在');
- return false;
- }
- // 查找门店店主的上级是否是招商员
- $store_user = User::findOne(['id' => $store_info['user_id']]);
- if ($store_user['parent_id'] <= 0) {
- self::setStaticError('门店店主推荐人不存在');
- return false;
- }
- $parent_business_user = BusinessBonusUser::getOne([
- ['=', 'mall_id', $store_user['mall_id']],
- ['=', 'user_id', $store_user['parent_id']],
- ['>', 'status', StatusEnum::DISABLED], // 禁用后不给予奖励
- ], true);
- if (!$parent_business_user) {
- self::setStaticError('门店店主推荐人不是招商员或已禁用');
- return false;
- }
- if ($store_info['created_at'] < $parent_business_user['register_time']) {
- self::setStaticError('推荐人成为招商员之前门店或商户已存在,不予奖励');
- return false;
- }
- // 获取分红比例
- $business_level = BusinessBonusLevel::getOne([
- ['=', 'mall_id', $store_user['mall_id']],
- ['=', 'level', $parent_business_user['business_bonus_level']],
- ['>', 'status', StatusEnum::DISABLED], // 禁用的等级不给予奖励
- ], true);
- if (!$business_level) {
- self::setStaticError('招商员等级不存在或已禁用');
- return false;
- }
- // 计算出分红金额
- $bonus_amount = $settle_amount * $business_level['bonus_rate'] / 100;
- if ($bonus_amount < 0.01) { // 只精确2位数
- self::setStaticError('分红金额小于0.01');
- return false;
- }
- // 结算周期
- $settle_circle = $config['settle_circle'] ?? BusinessBonusEnums::SETTLE_CIRCLE_DAY;
- if ($settle_circle == BusinessBonusEnums::SETTLE_CIRCLE_DAY) { // 一天 (凌晨)
- $settle_time = strtotime ('tomorrow');
- } else if ($settle_circle == BusinessBonusEnums::SETTLE_CIRCLE_WEEK) { // 一周 (下周一)
- $settle_time = strtotime('next Monday');
- } else { // 一个月 (下月1号)
- $settle_time = strtotime('midnight first day of next month');
- }
- // 保存数据
- $reward_data = [
- 'mall_id' => $store_user['mall_id'],
- 'user_id' => $parent_business_user['user_id'],
- 'order_id' => $store_order['id'],
- 'order_no' => $store_order['order_no'],
- 'settle_base_on' => 1,
- 'settle_amount' => $settle_amount,
- 'bonus_rate' => $business_level['bonus_rate'],
- 'bonus_amount' => $bonus_amount,
- 'bonus_status' => BusinessBonusEnums::BONUS_STATUS_TODO,
- 'bonus_time' => 0,
- 'settle_time' => $settle_time, // 预结算时间
- 'bonus_type' => BusinessBonusEnums::BONUS_TYPE_BUSINESS,
- 'from_type' => $from_type,
- 'store_id' => $store_info['id'],
- 'status' => StatusEnum::ENABLED
- ];
- // 门店统计
- $store_data = [
- 'mall_id' => $store_user['mall_id'],
- 'store_id' => $store_info['id'],
- 'store_type' => $store_type,
- 'store_user_id' => $store_info['user_id'],
- 'business_user_id' => $parent_business_user['user_id'],
- 'history_income' => $store_order['pay_money'], // 累计收入
- 'history_earn' => $order_earn, // 累计利润
- 'store_created_at' => $store_info['created_at']
- ];
- $user_data = [
- 'id' => $parent_business_user['id'],
- 'mall_id' => $store_user['mall_id'],
- ];
- $store_exist = BusinessBonusStore::findOne(['mall_id' => $store_data['mall_id'], 'store_id' => $store_data['store_id'], 'store_type' => $store_data['store_type'], 'status' => [StatusEnum::DISABLED, StatusEnum::ENABLED]]);
- if (!$store_exist) {
- if ($store_type == BusinessBonusEnums::STORE_TYPE_STORE) {
- $user_data['store_number'] = 1;
- } else {
- $user_data['mch_number'] = 1;
- }
- }
- // 调用方法必须用try {} catch() {}
- $res = self::setData($reward_data);
- if ($res == false) throw new Exception(self::getStaticError());
- $res = BusinessBonusStore::setData($store_data);
- if ($res == false) throw new Exception(BusinessBonusStore::getStaticError());
- if (isset($user_data['mch_number']) || isset($user_data['store_number'])) {
- $res = BusinessBonusUser::setData($user_data);
- if ($res == false) throw new Exception(BusinessBonusUser::getStaticError());
- }
- return true;
- }
- public static function computeServiceCharge($order, $store_type)
- {
- $platform_ratio= 0;
- $price = $order['pay_money'];
- if ($store_type == BusinessBonusEnums::STORE_TYPE_STORE) {
- // 门店
- $store_settings = StoreSettings::getOne([['store_id' => $order['store_id']]]);
- $basic = \Yii::$app->services->setting->addons->get($order['mall_id'], StoreEnum::ADDONS_NAME, 'basic');
- } else {
- // 多商户
- $store_settings = MchSettings::getOne([['mch_id' => $order['mch_id']]]);
- $basic = \Yii::$app->services->setting->addons->get($order['mall_id'], AddonsEnum::ADDONS_NAME_MCH, 'basic');
- }
- if ($store_type == BusinessBonusEnums::STORE_TYPE_STORE) {
- if (isset($store_settings['store_service_fee']) && !empty($store_settings['store_service_fee'])) {
- $platform_ratio = $store_settings['store_service_ratio'] ?? 0;
- $service_fee_settle_type = $store_settings['store_service_fee_settle_type'] ?? 1;
- } else {
- $platform_ratio = $basic['platform_ratio'] ?? 0;
- $service_fee_settle_type = $basic['store_service_fee_settle_type'] ?? 1;
- }
- } else {
- if (isset($store_settings['individual_fee_setting']) && !empty($store_settings['individual_fee_setting'])) {
- $platform_ratio = $store_settings['store_service_ratio'] ?? 0;
- $service_fee_settle_type = $store_settings['store_service_fee_settle_type'] ?? 1;
- } else {
- $platform_ratio = $basic['platform_ratio'] ?? 0;
- $service_fee_settle_type = $basic['store_service_fee_settle_type'] ?? 1;
- }
- }
- if($service_fee_settle_type == 2){
- $price = $order['original_goods_price'];
- }elseif($service_fee_settle_type == 3){
- $price = StoreOrderDetail::find()->where(['order_id' => $order['id'],'status' => 1])->sum('cost_price');
- }
- return bcdiv($price * $platform_ratio,100,2);
- }
- /**
- * 结算分红并发放
- * @return bool
- */
- public static function sendBonus()
- {
- $redis_key = BusinessBonusEnums::ADDONS_NAME . ':BusinessBonusReward:sendBonus:lock';
- $redis_lock = Yii::$app->redis->get($redis_key);
- if ($redis_lock) {
- return false;
- }
- Yii::$app->redis->setex($redis_key, 86400, 1);
- $trans = Yii::$app->db->beginTransaction();
- try {
- $where = ['bonus_status'=>BusinessBonusEnums::BONUS_STATUS_TODO,'status'=>StatusEnum::ENABLED];
- $reward_list = self::find()->where(['and',$where,['<=', 'settle_time', time()]]);
- foreach ($reward_list->batch(200) as $detail){//分批查询标签
- $insert_wallet = [];
- foreach ($detail as $k=>$list){
- // 发放到推广中心可提现
- $order_type = $list['from_type'] == 1 ? '门店订单' : '商户订单';
- $desc = '用户(' . $list['user_id'] . '),获得' . $order_type . '(' . $list['order_id'] . ')奖励,奖励类型:招商分红,金额:' . $list['bonus_amount'];
- $insert_wallet[] = [
- 'mall_id' => $list['mall_id'],
- 'user_id' => $list['user_id'],
- 'is_frozen' => false,
- 'wallet_type' => UserWalletService::WALLET_TYPE_COMMISSION,
- 'money' => $list['bonus_amount'],
- 'desc' => $desc,
- 'source_table' => self::tableName(),
- 'source_table_id' => $list['id'],
- 'from_type' => UserWalletEnum::REWARD,
- 'capital_type'=> UserWalletEnum::BOUNS
- ];
- // 招商员增加累计分红
- $business_user = BusinessBonusUser::getOne([
- ['=', 'mall_id', $list['mall_id']],
- ['=', 'user_id', $list['user_id']],
- ['>=', 'status', StatusEnum::DISABLED]
- ], true, '', '', 'id');
- $user_data = [
- 'id' => $business_user['id'],
- 'user_id' => $list['user_id'],
- 'mall_id' => $list['mall_id'],
- 'history_bonus_amount' => $list['bonus_amount'],
- ];
- $res = BusinessBonusUser::setData($user_data);
- if ($res == false) throw new Exception(BusinessBonusUser::getStaticError());
- // 更改记录状态
- $update_data = [
- 'id' => $list['id'],
- 'mall_id' => $list['mall_id'],
- 'bonus_status' => BusinessBonusEnums::BONUS_STATUS_DONE,
- 'bonus_time' => time()
- ];
- $res = self::setData($update_data);
- if ($res == false) throw new Exception(self::getStaticError());
- }
- // 异步处理佣金
- if ($insert_wallet) {
- $res = UserWalletService::batchHandleByQueue($insert_wallet);
- if (empty($res)) throw new Exception(UserWalletService::getStaticError());
- }
- }
- $trans->commit();
- } catch (\Exception $e) {
- $trans->rollBack();
- Yii::$app->redis->del($redis_key);
- return false;
- }
- Yii::$app->redis->del($redis_key);
- return true;
- }
- /**
- * 处理分红记录的列表数据,加上其他需要的信息
- * @param array $list
- * @param int $mall_id
- * @param bool $add_order_goods 是否包含商品信息
- * @return array $list
- */
- public static function dealRewardList(array $list, int $mall_id, $add_order_goods = false)
- {
- $store_ids = $mch_ids = [];
- $store_order_ids = $mch_order_ids = [];
- foreach ($list as $item) {
- if ( in_array($item['from_type'],[BusinessBonusEnums::FROM_TYPE_STORE,BusinessBonusEnums::FROM_TYPE_STORE_CASHIER]) ) { // 门店
- $store_ids[] = $item['store_id'];
- $store_order_ids[] = $item['order_id'];
- } else if ($item['from_type'] == BusinessBonusEnums::FROM_TYPE_MCH) { // 多商户
- $mch_ids[] = $item['store_id'];
- $mch_order_ids[] = $item['order_id'];
- }
- }
- $store_array = $mch_array = [];
- if ($store_ids) {
- $store_list = Store::find()
- ->select('id,user_id,store_name')
- ->andWhere(['>=', 'status', StatusEnum::DISABLED])
- ->andWhere(['in', 'id', $store_ids])
- ->andWhere(['=', 'mall_id', $mall_id])
- ->asArray()
- ->all();
- $store_array = array_column($store_list, null, 'id');
- }
- if ($mch_ids) {
- $mch_list = Mch::find()
- ->select('id,user_id,store_name')
- ->andWhere(['>=', 'status', StatusEnum::DISABLED])
- ->andWhere(['in', 'id', $mch_ids])
- ->andWhere(['=', 'mall_id', $mall_id])
- ->asArray()
- ->all();
- $mch_array = array_column($mch_list, null, 'id');
- }
- $store_order_goods = $mch_order_goods = [];
- $select = 'id,order_id,goods_name,goods_price,num,pic_url';
- $order = 'id asc';
- if ($store_order_ids && $add_order_goods) {
- $where = [
- ['=', 'mall_id', $mall_id],
- ['=', 'status', StatusEnum::ENABLED],
- ['in', 'order_id', $store_order_ids],
- ];
- $condition = compact('where', 'select', 'order');
- $store_order_detail = StoreOrderDetail::lists($condition, true);
- foreach ($store_order_detail as $item) {
- $store_order_goods[$item['order_id']][] = $item;
- }
- }
- if ($mch_order_ids && $add_order_goods) {
- $where = [
- ['=', 'mall_id', $mall_id],
- ['=', 'status', StatusEnum::ENABLED],
- ['in', 'order_id', $mch_order_ids]
- ];
- $condition = compact('where', 'select', 'order');
- $mch_order_detail = OrderDetail::lists($condition, true);
- foreach ($mch_order_detail as $item) {
- $mch_order_goods[$item['order_id']][] = $item;
- }
- }
- foreach ($list as $key => $val) {
- $val['created_at_'] = date('Y-m-d H:i:s', $val['created_at']);
- $val['created_ats'] = date('Y/m/d', $val['created_at']);
- $val['store_name'] = '';
- $add_order_goods && $val['order_goods'] = [];
- if ( in_array($val['from_type'],[BusinessBonusEnums::FROM_TYPE_STORE,BusinessBonusEnums::FROM_TYPE_STORE_CASHIER]) ) { // 门店
- $val['store_name'] = $store_array[$val['store_id']]['store_name'] ?? '';
- $add_order_goods && $val['order_goods'] = $store_order_goods[$val['order_id']] ?? [];
- } else if ($val['from_type'] == BusinessBonusEnums::FROM_TYPE_MCH) { // 多商户
- $val['store_name'] = $mch_array[$val['store_id']]['store_name'] ?? '';
- $add_order_goods && $val['order_goods'] = $mch_order_goods[$val['order_id']] ?? [];
- }
- $list[$key] = $val;
- }
- return $list;
- }
- /**
- * 统计用户某个时间段的分红
- * @param $mall_id
- * @param $user_id
- * @param $start_time
- * @param $end_time
- * @return float
- */
- public static function getCustomStatistic($mall_id, $user_id, $start_time, $end_time)
- {
- $number = self::find()
- ->andWhere(['=', 'mall_id', $mall_id])
- ->andWhere(['=', 'user_id', $user_id])
- ->andWhere(['>=', 'created_at', $start_time])
- ->andWhere(['<=', 'created_at', $end_time])
- ->andWhere(['=', 'status', StatusEnum::ENABLED])
- ->sum('bonus_amount');
- return (float) $number;
- }
- /**
- * 可导出的字段
- * @param null $field
- * @return array
- */
- public static function fieldsList($field = null)
- {
- $fields = [
- 'id' => '序号',
- 'order_no' => '订单编号',
- 'user_id' => '招商员ID',
- 'nickname' => '招商员昵称',
- 'mobile' => '招商员手机号',
- 'settle_base_on' => '结算依据',
- 'settle_amount' => '结算金额',
- 'bonus_rate' => '分红比例(%)',
- 'bonus_amount' => '分红金额',
- 'bonus_status' => '状态',
- 'bonus_time' => '结算时间',
- 'settle_time' => '预结算时间',
- 'store_name' => '所属门店',
- 'from_type' => '来源类型',
- 'created_at' => '创建时间',
- ];
- if ($field === null) return $fields;
- $temp = [];
- foreach ($field as $val) {
- $temp[$val] = $fields[$val] ?? $val;
- }
- return $temp;
- }
- /**
- * 导出处理手柄
- */
- public static function exportHandle(array $data)
- {
- $download_id = $data['download_id'] ?? 0;
- $download = Download::findOne(['id' => $download_id]);
- if ($download) {
- try {
- $params = json_decode($download->params, true);
- $condition = $params['condition'];
- $list = self::lists($condition, true);
- $list = self::dealRewardList($list, $params['mall_id'], false);
- $filename = $download->name;
- $type = $download->type;
- $fields = $params['fields'];
- $fields_arr = self::fieldsList();
- $have_select_field_arr = [];
- foreach ($fields as $value) {
- $have_select_field_arr[] = $fields_arr[$value];
- }
- $csv = new CsvTool();
- $csv->filename = $filename;
- $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($type);
- $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
- $csv->header = $have_select_field_arr;
- $csv_data = [];
- foreach ($list as $data) {
- $row = [];
- foreach ($fields as $field) {
- switch ($field) {
- case (in_array($field, ['bonus_time', 'settle_time', 'created_at'])):
- $row[] = ($data[$field] ?? '') ? date('Y-m-d H:i:s', $data[$field] ?? '') : '';
- break;
- case (in_array($field, ['mobile', 'nickname'])):
- $row[] = $data['user'][$field] ?? '';
- break;
- case 'settle_base_on':
- $value = $data[$field] ?? 0;
- $temp = '';
- if ($value == BusinessBonusEnums::SETTLE_BASE_ON_PAY) {
- $temp = '订单金额';
- } else if ($value == BusinessBonusEnums::SETTLE_BASE_ON_EARN) {
- $temp = '订单利润';
- }
- $row[] = $temp;
- break;
- case 'bonus_status':
- $value = $data[$field] ?? 0;
- $temp = '';
- if ($value == BusinessBonusEnums::BONUS_STATUS_TODO) {
- $temp = '待结算';
- } else if ($value == BusinessBonusEnums::BONUS_STATUS_DONE) {
- $temp = '已结算';
- }
- $row[] = $temp;
- break;
- case 'from_type':
- $value = $data[$field] ?? 0;
- $temp = '';
- if ($value == BusinessBonusEnums::FROM_TYPE_STORE) {
- $temp = '门店';
- } else if ($value == BusinessBonusEnums::FROM_TYPE_MCH) {
- $temp = '商户';
- }
- $row[] = $temp;
- break;
- default:
- $row[] = $data[$field] ?? '';
- break;
- }
- }
- $csv_data[] = $row;
- }
- $csv->data = $csv_data;
- $csv->export();
- $csv->updateDown($download, $params['mall_id']);
- return true;
- } catch (Exception $e) {
- $download->status = 3;
- $download->save();
- self::setStaticError($e->getMessage());
- return $e->getMessage();
- }
- }
- }
- }
|