feat(种菜报销): 佣金人员可维护、自动放行检查、自动发通知、一键提交钉钉流程

- 报销佣金人员改为工作台维护(新增 / 移除 / 追加导入 / 导出),首次读取时自动导入以前上传的历史名单
- 去掉「去聚工单人工核对、勾选已核对」:改为放行检查(聚工单 20 分钟内同步过、额度已校验、
  规则不为空、自检全过、有可报销单),不通过不许导出 / 发通知 / 提交,并在页面列出原因
- 每天 11:20 汇总任务放行检查通过后自动发不予报销通知(@ 发起人,同一批不重发)
- 一键提交钉钉「种菜报销流程」(PROC-C5159B8D…):发起人李斯(按钉钉花名册查 userId),
  按钉钉表单实际结构自动填(收款费用明细 / 收款合计 / 收款人·开户行·账号=账号详见附件 /
  付款明细 / 报销类型=种菜核销),打款明细 xlsx 上传审批钉盘作附件;先可预览,
  缺必填 / 选项不匹配不许提交;同一账单日只提交一次,结果不确定记待核查
- 新配置 config/planting_reimbursement.php(凭据默认沿用快递入驻的财务系统钉钉应用,
  需补 PLANTING_DINGTALK_AGENT_ID)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UNTa9ohkCsVFACqjz3KMcG
This commit is contained in:
limeng 2026-12-01 05:56:51 +00:00
parent 17f5d7dfd3
commit b5244362a1
20 changed files with 1252 additions and 52 deletions

View File

