GenerateTestSeeder.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. <?php
  2. /**
  3. * 造测试数据.
  4. *
  5. * @author nj
  6. * @date 2021-08-14 10:20
  7. */
  8. use Illuminate\Database\Seeder;
  9. use Faker\Generator as Faker;
  10. use Carbon\Carbon;
  11. use App\Models\Mysql\AppModel;
  12. use Zhuzhichao\IpLocationZh\Ip;
  13. use Modules\InnerApi\Services\UserService;
  14. use Modules\InnerApi\Services\PayService;
  15. use Illuminate\Support\Facades\File;
  16. use App\Repositories\AgentRepository;
  17. use App\Repositories\ConfigRepoistory;
  18. use App\Repositories\Criterias\OrderLimitCriteria;
  19. use App\Repositories\ChannelRepository;
  20. /**
  21. * 命令:php -d memory_limit=100M artisan db:seed --class=GenerateTestSeeder
  22. * Class GenerateTestSeeder
  23. */
  24. class GenerateTestSeeder extends Seeder
  25. {
  26. /**
  27. * @var null|Faker
  28. */
  29. protected $faker = null;
  30. /**
  31. * 临时内存缓存
  32. * @var array
  33. */
  34. protected $cache = [];
  35. /**
  36. * 总代UID,代理系统中的第一个超管UID
  37. * @var string
  38. */
  39. protected $superUid = 'dQELY6';
  40. /**
  41. * 用户服务.
  42. * @var null|UserService
  43. */
  44. protected $userService = null;
  45. /**
  46. * 支付服务
  47. * @var null|PayService
  48. */
  49. protected $payService = null;
  50. /**
  51. * 测试配置.
  52. * @var array
  53. */
  54. protected $testConfig = [];
  55. /**
  56. * @var null |AgentRepository
  57. */
  58. protected $agentRepo = null;
  59. /**
  60. * @var null|ConfigRepoistory
  61. */
  62. protected $configRepo = null;
  63. /**
  64. * @var null|ChannelRepository
  65. */
  66. protected $channelRepo = null;
  67. public function run()
  68. {
  69. if (app()->environment() == 'production') {
  70. $this->comment('err, 禁止用于生产环境');
  71. return false;
  72. }
  73. // 创建全局规则.
  74. self::createGlobalRule();
  75. // 不限制超时.
  76. // set_time_limit(0);
  77. // 初始化缓存.
  78. self::initCache();
  79. // 缓存里初始化母包.
  80. self::appMom();
  81. // 创建代理.
  82. self::agent();
  83. // 新用户进来.
  84. $amountUsers = isset($this->testConfig['generate_test']['amount_users']) ? intval($this->testConfig['generate_test']['amount_users']) : 10;
  85. $startId = isset($this->testConfig['generate_test']['start_id']) ? intval($this->testConfig['generate_test']['start_id']) : 1000;
  86. $appVersion = isset($this->testConfig['generate_test']['app_version']) ? strval($this->testConfig['generate_test']['app_version']) : '1.0.1';
  87. $startDate = isset($this->testConfig['generate_test']['start_date']) ? strval($this->testConfig['generate_test']['start_date']) : '2021-08-13';
  88. $endDate = isset($this->testConfig['generate_test']['end_date']) ? strval($this->testConfig['generate_test']['end_date']) : '2021-08-16';
  89. $startDateObj = Carbon::parse($startDate);
  90. $endDateObj = Carbon::parse($endDate)->endOfDay();
  91. while ($startDateObj < $endDateObj) {
  92. $date = (clone $startDateObj)->toDateString();
  93. // 生产用户.
  94. self::incNewUsers($date, $amountUsers, $startId, $appVersion);
  95. // 生产支付.
  96. self::incPay($date, $amountUsers, $startId, $appVersion);
  97. $startDateObj = $startDateObj->addDays(1);
  98. }
  99. }
  100. private function initCache()
  101. {
  102. $configDir = __DIR__ . '/config';
  103. $configPath = $configDir . '/test.php';
  104. if (File::exists($configPath)) {
  105. $this->testConfig = include($configPath);
  106. }
  107. if (!isset($this->cache['mom_apps'])) {
  108. $this->cache['mom_apps'] = [];
  109. }
  110. if (!isset($this->cache['promoters'])) {
  111. $this->cache['promoters'] = [];
  112. }
  113. if (!isset($this->cache['agents'])) {
  114. $this->cache['agents'] = [];
  115. }
  116. if (!isset($this->cache['channels'])) {
  117. $this->cache['channels'] = [];
  118. }
  119. }
  120. /**
  121. * 获取faker
  122. * @return Faker|\Illuminate\Contracts\Foundation\Application|mixed|null
  123. */
  124. private function getFaker()
  125. {
  126. if (!$this->faker instanceof Faker) {
  127. $this->faker = app(Faker::class);
  128. }
  129. return $this->faker;
  130. }
  131. private function appMom()
  132. {
  133. $apps = AppModel::all();
  134. foreach ($apps as $item) {
  135. $this->cache['mom_apps'][$item->uid] = $item->toArray();
  136. }
  137. }
  138. /**
  139. * 生成代理.
  140. */
  141. private function agent()
  142. {
  143. $amount = isset($this->testConfig['generate_test']['amount_agent']) ? intval($this->testConfig['generate_test']['amount_agent']) : 1;
  144. for ($i = 0; $i < $amount; $i++) {
  145. $oneAgent = self::agentUserStruct();
  146. $parentUid = '';
  147. $commissionRatio = 100;
  148. $commissionDiffRatio = 100;
  149. $oneAgent['base']['commission_ratio'] = $commissionRatio;
  150. $oneAgent['base']['commission_diff_ratio'] = $commissionDiffRatio;
  151. $obj = $this->getAgentRepo()->createOne($oneAgent['base'], $parentUid);
  152. $agentUid = $obj->uid;
  153. $oneAgent['base']['uid'] = $agentUid;
  154. $oneAgent['base']['parent_uid'] = $obj->parent_uid;
  155. $oneAgent['attrs']['agent_uid'] = $agentUid;
  156. $this->cache['agents'][$agentUid] = $oneAgent;
  157. $this->cache['agents'][$agentUid]['child_channels'] = []; // 预先定义拥有渠道
  158. self::comment('创建代理用户:'. $agentUid);
  159. self::channel($oneAgent); // 创建该代理下的渠道.
  160. $childAgent = self::agentUserStruct();
  161. $childAgent['parent_uid'] = $oneAgent['base']['parent_uid'];
  162. $diffRatio = rand(10, 20);
  163. $childAgent['base']['commission_ratio'] = $oneAgent['base']['commission_ratio'] - $diffRatio;
  164. $childAgent['base']['commission_diff_ratio'] = $diffRatio;
  165. $childObj = $this->getAgentRepo()->createOne($childAgent['base'], $agentUid);
  166. $childUid = $childObj->uid;
  167. $childAgent['base']['uid'] = $childUid;
  168. $childAgent['base']['parent_uid'] = $childObj->parent_uid;
  169. $childAgent['attrs']['agent_uid'] = $childUid;
  170. $this->cache['agents'][$childUid] = $childAgent;
  171. $this->cache['agents'][$childUid]['child_channels'] = []; // 预先定义拥有渠道
  172. self::comment('创建2级代理用户:'. $childUid);
  173. self::channel($childAgent); // 创建该代理下的渠道.
  174. }
  175. }
  176. private function channel($agent)
  177. {
  178. $isExists = $this->getChannelRepo()->makeModel()->query()->where('agent_uid', $agent['base']['uid'])->exists();
  179. if ($isExists) {
  180. $lists = $this->getChannelRepo()->makeModel()->query()->where('agent_uid', $agent['base']['uid'])->get();
  181. foreach ($lists as $item) {
  182. $info = $item->toArray();
  183. if (!isset($this->cache['agents'][$agent['base']['uid']]['child_channels'])) {
  184. $this->cache['agents'][$agent['base']['uid']]['child_channels'] = [];
  185. }
  186. $this->cache['agents'][$agent['base']['uid']]['child_channels'][$item['uid']] = $info;
  187. $this->cache['channels'][$item['uid']] = $info; // 追加渠道.
  188. self::comment('初始化代理用户下['. $agent['base']['uid'] .']的渠道:'. $item['uid']);
  189. }
  190. } else {
  191. $amount = isset($this->testConfig['generate_test']['amount_channel']) ? intval($this->testConfig['generate_test']['amount_channel']) : 1;
  192. // 只创建一个.
  193. for ($i = 0; $i < $amount; $i++) {
  194. $momAppUid = array_rand($this->cache['mom_apps']);
  195. $item = [
  196. 'name' => self::getFaker()->name(),
  197. 'agent_uid' => $agent['base']['uid'],
  198. 'mom_app_uid' => $momAppUid,
  199. ];
  200. $result = $this->getChannelRepo()->createOne($item);
  201. $item['uid'] = $result->uid;
  202. if (!isset($this->cache['agents'][$agent['base']['uid']]['child_channels'])) {
  203. $this->cache['agents'][$agent['base']['uid']]['child_channels'] = [];
  204. }
  205. $this->cache['agents'][$agent['base']['uid']]['child_channels'][$item['uid']] = $item;
  206. $this->cache['channels'][$item['uid']] = $item; // 追加渠道.
  207. self::comment('创建代理用户下['. $agent['base']['uid'] .']的渠道:'. $item['uid']);
  208. }
  209. }
  210. return true;
  211. }
  212. /**
  213. * 代理系统用户基础结构
  214. * @return array
  215. */
  216. private function agentUserStruct()
  217. {
  218. $password = 'wg888888';
  219. $salt = $this->getAgentRepo()->makeSalt();
  220. $hashPwd = $this->getAgentRepo()->generatePassword($password, $salt);
  221. $momAppUid = array_rand($this->cache['mom_apps']);
  222. $arrOwnAppUids = [$momAppUid];
  223. $strOwnAppUids = implode(',', $arrOwnAppUids);
  224. $userBase = [
  225. 'username' => strtolower($this->getFaker()->userName() . '_' . strtolower(random(6))),
  226. 'password' => $hashPwd,
  227. 'salt' => $salt,
  228. 'nick' => $this->getFaker()->name(),
  229. 'status' => 1,
  230. 'agent_level' => -999,
  231. 'parent_uid' => '',
  232. 'commission_ratio' => 0,
  233. 'commission_diff_ratio' => 0,
  234. 'jdata' => null,
  235. 'own_app_uids' => $strOwnAppUids,
  236. ];
  237. $userAttrs = [
  238. 'agent_uid' => '',
  239. ];
  240. $user = [
  241. 'base' => $userBase,
  242. 'attrs' => $userAttrs,
  243. ];
  244. return $user;
  245. }
  246. /**
  247. * 创建用户的角色关系.
  248. * @param $userUid
  249. * @param $roleId
  250. * @return mixed
  251. */
  252. private function createUserRole($userUid, $roleId)
  253. {
  254. $roleUserTable = config('admin.database.role_users_table');
  255. $setarr = [
  256. 'role_id' => $roleId,
  257. 'user_id' => $userUid,
  258. ];
  259. return \DB::table($roleUserTable)->insert($setarr);
  260. }
  261. /**
  262. * 创建全局规则.
  263. * @return bool
  264. */
  265. private function createGlobalRule()
  266. {
  267. $items = $this->getConfigRepo()->pushCriteria(new OrderLimitCriteria([], 1))->findWhere(['sgroup' => 'sys', 'skey' => 'global_deduction_rules']);
  268. if ($items->count() == 0) {
  269. // 创建
  270. $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}}';
  271. $setarr = [
  272. 'name' => '系统全局扣量规则',
  273. 'sgroup' => 'sys',
  274. 'skey' => 'global_deduction_rules',
  275. 'svalue' => $jsonRule,
  276. ];
  277. $obj = $this->getConfigRepo()->create($setarr);
  278. return boolval($obj);
  279. } else {
  280. return false;
  281. }
  282. }
  283. /**
  284. * 终端输出备注.
  285. * @param $txt
  286. */
  287. private function comment($txt)
  288. {
  289. $this->command->comment('['. Carbon::now()->toDateTimeString() .']'. $txt);
  290. }
  291. /**
  292. * 生成新用户
  293. * @param $date
  294. * @param int $amountUsers
  295. * @param int $startId
  296. * @param string $appVersion
  297. */
  298. private function incNewUsers($date, $amountUsers = 100, $startId = 1000, $appVersion = '1.0.2')
  299. {
  300. $maxId = $startId + $amountUsers;
  301. $data = [];
  302. for ($id = $startId; $id < $maxId; $id++) {
  303. $channelUid = array_rand($this->cache['channels']);
  304. $uid = hashEncodeId($id);
  305. $createdAt = Carbon::parse($date)->setHours(13)->setMinutes(30);
  306. $momAppUid = $this->cache['channels'][$channelUid]['mom_app_uid'];
  307. $agentUid = $this->cache['channels'][$channelUid]['agent_uid'];
  308. $deviceType = $id % 2 == 0 ? 'A' : 'I';
  309. $deviceNo = md5(strval($id + 500));
  310. $isDeduction = rand(0, 1);
  311. $ip = implode('.', [rand(111, 254), rand(111, 254), rand(111, 254), rand(111, 254)]);
  312. $arrIpAddress = Ip::find($ip);
  313. $ipAddress = implode(' ', array_slice($arrIpAddress, 3));
  314. $item = [
  315. 'user_uid' => $uid,
  316. 'agent_uid' => $agentUid,
  317. 'created_at' => $createdAt,
  318. 'channel_uid' => $channelUid,
  319. 'mom_app_uid' => $momAppUid,
  320. 'app_version' => $appVersion,
  321. 'device_type' => $deviceType,
  322. 'device_no' => $deviceNo,
  323. 'ip' => $ip,
  324. 'ip_address' => $ipAddress,
  325. ];
  326. $item = $this->getUserService()->oneRandDeduction($item);
  327. $data[] = $item;
  328. }
  329. $this->getUserService()->inc($data);
  330. $this->comment('造用户,日期:'. $date . ',总计:'. $amountUsers . ', 开始ID:'. $startId . ',结束ID:'. $maxId);
  331. }
  332. /**
  333. * 生成充值(概率事件)
  334. * @param $date
  335. * @param int $amountUsers
  336. * @param int $startId
  337. * @param string $appVersion
  338. */
  339. private function incPay($date, $amountUsers = 100, $startId = 1000, $appVersion = '1.0.1')
  340. {
  341. $maxId = $startId + $amountUsers;
  342. $data = [];
  343. $arrDeviceTypes = ['A', 'I'];
  344. $arrPayTypes = ['wx', 'alipay', 'h5', 'union'];
  345. $arrOrderPrefix = ['XXAPP'];
  346. $arrPayChannel = ['xiyouji', 'maotai', 'zijin'];
  347. $arrPayStatus = ['1', '2', '3'];
  348. $arrOrderStatus = [1, 2, 3, 4];
  349. $arrOrderTypes = ['vip', 'coin', 'loufeng'];
  350. $arrPayGateWays = ['ys-wx', 'h5-alipay', 'h5-wx', 'wx-huafei'];
  351. for ($id = $startId; $id < $maxId; $id++) {
  352. $luck = rand(1, 10) % 2 == 0;
  353. if (!$luck) {
  354. // 硬币50概率,产生支付订单.
  355. continue;
  356. }
  357. $userUid = hashEncodeId($id);
  358. $orderSn = $arrOrderPrefix[0]. random(12);
  359. $payType = $arrPayTypes[array_rand($arrPayTypes, 1)];
  360. $payChannel = $arrPayChannel[array_rand($arrPayChannel, 1)];
  361. $payStatus = $arrPayStatus[array_rand($arrPayStatus, 1)];
  362. $orderStatus = $arrOrderStatus[array_rand($arrOrderStatus, 1)];
  363. $payGateWay = $arrPayGateWays[array_rand($arrPayGateWays, 1)];
  364. $orderAmount = rand(1, 99) * 10;
  365. $realAmount = floatval(number_format($orderAmount * (rand(10, 90) / 100), 2));
  366. $transactionNo = random(16);
  367. $buyNum = 20;
  368. $goodsInfo = '购买金币套餐1';
  369. if ($payStatus == 1) {
  370. $orderStatus = 1;
  371. }
  372. $channelUid = array_rand($this->cache['channels']);
  373. $agentUid = $this->cache['channels'][$channelUid]['agent_uid'];
  374. $createdAt = Carbon::parse($date)->setHours(15)->setMinutes(30);
  375. $momAppUid = $this->cache['channels'][$channelUid]['mom_app_uid'];
  376. $deviceType = $id % 2 == 0 ? 'A' : 'I';
  377. $orderType = $arrOrderTypes[array_rand($arrOrderTypes, 1)];
  378. $item = [
  379. 'user_uid' => $userUid,
  380. 'channel_uid' => $channelUid,
  381. 'agent_uid' => $agentUid,
  382. 'mom_app_uid' => $momAppUid,
  383. 'device_type' => $deviceType,
  384. 'created_at' => $createdAt,
  385. 'updated_at' => $createdAt,
  386. 'paid_at' => $createdAt,
  387. 'order_sn' => $orderSn,
  388. 'order_type' => $orderType,
  389. 'pay_type' => $payType,
  390. 'pay_channel' => $payChannel,
  391. 'pay_gate_way' => $payGateWay,
  392. 'order_amount' => $orderAmount,
  393. 'real_amount' => $realAmount,
  394. 'transaction_no' => $transactionNo,
  395. 'buy_num' => $buyNum,
  396. 'goods_info' => $goodsInfo,
  397. 'pay_status' => $payStatus,
  398. 'order_status' => $orderStatus,
  399. 'invite_uid' => '', // 分享码
  400. ];
  401. $item = $this->getPayService()->oneRandDeduction($item);
  402. $data[] = $item;
  403. }
  404. $this->getPayService()->inc($data);
  405. $this->comment('造支付,日期:'. $date . ',总计:'. $amountUsers . ', 开始ID:'. $startId . ',结束ID:'. $maxId);
  406. }
  407. /**
  408. * 获取用户服务.
  409. * @return UserService
  410. */
  411. private function getUserService()
  412. {
  413. if (!$this->userService instanceof UserService) {
  414. $this->userService = new UserService();
  415. }
  416. return $this->userService;
  417. }
  418. /**
  419. * 获取支付服务.
  420. * @return PayService
  421. */
  422. private function getPayService()
  423. {
  424. if (!$this->payService instanceof PayService) {
  425. $this->payService = new PayService();
  426. }
  427. return $this->payService;
  428. }
  429. /**
  430. * @return AgentRepository|AppRepository|\Illuminate\Contracts\Foundation\Application|mixed|null
  431. */
  432. private function getAgentRepo()
  433. {
  434. if (!$this->agentRepo instanceof AgentRepository) {
  435. $this->agentRepo = app(AgentRepository::class);
  436. }
  437. return $this->agentRepo;
  438. }
  439. /**
  440. * @return ConfigRepoistory|\Illuminate\Contracts\Foundation\Application|mixed|null
  441. */
  442. private function getConfigRepo()
  443. {
  444. if (!$this->configRepo instanceof ConfigRepoistory) {
  445. $this->configRepo = app(ConfigRepoistory::class);
  446. }
  447. return $this->configRepo;
  448. }
  449. /**
  450. * @return ChannelRepository|\Illuminate\Contracts\Foundation\Application|mixed|null
  451. */
  452. private function getChannelRepo()
  453. {
  454. if (!$this->channelRepo instanceof ChannelRepository) {
  455. $this->channelRepo = app(ChannelRepository::class);
  456. }
  457. return $this->channelRepo;
  458. }
  459. }