AlibabaTodayImport.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. namespace app\command;
  3. use app\services\ThirdParty\AlibabaAgent\ProductService;
  4. use think\console\Command;
  5. use think\console\Input;
  6. use think\console\Output;
  7. use think\facade\Db;
  8. /**
  9. * 今日1688商品自动入库命令
  10. *
  11. * 从 alibaba_import_goods 表中获取今日创建的商品,
  12. * 调用 ProductService::importToStoreProduct() 进行正式入库到 store_product 表
  13. *
  14. * 用法:
  15. * php think alibaba:today-import # 默认今天,mer_id=3447
  16. * php think alibaba:today-import --mer_id=3447 # 指定商户ID
  17. * php think alibaba:today-import --date=2026-05-21 # 指定日期
  18. * php think alibaba:today-import --mer_id=3447 --date=2026-05-21 # 指定商户+日期
  19. * php think alibaba:today-import --batch=100 # 每批处理100条(默认50)
  20. * php think alibaba:today-import --skip=10 # 跳过前10条(断点续传)
  21. *
  22. * 定时任务配置(每天23:55执行):
  23. * 55 23 * * * php /www/wwwroot/shop/think alibaba:today-import --mer_id=3447 >> /tmp/alibaba_today_import.log 2>&1
  24. *
  25. * 分润设置(写死):
  26. * - extension_type: 1(开启分润)
  27. * - concession_pri: 售价 × 15%(商家让利金额)
  28. * - extension_one: 15(SKU级分润比例)
  29. * - plate_mer_profit: 0(平台商户利润)
  30. * - commission: 保持原样(不修改)
  31. *
  32. * 原价计算规则(根据SKU售价阶梯加价):
  33. * 1-20元 => 固定加5元
  34. * 21-50元 => 固定加20元
  35. * 51-120元 => 固定加40元
  36. * 121-200元 => 固定加45元
  37. * 201-300元 => 固定加50元
  38. */
  39. class AlibabaTodayImport extends Command
  40. {
  41. protected function configure()
  42. {
  43. $this->setName('alibaba:today-import')
  44. ->setDescription('从alibaba_import_goods获取今日创建的商品,调用importStore接口正式入库')
  45. ->addOption('mer_id', null, \think\console\input\Option::VALUE_OPTIONAL, '商户ID', '3447')
  46. ->addOption('date', null, \think\console\input\Option::VALUE_OPTIONAL, '指定日期 (Y-m-d),默认今天', '')
  47. ->addOption('batch', null, \think\console\input\Option::VALUE_OPTIONAL, '每批处理数量', '50')
  48. ->addOption('skip', null, \think\console\input\Option::VALUE_OPTIONAL, '跳过前N条(断点续传)', '0');
  49. }
  50. protected function execute(Input $input, Output $output)
  51. {
  52. // 解除时间限制
  53. set_time_limit(0);
  54. $output->writeln('========================================');
  55. $output->writeln(' 1688今日商品自动入库 开始');
  56. $output->writeln('========================================');
  57. // 1. 解析参数
  58. $merId = (int)$input->getOption('mer_id');
  59. $date = $input->getOption('date');
  60. $batch = (int)$input->getOption('batch');
  61. $skip = (int)$input->getOption('skip');
  62. if ($batch < 1) $batch = 50;
  63. if ($skip < 0) $skip = 0;
  64. if (empty($date)) {
  65. $date = date('Y-m-d');
  66. }
  67. // ============================================================
  68. // 分润配置(写死)
  69. // ============================================================
  70. $profitConfig = [
  71. 'extension_type' => 1, // 1=开启分润
  72. 'concession_rate' => 0.15, // 商家让利比例15%(concession_pri = 售价 × 15%)
  73. 'extension_one' => 15, // SKU级分润比例15%
  74. ];
  75. $output->writeln("商户ID: {$merId}");
  76. $output->writeln("查询日期: {$date}");
  77. $output->writeln("每批数量: {$batch}");
  78. $output->writeln("跳过前N条: {$skip}");
  79. $output->writeln('分润设置:');
  80. $output->writeln(" extension_type: {$profitConfig['extension_type']} (开启分润)");
  81. $output->writeln(" concession_rate: {$profitConfig['concession_rate']} (售价×{$profitConfig['concession_rate']})");
  82. $output->writeln(" extension_one: {$profitConfig['extension_one']}%");
  83. // 2. 查询今日创建的 alibaba_import_goods 记录(只查ID,不查全字段,节省内存)
  84. $todayStart = $date . ' 00:00:00';
  85. $todayEnd = $date . ' 23:59:59';
  86. $output->write('正在查询今日待入库商品... ');
  87. $allIds = Db::name('alibaba_import_goods')
  88. ->where('status', 1)
  89. ->where('create_time', '>=', $todayStart)
  90. ->where('create_time', '<=', $todayEnd)
  91. ->order('id', 'ASC')
  92. ->column('id');
  93. $total = count($allIds);
  94. $output->writeln("共 {$total} 条");
  95. if ($total === 0) {
  96. $output->writeln("{$date} 没有需要入库的商品");
  97. $output->writeln('========================================');
  98. $output->writeln(' 1688今日商品自动入库 结束 (无商品)');
  99. $output->writeln('========================================');
  100. return;
  101. }
  102. // 3. 应用 skip 跳过已处理的
  103. if ($skip > 0) {
  104. $allIds = array_slice($allIds, $skip);
  105. $output->writeln("跳过前 {$skip} 条,剩余 " . count($allIds) . " 条");
  106. }
  107. // 4. 分批处理
  108. /** @var ProductService $productService */
  109. $productService = app()->make(ProductService::class);
  110. $chunks = array_chunk($allIds, $batch);
  111. $totalChunks = count($chunks);
  112. $output->writeln("共分 {$totalChunks} 批执行");
  113. $output->writeln('');
  114. $globalSuccess = 0;
  115. $globalFail = 0;
  116. $globalProfitSet = 0;
  117. $startTime = time();
  118. foreach ($chunks as $chunkIndex => $idBatch) {
  119. $batchStartTime = time();
  120. $batchNum = $chunkIndex + 1;
  121. $processedCount = $skip + ($chunkIndex * $batch) + 1;
  122. $output->writeln("--- 第 {$batchNum}/{$totalChunks} 批 (已处理 {$processedCount}/{$total}) ---");
  123. foreach ($idBatch as $importId) {
  124. $output->write(" [{$processedCount}/{$total}] import_goods_id={$importId} ... ");
  125. try {
  126. // 4a. 调用原始入库方法
  127. $result = $productService->importToStoreProduct($importId, $merId);
  128. if ($result['code'] === 200) {
  129. $productId = $result['product_id'];
  130. $globalSuccess++;
  131. // 4b. 根据SKU售价阶梯计算原价(ot_price)
  132. try {
  133. // 获取所有SKU的售价(用 unique 字段唯一标识每个SKU)
  134. $skuValues = Db::name('store_product_attr_value')
  135. ->where('product_id', $productId)
  136. ->field('unique, price')
  137. ->select()
  138. ->toArray();
  139. $skuPrices = [];
  140. $skuOtPrices = [];
  141. foreach ($skuValues as $sku) {
  142. $salePrice = (float)$sku['price'];
  143. $skuPrices[] = $salePrice;
  144. // 根据售价区间计算原价
  145. $otPrice = self::calcOtPrice($salePrice);
  146. $skuOtPrices[] = $otPrice;
  147. // 通过 unique 字段更新当前SKU的 ot_price
  148. Db::name('store_product_attr_value')
  149. ->where('unique', $sku['unique'])
  150. ->update(['ot_price' => $otPrice]);
  151. }
  152. // 更新 store_product 表的 price(最低售价)和 ot_price(最高原价)
  153. $minPrice = !empty($skuPrices) ? min($skuPrices) : 0;
  154. $maxOtPrice = !empty($skuOtPrices) ? max($skuOtPrices) : 0;
  155. Db::name('store_product')
  156. ->where('product_id', $productId)
  157. ->update([
  158. 'price' => $minPrice,
  159. 'ot_price' => $maxOtPrice,
  160. ]);
  161. $output->write("<info>[原价已计算]</info> ");
  162. } catch (\Throwable $priceE) {
  163. $output->write("<comment>[原价计算失败: {$priceE->getMessage()}]</comment> ");
  164. }
  165. // 4c. 设置分润(写死15%)
  166. try {
  167. // 获取商品最低售价
  168. $storeProduct = Db::name('store_product')
  169. ->where('product_id', $productId)
  170. ->field('price')
  171. ->find();
  172. $salePrice = $storeProduct ? (float)$storeProduct['price'] : 0;
  173. // 计算 concession_pri = 售价 × 15%,使用 bc 函数保留两位小数
  174. $concessionPri = '0.00';
  175. if ($salePrice > 0) {
  176. $concessionPri = bcmul((string)$salePrice, (string)$profitConfig['concession_rate'], 2);
  177. }
  178. // 更新 store_product 表的分润字段(commission保持原样不修改)
  179. Db::name('store_product')
  180. ->where('product_id', $productId)
  181. ->update([
  182. 'extension_type' => $profitConfig['extension_type'],
  183. 'concession_pri' => $concessionPri,
  184. ]);
  185. // 更新 store_product_attr_value 表的 SKU 分润比例
  186. Db::name('store_product_attr_value')
  187. ->where('product_id', $productId)
  188. ->update([
  189. 'extension_one' => $profitConfig['extension_one'],
  190. ]);
  191. $globalProfitSet++;
  192. $output->write("<info>[分润15%已设置]</info> ");
  193. } catch (\Throwable $profitE) {
  194. $output->write("<comment>[分润设置失败: {$profitE->getMessage()}]</comment> ");
  195. }
  196. $output->writeln("<info>成功 => product_id={$productId}</info>");
  197. } else {
  198. $globalFail++;
  199. $output->writeln("<comment>跳过: {$result['msg']}</comment>");
  200. }
  201. } catch (\Throwable $e) {
  202. $globalFail++;
  203. $output->writeln("<error>异常: {$e->getMessage()}</error>");
  204. }
  205. $processedCount++;
  206. }
  207. // 每批结束后输出当前进度和耗时
  208. $batchElapsed = time() - $batchStartTime;
  209. $totalElapsed = time() - $startTime;
  210. $output->writeln(" 本批耗时: {$batchElapsed}s | 累计耗时: {$totalElapsed}s | 累计成功: {$globalSuccess} | 累计失败: {$globalFail} | 分润设置: {$globalProfitSet}");
  211. $output->writeln('');
  212. // 每批之间短暂休眠,避免数据库压力过大
  213. if ($chunkIndex < $totalChunks - 1) {
  214. $output->writeln(" 等待 1 秒后继续下一批...");
  215. sleep(1);
  216. }
  217. }
  218. // 5. 输出汇总结果
  219. $totalElapsed = time() - $startTime;
  220. $output->writeln('');
  221. $output->writeln('========================================');
  222. $output->writeln(' 入库完成');
  223. $output->writeln('========================================');
  224. $output->writeln("总耗时: {$totalElapsed}s");
  225. $output->writeln("总处理: {$total} 条");
  226. $output->writeln("成功: {$globalSuccess} 条");
  227. $output->writeln("失败: {$globalFail} 条");
  228. $output->writeln("已设置分润15%: {$globalProfitSet} 条");
  229. if ($globalFail > 0) {
  230. $output->writeln('');
  231. $output->writeln('<comment>提示: 失败的商品可以查看 alibaba 日志通道获取详细信息</comment>');
  232. $output->writeln("<comment> 重跑时可加 --skip={$skip} 跳过已处理的商品</comment>");
  233. }
  234. $output->writeln('========================================');
  235. $output->writeln(' 1688今日商品自动入库 结束');
  236. $output->writeln('========================================');
  237. }
  238. /**
  239. * 根据售价计算原价(阶梯加价)
  240. *
  241. * @param float $salePrice SKU售价
  242. * @return float 计算后的原价
  243. */
  244. protected static function calcOtPrice(float $salePrice): float
  245. {
  246. if ($salePrice <= 0) {
  247. return 0;
  248. }
  249. if ($salePrice >= 1 && $salePrice <= 20) {
  250. return $salePrice + 5;
  251. } elseif ($salePrice >= 21 && $salePrice <= 50) {
  252. return $salePrice + 20;
  253. } elseif ($salePrice >= 51 && $salePrice <= 120) {
  254. return $salePrice + 40;
  255. } elseif ($salePrice >= 121 && $salePrice <= 200) {
  256. return $salePrice + 45;
  257. } else {
  258. // 201元以上(含201-300及超过300),统一加50元
  259. return $salePrice + 50;
  260. }
  261. }
  262. }