@ -7,11 +7,12 @@ use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Repositories\PlantingReimbursementRepository as Repository;
use Modules\EcommerceFinance\Services\PlantingReimbursementAuditor as Auditor;
use Modules\EcommerceFinance\Services\PlantingReimbursementGate as Gate;
use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
use Throwable;
/** 每天 11:20 生成当天种菜报销批次,把核对数、可报销合计、要取消的单和自检结果推到钉钉群并 @ 报销人。只读,不改聚工单。 */
/** 每天 11:20 生成当天种菜报销批次:把可报销合计、要取消的单和放行检查结果推到钉钉群并 @ 报销人,并自动发不予报销通知(@ 发起人)。不改聚工单。 */
class PlantingReimbursementDailyDigest extends Command
{
protected $signature = 'planting-reimbursement:daily-digest
@ -46,7 +47,7 @@ class PlantingReimbursementDailyDigest extends Command
}
try {
[$title, $text] = $this->message($workbench, $repository, (int) $company->id, $date);
[$title, $text] = $this->message($workbench, $repository, $robot, (int) $company->id, $date, ! $this->option('dry-run'));
if ($this->option('dry-run')) {
$this->line($title . "\n" . $text);
continue;
@ -65,7 +66,7 @@ class PlantingReimbursementDailyDigest extends Command
}
/** @return array{0:string,1:string} */
private function message(Workbench $workbench, Repository $repository, int $companyId, string $date): array
private function message(Workbench $workbench, Repository $repository, Robot $robot, int $companyId, string $date, bool $sendNotices): array
{
$sync = $repository->syncStatus();
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
@ -86,7 +87,7 @@ class PlantingReimbursementDailyDigest extends Command
$result = $workbench->build($companyId, $date);
$s = $result['summary'];
$lines[] = '- 待处理(付款 ' . substr($result['window']['from'], 0, 10) . ' ~ ' . substr($result['window']['to'], 0, 10) . '):**' . $s['source']['count'] . ' 条 / ' . number_format((float) $s['source']['amount'], 2) . ' 元**,请先在聚工单核对';
$lines[] = '- 待处理(付款 ' . substr($result['window']['from'], 0, 10) . ' ~ ' . substr($result['window']['to'], 0, 10) . '):**' . $s['source']['count'] . ' 条 / ' . number_format((float) $s['source']['amount'], 2) . ' 元**';
$lines[] = '- 可报销:' . $s['counts'][Auditor::DECISION_PASS] . ' 条 / **' . number_format((float) $s['total'], 2) . ' 元**(三大天猫 ' . number_format((float) $s['group_amounts'][Auditor::GROUP_BIG_TMALL], 2) . ',其他 ' . number_format((float) $s['group_amounts'][Auditor::GROUP_OTHER], 2) . ')';
$lines[] = '- 取消工单:' . $s['counts'][Auditor::DECISION_CANCEL] . ' 条;待复查:' . $s['counts'][Auditor::DECISION_RECHECK] . ' 条';
$bad = array_column(array_filter($s['checks'], static fn (array $check): bool => ! $check['ok']), 'label');
@ -100,7 +101,20 @@ class PlantingReimbursementDailyDigest extends Command
if (($result['roster_source'] ?? '') === 'none') {
$lines[] = '- 取不到在职名单,收款人在职未校验';
}
$lines[] = '- [打开工作台核对](' . $url . ')';
// 自动发取消 / 待复查通知(@ 发起人;同一批已发过的不重发),放行检查不过就不发,等人看。
$gate = Gate::check($result, false);
if (! $gate['ok']) {
$lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']);
} elseif ($s['notices'] === []) {
$lines[] = '- 没有要取消或复查的工单';
} elseif ($sendNotices) {
$sent = $robot->sendNotices($companyId, $date, $s['notices']);
$lines[] = sprintf('- 已自动发不予报销通知:%d 人(之前已发 %d 人%s)', $sent['sent'], $sent['skipped'], $sent['failed'] > 0 ? ',失败 ' . $sent['failed'] . ' 人' : '');
}
if ($gate['ok'] && Gate::check($result)['ok']) {
$lines[] = '- 确认无误后在工作台点「提交钉钉流程」';
}
$lines[] = '- [打开工作台](' . $url . ')';
return [$title, implode("\n", $lines)];
}

View File

@ -5,7 +5,10 @@ namespace App\Http\Controllers\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\PlantingCommissionPeople as CommissionPeople;
use Modules\EcommerceFinance\Services\PlantingDingTalkSubmission as DingTalkSubmission;
use Modules\EcommerceFinance\Services\PlantingQuotaRules as QuotaRules;
use Modules\EcommerceFinance\Services\PlantingReimbursementGate as Gate;
use Modules\EcommerceFinance\Services\PlantingReimbursementReferences as References;
use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbookExporter as Exporter;
@ -48,20 +51,18 @@ class PlantingReimbursementWorkbench extends Controller
{
abort_unless(isset(Exporter::TYPES[$type]), 404);
$filters = $page->filters();
// 导出前必须先在聚工单核对条数、金额一致。
if (request('verified') !== '1') {
return redirect()->route('business.pages.show', [
'company_id' => company_id(), 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench',
] + array_diff_key($filters, ['decision' => true]))->with('error', '请先在聚工单按同样条件查询,核对条数和最终报销金额一致后,勾选「已核对」再导出。');
}
try {
$result = $page->build($filters);
$spreadsheet = $exporter->build($type, $result);
} catch (\Throwable $exception) {
report($exception);
abort(503, '聚工单镜像未就绪,未生成不完整的导出文件,请稍后重试。');
}
// 放行检查替代原来的「去聚工单人工核对、勾选已核对」。
$gate = Gate::check($result);
if (! $gate['ok']) {
return $this->back(request())->with('error', '暂不能导出:' . implode(';', $gate['reasons']) . '。');
}
$spreadsheet = $exporter->build($type, $result);
return response()->streamDownload(static function () use ($spreadsheet): void {
(new Xlsx($spreadsheet))->save('php://output');
@ -85,16 +86,16 @@ class PlantingReimbursementWorkbench extends Controller
return $this->back($request)->with('success', '钉钉机器人设置已保存。');
}
/** 按发起人把取消 / 待复查通知发到钉钉群(须先勾选已与聚工单核对)。 */
/** 按发起人把取消 / 待复查通知发到钉钉群(放行检查通过才发;每天 11:20 也会自动发)。 */
public function notify(Request $request, PageData $page, Robot $robot)
{
$filters = $page->filters();
if ($request->input('verified') !== '1') {
return $this->back($request)->with('error', '请先在聚工单核对条数和金额一致,勾选「已核对」后再发通知。');
}
try {
$result = $page->build($filters);
$gate = Gate::check($result, false);
if (! $gate['ok']) {
return $this->back($request)->with('error', '暂不能发通知:' . implode(';', $gate['reasons']) . '。');
}
$sent = $robot->sendNotices((int) company_id(), $filters['date'], $result['summary']['notices'], $request->boolean('force'));
} catch (\Throwable $exception) {
report($exception);
@ -159,6 +160,82 @@ class PlantingReimbursementWorkbench extends Controller
}, '种菜额度规则_' . now()->format('Ymd') . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
/** 报销佣金人员:新增一人。 */
public function addCommission(Request $request, CommissionPeople $people)
{
try {
$name = $people->add((int) company_id(), (string) $request->input('name', ''), (string) $request->input('platform', ''), (string) $request->input('remark', ''), optional(user())->id);
} catch (InvalidArgumentException $exception) {
return $this->back($request, 'pwb-commission')->withInput()->with('error', '报销佣金人员保存失败:' . $exception->getMessage());
}
return $this->back($request, 'pwb-commission')->with('success', '已把 ' . $name . ' 加入报销佣金人员。');
}
public function removeCommission(Request $request, CommissionPeople $people)
{
try {
$people->remove((int) company_id(), (string) $request->input('name', ''), optional(user())->id);
} catch (InvalidArgumentException $exception) {
return $this->back($request, 'pwb-commission')->with('error', $exception->getMessage());
}
return $this->back($request, 'pwb-commission')->with('success', '已从报销佣金人员中移除 ' . trim((string) $request->input('name')) . '。');
}
/** 用以前的「报销佣金人员」表追加名单,已有的不重复加。 */
public function importCommission(Request $request, CommissionPeople $people)
{
$request->validate(['file' => ['required', 'file', 'max:51200']]);
$file = $request->file('file');
try {
$result = $people->import((int) company_id(), (string) $file->getRealPath(), (string) $file->getClientOriginalName(), optional(user())->id);
} catch (InvalidArgumentException $exception) {
return $this->back($request, 'pwb-commission')->with('error', '报销佣金人员导入失败:' . $exception->getMessage());
}
return $this->back($request, 'pwb-commission')->with('success', sprintf('报销佣金人员导入:新增 %d 人,已在名单里 %d 人。', $result['added'], $result['skipped']));
}
public function exportCommission(CommissionPeople $people)
{
$csv = $people->exportCsv((int) company_id());
return response()->streamDownload(static function () use ($csv): void {
echo $csv;
}, '报销佣金人员_' . now()->format('Ymd') . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
/** 预览钉钉表单:页面带上 ding_preview=1 时读取钉钉表单结构并按本批填好展示,不上传、不发起。 */
public function previewDingTalk(Request $request)
{
return redirect()->to(route('business.pages.show', array_filter([
'company_id' => company_id(), 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench',
'date' => (string) $request->input('date', ''), 'paid_from' => (string) $request->input('paid_from', ''),
'scope' => (string) $request->input('scope', ''), 'ding_preview' => '1',
], static fn ($v) => $v !== '')) . '#pwb-ding');
}
/** 一键提交钉钉「种菜报销流程」(发起人李斯)。 */
public function submitDingTalk(Request $request, PageData $page, DingTalkSubmission $submission)
{
$filters = $page->filters();
try {
$result = $page->build($filters);
$record = $submission->submit((int) company_id(), $result, optional(user())->id, $request->boolean('confirm_no_duplicate'));
} catch (\Modules\EcommerceFinance\Services\PlantingDingTalkUncertainException $exception) {
return $this->back($request, 'pwb-ding')->with('error', $exception->getMessage());
} catch (\RuntimeException $exception) {
return $this->back($request, 'pwb-ding')->with('error', '钉钉流程没有提交:' . $exception->getMessage());
} catch (\Throwable $exception) {
report($exception);
return $this->back($request, 'pwb-ding')->with('error', '钉钉流程没有提交,请稍后重试。');
}
return $this->back($request, 'pwb-ding')->with('success', sprintf('已以 %s 的名义提交钉钉「种菜报销流程」:%s 元,审批编号 %s。', $record['originator'], number_format((float) $record['total'], 2), $record['instance_id']));
}
private function back(Request $request, string $fragment = '')
{
return redirect()->to(route('business.pages.show', array_filter([

View File

@ -0,0 +1,17 @@
<?php
return [
// 种菜报销工作台一键提交钉钉「种菜报销流程」。应用凭据默认沿用「财务系统」钉钉应用(快递入驻同一个)。
'dingtalk' => [
'enabled' => (bool) env('PLANTING_DINGTALK_ENABLED', true),
'client_id' => env('PLANTING_DINGTALK_CLIENT_ID', env('COURIER_ONBOARDING_DINGTALK_CLIENT_ID')),
'client_secret' => env('PLANTING_DINGTALK_CLIENT_SECRET', env('COURIER_ONBOARDING_DINGTALK_CLIENT_SECRET')),
// 上传审批附件(打款明细)要用应用的 AgentId。
'agent_id' => env('PLANTING_DINGTALK_AGENT_ID'),
'process_code' => env('PLANTING_DINGTALK_PROCESS_CODE', 'PROC-C5159B8D-F412-4DF8-981D-64EBB8D03EB6'),
// 发起人花名(2026-12-01 财务确认:李斯);钉钉 userId 按钉钉花名册自动查,查不到时可直接配置。
'originator_flower_name' => env('PLANTING_DINGTALK_ORIGINATOR', '李斯'),
'originator_user_id' => env('PLANTING_DINGTALK_ORIGINATOR_USER_ID'),
'dept_id' => env('PLANTING_DINGTALK_DEPT_ID'),
],
];

View File

@ -0,0 +1,134 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Facades\Storage;
use InvalidArgumentException;
use RuntimeException;
/**
* 种菜报销「报销佣金人员」名单:发起人在名单里才能报佣金。
*
* 2026-12-01 起在工作台维护(新增 / 删除 / 导入),不再每次上传整表。第一次读取时,用以前上传过的历史名单
* (planting-reimbursement-references/<公司>/commission.json)初始化。
* 存为 storage/app/planting-reimbursement-references/<公司>/commission-people.json(持久卷),不建表。
*/
class PlantingCommissionPeople
{
public const FILE = 'commission-people.json';
/** @var array<int,array<string,mixed>> */
private array $loaded = [];
public function __construct(private readonly PlantingReimbursementReferences $references) {}
/** @return array{people:list<array{name:string,platform:string,remark:string,added_at:?string}>,source:string,updated_at:?string} */
public function document(int $companyId): array
{
if (isset($this->loaded[$companyId])) {
return $this->loaded[$companyId];
}
$disk = Storage::disk('local');
$document = $disk->exists($this->path($companyId)) ? json_decode((string) $disk->get($this->path($companyId)), true) : null;
if (! is_array($document) || ! is_array($document['people'] ?? null)) {
// 首次:用历史上传的名单初始化。
$people = [];
foreach (array_keys($this->references->nameSet($companyId, PlantingReimbursementReferences::KIND_COMMISSION)) as $name) {
$people[] = ['name' => (string) $name, 'platform' => '', 'remark' => '历史上传名单导入', 'added_at' => null];
}
$document = ['people' => $people, 'source' => $people === [] ? 'empty' : 'history', 'updated_at' => null];
}
return $this->loaded[$companyId] = $document;
}
/** @return array<string,bool> 姓名集合(给校验用) */
public function nameSet(int $companyId): array
{
$set = [];
foreach ($this->document($companyId)['people'] as $person) {
$set[PlantingReimbursementAuditor::normName($person['name'])] = true;
}
return $set;
}
public function add(int $companyId, string $name, string $platform, string $remark, ?int $userId): string
{
$name = PlantingReimbursementAuditor::normName($name);
if ($name === '' || mb_strlen($name) > 50 || preg_match('/^\d+$/', $name)) {
throw new InvalidArgumentException('请填写发起人花名(不超过 50 个字)。');
}
$people = $this->document($companyId)['people'];
foreach ($people as $person) {
if ($person['name'] === $name) {
throw new InvalidArgumentException($name . ' 已在名单里。');
}
}
$people[] = ['name' => $name, 'platform' => mb_substr(trim($platform), 0, 50), 'remark' => mb_substr(trim($remark), 0, 200), 'added_at' => now()->format('Y-m-d H:i:s')];
$this->store($companyId, $people, $userId);
return $name;
}
public function remove(int $companyId, string $name, ?int $userId): void
{
$name = PlantingReimbursementAuditor::normName($name);
$people = array_values(array_filter($this->document($companyId)['people'], static fn (array $person): bool => $person['name'] !== $name));
if (count($people) === count($this->document($companyId)['people'])) {
throw new InvalidArgumentException($name . ' 不在名单里,请刷新页面后重试。');
}
$this->store($companyId, $people, $userId);
}
/**
* 用表格追加名单(格式同以前上传的「报销佣金人员」表,取右侧「人员 / 平台」)。已有的不重复加。
*
* @return array{added:int,skipped:int}
*/
public function import(int $companyId, string $path, string $fileName, ?int $userId): array
{
$rows = $this->references->parse(PlantingReimbursementReferences::KIND_COMMISSION, $path, $fileName);
$people = $this->document($companyId)['people'];
$existing = array_flip(array_column($people, 'name'));
$added = 0;
foreach ($rows as $row) {
$name = PlantingReimbursementAuditor::normName((string) $row['key']);
if ($name === '' || isset($existing[$name])) {
continue;
}
$people[] = ['name' => $name, 'platform' => '', 'remark' => '导入:' . mb_substr($fileName, 0, 80), 'added_at' => now()->format('Y-m-d H:i:s')];
$existing[$name] = true;
$added++;
}
$this->store($companyId, $people, $userId);
return ['added' => $added, 'skipped' => count($rows) - $added];
}
public function exportCsv(int $companyId): string
{
$lines = ["\xEF\xBB\xBF人员,平台,备注,加入时间"];
foreach ($this->document($companyId)['people'] as $person) {
$lines[] = implode(',', array_map(static fn (?string $value): string => '"' . str_replace('"', '""', (string) $value) . '"', [$person['name'], $person['platform'], $person['remark'], $person['added_at']]));
}
return implode("\n", $lines) . "\n";
}
/** @param list<array<string,mixed>> $people */
private function store(int $companyId, array $people, ?int $userId): void
{
usort($people, static fn (array $a, array $b): int => strcmp($a['name'], $b['name']));
$document = ['people' => array_values($people), 'source' => 'edited', 'updated_at' => now()->format('Y-m-d H:i:s'), 'updated_by' => $userId];
if (! Storage::disk('local')->put($this->path($companyId), json_encode($document, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))) {
throw new RuntimeException('报销佣金人员名单保存失败。');
}
$this->loaded[$companyId] = $document;
}
private function path(int $companyId): string
{
return PlantingReimbursementReferences::DIRECTORY . '/' . $companyId . '/' . self::FILE;
}
}

View File

@ -0,0 +1,171 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use RuntimeException;
/**
* 种菜报销流程用到的钉钉开放接口:应用凭证、表单结构、发起人 unionId、审批钉盘空间、上传附件、发起审批。
* 发起审批的请求绝不自动重试(超时视为「可能已发起」,由调用方标记待核查)。
*/
class PlantingDingTalkClient
{
private const API = 'https://api.dingtalk.com/v1.0';
private const OAPI = 'https://oapi.dingtalk.com';
/** @return array<string,mixed> */
public function settings(): array
{
return (array) config('planting_reimbursement.dingtalk', []);
}
public function token(): string
{
$settings = $this->settings();
if (trim((string) ($settings['client_id'] ?? '')) === '' || trim((string) ($settings['client_secret'] ?? '')) === '') {
throw new RuntimeException('没有配置钉钉应用凭据(PLANTING_DINGTALK_CLIENT_ID / SECRET)。');
}
return Cache::remember('planting-dingtalk:token:' . md5((string) $settings['client_id']), 5400, function () use ($settings): string {
$response = $this->send(fn () => Http::acceptJson()->connectTimeout(3)->timeout(8)->post(self::API . '/oauth2/accessToken', [
'appKey' => $settings['client_id'], 'appSecret' => $settings['client_secret'],
]), '获取钉钉应用凭证');
$token = $response->json('accessToken');
if (! is_string($token) || $token === '') {
throw new RuntimeException('获取钉钉应用凭证失败,请检查应用凭据。');
}
return $token;
});
}
/** @return list<array<string,mixed>> 表单组件(schemaContent.items) */
public function formSchema(string $processCode): array
{
$response = $this->send(fn () => $this->api()->get(self::API . '/workflow/forms/schemas/processCodes', ['processCode' => $processCode]), '读取钉钉流程表单');
$items = $response->json('result.schemaContent.items');
if (! is_array($items) || $items === []) {
throw new RuntimeException('钉钉没有返回「种菜报销流程」的表单结构,请检查流程编码和应用的审批权限。');
}
return $items;
}
public function unionId(string $userId): string
{
$response = $this->send(fn () => Http::acceptJson()->connectTimeout(3)->timeout(8)
->post(self::OAPI . '/topapi/v2/user/get?access_token=' . urlencode($this->token()), ['userid' => $userId, 'language' => 'zh_CN']), '读取发起人信息');
$unionId = $response->json('result.unionid');
if ((int) $response->json('errcode', 0) !== 0 || ! is_string($unionId) || $unionId === '') {
throw new RuntimeException('读取发起人钉钉信息失败(' . $response->json('errmsg', '无 unionId') . '),请检查应用的通讯录权限。');
}
return $unionId;
}
/** @return list<int> 发起人所在部门 */
public function deptIds(string $userId): array
{
$response = $this->send(fn () => Http::acceptJson()->connectTimeout(3)->timeout(8)
->post(self::OAPI . '/topapi/v2/user/get?access_token=' . urlencode($this->token()), ['userid' => $userId, 'language' => 'zh_CN']), '读取发起人部门');
return array_values(array_map('intval', (array) $response->json('result.dept_id_list', [])));
}
/**
* 把文件上传到发起人的审批钉盘空间,返回审批附件组件要的值。
*
* @return array{spaceId:string,fileName:string,fileSize:string,fileType:string,fileId:string}
*/
public function uploadAttachment(string $userId, string $fileName, string $content): array
{
$agentId = trim((string) ($this->settings()['agent_id'] ?? ''));
if ($agentId === '') {
throw new RuntimeException('没有配置钉钉应用 AgentId(PLANTING_DINGTALK_AGENT_ID),无法上传打款明细附件。');
}
$space = $this->send(fn () => $this->api()->post(self::API . '/workflow/processInstances/spaces/infos/query', [
'userId' => $userId, 'agentId' => (int) $agentId,
]), '获取审批钉盘空间');
$spaceId = (string) $space->json('result.spaceId', '');
if ($spaceId === '') {
throw new RuntimeException('钉钉没有返回审批钉盘空间。');
}
$unionId = $this->unionId($userId);
$info = $this->send(fn () => $this->api()->post(self::API . '/storage/spaces/' . $spaceId . '/files/uploadInfos/query?unionId=' . urlencode($unionId), [
'protocol' => 'HEADER_SIGNATURE', 'multipart' => false,
]), '获取附件上传地址');
$uploadKey = (string) $info->json('uploadKey', '');
$url = (string) ($info->json('headerSignatureInfo.resourceUrls.0') ?? '');
$headers = (array) $info->json('headerSignatureInfo.headers', []);
if ($uploadKey === '' || $url === '') {
throw new RuntimeException('钉钉没有返回附件上传地址。');
}
$this->send(fn () => Http::withHeaders($headers)->connectTimeout(5)->timeout(30)->withBody($content, 'application/octet-stream')->put($url), '上传打款明细附件');
$commit = $this->send(fn () => $this->api()->post(self::API . '/storage/spaces/' . $spaceId . '/files/commit?unionId=' . urlencode($unionId), [
'uploadKey' => $uploadKey, 'name' => $fileName, 'parentId' => '0',
'option' => ['conflictStrategy' => 'AUTO_RENAME', 'size' => strlen($content)],
]), '提交打款明细附件');
$dentry = (array) $commit->json('dentry', []);
if (($dentry['id'] ?? '') === '') {
throw new RuntimeException('钉钉没有返回附件编号。');
}
return [
'spaceId' => (string) ($dentry['spaceId'] ?? $spaceId),
'fileName' => (string) ($dentry['name'] ?? $fileName),
'fileSize' => (string) ($dentry['size'] ?? strlen($content)),
'fileType' => (string) ($dentry['extension'] ?? pathinfo($fileName, PATHINFO_EXTENSION)),
'fileId' => (string) $dentry['id'],
];
}
/** 发起审批。失败抛异常;$uncertain=true 表示可能已经发起成功(超时 / 服务端错误)。 */
public function startInstance(array $payload): string
{
try {
$response = $this->api()->connectTimeout(3)->timeout(15)->post(self::API . '/workflow/processInstances', $payload);
} catch (ConnectionException) {
throw new PlantingDingTalkUncertainException('发起审批超时,可能已经发起成功,请先到钉钉核查,勿重复提交。');
}
if (! $response->successful()) {
$code = preg_replace('/[^a-zA-Z0-9_.-]/', '', (string) $response->json('code', ''));
$message = mb_substr((string) $response->json('message', ''), 0, 120);
if ($response->serverError() || $response->status() === 408) {
throw new PlantingDingTalkUncertainException('钉钉返回 HTTP ' . $response->status() . ',可能已经发起成功,请先到钉钉核查,勿重复提交。');
}
throw new RuntimeException('钉钉拒绝发起(HTTP ' . $response->status() . ($code !== '' ? ' ' . $code : '') . ($message !== '' ? ':' . $message : '') . '),请检查表单字段和发起权限。');
}
$id = $response->json('instanceId');
if (! is_string($id) || $id === '') {
throw new PlantingDingTalkUncertainException('钉钉响应缺少审批编号,可能已经发起成功,请先到钉钉核查。');
}
return $id;
}
private function api()
{
return Http::acceptJson()->connectTimeout(3)->timeout(10)->withHeaders(['x-acs-dingtalk-access-token' => $this->token()]);
}
private function send(callable $request, string $step)
{
try {
$response = $request();
} catch (ConnectionException) {
throw new RuntimeException($step . '超时,请稍后重试。');
}
if (! $response->successful()) {
$code = preg_replace('/[^a-zA-Z0-9_.-]/', '', (string) $response->json('code', ''));
throw new RuntimeException($step . '失败(HTTP ' . $response->status() . ($code !== '' ? ' ' . $code : '') . ')。');
}
return $response;
}
}

View File

@ -0,0 +1,226 @@
<?php
namespace Modules\EcommerceFinance\Services;
/**
* 按钉钉「种菜报销流程」的实际表单结构(接口读取),把工作台的钉钉流程明细填成发起审批的 formComponentValues。
*
* 字段按标题匹配(兼容常见写法),以前手工发起时的填法:
* - 收款费用明细:一行一条钉钉流程明细(费用承担部门 = 利润中心、店铺、用途 = M.D种菜报销、收款金额、支付方式 = 银行卡);
* - 收款人 / 开户行 / 账号:填「账号详见附件」,附件 = 种菜报销明细M.D.xlsx;
* - 付款明细:一行,付款金额 = 合计,付款方式 = 银行卡;打款时间留给出纳;
* - 报销类型:种菜核销。
* 必填字段填不上、下拉选项不匹配时列出来,不允许提交。纯计算类。
*/
final class PlantingDingTalkForm
{
public const PAYEE_TEXT = '账号详见附件';
public const REIMBURSE_TYPE = '种菜核销';
public const PAYMENT_METHOD = '银行卡';
private const MAIN = [
'total' => ['收款合计', '报销合计', '合计金额', '金额合计', '报销金额合计', '付款合计', '总金额', '报销总金额'],
'type' => ['报销类型', '核销类型', '费用类型'],
'payee' => ['收款人', '收款户名', '收款人姓名', '开户行', '开户银行', '收款银行', '账号', '收款账号', '银行账号', '银行卡号', '收款人账号'],
'purpose' => ['用途', '事由', '报销事由'],
'payment' => ['支付方式', '付款方式'],
];
private const EXPENSE_ROW = [
'seq' => ['序号'],
'department' => ['费用承担部门', '承担部门', '费用部门', '所属部门', '利润中心', '所属利润中心'],
'shop' => ['店铺', '店铺名称', '所属店铺'],
'purpose' => ['用途', '事由'],
'amount' => ['收款金额', '金额', '报销金额', '费用金额'],
'payment' => ['支付方式', '付款方式'],
'type' => ['报销类型', '核销类型', '费用类型'],
'payee' => ['收款人', '收款户名', '开户行', '开户银行', '账号', '收款账号', '银行账号'],
];
private const PAYMENT_ROW = [
'seq' => ['对应序号', '序号'],
'amount' => ['付款金额', '金额'],
'payment' => ['付款方式', '支付方式'],
'payee' => ['收款人', '收款户名', '开户行', '开户银行', '账号', '收款账号', '银行账号'],
];
/** 不需要填写的说明类组件。 */
private const SKIP = ['TextNote', 'DDBizSuite'];
/**
* @param list<array<string,mixed>> $schema 钉钉表单组件(schemaContent.items)
* @param array<string,mixed> $summary 工作台批次汇总(ding_lines、total、purpose、bill_date)
* @param array<string,string>|null $attachment 已上传附件;预览时为 null
* @return array{values:list<array<string,string>>,preview:list<array<string,mixed>>,missing:list<string>,invalid:list<string>,attachment_label:?string}
*/
public function build(array $schema, array $summary, ?array $attachment, string $attachmentName): array
{
$lines = array_values($summary['ding_lines'] ?? []);
$total = self::money(array_sum(array_column($lines, 'cents')));
$main = [
'total' => $total,
'type' => self::REIMBURSE_TYPE,
'payee' => self::PAYEE_TEXT,
'purpose' => (string) ($summary['purpose'] ?? ''),
'payment' => self::PAYMENT_METHOD,
];
$values = [];
$preview = [];
$missing = [];
$invalid = [];
$attachmentLabel = null;
foreach ($schema as $item) {
$type = (string) ($item['componentName'] ?? '');
$props = (array) ($item['props'] ?? []);
$label = trim((string) ($props['label'] ?? ''));
$required = (bool) ($props['required'] ?? false);
if ($label === '' || in_array($type, self::SKIP, true)) {
continue;
}
if ($type === 'TableField') {
$isPayment = str_contains($label, '付款');
$rows = $isPayment ? [$this->paymentRow($lines, $total)] : $this->expenseRows($lines, $summary);
$map = $isPayment ? self::PAYMENT_ROW : self::EXPENSE_ROW;
$table = [];
foreach ($rows as $rowIndex => $row) {
$cells = [];
foreach ((array) ($item['children'] ?? []) as $child) {
$childLabel = trim((string) ($child['props']['label'] ?? ''));
$childType = (string) ($child['componentName'] ?? '');
if ($childLabel === '' || in_array($childType, self::SKIP, true)) {
continue;
}
$key = self::key($map, $childLabel);
$value = $key === null ? '' : (string) ($row[$key] ?? '');
if ($value === '') {
if ((bool) ($child['props']['required'] ?? false) && $rowIndex === 0) {
$missing[] = $label . ' → ' . $childLabel;
}
continue;
}
if (! self::optionOk($child, $value)) {
$invalid[] = $label . ' → ' . $childLabel . '(选项里没有「' . $value . '」)';
}
$cells[] = ['name' => $childLabel, 'value' => $value];
}
$table[] = $cells;
}
if ($table === [] || $table[0] === []) {
if ($required) {
$missing[] = $label;
}
continue;
}
$values[] = ['name' => $label, 'value' => json_encode($table, JSON_UNESCAPED_UNICODE)];
$preview[] = ['label' => $label, 'type' => $type, 'required' => $required, 'rows' => $table];
continue;
}
if ($type === 'DDAttachment') {
$attachmentLabel ??= $label;
if ($attachmentLabel !== $label) {
continue;
}
$value = $attachment === null ? '' : json_encode([$attachment], JSON_UNESCAPED_UNICODE);
if ($attachment !== null) {
$values[] = ['name' => $label, 'value' => $value];
}
$preview[] = ['label' => $label, 'type' => $type, 'required' => $required, 'value' => '提交时上传:' . $attachmentName];
continue;
}
$key = self::key(self::MAIN, $label);
$value = $key === null ? '' : $main[$key];
if ($value === '') {
if ($required) {
$missing[] = $label;
}
$preview[] = ['label' => $label, 'type' => $type, 'required' => $required, 'value' => ''];
continue;
}
if (! self::optionOk($item, $value)) {
$invalid[] = $label . '(选项里没有「' . $value . '」)';
}
$values[] = ['name' => $label, 'value' => $value];
$preview[] = ['label' => $label, 'type' => $type, 'required' => $required, 'value' => $value];
}
if ($attachmentLabel === null) {
$missing[] = '附件(表单里没有附件字段,无法附上打款明细)';
}
return ['values' => $values, 'preview' => $preview, 'missing' => array_values(array_unique($missing)), 'invalid' => $invalid, 'attachment_label' => $attachmentLabel];
}
/** @return list<array<string,string>> */
private function expenseRows(array $lines, array $summary): array
{
$rows = [];
foreach ($lines as $index => $line) {
$rows[] = [
'seq' => (string) ($index + 1),
'department' => (string) ($line['department'] ?? ''),
'shop' => (string) ($line['shop'] ?? ''),
'purpose' => (string) ($line['purpose'] ?? $summary['purpose'] ?? ''),
'amount' => self::money((int) $line['cents']),
'payment' => (string) ($line['payment_method'] ?? self::PAYMENT_METHOD),
'type' => self::REIMBURSE_TYPE,
'payee' => self::PAYEE_TEXT,
];
}
return $rows;
}
/** @return array<string,string> */
private function paymentRow(array $lines, string $total): array
{
return [
'seq' => count($lines) > 1 ? '1-' . count($lines) : '1',
'amount' => $total,
'payment' => self::PAYMENT_METHOD,
'payee' => self::PAYEE_TEXT,
];
}
/** @param array<string,list<string>> $map */
private static function key(array $map, string $label): ?string
{
$normalized = preg_replace('/[\s((].*$/u', '', $label) ?? $label;
foreach ($map as $key => $aliases) {
if (in_array($label, $aliases, true) || in_array($normalized, $aliases, true)) {
return $key;
}
}
return null;
}
/** 单选 / 多选组件的值必须是选项之一;拿不到选项时不拦。 */
private static function optionOk(array $component, string $value): bool
{
if (! in_array((string) ($component['componentName'] ?? ''), ['DDSelectField', 'DDMultiSelectField'], true)) {
return true;
}
$options = [];
foreach ((array) ($component['props']['options'] ?? []) as $option) {
if (is_string($option)) {
$decoded = json_decode($option, true);
$options[] = is_array($decoded) ? (string) ($decoded['value'] ?? '') : $option;
} elseif (is_array($option)) {
$options[] = (string) ($option['value'] ?? $option['text'] ?? '');
}
}
return $options === [] || in_array($value, $options, true);
}
private static function money(int $cents): string
{
return number_format($cents / 100, 2, '.', '');
}
}

View File

@ -0,0 +1,165 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use RuntimeException;
use Throwable;
/**
* 工作台一键提交钉钉「种菜报销流程」:发起人李斯,表单按钉钉实际结构自动填,附件 = 种菜报销明细M.D.xlsx。
*
* 防重复:同一账单日只提交一次,结果记在 storage/app/planting-reimbursement-references/<公司>/ding-submissions/<账单日>.json;
* 结果不确定(超时等)记为「待核查」,同样不允许再次提交,直到在钉钉核查后勾选「确认钉钉里没有」重提。
*/
class PlantingDingTalkSubmission
{
public function __construct(
private readonly PlantingDingTalkClient $client,
private readonly PlantingDingTalkForm $form,
private readonly PlantingReimbursementDirectory $directory,
private readonly PlantingReimbursementWorkbookExporter $exporter,
) {}
/** @return array<string,mixed>|null 已提交记录 */
public function record(int $companyId, string $billDate): ?array
{
$disk = Storage::disk('local');
$path = $this->path($companyId, $billDate);
$record = $disk->exists($path) ? json_decode((string) $disk->get($path), true) : null;
return is_array($record) ? $record : null;
}
/**
* 预览:读取钉钉表单结构,按本批数据填好,列出缺的 / 不匹配的字段。不上传、不发起。
*
* @param array<string,mixed> $result 工作台批次
* @return array<string,mixed>
*/
public function preview(array $result): array
{
$settings = $this->client->settings();
$form = $this->form->build($this->client->formSchema((string) $settings['process_code']), $result['summary'], null, $this->attachmentName($result));
$originator = $this->originator();
return $form + ['originator' => $originator, 'attachment_name' => $this->attachmentName($result), 'total' => $result['summary']['total']];
}
/**
* 提交。$confirmedNoDuplicate:之前结果「待核查」、已在钉钉确认没有生成时才允许再提交。
*
* @param array<string,mixed> $result
* @return array<string,mixed> 提交记录
*/
public function submit(int $companyId, array $result, ?int $userId, bool $confirmedNoDuplicate = false): array
{
$gate = PlantingReimbursementGate::check($result);
if (! $gate['ok']) {
throw new RuntimeException('暂不能提交:' . implode(';', $gate['reasons']) . '。');
}
$billDate = (string) $result['summary']['bill_date'];
$lock = Cache::lock('planting-dingtalk-submit:' . $companyId . ':' . $billDate, 120);
if (! $lock->get()) {
throw new RuntimeException('这一批正在提交,请稍候刷新页面查看结果,不要重复点。');
}
try {
$existing = $this->record($companyId, $billDate);
if ($existing !== null && ($existing['status'] === 'submitted' || ! $confirmedNoDuplicate)) {
throw new RuntimeException($existing['status'] === 'submitted'
? '这一批(' . $billDate . ')已经在 ' . $existing['submitted_at'] . ' 提交过钉钉流程,不能重复提交。'
: '上次提交结果不确定,请先到钉钉核查是否已生成审批;确认没有后勾选「已在钉钉确认没有生成」再提交。');
}
$settings = $this->client->settings();
$originator = $this->originator();
$schema = $this->client->formSchema((string) $settings['process_code']);
$check = $this->form->build($schema, $result['summary'], null, $this->attachmentName($result));
if ($check['missing'] !== [] || $check['invalid'] !== []) {
throw new RuntimeException('钉钉表单有字段填不上:' . implode('、', array_merge($check['missing'], $check['invalid'])) . '。请先点「预览钉钉表单」查看。');
}
$attachment = $this->client->uploadAttachment($originator['user_id'], $this->attachmentName($result), $this->attachmentContent($result));
$form = $this->form->build($schema, $result['summary'], $attachment, $this->attachmentName($result));
$payload = array_filter([
'originatorUserId' => $originator['user_id'],
'processCode' => (string) $settings['process_code'],
'deptId' => $originator['dept_id'],
'formComponentValues' => $form['values'],
], static fn ($value): bool => $value !== null && $value !== '');
$record = [
'bill_date' => $billDate, 'total' => $result['summary']['total'], 'lines' => count($result['summary']['ding_lines']),
'originator' => $originator['name'], 'by' => $userId, 'attachment' => $attachment['fileName'],
];
try {
$instanceId = $this->client->startInstance($payload);
} catch (PlantingDingTalkUncertainException $exception) {
$this->save($companyId, $billDate, $record + ['status' => 'uncertain', 'submitted_at' => now()->format('Y-m-d H:i:s'), 'message' => $exception->getMessage()]);
throw $exception;
}
$record += ['status' => 'submitted', 'instance_id' => $instanceId, 'submitted_at' => now()->format('Y-m-d H:i:s')];
$this->save($companyId, $billDate, $record);
return $record;
} finally {
$lock->release();
}
}
/** @return array{name:string,user_id:string,dept_id:?int} */
public function originator(): array
{
$settings = $this->client->settings();
$name = trim((string) ($settings['originator_flower_name'] ?? '李斯'));
$userId = trim((string) ($settings['originator_user_id'] ?? ''));
if ($userId === '') {
$userId = (string) ($this->directory->userIds([$name])[PlantingReimbursementAuditor::normName($name)] ?? '');
}
if ($userId === '') {
throw new RuntimeException('钉钉花名册里找不到发起人「' . $name . '」(或同名多人),请配置 PLANTING_DINGTALK_ORIGINATOR_USER_ID。');
}
$deptId = trim((string) ($settings['dept_id'] ?? ''));
if ($deptId === '') {
try {
$deptId = (string) ($this->client->deptIds($userId)[0] ?? '');
} catch (Throwable $exception) {
report($exception);
$deptId = '';
}
}
return ['name' => $name, 'user_id' => $userId, 'dept_id' => $deptId === '' ? null : (int) $deptId];
}
private function attachmentName(array $result): string
{
return $this->exporter->fileName('details', $result['summary']);
}
private function attachmentContent(array $result): string
{
$path = tempnam(sys_get_temp_dir(), 'planting-details-');
try {
(new Xlsx($this->exporter->build('details', $result)))->save($path);
return (string) file_get_contents($path);
} finally {
@unlink($path);
}
}
private function save(int $companyId, string $billDate, array $record): void
{
Storage::disk('local')->put($this->path($companyId, $billDate), json_encode($record, JSON_UNESCAPED_UNICODE));
}
private function path(int $companyId, string $billDate): string
{
return PlantingReimbursementReferences::DIRECTORY . '/' . $companyId . '/ding-submissions/' . preg_replace('/[^0-9-]/', '', $billDate) . '.json';
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace Modules\EcommerceFinance\Services;
use RuntimeException;
/** 发起钉钉审批时结果不确定(超时、服务端错误):可能已经发起成功,不能自动重试。 */
class PlantingDingTalkUncertainException extends RuntimeException {}

View File

@ -0,0 +1,52 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Carbon;
/**
* 种菜报销批次放行检查(2026-12-01 起替代「去聚工单人工核对条数和金额、勾选已核对」):
* 导出、发群通知、提交钉钉流程前,以下全部满足才放行;不满足时给出原因。
* - 聚工单镜像最近 20 分钟内同步成功(数据是最新的);
* - 种菜额度已校验(经营分析副本库可用);
* - 额度规则不为空;
* - 金额与条数自检全部通过;
* - 本批有可报销的工单(导出 / 提交时)。
* 纯计算类。
*/
final class PlantingReimbursementGate
{
public const STALE_MINUTES = 20;
/**
* @param array<string,mixed> $result PlantingReimbursementWorkbench::build() 的结果
* @return array{ok:bool,reasons:list<string>}
*/
public static function check(array $result, bool $requirePass = true, ?Carbon $now = null): array
{
$now ??= now();
$reasons = [];
$sync = $result['sync'] ?? ['code' => 'unavailable', 'last_succeeded_at' => null];
$last = $sync['last_succeeded_at'] ?? null;
if (($sync['code'] ?? '') !== 'ready' || $last === null) {
$reasons[] = '聚工单数据同步异常(最后成功:' . ($last ? substr((string) $last, 0, 16) : '无') . ')';
} elseif ($now->diffInMinutes(Carbon::parse((string) $last), true) > self::STALE_MINUTES) {
$reasons[] = '聚工单数据超过 ' . self::STALE_MINUTES . ' 分钟没同步(最后成功:' . substr((string) $last, 0, 16) . ')';
}
if (trim((string) ($result['quota_error'] ?? '')) !== '') {
$reasons[] = '种菜额度没有校验(' . $result['quota_error'] . ')';
}
if (($result['quota_rules']['count'] ?? 1) === 0) {
$reasons[] = '没有种菜额度规则';
}
$failed = array_column(array_filter($result['summary']['checks'] ?? [], static fn (array $check): bool => ! $check['ok']), 'label');
if ($failed !== []) {
$reasons[] = '自检未通过:' . implode('、', $failed);
}
if ($requirePass && (int) ($result['summary']['counts'][PlantingReimbursementAuditor::DECISION_PASS] ?? 0) === 0) {
$reasons[] = '本批没有可报销的工单';
}
return ['ok' => $reasons === [], 'reasons' => $reasons];
}
}

View File

@ -8,7 +8,7 @@ use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
/**
* 种菜报销工作台的参考名单:财务上传的报销佣金人员、花名册在职姓名。
* 种菜报销工作台的参考名单:财务上传的花名册在职姓名;以前上传的报销佣金人员名单只用来初始化 PlantingCommissionPeople。
* (种菜监控看板、店铺信息 2026-11-27 起不再上传:额度由财务系统自算,店铺信息直接读工作平台。)
* 每次上传整类替换,存为 storage/app/planting-reimbursement-references/<公司>/<类型>.json;
* 花名册只取「在职」表的姓名列,不保存证件号、手机号等其他列。
@ -19,11 +19,14 @@ class PlantingReimbursementReferences
public const KIND_ROSTER = 'roster';
/** 工作台可上传的名单(报销佣金人员 2026-12-01 起改在工作台维护,见 PlantingCommissionPeople)。 */
public const KINDS = [
self::KIND_COMMISSION => '报销佣金人员',
self::KIND_ROSTER => '花名册(在职)',
];
/** 存储里可能存在的名单(含历史上传的报销佣金人员,用来初始化新的名单)。 */
private const STORED_KINDS = [self::KIND_COMMISSION, self::KIND_ROSTER];
public const DIRECTORY = 'planting-reimbursement-references';
/** @var array<string,array<string,mixed>|null> 本次请求内已读过的名单 */
@ -95,7 +98,7 @@ class PlantingReimbursementReferences
private function path(int $companyId, string $kind): string
{
if (! isset(self::KINDS[$kind])) {
if (! in_array($kind, self::STORED_KINDS, true)) {
throw new InvalidArgumentException('未知的名单类型。');
}

View File

@ -32,6 +32,7 @@ class PlantingReimbursementWorkbench
private readonly PlantingQuotaDimensions $dimensions,
private readonly PlantingQuotaRules $rules,
private readonly PlantingQuotaCalculator $calculator,
private readonly PlantingCommissionPeople $commissionPeople,
) {}
public static function defaultDate(?CarbonImmutable $now = null): string
@ -142,7 +143,7 @@ class PlantingReimbursementWorkbench
$refs = [
'reimbursed' => $this->repository->reimbursedOrders($date, array_column($rows, 'work_order_no')),
'commission_people' => $this->references->nameSet($companyId, PlantingReimbursementReferences::KIND_COMMISSION),
'commission_people' => $this->commissionPeople->nameSet($companyId),
'roster' => $roster,
'roster_exceptions' => self::ROSTER_EXCEPTIONS,
'profit_centers' => $profitCenters,
@ -156,6 +157,7 @@ class PlantingReimbursementWorkbench
'shop_source' => $shopInfo['source'],
'quota_error' => $quotaError,
'quota_rules' => ['count' => count($this->rules->all($companyId)), 'source' => $this->rules->document($companyId)['source']],
'sync' => $this->repository->syncStatus(),
'uploads' => $this->references->uploads($companyId),
];
}

View File

@ -42,6 +42,8 @@ class PlantingReimbursementWorkbenchPageData
private readonly References $references,
private readonly \Modules\EcommerceFinance\Services\PlantingReimbursementRobot $robot,
private readonly \Modules\EcommerceFinance\Services\PlantingQuotaRules $quotaRules,
private readonly \Modules\EcommerceFinance\Services\PlantingCommissionPeople $commissionPeople,
private readonly \Modules\EcommerceFinance\Services\PlantingDingTalkSubmission $dingTalk,
) {}
/** @return array{date:string,paid_from:string,scope:string,decision:string} */
@ -105,6 +107,10 @@ class PlantingReimbursementWorkbenchPageData
'workbenchShopSource' => $result['shop_source'] ?? null,
'workbenchQuotaError' => $result['quota_error'] ?? null,
'workbenchQuotaRules' => $this->quotaRulesPage(),
'workbenchCommission' => $this->commissionPage(),
'workbenchGate' => $result ? \Modules\EcommerceFinance\Services\PlantingReimbursementGate::check($result) : null,
'workbenchDingRecord' => $result ? $this->dingTalk->record((int) company_id(), (string) $result['summary']['bill_date']) : null,
'workbenchDingPreview' => $result && request('ding_preview') === '1' ? $this->dingPreview($result) : null,
'workbenchFilters' => $filters,
'workbenchWindow' => Workbench::paidWindow($filters['date'], $filters['paid_from']),
'workbenchSync' => $sync,
@ -129,6 +135,30 @@ class PlantingReimbursementWorkbenchPageData
}
}
/** @return array<string,mixed> */
private function commissionPage(): array
{
try {
return $this->commissionPeople->document((int) company_id()) + ['error' => null];
} catch (\Throwable $exception) {
report($exception);
return ['people' => [], 'source' => 'error', 'updated_at' => null, 'error' => '报销佣金人员名单读取失败'];
}
}
/** @return array<string,mixed> */
private function dingPreview(array $result): array
{
try {
return $this->dingTalk->preview($result) + ['error' => null];
} catch (\Throwable $exception) {
report($exception);
return ['error' => $exception instanceof \RuntimeException ? $exception->getMessage() : '读取钉钉表单失败,请稍后重试。'];
}
}
/** @return array<string,mixed> */
private function safeUploads(): array
{

View File

@ -325,6 +325,8 @@
}));
one('[data-pwb-open-robot]').addEventListener('click', event => { event.preventDefault(); const robot = one('#pwb-robot'); robot.open = true; robot.scrollIntoView({block:'start'}); robot.querySelector('summary').focus(); });
one('[data-pwb-retry]')?.addEventListener('click', () => one('.pwb-filters').requestSubmit());
// 预览 / 提交钉钉流程后回到「钉钉流程明细」页签。
if (location.hash === '#pwb-ding') { showTab('ding'); one('#pwb-ding')?.scrollIntoView({block:'start'}); }
})();
</script>
@endpush

View File

@ -0,0 +1,55 @@
@php
$commission = $workbenchCommission ?? ['people' => [], 'source' => 'empty', 'updated_at' => null, 'error' => null];
$commissionQuery = ['date' => $workbenchFilters['date'], 'paid_from' => $workbenchFilters['paid_from'], 'scope' => $workbenchFilters['scope']];
$commissionSource = ['history' => '历史上传名单', 'edited' => '页面维护', 'empty' => '还没有名单', 'error' => '读取失败'][$commission['source']] ?? '';
@endphp
<details id="pwb-commission" class="pwb-support pwb-settings" @if(old('name') || (session('error') && str_contains((string) session('error'), '报销佣金人员'))) open @endif>
<summary>报销佣金人员({{ number_format(count($commission['people'])) }} 人)<span class="pwb-muted"> · {{ $commissionSource }}@if($commission['updated_at']) · {{ substr($commission['updated_at'], 0, 16) }}@endif</span></summary>
@if($commission['error'])<p class="pwb-alert is-danger">{{ $commission['error'] }}</p>@endif
<p class="pwb-note">工单里有佣金、而发起人不在这个名单的,取消工单。新增发起人在这里加;以前上传过的名单已经导入。</p>
<form method="post" action="{{ route('business.planting-data.planting-reimbursement-workbench.commission.add') }}" class="pwb-robot">
@csrf
@foreach($commissionQuery as $key => $value)<input type="hidden" name="{{ $key }}" value="{{ $value }}">@endforeach
<label>发起人花名<input type="text" name="name" value="{{ old('name') }}" maxlength="50" required></label>
<label>平台(可空)<input type="text" name="platform" value="{{ old('platform') }}" maxlength="50"></label>
<label>备注(可空)<input type="text" name="remark" value="{{ old('remark') }}" maxlength="200"></label>
<button type="submit" class="pwb-button is-primary">加入名单</button>
</form>
<div class="pwb-table-tools">
<label class="pwb-search"><span class="material-icons-outlined" aria-hidden="true">search</span><input type="search" data-pwb-commission-search placeholder="花名" aria-label="搜索报销佣金人员"></label>
<div class="pwb-export-buttons">
<a class="pwb-button" href="{{ route('business.planting-data.planting-reimbursement-workbench.commission.export') }}"><span class="material-icons-outlined" aria-hidden="true">download</span>导出名单</a>
<form method="post" enctype="multipart/form-data" action="{{ route('business.planting-data.planting-reimbursement-workbench.commission.import') }}" class="pwb-file">
@csrf
@foreach($commissionQuery as $key => $value)<input type="hidden" name="{{ $key }}" value="{{ $value }}">@endforeach
<label class="pwb-button"><input type="file" name="file" accept=".xlsx,.xls,.csv" required aria-label="选择报销佣金人员表"><span data-pwb-file-label>选择表格</span></label><button type="submit" class="pwb-button">追加导入</button>
</form>
</div>
</div>
<div class="pwb-table-scroll" tabindex="0" aria-label="报销佣金人员">
<table>
<thead><tr><th>花名</th><th>平台</th><th>备注</th><th>加入时间</th><th>操作</th></tr></thead>
<tbody>
@forelse($commission['people'] as $person)
<tr data-pwb-commission-row data-search="{{ mb_strtolower($person['name']) }}">
<td>{{ $person['name'] }}</td><td>{{ $person['platform'] ?: '—' }}</td><td>{{ $person['remark'] ?: '' }}</td><td>{{ $person['added_at'] ? substr($person['added_at'], 0, 16) : '—' }}</td>
<td><form method="post" action="{{ route('business.planting-data.planting-reimbursement-workbench.commission.remove') }}" onsubmit="return confirm('确定把 {{ $person['name'] }} 移出报销佣金人员?');">@csrf @foreach($commissionQuery as $key => $value)<input type="hidden" name="{{ $key }}" value="{{ $value }}">@endforeach<input type="hidden" name="name" value="{{ $person['name'] }}"><button type="submit" class="pwb-button">移除</button></form></td>
</tr>
@empty
<tr><td colspan="5" class="pwb-empty">名单是空的:所有带佣金的工单都会取消。</td></tr>
@endforelse
</tbody>
</table>
</div>
</details>
<script>
(() => {
const input = document.querySelector('[data-pwb-commission-search]');
if (!input) return;
input.addEventListener('input', () => {
const word = input.value.trim().toLowerCase();
document.querySelectorAll('[data-pwb-commission-row]').forEach((row) => { row.hidden = word !== '' && !row.dataset.search.includes(word); });
});
if (location.hash === '#pwb-commission') document.getElementById('pwb-commission').open = true;
})();
</script>

View File

@ -0,0 +1,44 @@
@php
$dingQuery = ['date' => $workbenchFilters['date'], 'paid_from' => $workbenchFilters['paid_from'], 'scope' => $workbenchFilters['scope']];
$record = $workbenchDingRecord;
$preview = $workbenchDingPreview;
@endphp
@if($summary)
<div class="pwb-ding-submit" id="pwb-ding-submit">
@if($record && $record['status'] === 'submitted')
<p class="pwb-alert is-success" role="status">已在 {{ $record['submitted_at'] }} 以 {{ $record['originator'] }} 的名义提交钉钉「种菜报销流程」:{{ number_format((float) $record['total'], 2) }} 元,{{ $record['lines'] }} 行明细,附件 {{ $record['attachment'] }},审批编号 {{ $record['instance_id'] }}。同一批不会再重复提交。</p>
@else
@if($record && $record['status'] === 'uncertain')
<p class="pwb-alert is-danger" role="alert">{{ $record['submitted_at'] }} 提交时结果不确定:{{ $record['message'] ?? '' }} 请先到钉钉查是否已经生成这条审批。</p>
@endif
<div class="pwb-export-buttons">
<a class="pwb-button" href="{{ route('business.planting-data.planting-reimbursement-workbench.dingtalk.preview', $dingQuery) }}"><span class="material-icons-outlined" aria-hidden="true">visibility</span>预览钉钉表单</a>
<form method="post" action="{{ route('business.planting-data.planting-reimbursement-workbench.dingtalk.submit') }}" onsubmit="return confirm('将以李斯的名义提交钉钉「种菜报销流程」:{{ number_format((float) $summary['total'], 2) }} 元。确定提交?');" style="display:inline-flex;gap:8px;align-items:center">
@csrf
@foreach($dingQuery as $key => $value)<input type="hidden" name="{{ $key }}" value="{{ $value }}">@endforeach
@if($record && $record['status'] === 'uncertain')<label class="pwb-check"><input type="checkbox" name="confirm_no_duplicate" value="1" required> 已在钉钉确认没有生成</label>@endif
<button type="submit" class="pwb-button is-primary" @disabled(! ($workbenchGate['ok'] ?? false))><span class="material-icons-outlined" aria-hidden="true">send</span>提交钉钉流程({{ number_format((float) $summary['total'], 2) }} 元)</button>
</form>
</div>
@if(! ($workbenchGate['ok'] ?? false))<p class="pwb-panel-note pwb-warning">放行检查没通过,暂不能提交:{{ implode(';', $workbenchGate['reasons'] ?? []) }}。</p>@endif
@endif
@if($preview)
@if($preview['error'])
<p class="pwb-alert is-danger" role="alert">预览钉钉表单失败:{{ $preview['error'] }}</p>
@else
<div class="pwb-panel-heading"><div><h3>钉钉表单预览</h3><p>发起人 {{ $preview['originator']['name'] }}({{ $preview['originator']['user_id'] }}{{ $preview['originator']['dept_id'] ? ',部门 ' . $preview['originator']['dept_id'] : '' }});附件 {{ $preview['attachment_name'] }}。</p></div></div>
@if($preview['missing'] || $preview['invalid'])<p class="pwb-alert is-danger" role="alert">这些字段填不上,暂不能提交:{{ implode('、', array_merge($preview['missing'], $preview['invalid'])) }}。</p>@else<p class="pwb-alert is-success" role="status">表单必填项都能自动填好,可以提交。</p>@endif
<div class="pwb-table-scroll"><table><thead><tr><th>字段</th><th>类型</th><th>必填</th><th>自动填入</th></tr></thead><tbody>
@foreach($preview['preview'] as $field)
<tr><td>{{ $field['label'] }}</td><td>{{ $field['type'] }}</td><td>{{ $field['required'] ? '是' : '' }}</td><td>
@if(isset($field['rows']))
@foreach($field['rows'] as $row)<div>{{ collect($row)->map(fn ($cell) => $cell['name'] . ':' . $cell['value'])->implode(';') }}</div>@endforeach
@else{{ $field['value'] !== '' ? $field['value'] : '—' }}@endif
</td></tr>
@endforeach
</tbody></table></div>
@endif
@endif
</div>
@endif

View File

@ -10,7 +10,7 @@
<label>汇总群加签密钥(可空)<input type="password" name="digest_secret" placeholder="{{ $workbenchRobot['has_digest_secret'] ? '已保存,留空不改' : '' }}" autocomplete="new-password"></label>
@if($workbenchRobot['digest_webhook'])<label class="pwb-check"><input type="checkbox" name="clear_digest" value="1"> 清除汇总群设置</label>@endif
<button type="submit" class="pwb-button">保存</button>
<p class="pwb-note">Webhook 和密钥加密保存,页面不回显,留空表示不改。每天 11:20 自动把当天批次汇总推到群里并 @ 报销人;取消通知要在上面核对后手动点发送。</p>
<p class="pwb-note">Webhook 和密钥加密保存,页面不回显,留空表示不改。每天 11:20 自动把当天批次汇总推到群里并 @ 报销人,同时自动发不予报销通知(@ 发起人,已发过的不重发);放行检查没通过时只推汇总、不发通知。</p>
</form>
</details>
<details class="pwb-support pwb-settings"><summary>校验规则</summary><p>取单与聚工单锁单一致:种菜报销、工单状态待处理(可切换处理中)、订单付款时间默认报销日前 7 天至前一天、ERP订单状态不为取消 / 删除 / 空、售后单号为空。</p><p><b>取消工单:</b>重复报销(本月、上月已报销过或本批重复);最终报销金额 ≠ 任务付款+快递费+佣金+京喜差价−扣款+空包费;发起人不在报销佣金人员名单却报了佣金;收款人不在花名册在职名单(柴嘉伟(建行)除外);种菜额度单笔 / 每日 / 月度超额(全部取消,不按付款先后保留);未匹配负责人、职级为空、职级未配置、额度规则未配置。</p><p><b>种菜额度口径</b>(同「脉象」每日种菜监控看板):金额取工单实付金额字段(为空才取最终报销金额);商品ID → ID负责人(取第一个有负责人的商品,都没有用店长兜底)→ 职级;规则优先级 ID负责人 &gt; 店铺+职级 &gt; 店铺 &gt; 平台+职级;同一负责人同一额度域内,按支付日、支付月累计(含已报销的单,排除驳回、作废)。</p><p><b>待复查:</b>店铺在工作平台店铺信息里查不到利润中心;额度数据暂时取不到。</p></details>
<details class="pwb-support pwb-settings"><summary>校验规则</summary><p>取单与聚工单锁单一致:种菜报销、工单状态待处理(可切换处理中)、订单付款时间默认报销日前 7 天至前一天、ERP订单状态不为取消 / 删除 / 空、售后单号为空。</p><p><b>取消工单:</b>重复报销(本月、上月已报销过或本批重复);最终报销金额 ≠ 任务付款+快递费+佣金+京喜差价−扣款+空包费;发起人不在报销佣金人员名单却报了佣金;收款人不在花名册在职名单(柴嘉伟(建行)除外);种菜额度单笔 / 每日 / 月度超额(全部取消,不按付款先后保留);未匹配负责人、职级为空、职级未配置、额度规则未配置。</p><p><b>种菜额度口径</b>(同「脉象」每日种菜监控看板):金额取工单实付金额字段(为空才取最终报销金额);商品ID → ID负责人(取第一个有负责人的商品,都没有用店长兜底)→ 职级;规则优先级 ID负责人 &gt; 店铺+职级 &gt; 店铺 &gt; 平台+职级;同一负责人同一额度域内,按支付日、支付月累计(含已报销的单,排除驳回、作废)。</p><p><b>待复查:</b>店铺在工作平台店铺信息里查不到利润中心;额度数据暂时取不到。</p><p><b>放行检查</b>(替代去聚工单人工核对):聚工单数据 20 分钟内同步过、种菜额度已校验、额度规则不为空、金额与条数自检全部通过,才允许导出、发通知和提交钉钉流程。</p></details>

View File

@ -45,7 +45,7 @@
@endif
<details class="pwb-support" data-pwb-references>
<summary><span class="material-icons-outlined" aria-hidden="true">folder_open</span><strong>参考资料</strong><span>{{ count(array_filter($workbenchUploads)) }} / {{ count(References::KINDS) }} 已上传</span><span class="pwb-support-note">按需更新名单;种菜额度与店铺信息自动读取,不用上传</span><span class="material-icons-outlined pwb-chevron" aria-hidden="true">expand_more</span></summary>
<summary><span class="material-icons-outlined" aria-hidden="true">folder_open</span><strong>参考资料</strong><span>{{ count(array_filter($workbenchUploads)) }} / {{ count(References::KINDS) }} 已上传</span><span class="pwb-support-note">花名册可选上传(不传则按钉钉花名册);佣金人员、额度规则在下方维护</span><span class="material-icons-outlined pwb-chevron" aria-hidden="true">expand_more</span></summary>
<div class="pwb-uploads">
@foreach(References::KINDS as $kind => $label)
@php $upload = $workbenchUploads[$kind] ?? null; @endphp
@ -66,12 +66,11 @@
@if($workbenchRosterSource === 'none')<p class="pwb-alert is-warning">未取得在职名单,本次未校验收款人是否在职。请在参考资料中上传花名册。</p>@endif
@if($summary)
<section class="pwb-verification" aria-label="与聚工单核对">
<div class="pwb-verify-heading"><div><strong>核对聚工单原数据</strong><p>相同条件下,应为 <b>{{ number_format($summary['source']['count']) }} 条</b><span> / </span>最终报销金额 <b>{{ number_format((float) $summary['source']['amount'], 2) }} 元</b>。一致后再导出。</p></div><details class="pwb-help"><summary>查看核对条件<span class="material-icons-outlined" aria-hidden="true">expand_more</span></summary><p>聚工单「打款工单 → 种菜报销」:工单状态 {{ Workbench::SCOPES[$workbenchFilters['scope']] }};付款时间 {{ $workbenchWindow['from'] }} 至 {{ $workbenchWindow['to'] }};ERP订单状态除取消 / 删除 / 为空 / 不为空外全选,售后单号查询为空。条数或金额不一致,先别报销。</p></details></div>
<section class="pwb-verification" aria-label="放行检查">
<div class="pwb-verify-heading"><div><strong>放行检查</strong>@if($workbenchGate && $workbenchGate['ok'])<p class="pwb-good">全部通过:聚工单数据是最新的、种菜额度已校验、金额与条数自检通过,可以导出和提交。本批 <b>{{ number_format($summary['source']['count']) }} 条</b> / <b>{{ number_format((float) $summary['source']['amount'], 2) }} 元</b>。</p>@else<p class="pwb-danger">暂不能导出、提交:{{ implode(';', $workbenchGate['reasons'] ?? ['数据未就绪']) }}。</p>@endif</div><details class="pwb-help"><summary>取单条件<span class="material-icons-outlined" aria-hidden="true">expand_more</span></summary><p>聚工单「打款工单 → 种菜报销」:工单状态 {{ Workbench::SCOPES[$workbenchFilters['scope']] }};付款时间 {{ $workbenchWindow['from'] }} 至 {{ $workbenchWindow['to'] }};ERP订单状态不为取消 / 删除 / 空,售后单号为空。不再需要去聚工单人工核对条数和金额。</p></details></div>
<form method="get" class="pwb-export" data-pwb-export>
@foreach($exportQuery as $key => $value)<input type="hidden" name="{{ $key }}" value="{{ $value }}">@endforeach
<label class="pwb-check"><input type="checkbox" name="verified" value="1" required>已在聚工单核对,条数和金额一致</label>
<div class="pwb-export-buttons">@foreach(Exporter::TYPES as $type => $label)<button type="submit" class="pwb-button {{ $type === 'details' ? 'is-primary' : '' }}" formaction="{{ route('business.planting-data.planting-reimbursement-workbench.export', ['type' => $type]) }}"><span class="material-icons-outlined" aria-hidden="true">download</span>导出{{ $label }}</button>@endforeach</div>
<div class="pwb-export-buttons">@foreach(Exporter::TYPES as $type => $label)<button type="submit" class="pwb-button {{ $type === 'details' ? 'is-primary' : '' }}" formaction="{{ route('business.planting-data.planting-reimbursement-workbench.export', ['type' => $type]) }}" @disabled(! ($workbenchGate['ok'] ?? false))><span class="material-icons-outlined" aria-hidden="true">download</span>导出{{ $label }}</button>@endforeach</div>
</form>
<details class="pwb-checks"><summary><span class="material-icons-outlined {{ $checkCount === count($summary['checks']) ? 'pwb-good' : 'pwb-danger' }}" aria-hidden="true">{{ $checkCount === count($summary['checks']) ? 'check_circle_outline' : 'error_outline' }}</span>金额与条数自检 <b>{{ $checkCount }} / {{ count($summary['checks']) }} 通过</b><span class="material-icons-outlined pwb-chevron" aria-hidden="true">expand_more</span></summary><ul>@foreach($summary['checks'] as $check)<li class="{{ $check['ok'] ? 'pwb-good' : 'pwb-danger' }}">{{ $check['ok'] ? '✓' : '✗' }} {{ $check['label'] }}</li>@endforeach</ul><p>标记已打款、提交钉钉后,用聚工单「已完成」状态 + 完成时间复核:{{ $summary['counts'][Auditor::DECISION_PASS] }} 条 / {{ number_format((float) $summary['total'], 2) }} 元,并确认钉钉收款合计相同。</p></details>
</section>
@ -100,16 +99,18 @@
<div id="pwb-ding" role="tabpanel" aria-labelledby="pwb-tab-ding" data-pwb-panel="ding" hidden>
<div class="pwb-panel-heading"><div><h3>钉钉「种菜报销流程」明细</h3><p>报销类型:种菜核销。提交前先在聚工单标记已打款,并核对合计。</p></div><span class="pwb-amount">合计 {{ number_format((float) ($summary['total'] ?? 0), 2) }} 元</span></div>
<div class="pwb-table-scroll"><table><thead><tr><th>费用承担部门</th><th>店铺</th><th>用途</th><th>支付方式</th><th class="pwb-money">金额(元)</th></tr></thead><tbody>@forelse($summary['ding_lines'] ?? [] as $line)<tr><td>{{ $line['department'] ?: '(利润中心待补)' }}</td><td>{{ $line['shop'] }}</td><td>{{ $line['purpose'] }}</td><td>{{ $line['payment_method'] }}</td><td class="pwb-money">{{ number_format($line['cents'] / 100, 2) }}</td></tr>@empty<tr><td colspan="5" class="pwb-empty">本批次没有可报销的工单,暂不生成流程明细。</td></tr>@endforelse</tbody>@if($summary && $summary['ding_lines'])<tfoot><tr><th colspan="4">合计</th><th class="pwb-money">{{ number_format((float) $summary['total'], 2) }}</th></tr></tfoot>@endif</table></div>
<p class="pwb-panel-note">收款人、开户行、账号填「账号详见附件」,附件使用「种菜报销明细{{ $summary ? (int) substr($summary['bill_date'], 5, 2) . '.' . (int) substr($summary['bill_date'], 8, 2) : '' }}」。</p>
<p class="pwb-panel-note">收款人、开户行、账号填「账号详见附件」,附件使用「种菜报销明细{{ $summary ? (int) substr($summary['bill_date'], 5, 2) . '.' . (int) substr($summary['bill_date'], 8, 2) : '' }}」。点「提交钉钉流程」后由系统自动填好表单、上传附件并以李斯的名义发起。</p>
@include('business.pages.billing-transactions.partials.planting-workbench-dingtalk')
</div>
<div id="pwb-notices" role="tabpanel" aria-labelledby="pwb-tab-notices" data-pwb-panel="notices" hidden>
<div class="pwb-panel-heading"><div><h3>按发起人核对通知</h3><p>包含取消和待复查工单,可逐人复制;发群前仍需确认已核对。</p></div><a href="#pwb-robot" class="pwb-button" data-pwb-open-robot>机器人设置</a></div>
@if($summary)<form method="post" action="{{ route('business.planting-data.planting-reimbursement-workbench.notify') }}" class="pwb-notify">@csrf @foreach($exportQuery as $key => $value)<input type="hidden" name="{{ $key }}" value="{{ $value }}">@endforeach<label class="pwb-check"><input type="checkbox" name="verified" value="1" required>已核对条数和金额</label><button type="submit" class="pwb-button is-primary" @disabled(! $workbenchRobot['configured'] || ! $summary['notices'])>发取消通知到钉钉群({{ count($summary['notices']) }} 人)</button><label class="pwb-check"><input type="checkbox" name="force" value="1">已发过的也重发</label>@if(! $workbenchRobot['configured'])<small class="pwb-warning">尚未配置机器人,请先填写设置。</small>@endif</form>@endif
<div class="pwb-panel-heading"><div><h3>按发起人核对通知</h3><p>包含取消和待复查工单,每天 11:20 自动发到群里并 @ 发起人;也可逐人复制。</p></div><a href="#pwb-robot" class="pwb-button" data-pwb-open-robot>机器人设置</a></div>
@if($summary)<form method="post" action="{{ route('business.planting-data.planting-reimbursement-workbench.notify') }}" class="pwb-notify">@csrf @foreach($exportQuery as $key => $value)<input type="hidden" name="{{ $key }}" value="{{ $value }}">@endforeach<button type="submit" class="pwb-button is-primary" @disabled(! $workbenchRobot['configured'] || ! $summary['notices'])>发取消通知到钉钉群({{ count($summary['notices']) }} 人)</button><small>每天 11:20 会自动发,这里用于补发。</small><label class="pwb-check"><input type="checkbox" name="force" value="1">已发过的也重发</label>@if(! $workbenchRobot['configured'])<small class="pwb-warning">尚未配置机器人,请先填写设置。</small>@endif</form>@endif
@if($workbenchNoticeLog)<p class="pwb-panel-note">当天已发:{{ collect($workbenchNoticeLog)->map(fn ($v, $k) => $k . ' ' . substr($v['sent_at'], 11, 5))->implode('、') }}</p>@endif
@if($summary && $summary['counts'][Auditor::DECISION_RECHECK] > 0)<p class="pwb-panel-note pwb-warning">待复查:利润中心查不到的,先到工作平台补齐店铺所属利润中心;额度未校验的,稍后重新生成。</p>@endif
<div class="pwb-notice-list">@forelse($summary['notices'] ?? [] as $notice)<details class="pwb-notice"><summary><strong>{{ $notice['initiator'] }}</strong><span>{{ count($notice['items']) }} 单需处理</span><span class="material-icons-outlined pwb-chevron" aria-hidden="true">expand_more</span></summary><div><button type="button" class="pwb-button" data-pwb-copy>复制通知</button><pre>{{ $notice['message'] }}</pre><small>工单号:{{ implode('、', array_column($notice['items'], 'work_order_no')) }}</small></div></details>@empty<div class="pwb-empty">本批次没有需要取消或复查的工单,无需发送通知。</div>@endforelse</div>
</div>
</section>
@include('business.pages.billing-transactions.partials.planting-workbench-commission')
@include('business.pages.billing-transactions.partials.planting-workbench-rules')
@include('business.pages.billing-transactions.partials.planting-workbench-settings')
</div>

View File

@ -390,7 +390,7 @@ Route::get('workspace/planting-data/planting-loss/export', [\App\Http\Controller
->name('business.planting-data.planting-loss.export');
Route::post('workspace/planting-data/planting-reimbursement-workbench/upload/{kind}', [\App\Http\Controllers\Business\PlantingReimbursementWorkbench::class, 'upload'])
->where('kind', 'commission|roster')
->where('kind', 'roster')
->middleware(['business.page:planting-data,planting-reimbursement-workbench', 'throttle:import-upload'])
->name('business.planting-data.planting-reimbursement-workbench.upload');
@ -402,6 +402,30 @@ Route::post('workspace/planting-data/planting-reimbursement-workbench/notify', [
->middleware('business.page:planting-data,planting-reimbursement-workbench')
->name('business.planting-data.planting-reimbursement-workbench.notify');
Route::post('workspace/planting-data/planting-reimbursement-workbench/commission', [\App\Http\Controllers\Business\PlantingReimbursementWorkbench::class, 'addCommission'])
->middleware('business.page:planting-data,planting-reimbursement-workbench')
->name('business.planting-data.planting-reimbursement-workbench.commission.add');
Route::post('workspace/planting-data/planting-reimbursement-workbench/commission/remove', [\App\Http\Controllers\Business\PlantingReimbursementWorkbench::class, 'removeCommission'])
->middleware('business.page:planting-data,planting-reimbursement-workbench')
->name('business.planting-data.planting-reimbursement-workbench.commission.remove');
Route::post('workspace/planting-data/planting-reimbursement-workbench/commission/import', [\App\Http\Controllers\Business\PlantingReimbursementWorkbench::class, 'importCommission'])
->middleware(['business.page:planting-data,planting-reimbursement-workbench', 'throttle:import-upload'])
->name('business.planting-data.planting-reimbursement-workbench.commission.import');
Route::get('workspace/planting-data/planting-reimbursement-workbench/commission/export', [\App\Http\Controllers\Business\PlantingReimbursementWorkbench::class, 'exportCommission'])
->middleware('business.page:planting-data,planting-reimbursement-workbench')
->name('business.planting-data.planting-reimbursement-workbench.commission.export');
Route::get('workspace/planting-data/planting-reimbursement-workbench/dingtalk/preview', [\App\Http\Controllers\Business\PlantingReimbursementWorkbench::class, 'previewDingTalk'])
->middleware('business.page:planting-data,planting-reimbursement-workbench')
->name('business.planting-data.planting-reimbursement-workbench.dingtalk.preview');
Route::post('workspace/planting-data/planting-reimbursement-workbench/dingtalk/submit', [\App\Http\Controllers\Business\PlantingReimbursementWorkbench::class, 'submitDingTalk'])
->middleware('business.page:planting-data,planting-reimbursement-workbench')
->name('business.planting-data.planting-reimbursement-workbench.dingtalk.submit');
Route::post('workspace/planting-data/planting-reimbursement-workbench/rules', [\App\Http\Controllers\Business\PlantingReimbursementWorkbench::class, 'saveRule'])
->middleware('business.page:planting-data,planting-reimbursement-workbench')
->name('business.planting-data.planting-reimbursement-workbench.rules.save');

View File

@ -6,6 +6,7 @@ use App\Models\Auth\Permission;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\PlantingCommissionPeople;
use Modules\EcommerceFinance\Services\PlantingQuotaDimensions;
use Modules\EcommerceFinance\Services\PlantingQuotaRules;
use Modules\EcommerceFinance\Services\PlantingReimbursementDirectory;
@ -32,7 +33,8 @@ class PlantingReimbursementWorkbenchTest extends FeatureTestCase
private function mockRepository(array $rows): void
{
$repository = \Mockery::mock(PlantingReimbursementRepository::class);
$repository->shouldReceive('syncStatus')->andReturn(['code' => 'ready', 'last_succeeded_at' => '2026-11-12 12:57:00']);
// 放行检查要求 20 分钟内同步成功。
$repository->shouldReceive('syncStatus')->andReturn(['code' => 'ready', 'last_succeeded_at' => now()->subMinutes(3)->format('Y-m-d H:i:s')]);
$repository->shouldReceive('pendingRows')->with('2026-11-05 00:00:00', '2026-11-11 23:59:59', ['WAIT_CONFIRM'])->andReturn($rows);
$repository->shouldReceive('reimbursedOrders')->andReturn(['900' => '2026-11-03']);
// 额度:本月 1 日起的全部种菜工单(这里就是本批)。
@ -49,7 +51,7 @@ class PlantingReimbursementWorkbenchTest extends FeatureTestCase
$this->app->instance(PlantingReimbursementRepository::class, $repository);
Storage::fake('local');
$directory = \Mockery::mock(PlantingReimbursementDirectory::class);
$directory->shouldReceive('userIds')->andReturnUsing(static fn (array $names): array => array_intersect_key(['白菜' => 'U-BAICAI', '星璃' => 'U-XINGLI', '胖虎' => 'U-PANGHU'], array_flip($names)));
$directory->shouldReceive('userIds')->andReturnUsing(static fn (array $names): array => array_intersect_key(['白菜' => 'U-BAICAI', '星璃' => 'U-XINGLI', '胖虎' => 'U-PANGHU', '李斯' => 'U-LISI'], array_flip($names)));
$directory->shouldReceive('activeNames')->andReturn(['姚佳炜' => true, '王敏佳' => true]);
$this->app->instance(PlantingReimbursementDirectory::class, $directory);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
@ -78,11 +80,12 @@ class PlantingReimbursementWorkbenchTest extends FeatureTestCase
$this->row('104', '30.00', ['shop_name' => '天猫-新开的店']),
]);
$this->upload('commission', '报销佣金人员.csv', "平台,人员,佣金,人员,平台\n天猫,王也,10元,白菜,天猫\n")->assertRedirect();
// 以前上传过的报销佣金人员名单:第一次读取时自动导入。
Storage::disk('local')->put('planting-reimbursement-references/' . $this->company->id . '/commission.json', json_encode(['rows' => [['key' => '白菜', 'payload' => null]]], JSON_UNESCAPED_UNICODE));
$this->upload('roster', '花名册.csv', "序号,花名,姓名\n1,白,姚佳炜\n2,星,王敏佳\n")->assertRedirect();
// 104 的店铺在工作平台查不到利润中心 → 待复查;额度按初始 309 条规则(天猫 / 京喜 P2)计算,均未超额。
$this->assertSame(['白菜' => true], app(PlantingReimbursementReferences::class)->nameSet($this->company->id, 'commission'));
$this->assertSame(['白菜' => true], app(PlantingCommissionPeople::class)->nameSet($this->company->id));
$this->assertSame(['姚佳炜' => true, '王敏佳' => true], app(PlantingReimbursementReferences::class)->nameSet($this->company->id, 'roster'));
$this->loginAs()->get($this->url(['date' => '2026-11-12']))
@ -96,15 +99,16 @@ class PlantingReimbursementWorkbenchTest extends FeatureTestCase
->assertSee('不在在职花名册')
->assertSee('@星璃 以上订单本次不予报销', false)
->assertSee('待复查')
->assertSee('应为')
->assertSee('全部通过')
->assertSee('5 条', false)
->assertDontSee('已在聚工单核对')
->assertSee('钉钉明细合计 = 可报销合计')
->assertSee('平台+职级:天猫/P2')
->assertSee('种菜额度规则(309 条,启用 306)', false)
->assertDontSee('未上传看板');
$response = $this->loginAs()->get(route('business.planting-data.planting-reimbursement-workbench.export', [
'company_id' => $this->company->id, 'type' => 'reconciliation', 'date' => '2026-11-12', 'verified' => '1',
'company_id' => $this->company->id, 'type' => 'reconciliation', 'date' => '2026-11-12',
]));
$response->assertOk();
$this->assertStringContainsString('11.11.xlsx', (string) $response->headers->get('content-disposition'));
@ -112,14 +116,10 @@ class PlantingReimbursementWorkbenchTest extends FeatureTestCase
foreach (['details', 'import-template'] as $type) {
$this->loginAs()->get(route('business.planting-data.planting-reimbursement-workbench.export', [
'company_id' => $this->company->id, 'type' => $type, 'date' => '2026-11-12', 'verified' => '1',
'company_id' => $this->company->id, 'type' => $type, 'date' => '2026-11-12',
]))->assertOk();
}
// 没勾「已核对」不给导出。
$this->loginAs()->get(route('business.planting-data.planting-reimbursement-workbench.export', [
'company_id' => $this->company->id, 'type' => 'details', 'date' => '2026-11-12',
]))->assertRedirect()->assertSessionHas('error');
$this->withExceptionHandling()->loginAs()->get($this->url(['date' => '2026-13-40']))->assertStatus(422);
$this->withExceptionHandling()->loginAs()->get($this->url(['date' => '2026-11-12', 'paid_from' => '2026-11-12']))->assertStatus(422);
@ -162,7 +162,10 @@ class PlantingReimbursementWorkbenchTest extends FeatureTestCase
{
$this->mockRepository([]);
$this->upload('commission', 'x.csv', "a,b\n1,2\n")->assertRedirect()->assertSessionHas('error');
$this->upload('roster', 'x.csv', "a,b\n1,2\n")->assertRedirect()->assertSessionHas('error');
$this->loginAs()->post(route('business.planting-data.planting-reimbursement-workbench.commission.import', ['company_id' => $this->company->id]), [
'file' => UploadedFile::fake()->createWithContent('x.csv', "a,b\n1,2\n"),
])->assertSessionHas('error');
// 看板、店铺信息不再上传。
$status = $this->withExceptionHandling()->upload('monitor', 'x.csv', "a,b\n1,2\n")->status();
$this->assertContains($status, [404, 405]);
@ -219,6 +222,89 @@ class PlantingReimbursementWorkbenchTest extends FeatureTestCase
->assertSee('工作平台店铺信息暂时读不到');
}
public function test_commission_people_can_be_maintained(): void
{
$this->mockRepository([$this->row('101', '65.00', ['task_commission' => '5.00', 'task_payment' => '60.00'])]);
$url = fn (string $name): string => route('business.planting-data.planting-reimbursement-workbench.commission.' . $name, ['company_id' => $this->company->id]);
// 名单为空:带佣金的单取消。
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertViewHas('content', static fn (array $content): bool => array_column($content['workbenchRows'], 'decision') === ['cancel'])
->assertSee('报销佣金人员(0 人)', false);
$this->loginAs()->post($url('add'), ['name' => ' 白 菜 ', 'platform' => '天猫', 'date' => '2026-11-12'])->assertSessionHas('success');
$this->loginAs()->post($url('add'), ['name' => '白菜'])->assertSessionHas('error');
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertViewHas('content', static fn (array $content): bool => array_column($content['workbenchRows'], 'decision') === ['pass']);
$this->loginAs()->post($url('import'), ['file' => UploadedFile::fake()->createWithContent('报销佣金人员.csv', "平台,人员,佣金,人员,平台\n天猫,王也,10元,白菜,天猫\n,,,星璃,京东\n")])
->assertSessionHas('success', '报销佣金人员导入:新增 1 人,已在名单里 1 人。');
$this->assertStringContainsString('"星璃"', $this->loginAs()->get($url('export'))->streamedContent());
$this->loginAs()->post($url('remove'), ['name' => '白菜'])->assertSessionHas('success');
$this->assertSame(['星璃' => true], app(PlantingCommissionPeople::class)->nameSet($this->company->id));
}
public function test_stale_sync_blocks_export(): void
{
$this->mockRepository([$this->row('101', '60.00')]);
$repository = \Mockery::mock(PlantingReimbursementRepository::class);
$repository->shouldReceive('syncStatus')->andReturn(['code' => 'ready', 'last_succeeded_at' => now()->subHours(2)->format('Y-m-d H:i:s')]);
$repository->shouldReceive('pendingRows')->andReturn([$this->row('101', '60.00')]);
$repository->shouldReceive('quotaRows')->andReturn([$this->row('101', '60.00')]);
$repository->shouldReceive('reimbursedOrders')->andReturn([]);
$this->app->instance(PlantingReimbursementRepository::class, $repository);
$this->loginAs()->get(route('business.planting-data.planting-reimbursement-workbench.export', [
'company_id' => $this->company->id, 'type' => 'details', 'date' => '2026-11-12',
]))->assertRedirect()->assertSessionHas('error', fn (string $message): bool => str_contains($message, '超过 20 分钟没同步'));
}
public function test_dingtalk_preview_and_one_click_submit(): void
{
$this->mockRepository([$this->row('101', '60.00'), $this->row('102', '40.50')]);
config(['planting_reimbursement.dingtalk' => [
'enabled' => true, 'client_id' => 'ding-app', 'client_secret' => 'ding-secret', 'agent_id' => '3001',
'process_code' => 'PROC-C5159B8D-F412-4DF8-981D-64EBB8D03EB6', 'originator_flower_name' => '李斯', 'originator_user_id' => null, 'dept_id' => null,
]]);
Http::fake([
'api.dingtalk.com/v1.0/oauth2/accessToken' => Http::response(['accessToken' => 'TOKEN']),
'api.dingtalk.com/v1.0/workflow/forms/schemas/processCodes*' => Http::response(['result' => ['schemaContent' => ['items' => \Tests\Unit\EcommerceFinance\PlantingDingTalkFormTest::schema()]]]),
'oapi.dingtalk.com/topapi/v2/user/get*' => Http::response(['errcode' => 0, 'result' => ['unionid' => 'UNION-LISI', 'dept_id_list' => [123]]]),
'api.dingtalk.com/v1.0/workflow/processInstances/spaces/infos/query' => Http::response(['result' => ['spaceId' => 'S1']]),
'api.dingtalk.com/v1.0/storage/spaces/S1/files/uploadInfos/query*' => Http::response(['uploadKey' => 'UK', 'headerSignatureInfo' => ['resourceUrls' => ['https://upload.example.com/f'], 'headers' => ['Authorization' => 'sig']]]),
'upload.example.com/*' => Http::response('', 200),
'api.dingtalk.com/v1.0/storage/spaces/S1/files/commit*' => Http::response(['dentry' => ['id' => 'F1', 'spaceId' => 'S1', 'name' => '种菜报销明细11.11.xlsx', 'size' => 2048, 'extension' => 'xlsx']]),
'api.dingtalk.com/v1.0/workflow/processInstances' => Http::response(['instanceId' => 'INST-1']),
]);
Storage::disk('local')->put('planting-reimbursement-references/' . $this->company->id . '/commission-people.json', json_encode(['people' => [], 'source' => 'edited', 'updated_at' => null]));
$this->loginAs()->get($this->url(['date' => '2026-11-12', 'ding_preview' => '1']))->assertOk()
->assertSee('钉钉表单预览')
->assertSee('表单必填项都能自动填好')
->assertSee('U-LISI');
Http::assertNotSent(static fn ($request): bool => str_ends_with($request->url(), '/workflow/processInstances'));
$submitUrl = route('business.planting-data.planting-reimbursement-workbench.dingtalk.submit', ['company_id' => $this->company->id]);
$this->loginAs()->post($submitUrl, ['date' => '2026-11-12'])->assertSessionHas('success', fn (string $message): bool => str_contains($message, 'INST-1') && str_contains($message, '100.50'));
Http::assertSent(static function ($request): bool {
if (! str_ends_with($request->url(), '/workflow/processInstances')) {
return false;
}
$values = array_column($request['formComponentValues'], 'value', 'name');
return $request['originatorUserId'] === 'U-LISI' && $request['deptId'] === 123
&& $request['processCode'] === 'PROC-C5159B8D-F412-4DF8-981D-64EBB8D03EB6'
&& $values['收款合计'] === '100.50' && $values['报销类型'] === '种菜核销'
&& json_decode($values['附件'], true)[0]['fileId'] === 'F1'
&& count(json_decode($values['收款费用明细'], true)) === 1;
});
// 同一批不能重复提交。
$this->loginAs()->post($submitUrl, ['date' => '2026-11-12'])->assertSessionHas('error', fn (string $message): bool => str_contains($message, '已经在'));
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()->assertSee('审批编号 INST-1');
}
public function test_robot_settings_notices_and_daily_digest(): void
{
$this->mockRepository([
@ -240,24 +326,22 @@ class PlantingReimbursementWorkbenchTest extends FeatureTestCase
$page = $this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()->assertSee('钉钉机器人设置(已配置)')->assertSee('钉钉花名册');
$page->assertDontSee('SECRET-TOKEN-1234')->assertDontSee('SECabc');
// 未勾选已核对不发。
$this->loginAs()->post($notifyUrl, ['date' => '2026-11-12'])->assertSessionHas('error');
Http::assertNothingSent();
$this->loginAs()->post($notifyUrl, ['date' => '2026-11-12', 'verified' => '1'])->assertSessionHas('success');
$this->loginAs()->post($notifyUrl, ['date' => '2026-11-12'])->assertSessionHas('success');
Http::assertSentCount(2);
Http::assertSent(static fn ($request): bool => str_contains($request->url(), 'sign=')
&& $request['at']['atUserIds'] === ['U-XINGLI'] && str_contains($request['markdown']['text'], '900'));
Http::assertSent(static fn ($request): bool => $request['at']['atUserIds'] === ['U-BAICAI'] && str_contains($request['markdown']['text'], '103'));
// 同一批再点不重复发。
$this->loginAs()->post($notifyUrl, ['date' => '2026-11-12', 'verified' => '1'])->assertSessionHas('success', '群通知:发送 0 人,跳过已发 2 人。');
$this->loginAs()->post($notifyUrl, ['date' => '2026-11-12'])->assertSessionHas('success', '群通知:发送 0 人,跳过已发 2 人。');
Http::assertSentCount(2);
$this->artisan('planting-reimbursement:daily-digest', ['--date' => '2026-11-12'])->assertExitCode(0);
Http::assertSentCount(3);
// 每日汇总自动发不予报销通知:同一批已发过的跳过。
Http::assertSent(static fn ($request): bool => str_contains($request['markdown']['text'], '可报销:1 条')
&& str_contains($request['markdown']['text'], '3 条 / 90.00 元') && $request['at']['atUserIds'] === ['U-PANGHU']);
&& str_contains($request['markdown']['text'], '3 条 / 90.00 元') && str_contains($request['markdown']['text'], '已自动发不予报销通知:0 人(之前已发 2 人)')
&& $request['at']['atUserIds'] === ['U-PANGHU']);
// 当天只推一次。
$this->artisan('planting-reimbursement:daily-digest', ['--date' => '2026-11-12'])->assertExitCode(0);
Http::assertSentCount(3);

View File

@ -0,0 +1,91 @@
<?php
namespace Tests\Unit\EcommerceFinance;
use Modules\EcommerceFinance\Services\PlantingDingTalkForm as Form;
use PHPUnit\Framework\TestCase;
class PlantingDingTalkFormTest extends TestCase
{
/** 结构仿照钉钉表单接口返回(schemaContent.items)。 */
public static function schema(): array
{
$field = static fn (string $type, string $label, bool $required = true, array $extra = []): array => ['componentName' => $type, 'props' => ['label' => $label, 'required' => $required] + $extra];
return [
$field('TextNote', '说明'),
$field('DDSelectField', '报销类型', true, ['options' => [['key' => 'a', 'value' => '种菜核销'], ['key' => 'b', 'value' => '日常报销']]]),
['componentName' => 'TableField', 'props' => ['label' => '收款费用明细', 'required' => true], 'children' => [
$field('NumberField', '序号'),
$field('DepartmentField', '费用承担部门(利润中心)'),
$field('TextField', '店铺'),
$field('TextField', '用途'),
$field('MoneyField', '收款金额'),
$field('TextField', '备注', false),
]],
$field('MoneyField', '收款合计'),
$field('TextField', '收款人'),
$field('TextField', '开户行'),
$field('TextField', '账号'),
['componentName' => 'TableField', 'props' => ['label' => '付款明细', 'required' => false], 'children' => [
$field('TextField', '对应序号'),
$field('MoneyField', '付款金额'),
$field('DDSelectField', '付款方式', true, ['options' => ['{"key":"1","value":"银行卡"}', '{"key":"2","value":"支付宝"}']]),
$field('DDDateField', '打款时间', false),
]],
$field('DDAttachment', '附件'),
];
}
public static function summary(): array
{
return [
'bill_date' => '2026-11-11', 'purpose' => '11.11种菜报销', 'total' => '130.50',
'ding_lines' => [
['department' => '运营中心A', 'shop' => '欧意朗', 'purpose' => '11.11种菜报销', 'payment_method' => '银行卡', 'cents' => 10050],
['department' => '运营中心G', 'shop' => '其他', 'purpose' => '11.11种菜报销', 'payment_method' => '银行卡', 'cents' => 3000],
],
];
}
public function test_fills_form_by_labels_and_attachment(): void
{
$attachment = ['spaceId' => 'S1', 'fileName' => '种菜报销明细11.11.xlsx', 'fileSize' => '123', 'fileType' => 'xlsx', 'fileId' => 'F1'];
$result = (new Form())->build(self::schema(), self::summary(), $attachment, '种菜报销明细11.11.xlsx');
$this->assertSame([], $result['missing']);
$this->assertSame([], $result['invalid']);
$values = array_column($result['values'], 'value', 'name');
$this->assertSame('种菜核销', $values['报销类型']);
$this->assertSame('130.50', $values['收款合计']);
$this->assertSame('账号详见附件', $values['收款人']);
$this->assertSame('账号详见附件', $values['账号']);
$this->assertSame([
[['name' => '序号', 'value' => '1'], ['name' => '费用承担部门(利润中心)', 'value' => '运营中心A'], ['name' => '店铺', 'value' => '欧意朗'], ['name' => '用途', 'value' => '11.11种菜报销'], ['name' => '收款金额', 'value' => '100.50']],
[['name' => '序号', 'value' => '2'], ['name' => '费用承担部门(利润中心)', 'value' => '运营中心G'], ['name' => '店铺', 'value' => '其他'], ['name' => '用途', 'value' => '11.11种菜报销'], ['name' => '收款金额', 'value' => '30.00']],
], json_decode($values['收款费用明细'], true));
$this->assertSame([[['name' => '对应序号', 'value' => '1-2'], ['name' => '付款金额', 'value' => '130.50'], ['name' => '付款方式', 'value' => '银行卡']]], json_decode($values['付款明细'], true));
$this->assertSame([$attachment], json_decode($values['附件'], true));
$this->assertArrayNotHasKey('说明', $values);
// 预览时不带附件:不出附件值,但不算缺字段。
$preview = (new Form())->build(self::schema(), self::summary(), null, '种菜报销明细11.11.xlsx');
$this->assertSame([], $preview['missing']);
$this->assertArrayNotHasKey('附件', array_column($preview['values'], 'value', 'name'));
}
public function test_reports_required_fields_it_cannot_fill_and_bad_options(): void
{
$schema = self::schema();
$schema[] = ['componentName' => 'DDDateField', 'props' => ['label' => '报销日期', 'required' => true]];
$schema[1]['props']['options'] = [['key' => 'b', 'value' => '日常报销']];
array_pop($schema[2]['children']);
$schema[2]['children'][] = ['componentName' => 'TextField', 'props' => ['label' => '经办人', 'required' => true]];
$withoutAttachment = array_values(array_filter($schema, static fn (array $item): bool => $item['componentName'] !== 'DDAttachment'));
$result = (new Form())->build($withoutAttachment, self::summary(), null, 'x.xlsx');
$this->assertSame(['收款费用明细 → 经办人', '报销日期', '附件(表单里没有附件字段,无法附上打款明细)'], $result['missing']);
$this->assertSame(['报销类型(选项里没有「种菜核销」)'], $result['invalid']);
}
}