AlibabaTodayImport.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. namespace app\command;
  3. use app\common\repositories\store\product\ProductRepository;
  4. use app\services\ThirdParty\AlibabaAgent\ProductService;
  5. use think\console\Command;
  6. use think\console\Input;
  7. use think\console\Output;
  8. use think\facade\Db;
  9. /**
  10. * 今日1688商品自动入库命令
  11. *
  12. * 从 alibaba_import_goods 表中获取今日创建的商品,
  13. * 调用 ProductService::importToStoreProduct() 进行正式入库到 store_product 表,
  14. * 然后通过 ProductRepository::update() 更新原价和分润设置
  15. *
  16. * 用法:
  17. * php think alibaba:today-import # 默认今天,mer_id=3447
  18. * php think alibaba:today-import --mer_id=3447 # 指定商户ID
  19. * php think alibaba:today-import --date=2026-05-21 # 指定日期
  20. * php think alibaba:today-import --mer_id=3447 --date=2026-05-21 # 指定商户+日期
  21. * php think alibaba:today-import --batch=100 # 每批处理100条(默认50)
  22. * php think alibaba:today-import --skip=10 # 跳过前10条(断点续传)
  23. *
  24. * 定时任务配置(每天23:55执行):
  25. * 55 23 * * * php /www/wwwroot/shop/think alibaba:today-import --mer_id=3447 >> /tmp/alibaba_today_import.log 2>&1
  26. *
  27. * 分润设置(写死):
  28. * - extension_type: 1(开启分润)
  29. * - concession_pri: 售价 × 15%(商家让利金额)
  30. * - extension_one: 15(SKU级分润比例)
  31. * - commission: 保持原样(不修改)
  32. *
  33. * 原价计算规则(根据SKU售价阶梯加价):
  34. * 1-20元 => 固定加5元
  35. * 21-50元 => 固定加20元
  36. * 51-120元 => 固定加40元
  37. * 121-200元 => 固定加45元
  38. * 201元以上 => 固定加50元
  39. */
  40. class AlibabaTodayImport extends Command
  41. {
  42. protected function configure()
  43. {
  44. $this->setName('alibaba:today-import')
  45. ->setDescription('从alibaba_import_goods获取今日创建的商品,调用importStore接口正式入库')
  46. ->addOption('mer_id', null, \think\console\input\Option::VALUE_OPTIONAL, '商户ID', '3447')
  47. ->addOption('date', null, \think\console\input\Option::VALUE_OPTIONAL, '指定日期 (Y-m-d),默认今天', '')
  48. ->addOption('batch', null, \think\console\input\Option::VALUE_OPTIONAL, '每批处理数量', '50')
  49. ->addOption('skip', null, \think\console\input\Option::VALUE_OPTIONAL, '跳过前N条(断点续传)', '0');
  50. }
  51. protected function execute(Input $input, Output $output)
  52. {
  53. // 解除时间限制
  54. set_time_limit(0);
  55. $output->writeln('========================================');
  56. $output->writeln(' 1688今日商品自动入库 开始');
  57. $output->writeln('========================================');
  58. // 1. 解析参数
  59. $merId = (int)$input->getOption('mer_id');
  60. $date = $input->getOption('date');
  61. $batch = (int)$input->getOption('batch');
  62. $skip = (int)$input->getOption('skip');
  63. if ($batch < 1) $batch = 50;
  64. if ($skip < 0) $skip = 0;
  65. if (empty($date)) {
  66. $date = date('Y-m-d');
  67. }
  68. // ============================================================
  69. // 分润配置(写死)
  70. // ============================================================
  71. $profitConfig = [
  72. 'extension_type' => 1, // 1=开启分润
  73. 'concession_rate' => 0.15, // 商家让利比例15%(concession_pri = 售价 × 15%)
  74. 'extension_one' => 15, // SKU级分润比例15%
  75. ];
  76. $output->writeln("商户ID: {$merId}");
  77. $output->writeln("查询日期: {$date}");
  78. $output->writeln("每批数量: {$batch}");
  79. $output->writeln("跳过前N条: {$skip}");
  80. $output->writeln('分润设置:');
  81. $output->writeln(" extension_type: {$profitConfig['extension_type']} (开启分润)");
  82. $output->writeln(" concession_rate: {$profitConfig['concession_rate']} (售价×{$profitConfig['concession_rate']})");
  83. $output->writeln(" extension_one: {$profitConfig['extension_one']}%");
  84. // 2. 查询今日创建的 alibaba_import_goods 记录(只查ID,不查全字段,节省内存)
  85. $todayStart = $date . ' 00:00:00';
  86. $todayEnd = $date . ' 23:59:59';
  87. $output->write('正在查询今日待入库商品... ');
  88. $allIds = Db::name('alibaba_import_goods')
  89. ->where('status', 1)
  90. ->where('create_time', '>=', $todayStart)
  91. ->where('create_time', '<=', $todayEnd)
  92. ->order('id', 'ASC')
  93. ->column('id');
  94. $total = count($allIds);
  95. $output->writeln("共 {$total} 条");
  96. if ($total === 0) {
  97. $output->writeln("{$date} 没有需要入库的商品");
  98. $output->writeln('========================================');
  99. $output->writeln(' 1688今日商品自动入库 结束 (无商品)');
  100. $output->writeln('========================================');
  101. return;
  102. }
  103. // 3. 应用 skip 跳过已处理的
  104. if ($skip > 0) {
  105. $allIds = array_slice($allIds, $skip);
  106. $output->writeln("跳过前 {$skip} 条,剩余 " . count($allIds) . " 条");
  107. }
  108. // 4. 分批处理
  109. /** @var ProductService $productService */
  110. $productService = app()->make(ProductService::class);
  111. $chunks = array_chunk($allIds, $batch);
  112. $totalChunks = count($chunks);
  113. $output->writeln("共分 {$totalChunks} 批执行");
  114. $output->writeln('');
  115. $globalSuccess = 0;
  116. $globalFail = 0;
  117. $globalProfitSet = 0;
  118. $startTime = time();
  119. foreach ($chunks as $chunkIndex => $idBatch) {
  120. $batchStartTime = time();
  121. $batchNum = $chunkIndex + 1;
  122. $processedCount = $skip + ($chunkIndex * $batch) + 1;
  123. $output->writeln("--- 第 {$batchNum}/{$totalChunks} 批 (已处理 {$processedCount}/{$total}) ---");
  124. foreach ($idBatch as $importId) {
  125. $output->write(" [{$processedCount}/{$total}] import_goods_id={$importId} ... ");
  126. try {
  127. // 4a. 调用原始入库方法
  128. $result = $productService->importToStoreProduct($importId, $merId);
  129. if ($result['code'] === 200) {
  130. $productId = $result['product_id'];
  131. $globalSuccess++;
  132. // 4b. 组装数据,调用 ProductRepository::update() 更新原价和分润
  133. try {
  134. self::updateProductData($productId, $merId, $profitConfig);
  135. $globalProfitSet++;
  136. $output->write("<info>[原价+分润已更新]</info> ");
  137. } catch (\Throwable $updateE) {
  138. $output->write("<comment>[更新失败: {$updateE->getMessage()}]</comment> ");
  139. }
  140. $output->writeln("<info>成功 => product_id={$productId}</info>");
  141. } else {
  142. $globalFail++;
  143. $output->writeln("<comment>跳过: {$result['msg']}</comment>");
  144. }
  145. } catch (\Throwable $e) {
  146. $globalFail++;
  147. $output->writeln("<error>异常: {$e->getMessage()}</error>");
  148. }
  149. $processedCount++;
  150. }
  151. // 每批结束后输出当前进度和耗时
  152. $batchElapsed = time() - $batchStartTime;
  153. $totalElapsed = time() - $startTime;
  154. $output->writeln(" 本批耗时: {$batchElapsed}s | 累计耗时: {$totalElapsed}s | 累计成功: {$globalSuccess} | 累计失败: {$globalFail} | 更新: {$globalProfitSet}");
  155. $output->writeln('');
  156. // 每批之间短暂休眠,避免数据库压力过大
  157. if ($chunkIndex < $totalChunks - 1) {
  158. $output->writeln(" 等待 1 秒后继续下一批...");
  159. sleep(1);
  160. }
  161. }
  162. // 5. 输出汇总结果
  163. $totalElapsed = time() - $startTime;
  164. $output->writeln('');
  165. $output->writeln('========================================');
  166. $output->writeln(' 入库完成');
  167. $output->writeln('========================================');
  168. $output->writeln("总耗时: {$totalElapsed}s");
  169. $output->writeln("总处理: {$total} 条");
  170. $output->writeln("成功: {$globalSuccess} 条");
  171. $output->writeln("失败: {$globalFail} 条");
  172. $output->writeln("已更新原价+分润: {$globalProfitSet} 条");
  173. if ($globalFail > 0) {
  174. $output->writeln('');
  175. $output->writeln('<comment>提示: 失败的商品可以查看 alibaba 日志通道获取详细信息</comment>');
  176. $output->writeln("<comment> 重跑时可加 --skip={$skip} 跳过已处理的商品</comment>");
  177. }
  178. $output->writeln('========================================');
  179. $output->writeln(' 1688今日商品自动入库 结束');
  180. $output->writeln('========================================');
  181. }
  182. /**
  183. * 组装数据并调用 ProductRepository::update() 更新商品
  184. *
  185. * 从数据库查询商品完整信息,组装成 update 接口所需的格式,
  186. * 修改 ot_price(按阶梯计算)和 extension_one(15),
  187. * 然后调用 ProductRepository::update() 执行更新。
  188. *
  189. * @param int $productId
  190. * @param int $merId
  191. * @param array $profitConfig
  192. * @throws \Throwable
  193. */
  194. protected static function updateProductData(int $productId, int $merId, array $profitConfig): void
  195. {
  196. // 1. 查询 store_product 表获取商品基本信息
  197. $product = Db::name('store_product')
  198. ->where('product_id', $productId)
  199. ->find();
  200. if (!$product) {
  201. throw new \RuntimeException("商品不存在 product_id={$productId}");
  202. }
  203. // 2. 查询 store_product_attr_value 表获取所有SKU
  204. $skuValues = Db::name('store_product_attr_value')
  205. ->where('product_id', $productId)
  206. ->select()
  207. ->toArray();
  208. if (empty($skuValues)) {
  209. throw new \RuntimeException("商品SKU数据为空 product_id={$productId}");
  210. }
  211. // 3. 查询 store_product_attr 表获取规格属性
  212. $attrList = Db::name('store_product_attr')
  213. ->where('product_id', $productId)
  214. ->select()
  215. ->toArray();
  216. // 4. 查询 store_product_content 表获取商品详情
  217. $content = Db::name('store_product_content')
  218. ->where('product_id', $productId)
  219. ->value('content');
  220. // 5. 组装 attrValue 数据(参考 detail 接口返回格式)
  221. $attrValue = [];
  222. $skuPrices = [];
  223. foreach ($skuValues as $sku) {
  224. $salePrice = (float)$sku['price'];
  225. $skuPrices[] = $salePrice;
  226. // 根据售价区间计算原价
  227. $otPrice = self::calcOtPrice($salePrice);
  228. // detail 字段(规格明细)
  229. $detail = [];
  230. if (!empty($sku['detail'])) {
  231. $detail = is_string($sku['detail']) ? json_decode($sku['detail'], true) : $sku['detail'];
  232. }
  233. $attrValue[] = [
  234. 'product_id' => $productId,
  235. 'detail' => $detail,
  236. 'sku' => $sku['sku'] ?? '',
  237. 'stock' => $sku['stock'] ?? 0,
  238. 'sales' => $sku['sales'] ?? 0,
  239. 'image' => $sku['image'] ?? '',
  240. 'bar_code' => $sku['bar_code'] ?? '',
  241. 'cost' => (string)($sku['cost'] ?? 0),
  242. 'ot_price' => (string)$otPrice,
  243. 'price' => (string)($sku['price'] ?? 0),
  244. 'volume' => (string)($sku['volume'] ?? 0),
  245. 'weight' => (string)($sku['weight'] ?? 0),
  246. 'type' => $sku['type'] ?? 0,
  247. 'extension_one' => (string)$profitConfig['extension_one'],
  248. 'extension_two' => $sku['extension_two'] ?? null,
  249. 'unique' => $sku['unique'] ?? '',
  250. 'dacang_price' => (string)($sku['dacang_price'] ?? 0),
  251. 'cost_price' => $sku['cost_price'] ?? null,
  252. 'gong_sku_id' => $sku['gong_sku_id'] ?? null,
  253. 'gong_mer_profit' => (string)($sku['gong_mer_profit'] ?? 0),
  254. 'gong_pension' => $sku['gong_pension'] ?? null,
  255. 'gong_market_price'=> (string)($sku['gong_market_price'] ?? 0),
  256. 'plate_mer_profit' => (string)($sku['plate_mer_profit'] ?? 0),
  257. 'pension_num' => (string)($sku['pension_num'] ?? 0),
  258. 'share_num' => (string)($sku['share_num'] ?? 0),
  259. 'stock_num' => (string)($sku['stock_num'] ?? 0),
  260. 'shares_num' => (string)($sku['shares_num'] ?? 0),
  261. 'is_usable' => $sku['is_usable'] ?? 0,
  262. 'sku_id' => $sku['sku_id'] ?? '',
  263. 'spec_id' => $sku['spec_id'] ?? '',
  264. 'value0' => $sku['value0'] ?? ($sku['sku'] ?? ''),
  265. 'dacang_cost_price'=> (string)($sku['dacang_cost_price'] ?? 0),
  266. 'no_dacang_cost_price'=> (string)($sku['no_dacang_cost_price'] ?? 0),
  267. ];
  268. }
  269. // 6. 组装 attr 数据(规格属性)
  270. $attr = [];
  271. foreach ($attrList as $attrItem) {
  272. $detail = !empty($attrItem['attr_values'])
  273. ? explode('-!-', $attrItem['attr_values'])
  274. : [];
  275. $attr[] = [
  276. 'value' => $attrItem['attr_name'],
  277. 'detail' => $detail,
  278. ];
  279. }
  280. // 7. 计算商品级价格
  281. $minPrice = !empty($skuPrices) ? min($skuPrices) : 0;
  282. $maxOtPrice = self::calcOtPrice($minPrice);
  283. // 取所有SKU中最大的ot_price
  284. foreach ($skuPrices as $p) {
  285. $ot = self::calcOtPrice($p);
  286. if ($ot > $maxOtPrice) {
  287. $maxOtPrice = $ot;
  288. }
  289. }
  290. // 8. 组装完整数据(参考 detail 接口返回 + update 接口所需字段)
  291. $sliderImages = !empty($product['slider_image'])
  292. ? (is_string($product['slider_image']) ? explode(',', $product['slider_image']) : $product['slider_image'])
  293. : [];
  294. $updateData = [
  295. 'volunteer' => $product['volunteer'] ?? 0,
  296. 'image' => $product['image'] ?? '',
  297. 'slider_image' => $sliderImages,
  298. 'store_name' => $product['store_name'] ?? '',
  299. 'store_info' => $product['store_info'] ?? '',
  300. 'keyword' => $product['keyword'] ?? '',
  301. 'brand_id' => $product['brand_id'] ?? null,
  302. 'cate_id' => $product['cate_id'] ?? 0,
  303. 'mer_cate_id' => [], // 商户分类,保持空数组
  304. 'unit_name' => $product['unit_name'] ?? '件',
  305. 'sort' => $product['sort'] ?? 0,
  306. 'is_good' => $product['is_good'] ?? 0,
  307. 'temp_id' => $product['temp_id'] ?? 0,
  308. 'attr' => $attr,
  309. 'content' => $content ?? '',
  310. 'spec_type' => $product['spec_type'] ?? 1,
  311. 'extension_type' => $profitConfig['extension_type'],
  312. 'give_coupon_ids' => [],
  313. 'is_gift_bag' => $product['is_gift_bag'] ?? 0,
  314. 'type' => $product['type'] ?? 1,
  315. 'commission' => $product['commission'] ?? '',
  316. 'pension' => (string)($product['pension'] ?? '0.00'),
  317. 'pension_is' => $product['pension_is'] ?? 0,
  318. 'share_is' => $product['share_is'] ?? 0,
  319. 'ficti' => $product['ficti'] ?? 0,
  320. 'icon_type' => !empty($product['icon_type'])
  321. ? (is_string($product['icon_type']) ? json_decode($product['icon_type'], true) : $product['icon_type'])
  322. : [],
  323. 'attrValue' => $attrValue,
  324. ];
  325. // 9. 调用 ProductRepository::update() 执行更新
  326. /** @var ProductRepository $productRepository */
  327. $productRepository = app()->make(ProductRepository::class);
  328. $productRepository->update($productId, $updateData, $merId);
  329. }
  330. /**
  331. * 根据售价计算原价(阶梯加价)
  332. *
  333. * @param float $salePrice SKU售价
  334. * @return float 计算后的原价
  335. */
  336. protected static function calcOtPrice(float $salePrice): float
  337. {
  338. if ($salePrice <= 0) {
  339. return 0;
  340. }
  341. if ($salePrice >= 1 && $salePrice <= 20) {
  342. return $salePrice + 5;
  343. } elseif ($salePrice >= 21 && $salePrice <= 50) {
  344. return $salePrice + 20;
  345. } elseif ($salePrice >= 51 && $salePrice <= 120) {
  346. return $salePrice + 40;
  347. } elseif ($salePrice >= 121 && $salePrice <= 200) {
  348. return $salePrice + 45;
  349. } else {
  350. // 201元以上(含201-300及超过300),统一加50元
  351. return $salePrice + 50;
  352. }
  353. }
  354. }