From b5244362a11b69fe4eacda16da3df8d5a1c65dbc Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Tue, 1 Dec 2026 05:56:51 +0000 Subject: [PATCH] =?UTF-8?q?feat(=E7=A7=8D=E8=8F=9C=E6=8A=A5=E9=94=80):=20?= =?UTF-8?q?=E4=BD=A3=E9=87=91=E4=BA=BA=E5=91=98=E5=8F=AF=E7=BB=B4=E6=8A=A4?= =?UTF-8?q?=E3=80=81=E8=87=AA=E5=8A=A8=E6=94=BE=E8=A1=8C=E6=A3=80=E6=9F=A5?= =?UTF-8?q?=E3=80=81=E8=87=AA=E5=8A=A8=E5=8F=91=E9=80=9A=E7=9F=A5=E3=80=81?= =?UTF-8?q?=E4=B8=80=E9=94=AE=E6=8F=90=E4=BA=A4=E9=92=89=E9=92=89=E6=B5=81?= =?UTF-8?q?=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 报销佣金人员改为工作台维护(新增 / 移除 / 追加导入 / 导出),首次读取时自动导入以前上传的历史名单 - 去掉「去聚工单人工核对、勾选已核对」:改为放行检查(聚工单 20 分钟内同步过、额度已校验、 规则不为空、自检全过、有可报销单),不通过不许导出 / 发通知 / 提交,并在页面列出原因 - 每天 11:20 汇总任务放行检查通过后自动发不予报销通知(@ 发起人,同一批不重发) - 一键提交钉钉「种菜报销流程」(PROC-C5159B8D…):发起人李斯(按钉钉花名册查 userId), 按钉钉表单实际结构自动填(收款费用明细 / 收款合计 / 收款人·开户行·账号=账号详见附件 / 付款明细 / 报销类型=种菜核销),打款明细 xlsx 上传审批钉盘作附件;先可预览, 缺必填 / 选项不匹配不许提交;同一账单日只提交一次,结果不确定记待核查 - 新配置 config/planting_reimbursement.php(凭据默认沿用快递入驻的财务系统钉钉应用, 需补 PLANTING_DINGTALK_AGENT_ID) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UNTa9ohkCsVFACqjz3KMcG --- .../PlantingReimbursementDailyDigest.php | 24 +- .../PlantingReimbursementWorkbench.php | 103 +++++++- config/planting_reimbursement.php | 17 ++ .../Services/PlantingCommissionPeople.php | 134 +++++++++++ .../Services/PlantingDingTalkClient.php | 171 +++++++++++++ .../Services/PlantingDingTalkForm.php | 226 ++++++++++++++++++ .../Services/PlantingDingTalkSubmission.php | 165 +++++++++++++ .../PlantingDingTalkUncertainException.php | 8 + .../Services/PlantingReimbursementGate.php | 52 ++++ .../PlantingReimbursementReferences.php | 9 +- .../PlantingReimbursementWorkbench.php | 4 +- ...PlantingReimbursementWorkbenchPageData.php | 30 +++ .../planting-workbench-assets.blade.php | 2 + .../planting-workbench-commission.blade.php | 55 +++++ .../planting-workbench-dingtalk.blade.php | 44 ++++ .../planting-workbench-settings.blade.php | 4 +- ...planting-reimbursement-workbench.blade.php | 17 +- routes/admin.php | 26 +- .../PlantingReimbursementWorkbenchTest.php | 122 ++++++++-- .../PlantingDingTalkFormTest.php | 91 +++++++ 20 files changed, 1252 insertions(+), 52 deletions(-) create mode 100644 config/planting_reimbursement.php create mode 100644 modules/EcommerceFinance/Services/PlantingCommissionPeople.php create mode 100644 modules/EcommerceFinance/Services/PlantingDingTalkClient.php create mode 100644 modules/EcommerceFinance/Services/PlantingDingTalkForm.php create mode 100644 modules/EcommerceFinance/Services/PlantingDingTalkSubmission.php create mode 100644 modules/EcommerceFinance/Services/PlantingDingTalkUncertainException.php create mode 100644 modules/EcommerceFinance/Services/PlantingReimbursementGate.php create mode 100644 resources/views/business/pages/billing-transactions/partials/planting-workbench-commission.blade.php create mode 100644 resources/views/business/pages/billing-transactions/partials/planting-workbench-dingtalk.blade.php create mode 100644 tests/Unit/EcommerceFinance/PlantingDingTalkFormTest.php diff --git a/app/Console/Commands/PlantingReimbursementDailyDigest.php b/app/Console/Commands/PlantingReimbursementDailyDigest.php index 4a7a7d4a..00b5f9c8 100644 --- a/app/Console/Commands/PlantingReimbursementDailyDigest.php +++ b/app/Console/Commands/PlantingReimbursementDailyDigest.php @@ -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)]; } diff --git a/app/Http/Controllers/Business/PlantingReimbursementWorkbench.php b/app/Http/Controllers/Business/PlantingReimbursementWorkbench.php index b9dd8958..04755d32 100644 --- a/app/Http/Controllers/Business/PlantingReimbursementWorkbench.php +++ b/app/Http/Controllers/Business/PlantingReimbursementWorkbench.php @@ -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([ diff --git a/config/planting_reimbursement.php b/config/planting_reimbursement.php new file mode 100644 index 00000000..23af5098 --- /dev/null +++ b/config/planting_reimbursement.php @@ -0,0 +1,17 @@ + [ + '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'), + ], +]; diff --git a/modules/EcommerceFinance/Services/PlantingCommissionPeople.php b/modules/EcommerceFinance/Services/PlantingCommissionPeople.php new file mode 100644 index 00000000..055769c3 --- /dev/null +++ b/modules/EcommerceFinance/Services/PlantingCommissionPeople.php @@ -0,0 +1,134 @@ +/commission.json)初始化。 + * 存为 storage/app/planting-reimbursement-references/<公司>/commission-people.json(持久卷),不建表。 + */ +class PlantingCommissionPeople +{ + public const FILE = 'commission-people.json'; + + /** @var array> */ + private array $loaded = []; + + public function __construct(private readonly PlantingReimbursementReferences $references) {} + + /** @return array{people:list,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 姓名集合(给校验用) */ + 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> $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; + } +} diff --git a/modules/EcommerceFinance/Services/PlantingDingTalkClient.php b/modules/EcommerceFinance/Services/PlantingDingTalkClient.php new file mode 100644 index 00000000..5a3e38b2 --- /dev/null +++ b/modules/EcommerceFinance/Services/PlantingDingTalkClient.php @@ -0,0 +1,171 @@ + */ + 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> 表单组件(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 发起人所在部门 */ + 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; + } +} diff --git a/modules/EcommerceFinance/Services/PlantingDingTalkForm.php b/modules/EcommerceFinance/Services/PlantingDingTalkForm.php new file mode 100644 index 00000000..c79caca7 --- /dev/null +++ b/modules/EcommerceFinance/Services/PlantingDingTalkForm.php @@ -0,0 +1,226 @@ + ['收款合计', '报销合计', '合计金额', '金额合计', '报销金额合计', '付款合计', '总金额', '报销总金额'], + '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> $schema 钉钉表单组件(schemaContent.items) + * @param array $summary 工作台批次汇总(ding_lines、total、purpose、bill_date) + * @param array|null $attachment 已上传附件;预览时为 null + * @return array{values:list>,preview:list>,missing:list,invalid:list,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> */ + 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 */ + 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> $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, '.', ''); + } +} diff --git a/modules/EcommerceFinance/Services/PlantingDingTalkSubmission.php b/modules/EcommerceFinance/Services/PlantingDingTalkSubmission.php new file mode 100644 index 00000000..5beefa51 --- /dev/null +++ b/modules/EcommerceFinance/Services/PlantingDingTalkSubmission.php @@ -0,0 +1,165 @@ +/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|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 $result 工作台批次 + * @return array + */ + 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 $result + * @return array 提交记录 + */ + 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'; + } +} diff --git a/modules/EcommerceFinance/Services/PlantingDingTalkUncertainException.php b/modules/EcommerceFinance/Services/PlantingDingTalkUncertainException.php new file mode 100644 index 00000000..801d32db --- /dev/null +++ b/modules/EcommerceFinance/Services/PlantingDingTalkUncertainException.php @@ -0,0 +1,8 @@ + $result PlantingReimbursementWorkbench::build() 的结果 + * @return array{ok:bool,reasons:list} + */ + 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]; + } +} diff --git a/modules/EcommerceFinance/Services/PlantingReimbursementReferences.php b/modules/EcommerceFinance/Services/PlantingReimbursementReferences.php index 1c1ccdd9..ad2adf76 100644 --- a/modules/EcommerceFinance/Services/PlantingReimbursementReferences.php +++ b/modules/EcommerceFinance/Services/PlantingReimbursementReferences.php @@ -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|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('未知的名单类型。'); } diff --git a/modules/EcommerceFinance/Services/PlantingReimbursementWorkbench.php b/modules/EcommerceFinance/Services/PlantingReimbursementWorkbench.php index 9f818994..257da90a 100644 --- a/modules/EcommerceFinance/Services/PlantingReimbursementWorkbench.php +++ b/modules/EcommerceFinance/Services/PlantingReimbursementWorkbench.php @@ -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), ]; } diff --git a/modules/EcommerceFinance/View/PlantingReimbursementWorkbenchPageData.php b/modules/EcommerceFinance/View/PlantingReimbursementWorkbenchPageData.php index cff02efa..73ea8658 100644 --- a/modules/EcommerceFinance/View/PlantingReimbursementWorkbenchPageData.php +++ b/modules/EcommerceFinance/View/PlantingReimbursementWorkbenchPageData.php @@ -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 */ + 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 */ + 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 */ private function safeUploads(): array { diff --git a/resources/views/business/pages/billing-transactions/partials/planting-workbench-assets.blade.php b/resources/views/business/pages/billing-transactions/partials/planting-workbench-assets.blade.php index 1164367e..6e43fb99 100644 --- a/resources/views/business/pages/billing-transactions/partials/planting-workbench-assets.blade.php +++ b/resources/views/business/pages/billing-transactions/partials/planting-workbench-assets.blade.php @@ -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'}); } })(); @endpush diff --git a/resources/views/business/pages/billing-transactions/partials/planting-workbench-commission.blade.php b/resources/views/business/pages/billing-transactions/partials/planting-workbench-commission.blade.php new file mode 100644 index 00000000..0f9f5364 --- /dev/null +++ b/resources/views/business/pages/billing-transactions/partials/planting-workbench-commission.blade.php @@ -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 +
+ 报销佣金人员({{ number_format(count($commission['people'])) }} 人) · {{ $commissionSource }}@if($commission['updated_at']) · {{ substr($commission['updated_at'], 0, 16) }}@endif + @if($commission['error'])

{{ $commission['error'] }}

@endif +

工单里有佣金、而发起人不在这个名单的,取消工单。新增发起人在这里加;以前上传过的名单已经导入。

+
+ @csrf + @foreach($commissionQuery as $key => $value)@endforeach + + + + +
+
+ +
+ 导出名单 +
+ @csrf + @foreach($commissionQuery as $key => $value)@endforeach + +
+
+
+
+ + + + @forelse($commission['people'] as $person) + + + + + @empty + + @endforelse + +
花名平台备注加入时间操作
{{ $person['name'] }}{{ $person['platform'] ?: '—' }}{{ $person['remark'] ?: '' }}{{ $person['added_at'] ? substr($person['added_at'], 0, 16) : '—' }}
@csrf @foreach($commissionQuery as $key => $value)@endforeach
名单是空的:所有带佣金的工单都会取消。
+
+
+ diff --git a/resources/views/business/pages/billing-transactions/partials/planting-workbench-dingtalk.blade.php b/resources/views/business/pages/billing-transactions/partials/planting-workbench-dingtalk.blade.php new file mode 100644 index 00000000..a6bac699 --- /dev/null +++ b/resources/views/business/pages/billing-transactions/partials/planting-workbench-dingtalk.blade.php @@ -0,0 +1,44 @@ +@php + $dingQuery = ['date' => $workbenchFilters['date'], 'paid_from' => $workbenchFilters['paid_from'], 'scope' => $workbenchFilters['scope']]; + $record = $workbenchDingRecord; + $preview = $workbenchDingPreview; +@endphp +@if($summary) +
+ @if($record && $record['status'] === 'submitted') +

已在 {{ $record['submitted_at'] }} 以 {{ $record['originator'] }} 的名义提交钉钉「种菜报销流程」:{{ number_format((float) $record['total'], 2) }} 元,{{ $record['lines'] }} 行明细,附件 {{ $record['attachment'] }},审批编号 {{ $record['instance_id'] }}。同一批不会再重复提交。

+ @else + @if($record && $record['status'] === 'uncertain') + + @endif +
+ 预览钉钉表单 +
+ @csrf + @foreach($dingQuery as $key => $value)@endforeach + @if($record && $record['status'] === 'uncertain')@endif + +
+
+ @if(! ($workbenchGate['ok'] ?? false))

放行检查没通过,暂不能提交:{{ implode(';', $workbenchGate['reasons'] ?? []) }}。

@endif + @endif + + @if($preview) + @if($preview['error']) + + @else +

钉钉表单预览

发起人 {{ $preview['originator']['name'] }}({{ $preview['originator']['user_id'] }}{{ $preview['originator']['dept_id'] ? ',部门 ' . $preview['originator']['dept_id'] : '' }});附件 {{ $preview['attachment_name'] }}。

+ @if($preview['missing'] || $preview['invalid'])@else

表单必填项都能自动填好,可以提交。

@endif +
+ @foreach($preview['preview'] as $field) + + @endforeach +
字段类型必填自动填入
{{ $field['label'] }}{{ $field['type'] }}{{ $field['required'] ? '是' : '' }} + @if(isset($field['rows'])) + @foreach($field['rows'] as $row)
{{ collect($row)->map(fn ($cell) => $cell['name'] . ':' . $cell['value'])->implode(';') }}
@endforeach + @else{{ $field['value'] !== '' ? $field['value'] : '—' }}@endif +
+ @endif + @endif +
+@endif diff --git a/resources/views/business/pages/billing-transactions/partials/planting-workbench-settings.blade.php b/resources/views/business/pages/billing-transactions/partials/planting-workbench-settings.blade.php index 21f46ede..aa0c4c90 100644 --- a/resources/views/business/pages/billing-transactions/partials/planting-workbench-settings.blade.php +++ b/resources/views/business/pages/billing-transactions/partials/planting-workbench-settings.blade.php @@ -10,7 +10,7 @@ @if($workbenchRobot['digest_webhook'])@endif -

Webhook 和密钥加密保存,页面不回显,留空表示不改。每天 11:20 自动把当天批次汇总推到群里并 @ 报销人;取消通知要在上面核对后手动点发送。

+

Webhook 和密钥加密保存,页面不回显,留空表示不改。每天 11:20 自动把当天批次汇总推到群里并 @ 报销人,同时自动发不予报销通知(@ 发起人,已发过的不重发);放行检查没通过时只推汇总、不发通知。

-
校验规则

取单与聚工单锁单一致:种菜报销、工单状态待处理(可切换处理中)、订单付款时间默认报销日前 7 天至前一天、ERP订单状态不为取消 / 删除 / 空、售后单号为空。

取消工单:重复报销(本月、上月已报销过或本批重复);最终报销金额 ≠ 任务付款+快递费+佣金+京喜差价−扣款+空包费;发起人不在报销佣金人员名单却报了佣金;收款人不在花名册在职名单(柴嘉伟(建行)除外);种菜额度单笔 / 每日 / 月度超额(全部取消,不按付款先后保留);未匹配负责人、职级为空、职级未配置、额度规则未配置。

种菜额度口径(同「脉象」每日种菜监控看板):金额取工单实付金额字段(为空才取最终报销金额);商品ID → ID负责人(取第一个有负责人的商品,都没有用店长兜底)→ 职级;规则优先级 ID负责人 > 店铺+职级 > 店铺 > 平台+职级;同一负责人同一额度域内,按支付日、支付月累计(含已报销的单,排除驳回、作废)。

待复查:店铺在工作平台店铺信息里查不到利润中心;额度数据暂时取不到。

+
校验规则

取单与聚工单锁单一致:种菜报销、工单状态待处理(可切换处理中)、订单付款时间默认报销日前 7 天至前一天、ERP订单状态不为取消 / 删除 / 空、售后单号为空。

取消工单:重复报销(本月、上月已报销过或本批重复);最终报销金额 ≠ 任务付款+快递费+佣金+京喜差价−扣款+空包费;发起人不在报销佣金人员名单却报了佣金;收款人不在花名册在职名单(柴嘉伟(建行)除外);种菜额度单笔 / 每日 / 月度超额(全部取消,不按付款先后保留);未匹配负责人、职级为空、职级未配置、额度规则未配置。

种菜额度口径(同「脉象」每日种菜监控看板):金额取工单实付金额字段(为空才取最终报销金额);商品ID → ID负责人(取第一个有负责人的商品,都没有用店长兜底)→ 职级;规则优先级 ID负责人 > 店铺+职级 > 店铺 > 平台+职级;同一负责人同一额度域内,按支付日、支付月累计(含已报销的单,排除驳回、作废)。

待复查:店铺在工作平台店铺信息里查不到利润中心;额度数据暂时取不到。

放行检查(替代去聚工单人工核对):聚工单数据 20 分钟内同步过、种菜额度已校验、额度规则不为空、金额与条数自检全部通过,才允许导出、发通知和提交钉钉流程。

diff --git a/resources/views/business/pages/billing-transactions/planting-reimbursement-workbench.blade.php b/resources/views/business/pages/billing-transactions/planting-reimbursement-workbench.blade.php index c84f79f2..99f4863b 100644 --- a/resources/views/business/pages/billing-transactions/planting-reimbursement-workbench.blade.php +++ b/resources/views/business/pages/billing-transactions/planting-reimbursement-workbench.blade.php @@ -45,7 +45,7 @@ @endif
- 参考资料{{ count(array_filter($workbenchUploads)) }} / {{ count(References::KINDS) }} 已上传按需更新名单;种菜额度与店铺信息自动读取,不用上传 + 参考资料{{ count(array_filter($workbenchUploads)) }} / {{ count(References::KINDS) }} 已上传花名册可选上传(不传则按钉钉花名册);佣金人员、额度规则在下方维护
@foreach(References::KINDS as $kind => $label) @php $upload = $workbenchUploads[$kind] ?? null; @endphp @@ -66,12 +66,11 @@ @if($workbenchRosterSource === 'none')

未取得在职名单,本次未校验收款人是否在职。请在参考资料中上传花名册。

@endif @if($summary) -
-
核对聚工单原数据

相同条件下,应为 {{ number_format($summary['source']['count']) }} 条 / 最终报销金额 {{ number_format((float) $summary['source']['amount'], 2) }} 元。一致后再导出。

查看核对条件

聚工单「打款工单 → 种菜报销」:工单状态 {{ Workbench::SCOPES[$workbenchFilters['scope']] }};付款时间 {{ $workbenchWindow['from'] }} 至 {{ $workbenchWindow['to'] }};ERP订单状态除取消 / 删除 / 为空 / 不为空外全选,售后单号查询为空。条数或金额不一致,先别报销。

+
+
放行检查@if($workbenchGate && $workbenchGate['ok'])

全部通过:聚工单数据是最新的、种菜额度已校验、金额与条数自检通过,可以导出和提交。本批 {{ number_format($summary['source']['count']) }} 条 / {{ number_format((float) $summary['source']['amount'], 2) }} 元。

@else

暂不能导出、提交:{{ implode(';', $workbenchGate['reasons'] ?? ['数据未就绪']) }}。

@endif
取单条件

聚工单「打款工单 → 种菜报销」:工单状态 {{ Workbench::SCOPES[$workbenchFilters['scope']] }};付款时间 {{ $workbenchWindow['from'] }} 至 {{ $workbenchWindow['to'] }};ERP订单状态不为取消 / 删除 / 空,售后单号为空。不再需要去聚工单人工核对条数和金额。

@foreach($exportQuery as $key => $value)@endforeach - -
@foreach(Exporter::TYPES as $type => $label)@endforeach
+
@foreach(Exporter::TYPES as $type => $label)@endforeach
金额与条数自检 {{ $checkCount }} / {{ count($summary['checks']) }} 通过
    @foreach($summary['checks'] as $check)
  • {{ $check['ok'] ? '✓' : '✗' }} {{ $check['label'] }}
  • @endforeach

标记已打款、提交钉钉后,用聚工单「已完成」状态 + 完成时间复核:{{ $summary['counts'][Auditor::DECISION_PASS] }} 条 / {{ number_format((float) $summary['total'], 2) }} 元,并确认钉钉收款合计相同。

@@ -100,16 +99,18 @@
+ @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')
diff --git a/routes/admin.php b/routes/admin.php index 2229576e..3ab42104 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -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'); diff --git a/tests/Feature/Business/PlantingReimbursementWorkbenchTest.php b/tests/Feature/Business/PlantingReimbursementWorkbenchTest.php index d99076a5..3fccb40b 100644 --- a/tests/Feature/Business/PlantingReimbursementWorkbenchTest.php +++ b/tests/Feature/Business/PlantingReimbursementWorkbenchTest.php @@ -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); diff --git a/tests/Unit/EcommerceFinance/PlantingDingTalkFormTest.php b/tests/Unit/EcommerceFinance/PlantingDingTalkFormTest.php new file mode 100644 index 00000000..18c5ae39 --- /dev/null +++ b/tests/Unit/EcommerceFinance/PlantingDingTalkFormTest.php @@ -0,0 +1,91 @@ + ['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']); + } +}