fix(快递账单): 复用工作平台机器人并支持指定对账群 (#1674)

This commit is contained in:
limeng 2026-12-03 09:47:10 +08:00
parent 8504b67084
commit 6ca6501466
7 changed files with 341 additions and 3 deletions

View File

@ -0,0 +1,44 @@
<?php
namespace App\Console\Commands;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\WorkPlatformCourierRobots;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
class ImportWorkPlatformCourierRobots extends Command
{
protected $signature = 'courier-bills:import-platform-robots {file : Private JSON export of courier payable robot rows} {--company=1} {--apply : Save the reviewed exact matches}';
protected $description = '预演或导入工作平台快递应付群机器人配置;不发送消息';
public function handle(CourierBillStore $store, WorkPlatformCourierRobots $matcher, SupplierDingTalkNotifier $notifier): int
{
$path = (string) $this->argument('file');
if (! is_file($path) || filesize($path) > 2 * 1024 * 1024) throw new RuntimeException('配置文件不存在或超过 2MB。');
$rows = json_decode(file_get_contents($path), true, 32, JSON_THROW_ON_ERROR);
if (! is_array($rows) || ! array_is_list($rows) || count($rows) > 10000) throw new RuntimeException('配置文件必须是最多 10000 条的数组。');
\App\Models\Common\Company::findOrFail((int) $this->option('company'))->makeCurrent(true);
$result = $matcher->match($store->groups(), $rows);
$this->line('名称匹配:' . count($result['robots']) . ';未匹配:' . count($result['unmatched']) . ';有歧义:' . count($result['ambiguous']));
foreach ($result['robots'] as $name => $robot) $this->line($name . ' → ' . ($robot['group_name'] ?: '工作平台已配置群') . '(配置 ' . $robot['source_id'] . ')');
$this->line('未匹配:' . implode('、', $result['unmatched']));
$this->line('有歧义:' . implode('、', $result['ambiguous']));
if (! $this->option('apply')) return self::SUCCESS;
$backup = 'private/courier-robot-backups/' . now()->format('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.enc';
$backedUp = Storage::disk('local')->put($backup, Crypt::encryptString(json_encode([
'company_id' => (int) $this->option('company'),
'value' => setting('supplier_reconciliation.dingtalk_robots', []),
], JSON_THROW_ON_ERROR)));
if (! $backedUp || ! chmod(Storage::disk('local')->path($backup), 0600)) {
throw new RuntimeException('原配置备份失败,未修改机器人配置。');
}
$notifier->importCourierRobots($result['robots']);
$this->info('已保存 ' . count($result['robots']) . ' 家;原配置已加密备份:' . $backup . ';未发送消息。');
return self::SUCCESS;
}
}

View File

@ -0,0 +1,92 @@
<?php
namespace App\Support\CourierBills;
use RuntimeException;
/** 按财务分组名称匹配工作平台的快递名称或群名;组合分组任一名称命中即可。 */
final class WorkPlatformCourierRobots
{
/** 负责人明确指定的对应关系,目标必须命中工作平台完整业务名称。 */
private const DESIGNATED_NAMES = [
'北京韵达-乐鑫达' => '北京大件韵达',
'樵舍中通' => '樵舍中通',
'樵舍中通-上楼' => '樵舍中通',
'樵舍中通上楼' => '樵舍中通',
'江西中通快运' => '樵舍中通',
'江西新建中通' => '樵舍中通',
'山东中通快运' => '樵舍中通',
'南昌樵舍仓仓储费' => '樵舍中通',
'中通快运专线' => '常州中通快运',
'宿迁中通快运' => '沭阳中通快运',
'山东顺丰干配' => '顺德德邦',
'河北中通-江三' => '顺德德邦',
'苏北顺丰干配大件' => '顺德德邦',
];
public function match(array $groups, array $rows): array
{
$platformRows = [];
foreach ($rows as $row) {
if (! is_array($row) || ! isset($row['Id'])) {
throw new RuntimeException('机器人配置缺少有效的记录编号。');
}
if (trim((string) ($row['forModel'] ?? '')) !== '快递应付') continue;
$platformRows[] = $row;
}
$robots = $unmatched = $ambiguous = [];
foreach ($groups as $group) {
$name = (string) $group->name;
$designatedName = self::DESIGNATED_NAMES[$name] ?? null;
$candidates = [];
$bestScore = 0;
$names = preg_split('/[|++、,,;;]+/u', $name, -1, PREG_SPLIT_NO_EMPTY) ?: [];
foreach ($platformRows as $row) {
$keys = array_filter(array_map('trim', explode('|', (string) ($row['businessKey'] ?? ''))));
if ($designatedName !== null) {
if (in_array($designatedName, $keys, true)) $candidates[(string) $row['Id']] = $row;
continue;
}
$platformGroup = (string) ($row['groupname'] ?? '');
$score = 0;
foreach ($names as $part) {
$part = trim($part);
if ($part === '') continue;
// 负责人明确这两家独立,缺少本家配置时也不能借用另一家。
if (in_array($part, ['常州德邦', '常州德邦逆向'], true)) {
if (in_array($part, $keys, true)) $score = max($score, 100000 + mb_strlen($part));
continue;
}
if (str_contains($platformGroup, $part)) $score = max($score, mb_strlen($part));
foreach ($keys as $key) {
if ($part === $key) {
$score = max($score, 100000 + mb_strlen($key));
} elseif (str_contains($part, $key) || str_contains($key, $part)) {
$score = max($score, min(mb_strlen($part), mb_strlen($key)));
}
}
}
if ($score > $bestScore) {
$candidates = [];
$bestScore = $score;
}
if ($score > 0 && $score === $bestScore) $candidates[(string) $row['Id']] = $row;
}
if ($candidates === []) { $unmatched[] = $name; continue; }
if (count($candidates) !== 1) { $ambiguous[] = $name; continue; }
$row = reset($candidates);
$webhook = trim((string) ($row['webAccesstoken'] ?? ''));
if ($webhook === '') { $unmatched[] = $name; continue; }
if (! str_starts_with($webhook, 'https://')) {
$webhook = 'https://oapi.dingtalk.com/robot/send?access_token=' . rawurlencode($webhook);
}
$robots[$name] = [
'webhook' => $webhook, 'secret' => trim((string) ($row['Secret'] ?? '')),
'group_name' => trim(preg_replace('/[\x00-\x1F\x7F]/u', '', (string) ($row['groupname'] ?? '')) ?? ''),
'source_id' => (string) $row['Id'], 'source_updated_at' => (string) ($row['modifytime'] ?? ''),
];
}
return compact('robots', 'unmatched', 'ambiguous');
}
}

View File

@ -0,0 +1,26 @@
# 快递账单群机器人复用
对账分组使用现有加密机器人设置。工作平台配置复制后,钉钉对账群列显示原群名和“工作平台应付群”,上传链接通知与账单上传回执使用同一份设置。只有 Webhook 的脱敏提示可见,不回显 Webhook 或加签密钥。
配置来源为负责人指定的工作平台“应付群机器人配置”导出,字段为 `Id`、`forModel`、`businessKey`、`groupname`、`webAccesstoken`、`Secret`、`modifytime`。导出文件只放在服务器私有目录并设为 `0600`,不得进入 Git 或日志。此功能不建立对旧业务库的自动同步,也不在页面请求时读取上游。
仅使用 `forModel=快递应付` 的记录,以财务系统“分组名称”为匹配依据,组合名称按 `|`、`+`、顿号或逗号分开。任一名称在工作平台群名中命中,或与 `businessKey` 中某个快递名称互相包含,即视为命中。不使用“归到承运商”和“快递名称1”代替分组名称。完整业务名称命中优先,其次取相交名称最长的一条,避免“常州德邦”抢走“常州德邦逆向”;仍有同等匹配时跳过并报告歧义。没有匹配时保留原设置。空群名不影响按业务名称匹配到的机器人发送能力。
先预演,核对结果后再写入:
常州德邦与常州德邦逆向是两家独立快递,两者只接受本家完整业务名称匹配;缺少本家配置时保持未匹配,不借用另一家的机器人。
北京韵达-乐鑫达按负责人指定使用“北京大件韵达+北京大件韵达临时”的机器人,匹配业务名称“北京大件韵达”。
樵舍中通、樵舍中通-上楼(也兼容樵舍中通上楼)、江西中通快运、江西新建中通、山东中通快运、南昌樵舍仓仓储费,统一使用包含完整业务名称“樵舍中通”的南昌对接群配置。中通快运专线使用“常州中通快运+武进韵达快运”的机器人;宿迁中通快运使用“沭阳中通快运”的机器人。指定目标不存在或存在多条时保持未匹配/有歧义,不回退到其他同名群。
山东顺丰干配、河北中通-江三、苏北顺丰干配大件按负责人指定使用“顺德德邦+廊坊德邦+廊坊德邦其他”的机器人,匹配业务名称“顺德德邦”。
```sh
php artisan courier-bills:import-platform-robots /private/path/robots.json --company=1
php artisan courier-bills:import-platform-robots /private/path/robots.json --company=1 --apply
```
命令接受最多 2MB、10000 条的配置文件。实际为几十条记录,内存中匹配并一次写入设置;不是账单导入或全量业务处理。写入前把原公司设置加密备份到 `storage/app/private/courier-robot-backups/`,备份中包含公司编号和原设置值。恢复时用同一应用密钥解密,并仅恢复该公司的 `supplier_reconciliation.dingtalk_robots` 设置。
导入会替换明确匹配分组的 Webhook、加签密钥和来源标记,保留无关供应商设置、互动卡片字段和发送记录。导入不发送任何群消息;原通知按钮由财务按账期手动操作。后续工作平台配置有变化时,需要重新导出、预演并导入。

View File

@ -109,6 +109,8 @@ class SupplierDingTalkNotifier
return [
'configured' => $webhook !== '',
'webhook_hint' => $this->maskWebhook($webhook),
'group_name' => (string) ($config['group_name'] ?? ''),
'config_source' => (string) ($config['config_source'] ?? ''),
'at_all' => (bool) ($config['at_all'] ?? false),
'card_group_configured' => $cardConversationId !== '',
'card_group_hint' => $this->maskConversationId($cardConversationId),
@ -180,7 +182,24 @@ class SupplierDingTalkNotifier
'card_robot_code' => $cardRobotCode,
'last_pushed_at' => (string) ($existing['last_pushed_at'] ?? ''),
'last_push_count' => (int) ($existing['last_push_count'] ?? 0),
];
] + ($webhook === $existingWebhook ? array_intersect_key($existing, array_flip([
'group_name', 'config_source', 'source_id', 'source_updated_at',
])) : []);
$this->persist($configs);
}
/** Import only reviewed courier matches, preserving unrelated suppliers and encrypting credentials. */
public function importCourierRobots(array $robots): void
{
$configs = $this->configs();
foreach ($robots as $name => $robot) {
$this->assertWebhook((string) $robot['webhook']);
if (mb_strlen((string) $robot['secret']) > 256) {
throw new RuntimeException('工作平台机器人加签密钥过长。');
}
$existing = $configs[$name] ?? [];
$configs[$name] = array_replace($existing, $robot, ['config_source' => 'work_platform']);
}
$this->persist($configs);
}
@ -1087,6 +1106,10 @@ class SupplierDingTalkNotifier
'card_robot_code' => trim((string) ($config['card_robot_code'] ?? '')),
'last_pushed_at' => (string) ($config['last_pushed_at'] ?? ''),
'last_push_count' => (int) ($config['last_push_count'] ?? 0),
'group_name' => (string) ($config['group_name'] ?? ''),
'config_source' => (string) ($config['config_source'] ?? ''),
'source_id' => (string) ($config['source_id'] ?? ''),
'source_updated_at' => (string) ($config['source_updated_at'] ?? ''),
];
}

