CaiWuXiTong/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php

1154 lines
49 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 Modules\EcommerceFinance\Services;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use RuntimeException;
use Throwable;
/**
* 供应商对账:按供应商保存钉钉群机器人,推送对账汇总、货款差异或整月退货。
*/
class SupplierDingTalkNotifier
{
private const SETTING_KEY = 'supplier_reconciliation.dingtalk_robots';
private const ROWS_PER_MESSAGE = 30;
private const MAX_MESSAGES = 20;
public function __construct(
private readonly SupplierReturnShareLink $returnShareLinks,
private readonly SupplierSummaryAICard $summaryAICard,
private readonly SupplierSummaryConfirmation $summaryConfirmations,
private readonly SupplierSummaryShareLink $summaryShareLinks,
) {
}
/**
* @return array{
* configured:bool,
* webhook_hint:string,
* at_all:bool,
* card_group_configured:bool,
* card_group_hint:string,
* card_robot_configured:bool,
* card_robot_hint:string,
* last_pushed_at:string,
* last_push_count:int
* }
*/
public function configuration(string $supplier): array
{
return $this->configurationFrom($this->configs()[$supplier] ?? null);
}
/**
* 一次读取配置并返回多个厂家的推送状态,避免供应商列表逐行查询。
*
* @param list<string> $suppliers
* @return array<string,array{
* configured:bool,
* webhook_hint:string,
* at_all:bool,
* card_group_configured:bool,
* card_group_hint:string,
* card_robot_configured:bool,
* card_robot_hint:string,
* last_pushed_at:string,
* last_push_count:int
* }>
*/
public function configurationMap(array $suppliers): array
{
$configs = $this->configs();
$result = [];
foreach (array_unique(array_filter(array_map('trim', $suppliers))) as $supplier) {
$result[$supplier] = $this->configurationFrom($configs[$supplier] ?? null);
}
return $result;
}
/** @return list<string> */
public function configuredSuppliers(): array
{
return array_keys(array_filter(
$this->configs(),
static fn (mixed $config): bool => is_array($config)
&& trim((string) ($config['webhook'] ?? '')) !== '',
));
}
/**
* @return array{
* configured:bool,
* webhook_hint:string,
* at_all:bool,
* card_group_configured:bool,
* card_group_hint:string,
* card_robot_configured:bool,
* card_robot_hint:string,
* last_pushed_at:string,
* last_push_count:int
* }
*/
private function configurationFrom(mixed $config): array
{
$webhook = is_array($config) ? trim((string) ($config['webhook'] ?? '')) : '';
$cardConversationId = is_array($config)
? trim((string) ($config['card_conversation_id'] ?? ''))
: '';
$cardRobotCode = is_array($config)
? trim((string) ($config['card_robot_code'] ?? ''))
: '';
return [
'configured' => $webhook !== '',
'webhook_hint' => $this->maskWebhook($webhook),
'group_name' => (string) ($config['group_name'] ?? ''),
'config_source' => (string) ($config['config_source'] ?? ''),
'at_all' => (bool) ($config['at_all'] ?? false),
'card_group_configured' => $cardConversationId !== '',
'card_group_hint' => $this->maskConversationId($cardConversationId),
'card_robot_configured' => $cardRobotCode !== '',
'card_robot_hint' => $cardRobotCode !== '' ? '已指定机器人编码' : '自动识别群内企业机器人',
'last_pushed_at' => (string) ($config['last_pushed_at'] ?? ''),
'last_push_count' => (int) ($config['last_push_count'] ?? 0),
];
}
public function save(
string $supplier,
string $webhook,
string $secret,
bool $atAll,
?string $cardConversationId = null,
?string $cardRobotCode = null,
): void {
$configs = $this->configs();
$existing = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$existingWebhook = trim((string) ($existing['webhook'] ?? ''));
$webhook = trim($webhook);
if ($webhook === '') {
$webhook = $existingWebhook;
}
if ($webhook === '') {
throw ValidationException::withMessages(['dingtalk_webhook' => '请填写钉钉群机器人 Webhook。']);
}
$this->assertWebhook($webhook);
$secret = trim($secret);
if ($secret === '' && $webhook === $existingWebhook) {
$secret = trim((string) ($existing['secret'] ?? ''));
}
if (mb_strlen($secret) > 256) {
throw ValidationException::withMessages(['dingtalk_secret' => '机器人加签密钥过长。']);
}
$existingCardConversationId = trim((string) ($existing['card_conversation_id'] ?? ''));
$cardConversationId = trim((string) $cardConversationId);
if ($cardConversationId !== '') {
$cardConversationId = SupplierSummaryAICard::normalizeOpenConversationId($cardConversationId);
if ($cardConversationId === '') {
throw ValidationException::withMessages([
'dingtalk_card_conversation_id' => '请填写有效的互动卡片群会话 ID(通常以 cid 开头)。',
]);
}
} else {
$cardConversationId = $existingCardConversationId;
}
$cardRobotCode = trim((string) $cardRobotCode);
if ($cardRobotCode === '') {
$cardRobotCode = trim((string) ($existing['card_robot_code'] ?? ''));
}
if (mb_strlen($cardRobotCode) > 191) {
throw ValidationException::withMessages([
'dingtalk_card_robot_code' => '互动卡片机器人编码过长。',
]);
}
$configs[$supplier] = [
'webhook' => $webhook,
'secret' => $secret,
'at_all' => $atAll,
'card_conversation_id' => $cardConversationId,
'card_robot_code' => $cardRobotCode,
'last_pushed_at' => (string) ($existing['last_pushed_at'] ?? ''),
'last_push_count' => (int) ($existing['last_push_count'] ?? 0),
] + ($webhook === $existingWebhook ? array_intersect_key($existing, array_flip([
'group_name', 'config_source', 'source_id', 'source_updated_at',
])) : []);
$this->persist($configs);
}
/** Import only reviewed courier matches, preserving unrelated suppliers and encrypting credentials. */
public function importCourierRobots(array $robots): void
{
$configs = $this->configs();
foreach ($robots as $name => $robot) {
$this->assertWebhook((string) $robot['webhook']);
if (mb_strlen((string) $robot['secret']) > 256) {
throw new RuntimeException('工作平台机器人加签密钥过长。');
}
$existing = $configs[$name] ?? [];
$configs[$name] = array_replace($existing, $robot, ['config_source' => 'work_platform']);
}
$this->persist($configs);
}
/**
* @param list<array<string,mixed>> $differences
* @param array<string,mixed> $filters
* @return array{messages:int,rows:int}
*/
public function push(string $supplier, array $differences, array $filters): array
{
if ($differences === []) {
throw ValidationException::withMessages(['dingtalk_push' => '当前筛选没有可推送的差异。']);
}
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
throw ValidationException::withMessages(['dingtalk_push' => '该厂家还没有配置钉钉群机器人 Webhook。']);
}
$this->assertWebhook($webhook);
$chunks = array_chunk(array_values($differences), self::ROWS_PER_MESSAGE);
if (count($chunks) > self::MAX_MESSAGES) {
throw ValidationException::withMessages([
'dingtalk_push' => '当前差异超过 ' . (self::ROWS_PER_MESSAGE * self::MAX_MESSAGES)
. ' 条,请先缩小月份或对账人范围后再分批推送。',
]);
}
$summary = $this->summarize($differences);
$total = max(count($chunks), 1);
foreach ($chunks as $index => $chunk) {
$title = $supplier . ' · 货款对账差异';
$this->send(
$webhook,
trim((string) ($config['secret'] ?? '')),
(bool) ($config['at_all'] ?? false),
$title,
$this->message($supplier, $chunk, $summary, $filters, $index + 1, $total, $index * self::ROWS_PER_MESSAGE),
);
}
$config['last_pushed_at'] = $this->platformTimestamp();
$config['last_push_count'] = count($differences);
$configs[$supplier] = $config;
$this->persist($configs);
return ['messages' => count($chunks), 'rows' => count($differences)];
}
/**
* 推送当前账期的原始件数和货款汇总。
*
* @return array{messages:int,qty:float,amount:float,period:string,request_id?:string,confirmation_url?:string}
*/
public function pushReconciliationSummary(
string $supplier,
string $month,
float $qty,
float $amount,
int $companyId = 0,
string $pushBasis = 'settlement',
?int $userId = null,
): array {
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
throw ValidationException::withMessages([
'dingtalk_summary_push' => '请选择需要推送的完整账期。',
]);
}
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
throw ValidationException::withMessages([
'dingtalk_summary_push' => '该厂家还没有配置钉钉群机器人 Webhook。',
]);
}
$this->assertWebhook($webhook);
$mode = trim((string) config('dingtalk.summary_confirmation_mode', 'link'));
if ($mode === 'card' && config('dingtalk.card.enabled', true)) {
$result = $this->summaryAICard->push(
$supplier,
$month,
$qty,
$amount,
in_array($pushBasis, ['settlement', 'mine'], true) ? $pushBasis : 'settlement',
$companyId > 0 ? $companyId : (int) (company_id() ?: 1),
$userId,
trim((string) ($config['card_conversation_id'] ?? '')),
trim((string) ($config['card_robot_code'] ?? '')),
trim((string) ($config['card_robot_name'] ?? '')),
);
$config['last_pushed_at'] = $this->platformTimestamp();
$config['last_push_count'] = 1;
$configs[$supplier] = $config;
$this->persist($configs);
return $result;
}
$period = $this->displayMonth($month);
$resolvedCompanyId = $companyId > 0 ? $companyId : (int) (company_id() ?: 1);
$resolvedBasis = in_array($pushBasis, ['settlement', 'mine'], true) ? $pushBasis : 'settlement';
$requestId = 'supplier-summary-l' . $resolvedCompanyId . '-' . bin2hex(random_bytes(16));
$this->summaryConfirmations->create(
$requestId,
$supplier,
$month,
$resolvedBasis,
$qty,
$amount,
$resolvedCompanyId,
$userId,
);
$confirmationUrl = $this->summaryShareLinks->pageUrl(
$resolvedCompanyId,
$supplier,
$month,
$resolvedBasis,
$requestId,
);
try {
$this->send(
$webhook,
trim((string) ($config['secret'] ?? '')),
(bool) ($config['at_all'] ?? false),
$supplier . ' · 货款对账确认 · ' . $period,
implode("\n", [
'### 供应商货款对账确认 · ' . $supplier,
'- 账期:**' . $period . '**',
'- 件数:**' . $this->number($qty) . '** 件',
'- 货款:**¥' . number_format($amount, 2) . '**',
'',
'#### [打开货款确认页](' . $confirmationUrl . ')',
'- 打开后核对数据,点击“确认本期货款”。',
'- 确认结果会实时回传财务系统。',
'',
'> 无需登录;链接仅可查看本厂家本次账期,有效期 '
. SupplierSummaryShareLink::TTL_DAYS . ' 天。',
]),
);
$this->summaryConfirmations->markSent($requestId, $resolvedCompanyId);
} catch (Throwable $exception) {
$this->summaryConfirmations->markFailed($requestId, $resolvedCompanyId, $exception->getMessage());
throw $exception;
}
$config['last_pushed_at'] = $this->platformTimestamp();
$config['last_push_count'] = 1;
$configs[$supplier] = $config;
$this->persist($configs);
return [
'messages' => 1,
'qty' => round($qty, 4),
'amount' => round($amount, 2),
'period' => $period,
'request_id' => $requestId,
'confirmation_url' => $confirmationUrl,
];
}
/** @param array<string,mixed> $record */
public function sendSummaryConfirmationReceipt(array $record): bool
{
$supplier = trim((string) ($record['supplier'] ?? ''));
if ($supplier === '') {
return false;
}
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
return false;
}
$this->assertWebhook($webhook);
$month = trim((string) ($record['month'] ?? ''));
$period = preg_match('/^\d{4}-\d{2}$/', $month) === 1 ? $this->displayMonth($month) : $month;
$this->send(
$webhook,
trim((string) ($config['secret'] ?? '')),
(bool) ($config['at_all'] ?? false),
$supplier . ' · 货款确认回执 · ' . $period,
implode("\n", [
'### 供应商货款确认回执 · ' . $supplier,
'- 账期:**' . $period . '**',
'- 本次确认:**' . $this->number((float) ($record['qty'] ?? 0)) . '** 件,**¥'
. number_format((float) ($record['amount'] ?? 0), 2) . '**',
'- 确认方式:厂家通过货款确认页点击确认',
'- 确认时间:' . (string) ($record['confirmed_at'] ?? $this->platformTimestamp()),
'- 系统状态:**已实时回传财务系统**',
]),
);
return true;
}
/**
* @param list<array<string,mixed>> $returns
* @return array{messages:int,rows:int}
*/
public function pushReturns(string $supplier, array $returns, string $month, int $companyId): array
{
if ($returns === []) {
throw ValidationException::withMessages([
'dingtalk_return_push' => '该厂家在 ' . $month . ' 没有可推送的退货数据。',
]);
}
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
throw ValidationException::withMessages([
'dingtalk_return_push' => '该厂家还没有配置钉钉群机器人 Webhook。',
]);
}
$this->assertWebhook($webhook);
$summary = $this->summarizeReturns($returns);
$title = $supplier . ' · 供应商退货对账 · ' . $month;
$this->send(
$webhook,
trim((string) ($config['secret'] ?? '')),
(bool) ($config['at_all'] ?? false),
$title,
$this->returnMessage(
$supplier,
$summary,
$month,
$this->returnShareLinks->pageUrl($companyId, $supplier, $month),
),
);
$config['last_pushed_at'] = $this->platformTimestamp();
$config['last_push_count'] = count($returns);
$configs[$supplier] = $config;
$this->persist($configs);
return ['messages' => 1, 'rows' => count($returns)];
}
public function sendReturnConfirmationReceipt(
string $supplier,
string $month,
int $confirmedRows,
int $disputedRows,
): bool {
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
return false;
}
$this->assertWebhook($webhook);
$lines = [
'### 供应商退货确认回执 · ' . $supplier,
'- 对账月份:**' . $month . '**',
'- 本次确认:**' . max(0, $confirmedRows) . '** 行退货扣减',
'- 异议保留:**' . max(0, $disputedRows) . '** 行',
'- 确认方式:厂家通过退货明细链接确认',
'- 确认时间:' . $this->platformTimestamp(),
'- 系统状态:**已回传财务系统**',
];
$this->send(
$webhook,
trim((string) ($config['secret'] ?? '')),
(bool) ($config['at_all'] ?? false),
$supplier . ' · 退货确认回执 · ' . $month,
implode("\n", $lines),
);
return true;
}
/** @param list<array<string,mixed>> $records */
public function sendStatementUploadReceipt(string $supplier, string $fileName, array $records): bool
{
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
return false;
}
$this->assertWebhook($webhook);
$month = $this->statementMonths($records);
$fileName = trim((string) preg_replace('/[\r\n`]+/u', ' ', basename($fileName)));
$fileName = mb_strimwidth($fileName, 0, 120, '…', 'UTF-8');
if ($fileName === '') {
$fileName = '未命名文件';
}
$lines = [
'### 供应商对账单上传回执 · ' . $supplier,
'- 对账月份:**' . $month . '**',
'- 上传文件:' . $fileName,
'- 上传行数:**' . count($records) . '** 行',
'- 上传时间:' . $this->platformTimestamp(),
'- 数据状态:**已进入财务核对**',
];
$title = $supplier . ' · 对账单上传回执';
if (! str_contains($month, '、') && $month !== '未识别') {
$title .= ' · ' . $month;
}
$this->send(
$webhook,
trim((string) ($config['secret'] ?? '')),
(bool) ($config['at_all'] ?? false),
$title,
implode("\n", $lines),
);
return true;
}
/**
* 代发运费:提醒厂家到厂家对账入口(钉钉登录)上传这个月的代发运费账单。
* 给了截止日(次月 14 日)就写明截止日、还剩几天,以及逾期本月货款和运费不予结算。
*/
public function pushDropshipUploadReminder(string $supplier, string $month, string $portalUrl,
?\Carbon\CarbonInterface $deadline = null, ?\Carbon\CarbonInterface $today = null): void
{
[$webhook, $config] = $this->robotFor($supplier, 'dropship_upload_reminder');
$deadlineLines = [];
$title = '代发运费账单上传提醒';
if ($deadline !== null) {
$left = $today === null ? null : (int) \Carbon\CarbonImmutable::parse($today->format('Y-m-d'))->diffInDays(\Carbon\CarbonImmutable::parse($deadline->format('Y-m-d')), false);
$title .= $left === 0 ? '(今天截止)' : '';
$deadlineLines = [
'- 请于 **' . (int) $deadline->format('n') . '月' . (int) $deadline->format('j') . '日** 前上传 **' . $this->displayMonth($month) . '** 代发运费账单'
. ($left === 0 ? ',**今天截止**' : ($left !== null && $left > 0 ? ',还剩 ' . $left . ' 天' : '')),
'- **逾期未上传,本月货款和运费将不予结算**',
];
}
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
$supplier . ' · ' . $title . ' · ' . $this->displayMonth($month), implode("\n", [
'### ' . $title . ' · ' . $supplier,
...($deadlineLines ?: ['- 请上传 **' . $this->displayMonth($month) . '** 代发运费账单']),
'- 按上传模板填写(单号、省、重量、运费、快递名称、面单、费率),单号和运费必填',
'- 有附加费的填模板里的「附加费」表(快递单号、附加费金额、附加费类型),没有就空着',
'',
'#### [打开厂家对账入口](' . $portalUrl . ')',
'- 钉钉登录后,在「上传运费账单」里选「代发运费账单」,可先下载上传模板。',
'- 上传后群里会收到回执;如无法登录或上传,请在群里联系财务。',
]));
$this->touch($supplier, 1);
}
/** 快递账单:往这家快递的钉钉对账群推免登录上传链接(机器人在快递账单对账 → 对账分组里配置)。 */
public function pushCourierUploadLink(string $courier, string $month, string $url): void
{
[$webhook, $config] = $this->robotFor($courier, 'courier_upload_link');
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
$courier . ' · 运费账单上传 · ' . $this->displayMonth($month), implode("\n", [
'### 运费账单上传 · ' . $courier,
'- 账单月份:**' . $this->displayMonth($month) . '**',
'- 请按上传模板填写(单号、省、重量、运费、快递名称、面单、费率),单号和运费必填',
'- 有附加费的填模板里的「附加费」表(快递单号、附加费金额、附加费类型),没有就空着',
'',
'#### [打开账单上传页](' . $url . ')',
'- 页面上可下载上传模板;同一个月可以分几次上传,上传后群里会收到回执。',
'',
'> 无需登录;链接只能上传本快递本月的账单,有效期 ' . \App\Support\CourierBills\CourierUploadLink::TTL_DAYS . ' 天。',
]));
$this->touch($courier, 1);
}
/** @param array{rows:int,waybills:int,amount:float,surcharge_rows?:int,surcharge_amount?:float} $summary */
public function sendFreightBillUploadReceipt(string $name, string $kind, string $month, string $fileName, array $summary): bool
{
$configs = $this->configs();
$config = is_array($configs[$name] ?? null) ? $configs[$name] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
return false;
}
$this->assertWebhook($webhook);
$fileName = mb_strimwidth(trim((string) preg_replace('/[\r\n`]+/u', ' ', basename($fileName))), 0, 120, '…', 'UTF-8');
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
$name . ' · ' . $kind . '上传回执 · ' . $this->displayMonth($month), implode("\n", [
'### ' . $kind . '上传回执 · ' . $name,
'- 账单月份:**' . $this->displayMonth($month) . '**',
'- 上传文件:' . ($fileName !== '' ? $fileName : '未命名文件'),
'- 账单:**' . $summary['rows'] . '** 行,运费合计 **¥' . number_format((float) $summary['amount'], 2) . '**',
...(($summary['surcharge_rows'] ?? 0) > 0 ? ['- 附加费:**' . $summary['surcharge_rows'] . '** 行,合计 **¥' . number_format((float) $summary['surcharge_amount'], 2) . '**'] : []),
'- 上传时间:' . $this->platformTimestamp(),
'- 数据状态:**已进入财务核对**',
]));
return true;
}
public function sendStatementReminder(
string $supplier,
string $accountingMonth,
Carbon $finalVersionDate,
Carbon $runDate,
int $companyId,
): void {
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $accountingMonth) !== 1) {
throw ValidationException::withMessages(['statement_reminder' => '对账月份格式无效。']);
}
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
throw ValidationException::withMessages([
'dingtalk_statement_reminder' => '该厂家还没有配置钉钉群机器人 Webhook。',
]);
}
$this->assertWebhook($webhook);
$month = Carbon::createFromFormat('!Y-m', $accountingMonth, config('app.platform_timezone', 'Asia/Shanghai'));
$daysUntilFinalVersion = $finalVersionDate->day - $runDate->day;
$statusLine = $daysUntilFinalVersion > 1
? '距离财务出上月终版还有 **' . $daysUntilFinalVersion . ' 天**,请尽快上传。'
: '**今天是终版前的最后一次系统提醒**,财务将在明天出具上月终版。';
$finalDateLabel = $finalVersionDate->format('n月j日');
$portalUrl = route('business.supplier-portal.home', ['company_id' => $companyId]);
$contactName = trim((string) config('supplier_reconciliation.reminder.contact_name', '苏木'));
$contactLine = $contactName !== ''
? '如无法登录或上传,请在群里反馈并艾特' . $contactName . '。'
: '如无法登录或上传,请在群里反馈并联系财务。';
$lines = [
'### 供应商月度对账单催办 · ' . $supplier,
'- 对账月份:**' . $month->format('Y年n月') . '**',
'- 终版日期:**' . $finalDateLabel . '**',
'- 系统状态:**尚未收到对账单上传记录**',
'- ' . $statusLine,
'',
'#### [打开厂家端对账入口](' . $portalUrl . ')',
'上传入口不设截止时间;系统在每月 1-14 日每日 10:00、16:00 提醒未上传厂家。',
'请同时核对' . $month->format('Y年n月')
. '退货明细;如有异议请在退货明细中提交,确认后的退货扣减会实时回传财务系统。',
'请完成钉钉身份验证后上传对账单;同一钉钉账号对应多家供应商时,登录后可切换厂家。',
$contactLine,
'如已完成上传,可忽略本提醒。',
];
$this->send(
$webhook,
trim((string) ($config['secret'] ?? '')),
(bool) ($config['at_all'] ?? false),
$supplier . ' · 供应商对账单催办',
implode("\n", $lines),
);
$config['last_pushed_at'] = $this->platformTimestamp();
$config['last_push_count'] = 1;
$configs[$supplier] = $config;
$this->persist($configs);
}
/**
* 代发运费对账:推送核对好的运费汇总和确认页链接到这家厂家的钉钉群(和货款对账同一个群机器人)。
*
* @param array{billed:int,bill:float,settle:float,diff:float} $summary
*/
public function pushDropshipFreight(string $supplier, string $month, array $summary, int $attention, int $version, string $url): void
{
[$webhook, $config] = $this->robotFor($supplier, 'dingtalk_dropship_push');
$lines = [
'### 代发运费对账确认 · ' . $supplier,
'- 账期:**' . $this->displayMonth($month) . '**',
'- 厂家开运费:**' . $summary['billed'] . '** 单,**¥' . number_format((float) $summary['bill'], 2) . '**',
'- 核对后应结运费:**¥' . number_format((float) $summary['settle'], 2) . '**',
'- 差额(厂家 − 应结):**¥' . number_format((float) $summary['diff'], 2) . '**',
'- 不结或运费有差的单:**' . $attention . '** 单,原因见确认页',
];
if ($version > 1) {
$lines[] = '- 本次为第 **' . $version . '** 次推送,以本次为准,之前的链接作废';
}
array_push($lines, '', '#### [打开运费确认页](' . $url . ')',
'- 逐单核对;对哪一单有异议,就在那一单勾选「有异议」并写原因,没有异议直接点「确认无异议」。',
'- 提交后结果实时回传财务系统,并在本群发送回执。', '',
'> 无需登录;链接仅可查看本厂家本账期,有效期 ' . \App\Support\DropshipFreight\DropshipShareLink::TTL_DAYS . ' 天。');
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
$supplier . ' · 代发运费对账确认 · ' . $this->displayMonth($month), implode("\n", $lines));
$this->touch($supplier, 1);
}
/** @param array<string,string> $disputes 快递单号 => 原因 */
public function sendDropshipFreightReceipt(string $supplier, string $month, float $settle, array $disputes): bool
{
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
return false;
}
$this->assertWebhook($webhook);
$lines = [
'### 代发运费确认回执 · ' . $supplier,
'- 账期:**' . $this->displayMonth($month) . '**',
'- 应结运费:**¥' . number_format($settle, 2) . '**',
'- 结果:' . ($disputes === [] ? '**确认无异议**' : '**有异议 ' . count($disputes) . ' 单**,财务核实后回复'),
];
$n = 0;
foreach ($disputes as $waybill => $reason) {
if (++$n > 10) {
$lines[] = '- ……其余 ' . (count($disputes) - 10) . ' 单见财务系统';
break;
}
$lines[] = '- ' . $waybill . ':' . mb_strimwidth(str_replace(["\r", "\n"], ' ', $reason), 0, 60, '…', 'UTF-8');
}
array_push($lines, '- 提交时间:' . $this->platformTimestamp(), '- 系统状态:**已实时回传财务系统**');
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
$supplier . ' · 代发运费确认回执 · ' . $this->displayMonth($month), implode("\n", $lines));
return true;
}
/** @return array{0:string,1:array<string,mixed>} */
private function robotFor(string $supplier, string $field): array
{
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
throw ValidationException::withMessages([$field => '「' . $supplier . '」还没有配置钉钉群机器人。']);
}
$this->assertWebhook($webhook);
return [$webhook, $config];
}
private function touch(string $supplier, int $count): void
{
$configs = $this->configs();
if (! is_array($configs[$supplier] ?? null)) {
return;
}
$configs[$supplier]['last_pushed_at'] = $this->platformTimestamp();
$configs[$supplier]['last_push_count'] = $count;
$this->persist($configs);
}
/** @param list<array<string,mixed>> $records */
private function statementMonths(array $records): string
{
$months = [];
foreach ($records as $record) {
$date = trim((string) ($record['createdAt'] ?? ''));
if (preg_match('/^(\d{4}-\d{2})-/', $date, $matches) === 1) {
$months[$matches[1]] = true;
}
}
if ($months === []) {
return '未识别';
}
$months = array_keys($months);
sort($months);
return implode('、', $months);
}
private function platformTimestamp(): string
{
$timezone = trim((string) config('app.platform_timezone', ''));
return now($timezone !== '' ? $timezone : 'Asia/Shanghai')->format('Y-m-d H:i:s');
}
private function displayMonth(string $month): string
{
[$year, $monthNumber] = explode('-', $month, 2);
return (int) $year . '年' . (int) $monthNumber . '月';
}
/**
* @param list<array<string,mixed>> $rows
* @return array{count:int,extra:int,mismatch:int,missing:int,unpriced:int,difference_amount:float}
*/
public function summarize(array $rows): array
{
$summary = [
'count' => count($rows),
'extra' => 0,
'mismatch' => 0,
'missing' => 0,
'unpriced' => 0,
'difference_amount' => 0.0,
];
foreach ($rows as $row) {
$type = (string) ($row['type'] ?? '');
$mine = (float) ($row['mineAmount'] ?? 0);
$theirs = (float) ($row['theirsAmount'] ?? 0);
if ($type === SupplierStatementMatcher::TYPE_SUPPLIER_EXTRA) {
$summary['extra']++;
$summary['difference_amount'] += $theirs;
} elseif ($type === SupplierStatementMatcher::TYPE_MISMATCH) {
$summary['mismatch']++;
$summary['difference_amount'] += abs($mine - $theirs);
} elseif ($type === SupplierStatementMatcher::TYPE_SUPPLIER_MISSING) {
$summary['missing']++;
$summary['difference_amount'] += $mine;
} elseif ($type === SupplierStatementMatcher::TYPE_UNPRICED) {
$summary['unpriced']++;
}
}
$summary['difference_amount'] = round($summary['difference_amount'], 2);
return $summary;
}
/**
* @param list<array<string,mixed>> $rows
* @return array{count:int,qty:float,amount:float,pending:int,confirmed:int,disputed:int}
*/
public function summarizeReturns(array $rows): array
{
$summary = [
'count' => count($rows),
'qty' => 0.0,
'amount' => 0.0,
'pending' => 0,
'confirmed' => 0,
'disputed' => 0,
];
foreach ($rows as $row) {
$summary['qty'] += (float) ($row['_supplier_qty'] ?? $row['qty'] ?? 0);
$summary['amount'] += (float) ($row['_supplier_amount'] ?? $row['amount'] ?? 0);
$status = (string) ($row['_status'] ?? '');
if ($status === SupplierReturnConfirmation::STATUS_CONFIRMED) {
$summary['confirmed']++;
} elseif ($status === SupplierReturnConfirmation::STATUS_DISPUTED) {
$summary['disputed']++;
} else {
$summary['pending']++;
}
}
$summary['qty'] = round($summary['qty'], 2);
$summary['amount'] = round($summary['amount'], 2);
return $summary;
}
/**
* @param array{count:int,qty:float,amount:float,pending:int,confirmed:int,disputed:int} $summary
*/
private function returnMessage(
string $supplier,
array $summary,
string $month,
string $detailUrl,
): string {
$lines = [
'### 供应商退货对账通知 · ' . $supplier,
'- 业务类型:货款对账 / 退货明细',
'- 对账月份:**' . $month . '**',
'- 本月全部退货:**' . $summary['count'] . '** 行(待确认 ' . $summary['pending']
. ' / 已确认 ' . $summary['confirmed'] . ' / 异议中 ' . $summary['disputed'] . ')',
'- 厂家净扣减:**' . $this->number($summary['qty']) . '** 件,**¥'
. number_format($summary['amount'], 2) . '**',
'',
'#### [查看退货明细表格](' . $detailUrl . ')',
'- 打开后可查看完整表格,并下载 Excel 或 CSV。',
'- 核对无误可在页面点击“全部确认无异议”,确认结果会实时回传财务系统,并向本群发送确认回执。',
'- 明细包含发货时间、条码、商品、数量、单价、金额、仓库、配货单号、快递单号和确认状态。',
'',
'> 链接仅可查看本厂家 ' . $month . ' 的退货数据,有效期 '
. SupplierReturnShareLink::TTL_DAYS . ' 天,无需厂家登录。',
];
return implode("\n", $lines);
}
/**
* @param list<array<string,mixed>> $rows
* @param array{count:int,extra:int,mismatch:int,missing:int,difference_amount:float} $summary
* @param array<string,mixed> $filters
*/
private function message(
string $supplier,
array $rows,
array $summary,
array $filters,
int $part,
int $parts,
int $rowOffset,
): string {
$month = trim((string) ($filters['month'] ?? ''));
$reconciler = trim((string) ($filters['reconciler'] ?? ''));
$lines = [
'### 货款对账差异通知 · ' . $supplier,
'- 对账月份:' . ($month !== '' ? $month : '全部月份'),
'- 对账人:' . ($reconciler !== '' ? $reconciler : '全部'),
'- 差异共 **' . $summary['count'] . '** 条(厂家多 ' . $summary['extra']
. ' / 数量金额不一致 ' . $summary['mismatch'] . ' / 厂家少 ' . $summary['missing']
. ' / 未定价 ' . $summary['unpriced'] . ')',
'- 差异金额:**¥' . number_format($summary['difference_amount'], 2) . '**',
];
if ($parts > 1) {
$lines[] = '- 本条为第 ' . $part . ' / ' . $parts . ' 条,请结合后续消息一起核对。';
}
$lines[] = '';
foreach ($rows as $index => $row) {
$differenceDetails = array_values(array_filter(
(array) ($row['differenceDetails'] ?? []),
static fn (mixed $detail): bool => is_array($detail),
));
if ($differenceDetails !== []) {
$lines[] = sprintf(
'%d. **%s**',
$rowOffset + $index + 1,
(string) ($row['type'] ?? '差异'),
);
$prefix = count($differenceDetails) > 1 ? ' - ' : ' ';
foreach ($differenceDetails as $detail) {
$lines[] = $prefix . $this->differenceDetailLine(
$detail,
(string) ($row['type'] ?? ''),
);
}
continue;
}
$mineQty = (float) ($row['mineQty'] ?? 0);
$theirsQty = (float) ($row['theirsQty'] ?? 0);
$mineAmount = (float) ($row['mineAmount'] ?? 0);
$theirsAmount = (float) ($row['theirsAmount'] ?? 0);
$mineUnitPrice = (float) ($row['mineUnitPrice'] ?? $row['unitPrice'] ?? 0);
$theirsUnitPrice = (float) ($row['theirsUnitPrice'] ?? $row['unitPrice'] ?? 0);
$purchaseNo = trim((string) ($row['purchaseNo'] ?? ''));
$date = trim((string) ($row['date'] ?? ''));
$barcode = trim((string) ($row['barcode'] ?? ''));
$supplierBarcode = trim((string) ($row['supplierBarcode'] ?? ''));
$lines[] = sprintf(
'%d. **%s**|采购单号:%s|日期:%s|商品编码:%s%s',
$rowOffset + $index + 1,
(string) ($row['type'] ?? '差异'),
$purchaseNo !== '' ? $purchaseNo : '—',
$date !== '' ? $date : '—',
$barcode,
$supplierBarcode !== '' ? '(厂家条码 ' . $supplierBarcode . ')' : '',
);
$lines[] = ' 我方:数量 ' . $this->number($mineQty)
. '|单价 ¥' . number_format($mineUnitPrice, 2)
. '|金额 ¥' . number_format($mineAmount, 2);
$lines[] = ' 厂家:数量 ' . $this->number($theirsQty)
. '|单价 ¥' . number_format($theirsUnitPrice, 2)
. '|金额 ¥' . number_format($theirsAmount, 2);
$lines[] = ' 处理:' . (string) ($row['note'] ?? '');
}
$lines[] = '';
$lines[] = '> 请登录厂家对账门户核对并修改对账单;如已确认,请联系财务处理。';
$lines[] = '- [打开厂家对账门户](' . route('login') . ')';
return implode("\n", $lines);
}
/** @param array<string,mixed> $detail */
private function differenceDetailLine(array $detail, string $type): string
{
$purchaseNo = trim((string) ($detail['purchaseNo'] ?? ''));
$expressNo = trim((string) ($detail['expressNo'] ?? ''));
$barcode = trim((string) ($detail['barcode'] ?? ''));
$mineQty = (float) ($detail['mineQty'] ?? 0);
$mineUnitPrice = (float) ($detail['mineUnitPrice'] ?? 0);
$mineAmount = (float) ($detail['mineAmount'] ?? 0);
$theirsQty = (float) ($detail['theirsQty'] ?? 0);
$theirsUnitPrice = (float) ($detail['theirsUnitPrice'] ?? 0);
$theirsAmount = (float) ($detail['theirsAmount'] ?? 0);
$amountDifference = (float) ($detail['amountDifference'] ?? 0);
$referenceLabel = trim((string) ($detail['referenceLabel'] ?? ''));
$referenceNo = trim((string) ($detail['referenceNo'] ?? ''));
if ($referenceLabel === '' || $referenceNo === '') {
$useExpress = (int) ($detail['matchedByLayer'] ?? 0) === 4
? $expressNo !== ''
: ($purchaseNo === '' && $expressNo !== '');
$referenceLabel = $useExpress ? '快递单号' : '采购单号';
$referenceNo = $useExpress ? $expressNo : $purchaseNo;
}
$amountText = abs($amountDifference) < 0.005
? '厂家多算 0.00'
: '厂家' . ($amountDifference > 0 ? '多算 ' : '少算 ') . number_format(abs($amountDifference), 2);
if ($type === SupplierStatementMatcher::TYPE_UNPRICED) {
return '条码:' . ($barcode !== '' ? $barcode : '—')
. ',我方未定价'
. ',厂家单价 ' . $this->number($theirsUnitPrice)
. ',厂家数量 ' . $this->number($theirsQty);
}
$base = $referenceLabel . ':' . ($referenceNo !== '' ? $referenceNo : '—')
. ',条码:' . ($barcode !== '' ? $barcode : '—')
. ',我方数量 ' . $this->number($mineQty)
. ',';
return $base
. '单价 ' . $this->number($mineUnitPrice)
. ',金额 ' . $this->number($mineAmount)
. ',厂家数量 ' . $this->number($theirsQty)
. ',单价 ' . $this->number($theirsUnitPrice)
. ',金额 ' . $this->number($theirsAmount)
. ',' . $amountText;
}
private function send(string $webhook, string $secret, bool $atAll, string $title, string $text): void
{
$url = $webhook;
if ($secret !== '') {
$timestamp = (string) (int) (microtime(true) * 1000);
$sign = urlencode(base64_encode(hash_hmac('sha256', $timestamp . "\n" . $secret, $secret, true)));
$url .= (str_contains($url, '?') ? '&' : '?') . 'timestamp=' . $timestamp . '&sign=' . $sign;
}
$response = Http::timeout(10)->post($url, [
'msgtype' => 'markdown',
'markdown' => ['title' => $title, 'text' => $text],
'at' => ['atMobiles' => [], 'isAtAll' => $atAll],
]);
if (! $response->successful()) {
throw new RuntimeException('钉钉机器人推送返回 HTTP ' . $response->status());
}
$body = (array) $response->json();
if ((int) ($body['errcode'] ?? 0) !== 0) {
throw new RuntimeException('钉钉机器人推送失败:' . (string) ($body['errcode'] ?? '?')
. ' ' . (string) ($body['errmsg'] ?? ''));
}
}
private function assertWebhook(string $webhook): void
{
$parts = parse_url($webhook);
parse_str((string) ($parts['query'] ?? ''), $query);
$host = strtolower((string) ($parts['host'] ?? ''));
if (($parts['scheme'] ?? '') !== 'https'
|| ! in_array($host, ['oapi.dingtalk.com', 'api.dingtalk.com'], true)
|| ($parts['path'] ?? '') !== '/robot/send'
|| trim((string) ($query['access_token'] ?? '')) === '') {
throw ValidationException::withMessages([
'dingtalk_webhook' => '请填写有效的钉钉群机器人 Webhook(必须以 https://oapi.dingtalk.com/robot/send?access_token= 开头)。',
]);
}
}
private function maskWebhook(string $webhook): string
{
if ($webhook === '') {
return '';
}
$parts = parse_url($webhook);
$host = (string) ($parts['host'] ?? '');
return $host !== '' ? 'https://' . $host . '/robot/send?access_token=••••••' : '已配置';
}
private function maskConversationId(string $conversationId): string
{
if ($conversationId === '') {
return '';
}
return 'cid••••••' . substr($conversationId, -8);
}
/** @return array<string,array<string,mixed>> */
private function configs(): array
{
$value = setting(self::SETTING_KEY, []);
if (is_string($value)) {
$value = json_decode($value, true) ?: [];
}
if (! is_array($value)) {
return [];
}
foreach ($value as $supplier => &$config) {
if (! is_array($config)) {
unset($value[$supplier]);
continue;
}
$config['webhook'] = $this->decryptValue($config['webhook'] ?? '');
$config['secret'] = $this->decryptValue($config['secret'] ?? '');
}
unset($config);
return $value;
}
/** @param array<string,array<string,mixed>> $configs */
private function persist(array $configs): void
{
$stored = [];
foreach ($configs as $supplier => $config) {
$webhook = trim((string) ($config['webhook'] ?? ''));
$secret = trim((string) ($config['secret'] ?? ''));
$stored[$supplier] = [
'webhook' => $webhook !== '' ? Crypt::encryptString($webhook) : '',
'secret' => $secret !== '' ? Crypt::encryptString($secret) : '',
'at_all' => (bool) ($config['at_all'] ?? false),
'card_conversation_id' => trim((string) ($config['card_conversation_id'] ?? '')),
'card_robot_code' => trim((string) ($config['card_robot_code'] ?? '')),
'last_pushed_at' => (string) ($config['last_pushed_at'] ?? ''),
'last_push_count' => (int) ($config['last_push_count'] ?? 0),
'group_name' => (string) ($config['group_name'] ?? ''),
'config_source' => (string) ($config['config_source'] ?? ''),
'source_id' => (string) ($config['source_id'] ?? ''),
'source_updated_at' => (string) ($config['source_updated_at'] ?? ''),
];
}
setting()->set(self::SETTING_KEY, json_encode($stored, JSON_UNESCAPED_UNICODE));
setting()->save();
}
private function decryptValue(mixed $value): string
{
$value = trim((string) $value);
if ($value === '') {
return '';
}
try {
return Crypt::decryptString($value);
} catch (Throwable) {
return $value;
}
}
private function number(float $value): string
{
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.');
}
}