diff --git a/app/Console/Commands/SyncCourierOnboardingDingTalkProfiles.php b/app/Console/Commands/SyncCourierOnboardingDingTalkProfiles.php new file mode 100644 index 00000000..cf461ddc --- /dev/null +++ b/app/Console/Commands/SyncCourierOnboardingDingTalkProfiles.php @@ -0,0 +1,68 @@ +info('入驻钉钉对接未启用。'); + + return self::SUCCESS; + } + $limit = max(1, min(50, (int) $this->option('limit'))); + $cursorKey = 'courier-onboarding:dingtalk-profile-cursor'; + $cursor = (int) Cache::get($cursorKey, 0); + $query = $profiles->candidates(); + $records = (clone $query)->where('id', '>', $cursor)->orderBy('id')->limit($limit)->get(); + if ($records->isEmpty() && $cursor > 0) { + $records = $query->orderBy('id')->limit($limit)->get(); + } + if ($records->isEmpty()) { + $this->info('没有需要同步的入驻审批。'); + + return self::SUCCESS; + } + try { + $token = $client->accessToken(); + } catch (CourierOnboardingDingTalkException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + $started = microtime(true); + $counts = ['synced' => 0, 'pending' => 0, 'closed' => 0, 'skipped' => 0, 'failed' => 0]; + foreach ($records as $record) { + // 两分钟调度内最多执行90秒,单接口自带8秒超时。 + if (microtime(true) - $started >= 90) { + break; + } + try { + $result = $profiles->synchronize($record->company_id, $record->id, $token); + $counts[$result]++; + } catch (Throwable $exception) { + $counts['failed']++; + $message = $exception instanceof CourierOnboardingDingTalkException + ? $exception->getMessage() : '钉钉快递资料同步异常,请联系管理员核查。'; + $profiles->recordFailure($record, $message); + } + // 每次从上次结束位置继续,避免前面的待审批单一直占满查询批次。 + Cache::put($cursorKey, $record->id, now()->addDay()); + } + $this->info('快递资料同步:' . json_encode($counts, JSON_UNESCAPED_UNICODE)); + + return $counts['failed'] > 0 ? self::FAILURE : self::SUCCESS; + } +} diff --git a/app/Http/Controllers/Business/CourierOnboardings.php b/app/Http/Controllers/Business/CourierOnboardings.php index 7d17a434..28165320 100644 --- a/app/Http/Controllers/Business/CourierOnboardings.php +++ b/app/Http/Controllers/Business/CourierOnboardings.php @@ -32,7 +32,8 @@ class CourierOnboardings extends Controller 'invite_label' => ['nullable', 'string', 'max:100'], 'valid_days' => ['nullable', 'integer', 'min:1', 'max:180'], 'workplatform_expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_\-]+$/'], - ...CourierOnboarding::profileRules(), + // 资料由内部人员在钉钉后续节点补充;兼容旧请求中明确提交的字段。 + ...CourierOnboarding::profileRules(true), ], [ 'courier_name.required' => '请先定好系统快递名称(需与报价名、发货数据里的快递名称一致)。', 'workplatform_expcode.required' => '请填写快递公司代码(与快递资料「快递公司代码」一致)。', diff --git a/app/Models/Business/CourierOnboarding.php b/app/Models/Business/CourierOnboarding.php index 7949b2fd..439924e4 100644 --- a/app/Models/Business/CourierOnboarding.php +++ b/app/Models/Business/CourierOnboarding.php @@ -32,7 +32,7 @@ class CourierOnboarding extends Model ]; /** - * 生成二维码时我方必填的快递资料(快递方看不到),直接对齐到快递资料。 + * 内部快递资料(快递方看不到),由钉钉审批通过后回传并对齐到快递资料。 * 字段 => [名称, 可选值(null 为自由填写)] */ public const PROFILE_FIELDS = [ @@ -50,7 +50,7 @@ class CourierOnboarding extends Model ]; /** - * 校验规则:生成二维码时全部必填;入驻详情里修改时,提交了哪项就校验哪项(不能清空)。 + * 完整资料校验;onlyPresent 用于兼容邀请请求及详情修改,仅校验实际提交的项。 * * @return array> */ diff --git a/app/Models/Business/CourierOnboardingEvent.php b/app/Models/Business/CourierOnboardingEvent.php index 466104cf..2be41d65 100644 --- a/app/Models/Business/CourierOnboardingEvent.php +++ b/app/Models/Business/CourierOnboardingEvent.php @@ -33,6 +33,9 @@ class CourierOnboardingEvent extends Model 'dingtalk_started' => '已发起钉钉审批', 'dingtalk_failed' => '钉钉审批发起失败', 'dingtalk_unknown' => '钉钉审批结果待核查', + 'dingtalk_profile_synced' => '钉钉快递资料已同步', + 'dingtalk_profile_failed' => '钉钉快递资料同步待处理', + 'dingtalk_profile_closed' => '钉钉审批未通过,未同步资料', 'first_approved' => '初审通过', 'returned' => '退回补件', 'final_approved' => '财务复审通过', diff --git a/app/Support/CourierOnboardingDingTalk.php b/app/Support/CourierOnboardingDingTalk.php index bc7e0c29..64588511 100644 --- a/app/Support/CourierOnboardingDingTalk.php +++ b/app/Support/CourierOnboardingDingTalk.php @@ -118,6 +118,7 @@ class CourierOnboardingDingTalk $values['原因'] = '快递方已提交入驻资料,申请开通快递合作。' . "\n" . $this->marker($record) . "\n主体:" . $record->company_full_name . "\n业务类型:" . $record->service_type . "\n对接人:" . $record->contact_name . "\n资料详情(登录财务系统查看):" . $detailUrl + . "\n快递类型、合作方式等内部快递资料请在后续审批节点填写,审批通过后回传财务系统。" . "\n报价签署及回传沿用财务系统的易签宝流程,无需重复上传报价单原件。"; // 系统对接方式、账号密码由后续节点补充;不传原件、占位密码或公开扫码链接。 diff --git a/app/Support/CourierOnboardingDingTalkProfiles.php b/app/Support/CourierOnboardingDingTalkProfiles.php new file mode 100644 index 00000000..e04901cc --- /dev/null +++ b/app/Support/CourierOnboardingDingTalkProfiles.php @@ -0,0 +1,96 @@ +disableCache() + ->whereNotNull('dingtalk_instance_id')->where('dingtalk_instance_id', '<>', '') + ->whereNotIn('status', [CourierOnboarding::STATUS_CANCELLED, CourierOnboarding::STATUS_REJECTED]) + ->whereDoesntHave('events', fn (Builder $query) => $query->withoutGlobalScope(\App\Scopes\Company::class) + ->withTrashed()->whereIn('event_type', self::FINISHED_EVENTS)); + } + + public function synchronize(int $companyId, int $id, string $token): string + { + $record = $this->candidates()->companyId($companyId)->find($id); + if ($record === null) { + return 'skipped'; + } + $instanceId = (string) $record->dingtalk_instance_id; + $snapshot = $this->client->instance($token, $instanceId); + $values = collect($snapshot['formComponentValues'] ?? [])->pluck('value', 'name')->all(); + $marker = '[财务入驻:' . $record->company_id . ':' . $record->id . ':' . $record->number . ']'; + if (($snapshot['originatorUserId'] ?? '') !== config('courier_onboarding.dingtalk.originator_user_id') + || ! is_string($values['原因'] ?? null) || ! str_contains($values['原因'], $marker)) { + throw new CourierOnboardingDingTalkException('钉钉审批与入驻申请不匹配,未同步资料。'); + } + $status = strtoupper((string) ($snapshot['status'] ?? '')); + if (! in_array($status, ['COMPLETED', 'TERMINATED'], true)) { + return 'pending'; + } + $approved = $status === 'COMPLETED' && strtolower((string) ($snapshot['result'] ?? '')) === 'agree'; + $profile = []; + if ($approved) { + foreach (CourierOnboarding::PROFILE_FIELDS as $field => [$label]) { + $value = $values[$label] ?? null; + // 仅接受约定的普通文本值,不接收表格、文件或账号密码。 + $profile[$field] = is_string($value) ? trim($value) : null; + } + $validator = Validator::make($profile, CourierOnboarding::profileRules(), [], CourierOnboarding::profileAttributes()); + if ($validator->fails()) { + $fields = array_map(fn (string $field): string => CourierOnboarding::PROFILE_FIELDS[$field][0], array_keys($validator->errors()->messages())); + throw new CourierOnboardingDingTalkException('钉钉审批中的快递资料缺失或格式不正确:' . implode('、', $fields) . '。请补齐后等待重新同步。'); + } + } + + return DB::transaction(function () use ($companyId, $id, $instanceId, $approved, $profile): string { + $record = $this->candidates()->companyId($companyId)->lockForUpdate()->find($id); + if ($record === null || $record->dingtalk_instance_id !== $instanceId) { + return 'skipped'; + } + if ($approved) { + $record->update($profile); + } + $this->event($record, $approved ? 'dingtalk_profile_synced' : 'dingtalk_profile_closed', + $approved ? '钉钉审批已通过,内部快递资料已同步到本入驻申请及快递资料。' : '钉钉审批未通过或已终止,保留财务系统原有资料及审核状态。'); + + return $approved ? 'synced' : 'closed'; + }); + } + + public function recordFailure(CourierOnboarding $record, string $message): void + { + $latest = CourierOnboardingEvent::allCompanies()->companyId($record->company_id) + ->where('onboarding_id', $record->id)->where('event_type', 'dingtalk_profile_failed')->latest('id')->first(); + if ($latest?->note !== $message) { + $this->event($record, 'dingtalk_profile_failed', $message); + } + } + + private function event(CourierOnboarding $record, string $type, string $note): void + { + CourierOnboardingEvent::create([ + 'company_id' => $record->company_id, 'onboarding_id' => $record->id, + 'event_type' => $type, 'from_status' => $record->status, 'to_status' => $record->status, + 'actor_type' => 'system', 'note' => $note, + ]); + } +} diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 3a64e8d3..d35eace4 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -234,6 +234,8 @@ CRON_TZ=Asia/Shanghai # 当前退款状态在上面的分钟任务中优先增量刷新。 0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 +# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。 +*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1 # 财务台账:每天 02:30 同步 AI 库动账并重算流水;10:30 生成前一晚店铺余额快照。 30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1 30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index 71944946..3b2f0ee2 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -238,6 +238,8 @@ CRON_TZ=Asia/Shanghai # 当前退款状态在上面的分钟任务中优先增量刷新。 0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 +# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。 +*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1 # 财务台账:每天 02:30 同步 AI 库动账并重算流水;10:30 生成前一晚店铺余额快照。 30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1 30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1 diff --git a/docs/快递入驻钉钉自动发起.md b/docs/快递入驻钉钉自动发起.md index fc03fe32..33cb6e99 100644 --- a/docs/快递入驻钉钉自动发起.md +++ b/docs/快递入驻钉钉自动发起.md @@ -18,11 +18,23 @@ COURIER_ONBOARDING_PUBLIC_URL=https://caiwu.jiansuntuzhi.cn:8442 ## 表单内容 -已填写的快递资料按同名字段传入;电话沿用该流程已有实例的手机号文本格式;业务类型「快递」对应物流「否」,「快运 / 大件专线」对应「是」,「其他」不猜测。已有工作平台账号时填入绑定快递名称。原因包含入驻编号、主体、联系人和需要登录财务系统的详情地址,不包含免登录扫码凭证、银行账号或证件号码。 +生成二维码仅填写快递公司代码、系统快递名称、备注和有效期。快递类型、合作方式、扣款方式等11项内部资料由钉钉后续节点补充,不再要求在发码前填写。旧申请已有的资料仍按同名字段带入;电话沿用该流程已有实例的手机号文本格式;业务类型「快递」对应物流「否」,「快运 / 大件专线」对应「是」,「其他」不猜测。已有工作平台账号时填入绑定快递名称。原因包含入驻编号、主体、联系人和需要登录财务系统的详情地址,不包含免登录扫码凭证、银行账号或证件号码。 不上传报价单原件,报价沿用易签宝签署和回传。系统对接方式和三组账号密码由内部后续审批节点补充,不以占位内容代填。其他文件留在财务系统资料页查看。本次不增加钉盘上传权限。 -钉钉模板应允许上述字段在发起时留空,并为负责人员配置后续填写权限;如钉钉返回必填或表单配置错误,在模板调整后对明确失败的申请单独重试,不填造假的账号或附件来绕过校验。 +钉钉模板应允许上述字段在发起时留空,并为负责人员配置后续填写权限;11项内部快递资料须在最终通过前填写完整。如钉钉返回必填或表单配置错误,在模板调整后对明确失败的申请单独重试,不填造假的账号或附件来绕过校验。 + +## 内部快递资料回传 + +生产每2分钟查询一次已关联的审批,每轮最多25单,最多运行115秒;命令内部在90秒时停止继续查询,单次HTTP请求上限8秒。采用缓存游标轮转,前面的未完成审批不会长期占满批次。没有已关联审批时不访问钉钉。当前核查规模为2条入驻、0条关联审批;真实审批完成后的回传仍需验收。 + +仅当审批状态为 `COMPLETED`、结果为 `agree`,且发起人与原因中的入驻标识匹配时,同步11项允许的内部字段。先完整校验再原子写入入驻表,现有快递资料页面按快递公司代码读取这些值。缺少字段、无效选项或邮箱格式错误时不部分覆盖,处理记录提示需补齐的字段。不会复制账号、密码、附件、账户或证件资料,也不会将钉钉结果直接转换为财务系统审核结果。 + +同一张已通过审批只自动同步一次,保留成功记录;之后人工修正的数据不会被重复轮询覆盖。拒绝或终止仅记录关闭,保留原资料。详情中保留人工修正入口。此功能复用现有入驻表、事件表和快递资料读取逻辑,无数据库迁移。 + +```bash +php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 +``` ## 记录与故障恢复 diff --git a/resources/views/business/pages/courier-payables/courier-onboarding-show.blade.php b/resources/views/business/pages/courier-payables/courier-onboarding-show.blade.php index 121ae8e4..2c7c7f9c 100644 --- a/resources/views/business/pages/courier-payables/courier-onboarding-show.blade.php +++ b/resources/views/business/pages/courier-payables/courier-onboarding-show.blade.php @@ -406,11 +406,11 @@
-

快递资料(我方填写)

+

快递资料(钉钉回传)

@csrf -

快递方看不到。保存后对齐到快递资料(扣款方式、网点代码等),代码 {{ $onboarding->workplatform_expcode ?: '未填' }}。

+

由内部人员在钉钉流程填写,审批通过后自动同步。这里保留人工修正入口,快递方看不到。代码 {{ $onboarding->workplatform_expcode ?: '未填' }}。

@foreach (\App\Models\Business\CourierOnboarding::PROFILE_FIELDS as $field => [$label, $options])
@@ -438,7 +438,7 @@
@if ($onboarding->erpPending()) -

下一步:ERP 专员开通发货系统账号后,在下方「手动补录」里填 ERP账户ID 保存即可(快递公司代码沿用生成二维码时填的)。快递类型、扣款方式等在上方「快递资料(我方填写)」维护,直接对齐到快递资料。

+

下一步:ERP 专员开通发货系统账号后,在下方「手动补录」里填 ERP账户ID 保存即可(快递公司代码沿用生成二维码时填的)。快递类型、扣款方式等由钉钉审批通过后回传,直接对齐到快递资料。

@else
快递代码
{{ $onboarding->workplatform_expcode }}
diff --git a/resources/views/business/pages/courier-payables/courier-onboarding.blade.php b/resources/views/business/pages/courier-payables/courier-onboarding.blade.php index 34fd1037..6ab68f56 100644 --- a/resources/views/business/pages/courier-payables/courier-onboarding.blade.php +++ b/resources/views/business/pages/courier-payables/courier-onboarding.blade.php @@ -44,9 +44,6 @@ .co-help { color:var(--co-muted); font-size:.68rem; line-height:1.5; } .co-error { color:#b80000; font-size:.72rem; } .co-invite__row { display:grid; grid-template-columns:minmax(0,1fr) 7rem; gap:.6rem; } .co-hero__main { display:grid; gap:1rem; align-content:start; min-width:0; } - .co-profile-grid { display:grid; grid-template-columns:repeat(3, minmax(0,1fr)); gap:.7rem .8rem; padding:1rem 1.15rem 1.15rem; } - @media (max-width: 1100px) { .co-profile-grid { grid-template-columns:repeat(2, minmax(0,1fr)); } } - @media (max-width: 560px) { .co-profile-grid { grid-template-columns:1fr; } } .co-button { display:inline-flex; align-items:center; justify-content:center; gap:.35rem; height:2.2rem; padding:0 .8rem; border:1px solid var(--co-border); border-radius:.45rem; background:#fff; color:var(--co-ink); font:inherit; font-weight:600; text-decoration:none; white-space:nowrap; cursor:pointer; } .co-button .material-icons-outlined { font-size:1rem; } .co-button--primary { border-color:var(--co-accent); background:var(--co-accent); color:#fff; } .co-button--primary:hover { background:#6a5129; } .co-toolbar { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:.75rem; padding:.75rem 1.15rem; border-bottom:1px solid var(--co-border); background:#fffdf8; } @@ -90,37 +87,13 @@ 快递方无需账号,扫码即可填写
    -
  1. 生成二维码填快递公司代码、系统快递名称和快递资料,生成后发给快递方
  2. +
  3. 生成二维码填快递公司代码和系统快递名称,生成后发给快递方
  4. 快递扫码填写主体、联系人、结算账户、报价、资质照片
  5. -
  6. 对接人初审资料不全可退回,快递用原码补件
  7. +
  8. 对接人初审提交后自动发起钉钉审批,内部快递资料在流程中补充
  9. 财务复审确认系统快递名称,首版报价进报价管理
  10. 签署并开通协议签署后开通,信息对齐到快递资料
-
-
-

快递资料

- 全部必填 · 我方填写,快递方看不到;生成后对齐到快递资料,入驻详情里也能改 -
-
- @foreach (\App\Models\Business\CourierOnboarding::PROFILE_FIELDS as $field => [$label, $options]) -
- - @if ($options !== null) - - @else - - @endif - @error($field){{ $message }}@enderror -
- @endforeach -
-
@csrf @@ -128,6 +101,7 @@

生成入驻二维码

+

快递类型、合作方式等内部资料在钉钉审批中填写,通过后自动同步到快递资料。

diff --git a/tests/Feature/Business/CourierOnboardingDingTalkProfilesTest.php b/tests/Feature/Business/CourierOnboardingDingTalkProfilesTest.php new file mode 100644 index 00000000..5a00f31e --- /dev/null +++ b/tests/Feature/Business/CourierOnboardingDingTalkProfilesTest.php @@ -0,0 +1,200 @@ +company->makeCurrent(); + config(['courier_onboarding.dingtalk' => [ + 'enabled' => true, 'client_id' => 'test-app', 'client_secret' => 'test-secret', + 'process_code' => 'PROC-TEST', 'originator_user_id' => 'originator-test', 'dept_id' => 123, + ]]); + Http::preventStrayRequests(); + } + + public function test_approved_profile_flows_to_courier_information_without_copying_passwords_or_changing_review(): void + { + $record = $this->record(); + $snapshot = $this->snapshot($record); + $snapshot['formComponentValues'][] = ['name' => '财务账单密码', 'value' => 'must-not-be-saved']; + $this->fake([$record->dingtalk_instance_id => $snapshot]); + $this->assertSame('synced', $this->service()->synchronize($record->company_id, $record->id, 'test-token')); + $fresh = $record->fresh(); + foreach ($this->profile() as $field => $value) { + $this->assertSame($value, $fresh->{$field}); + } + $this->assertSame(CourierOnboarding::STATUS_SUBMITTED, $fresh->status); + $row = (object) ['undefined3' => null, '_info' => ['onboarding' => $fresh]]; + $this->assertSame('运费', app(CourierProfileData::class)->fillFromOnboarding($row)->undefined3); + $this->assertSame('00123', app(CourierProfileData::class)->onboardingNetwork($fresh)->netcode); + $this->assertSame(1, $record->events()->where('event_type', 'dingtalk_profile_synced')->count()); + $this->assertStringNotContainsString('must-not-be-saved', json_encode($fresh->getAttributes())); + $this->assertStringNotContainsString('must-not-be-saved', $record->events()->firstOrFail()->note); + // 审批完成只同步一次,之后的人工修正不会被轮询覆盖。 + $fresh->update(['courier_email' => 'corrected@example.com']); + $this->assertSame('skipped', $this->service()->synchronize($record->company_id, $record->id, 'test-token')); + $this->assertSame('corrected@example.com', $record->fresh()->courier_email); + Http::assertSentCount(1); + } + + public function test_pending_refused_and_terminated_approvals_do_not_apply_profile(): void + { + foreach ([['RUNNING', 'agree', 'pending'], ['COMPLETED', 'refuse', 'closed'], ['TERMINATED', '', 'closed']] as [$status, $result, $expected]) { + $record = $this->record(); + $record->update(['network_region' => '原地区']); + $snapshots[$record->dingtalk_instance_id] = [...$this->snapshot($record), 'status' => $status, 'result' => $result]; + $records[] = [$record, $expected]; + } + $this->fake($snapshots); + foreach ($records as [$record, $expected]) { + $this->assertSame($expected, $this->service()->synchronize($record->company_id, $record->id, 'test-token')); + $this->assertSame('原地区', $record->fresh()->network_region); + $this->assertSame(CourierOnboarding::STATUS_SUBMITTED, $record->fresh()->status); + } + } + + public function test_wrong_company_originator_and_marker_never_write_profile(): void + { + $record = $this->record(); + $wrongOriginator = $this->record(); + $wrongMarker = $this->record(); + $this->fake([ + $record->dingtalk_instance_id => $this->snapshot($record), + $wrongOriginator->dingtalk_instance_id => [...$this->snapshot($wrongOriginator), 'originatorUserId' => 'other-user'], + $wrongMarker->dingtalk_instance_id => $this->snapshot($record), + ]); + $this->assertSame('skipped', $this->service()->synchronize($record->company_id + 1, $record->id, 'test-token')); + foreach ([$wrongOriginator, $wrongMarker] as $candidate) { + try { + $this->service()->synchronize($candidate->company_id, $candidate->id, 'test-token'); + $this->fail('不匹配的审批不可写入资料'); + } catch (CourierOnboardingDingTalkException) { + $this->assertNull($candidate->fresh()->courier_category); + } + } + $this->assertSame(0, CourierOnboardingEvent::query()->count()); + Http::assertSentCount(2); + } + + public function test_incomplete_or_invalid_profile_is_atomic_and_can_sync_after_it_is_corrected(): void + { + $record = $this->record(); + $invalid = $this->snapshot($record); + $invalid['formComponentValues'] = array_values(array_filter($invalid['formComponentValues'], fn (array $field): bool => $field['name'] !== '快递邮箱')); + $invalid['formComponentValues'][] = ['name' => '快递邮箱', 'value' => 'invalid-email']; + Http::fake(['*/workflow/processInstances*' => Http::sequence()->push(['result' => $invalid])->push(['result' => $this->snapshot($record)])]); + try { + $this->service()->synchronize($record->company_id, $record->id, 'test-token'); + $this->fail('无效资料不可部分写入'); + } catch (CourierOnboardingDingTalkException $exception) { + $this->assertStringContainsString('快递邮箱', $exception->getMessage()); + $this->assertNull($record->fresh()->courier_category); + $this->assertNull($record->fresh()->network_code); + } + $this->assertSame('synced', $this->service()->synchronize($record->company_id, $record->id, 'test-token')); + } + + public function test_polling_rotates_a_bounded_batch_and_does_not_create_any_approval(): void + { + $first = $this->record(); + $second = $this->record(); + $this->fake([ + $first->dingtalk_instance_id => [...$this->snapshot($first), 'status' => 'RUNNING'], + $second->dingtalk_instance_id => $this->snapshot($second), + ]); + $this->artisan('courier-onboarding:sync-dingtalk-profiles', ['--limit' => 1])->assertSuccessful(); + $this->assertNull($first->fresh()->courier_category); + $this->assertNull($second->fresh()->courier_category); + $this->artisan('courier-onboarding:sync-dingtalk-profiles', ['--limit' => 1])->assertSuccessful(); + $this->assertSame('内采快递', $second->fresh()->courier_category); + $this->artisan('courier-onboarding:sync-dingtalk-profiles', ['--limit' => 1])->assertSuccessful(); + $this->assertSame($first->id, Cache::get('courier-onboarding:dingtalk-profile-cursor')); + Http::assertNotSent(fn (Request $request): bool => $request->method() === 'POST' && str_contains($request->url(), '/workflow/')); + } + + public function test_polling_records_one_sanitized_failure_and_keeps_processing_other_records(): void + { + $failed = $this->record(); + $success = $this->record(); + $snapshots = [$success->dingtalk_instance_id => $this->snapshot($success)]; + $this->fake($snapshots); + $this->artisan('courier-onboarding:sync-dingtalk-profiles')->assertFailed(); + $this->assertSame('内采快递', $success->fresh()->courier_category); + $this->artisan('courier-onboarding:sync-dingtalk-profiles')->assertFailed(); + $this->assertSame(1, $failed->events()->where('event_type', 'dingtalk_profile_failed')->count()); + $this->assertStringNotContainsString('sensitive-data', $failed->events()->firstOrFail()->note); + } + + public function test_disabled_or_no_candidates_make_no_api_calls_and_closed_local_records_are_excluded(): void + { + config(['courier_onboarding.dingtalk.enabled' => false]); + $this->artisan('courier-onboarding:sync-dingtalk-profiles')->assertSuccessful(); + config(['courier_onboarding.dingtalk.enabled' => true]); + $record = $this->record(); + $record->update(['status' => CourierOnboarding::STATUS_CANCELLED]); + $this->artisan('courier-onboarding:sync-dingtalk-profiles')->assertSuccessful(); + Http::assertNothingSent(); + } + + private function record(): CourierOnboarding + { + return CourierOnboarding::create([ + 'company_id' => $this->company->id, 'number' => 'RZ-SYNC-' . uniqid(), 'token' => bin2hex(random_bytes(20)), + 'status' => CourierOnboarding::STATUS_SUBMITTED, 'courier_name' => '测试快递', 'workplatform_expcode' => 'SYNC-' . uniqid(), + 'dingtalk_instance_id' => 'instance-' . uniqid(), + ]); + } + + private function profile(): array + { + return [ + 'courier_category' => '内采快递', 'cooperation_mode' => '保丢保损', 'courier_attribute' => '简尚', + 'deduction_method' => '运费', 'waybill_type' => '系统对接', 'courier_email' => 'courier@example.com', + 'need_logistics_check' => '否', 'shipping_mode' => '一单一货', 'workplatform_account' => '新开', + 'network_code' => '00123', 'network_region' => '江苏省常州市', + ]; + } + + private function snapshot(CourierOnboarding $record): array + { + $fields = [['name' => '原因', 'value' => '[财务入驻:' . $record->company_id . ':' . $record->id . ':' . $record->number . ']']]; + foreach ($this->profile() as $field => $value) { + $fields[] = ['name' => CourierOnboarding::PROFILE_FIELDS[$field][0], 'value' => $value]; + } + + return ['status' => 'COMPLETED', 'result' => 'agree', 'originatorUserId' => 'originator-test', 'formComponentValues' => $fields]; + } + + private function fake(array $snapshots): void + { + Http::fake(function (Request $request) use ($snapshots) { + if (str_ends_with($request->url(), '/oauth2/accessToken')) { + return Http::response(['accessToken' => 'test-token']); + } + if ($request->method() === 'GET' && str_contains($request->url(), '/workflow/processInstances')) { + $id = $request['processInstanceId']; + + return isset($snapshots[$id]) ? Http::response(['result' => $snapshots[$id]]) : Http::response(['message' => 'sensitive-data'], 503); + } + throw new \LogicException('测试中禁止创建审批或请求其他接口'); + }); + } + + private function service(): CourierOnboardingDingTalkProfiles + { + return app(CourierOnboardingDingTalkProfiles::class); + } +} diff --git a/tests/Feature/Business/CourierOnboardingWorkflowTest.php b/tests/Feature/Business/CourierOnboardingWorkflowTest.php index 023ae253..c2a2b1cf 100644 --- a/tests/Feature/Business/CourierOnboardingWorkflowTest.php +++ b/tests/Feature/Business/CourierOnboardingWorkflowTest.php @@ -48,7 +48,10 @@ class CourierOnboardingWorkflowTest extends FeatureTestCase ->assertOk() ->assertSee('aria-label="快递入驻"', false) ->assertSeeText('生成入驻二维码') - ->assertSeeText('入驻流程'); + ->assertSeeText('入驻流程') + ->assertDontSee('id="co-profile-title"', false) + ->assertDontSee('name="courier_category"', false) + ->assertDontSee('name="network_region"', false); $this->withExceptionHandling()->loginAs() ->post(route('business.courier-onboardings.store'), ['invite_label' => '张经理']) @@ -1151,10 +1154,12 @@ class CourierOnboardingWorkflowTest extends FeatureTestCase $onboarding = CourierOnboarding::query()->where('workplatform_expcode', 'XKD10')->firstOrFail(); $this->assertSame(['外采快递', '损耗+运费', '519001'], [$onboarding->courier_category, $onboarding->deduction_method, $onboarding->network_code]); - // 快递资料全部必填。 + // 生成二维码不再要求提前填写钉钉后续节点的资料。 $this->withExceptionHandling()->loginAs()->post(route('business.courier-onboardings.store'), ['courier_name' => '新快递十一', 'workplatform_expcode' => 'XKD11']) - ->assertSessionHasErrors(['courier_category' => '请选择快递类型。', 'network_region' => '请填写网点所在地区。']); - $this->assertFalse(CourierOnboarding::query()->where('workplatform_expcode', 'XKD11')->exists()); + ->assertSessionHasNoErrors(); + $minimal = CourierOnboarding::query()->where('workplatform_expcode', 'XKD11')->firstOrFail(); + $this->assertNull($minimal->courier_category); + $this->assertNull($minimal->network_region); // 详情里修改时不能清空。 $this->withExceptionHandling()->loginAs()->post(route('business.courier-onboardings.internal', CourierOnboarding::query()->where('workplatform_expcode', 'XKD10')->firstOrFail()), ['courier_email' => '']) ->assertSessionHasErrors('courier_email'); @@ -1163,7 +1168,7 @@ class CourierOnboardingWorkflowTest extends FeatureTestCase ->assertOk()->assertSeeText('快递合作方式')->assertSeeText('保丢不保损')->assertSeeText('XKD10'); // 详情页可改;只改名称/对账人的旧表单不会清空这些字段。 - $this->loginAs()->get(route('business.courier-onboardings.show', $onboarding))->assertOk()->assertSeeText('快递资料(我方填写)'); + $this->loginAs()->get(route('business.courier-onboardings.show', $onboarding))->assertOk()->assertSeeText('快递资料(钉钉回传)'); $this->loginAs()->post(route('business.courier-onboardings.internal', $onboarding), ['reconciler' => '王会计'])->assertSessionHasNoErrors(); $this->assertSame('外采快递', $onboarding->fresh()->courier_category); $this->assertSame('新快递十', $onboarding->fresh()->courier_name); diff --git a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php index 1d05a916..074e6d0e 100644 --- a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php +++ b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php @@ -141,6 +141,8 @@ class BusinessMirrorScheduleTest extends TestCase $this->assertStringContainsString('esign:poll-signatures --quiet', $contents, $script); $this->assertStringContainsString('/run/caiwu-esign-polling.lock', $contents, $script); $this->assertSame(1, substr_count($contents, 'esign:poll-signatures --quiet'), $script); + $this->assertSame(1, substr_count($contents, 'courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet'), $script); + $this->assertStringContainsString('/run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115', $contents, $script); $this->assertSame(1, substr_count($contents, 'finance-ledger:sync-shop-data --balance-only --quiet'), $script); $this->assertStringContainsString( '# 财务台账:每天 02:30 同步 AI 库动账并重算流水;10:30 生成前一晚店铺余额快照。',