feat: 恢复对账人选项并支持批量推送退货 #848

Merged
renshen merged 1 commits from feature/supplier-batch-return-push into main 2026-11-04 10:59:38 +08:00
5 changed files with 364 additions and 20 deletions

View File

@ -7,6 +7,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\SupplierComparisonCsvExporter;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
@ -234,6 +235,75 @@ class SupplierReconciliation extends Controller
);
}
public function pushReturnsBatch(Request $request): RedirectResponse
{
$request->validate([
'selected_returns' => ['required', 'array', 'min:1', 'max:200'],
'selected_returns.*' => ['string', 'max:2048'],
]);
$targets = [];
foreach ((array) $request->input('selected_returns', []) as $encoded) {
$selection = json_decode((string) $encoded, true);
$supplier = is_array($selection) ? trim((string) ($selection['supplier'] ?? '')) : '';
$month = is_array($selection) ? trim((string) ($selection['month'] ?? '')) : '';
if ($supplier === '' || preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
throw ValidationException::withMessages([
'batch_return_push' => '批量退货选择无效,请刷新页面后重新选择。',
]);
}
$targets[$supplier] = $month;
}
$companyId = (int) (company_id() ?: 1);
$returnsBySupplier = $this->pageData->returnRowsForMonthTargets($targets, $companyId);
$pushedSuppliers = 0;
$pushedRows = 0;
$messages = 0;
$skipped = [];
foreach ($targets as $supplier => $month) {
$returns = $returnsBySupplier[$supplier] ?? [];
if ($returns === []) {
$skipped[] = "{$supplier}({$month} 无退货)";
continue;
}
try {
$result = $this->dingTalkNotifier->pushReturns($supplier, $returns, $month);
} catch (Throwable $exception) {
$reason = $exception instanceof ValidationException
? (string) (collect($exception->errors())->flatten()->first() ?: $exception->getMessage())
: $exception->getMessage();
$skipped[] = $supplier . '(' . ($reason !== '' ? $reason : '推送失败') . ')';
continue;
}
$pushedSuppliers++;
$pushedRows += (int) $result['rows'];
$messages += (int) $result['messages'];
}
$skippedNote = '';
if ($skipped !== []) {
$preview = implode('、', array_slice($skipped, 0, 6));
$skippedNote = ';未推送 ' . count($skipped) . ' 家:' . $preview
. (count($skipped) > 6 ? ' 等' : '');
}
if ($pushedSuppliers === 0) {
return back()->withErrors([
'batch_return_push' => '批量退货推送未完成' . $skippedNote,
]);
}
return back()->with(
'success',
"已批量推送 {$pushedSuppliers} 家供应商,共 {$pushedRows} 条退货({$messages} 条钉钉消息){$skippedNote}。",
);
}
private function markReturn(Request $request, string $status, string $message): RedirectResponse
{
$request->validate(['key' => ['required', 'string', 'max:191']]);

View File

@ -54,6 +54,22 @@ class SupplierReconciliationPageData
$companyId,
);
$reconcilers = [];
foreach ($mine as $row) {
$name = trim((string) ($row['reconciler'] ?? ''));
if ($name !== '') {
$reconcilers[$name] = true;
}
}
foreach ($returnRows as $row) {
$name = trim((string) ($row['reconciler'] ?? ''));
if ($name !== '') {
$reconcilers[$name] = true;
}
}
$reconcilers = array_keys($reconcilers);
sort($reconcilers);
$months = [];
$returnSupplierMonths = [];
foreach ($returnRows as $row) {
@ -86,16 +102,6 @@ class SupplierReconciliationPageData
$month = '';
}
$reconcilers = [];
foreach ($mine as $row) {
$name = trim((string) ($row['reconciler'] ?? ''));
if ($name !== '') {
$reconcilers[$name] = true;
}
}
$reconcilers = array_keys($reconcilers);
sort($reconcilers);
$reconciler = trim((string) request()->query('reconciler', ''));
if ($reconciler !== '') {
$mine = array_values(array_filter(
@ -542,18 +548,62 @@ class SupplierReconciliationPageData
return [];
}
$statuses = $this->returnConfirmations->statuses($supplier, $companyId);
$rows = [];
foreach ($this->returnRows($supplier, $companyId) as $row) {
if ($this->returnRowMonth($row) !== $month) {
return $this->returnRowsForMonthTargets([$supplier => $month], $companyId)[$supplier] ?? [];
}
/**
* 一次读取数据集,为多家供应商分别筛选指定月份的退货,供批量推送使用。
*
* @param array<string,string> $targets 厂家 => 月份
* @return array<string,list<array<string,mixed>>>
*/
public function returnRowsForMonthTargets(array $targets, int $companyId): array
{
$normalizedTargets = [];
foreach ($targets as $supplier => $month) {
$supplier = is_string($supplier) ? trim($supplier) : '';
$month = is_string($month) ? trim($month) : '';
if ($supplier !== '' && preg_match('/^\d{4}-\d{2}$/', $month) === 1) {
$normalizedTargets[$supplier] = $month;
}
}
if ($normalizedTargets === []) {
return [];
}
$result = [];
foreach ($normalizedTargets as $supplier => $month) {
$result[$supplier] = [];
}
$allRows = $this->store->listRows(
PayablesFinalActions::DATASET_PREFIX . 'supplier:return-reconciliation',
$companyId,
);
foreach ($allRows as $row) {
$supplier = trim((string) ($row['supplier'] ?? ''));
if (! array_key_exists($supplier, $result)
|| $this->returnRowMonth($row) !== (string) $normalizedTargets[$supplier]) {
continue;
}
$row['_status'] = $statuses[(string) ($row['_action_key'] ?? '')] ?? '';
$rows[] = $this->returnAccounting->enrich($row);
$result[$supplier][] = $row;
}
return $rows;
foreach ($result as $supplier => &$rows) {
if ($rows === []) {
continue;
}
$statuses = $this->returnConfirmations->statuses($supplier, $companyId);
foreach ($rows as &$row) {
$row['_status'] = $statuses[(string) ($row['_action_key'] ?? '')] ?? '';
$row = $this->returnAccounting->enrich($row);
}
unset($row);
}
unset($rows);
return $result;
}
/**

View File

@ -17,6 +17,12 @@
.supplier-reconciliation-page .sr-button.is-small { height: 26px; padding: 0 9px; font-size: .75rem; }
.supplier-reconciliation-page .sr-list-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.supplier-reconciliation-page .sr-list-actions form { margin: 0; }
.supplier-reconciliation-page .sr-batch-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; padding: 10px 12px; border: 1px solid #E4DCCB; border-radius: 8px; background: var(--vip-content-accent-soft, #F7F0DE); }
.supplier-reconciliation-page .sr-batch-selection { display: flex; align-items: center; gap: 7px; color: #5B5343; font-size: .8125rem; font-weight: 600; }
.supplier-reconciliation-page .sr-batch-selection input { width: 15px; height: 15px; accent-color: var(--vip-content-accent-dark, #856632); }
.supplier-reconciliation-page .sr-batch-summary { color: var(--vip-content-muted, #595959); font-size: .75rem; }
.supplier-reconciliation-page .sr-list-select-cell { width: 48px; text-align: center; }
.supplier-reconciliation-page .sr-list-select-cell input { width: 15px; height: 15px; accent-color: var(--vip-content-accent-dark, #856632); }
.supplier-reconciliation-page .sr-hint { margin: 0; color: var(--vip-content-muted, #595959); font-size: .75rem; line-height: 1.7; }
.supplier-reconciliation-page .sr-scroll { min-width: 0; max-width: 100%; overflow-x: auto; scrollbar-width: thin; }
.supplier-reconciliation-page table { width: 100%; min-width: 720px; border-collapse: collapse; font-size: .8125rem; }
@ -64,10 +70,11 @@
@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_return_push') || $errors->has('dingtalk_webhook') || $errors->has('dingtalk_secret') || $errors->has('month'))
@if ($errors->has('dingtalk_push') || $errors->has('dingtalk_return_push') || $errors->has('batch_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_return_push')
?: $errors->first('batch_return_push')
?: $errors->first('dingtalk_webhook')
?: $errors->first('dingtalk_secret')
?: $errors->first('month') }}
@ -238,12 +245,40 @@
<h2>各厂家上传情况(实时)</h2>
<p class="sr-hint">
每页显示 15 家。选择具体月份后,退货推送按该月份统计;全部月份下优先显示各厂家最新有数据的退货月份。
整月退货会包含待确认、已确认和异议中记录,并自动按钉钉消息容量分批发送。
整月退货会包含待确认、已确认和异议中记录,并自动按钉钉消息容量分批发送。勾选本页多家已配置机器人的厂家后,可批量推送。
</p>
@php
$batchEligibleCount = count(array_filter(
$supplierListRows,
fn (string $supplier): bool => (int) ($returnCounts[$supplier] ?? 0) > 0
&& (bool) ($robotConfigurations[$supplier]['configured'] ?? false),
));
@endphp
<form id="batch-return-push-form"
method="POST"
action="{{ route('business.supplier-reconciliation.push-returns-batch') }}">
@csrf
</form>
<div class="sr-batch-toolbar">
<label class="sr-batch-selection">
<input id="select-all-return-push" type="checkbox" @disabled($batchEligibleCount === 0)>
选择本页可推送厂家
</label>
<span id="batch-return-push-summary" class="sr-batch-summary">可批量推送 {{ $batchEligibleCount }} 家;未配置机器人或所选月份无退货的厂家暂不可选。</span>
<span style="flex:1 1 auto"></span>
<button id="batch-return-push-button"
form="batch-return-push-form"
type="submit"
class="sr-button is-primary is-disabled"
disabled>
批量推送退货(<span id="batch-return-push-count">0</span> 家)
</button>
</div>
<div class="sr-scroll">
<table data-finance-supplier-list>
<thead>
<tr>
<th scope="col" class="sr-list-select-cell">选择</th>
<th scope="col">供应商</th>
<th scope="col">最近上传时间</th>
<th scope="col">上传行数</th>
@ -269,6 +304,19 @@
], static fn (mixed $value): bool => $value !== '' && $value !== null));
@endphp
<tr>
<td class="sr-list-select-cell">
@if ($returnCount > 0 && $robotConfigured)
<input class="js-batch-supplier-checkbox"
form="batch-return-push-form"
type="checkbox"
name="selected_returns[]"
value="{{ json_encode(['supplier' => $supplier, 'month' => $returnMonth], JSON_UNESCAPED_UNICODE) }}"
data-supplier="{{ $supplier }}"
aria-label="选择 {{ $supplier }} 的整月退货">
@else
<span class="sr-muted">—</span>
@endif
</td>
<td>{{ $supplier }}</td>
<td class="sr-muted">{{ $upload['uploaded_at'] ?? '—' }}</td>
<td class="is-num">{{ $upload ? number_format((int) ($upload['rows'] ?? 0)) : '—' }}</td>
@ -295,7 +343,7 @@
</td>
</tr>
@empty
<tr><td colspan="6"><div class="sr-empty">还没有可对账的供应商:请先在「供应商应付(终版)→ 货款对账」导入我方结算数据。</div></td></tr>
<tr><td colspan="7"><div class="sr-empty">还没有可对账的供应商:请先在「供应商应付(终版)→ 货款对账」导入我方结算数据。</div></td></tr>
@endforelse
</tbody>
</table>
@ -675,3 +723,59 @@
})();
</script>
@endif
@if (! $detail)
<script>
(() => {
const form = document.getElementById('batch-return-push-form');
const button = document.getElementById('batch-return-push-button');
const countLabel = document.getElementById('batch-return-push-count');
const summary = document.getElementById('batch-return-push-summary');
const selectAll = document.getElementById('select-all-return-push');
const checkboxes = Array.from(document.querySelectorAll('.js-batch-supplier-checkbox'));
if (!form || !button || !countLabel || !summary || !selectAll) {
return;
}
const eligibleCount = checkboxes.length;
const updateSelection = () => {
const selected = checkboxes.filter((checkbox) => checkbox.checked);
countLabel.textContent = String(selected.length);
button.disabled = selected.length === 0;
button.classList.toggle('is-disabled', button.disabled);
selectAll.checked = selected.length > 0 && selected.length === eligibleCount;
selectAll.indeterminate = selected.length > 0 && selected.length < eligibleCount;
if (selected.length === 0) {
summary.textContent = `可批量推送 ${eligibleCount} 家;未配置机器人或所选月份无退货的厂家暂不可选。`;
return;
}
const names = selected.slice(0, 4).map((checkbox) => checkbox.dataset.supplier);
summary.textContent = `已选 ${selected.length} 家:${names.join('、')}${selected.length > 4 ? ' 等' : ''}`;
};
checkboxes.forEach((checkbox) => checkbox.addEventListener('change', updateSelection));
selectAll.addEventListener('change', () => {
checkboxes.forEach((checkbox) => {
checkbox.checked = selectAll.checked;
});
updateSelection();
});
form.addEventListener('submit', (event) => {
const selected = checkboxes.filter((checkbox) => checkbox.checked).length;
if (selected === 0 || !window.confirm(`确认将选中的 ${selected} 家供应商整月退货分别推送到各自钉钉群?`)) {
event.preventDefault();
return;
}
button.disabled = true;
button.classList.add('is-disabled');
button.textContent = '正在批量推送…';
});
updateSelection();
})();
</script>
@endif

View File

@ -468,6 +468,10 @@ Route::post('workspace/supplier-reconciliation/push-returns', [SupplierReconcili
->middleware('business.page:supplier-reconciliation,finance-data')
->name('business.supplier-reconciliation.push-returns');
Route::post('workspace/supplier-reconciliation/push-returns-batch', [SupplierReconciliationActions::class, 'pushReturnsBatch'])
->middleware('business.page:supplier-reconciliation,finance-data')
->name('business.supplier-reconciliation.push-returns-batch');
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

@ -270,6 +270,8 @@ class SupplierReconciliationDingTalkTest extends FeatureTestCase
$firstPage->assertSeeText('共 16 家')
->assertSeeText('每页 15 家')
->assertSeeText('第 1 / 2 页')
->assertSee('id="select-all-return-push"', false)
->assertSee('class="js-batch-supplier-checkbox"', false)
->assertSeeText('一键推送退货')
->assertSee('name="month" value="2026-10"', false);
$firstHtml = (string) $firstPage->getContent();
@ -294,6 +296,120 @@ class SupplierReconciliationDingTalkTest extends FeatureTestCase
$this->assertStringNotContainsString('分页厂家01', $secondTable);
}
public function test_reconciler_options_include_finance_names_when_month_has_only_returns(): void
{
$companyId = (int) $this->company->id;
$store = app(SupplierPayableOverrideStore::class);
$store->save('final:supplier:payment-reconciliation', 'payment:september', [
'summary_month' => '2026-09',
'purchaseNo' => 'PO-SEPTEMBER',
'date' => '2026-09-30',
'supplier' => '晨丰',
'skuCode' => 'SKU-1',
'qty' => '1',
'unitPrice' => '10',
'amount' => '10',
'reconciler' => '李萌',
], $companyId, null);
$store->save('final:supplier:return-reconciliation', 'return:october', [
'summary_month' => '2026-10',
'send_time' => '2026-10-08 10:00:00',
'supplier' => '晨丰',
'barcode' => 'RETURN-OCTOBER',
'sku_name' => '十月退货',
'qty' => '1',
'unit_price' => '10',
'amount' => '10',
'reconciler' => '陈亲园',
], $companyId, null);
$this->loginAs()->get(route('business.pages.show', [
'company_id' => $companyId,
'section' => 'supplier-reconciliation',
'page' => 'finance-data',
'month' => '2026-10',
]))
->assertOk()
->assertSee('<option value="李萌"', false)
->assertSee('<option value="陈亲园"', false);
}
public function test_batch_return_push_sends_each_selected_supplier_to_its_own_robot(): void
{
$companyId = (int) $this->company->id;
$store = app(SupplierPayableOverrideStore::class);
$notifier = app(SupplierDingTalkNotifier::class);
foreach (['晨丰', '鸣飞家具'] as $index => $supplier) {
$notifier->save($supplier, self::WEBHOOK, 'SEC-test-' . $index, false);
$store->save('final:supplier:return-reconciliation', 'return:' . $index, [
'summary_month' => '2026-10',
'send_time' => '2026-10-0' . ($index + 1) . ' 10:00:00',
'supplier' => $supplier,
'barcode' => 'RETURN-BATCH-' . $index,
'sku_name' => '批量推送退货',
'qty' => '1',
'unit_price' => '10',
'amount' => '10',
], $companyId, null);
}
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$this->loginAs()
->post(route('business.supplier-reconciliation.push-returns-batch'), [
'selected_returns' => [
json_encode(['supplier' => '晨丰', 'month' => '2026-10']),
json_encode(['supplier' => '鸣飞家具', 'month' => '2026-10']),
],
])
->assertStatus(302)
->assertSessionHas('success', '已批量推送 2 家供应商,共 2 条退货(2 条钉钉消息)。');
Http::assertSentCount(2);
Http::assertSent(fn ($request): bool => str_contains(
(string) ($request['markdown']['text'] ?? ''),
'RETURN-BATCH-0',
));
Http::assertSent(fn ($request): bool => str_contains(
(string) ($request['markdown']['text'] ?? ''),
'RETURN-BATCH-1',
));
}
public function test_batch_return_push_reports_suppliers_without_robots(): void
{
$companyId = (int) $this->company->id;
$store = app(SupplierPayableOverrideStore::class);
app(SupplierDingTalkNotifier::class)->save('晨丰', self::WEBHOOK, 'SEC-test-123', false);
foreach (['晨丰', '鸣飞家具'] as $index => $supplier) {
$store->save('final:supplier:return-reconciliation', 'return:partial:' . $index, [
'summary_month' => '2026-10',
'send_time' => '2026-10-0' . ($index + 1) . ' 10:00:00',
'supplier' => $supplier,
'barcode' => 'RETURN-PARTIAL-' . $index,
'sku_name' => '部分推送退货',
'qty' => '1',
'unit_price' => '10',
'amount' => '10',
], $companyId, null);
}
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$this->loginAs()
->post(route('business.supplier-reconciliation.push-returns-batch'), [
'selected_returns' => [
json_encode(['supplier' => '晨丰', 'month' => '2026-10']),
json_encode(['supplier' => '鸣飞家具', 'month' => '2026-10']),
],
])
->assertStatus(302)
->assertSessionHas('success', function (string $message): bool {
return str_contains($message, '已批量推送 1 家供应商,共 1 条退货(1 条钉钉消息)')
&& str_contains($message, '未推送 1 家:鸣飞家具(该厂家还没有配置钉钉群机器人 Webhook。)');
});
Http::assertSentCount(1);
}
public function test_return_months_are_available_and_default_to_the_latest_imported_month(): void
{
$this->seedReconciliation();