feat: 增加供应商整月退货钉钉推送 (#833)

增加供应商对账整月退货推送入口,支持全部确认状态、按消息容量自动分批、不限制退货行数;补充设置字段容量迁移。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
This commit is contained in:
苏木 2026-11-02 22:02:18 +08:00 committed by sumu
parent 10b54fe576
commit 801df996d4
7 changed files with 537 additions and 9 deletions

View File

@ -207,6 +207,33 @@ class SupplierReconciliation extends Controller
);
}
public function pushReturns(Request $request): RedirectResponse
{
$request->validate([
'supplier' => ['required', 'string', 'max:191'],
'month' => ['required', 'string', 'regex:/^\d{4}-\d{2}$/'],
]);
[$supplier, $companyId] = $this->returnTarget($request);
$month = trim((string) $request->input('month'));
$returns = $this->pageData->returnRowsForMonth($supplier, $companyId, $month);
if ($returns === []) {
return back()->withErrors([
'dingtalk_return_push' => "该厂家在 {$month} 没有可推送的退货数据。",
]);
}
try {
$result = $this->dingTalkNotifier->pushReturns($supplier, $returns, $month);
} catch (Throwable $exception) {
return back()->withErrors(['dingtalk_return_push' => '推送失败:' . $exception->getMessage()]);
}
return back()->with(
'success',
"已推送 {$result['rows']} 条退货到 {$supplier} 钉钉群({$month},{$result['messages']} 条消息)。",
);
}
private function markReturn(Request $request, string $status, string $message): RedirectResponse
{
$request->validate(['key' => ['required', 'string', 'max:191']]);

View File

@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (DB::getDriverName() !== 'mysql') {
return;
}
Schema::table('settings', function (Blueprint $table): void {
$table->mediumText('value')->nullable()->change();
});
}
public function down(): void
{
if (DB::getDriverName() !== 'mysql') {
return;
}
$maxLength = (int) DB::table('settings')
->selectRaw('MAX(CHAR_LENGTH(value)) AS max_length')
->value('max_length');
if ($maxLength > 65535) {
return;
}
Schema::table('settings', function (Blueprint $table): void {
$table->text('value')->nullable()->change();
});
}
};

View File

