'淘宝', 'taobao-wechat' => '淘宝', 'pinduoduo' => '拼多多', 'jd-transactions' => '京东', 'jingxi' => '京喜', 'jd-wallet' => '京东', 'douyin' => '抖音', 'dewu' => '得物', 'vipshop' => '唯品会MP', 'vipshop-jx' => '唯品会jx', ]; /** 店铺名前缀可识别的平台(顺序敏感:先长后短)。 */ private const STORE_PREFIX_PLATFORMS = [ '唯品会JX' => '唯品会jx', '唯品会MP' => '唯品会MP', '阿里巴巴' => '阿里巴巴', '拼多多' => '拼多多', '天猫' => '天猫', '淘宝' => '淘宝', '抖音' => '抖音', '得物' => '得物', '京喜' => '京喜', '京东' => '京东', ]; /** * @return array> [platform => [bill_item => ledger_remark]] */ public function map(): array { return Cache::rememberForever(self::CACHE_KEY, function (): array { try { if (! Schema::hasTable('ec_account_ledger_remarks')) { return []; } $map = []; foreach (\Illuminate\Support\Facades\DB::table('ec_account_ledger_remarks') ->select(['platform', 'bill_item', 'ledger_remark']) ->get() as $row) { $platform = trim((string) $row->platform); $item = trim((string) $row->bill_item); if ($platform === '' || $item === '') { continue; } $map[$platform][$item] = (string) $row->ledger_remark; } return $map; } catch (Throwable) { return []; } }); } public function forget(): void { Cache::forget(self::CACHE_KEY); } /** 页签默认平台。 */ public function defaultPlatform(string $tab): ?string { return self::TAB_PLATFORM[$tab] ?? null; } /** 解析某一行账单所属平台:优先店铺名前缀,其次页签默认。 */ public function platform(?string $storeName, ?string $tabPlatform): ?string { $name = trim((string) $storeName); if ($name !== '') { foreach (self::STORE_PREFIX_PLATFORMS as $prefix => $platform) { if (str_starts_with($name, $prefix)) { return $platform; } } } return $tabPlatform; } /** 查总账备注;没有匹配返回 null。 */ public function remark(?string $storeName, ?string $tabPlatform, ?string $billItem): ?string { $item = trim((string) $billItem); if ($item === '') { return null; } $map = $this->map(); if ($map === []) { return null; } foreach ([$this->platform($storeName, $tabPlatform), $tabPlatform] as $platform) { if ($platform === null || $platform === '') { continue; } if (isset($map[$platform][$item])) { return $map[$platform][$item]; } } return null; } /** * 给一行账单补上 payload.ledger_remark(内部字段名 ledger_remark)。 * * @param array $row * @return array */ public function decorate(array $row, string $tab): array { $tabPlatform = $this->defaultPlatform($tab); $remark = $this->remark( $row['store_name'] ?? null, $tabPlatform, $row['bill_item'] ?? null, ); if ($remark === null) { return $row; } $payload = is_array($row['payload'] ?? null) ? $row['payload'] : []; $payload['ledger_remark'] = $remark; $row['payload'] = $payload; // 淘系支付宝页签按顶层字段取值,这里同时补一份,页面与导出共用。 $row['ledger_remark'] = $remark; return $row; } /** * @param iterable> $rows * @return \Generator> */ public function decorateAll(iterable $rows, string $tab): \Generator { foreach ($rows as $row) { yield is_array($row) ? $this->decorate($row, $tab) : $row; } } }