| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513 |
- <?php
- /**
- * 造测试数据.
- *
- * @author nj
- * @date 2021-08-14 10:20
- */
- use Illuminate\Database\Seeder;
- use Faker\Generator as Faker;
- use Carbon\Carbon;
- use App\Models\Mysql\AppModel;
- use Zhuzhichao\IpLocationZh\Ip;
- use Modules\InnerApi\Services\UserService;
- use Modules\InnerApi\Services\PayService;
- use Illuminate\Support\Facades\File;
- use App\Repositories\AgentRepository;
- use App\Repositories\ConfigRepoistory;
- use App\Repositories\Criterias\OrderLimitCriteria;
- use App\Repositories\ChannelRepository;
- /**
- * 命令:php -d memory_limit=100M artisan db:seed --class=GenerateTestSeeder
- * Class GenerateTestSeeder
- */
- class GenerateTestSeeder extends Seeder
- {
- /**
- * @var null|Faker
- */
- protected $faker = null;
- /**
- * 临时内存缓存
- * @var array
- */
- protected $cache = [];
- /**
- * 总代UID,代理系统中的第一个超管UID
- * @var string
- */
- protected $superUid = 'dQELY6';
- /**
- * 用户服务.
- * @var null|UserService
- */
- protected $userService = null;
- /**
- * 支付服务
- * @var null|PayService
- */
- protected $payService = null;
- /**
- * 测试配置.
- * @var array
- */
- protected $testConfig = [];
- /**
- * @var null |AgentRepository
- */
- protected $agentRepo = null;
- /**
- * @var null|ConfigRepoistory
- */
- protected $configRepo = null;
- /**
- * @var null|ChannelRepository
- */
- protected $channelRepo = null;
- public function run()
- {
- if (app()->environment() == 'production') {
- $this->comment('err, 禁止用于生产环境');
- return false;
- }
- // 创建全局规则.
- self::createGlobalRule();
- // 不限制超时.
- // set_time_limit(0);
- // 初始化缓存.
- self::initCache();
- // 缓存里初始化母包.
- self::appMom();
- // 创建代理.
- self::agent();
- // 新用户进来.
- $amountUsers = isset($this->testConfig['generate_test']['amount_users']) ? intval($this->testConfig['generate_test']['amount_users']) : 10;
- $startId = isset($this->testConfig['generate_test']['start_id']) ? intval($this->testConfig['generate_test']['start_id']) : 1000;
- $appVersion = isset($this->testConfig['generate_test']['app_version']) ? strval($this->testConfig['generate_test']['app_version']) : '1.0.1';
- $startDate = isset($this->testConfig['generate_test']['start_date']) ? strval($this->testConfig['generate_test']['start_date']) : '2021-08-13';
- $endDate = isset($this->testConfig['generate_test']['end_date']) ? strval($this->testConfig['generate_test']['end_date']) : '2021-08-16';
- $startDateObj = Carbon::parse($startDate);
- $endDateObj = Carbon::parse($endDate)->endOfDay();
- while ($startDateObj < $endDateObj) {
- $date = (clone $startDateObj)->toDateString();
- // 生产用户.
- self::incNewUsers($date, $amountUsers, $startId, $appVersion);
- // 生产支付.
- self::incPay($date, $amountUsers, $startId, $appVersion);
- $startDateObj = $startDateObj->addDays(1);
- }
- }
- private function initCache()
- {
- $configDir = __DIR__ . '/config';
- $configPath = $configDir . '/test.php';
- if (File::exists($configPath)) {
- $this->testConfig = include($configPath);
- }
- if (!isset($this->cache['mom_apps'])) {
- $this->cache['mom_apps'] = [];
- }
- if (!isset($this->cache['promoters'])) {
- $this->cache['promoters'] = [];
- }
- if (!isset($this->cache['agents'])) {
- $this->cache['agents'] = [];
- }
- if (!isset($this->cache['channels'])) {
- $this->cache['channels'] = [];
- }
- }
- /**
- * 获取faker
- * @return Faker|\Illuminate\Contracts\Foundation\Application|mixed|null
- */
- private function getFaker()
- {
- if (!$this->faker instanceof Faker) {
- $this->faker = app(Faker::class);
- }
- return $this->faker;
- }
- private function appMom()
- {
- $apps = AppModel::all();
- foreach ($apps as $item) {
- $this->cache['mom_apps'][$item->uid] = $item->toArray();
- }
- }
- /**
- * 生成代理.
- */
- private function agent()
- {
- $amount = isset($this->testConfig['generate_test']['amount_agent']) ? intval($this->testConfig['generate_test']['amount_agent']) : 1;
- for ($i = 0; $i < $amount; $i++) {
- $oneAgent = self::agentUserStruct();
- $parentUid = '';
- $commissionRatio = 100;
- $commissionDiffRatio = 100;
- $oneAgent['base']['commission_ratio'] = $commissionRatio;
- $oneAgent['base']['commission_diff_ratio'] = $commissionDiffRatio;
- $obj = $this->getAgentRepo()->createOne($oneAgent['base'], $parentUid);
- $agentUid = $obj->uid;
- $oneAgent['base']['uid'] = $agentUid;
- $oneAgent['base']['parent_uid'] = $obj->parent_uid;
- $oneAgent['attrs']['agent_uid'] = $agentUid;
- $this->cache['agents'][$agentUid] = $oneAgent;
- $this->cache['agents'][$agentUid]['child_channels'] = []; // 预先定义拥有渠道
- self::comment('创建代理用户:'. $agentUid);
- self::channel($oneAgent); // 创建该代理下的渠道.
- $childAgent = self::agentUserStruct();
- $childAgent['parent_uid'] = $oneAgent['base']['parent_uid'];
- $diffRatio = rand(10, 20);
- $childAgent['base']['commission_ratio'] = $oneAgent['base']['commission_ratio'] - $diffRatio;
- $childAgent['base']['commission_diff_ratio'] = $diffRatio;
- $childObj = $this->getAgentRepo()->createOne($childAgent['base'], $agentUid);
- $childUid = $childObj->uid;
- $childAgent['base']['uid'] = $childUid;
- $childAgent['base']['parent_uid'] = $childObj->parent_uid;
- $childAgent['attrs']['agent_uid'] = $childUid;
- $this->cache['agents'][$childUid] = $childAgent;
- $this->cache['agents'][$childUid]['child_channels'] = []; // 预先定义拥有渠道
- self::comment('创建2级代理用户:'. $childUid);
- self::channel($childAgent); // 创建该代理下的渠道.
- }
- }
- private function channel($agent)
- {
- $isExists = $this->getChannelRepo()->makeModel()->query()->where('agent_uid', $agent['base']['uid'])->exists();
- if ($isExists) {
- $lists = $this->getChannelRepo()->makeModel()->query()->where('agent_uid', $agent['base']['uid'])->get();
- foreach ($lists as $item) {
- $info = $item->toArray();
- if (!isset($this->cache['agents'][$agent['base']['uid']]['child_channels'])) {
- $this->cache['agents'][$agent['base']['uid']]['child_channels'] = [];
- }
- $this->cache['agents'][$agent['base']['uid']]['child_channels'][$item['uid']] = $info;
- $this->cache['channels'][$item['uid']] = $info; // 追加渠道.
- self::comment('初始化代理用户下['. $agent['base']['uid'] .']的渠道:'. $item['uid']);
- }
- } else {
- $amount = isset($this->testConfig['generate_test']['amount_channel']) ? intval($this->testConfig['generate_test']['amount_channel']) : 1;
- // 只创建一个.
- for ($i = 0; $i < $amount; $i++) {
- $momAppUid = array_rand($this->cache['mom_apps']);
- $item = [
- 'name' => self::getFaker()->name(),
- 'agent_uid' => $agent['base']['uid'],
- 'mom_app_uid' => $momAppUid,
- ];
- $result = $this->getChannelRepo()->createOne($item);
- $item['uid'] = $result->uid;
- if (!isset($this->cache['agents'][$agent['base']['uid']]['child_channels'])) {
- $this->cache['agents'][$agent['base']['uid']]['child_channels'] = [];
- }
- $this->cache['agents'][$agent['base']['uid']]['child_channels'][$item['uid']] = $item;
- $this->cache['channels'][$item['uid']] = $item; // 追加渠道.
- self::comment('创建代理用户下['. $agent['base']['uid'] .']的渠道:'. $item['uid']);
- }
- }
- return true;
- }
- /**
- * 代理系统用户基础结构
- * @return array
- */
- private function agentUserStruct()
- {
- $password = 'wg888888';
- $salt = $this->getAgentRepo()->makeSalt();
- $hashPwd = $this->getAgentRepo()->generatePassword($password, $salt);
- $momAppUid = array_rand($this->cache['mom_apps']);
- $arrOwnAppUids = [$momAppUid];
- $strOwnAppUids = implode(',', $arrOwnAppUids);
- $userBase = [
- 'username' => strtolower($this->getFaker()->userName() . '_' . strtolower(random(6))),
- 'password' => $hashPwd,
- 'salt' => $salt,
- 'nick' => $this->getFaker()->name(),
- 'status' => 1,
- 'agent_level' => -999,
- 'parent_uid' => '',
- 'commission_ratio' => 0,
- 'commission_diff_ratio' => 0,
- 'jdata' => null,
- 'own_app_uids' => $strOwnAppUids,
- ];
- $userAttrs = [
- 'agent_uid' => '',
- ];
- $user = [
- 'base' => $userBase,
- 'attrs' => $userAttrs,
- ];
- return $user;
- }
- /**
- * 创建用户的角色关系.
- * @param $userUid
- * @param $roleId
- * @return mixed
- */
- private function createUserRole($userUid, $roleId)
- {
- $roleUserTable = config('admin.database.role_users_table');
- $setarr = [
- 'role_id' => $roleId,
- 'user_id' => $userUid,
- ];
- return \DB::table($roleUserTable)->insert($setarr);
- }
- /**
- * 创建全局规则.
- * @return bool
- */
- private function createGlobalRule()
- {
- $items = $this->getConfigRepo()->pushCriteria(new OrderLimitCriteria([], 1))->findWhere(['sgroup' => 'sys', 'skey' => 'global_deduction_rules']);
- if ($items->count() == 0) {
- // 创建
- $jsonRule = '{"deduction": {"pay": {"scope": [{"per_num": 10, "max_price": 49, "min_price": 30, "is_deduction": false, "deduction_num": 1}, {"per_num": 30, "max_price": 99, "min_price": 50, "is_deduction": true, "deduction_num": 2}, {"per_num": 10, "max_price": 49, "min_price": 30, "is_deduction": false, "deduction_num": 1}, {"per_num": 10, "max_price": 49, "min_price": 30, "is_deduction": false, "deduction_num": 1}, {"per_num": 10, "max_price": 49, "min_price": 30, "is_deduction": false, "deduction_num": 1}], "escape": 20}, "user": {"ratio": 10, "escape": 20}, "deduction_type": 1}}';
- $setarr = [
- 'name' => '系统全局扣量规则',
- 'sgroup' => 'sys',
- 'skey' => 'global_deduction_rules',
- 'svalue' => $jsonRule,
- ];
- $obj = $this->getConfigRepo()->create($setarr);
- return boolval($obj);
- } else {
- return false;
- }
- }
- /**
- * 终端输出备注.
- * @param $txt
- */
- private function comment($txt)
- {
- $this->command->comment('['. Carbon::now()->toDateTimeString() .']'. $txt);
- }
- /**
- * 生成新用户
- * @param $date
- * @param int $amountUsers
- * @param int $startId
- * @param string $appVersion
- */
- private function incNewUsers($date, $amountUsers = 100, $startId = 1000, $appVersion = '1.0.2')
- {
- $maxId = $startId + $amountUsers;
- $data = [];
- for ($id = $startId; $id < $maxId; $id++) {
- $channelUid = array_rand($this->cache['channels']);
- $uid = hashEncodeId($id);
- $createdAt = Carbon::parse($date)->setHours(13)->setMinutes(30);
- $momAppUid = $this->cache['channels'][$channelUid]['mom_app_uid'];
- $agentUid = $this->cache['channels'][$channelUid]['agent_uid'];
- $deviceType = $id % 2 == 0 ? 'A' : 'I';
- $deviceNo = md5(strval($id + 500));
- $isDeduction = rand(0, 1);
- $ip = implode('.', [rand(111, 254), rand(111, 254), rand(111, 254), rand(111, 254)]);
- $arrIpAddress = Ip::find($ip);
- $ipAddress = implode(' ', array_slice($arrIpAddress, 3));
- $item = [
- 'user_uid' => $uid,
- 'agent_uid' => $agentUid,
- 'created_at' => $createdAt,
- 'channel_uid' => $channelUid,
- 'mom_app_uid' => $momAppUid,
- 'app_version' => $appVersion,
- 'device_type' => $deviceType,
- 'device_no' => $deviceNo,
- 'ip' => $ip,
- 'ip_address' => $ipAddress,
- ];
- $item = $this->getUserService()->oneRandDeduction($item);
- $data[] = $item;
- }
- $this->getUserService()->inc($data);
- $this->comment('造用户,日期:'. $date . ',总计:'. $amountUsers . ', 开始ID:'. $startId . ',结束ID:'. $maxId);
- }
- /**
- * 生成充值(概率事件)
- * @param $date
- * @param int $amountUsers
- * @param int $startId
- * @param string $appVersion
- */
- private function incPay($date, $amountUsers = 100, $startId = 1000, $appVersion = '1.0.1')
- {
- $maxId = $startId + $amountUsers;
- $data = [];
- $arrDeviceTypes = ['A', 'I'];
- $arrPayTypes = ['wx', 'alipay', 'h5', 'union'];
- $arrOrderPrefix = ['XXAPP'];
- $arrPayChannel = ['xiyouji', 'maotai', 'zijin'];
- $arrPayStatus = ['1', '2', '3'];
- $arrOrderStatus = [1, 2, 3, 4];
- $arrOrderTypes = ['vip', 'coin', 'loufeng'];
- $arrPayGateWays = ['ys-wx', 'h5-alipay', 'h5-wx', 'wx-huafei'];
- for ($id = $startId; $id < $maxId; $id++) {
- $luck = rand(1, 10) % 2 == 0;
- if (!$luck) {
- // 硬币50概率,产生支付订单.
- continue;
- }
- $userUid = hashEncodeId($id);
- $orderSn = $arrOrderPrefix[0]. random(12);
- $payType = $arrPayTypes[array_rand($arrPayTypes, 1)];
- $payChannel = $arrPayChannel[array_rand($arrPayChannel, 1)];
- $payStatus = $arrPayStatus[array_rand($arrPayStatus, 1)];
- $orderStatus = $arrOrderStatus[array_rand($arrOrderStatus, 1)];
- $payGateWay = $arrPayGateWays[array_rand($arrPayGateWays, 1)];
- $orderAmount = rand(1, 99) * 10;
- $realAmount = floatval(number_format($orderAmount * (rand(10, 90) / 100), 2));
- $transactionNo = random(16);
- $buyNum = 20;
- $goodsInfo = '购买金币套餐1';
- if ($payStatus == 1) {
- $orderStatus = 1;
- }
- $channelUid = array_rand($this->cache['channels']);
- $agentUid = $this->cache['channels'][$channelUid]['agent_uid'];
- $createdAt = Carbon::parse($date)->setHours(15)->setMinutes(30);
- $momAppUid = $this->cache['channels'][$channelUid]['mom_app_uid'];
- $deviceType = $id % 2 == 0 ? 'A' : 'I';
- $orderType = $arrOrderTypes[array_rand($arrOrderTypes, 1)];
- $item = [
- 'user_uid' => $userUid,
- 'channel_uid' => $channelUid,
- 'agent_uid' => $agentUid,
- 'mom_app_uid' => $momAppUid,
- 'device_type' => $deviceType,
- 'created_at' => $createdAt,
- 'updated_at' => $createdAt,
- 'paid_at' => $createdAt,
- 'order_sn' => $orderSn,
- 'order_type' => $orderType,
- 'pay_type' => $payType,
- 'pay_channel' => $payChannel,
- 'pay_gate_way' => $payGateWay,
- 'order_amount' => $orderAmount,
- 'real_amount' => $realAmount,
- 'transaction_no' => $transactionNo,
- 'buy_num' => $buyNum,
- 'goods_info' => $goodsInfo,
- 'pay_status' => $payStatus,
- 'order_status' => $orderStatus,
- 'invite_uid' => '', // 分享码
- ];
- $item = $this->getPayService()->oneRandDeduction($item);
- $data[] = $item;
- }
- $this->getPayService()->inc($data);
- $this->comment('造支付,日期:'. $date . ',总计:'. $amountUsers . ', 开始ID:'. $startId . ',结束ID:'. $maxId);
- }
- /**
- * 获取用户服务.
- * @return UserService
- */
- private function getUserService()
- {
- if (!$this->userService instanceof UserService) {
- $this->userService = new UserService();
- }
- return $this->userService;
- }
- /**
- * 获取支付服务.
- * @return PayService
- */
- private function getPayService()
- {
- if (!$this->payService instanceof PayService) {
- $this->payService = new PayService();
- }
- return $this->payService;
- }
- /**
- * @return AgentRepository|AppRepository|\Illuminate\Contracts\Foundation\Application|mixed|null
- */
- private function getAgentRepo()
- {
- if (!$this->agentRepo instanceof AgentRepository) {
- $this->agentRepo = app(AgentRepository::class);
- }
- return $this->agentRepo;
- }
- /**
- * @return ConfigRepoistory|\Illuminate\Contracts\Foundation\Application|mixed|null
- */
- private function getConfigRepo()
- {
- if (!$this->configRepo instanceof ConfigRepoistory) {
- $this->configRepo = app(ConfigRepoistory::class);
- }
- return $this->configRepo;
- }
- /**
- * @return ChannelRepository|\Illuminate\Contracts\Foundation\Application|mixed|null
- */
- private function getChannelRepo()
- {
- if (!$this->channelRepo instanceof ChannelRepository) {
- $this->channelRepo = app(ChannelRepository::class);
- }
- return $this->channelRepo;
- }
- }
|