View File

@ -117,7 +117,11 @@
<details>
<summary>
@if ($robot['configured'] ?? false)
<span class="cbr-chip ok">已配</span> {{ $robot['webhook_hint'] ?? '' }}
<span class="cbr-chip ok">已配</span>
{{ ($robot['group_name'] ?? '') ?: ($robot['webhook_hint'] ?? '') }}
@if (($robot['config_source'] ?? '') === 'work_platform')
<span class="cbr-muted">工作平台应付群</span>
@endif
@else
<span class="cbr-chip">未配</span>
@endif

View File

@ -5,7 +5,7 @@
@csrf
<label>账单月份<input type="month" name="month" value="{{ $month }}" required></label>
<button type="submit" class="cbr-primary">推送上传链接到快递群</button>
<span class="cbr-muted">每家快递的钉钉对账群配一个群机器人(在「对账分组」里配,群设置 → 机器人 → 自定义,安全设置选「加签」),这里一键往这些群推本月的免登录上传链接。
<span class="cbr-muted">对账分组已复用工作平台「应付群机器人配置」中对应快递的群机器人;未匹配的可在「对账分组」里补充。这里一键往已配置的群推本月的免登录上传链接。
快递点开链接、下载模板(单号、省、重量、运费、快递名称、面单、费率)填好上传,后台校验读入后进入对账;链接只能传那一家那个月,30 天有效。已有 {{ collect($cbRobots ?? [])->where('configured', true)->count() }} 家配了机器人。</span>
</form>
</section>

