| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\modules\admin\models;
- use app\models\Cat;
- use app\models\Goods;
- use app\models\GoodsCat;
- use app\models\ActivityOrderRebateSelf;
- use app\models\ActivityOrderRebateSelfLevel;
- use app\models\ActivityOrderRebateSelfGoods;
- use app\models\ActivityOrderRebateSelfOrder;
- use app\models\ActivityOrderRebateSelfLog;
- use app\models\ActivityOrderRebateSelfUser;
- use app\models\AccountLog;
- use app\models\UserShareMoney;
- use app\models\Store;
- use app\models\User;
- use yii\base\Model;
- use app\models\Option;
- use app\constants\OptionSetting;
- use app\models\SaasUser;
- use app\models\Order;
- use app\models\Attr;
- use app\models\AttrGroup;
- use app\models\OrderDetail;
- use app\models\IntegralAppreciationPool;
- class ActivityOrderRebateSelfForm extends Model
- {
- public $store_id;
- public $saas_id;
- public $user_id;
- public $id;
- public $act_id;
- public $ids;
- public $name;
- public $start_time;
- public $end_time;
- public $status;
- public $goods_ids;
- public $goods_name;
- public $send_type;
- public $send_time;
- public $send_num;
- public $send_days;
- // 新增字段
- public $send_types;
- public $send_type_percentages;
- public $release_rate;
- public $send_rebate_type;
- public $fixed_rebate_profit;
- public $level;
- public $money;
- public $child_num;
- public $child_level;
- public $add_rat;
- public $add_rebate;
- public $phone;
- public $order_no;
- public $is_send;
- public $admin;
- public function rules()
- {
- return [
- [['status', 'id', 'send_rebate_type'], 'integer'],
- [['start_time', 'end_time', 'ids', 'name'], 'string'],
- [[
- 'goods_name',
- 'store_id',
- 'goods_ids',
- 'act_id',
- 'send_type',
- 'send_time',
- 'send_num',
- 'send_days',
- 'saas_id',
- 'user_id'
- ], 'safe'],
- [[
- 'level',
- 'money',
- 'child_num',
- 'child_level',
- 'add_rat',
- 'add_rebate'
- ], 'safe'],
- [['order_no'], 'safe'],
- [['is_send'], 'safe'],
- [['phone'], 'safe'],
- [['fixed_rebate_profit'], 'number'],
- // 新增规则
- [['send_types', 'send_type_percentages', 'release_rate'], 'safe']
- ];
- }
- public function init()
- {
- parent::init();
- if (empty($this->store_id)) {
- $this->store_id = get_store_id();
- }
- }
- /**
- * 导入会员增加积分和佣金
- * @return array
- */
- public function importUserRecharge()
- {
- $admin = \Yii::$app->jwt->getAdmin();
- $store_id = $this->store_id;
- // 获取活动类型参数
- $activity_type = post_params('send_type', 'integral'); // 默认为积分活动
- $activity_id = post_params('activity_id', 0); // 获取选择的活动ID
-
- set_time_limit(0);
- $filename = $_FILES['excel']['name'];
- $tmpname = $_FILES['excel']['tmp_name'];
- $path = \Yii::$app->basePath . '/web/temp/';
- if(!is_dir($path)){
- mkdir($path);
- }
- $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
- if (($ext != 'xlsx') && ($ext != 'xls')) {
- return [
- 'code' => 1,
- 'msg' => '请上传excel文件'
- ];
- }
- $file = time() . $this->store_id . '.' . $ext;
- $uploadfile = $path . $file;
- move_uploaded_file($tmpname, $uploadfile);
-
- $rows = \Spatie\SimpleExcel\SimpleExcelReader::create($uploadfile)
- ->getRows();
- $err = [];
- $success = [];
- // 如果指定了活动ID,则获取该活动
- $activity = null;
- if ($activity_id) {
- $activity = ActivityOrderRebateSelf::findOne($activity_id);
- if (!$activity) {
- return [
- 'code' => 1,
- 'msg' => '指定的活动不存在'
- ];
- }
-
- // 获取活动关联的产品
- $product = Goods::findOne($activity->goods_ids);
- if (!$product) {
- // 如果找不到产品,创建一个新产品
- $product = $this->createProduct($store_id, $activity->name . '导入产品');
- }
- } else {
- return [
- 'code' => 1,
- 'msg' => '指定的活动不存在'
- ];
- // 如果没有指定活动ID,则创建默认产品和活动
- // $product = $this->createProduct($store_id, '积分余额导入产品');
- //
- // // 根据活动类型创建不同的活动
- // switch ($activity_type) {
- // case 'integral':
- // $activity = $this->createActivity($store_id, '积分导入活动', $product->id, [2], [2=>100]);
- // break;
- // case 'balance':
- // $activity = $this->createActivity($store_id, '余额导入活动', $product->id, [3], [3=>100]);
- // break;
- // case 'commission':
- // $activity = $this->createActivity($store_id, '佣金导入活动', $product->id, [1], [1=>100]);
- // break;
- // default:
- // $activity = $this->createActivity($store_id, '积分余额导入活动', $product->id, [1,2,3], [1=>33,2=>33,3=>34]);
- // }
- }
-
- // 统计每种类型的成功和失败数量
- $stats = [
- 'balance' => ['success' => 0, 'fail' => 0],
- 'integral' => ['success' => 0, 'fail' => 0],
- 'commission' => ['success' => 0, 'fail' => 0]
- ];
-
- $rows->each(function (array $item) use ($admin, $store_id, &$err, &$success, &$stats, $activity, $activity_type, $product) {
- try {
- $mobile = trim($item['手机号']);
- $nickname = trim($item['昵称']);
- $change = isset($item['余额']) ? trim($item['余额']) : 0;
- $integral = isset($item['积分']) ? trim($item['积分']) : 0;
- $commission = isset($item['佣金']) ? trim($item['佣金']) : 0;
- $desc = trim($item['余额变动备注']) ? trim($item['余额变动备注']) : '';
- if ($activity->send_type ==1 && $commission == 0) {
- throw new \Exception('导入失败:请用佣金模板导入' );
- }
- if ($activity->send_type ==2 && $integral == 0) {
- throw new \Exception('导入失败:请用积分模板导入' );
- }
- if ($activity->send_type ==3 && $change == 0) {
- throw new \Exception('导入失败:请用余额模板导入' );
- }
-
- // 查找或创建用户
- $user = $this->findOrCreateUser($mobile, $nickname, $store_id);
- // $product = $activity = [];
- // if (empty($product)) {
- // $product = $this->createProduct($store_id, '积分余额导入产品');
- // $activity = $this->createActivity($store_id, '积分余额导入活动', $product->id, [1,2,3], [1=>33,2=>33,3=>34]);
- // }
- // 根据活动类型处理不同的数据
- switch ($activity_type) {
- case 'integral':
- if ($integral != 0) {
- try {
- $this->createOrder($user, $product, $activity, abs($integral), $store_id, '积分');
- $stats['integral']['success']++;
- } catch (\Exception $e) {
- $stats['integral']['fail']++;
- $err[] = [
- 'code' => 1,
- 'msg' => '处理积分失败: ' . $e->getMessage(),
- 'mobile' => $mobile
- ];
- }
- }
- break;
- case 'balance':
- if ($change != 0) {
- try {
- $this->createOrder($user, $product, $activity, abs($change), $store_id, '余额');
- $stats['balance']['success']++;
- } catch (\Exception $e) {
- $stats['balance']['fail']++;
- $err[] = [
- 'code' => 1,
- 'msg' => '处理余额失败: ' . $e->getMessage(),
- 'mobile' => $mobile
- ];
- }
- }
- break;
- case 'commission':
- if ($commission != 0) {
- try {
- $this->createOrder($user, $product, $activity, abs($commission), $store_id, '佣金');
- $stats['commission']['success']++;
- } catch (\Exception $e) {
- $stats['commission']['fail']++;
- $err[] = [
- 'code' => 1,
- 'msg' => '处理佣金失败: ' . $e->getMessage(),
- 'mobile' => $mobile
- ];
- }
- }
- break;
- default:
- // 处理所有类型
- // 处理余额增减
- if ($change != 0) {
- try {
- $this->createOrder($user, $product, $activity, abs($change), $store_id, '余额');
- $stats['balance']['success']++;
- } catch (\Exception $e) {
- $stats['balance']['fail']++;
- $err[] = [
- 'code' => 1,
- 'msg' => '处理余额失败: ' . $e->getMessage(),
- 'mobile' => $mobile
- ];
- }
- }
-
- // 处理积分增减
- if ($integral != 0) {
- try {
- $this->createOrder($user, $product, $activity, abs($integral), $store_id, '积分');
- $stats['integral']['success']++;
- } catch (\Exception $e) {
- $stats['integral']['fail']++;
- $err[] = [
- 'code' => 1,
- 'msg' => '处理积分失败: ' . $e->getMessage(),
- 'mobile' => $mobile
- ];
- }
- }
-
- // 处理佣金增减
- if ($commission != 0) {
- try {
- $this->createOrder($user, $product, $activity, abs($commission), $store_id, '佣金');
- $stats['commission']['success']++;
- } catch (\Exception $e) {
- $stats['commission']['fail']++;
- $err[] = [
- 'code' => 1,
- 'msg' => '处理佣金失败: ' . $e->getMessage(),
- 'mobile' => $mobile
- ];
- }
- }
- }
-
- $success[] = [
- 'mobile' => $mobile,
- 'nickname' => $nickname,
- 'change' => $change,
- 'integral' => $integral,
- 'commission' => $commission
- ];
-
- } catch (\Exception $e){
- debug_log($e->getMessage());
- $err[] = [
- 'code' => 1,
- 'msg' => $e->getMessage(),
- 'mobile' => $mobile
- ];
- }
- });
-
- $count = count($err);
- $successCount = count($success);
- @unlink($uploadfile);
-
- // 生成详细的统计信息
- $statMsg = sprintf(
- "余额导入成功%d条,失败%d条;积分导入成功%d条,失败%d条;佣金导入成功%d条,失败%d条",
- $stats['balance']['success'], $stats['balance']['fail'],
- $stats['integral']['success'], $stats['integral']['fail'],
- $stats['commission']['success'], $stats['commission']['fail']
- );
- if ($activity->send_type == 1) {
- $statMsg = sprintf(
- "佣金导入成功%d条,失败%d条",
- $stats['commission']['success'], $stats['commission']['fail']
- );
- }
- if ($activity->send_type == 2) {
- $statMsg = sprintf(
- "积分导入成功%d条,失败%d条",
- $stats['integral']['success'], $stats['integral']['fail']
- );
- }
- if ($activity->send_type == 3) {
- $statMsg = sprintf(
- "余额导入成功%d条,失败%d条",
- $stats['balance']['success'], $stats['balance']['fail']
- );
- }
-
- return [
- 'code' => $count ? 1 : 0,
- 'msg' => "操作完成,导入条数据" . ($err ? ",失败{$count}条数据" : '') . "\n{$statMsg}",
- 'err' => $err,
- 'success' => $success,
- ];
- }
-
- /**
- * 创建活动产品
- * @param int $store_id 店铺ID
- * @param string $name 产品名称
- * @return Goods 产品对象
- */
- public function createProduct($store_id, $name)
- {
- $product = new Goods();
- $product->store_id = $store_id;
- $product->name = $name;
- $product->detail = $name . '详情';
- $product->price = 1; // 产品金额1元
- $product->status = 0;
- $product->created_at = time();
- $product->updated_at = time();
-
- if (!$product->save()) {
- throw new \Exception('创建活动产品失败:' . json_encode($product->errors));
- }
-
- return $product;
- }
-
- /**
- * 创建活动
- * @param int $store_id 店铺ID
- * @param string $name 活动名称
- * @param int $product_id 产品ID
- * @param array $send_types 返利类型
- * @param array $send_type_percentages 返利比例
- * @return ActivityOrderRebateSelf 活动对象
- */
- public function createActivity($store_id, $name, $product_id, $send_types, $send_type_percentages, $release_rate = 10)
- {
- $activity = new ActivityOrderRebateSelf();
- $activity->store_id = $store_id;
- $activity->name = $name . '-' . date('YmdHis');
- $activity->start_time = time();
- $activity->end_time = time() + 86400 * 30; // 30天后结束
- $activity->goods_ids = $product_id; // 产品
- $activity->send_days = 1; // 周期
- $activity->send_num = 100; // 返利比例
- $activity->send_types = json_encode($send_types); // 返利类型
- $activity->send_type_percentages = json_encode($send_type_percentages); // 返利比例
- $activity->status = 1; // 活动状态:启用
- $activity->release_rate = $release_rate;
- $activity->created_at = time();
- $activity->updated_at = time();
-
- if (!$activity->save()) {
- throw new \Exception('创建活动失败:' . json_encode($activity->errors));
- }
-
- $gids = [$product_id];
- if(!empty($gids)){
- $result = ActivityOrderRebateSelfGoods::saveList($gids, $activity->id);
- if ($result['code'] !== 0) {
- throw new \Exception($result['msg']);
- }
- }
-
- return $activity;
- }
-
- /**
- * 查找或创建用户
- * @param string $mobile 手机号
- * @param string $nickname 昵称
- * @param int $store_id 店铺ID
- * @return User 用户对象
- */
- private function findOrCreateUser($mobile, $nickname, $store_id)
- {
- $user = User::findOne(['binding' => $mobile, 'is_delete' => 0, 'store_id' => $store_id]);
- $saas_user = SaasUser::findOne(['mobile' => $mobile, 'is_delete' => 0]);
-
- if(!$user){
- if (!$saas_user) {
- $saas_user = new SaasUser();
- $saas_user->access_token = \Yii::$app->security->generateRandomString();
- $saas_user->avatar = \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . '/web/v1/statics/images/avatar.png';
- $saas_user->mobile = $mobile ?: '';
- $saas_user->name = $nickname ? $nickname : substr_replace($mobile, '******', 3, 6);
- $saas_user->store_id = $store_id;
- if (!$saas_user->save()) {
- throw new \Exception(array_shift($saas_user->getFirstErrors()));
- }
- }
-
- $user = new User();
- $user->access_token = \Yii::$app->security->generateRandomString();
- $user->binding = $saas_user->mobile;
- $user->nickname = $saas_user->name;
- $user->avatar_url = $saas_user->avatar;
- $user->username = \Yii::$app->security->generateRandomString();
- $user->password = \Yii::$app->security->generatePasswordHash(\Yii::$app->security->generateRandomString(), 5);
- $user->auth_key = \Yii::$app->security->generateRandomString();
- $user->store_id = $store_id;
- if (!$user->save()) {
- throw new \Exception(array_shift($user->getFirstErrors()));
- }
- }
-
- if($nickname && $nickname != $saas_user->name){
- $saas_user->name = $nickname;
- if (!$saas_user->save()) {
- throw new \Exception(array_shift($saas_user->getFirstErrors()));
- }
- }
-
- if($nickname && $nickname != $user->nickname){
- $user->nickname = $nickname;
- if (!$user->save()) {
- throw new \Exception(array_shift($user->getFirstErrors()));
- }
- }
-
- return $user;
- }
-
- /**
- * 处理余额增减
- * @param User $user 用户对象
- * @param float $change 变动金额
- * @param string $desc 变动描述
- * @param object $admin 管理员对象
- * @param int $store_id 店铺ID
- */
- private function processBalanceChange($user, $change, $desc, $admin, $store_id)
- {
- $recharge_type = ($change > 0) ? AccountLog::LOG_TYPE_INCOME : AccountLog::LOG_TYPE_EXPEND;
- $data = [
- 'explain' => '',
- 'money' => abs($change),
- 'integral' => 0,
- 'recharge_type' => $recharge_type,
- 'type' => AccountLog::TYPE_BALANCE,
- 'user_id' => $user->id,
- 'desc' => $desc
- ];
-
- if($recharge_type == AccountLog::LOG_TYPE_EXPEND && $user->money < $data['money']){
- $data['money'] = $user->money;
- }
-
- if($data['money'] > 0){
- $form = new AccountLogForm();
- $form->store_id = $store_id;
- $form->admin = $admin;
- $form->attributes = $data;
- $res = $form->recharge();
-
- if($res['code'] != 0){
- throw new \Exception($res['msg']);
- }
- }
- }
-
- /**
- * 处理积分增减
- * @param User $user 用户对象
- * @param float $integral 变动积分
- * @param string $desc 变动描述
- * @param object $admin 管理员对象
- * @param int $store_id 店铺ID
- */
- private function processIntegralChange($user, $integral, $desc, $admin, $store_id)
- {
- $recharge_type = ($integral > 0) ? AccountLog::LOG_TYPE_INCOME : AccountLog::LOG_TYPE_EXPEND;
- $data = [
- 'explain' => '',
- 'money' => 0,
- 'integral' => abs($integral),
- 'recharge_type' => $recharge_type,
- 'type' => AccountLog::TYPE_INTEGRAL,
- 'user_id' => $user->id,
- 'desc' => $desc
- ];
-
- if($recharge_type == AccountLog::LOG_TYPE_EXPEND && $user->integral < $data['integral']){
- $data['integral'] = $user->integral;
- }
-
- if($data['integral'] > 0){
- $form = new AccountLogForm();
- $form->store_id = $store_id;
- $form->admin = $admin;
- $form->attributes = $data;
- $res = $form->recharge();
-
- if($res['code'] != 0){
- throw new \Exception($res['msg']);
- }
- }
- }
-
- /**
- * 处理佣金增减
- * @param User $user 用户对象
- * @param float $commission 变动佣金
- * @param string $desc 变动描述
- * @param int $store_id 店铺ID
- */
- private function processCommissionChange($user, $commission, $desc, $store_id)
- {
- // 使用 UserShareMoney 模型处理佣金变动
- // 参数说明:金额, 用户ID, 订单ID(0表示无订单), 类型(0表示佣金), 来源(10表示后台修改), 店铺ID, 订单类型(0表示商城订单), 描述
- $result = UserShareMoney::set(
- abs($commission),
- $user->id,
- 0,
- 0,
- 10,
- $store_id,
- 0,
- $desc ?: '后台导入佣金' . ($commission > 0 ? '增加' : '减少')
- );
-
- if (!$result) {
- throw new \Exception('佣金' . ($commission > 0 ? '增加' : '减少') . '失败');
- }
- }
-
- /**
- * 创建订单和返利记录
- * @param User $user 用户对象
- * @param Goods $product 产品对象
- * @param ActivityOrderRebateSelf $activity 活动对象
- * @param float $quantity 数量
- * @param int $store_id 店铺ID
- * @param string $type_name 类型名称(用于日志)
- * @return Order 订单对象
- */
- public function createOrder($user, $product, $activity, $quantity, $store_id, $type_name)
- {
- // 创建订单
- $order = new Order();
- $order->user_id = $user->id;
- $order->store_id = $store_id;
- $order->order_no = 'AO' . date('YmdHis') . mt_rand(1000, 9999);
- // $order->total_price = $product->price * $quantity;
- $order->total_price = 1 * $quantity;
- $order->first_price = 0.00;
- $order->second_price = 0.00;
- $order->third_price = 0.00;
- $order->integral = json_encode(['forehead' => 0, 'forehead_integral' => 0]);
- $order->name = $user->nickname;
- $order->mobile = $user->binding;
- $order->is_pay = 1; // 已支付
- $order->is_sale = 1; // 标记为已售后,以便触发返利
- $order->created_at = time();
- $order->updated_at = time();
-
- if (!$order->save()) {
- throw new \Exception('创建订单失败:' . json_encode($order->errors));
- }
-
- // 创建订单详情
- $orderDetail = new OrderDetail();
- $orderDetail->order_id = $order->id;
- $orderDetail->goods_id = $product->id;
- $orderDetail->num = $quantity;
- $orderDetail->attr = json_encode(["规格" => "默认规格"]); // 修改为JSON格式的规格信息
- $orderDetail->pic = $product->cover_pic ?: 'default.jpg'; // 使用产品的封面图片,如果没有则使用默认图片
- // $orderDetail->total_price = $product->price * $quantity;
- $orderDetail->total_price = 1 * $quantity;
- $orderDetail->goods_info = json_encode([
- 'id' => $product->id,
- 'name' => $product->name,
- 'price' => $product->price,
- 'store_id' => $store_id
- ]);
-
- if (!$orderDetail->save()) {
- throw new \Exception('创建订单详情失败:' . json_encode($orderDetail->errors, JSON_UNESCAPED_UNICODE));
- }
-
- // 调用afterOrderDetailSave函数处理返利
- $result = self::afterOrderDetailSave([
- 'orderDetail' => $orderDetail,
- 'goods' => json_encode([
- 'id' => $product->id,
- 'name' => $product->name,
- 'price' => $product->price,
- 'store_id' => $store_id,
- 'user_id' => $user->id,
- ]),
- 'user' => $user,
- 'order' => $order,
- 'activity' => $activity,
- 'goods_id' => $product->id
- ]);
- if (isset($result['code']) && $result['code'] != 0) {
- throw new \Exception('处理返利失败:' . ($result['msg'] ?? '未知错误'));
- }
- }
-
- /**
- * 配置项
- */
- public function conf()
- {
- $conf = Option::get(OptionSetting::ACTIVITY_ORDER_REBATE_SELF, $this->store_id, 'store')['value'];
- if ($conf) {
- $conf = json_decode($conf, true);
- if (isset($conf['conf'])) {
- if (!isset($conf['conf']['type'])) {
- $conf['conf']['type'] = 0;
- }
- }
- } else {
- $conf = ['conf' => [
- 'is_open' => 0,
- 'type' => 0
- ]];
- }
- return [
- 'code' => 0,
- 'msg' => 'ok',
- 'data' => $conf,
- ];
- }
- public static function is_open($store_id = 0)
- {
- $is_open = (new self(['store_id' => $store_id ?: get_store_id()]))->conf()['data']['conf']['is_open'];
- return $is_open;
- }
- public function confSave($conf)
- {
- if (!is_array($conf)) {
- $conf = json_decode($conf, true);
- }
- if (!isset($conf['is_open'])) {
- $conf['is_open'] = 0;
- }
- $data = ['conf' => $conf];
- Option::set(OptionSetting::ACTIVITY_ORDER_REBATE_SELF, json_encode($data), $this->store_id, 'store');
- return [
- 'code' => 0,
- 'msg' => '保存成功'
- ];
- }
- /**
- * 配置项结束
- */
- /**
- * 活动逻辑
- */
- //订单活动数据写入
- public static function afterOrderDetailSave($od)
- {
- try {
- $goods = json_decode($od->goods_info, true);
- debug_log(['goods_store_id_01' => $goods->store_id, 'goods_store_id_02' => $goods['store_id']], 'ActivityOrderRebateSelfForm.log');
- if (!self::is_open($goods['store_id'])) {
- return [
- 'code' => 0,
- 'msg' => '功能未开启!'
- ];
- }
- $order = $od->order;
- if (!$order->user_id) {
- return;
- }
- $activity = ActivityOrderRebateSelf::activityAt($order->store_id, $od->goods_id);
- if (!$activity) {
- return;
- }
- $add_rat = 0;
- $add_rebate = 0;
- $aUser = ActivityOrderRebateSelfUser::findOne(['user_id' => $order->user_id]);
- if ($aUser && $aUser->level) {
- $aUserLevel = ActivityOrderRebateSelfLevel::findOne(['store_id' => $order->store_id, 'level' => $aUser->level, 'is_delete' => 0, 'status' => 1]);
- if ($aUserLevel) {
- $add_rat = $aUserLevel['add_rat']; //释放加速比例
- $add_rebate = $aUserLevel['add_rebate']; //返利赠送比例
- }
- }
- $AF = $activity->send_num;
- $LF = $add_rebate;
- $P = $od->total_price;
- $type = 0;
- $conf = Option::get(OptionSetting::ACTIVITY_ORDER_REBATE_SELF, $goods['store_id'], 'store')['value'];
- if ($conf) {
- $conf = json_decode($conf, true);
- $type = $conf['conf']['type'];
- }
- if (intval($type)) {
- $P = 0;
- // $goods_info = json_decode($order_detail['goods_info'], true);
- $goods_attr = json_decode($goods['attr'], true);
- $order_goods_attr = json_decode($od->attr, true);
- $order_goods_attr_id = array_column($order_goods_attr, 'attr_id');
- sort($order_goods_attr_id);
- $goods_price = 0;
- foreach ($goods_attr as $item) {
- $goods_attr_list = $item['attr_list'];
- $goods_attr_id = array_column($goods_attr_list, 'attr_id');
- sort($goods_attr_id);
- if (!array_diff($order_goods_attr_id, $goods_attr_id)) {
- $goods_price = $item['price'];
- }
- }
- if ($goods_price > 0) {
- $P = $goods_price * $od->num;
- }
- }
- $price_total = floor_num($P * $AF / 100 * (100 + $LF) / 100);
- if ($price_total <= 0) {
- return;
- }
- $ao = new ActivityOrderRebateSelfOrder();
- $ao->store_id = $order->store_id;
- $ao->user_id = $order->user_id;
- $ao->act_id = $activity->id;
- $ao->order_id = $order->id;
- $ao->od_id = $od->id;
- $ao->goods_id = $od->goods_id;
- $ao->send_type = $activity->send_type;
- $ao->send_time = $activity->send_time;
- $ao->send_days = $activity->send_days;
- $ao->release_rate = $activity->release_rate;
- $ao->send_num = $activity->send_num;
- $ao->price_total = $price_total;
- $ao->price_send = 0;
- $ao->price_wait = $price_total;
- $ao->add_rat = $add_rat;
- $ao->add_rebate = $add_rebate;
- $ao->fixed_rebate_profit = $activity->fixed_rebate_profit;
- $ao->send_rebate_type = $activity->send_rebate_type;
- if (!$ao->save()) {
- throw new \Exception(array_shift($ao->getFirstErrors()));
- }
- if ($order->is_sale) {
- self::afterOrderSales($order);
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- //处理订单售后(升级、返利)
- public static function afterOrderSales($order)
- {
- try {
- if (!self::is_open($order->store_id)) {
- return [
- 'code' => 0,
- 'msg' => '功能未开启!'
- ];
- }
- $levelUp = self::levelUp($order->user_id);
- if ($levelUp['code'] != 0) {
- debug_log([__METHOD__, $order->user_id, $levelUp['msg']], __CLASS__ . '.log');
- return;
- }
- $time1 = strtotime('today midnight'); // 今天凌晨时间戳
- $aos = ActivityOrderRebateSelfOrder::findAll(['order_id' => $order->id, 'is_sale' => 0, 'is_delete' => 0]);
- foreach ($aos as $ao) {
- $ao->is_sale = 1;
- if (!$ao->save()) {
- throw new \Exception(array_shift($ao->getFirstErrors()));
- }
- //
- $od = \app\models\OrderDetail::findOne($ao->od_id);
- $activity = ActivityOrderRebateSelf::findOne($ao->act_id);
- // 获取返利类型和比例
- $send_types = $activity->send_types ? json_decode($activity->send_types, true) : [$activity->send_type];
- $send_type_percentages = $activity->send_type_percentages ? json_decode($activity->send_type_percentages, true) : [$activity->send_type => 100];
- $AC = $ao->send_days; //返利周期
- $send_rebate_type = intval($ao->send_rebate_type); //全返类型:0=时间,1=固定比例
- $fixed_rebate_profit = $ao->fixed_rebate_profit; //固定比例
- $LA = $ao->add_rat; //释放加速比例
- $price_total = $ao->price_total; //总金额
- // $release_rate = isset($ao->release_rate) ? floatval($ao->release_rate) : 0; // 获取释放速率
- $price_sends = [];
- //if ($release_rate > 0) {
- // // 按释放速率计算
- // $remaining = $price_total;
- // $day = 1;
- // $AC = 90; //最多90天
- //
- // while ($remaining > 0.01 && $day <= $AC) {
- // // 按释放速率计算当天释放金额
- // $price_day = floor_num($remaining * $release_rate / 100);
- //
- // // 确保最小释放金额为0.01
- // if ($price_day < 0.01) {
- // $price_day = 0.01;
- // }
- //
- // // 最后一天释放所有剩余金额
- // if ($day == $AC) {
- // $price_day = $remaining;
- // }
- //
- // $price_sends[] = $price_day;
- // $remaining -= $price_day;
- // $day++;
- // }
- //} else {
- if ($send_rebate_type) {
- //固定比例类型
- if ($fixed_rebate_profit > 0) {
- $p1 = $price_total;
- $day = 1;
- $AC = 90; //最多90天
- while ($p1 >= 0.01 && $day <= $AC) {
- // $p1 = $price_total - array_sum($price_sends); //计算剩余还需要分多钱
- //等同于 $price_once = ($p1 * $fixed_rebate_profit) / 100 ;
- $price_once = bcdiv(bcmul($p1, $fixed_rebate_profit, 2), 100, 2); //计算按照原进度的分红比例每次需要分多钱
- //等同于$price_once += ($price_once * $LA) / 100;
- $price_once = bcadd($price_once, bcdiv(bcmul($price_once, $LA, 2), 100, 2), 2); //将每次的进度的钱再加速获取
- // $price_sends[] = $price_once >= 0.01 ? $price_once : $p1; //获取结果
- if ($p1 < 0.01) {
- $p1 = 0.01;
- }
- if ($day == $AC) {
- $price_once = $p1;
- }
- $price_sends[] = $p1; //获取结果
- $p1 -= $price_once; //计算剩余还需要分多钱
- $day++;
- };
- }
- } else {
- //固定时间类型
- $price_day_rate = (100 / $AC + $LA) / 100;
- $price_day = floor_num($price_total * $price_day_rate);
- if ($price_day < 0.01) {
- $price_day = 0;
- }
- $price_sends = [];
- for ($i = 1; $i <= $AC; $i++) {
- $p1 = $price_total - array_sum($price_sends);
- if ($p1 < 0.01) {
- break;
- }
- $price_sends[] = $i == $AC ? $p1 : $price_day;
- }
- }
- // }
- foreach ($price_sends as $i => $price_send) {
- if ($price_send <= 0.00) {
- continue;
- }
- // 按照返利类型比例分配返利金额
- foreach($send_types as $type) {
- $percentage = isset($send_type_percentages[$type]) ? $send_type_percentages[$type] : 0;
- if ($percentage <= 0) continue;
- // 计算当前类型的返利金额
- $type_price_send = floor_num($price_send * $percentage / 100);
- if ($type_price_send <= 0) continue;
- $al = new ActivityOrderRebateSelfLog();
- $al->self_id = $ao->id;
- $al->store_id = $order->store_id;
- $al->user_id = $order->user_id;
- $al->act_id = $ao->act_id;
- $al->order_id = $order->id;
- $al->od_id = $od->id;
- $al->goods_id = $ao->goods_id;
- //$al->send_type = $ao->send_type;
- //$al->price_send = $price_send;
- $al->send_type = $type; // 使用当前循环的返利类型
- $al->price_send = $type_price_send; // 按比例分配的返利金额
- $al->day = $i + 1;
- $al->is_sale = 1;
- if ($ao->send_time == 1) {
- $al->pre_send_time = $time1 + $al['day'] * 86400 * 365;
- } else if ($ao->send_time == 2) {
- $al->pre_send_time = $time1 + $al['day'] * 86400 * 30;
- } else if ($ao->send_time == 4) {
- $al->pre_send_time = time() + $al['day'] * 60;
- } else {
- $al->pre_send_time = $time1 + $al['day'] * 86400;
- }
- if (!$al->save()) {
- throw new \Exception(array_shift($al->getFirstErrors()));
- }
- }
- }
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- //返利
- public static function rebate($time = 0, $queue = 0)
- {
- try {
- if (!$time) {
- $time = time();
- }
- if ($queue) {
- $queue = queue_push(new \app\jobs\orderEvent\ActivityOrderRebateSelfRebateJob([
- 'time' => $time,
- ]), 0, 1);
- return [
- 'code' => 0,
- 'msg' => '操作成功!' . $queue
- ];
- }
- $count = 100;
- $als = ActivityOrderRebateSelfLog::find()->where(['is_sale' => 1, 'is_send' => 0])->andWhere(['<=', 'pre_send_time', $time])->limit($count)->all();
- foreach ($als as $al) {
- $al->is_send = 1;
- $al->send_time = time();
- if (!$al->save()) {
- throw new \Exception(array_shift($al->getFirstErrors()));
- }
- $ao = ActivityOrderRebateSelfOrder::findOne(['is_sale' => 1, 'order_id' => $al->order_id, 'goods_id' => $al->goods_id, 'is_delete' => 0, 'id' => $al->self_id]);
- $ao->price_send += $al->price_send;
- $ao->price_wait -= $al->price_send;
- if (!$ao->save()) {
- throw new \Exception(array_shift($ao->getFirstErrors()));
- }
- $order = Order::findOne($al->order_id);
- $user = User::findOne(['id' => $al->user_id]);
- if ($al->send_type == 2) {
- $save = AccountLog::saveLog(
- $al->user_id,
- $al->price_send,
- AccountLog::TYPE_INTEGRAL,
- AccountLog::LOG_TYPE_INCOME,
- AccountLog::TYPE_PLATFORM_ORDER,
- $order->id,
- "活动返利赠送积分, 订单号:{$order->order_no}"
- );
- } else if ($al->send_type == 3) {
- $save = AccountLog::saveLog(
- $al->user_id,
- $al->price_send,
- AccountLog::TYPE_BALANCE,
- AccountLog::LOG_TYPE_INCOME,
- AccountLog::TYPE_PLATFORM_ORDER,
- $order->id,
- "活动返利赠送余额, 订单号:{$order->order_no}"
- );
- } else if ($al->send_type == 4) {
- $pool = IntegralAppreciationPool::findOne(['store_id' => $al->store_id]);
- if ($pool->integral_price > 0) {
- $save = AccountLog::saveLog(
- $al->user_id,
- floor_num($al->price_send/$pool->integral_price),
- AccountLog::TYPE_INTEGRAL,
- AccountLog::LOG_TYPE_INCOME,
- AccountLog::TYPE_PLATFORM_ORDER,
- $order->id,
- "活动返利赠送增值积分, 订单号:{$order->order_no}"
- );
- }
- } else {
- $user->total_price += doubleval($al->price_send);
- $user->price += doubleval($al->price_send);
- $user->save();
- $order->share_price += doubleval($al->price_send);
- UserShareMoney::set($al->price_send, $al->user_id, $order->id, 0, 4, $order->store_id, 0);
- }
- }
- if ($count == count($als)) {
- $queue = queue_push(new \app\jobs\orderEvent\ActivityOrderRebateSelfRebateJob([
- 'time' => $time,
- ]), 0, 1);
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- //升级(自己和上级)
- public static function levelUp($user_id)
- {
- try {
- $user = User::findOne($user_id);
- $store_id = $user->store_id;
- $aUser = ActivityOrderRebateSelfUser::findOne(['user_id' => $user_id]);
- $aUserLevel = 0;
- if ($aUser) {
- $aUserLevel = $aUser->level;
- } else {
- $aUser = new ActivityOrderRebateSelfUser();
- $aUser->store_id = $store_id;
- $aUser->user_id = $user_id;
- $aUser->level = 0;
- }
- $aLevels = ActivityOrderRebateSelfLevel::find()->where(['store_id' => $store_id, 'is_delete' => 0, 'status' => 1])->orderBy('level DESC')->all();
- if (!in_array($aUserLevel, array_column($aLevels, 'level'))) {
- $aUserLevel = 0;
- }
- $order_money = Order::find()->where([
- 'store_id' => $store_id,
- 'is_delete' => 0,
- 'trade_status' => Order::ORDER_FLOW_CONFIRM,
- 'user_id' => $user_id
- ])->andWhere(['or', ['is_pay' => 1], ['pay_type' => 2]])->sum('pay_price');
- $childsLevel = ActivityOrderRebateSelfUser::find()->alias('au')->leftJoin(['u' => User::tableName()], 'au.user_id = u.id')->where([
- 'u.old_parent_id' => $user_id,
- ])->groupBy('au.level')->select('au.level, count(1) acount')->asArray()->all();
- foreach ($aLevels as $aLevel) {
- $moneyOk = $order_money > $aLevel['money'];
- $childOk = 0;
- if (!$aLevel['child_level'] || !$aLevel['child_num']) {
- $childOk = 1;
- } else {
- foreach ($childsLevel as $item) {
- $child_levelOk = $item['level'] >= $aLevel['child_level'];
- $child_numOk = $item['acount'] >= $aLevel['child_num'];
- if ($child_levelOk && $child_numOk) {
- $childOk = 1;
- break;
- }
- }
- }
- if ($moneyOk && $childOk) {
- $aUserLevel = $aLevel['level'];
- break;
- }
- }
- if ($aUser->level != $aUserLevel) {
- $aUser->level = $aUserLevel;
- if (!$aUser->save()) {
- throw new \Exception(array_shift($aUser->getFirstErrors()));
- }
- self::levelUp($user->old_parent_id);
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- \Yii::error($e);
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 活动逻辑结束
- */
- /**
- * 活动信息
- */
- public function search()
- {
- try {
- $query = ActivityOrderRebateSelf::find()->where(['is_delete' => 0, 'store_id' => get_store_id()]);
- if ((int)$this->status === 1) { //未开始
- $query->andWhere(['>', 'start_time', time()]);
- }
- if ((int)$this->status === 2) { //进行中
- $query->andWhere(['AND', ['<', 'start_time', time()], ['>', 'end_time', time()]]);
- }
- if ((int)$this->status === 3) { //已结束
- $query->andWhere(['<', 'end_time', time()]);
- }
- if (isset($this->send_type) && $this->send_type > 0) {
- $query->andWhere(['send_type' => $this->send_type]);
- }
- if (!empty($this->name)) { //名称
- $query->andWhere(['LIKE', 'name', $this->name]);
- }
- if (!empty($this->start_time)) {
- $query->andWhere(['>', 'end_time', strtotime($this->start_time)]);
- }
- if (!empty($this->end_time)) {
- $query->andWhere(['<', 'start_time', strtotime($this->end_time)]);
- }
- $query->orderBy('id DESC');
- $pagination = pagination_make($query);
- foreach ($pagination['list'] as &$item) {
- $item['publish'] = $item['status'];
- //获取活动状态
- if ($item['start_time'] > time()) {
- $item['status'] = 1;
- }
- if ($item['start_time'] < time() && $item['end_time'] > time()) {
- $item['status'] = 2;
- }
- if ($item['end_time'] < time()) {
- $item['status'] = 3;
- }
- //格式化时间
- $item['start_time'] = date("Y-m-d H:i:s", $item['start_time']);
- $item['end_time'] = date("Y-m-d H:i:s", $item['end_time']);
- $item['created_at'] = date("Y-m-d H:i:s", $item['created_at']);
- $item['updated_at'] = date("Y-m-d H:i:s", $item['updated_at']);
- $userCount = ActivityOrderRebateSelfOrder::find()->where(['act_id' => $item['id']])->groupBy(['user_id'])->count();
- $item['userCount'] = $userCount;
- $orderCount = ActivityOrderRebateSelfOrder::find()->where(['act_id' => $item['id']])->count();
- $item['orderCount'] = $orderCount;
- $orderSum = ActivityOrderRebateSelfOrder::find()->where(['act_id' => $item['id']])->sum('price_total');
- $item['orderSum'] = $orderSum;
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => [
- 'data' => $pagination['list'],
- 'pageNo' => $pagination['pageNo'],
- 'totalCount' => $pagination['totalCount'],
- 'q' => $query->createCommand()->getRawSql(),
- ]
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- public function listSelect()
- {
- $query = ActivityOrderRebateSelf::find()->where(['is_delete' => 0]);
- $this->store_id && $query->andWhere(['store_id' => $this->store_id]);
- // 根据活动类型筛选活动
- // $activity_type = get_params('activity_type');
- if ($this->send_type) {
- switch ($this->send_type) {
- case 'integral':
- // 筛选积分类型的活动(send_type=2 或 send_types 包含 2)
- $query->andWhere(['or',
- ['send_type' => 2],
- ['like', 'send_types', '"2222"']
- ]);
- break;
- case 'balance':
- // 筛选余额类型的活动(send_type=3 或 send_types 包含 3)
- $query->andWhere(['or',
- ['send_type' => 3],
- ['like', 'send_types', '"3333"']
- ]);
- break;
- case 'commission':
- // 筛选佣金类型的活动(send_type=1 或 send_types 包含 1)
- $query->andWhere(['or',
- ['send_type' => 1],
- ['like', 'send_types', '"1111"']
- ]);
- break;
- }
- }
- if($this->name){
- $query->andWhere(['like', 'name', $this->name]);
- }
- if (!empty($this->start_time)) {
- $query->andWhere(['>', 'end_time', strtotime($this->start_time)]);
- }
- if (!empty($this->end_time)) {
- $query->andWhere(['<', 'start_time', strtotime($this->end_time)]);
- }
- $query->select('id, name');
- $query->orderBy('id desc');
- $res = $query->asArray()->all();
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $res,
- ];
- }
- public static function sortGoods($goods_ids, $goods)
- {
- $res = [];
- foreach ($goods_ids as $id) {
- foreach ($goods as $gitem) {
- if ($gitem['id'] == $id) {
- $res[] = $gitem;
- }
- }
- }
- return $res;
- }
- public function getInfo()
- {
- try {
- $activity = ActivityOrderRebateSelf::find()->where(['id' => $this->id])->asArray()->one();
- if ($activity) {
- $gids = ActivityOrderRebateSelfGoods::find()->select('goods_id')->where(['act_id' => $activity['id']]);
- $activity_goods = Goods::find()->where(['id' => $gids])->andWhere(['is_delete' => 0])->asArray()->all();
- $activity['start_time'] = date("Y-m-d H:i:s", $activity['start_time']);
- $activity['end_time'] = date("Y-m-d H:i:s", $activity['end_time']);
- $activity_goods = self::sortGoods(explode(',', $activity['goods_ids']), $activity_goods);
- $activity['send_rebate_type'] = intval($activity['send_rebate_type']);
- //$activity['send_type'] = intval($activity['send_type']);
- $activity['send_types'] = json_decode($activity['send_types'], true);
- $activity['send_type_percentages'] = json_decode($activity['send_type_percentages'], true);
- }
- return [
- 'code' => 0,
- 'msg' => '获取成功',
- 'data' => [
- 'activity_goods' => $activity_goods ?? [],
- 'activity' => $activity ?: [],
- ]
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage() . $e->getFile() . $e->getLine()
- ];
- }
- }
- public function save()
- {
- $t = \Yii::$app->db->beginTransaction();
- try {
- if (!$this->name || !$this->start_time || !$this->end_time) {
- throw new \Exception("请将参数填充完整");
- }
- $activity = ActivityOrderRebateSelf::findOne($this->id);
- if (empty($activity)) {
- $activity = new ActivityOrderRebateSelf();
- $activity->store_id = $this->store_id;
- if (isset($this->send_rebate_type) && !in_array($this->send_rebate_type, ActivityOrderRebateSelf::SEND_REBATE_TYPE_ARR)) {
- throw new \Exception("请选择返利方式");
- }
- $activity->send_rebate_type = $this->send_rebate_type ?: 0;
- }
- $activity->name = $this->name;
- $activity->start_time = strtotime($this->start_time);
- $activity->end_time = strtotime($this->end_time);
- $activity->goods_ids = $this->goods_ids ?: '';
- $activity->send_type = $this->send_type ?: 0;
- $activity->send_time = $this->send_time;
- $activity->send_num = $this->send_num ?: 0;
- $activity->send_days = $this->send_days ?: 1;
- $activity->fixed_rebate_profit = $this->fixed_rebate_profit ?: 0;
- $activity->send_types = $this->send_types ? $this->send_types : null;
- $activity->send_type_percentages = $this->send_type_percentages ? $this->send_type_percentages : null;
- $activity->release_rate = $this->release_rate;
- if (!$activity->save()) {
- throw new \Exception(implode(';', array_values($activity->firstErrors)));
- }
- $gids = explode(',', $activity->goods_ids);
- if (!empty($gids)) {
- $result = ActivityOrderRebateSelfGoods::saveList($gids, $activity->id);
- if ($result['code'] !== 0) {
- throw new \Exception($result['msg']);
- }
- }
- $t->commit();
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- public function status()
- {
- try {
- if ($this->ids) {
- $ids = explode(',', $this->ids);
- foreach ($ids as $id) {
- $model = ActivityOrderRebateSelf::findOne(['id' => $id, 'store_id' => $this->store_id]);
- $model->status = (int)$this->status;
- if (!$model->save()) {
- throw new \Exception(array_shift($model->getFirstErrors()));
- }
- }
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- public function del()
- {
- try {
- if ($this->ids) {
- $ids = explode(',', $this->ids);
- ActivityOrderRebateSelf::updateAll(['is_delete' => 1], ['and', ['in', 'id', $ids], ['store_id' => $this->store_id]]);
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 活动信息结束
- */
- /**
- * 等级信息
- */
- public function levelSearch()
- {
- if (!$this->validate()) {
- return [
- 'code' => 1,
- 'msg' => '参数错误'
- ];
- }
- $query = ActivityOrderRebateSelfLevel::find()->where(['store_id' => $this->store_id, 'is_delete' => 0]);
- if (isset($this->status) && $this->status >= 0) {
- $query->andWhere(['status' => $this->status]);
- }
- if ($this->name) {
- $query->andWhere(['like', 'name', $this->name]);
- }
- if (!empty($this->start_time)) {
- $query->andWhere(['>', 'created_at', strtotime($this->start_time)]);
- }
- if (!empty($this->end_time)) {
- $query->andWhere(['<', 'created_at', strtotime($this->end_time)]);
- }
- $query->orderBy(['level' => SORT_ASC]);
- $pagination = pagination_make($query);
- $aul = ActivityOrderRebateSelfUser::find()->where(['store_id' => $this->store_id])->select('level, count(1) count')->groupBy('level')->asArray()->all();
- foreach ($pagination['list'] as &$value) {
- $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
- $value['user_count'] = 0;
- foreach ($aul as $l) {
- if ($l['level'] == $value['level']) {
- $value['user_count'] = $l['count'];
- }
- }
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $pagination,
- 'q' => $query->createCommand()->getRawSql(),
- ];
- }
- public function levelListSelect()
- {
- $list = ActivityOrderRebateSelfLevel::find()->where(['store_id' => $this->store_id, 'status' => 1, 'is_delete' => 0])
- ->select('id, level, name')
- ->orderBy('level')
- ->asArray()->all();
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $list,
- ];
- }
- public function levelSave()
- {
- $level = ActivityOrderRebateSelfLevel::findOne($this->id);
- if (empty($level)) {
- $level = new ActivityOrderRebateSelfLevel();
- $level->store_id = $this->store_id;
- }
- $level->store_id = $this->store_id;
- $level->level = $this->level;
- $level->name = $this->name;
- $level->money = $this->money;
- $level->child_num = (int)$this->child_num;
- $level->child_level = (int)$this->child_level;
- $level->add_rat = $this->add_rat;
- $level->add_rebate = $this->add_rebate;
- if (!$level->save()) {
- return [
- 'code' => 1,
- 'msg' => '操作失败,' . array_shift($level->getFirstErrors())
- ];
- }
- return [
- 'code' => 0,
- 'msg' => '成功'
- ];
- }
- public function levelStatus()
- {
- try {
- if ($this->ids) {
- $ids = explode(',', $this->ids);
- foreach ($ids as $id) {
- $model = ActivityOrderRebateSelfLevel::findOne(['id' => $id, 'store_id' => $this->store_id]);
- $model->status = (int)$this->status;
- if (!$model->save()) {
- throw new \Exception(array_shift($model->getFirstErrors()));
- }
- }
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- public function levelDel()
- {
- try {
- if ($this->ids) {
- $ids = explode(',', $this->ids);
- foreach ($ids as $id) {
- $model = ActivityOrderRebateSelfLevel::findOne(['id' => $id, 'store_id' => $this->store_id]);
- $model->is_delete = 1;
- if (!$model->save()) {
- throw new \Exception(array_shift($model->getFirstErrors()));
- }
- }
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功!'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- /**
- * 等级信息结束
- */
- /**
- * 用户信息
- */
- public function userSearch()
- {
- if (!$this->validate()) {
- return [
- 'code' => 1,
- 'msg' => '参数错误'
- ];
- }
- $store_id = $this->store_id;
- $query = ActivityOrderRebateSelfUser::find()->alias('au')
- ->leftJoin(['al' => ActivityOrderRebateSelfLevel::tableName()], 'au.level = al.level')
- ->leftJoin(['u' => User::tableName()], 'u.id = au.user_id')
- ->leftJoin(['su' => SaasUser::tableName()], 'u.binding = su.mobile AND su.mobile != ""')
- ->where(['au.store_id' => $store_id]);
- if (isset($this->level) && $this->level > 0) {
- $query->andWhere(['au.level' => $this->level]);
- }
- if ($this->name) {
- $query->andWhere(['like', 'su.name', $this->name]);
- }
- if ($this->phone) {
- $query->andWhere(['like', 'su.mobile', $this->phone]);
- }
- $query->orderBy('au.id desc');
- $query->select('au.*, al.name level_name, su.mobile, su.name, su.avatar');
- $pagination = pagination_make($query);
- foreach ($pagination['list'] as &$value) {
- $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
- $order_money = Order::find()->where([
- 'store_id' => $store_id,
- 'is_delete' => 0,
- 'trade_status' => Order::ORDER_FLOW_CONFIRM,
- 'user_id' => $value['user_id'],
- ])->andWhere(['or', ['is_pay' => 1], ['pay_type' => 2]])->sum('pay_price');
- $value['user_order_money'] = $order_money;
- $childsLevel = User::find()->alias('u')->leftJoin(['au' => ActivityOrderRebateSelfUser::tableName()], 'au.user_id = u.id')->where([
- 'u.old_parent_id' => $value['user_id'],
- ])->groupBy('au.level')->select(['IF(au.level>0,au.level,0) level', 'count(1) count'])->asArray()->all();
- $value['childsLevel'] = $childsLevel;
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $pagination,
- 'q' => $query->createCommand()->getRawSql(),
- ];
- }
- /**
- * 用户信息结束
- */
- /**
- * 订单信息
- */
- public function orderList($getTotal = 1)
- {
- $query = ActivityOrderRebateSelfOrder::find()->alias('ao')
- ->leftJoin(['a' => ActivityOrderRebateSelf::tableName()], 'ao.act_id = a.id')
- ->leftJoin(['o' => Order::tableName()], 'ao.order_id = o.id')
- ->leftJoin(['u' => User::tableName()], 'ao.user_id = u.id')
- ->leftJoin(['su' => SaasUser::tableName()], 'su.mobile = u.binding');
- // 新增的删除状态
- $query->andWhere(['ao.is_delete' => ActivityOrderRebateSelfOrder::NOT_DELETE]);
- $query->andWhere(['!=', 'o.trade_status', Order::ORDER_FLOW_CANCEL]);
- $query->andWhere(['ao.store_id' => $this->store_id]);
- if ($this->user_id) {
- $query->andWhere(['ao.user_id' => $this->user_id]);
- $level = ActivityOrderRebateSelfUser::find()->alias('u')
- ->leftJoin(['l' => ActivityOrderRebateSelfLevel::tableName()], 'u.level = l.level AND u.store_id = l.store_id AND l.is_delete = 0 AND l.status = 1')
- ->where(['u.user_id' => $this->user_id])
- ->select('l.*')->limit(1)->asArray()->one();
- }
- if ($this->act_id) {
- $query->andWhere(['ao.act_id' => $this->act_id]);
- }
- if ($this->send_type > 0) {
- $query->andWhere(['ao.send_type' => $this->send_type]);
- }
- if (!empty($this->name)) {
- $query->andWhere(['LIKE', 'su.name', $this->name]);
- }
- if (!empty($this->order_no)) {
- $query->andWhere(['LIKE', 'o.order_no', $this->order_no]);
- }
- if (!empty($this->start_time)) {
- $query->andWhere(['>', 'o.created_at', strtotime($this->start_time)]);
- }
- if (!empty($this->end_time)) {
- $query->andWhere(['<', 'o.created_at', strtotime($this->end_time)]);
- }
- $total = null;
- if ($getTotal) {
- $select = ['IFNULL(SUM(ao.price_total),0) price_total', 'IFNULL(SUM(ao.price_wait),0) price_wait', 'IFNULL(SUM(ao.price_send),0) price_send', 'count(DISTINCT order_id) num'];
- $queryPrice = clone $query;
- $total['price'] = $queryPrice->andWhere(['ao.send_type' => 1])->select($select)->asArray()->one();
- $queryJifen = clone $query;
- $total['jifen'] = $queryJifen->andWhere(['ao.send_type' => 2])->select($select)->asArray()->one();
- $queryBalance = clone $query;
- $total['balance'] = $queryBalance->andWhere(['ao.send_type' => 3])->select($select)->asArray()->one();
- }
- $query->select('ao.*, su.avatar, su.name, su.mobile, o.trade_status, o.order_type, o.is_pay, o.total_price, o.pay_price, o.order_no, o.created_at order_created_at')->orderBy('ao.id desc');
- $res = pagination_make($query);
- foreach ($res['list'] as &$value) {
- $value['order_created_at'] = $value['order_created_at'] ? date('Y-m-d H:i:s', $value['order_created_at']) : '-';
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $res,
- 'total' => $total,
- 'level' => $level,
- 'q' => $query->createCommand()->getRawSql(),
- ];
- }
- /**
- * 删除返利订单
- */
- public function orderDelete() {
- if(count($this->ids) <= 0){
- return ['code' => 1, 'msg' => '请选择要删除的数据'];
- }
- $count = ActivityOrderRebateSelfOrder::updateAll(['is_delete' => ActivityOrderRebateSelfOrder::IS_DELETE], ['id' => $this->ids]);
- $ol = ActivityOrderRebateSelfOrder::findAll(['id' => $this->ids]);
- foreach($ol as $item){
- if(!$item->is_delete){
- continue;
- }
- ActivityOrderRebateSelfLog::deleteAll(['order_id' => $item['order_id'], 'act_id' => $item['act_id']]);
- }
- if($count == count($this->ids)){
- return ['code' => 0, 'msg' => '删除成功'];
- }else{
- return ['code' => 0, 'msg' => '部分删除成功'];
- }
- }
-
- /**
- * 订单信息结束
- */
- /**
- * 返利信息
- */
- public function logList($getTotal = 1)
- {
- $query = ActivityOrderRebateSelfLog::find()->alias('al')
- ->leftJoin(['a' => ActivityOrderRebateSelf::tableName()], 'al.act_id = a.id')
- ->leftJoin(['o' => Order::tableName()], 'al.order_id = o.id')
- ->leftJoin(['u' => User::tableName()], 'al.user_id = u.id')
- ->leftJoin(['su' => SaasUser::tableName()], 'su.mobile = u.binding');
- $query->andWhere(['!=', 'o.trade_status', Order::ORDER_FLOW_CANCEL]);
- $query->andWhere(['al.store_id' => $this->store_id]);
- if ($this->user_id) {
- $query->andWhere(['al.user_id' => $this->user_id]);
- }
- if ($this->act_id) {
- $query->andWhere(['al.act_id' => $this->act_id]);
- }
- if ($this->send_type > 0) {
- $query->andWhere(['al.send_type' => $this->send_type]);
- }
- if (isset($this->is_send) && $this->is_send >= 0) {
- $query->andWhere(['al.is_send' => $this->is_send]);
- }
- if (!empty($this->name)) {
- $query->andWhere(['LIKE', 'su.name', $this->name]);
- }
- if (!empty($this->order_no)) {
- $query->andWhere(['LIKE', 'o.order_no', $this->order_no]);
- }
- if (!empty($this->start_time)) {
- $query->andWhere(['>', 'o.created_at', strtotime($this->start_time)]);
- }
- if (!empty($this->end_time)) {
- $query->andWhere(['<', 'o.created_at', strtotime($this->end_time)]);
- }
- $total = null;
- if ($getTotal) {
- $queryCountUser = clone $query;
- $totalCountUser = intval($queryCountUser->groupBy(['al.user_id'])->count());
- $select = ['IFNULL(SUM(al.price_send),0) price_send', 'count(1) num'];
- $queryPrice = clone $query;
- $total['price'] = $queryPrice->andWhere(['al.send_type' => 1])->select($select)->asArray()->one();
- $queryJifen = clone $query;
- $total['jifen'] = $queryJifen->andWhere(['al.send_type' => 2])->select($select)->asArray()->one();
- $queryBalance = clone $query;
- $total['balance'] = $queryBalance->andWhere(['al.send_type' => 3])->select($select)->asArray()->one();
- }
- $query->select('al.*, su.avatar, su.name, su.mobile, o.trade_status, o.order_type, o.is_pay, o.total_price, o.pay_price, o.order_no, o.created_at order_created_at')
- ->orderBy('al.pre_send_time DESC, al.id asc');
- $res = pagination_make($query);
- foreach ($res['list'] as &$value) {
- $value['order_created_at'] = $value['order_created_at'] ? date('Y-m-d H:i:s', $value['order_created_at']) : '-';
- $value['pre_send_time'] = $value['pre_send_time'] ? date('Y-m-d H:i:s', $value['pre_send_time']) : '-';
- $value['send_time'] = $value['send_time'] ? date('Y-m-d H:i:s', $value['send_time']) : '-';
- }
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => $res,
- 'total' => $total,
- 'totalCountUser' => $totalCountUser ?? 0,
- 'q' => $query->createCommand()->getRawSql(),
- ];
- }
- /**
- * 返利信息结束
- */
- }
|