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