CaiWuXiTong/app/Http/Controllers/Business/PlantingReimbursementWorkbench.php
limeng 8e1d9ab778 feat(种菜报销): 确认本批 + 聚工单操作清单,提速商品负责人查询
- 确认本批:把当天校验结果固定下来(每天 11:20 放行检查通过自动确认,也可手动;钉钉已提交前可撤销),
  之后页面、导出、通知、提交钉钉都按确认时的结果,聚工单锁单 / 标记打款后批次不再消失
- 聚工单操作清单(同手工顺序):① 整批锁单(标处理中)② 取消判为取消的 ③ 打款后标记打款(变为已完成),
  给出未完成工单的线上订单号(逗号分隔可直接粘贴查询)和工单编号,进度按同步回来的工单状态核对
- 取单默认改为「待处理 + 处理中」:整批锁单后待复查的单留在处理中,下次批次再带进来
- 商品负责人查询:商品ID 校验后内联为 varchar 字面量(参数按 nvarchar 绑定用不上索引,本机实测 2,271 个商品 181 秒),
  并按商品缓存一天,只查新出现的商品
- 每日群汇总写明本批确认情况和聚工单三步待办数

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UNTa9ohkCsVFACqjz3KMcG
2026-12-01 06:38:03 +00:00

277 lines
14 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
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\PlantingReimbursementBatches as Batches;
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;
use Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData as PageData;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
/** 种菜报销工作台:上传参考名单、维护种菜额度规则、导出对账 / 打款明细 / 种菜任务工单导入模板。 */
class PlantingReimbursementWorkbench extends Controller
{
public function upload(Request $request, string $kind, References $references)
{
abort_unless(isset(References::KINDS[$kind]), 404);
$request->validate(['file' => ['required', 'file', 'max:51200']]);
$file = $request->file('file');
$name = (string) $file->getClientOriginalName();
$redirect = redirect()->route('business.pages.show', [
'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', ''),
]);
try {
$rows = $references->parse($kind, (string) $file->getRealPath(), $name);
$references->replace((int) company_id(), $kind, $rows, $name, optional(user())->id);
} catch (InvalidArgumentException $exception) {
return $redirect->with('error', References::KINDS[$kind] . '上传失败:' . $exception->getMessage());
} catch (\Throwable $exception) {
report($exception);
return $redirect->with('error', References::KINDS[$kind] . '上传失败,请检查文件格式后重新上传。');
}
return $redirect->with('success', sprintf('%s已更新:%s 条。', References::KINDS[$kind], number_format(count($rows))));
}
public function export(string $type, PageData $page, Exporter $exporter)
{
abort_unless(isset(Exporter::TYPES[$type]), 404);
$filters = $page->filters();
try {
$result = $page->build($filters);
} 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');
}, $exporter->fileName($type, $result['summary']), [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
]);
}
public function saveRobot(Request $request, Robot $robot)
{
$robot->save([
'webhook' => (string) $request->input('webhook', ''),
'secret' => (string) $request->input('secret', ''),
'keyword' => (string) $request->input('keyword', ''),
'reporters' => (string) $request->input('reporters', ''),
'digest_webhook' => (string) $request->input('digest_webhook', ''),
'digest_secret' => (string) $request->input('digest_secret', ''),
'clear_digest' => $request->boolean('clear_digest'),
]);
return $this->back($request)->with('success', '钉钉机器人设置已保存。');
}
/** 按发起人把取消 / 待复查通知发到钉钉群(放行检查通过才发;每天 11:20 也会自动发)。 */
public function notify(Request $request, PageData $page, Robot $robot)
{
$filters = $page->filters();
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);
return $this->back($request)->with('error', '群通知发送失败:' . mb_substr($exception->getMessage(), 0, 120));
}
$message = sprintf('群通知:发送 %d 人,跳过已发 %d 人', $sent['sent'], $sent['skipped']);
if ($sent['failed'] > 0) {
$message .= ',失败 ' . $sent['failed'] . ' 人';
}
if ($sent['unmatched'] !== []) {
$message .= ';钉钉里没匹配到、未能 @ 的:' . implode('、', $sent['unmatched']);
}
return $this->back($request)->with($sent['failed'] > 0 ? 'error' : 'success', $message . '。');
}
/** 新增 / 修改一条种菜额度规则。 */
public function saveRule(Request $request, QuotaRules $rules)
{
$id = $request->filled('id') ? (int) $request->input('id') : null;
try {
$rule = $rules->save((int) company_id(), $id, $request->only(QuotaRules::FIELDS), optional(user())->id);
} catch (InvalidArgumentException $exception) {
return $this->back($request, 'pwb-rules')->withInput()->with('error', '额度规则保存失败:' . $exception->getMessage());
}
return $this->back($request, 'pwb-rules')->with('success', ($id === null ? '已新增' : '已修改') . '额度规则:' . \Modules\EcommerceFinance\Services\PlantingQuotaCalculator::ruleLabel($rule) . '。');
}
public function deleteRule(Request $request, int $rule, QuotaRules $rules)
{
try {
$rules->delete((int) company_id(), $rule, optional(user())->id);
} catch (InvalidArgumentException $exception) {
return $this->back($request, 'pwb-rules')->with('error', $exception->getMessage());
}
return $this->back($request, 'pwb-rules')->with('success', '已删除额度规则。');
}
/** 用 CSV 整体替换额度规则(脉象导出格式或本页「导出规则」的文件)。 */
public function importRules(Request $request, QuotaRules $rules)
{
$request->validate(['file' => ['required', 'file', 'max:5120']]);
try {
$count = $rules->import((int) company_id(), (string) file_get_contents((string) $request->file('file')->getRealPath()), optional(user())->id);
} catch (InvalidArgumentException $exception) {
return $this->back($request, 'pwb-rules')->with('error', '额度规则导入失败:' . $exception->getMessage());
}
return $this->back($request, 'pwb-rules')->with('success', sprintf('额度规则已整体替换:%d 条。', $count));
}
public function exportRules(QuotaRules $rules)
{
$csv = $rules->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']);
}
/** 报销佣金人员:新增一人。 */
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']));
}
/** 确认本批:把当前校验结果固定下来,之后导出、通知、提交钉钉、聚工单操作都以它为准。 */
public function confirmBatch(Request $request, PageData $page, Batches $batches)
{
$filters = $page->filters();
try {
$batch = $batches->confirm((int) company_id(), $filters['date'], $page->fresh($filters), $filters, optional(user())->id);
} catch (\RuntimeException $exception) {
return $this->back($request)->with('error', $exception->getMessage());
}
return $this->back($request, 'pwb-ops')->with('success', sprintf('已确认本批:%d 单,其中可报销 %d 单 / %s 元。下一步在聚工单整批锁单。', $batch['summary']['source']['count'], $batch['summary']['counts']['pass'], number_format((float) $batch['summary']['total'], 2)));
}
/** 撤销确认,重新按聚工单当前状态取单(钉钉流程已提交的不能撤销)。 */
public function discardBatch(Request $request, PageData $page, Batches $batches, DingTalkSubmission $dingTalk)
{
try {
$batches->discard((int) company_id(), $page->filters()['date'], $dingTalk);
} catch (\RuntimeException $exception) {
return $this->back($request)->with('error', $exception->getMessage());
}
return $this->back($request)->with('success', '已撤销确认,当前显示的是按聚工单最新状态重新生成的批次。');
}
private function back(Request $request, string $fragment = '')
{
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', ''),
], static fn ($v) => $v !== '')) . ($fragment !== '' ? '#' . $fragment : ''));
}
}