feat(供应商对账): 增加月度未上传催办
This commit is contained in:
parent
a65b0b41ff
commit
e53fb8bfe5
100
app/Console/Commands/SendSupplierStatementReminders.php
Normal file
100
app/Console/Commands/SendSupplierStatementReminders.php
Normal file
@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Common\Company;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementReminder;
|
||||
use Throwable;
|
||||
|
||||
class SendSupplierStatementReminders extends Command
|
||||
{
|
||||
protected $signature = 'supplier-statement:send-reminders
|
||||
{--date= : 执行日期,格式 Y-m-d,默认今天}
|
||||
{--supplier= : 仅检查指定供应商}
|
||||
{--dry-run : 只预览,不发送也不记录}';
|
||||
|
||||
protected $description = '按月度上传截止时间提醒尚未上传对账单的供应商';
|
||||
|
||||
public function handle(SupplierStatementReminder $reminder): int
|
||||
{
|
||||
$timezone = (string) config('app.platform_timezone', 'Asia/Shanghai');
|
||||
$dateValue = trim((string) $this->option('date')) ?: now($timezone)->toDateString();
|
||||
try {
|
||||
$date = Carbon::createFromFormat('!Y-m-d', $dateValue, $timezone)->startOfDay();
|
||||
} catch (Throwable) {
|
||||
$this->error('执行日期格式无效。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($date->format('Y-m-d') !== $dateValue) {
|
||||
$this->error('执行日期格式无效。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$failed = false;
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
foreach (Company::enabled()->orderBy('id')->get() as $company) {
|
||||
$company->makeCurrent();
|
||||
$lock = Cache::lock(sprintf(
|
||||
'supplier-statement-reminder:%d:%s',
|
||||
$company->id,
|
||||
$date->toDateString(),
|
||||
), 900);
|
||||
if (! $dryRun && ! $lock->get()) {
|
||||
$this->warn("#{$company->id} {$company->name}: 已有催办任务运行");
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $reminder->send(
|
||||
$date,
|
||||
(int) $company->id,
|
||||
$dryRun,
|
||||
trim((string) $this->option('supplier')),
|
||||
);
|
||||
if ($result['stage'] === null) {
|
||||
$this->line("#{$company->id} {$company->name}: 今天不在催办阶段");
|
||||
continue;
|
||||
}
|
||||
if ($result['target_count'] === 0) {
|
||||
$this->warn("#{$company->id} {$company->name}: 当前催办名单未配置");
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->line(sprintf(
|
||||
'#%d %s %s %s: 名单 %d 家,可提醒 %d 家,%s %d 家,已上传 %d 家,已提醒 %d 家,未配置机器人 %d 家,失败 %d 家',
|
||||
$company->id,
|
||||
$company->name,
|
||||
$result['accounting_month'],
|
||||
$result['stage'],
|
||||
$result['target_count'],
|
||||
$result['configured'],
|
||||
$dryRun ? '将提醒' : '已发送',
|
||||
count($dryRun ? $result['previewed'] : $result['sent']),
|
||||
count($result['uploaded']),
|
||||
count($result['already_sent']),
|
||||
count($result['missing_robot']),
|
||||
count($result['failed']),
|
||||
));
|
||||
foreach ($result['failed'] as $supplier => $message) {
|
||||
$this->error("{$supplier}: {$message}");
|
||||
$failed = true;
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error("#{$company->id} {$company->name}: 催办任务失败:" . $exception->getMessage());
|
||||
$failed = true;
|
||||
} finally {
|
||||
if (! $dryRun) {
|
||||
$lock->release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
96
app/Console/Commands/SetSupplierStatementReminderTargets.php
Normal file
96
app/Console/Commands/SetSupplierStatementReminderTargets.php
Normal file
@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Common\Company;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementReminderTargets;
|
||||
use Throwable;
|
||||
|
||||
class SetSupplierStatementReminderTargets extends Command
|
||||
{
|
||||
protected $signature = 'supplier-statement:targets:set
|
||||
{file=- : UTF-8 文本文件路径,每行一个供应商名称;- 表示从 stdin 读取}
|
||||
{--company= : 公司 ID,默认当前公司或 1}';
|
||||
|
||||
protected $description = '设置月度对账催办的当前供应商名单';
|
||||
|
||||
public function handle(
|
||||
SupplierStatementReminderTargets $targets,
|
||||
SupplierDingTalkNotifier $notifier,
|
||||
): int {
|
||||
$companyId = (int) ($this->option('company') ?: (company_id() ?: 1));
|
||||
$company = Company::query()->whereKey($companyId)->first();
|
||||
if (! $company) {
|
||||
$this->error("公司 #{$companyId} 不存在。");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$company->makeCurrent();
|
||||
|
||||
$path = trim((string) $this->argument('file')) ?: '-';
|
||||
$handle = $path === '-' ? STDIN : @fopen($path, 'rb');
|
||||
if (! is_resource($handle)) {
|
||||
$this->error('无法读取供应商名单文件。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$names = [];
|
||||
$lineNumber = 0;
|
||||
try {
|
||||
while (($line = fgets($handle)) !== false) {
|
||||
$lineNumber++;
|
||||
if ($lineNumber === 1) {
|
||||
$line = ltrim($line, "\xEF\xBB\xBF");
|
||||
}
|
||||
$name = trim($line);
|
||||
if ($lineNumber === 1 && in_array($name, ['供应商', '供应商名称'], true)) {
|
||||
continue;
|
||||
}
|
||||
if ($name !== '') {
|
||||
$names[] = $name;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if ($path !== '-') {
|
||||
fclose($handle);
|
||||
}
|
||||
}
|
||||
|
||||
if ($lineNumber > 5000) {
|
||||
$this->error('催办名单不能超过 5000 行。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($names === []) {
|
||||
$this->error('供应商名单为空,未修改现有名单。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$saved = $targets->replace($names);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$missingRobots = array_values(array_diff($saved, $notifier->configuredSuppliers()));
|
||||
$this->info(sprintf(
|
||||
'#%d %s: 已保存 %d 家当前供应商;其中 %d 家可自动催办,%d 家未配置钉钉群机器人。',
|
||||
$company->id,
|
||||
$company->name,
|
||||
count($saved),
|
||||
count($saved) - count($missingRobots),
|
||||
count($missingRobots),
|
||||
));
|
||||
if ($missingRobots !== []) {
|
||||
$this->warn('未配置机器人:' . implode('、', $missingRobots));
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -89,6 +89,14 @@ class Kernel extends ConsoleKernel
|
||||
->appendOutputTo(storage_path('logs/supplier-negative-alert-dingtalk.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 厂家对账单月度催办:每日运行,按截止日前、截止日、逾期阶段各提醒一次。
|
||||
$schedule->command('supplier-statement:send-reminders')
|
||||
->dailyAt((string) config('supplier_reconciliation.reminder.run_time', '10:00'))
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(30)
|
||||
->appendOutputTo(storage_path('logs/supplier-statement-reminders.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 进销存月报导入后检查仓库简称映射;每日补偿检查避免导入与提醒步骤间断。
|
||||
$schedule->command('inventory:sync-warehouse-mapping-alert')
|
||||
->dailyAt('10:15')
|
||||
|
||||
15
config/supplier_reconciliation.php
Normal file
15
config/supplier_reconciliation.php
Normal file
@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
// 每月核对上一个完整月份;上传和退货确认日期与厂家端页面保持一致。
|
||||
'upload_deadline_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_UPLOAD_DEADLINE_DAY', 5))),
|
||||
'return_confirmation_deadline_day' => max(1, min(28, (int) env('SUPPLIER_RETURN_CONFIRMATION_DEADLINE_DAY', 13))),
|
||||
|
||||
'reminder' => [
|
||||
// 每天运行任务,只在对应阶段执行;3-4 日提示即将截止,5 日提示当日截止,6 日起提示逾期。
|
||||
'due_soon_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_DUE_SOON_DAY', 3))),
|
||||
'overdue_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_OVERDUE_DAY', 6))),
|
||||
'run_time' => env('SUPPLIER_STATEMENT_REMINDER_TIME', '10:00'),
|
||||
'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'),
|
||||
],
|
||||
];
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@ -72,6 +73,16 @@ class SupplierDingTalkNotifier
|
||||
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,
|
||||
@ -494,6 +505,72 @@ class SupplierDingTalkNotifier
|
||||
return true;
|
||||
}
|
||||
|
||||
public function sendStatementReminder(
|
||||
string $supplier,
|
||||
string $accountingMonth,
|
||||
Carbon $deadline,
|
||||
Carbon $runDate,
|
||||
string $stage,
|
||||
int $companyId,
|
||||
): void {
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $accountingMonth) !== 1) {
|
||||
throw ValidationException::withMessages(['statement_reminder' => '对账月份格式无效。']);
|
||||
}
|
||||
if (! in_array($stage, ['due_soon', 'due_today', 'overdue'], true)) {
|
||||
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'));
|
||||
$deadlineLabel = $deadline->format('n月j日') . ' 24:00';
|
||||
$deadlineDays = $deadline->day - $runDate->day;
|
||||
$statusLine = match ($stage) {
|
||||
'due_soon' => '距离上传截止还有 **' . max(0, $deadlineDays) . ' 天**,请尽快上传。',
|
||||
'due_today' => '**今天是上传截止日**,请于 24:00 前完成上传。',
|
||||
'overdue' => '**上传已逾期 ' . max(0, -$deadlineDays) . ' 天**,请尽快补传。',
|
||||
};
|
||||
$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月') . '**',
|
||||
'- 上传截止:**' . $deadlineLabel . '**',
|
||||
'- 系统状态:**本月尚未收到对账单上传记录**',
|
||||
'- ' . $statusLine,
|
||||
'',
|
||||
'#### [打开厂家端对账入口](' . $portalUrl . ')',
|
||||
'请完成钉钉身份验证后上传对账单;同一钉钉账号对应多家供应商时,登录后可切换厂家。',
|
||||
$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 list<array<string,mixed>> $records */
|
||||
private function statementMonths(array $records): string
|
||||
{
|
||||
|
||||
156
modules/EcommerceFinance/Services/SupplierStatementReminder.php
Normal file
156
modules/EcommerceFinance/Services/SupplierStatementReminder.php
Normal file
@ -0,0 +1,156 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use Throwable;
|
||||
|
||||
class SupplierStatementReminder
|
||||
{
|
||||
private const SETTING_KEY = 'supplier_reconciliation.statement_reminders';
|
||||
|
||||
public function __construct(
|
||||
private readonly SupplierStatementStore $statements,
|
||||
private readonly SupplierDingTalkNotifier $notifier,
|
||||
private readonly SupplierStatementReminderTargets $targets,
|
||||
) {
|
||||
}
|
||||
|
||||
public function stageFor(Carbon $date): ?string
|
||||
{
|
||||
$deadlineDay = (int) config('supplier_reconciliation.upload_deadline_day', 5);
|
||||
$dueSoonDay = (int) config('supplier_reconciliation.reminder.due_soon_day', 3);
|
||||
$overdueDay = (int) config('supplier_reconciliation.reminder.overdue_day', 6);
|
||||
|
||||
if ($date->day >= $overdueDay) {
|
||||
return 'overdue';
|
||||
}
|
||||
if ($date->day === $deadlineDay) {
|
||||
return 'due_today';
|
||||
}
|
||||
if ($date->day >= $dueSoonDay) {
|
||||
return 'due_soon';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* stage:?string,
|
||||
* accounting_month:string,
|
||||
* deadline:string,
|
||||
* target_count:int,
|
||||
* configured:int,
|
||||
* missing_robot:list<string>,
|
||||
* uploaded:list<string>,
|
||||
* already_sent:list<string>,
|
||||
* sent:list<string>,
|
||||
* previewed:list<string>,
|
||||
* failed:array<string,string>
|
||||
* }
|
||||
*/
|
||||
public function send(
|
||||
Carbon $date,
|
||||
int $companyId,
|
||||
bool $dryRun = false,
|
||||
string $onlySupplier = '',
|
||||
): array {
|
||||
$stage = $this->stageFor($date);
|
||||
$accountingMonth = $date->copy()->startOfMonth()->subMonthNoOverflow()->format('Y-m');
|
||||
$deadline = $date->copy()->startOfMonth()
|
||||
->addDays((int) config('supplier_reconciliation.upload_deadline_day', 5) - 1)
|
||||
->setTime(23, 59, 59);
|
||||
$result = [
|
||||
'stage' => $stage,
|
||||
'accounting_month' => $accountingMonth,
|
||||
'deadline' => $deadline->toDateTimeString(),
|
||||
'target_count' => 0,
|
||||
'configured' => 0,
|
||||
'missing_robot' => [],
|
||||
'uploaded' => [],
|
||||
'already_sent' => [],
|
||||
'sent' => [],
|
||||
'previewed' => [],
|
||||
'failed' => [],
|
||||
];
|
||||
if ($stage === null) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$targets = $this->targets->names();
|
||||
$onlySupplier = trim($onlySupplier);
|
||||
if ($onlySupplier !== '') {
|
||||
$targets = array_values(array_filter(
|
||||
$targets,
|
||||
static fn (string $supplier): bool => $supplier === $onlySupplier,
|
||||
));
|
||||
}
|
||||
$configured = array_fill_keys($this->notifier->configuredSuppliers(), true);
|
||||
$suppliers = array_values(array_filter(
|
||||
$targets,
|
||||
static fn (string $supplier): bool => isset($configured[$supplier]),
|
||||
));
|
||||
$result['target_count'] = count($targets);
|
||||
$result['configured'] = count($suppliers);
|
||||
$result['missing_robot'] = array_values(array_diff($targets, $suppliers));
|
||||
$state = $this->state();
|
||||
|
||||
foreach (array_values(array_unique($suppliers)) as $supplier) {
|
||||
if ($this->statements->hasUploadInMonth($supplier, $date->format('Y-m'), $companyId)) {
|
||||
$result['uploaded'][] = $supplier;
|
||||
continue;
|
||||
}
|
||||
if (isset($state[$accountingMonth][$stage][$supplier])) {
|
||||
$result['already_sent'][] = $supplier;
|
||||
continue;
|
||||
}
|
||||
if ($dryRun) {
|
||||
$result['previewed'][] = $supplier;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->notifier->sendStatementReminder(
|
||||
$supplier,
|
||||
$accountingMonth,
|
||||
$deadline,
|
||||
$date,
|
||||
$stage,
|
||||
$companyId,
|
||||
);
|
||||
$this->recordSent($accountingMonth, $stage, $supplier, $deadline);
|
||||
$result['sent'][] = $supplier;
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$result['failed'][$supplier] = $exception->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function state(): array
|
||||
{
|
||||
$state = setting(self::SETTING_KEY, []);
|
||||
if (is_string($state)) {
|
||||
$state = json_decode($state, true) ?: [];
|
||||
}
|
||||
|
||||
return is_array($state) ? $state : [];
|
||||
}
|
||||
|
||||
private function recordSent(string $accountingMonth, string $stage, string $supplier, Carbon $deadline): void
|
||||
{
|
||||
$state = $this->state();
|
||||
$state[$accountingMonth][$stage][$supplier] = [
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
'deadline' => $deadline->toDateTimeString(),
|
||||
];
|
||||
uksort($state, static fn (string $left, string $right): int => strcmp($right, $left));
|
||||
$state = array_slice($state, 0, 24, true);
|
||||
|
||||
setting()->set(self::SETTING_KEY, json_encode($state, JSON_UNESCAPED_UNICODE));
|
||||
setting()->save();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class SupplierStatementReminderTargets
|
||||
{
|
||||
private const SETTING_KEY = 'supplier_reconciliation.statement_reminder_suppliers';
|
||||
|
||||
/** @return list<string> */
|
||||
public function names(): array
|
||||
{
|
||||
$names = setting(self::SETTING_KEY, []);
|
||||
if (is_string($names)) {
|
||||
$names = json_decode($names, true) ?: [];
|
||||
}
|
||||
if (! is_array($names)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->normalize($names);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function replace(array $names): array
|
||||
{
|
||||
$names = $this->normalize($names);
|
||||
if (count($names) > 5000) {
|
||||
throw new InvalidArgumentException('催办名单不能超过 5000 家供应商。');
|
||||
}
|
||||
|
||||
setting()->set(self::SETTING_KEY, json_encode($names, JSON_UNESCAPED_UNICODE));
|
||||
setting()->save();
|
||||
|
||||
return $names;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function normalize(array $names): array
|
||||
{
|
||||
$normalized = [];
|
||||
foreach ($names as $name) {
|
||||
$name = trim((string) $name);
|
||||
if ($name === '') {
|
||||
continue;
|
||||
}
|
||||
if (mb_strlen($name) > 191) {
|
||||
throw new InvalidArgumentException('供应商名称超过 191 个字符。');
|
||||
}
|
||||
$normalized[$name] = true;
|
||||
}
|
||||
|
||||
$normalized = array_keys($normalized);
|
||||
natcasesort($normalized);
|
||||
|
||||
return array_values($normalized);
|
||||
}
|
||||
}
|
||||
@ -50,6 +50,22 @@ class SupplierStatementStore
|
||||
return array_slice($uploads, 0, $limit);
|
||||
}
|
||||
|
||||
public function hasUploadInMonth(string $supplier, string $month, int $companyId): bool
|
||||
{
|
||||
$month = substr(trim($month), 0, 7);
|
||||
if ($supplier === '' || preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($this->store->listRows(self::LOG_PREFIX . $supplier, $companyId) as $upload) {
|
||||
if (substr((string) ($upload['uploaded_at'] ?? ''), 0, 7) === $month) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @return list<string> 已经上传过对账单的厂家名称 */
|
||||
public function uploadedSuppliers(int $companyId): array
|
||||
{
|
||||
|
||||
@ -410,8 +410,10 @@ class SupplierReconciliationPageData
|
||||
{
|
||||
$now = \Illuminate\Support\Carbon::now();
|
||||
$accountingMonth = $now->copy()->subMonthNoOverflow()->startOfMonth();
|
||||
$uploadDeadline = $now->copy()->startOfMonth()->addDays(4)->setTime(23, 59, 59);
|
||||
$returnDeadline = $now->copy()->startOfMonth()->addDays(12)->setTime(18, 0);
|
||||
$uploadDeadlineDay = (int) config('supplier_reconciliation.upload_deadline_day', 5);
|
||||
$returnDeadlineDay = (int) config('supplier_reconciliation.return_confirmation_deadline_day', 13);
|
||||
$uploadDeadline = $now->copy()->startOfMonth()->addDays($uploadDeadlineDay - 1)->setTime(23, 59, 59);
|
||||
$returnDeadline = $now->copy()->startOfMonth()->addDays($returnDeadlineDay - 1)->setTime(18, 0);
|
||||
|
||||
return [
|
||||
'accountingMonthKey' => $accountingMonth->format('Y-m'),
|
||||
|
||||
201
tests/Feature/Business/SupplierStatementReminderTest.php
Normal file
201
tests/Feature/Business/SupplierStatementReminderTest.php
Normal file
@ -0,0 +1,201 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementReminder;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementReminderTargets;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class SupplierStatementReminderTest extends FeatureTestCase
|
||||
{
|
||||
private const WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=statement-reminder-test';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->company->makeCurrent();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Carbon::setTestNow();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_due_soon_reminder_is_scoped_to_unuploaded_suppliers_and_never_duplicates(): void
|
||||
{
|
||||
Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'));
|
||||
app(SupplierStatementReminderTargets::class)->replace(['晨丰', '鸣飞家具']);
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
$notifier->save('晨丰', self::WEBHOOK, '', false);
|
||||
$notifier->save('鸣飞家具', self::WEBHOOK . '-second', '', false);
|
||||
app(SupplierStatementStore::class)->save('晨丰', [], '晨丰-202610.csv', (int) $this->company->id, null);
|
||||
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
|
||||
|
||||
$this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-03'])
|
||||
->assertSuccessful();
|
||||
$this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-04'])
|
||||
->assertSuccessful();
|
||||
|
||||
Http::assertSentCount(1);
|
||||
$request = Http::recorded()->first()[0];
|
||||
$text = (string) ($request['markdown']['text'] ?? '');
|
||||
$this->assertStringContainsString('statement-reminder-test-second', $request->url());
|
||||
$this->assertStringContainsString('供应商月度对账单催办 · 鸣飞家具', $text);
|
||||
$this->assertStringContainsString('对账月份:**2026年10月**', $text);
|
||||
$this->assertStringContainsString('上传截止:**11月5日 24:00**', $text);
|
||||
$this->assertStringContainsString('距离上传截止还有 **2 天**', $text);
|
||||
$this->assertStringContainsString('/1/workspace/supplier-portal', $text);
|
||||
$this->assertStringNotContainsString('晨丰', $text);
|
||||
|
||||
$state = json_decode((string) setting('supplier_reconciliation.statement_reminders'), true);
|
||||
$this->assertArrayHasKey('鸣飞家具', $state['2026-10']['due_soon'] ?? []);
|
||||
$this->assertArrayNotHasKey('晨丰', $state['2026-10']['due_soon'] ?? []);
|
||||
}
|
||||
|
||||
public function test_deadline_and_overdue_stages_each_send_once(): void
|
||||
{
|
||||
app(SupplierStatementReminderTargets::class)->replace(['晨丰']);
|
||||
app(SupplierDingTalkNotifier::class)->save('晨丰', self::WEBHOOK, '', false);
|
||||
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
|
||||
|
||||
foreach (['2026-11-03', '2026-11-05', '2026-11-06', '2026-11-07'] as $date) {
|
||||
Carbon::setTestNow(Carbon::parse($date . ' 10:00:00', 'Asia/Shanghai'));
|
||||
$this->artisan('supplier-statement:send-reminders', ['--date' => $date])
|
||||
->assertSuccessful();
|
||||
}
|
||||
|
||||
Http::assertSentCount(3);
|
||||
$texts = Http::recorded()
|
||||
->map(static fn (array $pair): string => (string) ($pair[0]['markdown']['text'] ?? ''))
|
||||
->implode("\n");
|
||||
$this->assertStringContainsString('今天是上传截止日', $texts);
|
||||
$this->assertStringContainsString('上传已逾期 1 天', $texts);
|
||||
}
|
||||
|
||||
public function test_dry_run_reports_uploaded_and_pending_suppliers_without_sending(): void
|
||||
{
|
||||
Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'));
|
||||
app(SupplierStatementReminderTargets::class)->replace(['晨丰', '鸣飞家具', '未配置厂家']);
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
$notifier->save('晨丰', self::WEBHOOK, '', false);
|
||||
$notifier->save('鸣飞家具', self::WEBHOOK . '-second', '', false);
|
||||
app(SupplierStatementStore::class)->save('晨丰', [], '晨丰-202610.csv', (int) $this->company->id, null);
|
||||
Http::fake();
|
||||
|
||||
$result = app(SupplierStatementReminder::class)->send(
|
||||
Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'),
|
||||
(int) $this->company->id,
|
||||
true,
|
||||
);
|
||||
|
||||
Http::assertNothingSent();
|
||||
$this->assertSame(['鸣飞家具'], $result['previewed']);
|
||||
$this->assertSame(['晨丰'], $result['uploaded']);
|
||||
$this->assertSame(['未配置厂家'], $result['missing_robot']);
|
||||
$this->assertNull(setting('supplier_reconciliation.statement_reminders'));
|
||||
}
|
||||
|
||||
public function test_failed_delivery_is_not_recorded_and_can_be_retried(): void
|
||||
{
|
||||
Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'));
|
||||
app(SupplierStatementReminderTargets::class)->replace(['晨丰']);
|
||||
app(SupplierDingTalkNotifier::class)->save('晨丰', self::WEBHOOK, '', false);
|
||||
Http::fakeSequence()
|
||||
->push(['errcode' => 500, 'errmsg' => 'temporary failure'], 500)
|
||||
->push(['errcode' => 0, 'errmsg' => 'ok']);
|
||||
|
||||
$this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-03'])
|
||||
->assertFailed();
|
||||
$this->assertNull(setting('supplier_reconciliation.statement_reminders'));
|
||||
|
||||
$this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-03'])
|
||||
->assertSuccessful();
|
||||
Http::assertSentCount(2);
|
||||
$state = json_decode((string) setting('supplier_reconciliation.statement_reminders'), true);
|
||||
$this->assertArrayHasKey('晨丰', $state['2026-10']['due_soon'] ?? []);
|
||||
}
|
||||
|
||||
public function test_dry_run_handles_122_configured_suppliers(): void
|
||||
{
|
||||
Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'));
|
||||
$suppliers = array_map(static fn (int $index): string => '测试供应商' . str_pad(
|
||||
(string) $index,
|
||||
3,
|
||||
'0',
|
||||
STR_PAD_LEFT,
|
||||
), range(1, 122));
|
||||
|
||||
$configs = [];
|
||||
foreach ($suppliers as $supplier) {
|
||||
$configs[$supplier] = [
|
||||
'webhook' => \Illuminate\Support\Facades\Crypt::encryptString(self::WEBHOOK),
|
||||
'secret' => '',
|
||||
'at_all' => false,
|
||||
'card_conversation_id' => '',
|
||||
'card_robot_code' => '',
|
||||
'last_pushed_at' => '',
|
||||
'last_push_count' => 0,
|
||||
];
|
||||
}
|
||||
setting()->set(
|
||||
'supplier_reconciliation.dingtalk_robots',
|
||||
json_encode($configs, JSON_UNESCAPED_UNICODE),
|
||||
);
|
||||
setting()->save();
|
||||
app(SupplierStatementReminderTargets::class)->replace($suppliers);
|
||||
Http::fake();
|
||||
|
||||
$result = app(SupplierStatementReminder::class)->send(
|
||||
Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'),
|
||||
(int) $this->company->id,
|
||||
true,
|
||||
);
|
||||
|
||||
Http::assertNothingSent();
|
||||
$this->assertCount(122, $result['previewed']);
|
||||
$this->assertSame([], $result['failed']);
|
||||
$this->assertNull(setting('supplier_reconciliation.statement_reminders'));
|
||||
}
|
||||
|
||||
public function test_reminder_requires_a_current_supplier_allowlist(): void
|
||||
{
|
||||
Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'));
|
||||
app(SupplierDingTalkNotifier::class)->save('晨丰', self::WEBHOOK, '', false);
|
||||
Http::fake();
|
||||
|
||||
$this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-03'])
|
||||
->expectsOutputToContain('当前催办名单未配置')
|
||||
->assertSuccessful();
|
||||
|
||||
Http::assertNothingSent();
|
||||
$this->assertNull(setting('supplier_reconciliation.statement_reminders'));
|
||||
}
|
||||
|
||||
public function test_supplier_allowlist_can_be_imported_from_a_text_file(): void
|
||||
{
|
||||
$path = tempnam(sys_get_temp_dir(), 'supplier-reminder-targets-');
|
||||
file_put_contents($path, "\xEF\xBB\xBF供应商\n 晨丰 \n鸣飞家具\n晨丰\n");
|
||||
|
||||
try {
|
||||
$this->artisan('supplier-statement:targets:set', [
|
||||
'file' => $path,
|
||||
'--company' => $this->company->id,
|
||||
])->expectsOutputToContain('已保存 2 家当前供应商')
|
||||
->assertSuccessful();
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
|
||||
$this->assertSame(
|
||||
['晨丰', '鸣飞家具'],
|
||||
app(SupplierStatementReminderTargets::class)->names(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user