diff --git a/database/migrations/2026_11_09_190000_create_shengsuan_order_profit_detail_snapshots.php b/database/migrations/2026_11_09_190000_create_shengsuan_order_profit_detail_snapshots.php new file mode 100644 index 00000000..a428fd1a --- /dev/null +++ b/database/migrations/2026_11_09_190000_create_shengsuan_order_profit_detail_snapshots.php @@ -0,0 +1,53 @@ +hasTable(self::TABLE)) { + return; + } + + $schema->create(self::TABLE, function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('order_key', 191)->unique('shengsuan_detail_order_key_unique'); + $table->string('shop_name', 191)->default(''); + $table->string('online_order_no', 64)->nullable(); + $table->string('internal_order_no', 32)->nullable(); + $table->unsignedInteger('item_count')->default(0); + $table->unsignedInteger('after_item_count')->default(0); + $table->unsignedInteger('missing_cost_item_count')->default(0); + $table->longText('order_headers')->nullable(); + $table->longText('order_items')->nullable(); + $table->longText('after_headers')->nullable(); + $table->longText('after_items')->nullable(); + $table->longText('missing_cost_barcodes')->nullable(); + $table->dateTime('synced_at')->nullable(); + $table->timestamps(); + + $table->index(['shop_name', 'synced_at'], 'shengsuan_detail_shop_synced'); + $table->index(['online_order_no', 'synced_at'], 'shengsuan_detail_online_synced'); + }); + } + + public function down(): void + { + if (config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror')) + ->dropIfExists(self::TABLE); + } +}; diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 6c8f360b..9da9c8fe 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -42,7 +42,7 @@ | 待有效凭据后首次同步 | 普通商品当前成本价、商品类型和更新时间继续读取 `operations_replica.rpt.jst_sku`;`rpt.fys_skuCostPriceUpdate` 是一 SKU 一行的旧快照,不能充当变价历史。完整成本价变更仍读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;经典接口必须在服务器私有配置中使用同一应用的 `JUSHUITAN_PARTNER_ID / JUSHUITAN_PARTNER_KEY / JUSHUITAN_TOKEN`,不得把新开放平台的 App Key / App Secret / Access Token 混用。页面在首次同步完成前明确显示待同步或失败,不把 0 条解释为真实无历史。 | | 本次接入 | 流程明细读取 `operations_replica/rpt.ding_Workflow + rpt.ding_WorkflowScheme` 的结构化审批主表、费用明细和付款明细,写入 `ding_process_detail_mirror`、`ding_process_payment_mirror` 与付款按明细行分摊的 `ding_process_payment_line_mirror`;主表的 `originatorDeptName` 作为发起人部门单独保留,费用明细行的“店铺”字段规范化写入 `store_name`。禁止先把明细表和付款表铺平成 CSV 后逐行求和;付款明细必须按“对应序号”关联到代表明细行,但合计始终读取独立付款事实。管理费用按分摊后的付款月份统计,跨月分笔付款不会把整张审批重复计入多月。每个纳入范围的源审批至少保留一条页面记录,没有费用金额的审批以空金额显示,不静默隐藏。首次全量先运行 `business-mirror:sync-ding-process-details --full --dry-run` 校验,再使用 `business-mirror:sync-ding-process-details --full` 发布;日常通过 `updateAt/createAt` 48 小时重叠增量同步。当前纳入日常报销、应付、线上代发、种菜、快递面单、固定资产、日常物品、样品、一次性采买、板材、工资、外贸费用和种菜充值等 14 个财务流程;发现新的明细流程编码时全量同步报错并保留上一版。 | | 本次接入 | 财务经营报表 › 管理费用使用 `oa_process_account_mapping` 保存流程科目映射;当前快照包含原工作簿 191 个科目和补充的 `5601.11.01 货代费`、`1221.07 种菜备用金`、`5602.11.03.19 AI阿里云软件费`,共 194 个科目,其中 37 个进费比科目和 126 个分摊规则。页面按打款时间提供整月选择并默认展示上个月 OA 流程中审批状态为“已完成”、涉及付款且出纳已打款的明细,不涉及付款或出纳未打款的数据不进入汇总,按费用大类和二级汇总进费比/不进费比/未映射金额,点击二级查看三级汇总与 9 列明细模板。审批完成时间写入 `ding_process_detail_mirror.approval_finished_at`,页面月份筛选使用 `ding_process_detail_mirror.paid_at`;钉钉副本把费用明细表保存为未命名字段时,按配置中的金额列识别包含该列的未命名表格组件,避免只抓到付款明细而漏掉费用科目和金额。明细行没有科目时,使用同一审批表单表头的 `科目编码 / 科目名称` 回填;行级科目始终优先。 | -| 本次接入 | 订单利润的包材费、快递费、账单费用直接读取聚胜算订单利润页面接口 `pf.erp321.com/WebApi/PF/OrderSku/GetOrderSkuList`(支付/发货时间口径各分页抓取),导入 `ops_shengsuan_order_profit_rows`,页面按“店铺 + 线上/内部单号”原样回填,不把 0 或推算值写入缺口。抓取脚本为 `scripts/order-profit-shengsuan-sync.py`,导入命令为 `order-profit:import-shengsuan-rows`;脚本依赖本机已登录胜算的 Chrome 调试窗口,不能由服务器容器直连页面。`成本/运费异常`按该表“商品成本或快递费任一为0/空”筛选,分别标记“成本异常”“运费异常”,以发货时间为监控日期。 | +| 本次接入 | 订单利润的包材费、快递费、账单费用直接读取聚胜算订单利润页面接口 `pf.erp321.com/WebApi/PF/OrderSku/GetOrderSkuList`(支付/发货时间口径各分页抓取),导入 `ops_shengsuan_order_profit_rows`,页面按“店铺 + 线上/内部单号”原样回填,不把 0 或推算值写入缺口。异常订单再通过 `GetPfOrderDetList` 按每批最多 50 单抓取完整订单商品明细,保存至 `ops_shengsuan_order_profit_detail_snapshots`,包括全部订单字段、销售商品明细、退货商品明细和缺成本商品编码。主表抓取脚本为 `scripts/order-profit-shengsuan-sync.py`,明细补同步脚本为 `scripts/order-profit-shengsuan-details-sync.py`;导入命令分别为 `order-profit:import-shengsuan-rows`、`order-profit:import-shengsuan-details`。脚本依赖本机已登录胜算的 Chrome 调试窗口,不能由服务器容器直连页面。`成本/运费异常`按主表“商品成本或快递费任一为0/空”筛选,分别标记“成本异常”“运费异常”,并在订单下按具体商品编码展示缺成本条码,以发货时间为监控日期。 | 流程明细另设独立定时任务,避免与每分钟科目映射消费争用同一上游目录时被静默跳过。正式发布脚本会覆盖安装 `/etc/cron.d/caiwu-ding-process-details`:每 5 分钟尝试运行 `business-mirror:sync-ding-process-details`,页面定向刷新和一周一次的全量校准与增量同步共用 `/run/caiwu-oa-process.lock`,只在这些 OA 镜像任务之间排队,不再被店铺对账、商品同步等无关任务占用的全局上游锁阻塞;`scripts/install-ding-process-sync-cron.ps1` 仅作为手工修复入口。任务时间和镜像状态统一使用平台固定时区,审批等待时长按实际小时展示。OA 页面每小时最多把一次当前页“审批中”的审批编号写入定向刷新队列,由每分钟检查一次的批处理命令消费;其他时间直接展示最近镜像,已完成流程不进入即时刷新链路,仍由常规增量和每周全量校准处理付款等后续变化。进行中审批的钉钉接口按配置并发读取(默认 5 个、上限 10 个),单个审批失败不会丢弃同批成功结果。增量同步除跟进审批主表更新时间外,还以 `ding_WorkflowScheme` 的数字 `id` 高水位发现后补表单行,避免付款明细等新组件写入后主审批 `updateAt` 不变而被漏掉;原地改写同一组件仍由每周全量校准兜底。付款状态只按钉钉“出纳打款”节点判断,分为“出纳状态待同步 / 出纳未开始 / 出纳待打款 / 出纳退回 / 出纳已打款 / 流程终止 / 不涉及付款”。金额差异不参与付款状态判断,另以“付款差额 = 费用合计 − 已付款合计”展示。不能因为金额存在少量差异就覆盖出纳节点事实,也不能因为出纳已通过就隐藏金额差异。 diff --git a/modules/EcommerceFinance/Console/ExportShengsuanAnomalyOrders.php b/modules/EcommerceFinance/Console/ExportShengsuanAnomalyOrders.php new file mode 100644 index 00000000..9ec33440 --- /dev/null +++ b/modules/EcommerceFinance/Console/ExportShengsuanAnomalyOrders.php @@ -0,0 +1,39 @@ +option('from')) ?: now()->subDays(6)->toDateString(); + $to = trim((string) $this->option('to')) ?: now()->toDateString(); + $limit = max((int) $this->option('limit'), 0); + $orders = $repository->references([ + 'from' => $from, + 'to' => $to, + 'shop_names' => [], + 'order_no' => '', + ], (bool) $this->option('missing-details'), $limit); + + $this->line(json_encode([ + 'from' => $from, + 'to' => $to, + 'count' => count($orders), + 'orders' => $orders, + ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + + return self::SUCCESS; + } +} diff --git a/modules/EcommerceFinance/Console/ImportShengsuanOrderProfitDetails.php b/modules/EcommerceFinance/Console/ImportShengsuanOrderProfitDetails.php new file mode 100644 index 00000000..0091882a --- /dev/null +++ b/modules/EcommerceFinance/Console/ImportShengsuanOrderProfitDetails.php @@ -0,0 +1,71 @@ +option('file')); + $raw = $this->option('stdin') + ? stream_get_contents(STDIN) + : (($path !== '' && is_file($path)) ? file_get_contents($path) : ''); + if (! is_string($raw) || trim($raw) === '') { + $this->error('未读取到聚胜算订单明细 JSON。'); + + return self::FAILURE; + } + + try { + $decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + $this->error('聚胜算订单明细 JSON 无法解析。'); + + return self::FAILURE; + } + + $snapshots = $mapper->snapshots(is_array($decoded) ? $decoded : []); + if ($snapshots === []) { + $this->warn('JSON 中没有可导入的订单商品明细。'); + + return self::FAILURE; + } + + $connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + foreach (array_chunk($snapshots, 50) as $chunk) { + $connection->transaction(static function () use ($connection, $mapper, $chunk): void { + $connection->table($mapper->table())->upsert( + $chunk, + ['order_key'], + [ + 'shop_name', 'online_order_no', 'internal_order_no', + 'item_count', 'after_item_count', 'missing_cost_item_count', + 'order_headers', 'order_items', 'after_headers', 'after_items', + 'missing_cost_barcodes', 'synced_at', 'updated_at', + ], + ); + }); + } + + $items = array_sum(array_column($snapshots, 'item_count')); + $missing = array_sum(array_column($snapshots, 'missing_cost_item_count')); + $this->info(sprintf( + '聚胜算订单明细导入完成:%d 单、%d 条销售商品,其中缺成本商品 %d 条。', + count($snapshots), + $items, + $missing, + )); + + return self::SUCCESS; + } +} diff --git a/modules/EcommerceFinance/Providers/Main.php b/modules/EcommerceFinance/Providers/Main.php index fcebed69..9108f754 100644 --- a/modules/EcommerceFinance/Providers/Main.php +++ b/modules/EcommerceFinance/Providers/Main.php @@ -3,6 +3,8 @@ namespace Modules\EcommerceFinance\Providers; use Illuminate\Support\ServiceProvider as Provider; +use Modules\EcommerceFinance\Console\ExportShengsuanAnomalyOrders; +use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitDetails; use Modules\EcommerceFinance\Console\ProcessDingRefreshRequests; use Modules\EcommerceFinance\Console\DiagnoseJushuitanPackage; use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitRows; @@ -25,6 +27,8 @@ class Main extends Provider ProcessDingRefreshRequests::class, DiagnoseJushuitanPackage::class, ImportShengsuanOrderProfitRows::class, + ImportShengsuanOrderProfitDetails::class, + ExportShengsuanAnomalyOrders::class, ]); } } diff --git a/modules/EcommerceFinance/Repositories/CostFreightAnomalyRepository.php b/modules/EcommerceFinance/Repositories/CostFreightAnomalyRepository.php index 2cf42840..3fa9a8ae 100644 --- a/modules/EcommerceFinance/Repositories/CostFreightAnomalyRepository.php +++ b/modules/EcommerceFinance/Repositories/CostFreightAnomalyRepository.php @@ -5,12 +5,16 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Database\ConnectionInterface; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Modules\EcommerceFinance\Services\ShengsuanOrderProfitDetailMapper; +use Modules\EcommerceFinance\Services\ShengsuanOrderProfitDisplayMapper; use Modules\EcommerceFinance\Services\ShengsuanOrderProfitRowMapper; class CostFreightAnomalyRepository { private const TABLE = ShengsuanOrderProfitRowMapper::TABLE; + private const DETAIL_TABLE = ShengsuanOrderProfitDetailMapper::TABLE; + public function ready(): bool { try { @@ -27,11 +31,18 @@ class CostFreightAnomalyRepository } } - /** @return array{ready:bool,last_synced_at:?string,total:int,shops:list} */ + /** + * @return array{ + * ready:bool,last_synced_at:?string,total:int,shops:list, + * detail_ready:bool,detail_total:int,detail_last_synced_at:?string + * } + */ public function status(): array { try { $query = $this->connection()->table(self::TABLE); + $detailReady = $this->detailReady(); + $detailQuery = $detailReady ? $this->connection()->table(self::DETAIL_TABLE) : null; return [ 'ready' => $this->ready(), @@ -46,6 +57,9 @@ class CostFreightAnomalyRepository ->filter() ->values() ->all(), + 'detail_ready' => $detailReady, + 'detail_total' => $detailQuery === null ? 0 : (int) (clone $detailQuery)->count(), + 'detail_last_synced_at' => $detailQuery?->max('synced_at'), ]; } catch (\Throwable) { return [ @@ -53,6 +67,9 @@ class CostFreightAnomalyRepository 'last_synced_at' => null, 'total' => 0, 'shops' => [], + 'detail_ready' => false, + 'detail_total' => 0, + 'detail_last_synced_at' => null, ]; } } @@ -69,13 +86,13 @@ class CostFreightAnomalyRepository ->select([ 'shop_name', 'online_order_no', 'internal_order_no', 'order_key', 'ship_time', 'product_cost', 'matched_package_fee', - 'matched_freight_fee', 'matched_bill_fee', 'synced_at', + 'matched_freight_fee', 'matched_bill_fee', 'source_payload', 'synced_at', ]) ->orderByDesc('ship_time') ->orderByDesc('order_key') ->forPage(max($page, 1), min(max($limit, 1), 100)) ->get() - ->map(static function (object $row): array { + ->map(function (object $row): array { $anomalyTypes = self::anomalyTypes($row); return [ @@ -89,11 +106,13 @@ class CostFreightAnomalyRepository 'matched_freight_fee' => $row->matched_freight_fee === null ? null : (float) $row->matched_freight_fee, 'matched_bill_fee' => $row->matched_bill_fee === null ? null : (float) $row->matched_bill_fee, 'synced_at' => $row->synced_at, + 'order_source_payload' => $this->decodeJson($row->source_payload), 'anomaly_types' => $anomalyTypes, 'anomaly_type' => implode('、', $anomalyTypes), ]; }) ->all(); + $this->hydrateDetails($rows); return [ 'rows' => $rows, @@ -102,6 +121,47 @@ class CostFreightAnomalyRepository ]; } + /** + * @param array $filters + * @return list + */ + public function references(array $filters, bool $missingDetails = false, int $limit = 0): array + { + $query = $this->filtered($this->connection()->table(self::TABLE), $filters); + $query->select([ + self::TABLE . '.shop_name', + self::TABLE . '.online_order_no', + self::TABLE . '.internal_order_no', + self::TABLE . '.order_key', + ]); + if ($missingDetails && $this->detailReady()) { + $query->leftJoin( + self::DETAIL_TABLE, + self::DETAIL_TABLE . '.order_key', + '=', + self::TABLE . '.order_key', + )->whereNull(self::DETAIL_TABLE . '.order_key'); + } + $query->orderByDesc(self::TABLE . '.ship_time') + ->orderByDesc(self::TABLE . '.order_key'); + if ($limit > 0) { + $query->limit($limit); + } + + return $query->get()->map(static function (object $row): array { + $online = trim((string) ($row->online_order_no ?? '')); + $internal = trim((string) ($row->internal_order_no ?? '')); + + return [ + 'order_key' => trim((string) ($row->order_key ?? '')), + 'shop_name' => trim((string) ($row->shop_name ?? '')), + 'online_order_no' => $online === '' ? null : $online, + 'internal_order_no' => $internal === '' ? null : $internal, + 'order_no' => $online !== '' ? $online : $internal, + ]; + })->filter(static fn (array $row): bool => $row['order_no'] !== '')->values()->all(); + } + private function filtered(\Illuminate\Database\Query\Builder $query, array $filters): \Illuminate\Database\Query\Builder { $query->where(function ($anomaly) { @@ -159,6 +219,71 @@ class CostFreightAnomalyRepository return $value === null || (float) $value === 0.0; } + /** @param list> $rows */ + private function hydrateDetails(array &$rows): void + { + if ($rows === []) { + return; + } + + $snapshots = collect(); + if ($this->detailReady()) { + $keys = array_values(array_filter(array_map( + static fn (array $row): string => trim((string) ($row['order_key'] ?? '')), + $rows, + ))); + if ($keys !== []) { + $snapshots = $this->connection()->table(self::DETAIL_TABLE) + ->whereIn('order_key', array_slice(array_unique($keys), 0, 100)) + ->get() + ->keyBy('order_key'); + } + } + + foreach ($rows as &$row) { + $row['order_fields'] = ShengsuanOrderProfitDisplayMapper::fields( + (array) ($row['order_source_payload'] ?? []), + ); + $snapshot = $snapshots->get($row['order_key']); + $row['detail_synced_at'] = $snapshot->synced_at ?? null; + $row['detail_item_count'] = (int) ($snapshot->item_count ?? 0); + $row['detail_after_item_count'] = (int) ($snapshot->after_item_count ?? 0); + $row['detail_missing_cost_item_count'] = (int) ($snapshot->missing_cost_item_count ?? 0); + $row['missing_cost_barcodes'] = $this->decodeJson($snapshot->missing_cost_barcodes ?? null); + $row['detail_order_headers'] = $this->decodeJson($snapshot->order_headers ?? null); + $row['detail_order_items'] = $this->decodeJson($snapshot->order_items ?? null); + $row['detail_after_headers'] = $this->decodeJson($snapshot->after_headers ?? null); + $row['detail_after_items'] = $this->decodeJson($snapshot->after_items ?? null); + + $types = array_values(array_filter((array) ($row['anomaly_types'] ?? []))); + if (($row['missing_cost_barcodes'] ?? []) !== [] && ! in_array('成本异常', $types, true)) { + array_unshift($types, '成本异常'); + } + $row['anomaly_types'] = $types; + $row['anomaly_type'] = implode('、', $types); + } + } + + private function detailReady(): bool + { + try { + return Schema::connection($this->connectionName())->hasTable(self::DETAIL_TABLE); + } catch (\Throwable) { + return false; + } + } + + /** @return array */ + private function decodeJson(mixed $value): array + { + if (! is_string($value) || trim($value) === '') { + return []; + } + $decoded = json_decode($value, true); + + return is_array($decoded) ? $decoded : []; + } + /** @return list */ private function batchValues(string $value): array { diff --git a/modules/EcommerceFinance/Services/ShengsuanOrderProfitDetailMapper.php b/modules/EcommerceFinance/Services/ShengsuanOrderProfitDetailMapper.php new file mode 100644 index 00000000..b4cdda3b --- /dev/null +++ b/modules/EcommerceFinance/Services/ShengsuanOrderProfitDetailMapper.php @@ -0,0 +1,145 @@ + $decoded + * @return list> + */ + public function snapshots(array $decoded): array + { + $data = is_array($decoded['data'] ?? null) ? $decoded['data'] : $decoded; + $orders = $this->section($data['ords'] ?? []); + $afterSales = $this->section($data['afters'] ?? []); + $groups = []; + + foreach ([['orders', $orders], ['after_sales', $afterSales]] as [$section, $table]) { + foreach ($table['dataList'] as $record) { + $key = $this->orderKey($record); + if ($key === null) { + continue; + } + $groups[$key] ??= [ + 'order_key' => $key, + 'shop_name' => trim((string) ($record[self::SHOP_FIELD] ?? '')), + 'online_order_no' => $this->nullableText($record[self::ONLINE_ORDER_FIELD] ?? null), + 'internal_order_no' => $this->nullableText($record[self::INTERNAL_ORDER_FIELD] ?? null), + 'orders_headers' => $orders['fldHeads'], + 'orders' => [], + 'afters_headers' => $afterSales['fldHeads'], + 'afters' => [], + ]; + $groups[$key][$section === 'orders' ? 'orders' : 'afters'][] = $record; + } + } + + $now = now(); + $snapshots = []; + foreach ($groups as $group) { + $missingCostBarcodes = []; + $missingCostItemCount = 0; + foreach ($group['orders'] as $item) { + if (! $this->isZeroOrMissing($item[self::PRODUCT_COST_FIELD] ?? null)) { + continue; + } + $missingCostItemCount++; + $barcode = $this->nullableText($item[self::BARCODE_FIELD] ?? null); + if ($barcode !== null && ! in_array($barcode, $missingCostBarcodes, true)) { + $missingCostBarcodes[] = $barcode; + } + } + + $snapshots[] = [ + 'order_key' => $group['order_key'], + 'shop_name' => $group['shop_name'], + 'online_order_no' => $group['online_order_no'], + 'internal_order_no' => $group['internal_order_no'], + 'item_count' => count($group['orders']), + 'after_item_count' => count($group['afters']), + 'missing_cost_item_count' => $missingCostItemCount, + 'order_headers' => $this->json($group['orders_headers']), + 'order_items' => $this->json($group['orders']), + 'after_headers' => $this->json($group['afters_headers']), + 'after_items' => $this->json($group['afters']), + 'missing_cost_barcodes' => $this->json($missingCostBarcodes), + 'synced_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + + return $snapshots; + } + + /** @return array{fldHeads:list>,dataList:list>} */ + private function section(mixed $section): array + { + if (! is_array($section)) { + return ['fldHeads' => [], 'dataList' => []]; + } + + $headers = is_array($section['fldHeads'] ?? null) ? $section['fldHeads'] : []; + + return [ + 'fldHeads' => array_values(array_map( + static fn (array $header): array => [ + 'fld' => (string) ($header['fld'] ?? ''), + 'title' => (string) ($header['title'] ?? ''), + 'align' => $header['align'] ?? null, + 'sum' => (bool) ($header['sum'] ?? false), + ], + array_filter($headers, 'is_array'), + )), + 'dataList' => is_array($section['dataList'] ?? null) + ? array_values(array_filter($section['dataList'], 'is_array')) + : [], + ]; + } + + /** @param array $record */ + private function orderKey(array $record): ?string + { + $shop = trim((string) ($record[self::SHOP_FIELD] ?? '')); + $online = trim((string) ($record[self::ONLINE_ORDER_FIELD] ?? '')); + $internal = trim((string) ($record[self::INTERNAL_ORDER_FIELD] ?? '')); + $orderNo = $online !== '' ? $online : $internal; + + return $shop === '' || $orderNo === '' ? null : $shop . '|' . $orderNo; + } + + private function nullableText(mixed $value): ?string + { + $text = trim((string) $value); + + return $text === '' ? null : $text; + } + + private function isZeroOrMissing(mixed $value): bool + { + return $value === null || trim((string) $value) === '' || (float) $value === 0.0; + } + + private function json(mixed $value): string + { + return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '[]'; + } +} diff --git a/modules/EcommerceFinance/Services/ShengsuanOrderProfitDisplayMapper.php b/modules/EcommerceFinance/Services/ShengsuanOrderProfitDisplayMapper.php new file mode 100644 index 00000000..3218057f --- /dev/null +++ b/modules/EcommerceFinance/Services/ShengsuanOrderProfitDisplayMapper.php @@ -0,0 +1,136 @@ + '店铺名称', + 'c_900902' => '线上单号', + 'c_900903' => '内部单号', + 'c_900972' => '发货时间', + 'c_900966' => '订单类型', + 'c_900933' => '标签', + 'c_900905' => '订单销售数量(扣退)', + 'c_900015' => '订单销售金额(扣退)', + 'c_900208' => '订单销售成本(扣退)', + 'c_900952' => '分类单销售数量(扣退)', + 'c_900014' => '分类单销售金额(扣退)', + 'c_900207' => '分类单销售成本(扣退)', + 'c_900953' => '销售数量(扣退)', + 'c_900099' => '销售金额(扣退)', + 'c_900299' => '销售成本(扣退)', + 'c_900019' => '其中:手动调整收入', + 'c_900008' => '其中:其他调整收入', + 'c_900210' => '其中:手动调整成本', + 'c_900203' => '其中:其他调整成本', + 'c_900301' => '毛利额', + 'c_900302' => '毛利率', + 'c_900499' => '订单费用', + 'c_900498' => '费用占比', + 'c_900497' => '其中:推广费', + 'c_900501' => '经营利润', + 'c_900502' => '经营利润率', + 'c_900940' => '商品数量', + 'c_900001' => '商品金额', + 'c_900201' => '商品成本', + 'c_900209' => '其中:红冲订单成本', + 'c_900007' => '商家优惠', + 'c_900003' => '运费收入', + 'c_900002' => '付款金额', + 'c_900006' => '其中:平台优惠', + 'c_900016' => '其中:红冲订单金额', + 'c_900949' => '实发金额', + 'c_900925' => '实发数量', + 'c_900950' => '实发成本', + 'c_900954' => '退款数量合计', + 'c_900012' => '退款金额合计', + 'c_900018' => '其中:退平台补贴', + 'c_900202' => '退款成本合计', + 'c_900941' => '发货前-申请数量', + 'c_900943' => '发货前-申请金额', + 'c_900942' => '发货前-申请成本', + 'c_900926' => '发货前-退回数量', + 'c_900928' => '发货前-退回金额', + 'c_900929' => '发货前-退回成本', + 'c_900930' => '发货前-退款金额', + 'c_900984' => '发货前-退款类型', + 'c_900944' => '发货前-退平台补贴', + 'c_900945' => '发货后-申请数量', + 'c_900947' => '发货后-申请金额', + 'c_900946' => '发货后-申请成本', + 'c_900927' => '发货后-退回数量', + 'c_900931' => '发货后-退回金额', + 'c_900932' => '发货后-退回成本', + 'c_900935' => '发货后-退款金额', + 'c_900985' => '发货后-退货类型', + 'c_900948' => '发货后-退平台补贴', + 'c_900409' => '包材费(自动匹配)', + 'c_900407' => '快递费(自动匹配)', + 'c_900412' => '账单费用(自动匹配)', + 'c_900413' => '分类单成本生成费用', + 'c_900414' => '商品成本生成费用', + 'c_900415' => '人工维护', + 'c_900951' => '发货仓库', + 'c_9001013' => '运营云仓', + 'c_900989' => '供销商', + 'c_9001015' => '业务员', + 'c_9002022' => '线下客户', + 'c_9002010' => '省', + 'c_9002011' => '市', + 'c_9002014' => '订单卖家备注', + 'c_900967' => '胜算订单号', + 'c_9001062' => '确认收货状态', + 'c_9002013' => '商品总体积(扣退)', + ]; + + /** + * @param array $payload + * @param list> $headers + * @return list + */ + public static function fields(array $payload, array $headers = []): array + { + $titles = self::ORDER_TITLES; + $codes = []; + foreach ($headers as $header) { + $code = trim((string) ($header['fld'] ?? '')); + if ($code === '') { + continue; + } + $titles[$code] = trim((string) ($header['title'] ?? '')) ?: ($titles[$code] ?? $code); + $codes[$code] = true; + } + foreach (array_keys($payload) as $code) { + $codes[(string) $code] = true; + } + + $fields = []; + foreach (array_keys($codes) as $code) { + $fields[] = [ + 'code' => $code, + 'title' => $titles[$code] ?? $code, + 'value' => self::value($payload[$code] ?? null), + ]; + } + + return $fields; + } + + public static function value(mixed $value): string + { + if ($value === null) { + return '-'; + } + if (is_bool($value)) { + return $value ? '是' : '否'; + } + if (is_array($value) || is_object($value)) { + return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '-'; + } + + $text = trim((string) $value); + + return $text === '' ? '-' : $text; + } +} diff --git a/resources/views/business/pages/fee-ratio-monitoring/cost-freight-anomaly.blade.php b/resources/views/business/pages/fee-ratio-monitoring/cost-freight-anomaly.blade.php index 57ab1e19..384dae4d 100644 --- a/resources/views/business/pages/fee-ratio-monitoring/cost-freight-anomaly.blade.php +++ b/resources/views/business/pages/fee-ratio-monitoring/cost-freight-anomaly.blade.php @@ -41,12 +41,127 @@ background: #fdf3e3; color: #8a5d10; } + .cost-freight-barcode-list { + display: flex; + flex-wrap: wrap; + gap: .25rem; + max-width: 22rem; + } + .cost-freight-barcode { + display: inline-flex; + padding: .08rem .38rem; + border: 1px solid #e7c3c3; + border-radius: 4px; + background: #fff5f5; + color: #a32d2d; + font-size: .7rem; + font-weight: 600; + } + .cost-freight-detail-button { + height: 1.8rem; + padding: 0 .55rem; + border: 1px solid var(--vip-border, #d8d2c7); + border-radius: .4rem; + background: #fff; + color: var(--vip-content-accent-dark, #856632); + cursor: pointer; + white-space: nowrap; + } + .cost-freight-detail-button:hover { + border-color: var(--vip-content-accent-dark, #856632); + background: var(--vip-content-accent-soft, #f7f0de); + } + .cost-freight-detail-row > td { + padding: 0 !important; + background: #fbfaf6 !important; + } + .cost-freight-detail-row[hidden] { + display: none; + } + .cost-freight-detail-wrap { + padding: .9rem 1rem 1rem; + } + .cost-freight-detail-section { + margin-top: .85rem; + } + .cost-freight-detail-section:first-child { + margin-top: 0; + } + .cost-freight-detail-title { + margin-bottom: .5rem; + color: var(--vip-content-accent-dark, #856632); + font-size: .82rem; + font-weight: 700; + } + .cost-freight-order-fields { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + border-top: 1px solid var(--vip-border, #d8d2c7); + border-left: 1px solid var(--vip-border, #d8d2c7); + background: #fff; + } + .cost-freight-order-field { + display: grid; + grid-template-columns: minmax(7rem, 38%) minmax(0, 1fr); + min-height: 2.2rem; + border-right: 1px solid var(--vip-border, #d8d2c7); + border-bottom: 1px solid var(--vip-border, #d8d2c7); + font-size: .7rem; + } + .cost-freight-order-field dt { + margin: 0; + padding: .45rem .5rem; + background: var(--vip-content-accent-soft, #f7f0de); + color: var(--vip-content-muted, #595959); + font-weight: 600; + } + .cost-freight-order-field dd { + margin: 0; + padding: .45rem .5rem; + overflow-wrap: anywhere; + white-space: pre-wrap; + } + .cost-freight-item-table { + width: max-content; + min-width: 100%; + border-collapse: collapse; + background: #fff; + } + .cost-freight-item-table th, + .cost-freight-item-table td { + max-width: 18rem; + padding: .42rem .5rem; + border: 1px solid var(--vip-border, #d8d2c7); + font-size: .7rem; + line-height: 1.4; + text-align: left; + vertical-align: top; + white-space: nowrap; + } + .cost-freight-item-table th { + position: sticky; + top: 0; + z-index: 1; + background: var(--vip-content-accent-soft, #f7f0de); + } + .cost-freight-detail-empty { + padding: .7rem .8rem; + border: 1px dashed var(--vip-border, #d8d2c7); + border-radius: .4rem; + background: #fff; + color: var(--vip-content-muted, #595959); + font-size: .75rem; + } + @media (max-width: 1200px) { + .cost-freight-order-fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } + } @php $rows = $costFreightRows ?? null; $filters = $costFreightFilters ?? []; $status = $costFreightStatus ?? []; + $displayValue = static fn (mixed $value): string => \Modules\EcommerceFinance\Services\ShengsuanOrderProfitDisplayMapper::value($value); @endphp
@@ -98,6 +213,12 @@
数据状态:{{ ($status['ready'] ?? false) ? '胜算费用镜像已就绪' : '共享镜像同步中' }} @if (!empty($status['last_synced_at'])) · 最近同步 {{ $status['last_synced_at'] }} @endif + @if (!empty($status['detail_ready'])) + · 商品明细已同步 {{ number_format((int) ($status['detail_total'] ?? 0)) }} 单 + @if (!empty($status['detail_last_synced_at'])) · 最近明细 {{ $status['detail_last_synced_at'] }} @endif + @else + · 商品明细表尚未就绪 + @endif · 当前筛选 {{ number_format((int) ($status['total'] ?? 0)) }} 条
@@ -107,6 +228,7 @@ 店铺名称 线上单号 内部单号 + 缺成本条码 发货时间 商品成本 快递费(自动匹配) @@ -114,14 +236,37 @@ 包材费(自动匹配) 异常类型 同步时间 + 完整订单 @forelse ($rows ?? [] as $row) + @php + $detailId = 'cost-freight-detail-' . $loop->index; + $missingBarcodes = collect($row->missing_cost_barcodes ?? [])->filter()->values(); + $orderFields = collect($row->order_fields ?? []); + $salesHeaders = collect($row->detail_order_headers ?? []); + $salesItems = collect($row->detail_order_items ?? []); + $afterHeaders = collect($row->detail_after_headers ?? []); + $afterItems = collect($row->detail_after_items ?? []); + @endphp {{ $row->shop_name ?: '-' }} {{ $row->online_order_no ?: '-' }} {{ $row->internal_order_no ?: '-' }} + + @if ($missingBarcodes->isNotEmpty()) +
+ @foreach ($missingBarcodes as $barcode) + {{ $barcode }} + @endforeach +
+ @elseif ($row->detail_synced_at) + 未识别到缺成本条码 + @else + 待同步明细 + @endif + {{ $row->ship_time ?: '-' }} {{ $row->product_cost === null ? '-' : number_format((float) $row->product_cost, 2) }} {{ $row->matched_freight_fee === null ? '-' : number_format((float) $row->matched_freight_fee, 2) }} @@ -145,10 +290,111 @@
{{ $row->synced_at ?: '-' }} + + + + + + +
+
+
+ 完整订单数据 · {{ $row->shop_name }} · {{ $row->online_order_no ?: $row->internal_order_no }} +
+ @if ($orderFields->isNotEmpty()) +
+ @foreach ($orderFields as $field) +
+
{{ $field['title'] ?? $field['code'] ?? '-' }}
+
{{ $field['value'] ?? '-' }}
+
+ @endforeach +
+ @else +
该订单没有保存完整页面字段。
+ @endif +
+ + @if ($row->detail_synced_at) +
+
+ 销售商品明细 · {{ number_format((int) ($row->detail_item_count ?? 0)) }} 条 + · 缺成本商品 {{ number_format((int) ($row->detail_missing_cost_item_count ?? 0)) }} 条 +
+ @if ($salesItems->isNotEmpty()) +
+ + + + @foreach ($salesHeaders as $header) + + @endforeach + + + + @foreach ($salesItems as $item) + + @foreach ($salesHeaders as $header) + @php + $fieldCode = (string) ($header['fld'] ?? ''); + $fieldValue = $fieldCode === '' ? null : data_get($item, $fieldCode); + @endphp + + @endforeach + + @endforeach + +
{{ $header['title'] ?? $header['fld'] ?? '-' }}
{{ $displayValue($fieldValue) }}
+
+ @else +
暂无销售商品明细。
+ @endif +
+ + @if ($afterItems->isNotEmpty()) +
+
+ 退货商品明细 · {{ number_format($afterItems->count()) }} 条 +
+
+ + + + @foreach ($afterHeaders as $header) + + @endforeach + + + + @foreach ($afterItems as $item) + + @foreach ($afterHeaders as $header) + @php + $fieldCode = (string) ($header['fld'] ?? ''); + $fieldValue = $fieldCode === '' ? null : data_get($item, $fieldCode); + @endphp + + @endforeach + + @endforeach + +
{{ $header['title'] ?? $header['fld'] ?? '-' }}
{{ $displayValue($fieldValue) }}
+
+
+ @endif + @else +
+ 订单主数据已保存,但聚胜算商品条码明细尚未同步。 +
+ @endif +
+ @empty - 当前范围内没有商品成本或快递费为 0/空的订单。 + 当前范围内没有商品成本或快递费为 0/空的订单。 @endforelse @@ -168,3 +414,20 @@
+ + diff --git a/scripts/order-profit-shengsuan-details-sync.py b/scripts/order-profit-shengsuan-details-sync.py new file mode 100644 index 00000000..989281d1 --- /dev/null +++ b/scripts/order-profit-shengsuan-details-sync.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""同步聚胜算成本/运费异常订单的商品条码明细。 + +脚本从本地财务镜像读取异常订单,通过已登录的聚胜算 Chrome 调试窗口批量请求 +订单明细接口,再导入 shared mirror。接口单批最多接受 50 个订单,脚本默认每次 +并发 4 批,并逐组导入,可在中断后通过“只取缺失明细”继续。 +""" + +import argparse +import json +import subprocess +import sys +import time +import urllib.request + +import websocket + + +DETAIL_API_URL = ( + 'https://pf1.erp321.com/WebApi/PF/OrderSku/GetPfOrderDetList' + '?uvalue=pfcweb_profit-report.order-profit' +) + + +class RateLimited(RuntimeError): + pass + + +def page_target(port: int): + with urllib.request.urlopen(f'http://127.0.0.1:{port}/json/list', timeout=5) as response: + targets = json.load(response) + pages = [ + target for target in targets + if target.get('type') == 'page' + and 'ss.erp321.com' in (target.get('url') or '') + ] + if not pages: + raise RuntimeError('未找到已登录的胜算页面,请先扫码登录并打开订单利润页面。') + return pages[0] + + +def evaluate(ws: websocket.WebSocket, expression: str): + request_id = int(time.time() * 1000) % 2_000_000_000 + ws.send(json.dumps({ + 'id': request_id, + 'method': 'Runtime.evaluate', + 'params': { + 'expression': expression, + 'returnByValue': True, + 'awaitPromise': True, + }, + })) + while True: + message = json.loads(ws.recv()) + if message.get('id') != request_id: + continue + if 'error' in message: + raise RuntimeError(json.dumps(message['error'], ensure_ascii=False)) + result = message.get('result', {}) + if 'exceptionDetails' in result: + raise RuntimeError(json.dumps(result['exceptionDetails'], ensure_ascii=False)) + return result.get('result', {}).get('value') + + +def condition_for(ids: list[str]) -> dict: + joined = ','.join(ids) + return { + 'type': 'soId', + 'idType': joined, + 'dateFld': 'pay_date', + 'combineDate': None, + 'shop': [], + 'multiPriceType': 'User3', + 'multiplePrice': 63, + 'costTypeList': [], + 'orderType': [], + 'drpCoidtos': [], + 'wmsCoidList': [], + 'buIdList': [], + 'skuIn': {'type': 'anyonesku', 'values': [], 'select': 'in'}, + 'skuOut': {'type': 'anyonesku', 'values': [], 'select': 'out'}, + 'labelIn': {'type': 'anyonelabel', 'values': [], 'select': 'in'}, + 'labelout': {'type': 'anyonelabel', 'values': [], 'select': 'out'}, + 'creatorList': [], + 'cusIdList': [], + 'brands': [], + 'categorys': [], + 'vcNames': [], + 'goodsCostGroup': { + 'skuCostAmountSearchType': {'value': 2, 'label': '按固定值搜索商品成本'}, + 'value': '', + 'values': ['', ''], + }, + 'backGoodsType': 1, + 'splitCombine': True, + 'groupByType': 1, + 'soId': joined, + 'skuCostAmountSearchType': 2, + 'skuCostAmountList': [], + 'firstfreightList': [''], + 'stateCityList': [], + 'isOL': True, + 'isExport': False, + 'skugroup': 'so_id', + 'isValidateDate': False, + } + + +def request_payload(ids: list[str]) -> dict: + return { + 'uid': '', + 'coid': '', + 'ip': '', + 'page': {'currentPage': 1, 'pageSize': 5000}, + 'data': {'isAds': False, 'condition': condition_for(ids)}, + 'ssProjectType': 'SS', + 'ssClientType': 'Web', + } + + +def fetch_group(ws: websocket.WebSocket, groups: list[list[str]]) -> list[dict]: + payloads = [request_payload(group) for group in groups] + expression = f"""(async () => {{ + const payloads = {json.dumps(payloads, ensure_ascii=False)}; + return await Promise.all(payloads.map(async (payload) => {{ + const response = await fetch('{DETAIL_API_URL}', {{ + method: 'POST', + credentials: 'include', + headers: {{'Content-Type': 'application/json'}}, + body: JSON.stringify(payload) + }}); + return {{status: response.status, text: await response.text()}}; + }})); + }})()""" + responses = evaluate(ws, expression) + if not isinstance(responses, list): + raise RuntimeError('聚胜算订单明细接口没有返回有效响应。') + + decoded = [] + for response in responses: + if response.get('status') != 200: + raise RuntimeError(f'聚胜算订单明细接口 HTTP {response.get("status")}') + payload = json.loads(response.get('text') or '{}') + if payload.get('code') == 1908: + raise RateLimited('RATE_LIMIT') + if payload.get('code') not in (0, None): + raise RuntimeError( + f'聚胜算订单明细接口错误 code={payload.get("code")} msg={payload.get("msg")}' + ) + data = payload.get('data') + if not isinstance(data, dict): + raise RuntimeError('聚胜算订单明细接口缺少 data。') + decoded.append(data) + return decoded + + +def merge_data(items: list[dict]) -> dict: + merged = { + 'ords': {'fldHeads': [], 'dataList': []}, + 'afters': {'fldHeads': [], 'dataList': []}, + } + for data in items: + for section in ('ords', 'afters'): + source = data.get(section) or {} + if not isinstance(source, dict): + continue + if not merged[section]['fldHeads'] and isinstance(source.get('fldHeads'), list): + merged[section]['fldHeads'] = source['fldHeads'] + if isinstance(source.get('dataList'), list): + merged[section]['dataList'].extend(source['dataList']) + return merged + + +def database_orders(args) -> list[str]: + command = [ + 'docker', 'exec', '-i', '-u', 'www-data', 'jiangling_app', + 'php', 'artisan', 'order-profit:shengsuan-anomaly-orders', + '--from', args.begin, + '--to', args.end, + ] + if not args.refresh: + command.append('--missing-details') + if args.limit > 0: + command.extend(['--limit', str(args.limit)]) + process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) + if process.returncode != 0: + raise RuntimeError(process.stderr.decode('utf-8', 'replace').strip()) + + output = process.stdout.decode('utf-8', 'replace') + payload = None + for line in reversed(output.splitlines()): + line = line.strip() + if line.startswith('{'): + payload = json.loads(line) + break + if not isinstance(payload, dict): + raise RuntimeError('无法读取异常订单编号。') + orders = [] + seen = set() + for order in payload.get('orders') or []: + order_no = str(order.get('order_no') or '').strip() + if order_no != '' and order_no not in seen: + seen.add(order_no) + orders.append(order_no) + return orders + + +def import_details(payload: dict) -> None: + process = subprocess.run( + [ + 'docker', 'exec', '-i', '-u', 'www-data', 'jiangling_app', + 'php', 'artisan', 'order-profit:import-shengsuan-details', '--stdin', + ], + input=json.dumps({'data': payload}, ensure_ascii=False).encode('utf-8'), + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + ) + if process.returncode != 0: + message = process.stderr.decode('utf-8', 'replace').strip() + message = message or process.stdout.decode('utf-8', 'replace').strip() + raise RuntimeError(message or '订单明细导入失败。') + print(process.stdout.decode('utf-8', 'replace').strip(), flush=True) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument('--from', dest='begin', required=True) + parser.add_argument('--to', dest='end', required=True) + parser.add_argument('--batch-size', type=int, default=50) + parser.add_argument('--concurrency', type=int, default=4) + parser.add_argument('--retries', type=int, default=8) + parser.add_argument('--delay', type=float, default=1.0) + parser.add_argument('--limit', type=int, default=0) + parser.add_argument('--debug-port', type=int, default=9333) + parser.add_argument('--refresh', action='store_true', help='刷新已有明细,不只补缺失订单') + parser.add_argument('--no-import', action='store_true') + parser.add_argument('--json-out', default='') + args = parser.parse_args() + + args.batch_size = min(max(args.batch_size, 1), 50) + args.concurrency = min(max(args.concurrency, 1), 6) + args.retries = max(args.retries, 1) + + orders = database_orders(args) + if not orders: + print('没有待同步的商品明细订单。', flush=True) + return 0 + + batches = [orders[start:start + args.batch_size] for start in range(0, len(orders), args.batch_size)] + groups = [batches[start:start + args.concurrency] for start in range(0, len(batches), args.concurrency)] + print( + f'待同步 {len(orders)} 单,共 {len(batches)} 批;每次并发 {args.concurrency} 批。', + flush=True, + ) + + target = page_target(args.debug_port) + ws = websocket.create_connection(target['webSocketDebuggerUrl'], timeout=240) + all_data = [] + completed_orders = 0 + completed_items = 0 + try: + ws.send(json.dumps({'id': 0, 'method': 'Runtime.enable', 'params': {}})) + for group_index, group in enumerate(groups, start=1): + for attempt in range(1, args.retries + 1): + try: + data_items = fetch_group(ws, group) + break + except RateLimited: + wait = min(600, 60 * attempt) + print(f'第 {attempt} 次限流,等待 {wait} 秒后重试……', flush=True) + time.sleep(wait) + else: + raise RuntimeError('聚胜算订单明细接口持续限流,本次已保留此前导入结果。') + + merged = merge_data(data_items) + item_count = len((merged.get('ords') or {}).get('dataList') or []) + completed_orders += sum(len(batch) for batch in group) + completed_items += item_count + all_data.append(merged) + if not args.no_import: + import_details(merged) + print( + f'[{group_index}/{len(groups)}] 已请求 {completed_orders}/{len(orders)} 单,' + f'返回销售商品 {completed_items} 行。', + flush=True, + ) + if args.delay > 0 and group_index < len(groups): + time.sleep(args.delay) + finally: + ws.close() + + if args.json_out: + with open(args.json_out, 'w') as handle: + handle.write(json.dumps({'responses': all_data}, ensure_ascii=False)) + print(f'明细 JSON:{args.json_out}', flush=True) + + return 0 + + +if __name__ == '__main__': + try: + raise SystemExit(main()) + except KeyboardInterrupt: + print('已中止;已导入的批次会保留,可重新运行继续补缺失明细。', file=sys.stderr) + raise SystemExit(130) + except Exception as error: + print(f'明细同步失败:{error}', file=sys.stderr) + raise SystemExit(1) diff --git a/tests/Feature/Business/CostFreightAnomalyPageTest.php b/tests/Feature/Business/CostFreightAnomalyPageTest.php index 51d052d1..2711bd92 100644 --- a/tests/Feature/Business/CostFreightAnomalyPageTest.php +++ b/tests/Feature/Business/CostFreightAnomalyPageTest.php @@ -16,6 +16,9 @@ class CostFreightAnomalyPageTest extends FeatureTestCase 'last_synced_at' => '2026-11-07 17:44:20', 'total' => 1, 'shops' => ['天猫-卓禾家具旗舰店'], + 'detail_ready' => true, + 'detail_total' => 1, + 'detail_last_synced_at' => '2026-11-09 10:00:00', ]); $repository->shouldReceive('paginate')->once()->andReturn([ 'rows' => [[ @@ -31,6 +34,27 @@ class CostFreightAnomalyPageTest extends FeatureTestCase 'synced_at' => '2026-11-07 17:44:20', 'anomaly_types' => ['成本异常', '运费异常'], 'anomaly_type' => '成本异常、运费异常', + 'order_fields' => [ + ['code' => 'c_900901', 'title' => '店铺名称', 'value' => '天猫-卓禾家具旗舰店'], + ['code' => 'c_900951', 'title' => '发货仓库', 'value' => '简尚-崔桥工厂仓'], + ], + 'missing_cost_barcodes' => ['ZWJ003952N181V01'], + 'detail_synced_at' => '2026-11-09 10:00:00', + 'detail_item_count' => 1, + 'detail_after_item_count' => 0, + 'detail_missing_cost_item_count' => 1, + 'detail_order_headers' => [ + ['fld' => 'c_900904', 'title' => '商品编码'], + ['fld' => 'c_900910', 'title' => '商品名称'], + ['fld' => 'c_900201', 'title' => '商品成本'], + ], + 'detail_order_items' => [[ + 'c_900904' => 'ZWJ003952N181V01', + 'c_900910' => '支架', + 'c_900201' => 0, + ]], + 'detail_after_headers' => [], + 'detail_after_items' => [], ]], 'total' => 1, 'has_more' => false, @@ -50,6 +74,11 @@ class CostFreightAnomalyPageTest extends FeatureTestCase ->assertSeeText('5127581702031023636') ->assertSeeText('成本异常') ->assertSeeText('运费异常') + ->assertSeeText('缺成本条码') + ->assertSeeText('ZWJ003952N181V01') + ->assertSeeText('完整订单数据') + ->assertSeeText('简尚-崔桥工厂仓') + ->assertSeeText('销售商品明细') ->assertSeeText('最近同步'); } } diff --git a/tests/Unit/EcommerceFinance/CostFreightAnomalyRepositoryTest.php b/tests/Unit/EcommerceFinance/CostFreightAnomalyRepositoryTest.php index f96a52d4..ece8dd15 100644 --- a/tests/Unit/EcommerceFinance/CostFreightAnomalyRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/CostFreightAnomalyRepositoryTest.php @@ -33,6 +33,24 @@ class CostFreightAnomalyRepositoryTest extends TestCase $table->decimal('matched_package_fee', 18, 2)->nullable(); $table->decimal('matched_freight_fee', 18, 2)->nullable(); $table->decimal('matched_bill_fee', 18, 2)->nullable(); + $table->longText('source_payload')->nullable(); + $table->dateTime('synced_at')->nullable(); + $table->timestamps(); + }); + Schema::connection('business_mirror')->create('ops_shengsuan_order_profit_detail_snapshots', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('order_key'); + $table->string('shop_name'); + $table->string('online_order_no')->nullable(); + $table->string('internal_order_no')->nullable(); + $table->unsignedInteger('item_count')->default(0); + $table->unsignedInteger('after_item_count')->default(0); + $table->unsignedInteger('missing_cost_item_count')->default(0); + $table->longText('order_headers')->nullable(); + $table->longText('order_items')->nullable(); + $table->longText('after_headers')->nullable(); + $table->longText('after_items')->nullable(); + $table->longText('missing_cost_barcodes')->nullable(); $table->dateTime('synced_at')->nullable(); $table->timestamps(); }); @@ -49,11 +67,36 @@ class CostFreightAnomalyRepositoryTest extends TestCase 'internal_order_no' => null, 'matched_package_fee' => 0, 'matched_bill_fee' => 0, + 'source_payload' => json_encode(['c_900901' => $row['shop_name'], 'c_900902' => $row['online_order_no']]), 'synced_at' => '2026-11-07 10:00:00', 'created_at' => now(), 'updated_at' => now(), ]); } + $db->table('ops_shengsuan_order_profit_detail_snapshots')->insert([ + 'order_key' => '异常店|NO-1', + 'shop_name' => '异常店', + 'online_order_no' => 'NO-1', + 'internal_order_no' => null, + 'item_count' => 2, + 'after_item_count' => 0, + 'missing_cost_item_count' => 1, + 'order_headers' => json_encode([ + ['fld' => 'c_900904', 'title' => '商品编码'], + ['fld' => 'c_900910', 'title' => '商品名称'], + ['fld' => 'c_900201', 'title' => '商品成本'], + ]), + 'order_items' => json_encode([ + ['c_900904' => 'BAR-001', 'c_900910' => '缺成本商品', 'c_900201' => 0], + ['c_900904' => 'BAR-002', 'c_900910' => '正常成本商品', 'c_900201' => 20], + ]), + 'after_headers' => '[]', + 'after_items' => '[]', + 'missing_cost_barcodes' => json_encode(['BAR-001']), + 'synced_at' => '2026-11-09 10:00:00', + 'created_at' => now(), + 'updated_at' => now(), + ]); } public function test_orders_with_either_cost_or_freight_missing_are_classified_independently(): void @@ -74,6 +117,10 @@ class CostFreightAnomalyRepositoryTest extends TestCase $this->assertSame(['成本异常'], $rows['NO-3']['anomaly_types']); $this->assertSame(['成本异常'], $rows['NO-5']['anomaly_types']); $this->assertArrayNotHasKey('NO-4', $rows); + $this->assertSame(['BAR-001'], $rows['NO-1']['missing_cost_barcodes']); + $this->assertSame(2, $rows['NO-1']['detail_item_count']); + $this->assertSame('商品编码', $rows['NO-1']['detail_order_headers'][0]['title']); + $this->assertSame('异常店', collect($rows['NO-1']['order_fields'])->firstWhere('code', 'c_900901')['value']); } public function test_order_and_shop_batch_filters_are_applied(): void @@ -89,4 +136,21 @@ class CostFreightAnomalyRepositoryTest extends TestCase $this->assertSame(1, $result['total']); $this->assertSame('异常店', $result['rows'][0]['shop_name']); } + + public function test_missing_detail_references_exclude_orders_already_synced(): void + { + $references = app(CostFreightAnomalyRepository::class)->references([ + 'from' => '2026-11-01', + 'to' => '2026-11-07', + 'order_no' => '', + 'shop_names' => [], + ], true); + + $orderNumbers = array_column($references, 'order_no'); + $this->assertCount(3, $references); + $this->assertNotContains('NO-1', $orderNumbers); + $this->assertContains('NO-2', $orderNumbers); + $this->assertContains('NO-3', $orderNumbers); + $this->assertContains('NO-5', $orderNumbers); + } } diff --git a/tests/Unit/EcommerceFinance/ShengsuanOrderProfitDetailMapperTest.php b/tests/Unit/EcommerceFinance/ShengsuanOrderProfitDetailMapperTest.php new file mode 100644 index 00000000..c12ef532 --- /dev/null +++ b/tests/Unit/EcommerceFinance/ShengsuanOrderProfitDetailMapperTest.php @@ -0,0 +1,82 @@ +snapshots([ + 'data' => [ + 'ords' => [ + 'fldHeads' => [ + ['fld' => 'c_900904', 'title' => '商品编码'], + ['fld' => 'c_900910', 'title' => '商品名称'], + ['fld' => 'c_900201', 'title' => '商品成本'], + ['fld' => 'c_900407', 'title' => '商家运费'], + ], + 'dataList' => [ + [ + 'c_900901' => '天猫-卓禾家具旗舰店', + 'c_900902' => '5127581702031023636', + 'c_900903' => '10097143', + 'c_900904' => 'ZWJ003952N181V01', + 'c_900910' => '书架', + 'c_900201' => 0, + 'c_900407' => 7.05, + ], + [ + 'c_900901' => '天猫-卓禾家具旗舰店', + 'c_900902' => '5127581702031023636', + 'c_900903' => '10097143', + 'c_900904' => 'ZWJ003952N181V02', + 'c_900910' => '书架配件', + 'c_900201' => 18.5, + 'c_900407' => 0, + ], + [ + 'c_900901' => '天猫-卓禾家具旗舰店', + 'c_900902' => '5127581702031023637', + 'c_900903' => '10097144', + 'c_900904' => 'ZWJ003952N181V03', + 'c_900910' => '置物架', + 'c_900201' => 22, + 'c_900407' => 6, + ], + ], + ], + 'afters' => [ + 'fldHeads' => [ + ['fld' => 'c_900904', 'title' => '商品编码'], + ['fld' => 'c_900201', 'title' => '商品成本'], + ], + 'dataList' => [[ + 'c_900901' => '天猫-卓禾家具旗舰店', + 'c_900902' => '5127581702031023636', + 'c_900903' => '10097143', + 'c_900904' => 'ZWJ003952N181V01', + 'c_900201' => 0, + ]], + ], + ], + ]); + + $this->assertCount(2, $snapshots); + $snapshot = collect($snapshots)->firstWhere('order_key', '天猫-卓禾家具旗舰店|5127581702031023636'); + $this->assertSame(2, $snapshot['item_count']); + $this->assertSame(1, $snapshot['after_item_count']); + $this->assertSame(1, $snapshot['missing_cost_item_count']); + $this->assertSame(['ZWJ003952N181V01'], json_decode($snapshot['missing_cost_barcodes'], true)); + + $items = json_decode($snapshot['order_items'], true); + $this->assertSame('ZWJ003952N181V01', $items[0]['c_900904']); + $this->assertSame(18.5, $items[1]['c_900201']); + $this->assertCount(4, json_decode($snapshot['order_headers'], true)); + $this->assertSame('商品编码', json_decode($snapshot['order_headers'], true)[0]['title']); + $this->assertArrayNotHasKey('source_payload', $snapshot); + } +}