Maintain.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. namespace tw\command;
  3. use app\admin\model\store\StoreProduct;
  4. use app\admin\model\store\StoreProductAttr;
  5. use app\admin\model\store\StoreProductAttrResult;
  6. use app\admin\model\store\StoreProductAttrValue;
  7. use app\api\controller\board\UserBoardController;
  8. use app\models\store\StoreProductRule;
  9. use think\console\Command;
  10. use think\console\Input;
  11. use think\console\input\Argument;
  12. use think\console\Output;
  13. use \think\facade\Config;
  14. // use MeiliSearch\Client;
  15. use tw\lib\robot\Robots;
  16. /**
  17. * 维护命令,使用 nginx 帐号运行
  18. *
  19. * sudo -u http php think maintain ***
  20. */
  21. class Maintain extends Command
  22. {
  23. const PREV_YEAR = 21; // 活动的上一年标志。比如`幸运2021` 更新为 `幸运2022`,这个值就是 21
  24. protected $NEW_YEAR; // new year value
  25. protected $LUCKY;
  26. protected function configure()
  27. {
  28. $this->setName('maintain')
  29. ->addArgument('category', Argument::REQUIRED, 'act|prod|trash|reindex|robot_order|order_reset|none')
  30. ->setDescription('maintain some application data.');
  31. }
  32. protected function init(Input $input, Output $output)
  33. {
  34. global $argv;
  35. $argv[1] = $input->getArgument('category') ?? 'none';
  36. }
  37. protected function execute(Input $input, Output $output)
  38. {
  39. $category = $input->getArgument('category');
  40. if (is_callable([$this, $category])) {
  41. $this->$category();
  42. } else {
  43. console::log('bad argument ', $category);
  44. }
  45. }
  46. /**
  47. * 修改幸运 2021 后面的 2021
  48. *
  49. * IMPORTANT:
  50. * 修改步骤:
  51. * 1. 修改 eb_store_category 中分类名称
  52. * 2. 修改 congit/activity 中配置
  53. * 3. 执行 php think maintain act
  54. */
  55. protected function act()
  56. {
  57. console::log(__FUNCTION__);
  58. $act_parts = Config::get('activity.lucky_spec_items', []);
  59. if (is_array($act_parts) && count($act_parts) > 1) {
  60. $this->NEW_YEAR = intval($act_parts[1]);
  61. } else {
  62. console::log('bad config: activity.lucky_spec_items. quit.');
  63. return;
  64. }
  65. $act_name = Config::get('activity.lucky_spec_name', '');
  66. $this->LUCKY = $act_name;
  67. $this->_update_StoreProductAttr();
  68. $this->_update_StoreProductAttrValue();
  69. $this->_update_StoreProductAttrResult();
  70. $this->_udpate_StoreProductRule();
  71. }
  72. /**
  73. * 修改
  74. */
  75. private function _update_StoreProductAttr()
  76. {
  77. $rows = StoreProductAttr::getLuckyAttrs($this->LUCKY);
  78. $changed = false;
  79. foreach ($rows as &$row) {
  80. $changed = false;
  81. //
  82. if (
  83. is_array($row['attr_values']) &&
  84. count($row['attr_values']) > 1 &&
  85. intval($row['attr_values'][1]) == self::PREV_YEAR
  86. ) {
  87. $row['attr_values'][1] = $this->NEW_YEAR;
  88. $changed = true;
  89. }
  90. // sql
  91. if ($changed) {
  92. try {
  93. $data['attr_values'] = implode(',', $row['attr_values']);
  94. // console::log($row);
  95. $ok = StoreProductAttr::where('product_id', $row['product_id'])
  96. ->where('attr_name', $row['attr_name'])
  97. ->update($data);
  98. if (!$ok) {
  99. console::log('execute sql failed.');
  100. }
  101. } catch (\Exception $e) {
  102. console::log('execute sql exception:', $e->getMessage());
  103. }
  104. }
  105. } // foreach
  106. console::log('table StoreProductAttr updated.');
  107. }
  108. private function _update_StoreProductAttrValue()
  109. {
  110. $rows = StoreProductAttrValue::where('suk', 'like', '%' . self::PREV_YEAR . '%')->select()->toArray();
  111. foreach ($rows as $row) {
  112. $changed = false;
  113. $suks = explode(',', $row['suk']); // array
  114. // replace
  115. for ($i = 0; $i < count($suks); $i++) {
  116. if (intval($suks[$i]) == self::PREV_YEAR) {
  117. $suks[$i] = $this->NEW_YEAR;
  118. $changed = true;
  119. }
  120. }
  121. if (!$changed) {
  122. continue;
  123. }
  124. // $data['unique'] = sp_random_string(); // $row['unique'];
  125. $data['suk'] = implode(',', $suks); // string again
  126. try {
  127. $ok = StoreProductAttrValue::edit($data, $row['unique'], 'unique');
  128. if (!$ok) {
  129. console::log('update StoreProductAttrValue failed.', $ok);
  130. }
  131. } catch (\Exception $e) {
  132. console::log('update StoreProductAttrValue exception:', $e->getMessage());
  133. }
  134. }
  135. }
  136. private function _update_StoreProductAttrResult()
  137. {
  138. $rows = StoreProductAttrResult::where("1=1")->field('product_id,result')->select()->toArray();
  139. $changed = false;
  140. foreach ($rows as $row) {
  141. $changed = false;
  142. $result = json_decode($row['result'], true);
  143. if (isset($result['attr']) && count($result['attr']) > 0) {
  144. foreach ($result['attr'] as &$attr) {
  145. if (!isset($attr['value']) || $attr['value'] != $this->LUCKY) {
  146. continue;
  147. }
  148. if (isset($attr['detail']) && count($attr['detail']) > 0) {
  149. for ($i = 0; $i < count($attr['detail']); $i++) {
  150. // update
  151. if (intval($attr['detail'][$i]) == self::PREV_YEAR) {
  152. $attr['detail'][$i] = strval($this->NEW_YEAR);
  153. $changed = true;
  154. }
  155. }
  156. }
  157. }
  158. }
  159. if (isset($result['value']) && count($result['value']) > 0) {
  160. foreach ($result['value'] as &$value) {
  161. foreach ($value as $k => $v) {
  162. if (substr($k, 0, 5) == 'value' && intval($v) == self::PREV_YEAR) {
  163. $value[$k] = strval($this->NEW_YEAR);
  164. $changed = true;
  165. } else if ($k == 'detail') {
  166. foreach ($v as $kk => $vv) {
  167. // update
  168. if ($kk == $this->LUCKY && intval($vv) == self::PREV_YEAR) {
  169. $value[$k][$kk] = strval($this->NEW_YEAR);
  170. $changed = true;
  171. }
  172. }
  173. }
  174. }
  175. }
  176. }
  177. if (!$changed) {
  178. continue;
  179. }
  180. try {
  181. $data['result'] = json_encode($result);
  182. // console::log($row['product_id']);
  183. $ok = StoreProductAttrResult::where('product_id', $row['product_id'])
  184. ->update($data);
  185. if (!$ok) {
  186. console::log('sql execute error:', StoreProductAttrResult::getErrorInfo());
  187. }
  188. } catch (\Exception $e) {
  189. console::log('exception:', $e->getMessage());
  190. }
  191. }
  192. }
  193. private function _udpate_StoreProductRule()
  194. {
  195. $rows = StoreProductRule::where('rule_name', 'like', '%' . $this->LUCKY . '%')->select()->toArray();
  196. $changed = false;
  197. foreach ($rows as $row) {
  198. $changed = false;
  199. $values = json_decode($row['rule_value'], true);
  200. if (is_array($values)) {
  201. foreach ($values as &$value) {
  202. if (!isset($value['value']) && $value['value'] != $this->LUCKY) {
  203. continue;
  204. }
  205. if (
  206. isset($value['detail']) &&
  207. is_array($value['detail']) &&
  208. count($value['detail']) > 0
  209. ) {
  210. for ($i = 0; $i < count($value['detail']); $i++) {
  211. if (intval($value['detail'][$i]) == self::PREV_YEAR) {
  212. $value['detail'][$i] = strval($this->NEW_YEAR);
  213. $changed = true;
  214. }
  215. }
  216. }
  217. }
  218. }
  219. if (!$changed) {
  220. continue;
  221. }
  222. $data['rule_value'] = json_encode($values);
  223. try {
  224. console::log($values);
  225. $ok = StoreProductRule::where('id', $row['id'])->update($data);
  226. if (!$ok) {
  227. console::log('StoreProductRule failed:', StoreProductRule::getErrorInfo());
  228. }
  229. } catch (\Exception $e) {
  230. console::log('StoreProductRule exception:', $e->getMessage());
  231. }
  232. }
  233. }
  234. /**
  235. * 让一定时间之前的商品下架
  236. */
  237. protected function prod()
  238. {
  239. $now = time();
  240. $days = sys_config_int('off_days_before');
  241. if ($days <= 0) {
  242. warnlog("maintain prod quit. off_days_before=$days");
  243. return;
  244. }
  245. $days_ago = $now - $days * SECONDS_OF_ONEDAY;
  246. // 找到过期商品
  247. $products = StoreProduct::where([
  248. 'is_del' => 0,
  249. 'is_show' => 1,
  250. ])->where('add_time', '<', $days_ago)
  251. ->select()->toArray();
  252. // 下架
  253. $ids = [];
  254. foreach ($products as $p) {
  255. array_push($ids, $p['id']);
  256. }
  257. $ret = Storeproduct::where('id', 'in', $ids)->update([
  258. 'is_show' => 0,
  259. ]);
  260. // 记录日志
  261. warnlog("auto off-shelves executed: $ret" . json_encode($ids));
  262. }
  263. /**
  264. * 删除过期日志等数据
  265. */
  266. protected function trash()
  267. {
  268. }
  269. /**
  270. * 备份数据库
  271. *
  272. * 后台备份功能超出内存限制
  273. */
  274. protected function backup()
  275. {
  276. $db = config('database.connections.' . config('database.default'));
  277. $user = $db['username'];
  278. $password = $db['password'];
  279. $host = $db['hostname'];
  280. $database = $db['database'];
  281. $now = time();
  282. $dir = "backup-$now.sql";
  283. exec("mysqldump --user={$user} --password={$password} --host={$host} {$database} --result-file={$dir} 2>&1", $output);
  284. warnlog('backup database:' . json_encode($output));
  285. }
  286. /**
  287. * 创建机器人
  288. */
  289. protected function robot_init()
  290. {
  291. return Robots::to_redis();
  292. }
  293. /**
  294. * 机器人定时下单
  295. */
  296. protected function robot_order()
  297. {
  298. Robots::order();
  299. (new UserBoardController)->cache_board();
  300. }
  301. /**
  302. * 每日重置机器人日榜数据
  303. */
  304. protected function robot_reset()
  305. {
  306. Robots::to_redis();
  307. }
  308. /**
  309. * 重新索引商品
  310. *
  311. * 1.用于常见的商品分类展示。
  312. * 2.用于关键字搜索
  313. * 3.用于按价格/销量/好评度/上线时间排序
  314. *
  315. * TODO:
  316. * - 新增/上架商品: 新增索引
  317. * - 删除/下架商品:删除索引
  318. * - 編輯商品:重新索引
  319. *
  320. * cur: 當前新增的商品不會立即出現在搜索結果,而是每次都重新索引全部。
  321. * 因为这样实现简单,另外商品总的数据量不会很大
  322. *
  323. */
  324. // protected function reindex()
  325. // {
  326. // $ml = new Client(config('meilisearch.addr'), config('meilisearch.key'));
  327. // // remove first
  328. // $ml->deleteIndex('products');
  329. // // rebuild
  330. // $idx = $ml->index('products');
  331. // // setup
  332. // $idx->updateSearchableAttributes([
  333. // 'store_name',
  334. // 'store_info',
  335. // 'keyword',
  336. // ]);
  337. // $idx->updateFilterableAttributes([
  338. // 'cate_id',
  339. // 'price',
  340. // 'is_hot',
  341. // 'is_benefit',
  342. // 'is_best',
  343. // 'is_new',
  344. // 'add_time',
  345. // 'is_good',
  346. // ]);
  347. // $idx->updateSortableAttributes([
  348. // 'price',
  349. // 'sales',
  350. // 'cost',
  351. // 'browse',
  352. // ]);
  353. // // get all products
  354. // $page = 1;
  355. // $limit = 20;
  356. // $count = 0;
  357. // while (true) {
  358. // $products = StoreProduct::where('is_del', 0)
  359. // ->where('stock', '>', 0)
  360. // ->where('is_show', 1)
  361. // ->field('id,image,slider_image,store_name,
  362. // store_info,keyword,cate_id,price,vip_price,ot_price,postage,
  363. // unit_name,sort,sales,stock,
  364. // is_hot,is_benefit,is_best,is_new,add_time,is_postage,
  365. // give_integral,cost,is_good,ficti,spec_type,browse')
  366. // ->page($page, $limit)->select()->toArray();
  367. // $count += count($products);
  368. // if (count($products) > 0) {
  369. // $idx->addDocuments($products, 'id');
  370. // }
  371. // // no more rows
  372. // if (count($products) < $limit) {
  373. // break;
  374. // }
  375. // // loop
  376. // $page += 1;
  377. // }
  378. // echo "re-index all products finished. total=$count" . PHP_EOL;
  379. // }
  380. protected function _all_products_on_sale()
  381. {
  382. }
  383. protected function none()
  384. {
  385. // Robots::build();
  386. // print_r(Robots::$robots);
  387. // Robots::to_redis();
  388. // Robots::order();
  389. $robots = Robots::first_n_by_value(10);
  390. console::log($robots);
  391. }
  392. }