View File

@ -0,0 +1,149 @@
<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\WorkPlatformCourierRobots;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use Tests\Feature\FeatureTestCase;
final class WorkPlatformCourierRobotsTest extends FeatureTestCase
{
public function test_matching_uses_group_name_and_accepts_any_name_hit_without_using_other_fields(): void
{
$group = fn (string $name, array $aliases = []) => (object) ['name' => $name, 'summary_carrier' => $name, 'express_names' => $aliases];
$rows = [
$this->robot(1, '曹县韵达|曹县邮政', '账务群甲'),
$this->robot(2, '德邦快递|沭阳德邦', '德邦快递+沭阳德邦+睢宁邮政小包账务群乙'),
$this->robot(3, '韵达', '厂家群'),
];
$rows[2]['forModel'] = '供应商应付汇总';
$result = (new WorkPlatformCourierRobots())->match([
$group('曹县韵达', ['曹县韵达']), $group('曹县韵达小件'),
$group('别名分组', ['沭阳德邦']), $group('无匹配+曹县邮政'), $group('韵达'),
$group('睢宁邮政小包'), $group('曹县韵达+德邦快递'),
], $rows);
$this->assertSame(['曹县韵达', '曹县韵达小件', '无匹配+曹县邮政', '韵达', '睢宁邮政小包'], array_keys($result['robots']));
$this->assertSame('账务群甲', $result['robots']['曹县韵达']['group_name']);
$this->assertSame('https://oapi.dingtalk.com/robot/send?access_token=platform-1', $result['robots']['曹县韵达']['webhook']);
$this->assertSame(['别名分组'], $result['unmatched']);
$this->assertSame(['曹县韵达+德邦快递'], $result['ambiguous']);
}
public function test_exact_and_more_specific_names_win_over_short_containing_names(): void
{
$rows = [$this->robot(1, '常州德邦', '常州德邦群'), $this->robot(2, '常州德邦逆向', '常州德邦逆向群'),
$this->robot(3, '百世快运', '百世快运群'), $this->robot(4, '霸州百世快运', '霸州群')];
$groups = array_map(fn ($name) => (object) ['name' => $name], ['常州德邦', '常州德邦逆向', '霸州百世快运-雅柏']);
$result = (new WorkPlatformCourierRobots())->match($groups, $rows);
$this->assertSame('1', $result['robots']['常州德邦']['source_id']);
$this->assertSame('2', $result['robots']['常州德邦逆向']['source_id']);
$this->assertSame('4', $result['robots']['霸州百世快运-雅柏']['source_id']);
$this->assertSame([], $result['ambiguous']);
$onlyForward = (new WorkPlatformCourierRobots())->match($groups, [$rows[0]]);
$this->assertArrayNotHasKey('常州德邦逆向', $onlyForward['robots']);
$onlyReverse = (new WorkPlatformCourierRobots())->match($groups, [$rows[1]]);
$this->assertArrayNotHasKey('常州德邦', $onlyReverse['robots']);
}
public function test_beijing_lexinda_uses_the_explicitly_designated_robot(): void
{
$rows = [$this->robot(600, '北京大件韵达|北京大件韵达临时', '北京大件韵达+北京大件韵达临时'),
$this->robot(601, '北京韵达-乐鑫达', '其他群')];
$result = (new WorkPlatformCourierRobots())->match([(object) ['name' => '北京韵达-乐鑫达']], $rows);
$this->assertSame('600', $result['robots']['北京韵达-乐鑫达']['source_id']);
$this->assertSame('北京大件韵达+北京大件韵达临时', $result['robots']['北京韵达-乐鑫达']['group_name']);
}
public function test_designated_nanchang_changzhou_and_shuyang_groups_use_the_requested_robot(): void
{
$rows = [$this->robot(588, '樵舍中通|江西中通快运', '南昌对接群'),
$this->robot(601, '常州中通快运|武进韵达快运', '常州中通快运+武进韵达快运'),
$this->robot(624, '沭阳中通快运', '沭阳中通快运群'),
$this->robot(603, '顺德德邦|廊坊德邦|廊坊德邦其他', '顺德德邦+廊坊德邦+廊坊德邦其他'),
$this->robot(999, '山东中通快运|宿迁中通快运|中通快运专线', '同名但未指定的群')];
$names = ['樵舍中通', '樵舍中通-上楼', '樵舍中通上楼', '江西中通快运', '江西新建中通',
'山东中通快运', '南昌樵舍仓仓储费', '中通快运专线', '宿迁中通快运',
'山东顺丰干配', '河北中通-江三', '苏北顺丰干配大件'];
$groups = array_map(fn ($name) => (object) ['name' => $name], $names);
$result = (new WorkPlatformCourierRobots())->match($groups, $rows);
foreach (array_slice($names, 0, 7) as $name) $this->assertSame('588', $result['robots'][$name]['source_id']);
$this->assertSame('601', $result['robots']['中通快运专线']['source_id']);
$this->assertSame('624', $result['robots']['宿迁中通快运']['source_id']);
foreach (array_slice($names, 9) as $name) $this->assertSame('603', $result['robots'][$name]['source_id']);
$this->assertSame([], $result['unmatched']);
$this->assertSame([], $result['ambiguous']);
$missing = (new WorkPlatformCourierRobots())->match($groups, [end($rows)]);
$this->assertSame([], $missing['robots']);
}
public function test_import_is_previewed_backed_up_encrypted_and_used_for_upload_notifications(): void
{
Storage::fake('local');
Http::fake(['*' => Http::response(['errcode' => 0])]);
$this->company->makeCurrent(true);
$notifier = app(SupplierDingTalkNotifier::class);
$notifier->save('另一供应商', 'https://oapi.dingtalk.com/robot/send?access_token=keep-supplier', 'SEC-keep', false);
$before = setting('supplier_reconciliation.dingtalk_robots');
$db = CourierBillMatcher::db();
$groupId = $db->table('courier_bill_groups')->insertGetId(['name' => '曹县韵达', 'express_names' => '["曹县韵达"]', 'created_at' => now(), 'updated_at' => now()]);
$db->table('courier_bill_groups')->insert(['name' => '未匹配快递', 'express_names' => '[]', 'created_at' => now(), 'updated_at' => now()]);
Storage::disk('local')->put('robots.json', json_encode([$this->robot(1, '曹县韵达|曹县邮政', '曹县账务对接群')]));
$arguments = ['file' => Storage::disk('local')->path('robots.json'), '--company' => $this->company->id];
$this->artisan('courier-bills:import-platform-robots', $arguments)->assertExitCode(0);
$this->assertSame($before, setting('supplier_reconciliation.dingtalk_robots'));
Http::assertNothingSent();
$this->artisan('courier-bills:import-platform-robots', $arguments + ['--apply' => true])->assertExitCode(0);
Http::assertNothingSent();
$backups = Storage::disk('local')->files('private/courier-robot-backups');
$this->assertCount(1, $backups);
$backup = json_decode(Crypt::decryptString(Storage::disk('local')->get($backups[0])), true);
$this->assertSame($before, $backup['value']);
$stored = json_decode(setting('supplier_reconciliation.dingtalk_robots'), true);
$this->assertSame('SEC-platform-1', Crypt::decryptString($stored['曹县韵达']['secret']));
$this->assertStringNotContainsString('SEC-platform-1', setting('supplier_reconciliation.dingtalk_robots'));
$this->assertSame('SEC-keep', Crypt::decryptString($stored['另一供应商']['secret']));
$this->assertArrayNotHasKey('未匹配快递', $stored);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->get(route('business.pages.show', ['section' => 'courier-payables-final', 'page' => 'courier-bill-reconciliation', 'cb_view' => 'groups']))
->assertOk()->assertSeeText('曹县账务对接群')->assertSeeText('工作平台应付群')->assertDontSeeText('SEC-platform-1')->assertDontSeeText('platform-1');
$this->post(route('business.courier-payables-final.courier-bills.push-upload-links'), ['month' => '2026-11', 'group' => $groupId])->assertRedirect();
Http::assertSentCount(1);
Http::assertSent(fn ($request) => str_contains($request->url(), 'access_token=platform-1')
&& str_contains($request->url(), '&sign=') && str_contains($request['markdown']['text'], '运费账单上传 · 曹县韵达'));
$this->assertSame('work_platform', $notifier->configuration('曹县韵达')['config_source']);
$this->assertSame('曹县账务对接群', $notifier->configuration('曹县韵达')['group_name']);
$notifier->save('曹县韵达', '', '', false);
$this->assertSame('曹县账务对接群', $notifier->configuration('曹县韵达')['group_name']);
}
public function test_invalid_import_does_not_partially_replace_existing_settings(): void
{
$notifier = app(SupplierDingTalkNotifier::class);
$notifier->save('原配置', 'https://oapi.dingtalk.com/robot/send?access_token=original', '', false);
$before = setting('supplier_reconciliation.dingtalk_robots');
try {
$notifier->importCourierRobots([
'有效' => ['webhook' => 'https://oapi.dingtalk.com/robot/send?access_token=valid', 'secret' => ''],
'无效' => ['webhook' => 'https://example.test/robot/send?access_token=invalid', 'secret' => ''],
]);
$this->fail('Invalid robot must be rejected');
} catch (\Illuminate\Validation\ValidationException) {
$this->assertSame($before, setting('supplier_reconciliation.dingtalk_robots'));
}
}
private function robot(int $id, string $names, string $group): array
{
return ['Id' => $id, 'forModel' => '快递应付', 'businessKey' => $names, 'groupname' => $group,
'webAccesstoken' => 'platform-' . $id, 'Secret' => 'SEC-platform-' . $id, 'modifytime' => '2026-12-03 08:00:00'];
}
}