@ -9,7 +9,7 @@ use RuntimeException;
use Throwable;
/**
* 货款对账差异:按供应商保存钉钉群机器人,并推送当前比对差异。
* 供应商对账:按供应商保存钉钉群机器人,推送货款差异或整月退货。
*/
class SupplierDingTalkNotifier
{
@ -19,6 +19,9 @@ class SupplierDingTalkNotifier
private const MAX_MESSAGES = 20;
/** 钉钉单条内容有大小上限;这里留出 JSON 与签名参数的安全余量。 */
private const RETURN_MESSAGE_MAX_BYTES = 18_000;
/** @return array{configured:bool,webhook_hint:string,at_all:bool,last_pushed_at:string,last_push_count:int} */
public function configuration(string $supplier): array
{
@ -116,6 +119,52 @@ class SupplierDingTalkNotifier
return ['messages' => count($chunks), 'rows' => count($differences)];
}
/**
* @param list<array<string,mixed>> $returns
* @return array{messages:int,rows:int}
*/
public function pushReturns(string $supplier, array $returns, string $month): 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);
$chunks = $this->returnMessageChunks($supplier, $returns, $summary, $month);
$total = count($chunks);
$rowOffset = 0;
foreach ($chunks as $index => $chunk) {
$title = $supplier . ' · 供应商退货对账 · ' . $month;
$this->send(
$webhook,
trim((string) ($config['secret'] ?? '')),
(bool) ($config['at_all'] ?? false),
$title,
$this->returnMessage($supplier, $chunk, $summary, $month, $index + 1, $total, $rowOffset),
);
$rowOffset += count($chunk);
}
$config['last_pushed_at'] = now()->format('Y-m-d H:i:s');
$config['last_push_count'] = count($returns);
$configs[$supplier] = $config;
$this->persist($configs);
return ['messages' => count($chunks), 'rows' => count($returns)];
}
/**
* @param list<array<string,mixed>> $rows
* @return array{count:int,extra:int,mismatch:int,missing:int,difference_amount:float}
@ -144,6 +193,162 @@ class SupplierDingTalkNotifier
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 list<array<string,mixed>> $rows
* @param array{count:int,qty:float,amount:float,pending:int,confirmed:int,disputed:int} $summary
* @return list<list<array<string,mixed>>>
*/
private function returnMessageChunks(string $supplier, array $rows, array $summary, string $month): array
{
$chunks = [];
$current = [];
$rowOffset = 0;
foreach (array_values($rows) as $row) {
$candidate = [...$current, $row];
$messageSize = strlen($this->returnMessage($supplier, $candidate, $summary, $month, 1, 1, $rowOffset));
if ($current !== [] && $messageSize > self::RETURN_MESSAGE_MAX_BYTES) {
$chunks[] = $current;
$rowOffset += count($current);
$current = [$row];
continue;
}
if ($current === [] && $messageSize > self::RETURN_MESSAGE_MAX_BYTES) {
throw ValidationException::withMessages([
'dingtalk_return_push' => '第 ' . ($rowOffset + 1) . ' 条退货内容超过钉钉单条消息容量,无法推送。',
]);
}
$current = $candidate;
}
if ($current !== []) {
$chunks[] = $current;
}
return $chunks;
}
/**
* @param list<array<string,mixed>> $rows
* @param array{count:int,qty:float,amount:float,pending:int,confirmed:int,disputed:int} $summary
*/
private function returnMessage(
string $supplier,
array $rows,
array $summary,
string $month,
int $part,
int $parts,
int $rowOffset,
): string {
$lines = [
'### 供应商退货对账通知 · ' . $supplier,
'- 业务类型:货款对账 / 退货明细',
'- 对账月份:**' . $month . '**',
'- 本月全部退货:**' . $summary['count'] . '** 行(待确认 ' . $summary['pending']
. ' / 已确认 ' . $summary['confirmed'] . ' / 异议中 ' . $summary['disputed'] . ')',
'- 厂家净扣减:**' . $this->number($summary['qty']) . '** 件,**¥'
. number_format($summary['amount'], 2) . '**',
];
if ($parts > 1) {
$lines[] = '- 本条为第 ' . $part . ' / ' . $parts . ' 条。';
}
$lines[] = '';
foreach ($rows as $index => $row) {
$date = $this->messageText($row['send_time'] ?? '', 64);
$barcode = $this->messageText($row['barcode'] ?? '', 128);
$skuName = $this->messageText($row['sku_name'] ?? '', 160);
$status = $this->returnStatusLabel((string) ($row['_status'] ?? ''));
$target = $this->messageText($row['_accounting_label'] ?? '厂家扣减', 40);
$qty = (float) ($row['qty'] ?? $row['_supplier_qty'] ?? 0);
$supplierQty = (float) ($row['_supplier_qty'] ?? $qty);
$unitPrice = (float) ($row['unit_price'] ?? 0);
$amount = (float) ($row['amount'] ?? 0);
$supplierAmount = (float) ($row['_supplier_amount'] ?? $amount);
$lines[] = sprintf(
'%d. **%s**|条码:%s%s',
$rowOffset + $index + 1,
$date !== '' ? $date : '日期缺失',
$barcode !== '' ? $barcode : '—',
$skuName !== '' ? '|' . $skuName : '',
);
$lines[] = ' 状态:' . $status . '|记账归属:' . $target
. '|数量:' . $this->number($qty)
. '|单价:¥' . number_format($unitPrice, 2)
. '|金额:¥' . number_format($amount, 2);
$lines[] = ' 厂家净扣减:' . $this->number($supplierQty)
. ' 件 / ¥' . number_format($supplierAmount, 2);
$detail = [];
foreach ([
'仓库' => [$row['warehouse'] ?? '', 80],
'WMS配货单号' => [$row['wms_pick_no'] ?? '', 100],
'快递单号' => [$row['express_no'] ?? '', 100],
'备注' => [$row['remark'] ?? '', 300],
] as $label => [$value, $maxLength]) {
$value = $this->messageText($value, $maxLength);
if ($value !== '') {
$detail[] = $label . ':' . $value;
}
}
if ($detail !== []) {
$lines[] = ' ' . implode('|', $detail);
}
$accountingNote = $this->messageText($row['_accounting_note'] ?? '', 300);
if ($accountingNote !== '' && $accountingNote !== '按厂家退货扣减') {
$lines[] = ' ' . $accountingNote;
}
}
$lines[] = '';
$lines[] = '> 本条推送包含该厂家整月全部退货记录,不按确认状态筛选。请在本群核对;如有异议,请回复条目序号和原因。';
return implode("\n", $lines);
}
/**
* @param list<array<string,mixed>> $rows
* @param array{count:int,extra:int,mismatch:int,missing:int,difference_amount:float} $summary
@ -323,6 +528,25 @@ class SupplierDingTalkNotifier
}
}
private function returnStatusLabel(string $status): string
{
return match ($status) {
SupplierReturnConfirmation::STATUS_CONFIRMED => '已确认',
SupplierReturnConfirmation::STATUS_DISPUTED => '异议中',
default => '待确认',
};
}
private function messageText(mixed $value, int $maxLength): string
{
$text = is_scalar($value) ? trim((string) $value) : '';
if ($text === '' || mb_strlen($text) <= $maxLength) {
return $text;
}
return mb_substr($text, 0, max(1, $maxLength - 1)) . '…';
}
private function number(float $value): string
{
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.');

View File

@ -133,6 +133,7 @@ class SupplierReconciliationPageData
self::COMPARISON_PER_PAGE,
);
}
$returnPushMonth = $month !== '' ? $month : now()->format('Y-m');
return [
'view' => 'business.pages.supplier-reconciliation.finance-data',
@ -149,6 +150,7 @@ class SupplierReconciliationPageData
'financeReturnPanel' => $detail !== null
? $this->financeReturnPanel($selected, $companyId, $month, $reconciler)
: null,
'returnPushMonth' => $returnPushMonth,
'robot' => $selected !== '' ? $this->dingTalkNotifier->configuration($selected) : null,
'listUrl' => route('business.pages.show', array_filter([
'section' => 'supplier-reconciliation',
@ -307,10 +309,7 @@ class SupplierReconciliationPageData
$rows = [];
foreach ($allRows as $row) {
$rowMonth = substr(trim((string) ($row['send_time'] ?? '')), 0, 7);
if ($rowMonth === '') {
$rowMonth = substr(trim((string) ($row['summary_month'] ?? '')), 0, 7);
}
$rowMonth = $this->returnRowMonth($row);
if ($month !== '' && $rowMonth !== $month) {
continue;
}
@ -472,6 +471,31 @@ class SupplierReconciliationPageData
));
}
/**
* 返回指定厂家整月退货,不按确认状态或记账归属筛除。
*
* @return list<array<string,mixed>>
*/
public function returnRowsForMonth(string $supplier, int $companyId, string $month): array
{
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
return [];
}
$statuses = $this->returnConfirmations->statuses($supplier, $companyId);
$rows = [];
foreach ($this->returnRows($supplier, $companyId) as $row) {
if ($this->returnRowMonth($row) !== $month) {
continue;
}
$row['_status'] = $statuses[(string) ($row['_action_key'] ?? '')] ?? '';
$rows[] = $this->returnAccounting->enrich($row);
}
return $rows;
}
/**
* 厂家端当前查询条件下的全部退货行(用于导出,不分页)。
*
@ -610,6 +634,27 @@ class SupplierReconciliationPageData
: '';
}
/** @param array<string,mixed> $row */
private function returnRowMonth(array $row): string
{
$sendDate = $this->normalizeFilterDate($row['send_time'] ?? '');
if ($sendDate !== '') {
return substr($sendDate, 0, 7);
}
$summaryMonth = $this->filterText($row['summary_month'] ?? '');
if (preg_match('/^(\d{4})[-\/.](\d{1,2})/', $summaryMonth, $matches) !== 1) {
return '';
}
$year = (int) $matches[1];
$month = (int) $matches[2];
return $month >= 1 && $month <= 12
? sprintf('%04d-%02d', $year, $month)
: '';
}
private function companyId(): int
{
return (int) (company_id() ?: 1);

View File

@ -43,6 +43,9 @@
.supplier-reconciliation-page .sr-robot-config summary { cursor: pointer; color: #5B5343; font-size: .8125rem; font-weight: 600; }
.supplier-reconciliation-page .sr-robot-form { display: grid; grid-template-columns: minmax(260px, 2fr) minmax(180px, 1fr) auto; gap: 10px; align-items: end; margin-top: 12px; }
.supplier-reconciliation-page .sr-robot-check { display: flex; align-items: center; gap: 6px; min-height: 36px; color: var(--vip-content-muted, #595959); font-size: .75rem; }
.supplier-reconciliation-page .sr-return-push { display: flex; flex-wrap: wrap; align-items: end; gap: 10px; padding: 12px; border: 1px solid #E4DCCB; border-radius: 8px; background: var(--vip-content-accent-soft, #F7F0DE); }
.supplier-reconciliation-page .sr-return-push .sr-field { min-width: 180px; margin: 0; }
.supplier-reconciliation-page .sr-return-push-note { flex: 1 1 320px; color: var(--vip-content-muted, #595959); font-size: .75rem; line-height: 1.6; }
.supplier-reconciliation-page .sr-select-cell { width: 34px; text-align: center; }
.supplier-reconciliation-page .sr-select-cell input { width: 15px; height: 15px; accent-color: var(--vip-content-accent-dark, #856632); }
.supplier-reconciliation-page .sr-robot-form input[type="url"],
@ -59,9 +62,13 @@
@if ($errors->has('import'))
<div class="biz-alert biz-alert-error" role="alert">{{ $errors->first('import') }}</div>
@endif
@if ($errors->has('dingtalk_push') || $errors->has('dingtalk_webhook') || $errors->has('dingtalk_secret'))
@if ($errors->has('dingtalk_push') || $errors->has('dingtalk_return_push') || $errors->has('dingtalk_webhook') || $errors->has('dingtalk_secret') || $errors->has('month'))
<div class="biz-alert biz-alert-error" role="alert">
{{ $errors->first('dingtalk_push') ?: $errors->first('dingtalk_webhook') ?: $errors->first('dingtalk_secret') }}
{{ $errors->first('dingtalk_push')
?: $errors->first('dingtalk_return_push')
?: $errors->first('dingtalk_webhook')
?: $errors->first('dingtalk_secret')
?: $errors->first('month') }}
</div>
@endif
@ -181,7 +188,7 @@
</form>
@endif
</div>
<details class="sr-robot-config" @if (! $robot['configured']) open @endif>
<details id="dingtalk-robot-config" class="sr-robot-config" @if (! $robot['configured']) open @endif>
<summary>
厂家钉钉群机器人:
{{ $robot['configured'] ? '已配置' : '未配置,配置后才能推送差异' }}
@ -218,7 +225,7 @@
</form>
<p class="sr-hint">
在厂家钉钉群的「群设置 → 智能群助手 → 添加机器人 → 自定义」中复制 Webhook;如机器人启用加签,请同时填写加签密钥。
如机器人使用关键词校验,请把关键词设为「货款对账」。
如机器人使用关键词校验,请把关键词设为「对账」,可同时匹配货款差异和退货推送。
Webhook 和密钥保存后仅用于本系统推送,页面不会再次展示完整内容。
</p>
</details>
@ -427,6 +434,29 @@
直接读取「应付款终版 → 退货对账」同一数据集;修改退货数量、备注、标题后,财务端和厂家门户同时更新。
</span>
</div>
<form method="POST"
action="{{ route('business.supplier-reconciliation.push-returns') }}"
class="sr-return-push"
onsubmit="return confirm('确认将该厂家所选月份的全部退货推送到钉钉群?')">
@csrf
<input type="hidden" name="supplier" value="{{ $selectedSupplier }}">
<label class="sr-field"><span>推送月份</span>
<input type="month" name="month" value="{{ $returnPushMonth }}" required>
</label>
<button type="submit"
class="sr-button is-primary {{ $robot['configured'] ? '' : 'is-disabled' }}"
@disabled(! $robot['configured'])
title="{{ $robot['configured'] ? '推送该厂家所选月份的全部退货数据' : '请先配置厂家钉钉群机器人' }}">
一键推送整月退货
</button>
<span class="sr-return-push-note">
推送该月全部退货,包含待确认、已确认和异议中记录,不按确认状态筛选。
不受当前对账人筛选影响,不限制退货行数,按钉钉消息容量自动分批续发。
@if (! $robot['configured'])
<a href="#dingtalk-robot-config">请先配置厂家钉钉群机器人</a>。
@endif
</span>
</form>
<div class="sr-summary">
<div class="sr-summary-cell"><span>退货行数</span><b>{{ number_format($returnAccounting['count']) }}</b></div>
<div class="sr-summary-cell"><span>厂家净扣减</span><b>¥{{ number_format($returnAccounting['supplier_amount'], 2) }}</b></div>

View File

@ -464,6 +464,10 @@ Route::post('workspace/supplier-reconciliation/push-differences', [SupplierRecon
->middleware('business.page:supplier-reconciliation,finance-data')
->name('business.supplier-reconciliation.push-differences');
Route::post('workspace/supplier-reconciliation/push-returns', [SupplierReconciliationActions::class, 'pushReturns'])
->middleware('business.page:supplier-reconciliation,finance-data')
->name('business.supplier-reconciliation.push-returns');
Route::post('workspace/supplier-negative-alerts/dingtalk-group', [SupplierNegativeAlertDingTalkActions::class, 'saveRobot'])
->middleware(['business.page:negative-alerts,supplier-negative-alert', 'throttle:10,1'])
->name('business.supplier-negative-alerts.dingtalk-group.save');

View File

@ -6,6 +6,7 @@ use App\Models\Auth\Permission;
use Illuminate\Support\Facades\Http;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
use Modules\EcommerceFinance\Services\SupplierStatementStore;
use Tests\Feature\FeatureTestCase;
@ -229,6 +230,165 @@ class SupplierReconciliationDingTalkTest extends FeatureTestCase
Http::assertSentCount(2);
}
public function test_finance_page_shows_monthly_return_push_entry(): void
{
$this->seedReconciliation();
$this->loginAs()->get($this->pageUrl())
->assertOk()
->assertSeeText('一键推送整月退货')
->assertSeeText('推送该月全部退货,包含待确认、已确认和异议中记录,不按确认状态筛选。')
->assertSee('name="month"', false);
}
public function test_monthly_return_push_sends_all_statuses_and_only_the_selected_supplier_month(): void
{
$this->saveRobot();
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$companyId = (int) $this->company->id;
$store = app(SupplierPayableOverrideStore::class);
foreach ([
'return:pending' => [
'send_time' => '2026-09-03 10:00:00', 'barcode' => 'RETURN-PENDING',
'sku_name' => '待确认退货', 'qty' => '1', 'unit_price' => '100', 'amount' => '100',
],
'return:confirmed' => [
'send_time' => '2026-09-12 10:00:00', 'barcode' => 'RETURN-CONFIRMED',
'sku_name' => '已确认退货', 'qty' => '2', 'unit_price' => '50', 'amount' => '100',
],
'return:disputed' => [
'send_time' => '2026-09-22 10:00:00', 'barcode' => 'RETURN-DISPUTED',
'sku_name' => '异议中退货', 'qty' => '3', 'unit_price' => '10', 'amount' => '30',
],
'return:october' => [
'send_time' => '2026-10-01 10:00:00', 'barcode' => 'RETURN-OCTOBER',
'sku_name' => '其他月份退货', 'qty' => '9', 'unit_price' => '10', 'amount' => '90',
],
'return:foreign' => [
'send_time' => '2026-09-15 10:00:00', 'supplier' => '鸣飞家具', 'barcode' => 'RETURN-FOREIGN',
'sku_name' => '其他厂家退货', 'qty' => '8', 'unit_price' => '10', 'amount' => '80',
],
] as $key => $row) {
$store->save('final:supplier:return-reconciliation', $key, $row + [
'summary_month' => '2026-09',
'supplier' => '晨丰',
'warehouse' => '一号仓',
'wms_pick_no' => 'WMS-' . strtoupper(substr($key, 7)),
'express_no' => 'SF-' . strtoupper(substr($key, 7)),
], $companyId, null);
}
$confirmations = app(SupplierReturnConfirmation::class);
$confirmations->mark('晨丰', 'return:confirmed', SupplierReturnConfirmation::STATUS_CONFIRMED, $companyId, null);
$confirmations->mark('晨丰', 'return:disputed', SupplierReturnConfirmation::STATUS_DISPUTED, $companyId, null);
$this->loginAs()
->post(route('business.supplier-reconciliation.push-returns'), [
'supplier' => '晨丰',
'month' => '2026-09',
])
->assertStatus(302)
->assertSessionHas('success', '已推送 3 条退货到 晨丰 钉钉群(2026-09,1 条消息)。');
Http::assertSentCount(1);
Http::assertSent(function ($request): bool {
$text = (string) ($request['markdown']['text'] ?? '');
return str_contains($request->url(), 'oapi.dingtalk.com/robot/send')
&& str_contains($text, '供应商退货对账通知 · 晨丰')
&& str_contains($text, '业务类型:货款对账 / 退货明细')
&& str_contains($text, '- 对账月份:**2026-09**')
&& str_contains($text, '待确认 1 / 已确认 1 / 异议中 1')
&& str_contains($text, 'RETURN-PENDING')
&& str_contains($text, 'RETURN-CONFIRMED')
&& str_contains($text, 'RETURN-DISPUTED')
&& str_contains($text, '状态:已确认')
&& str_contains($text, '状态:异议中')
&& str_contains($text, '不按确认状态筛选')
&& ! str_contains($text, 'RETURN-OCTOBER')
&& ! str_contains($text, 'RETURN-FOREIGN');
});
}
public function test_return_messages_are_split_by_size_instead_of_a_fixed_row_count(): void
{
$this->saveRobot();
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$rows = [];
for ($index = 1; $index <= 31; $index++) {
$rows[] = $this->returnNotificationRow($index);
}
$result = app(SupplierDingTalkNotifier::class)->pushReturns('晨丰', $rows, '2026-09');
$this->assertSame(31, $result['rows']);
$this->assertSame(1, $result['messages']);
Http::assertSentCount(1);
Http::assertSent(function ($request): bool {
$text = (string) ($request['markdown']['text'] ?? '');
return str_contains($text, 'RETURN-BULK-01')
&& str_contains($text, 'RETURN-BULK-31');
});
}
public function test_monthly_return_push_has_no_application_row_or_message_cap(): void
{
$this->saveRobot();
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$rows = [];
for ($index = 1; $index <= 601; $index++) {
$rows[] = $this->returnNotificationRow($index);
}
$result = app(SupplierDingTalkNotifier::class)->pushReturns('晨丰', $rows, '2026-09');
$this->assertSame(601, $result['rows']);
$this->assertGreaterThan(1, $result['messages']);
Http::assertSentCount($result['messages']);
foreach (Http::recorded() as [$request]) {
$this->assertLessThanOrEqual(20_000, strlen((string) ($request['markdown']['text'] ?? '')));
}
}
public function test_monthly_return_push_rejects_an_empty_month_without_http_call(): void
{
$this->saveRobot();
Http::fake();
$this->loginAs()
->post(route('business.supplier-reconciliation.push-returns'), [
'supplier' => '晨丰',
'month' => '2026-08',
])
->assertStatus(302)
->assertSessionHasErrors([
'dingtalk_return_push' => '该厂家在 2026-08 没有可推送的退货数据。',
]);
Http::assertNothingSent();
}
private function returnNotificationRow(int $index): array
{
return [
'send_time' => '2026-09-' . str_pad((string) (($index - 1) % 28 + 1), 2, '0', STR_PAD_LEFT) . ' 10:00:00',
'barcode' => sprintf('RETURN-BULK-%02d', $index),
'sku_name' => '批量退货',
'qty' => '1',
'unit_price' => '10',
'amount' => '10',
'_supplier_qty' => 1.0,
'_supplier_amount' => 10.0,
'_status' => '',
'_accounting_label' => '厂家扣减',
'_accounting_note' => '按厂家退货扣减',
];
}
private function seedReconciliation(): void
{
$companyId = (int) $this->company->id;