CaiWuXiTong/app/Http/Controllers/Business/PlantingReimbursementWorkbench.php
limeng b5244362a1 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
2026-12-01 05:56:51 +00:00

251 lines
13 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\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']));
}
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 : ''));
}
}