feat: 进销存未映射仓库自动创建提醒任务

This commit is contained in:
chenxi 2026-11-02 11:13:51 +08:00
parent bc4844ed36
commit 69873f869a
9 changed files with 445 additions and 2 deletions

View File

@ -0,0 +1,242 @@
<?php
namespace App\Business;
use App\Models\Business\SystemizationTodo;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\InventoryReportAuthoritativeImporter;
use RuntimeException;
class InventoryWarehouseMappingAlerts
{
public const CATEGORY = '商品价格管理';
public const SECTION = '进销存报表';
private const SOURCE_KEY_PREFIX = 'inventory-warehouse-unmapped:';
private readonly string $mirrorConnection;
public function __construct(
private readonly DatabaseManager $databases,
private readonly InventoryWarehouseShortNames $shortNames,
) {
$this->mirrorConnection = (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function latestMonth(): ?string
{
$connection = $this->databases->connection($this->mirrorConnection);
$schema = Schema::connection($this->mirrorConnection);
if (! $schema->hasTable('inventory_report_authoritative_months')) {
return null;
}
$month = $connection->table('inventory_report_authoritative_months')
->where('dataset_key', InventoryReportAuthoritativeImporter::DATASET_KEY)
->where('status', 'succeeded')
->whereNotNull('active_generation')
->orderByDesc('source_month')
->value('source_month');
return $month === null
? null
: Carbon::parse($month)->startOfMonth()->toDateString();
}
/**
* @return array{
* status:string,
* month:string,
* missing_pair_count:int,
* missing_row_count:int,
* task_id:?int,
* action:string
* }
*/
public function syncMonth(string $month, int $companyId = 1): array
{
$month = Carbon::parse($month)->startOfMonth()->toDateString();
$lockKey = sprintf('inventory-warehouse-mapping-alert:%d:%s', $companyId, $month);
return Cache::lock($lockKey, 120)->block(20, function () use ($month, $companyId): array {
return $this->syncMonthWithoutLock($month, $companyId);
});
}
/**
* @return array{
* status:string,
* month:string,
* missing_pair_count:int,
* missing_row_count:int,
* task_id:?int,
* action:string
* }
*/
private function syncMonthWithoutLock(string $month, int $companyId): array
{
$connection = $this->databases->connection($this->mirrorConnection);
$schema = Schema::connection($this->mirrorConnection);
foreach (['inventory_report_authoritative_months', 'inventory_report_authoritative_rows'] as $table) {
if (! $schema->hasTable($table)) {
throw new RuntimeException('进销存权威月报表尚未完成迁移:' . $table);
}
}
$state = $connection->table('inventory_report_authoritative_months')
->where('dataset_key', InventoryReportAuthoritativeImporter::DATASET_KEY)
->whereDate('source_month', $month)
->where('status', 'succeeded')
->whereNotNull('active_generation')
->first();
if ($state === null) {
throw new RuntimeException('该月份尚无已激活的进销存权威月报:' . $month);
}
$sourcePairs = $connection->table('inventory_report_authoritative_rows')
->where('generation', (string) $state->active_generation)
->whereDate('report_month', $month)
->select(['warehouse_provider', 'warehouse'])
->selectRaw('COUNT(*) AS source_rows')
->groupBy('warehouse_provider', 'warehouse')
->orderByDesc('source_rows')
->orderBy('warehouse_provider')
->orderBy('warehouse')
->get();
$mapping = $this->shortNames->forCompany($companyId);
$missing = [];
foreach ($sourcePairs as $pair) {
$provider = trim((string) $pair->warehouse_provider);
$warehouse = trim((string) $pair->warehouse);
$shortName = trim((string) ($mapping[$provider . "\0" . $warehouse] ?? ''));
if ($shortName !== '') {
continue;
}
$missing[] = [
'warehouse_provider' => $provider,
'warehouse' => $warehouse,
'source_rows' => (int) $pair->source_rows,
];
}
$sourceKey = self::SOURCE_KEY_PREFIX . substr($month, 0, 7);
$todo = SystemizationTodo::withTrashed()
->allCompanies()
->where('company_id', $companyId)
->where('source_key', $sourceKey)
->first();
if ($todo?->trashed()) {
return [
'status' => 'skipped',
'month' => $month,
'missing_pair_count' => count($missing),
'missing_row_count' => array_sum(array_column($missing, 'source_rows')),
'task_id' => (int) $todo->id,
'action' => 'deleted',
];
}
$monthLabel = Carbon::parse($month)->format('Y年n月');
if ($missing === []) {
if ($todo === null) {
return [
'status' => 'complete',
'month' => $month,
'missing_pair_count' => 0,
'missing_row_count' => 0,
'task_id' => null,
'action' => 'none',
];
}
if ($todo->status !== SystemizationTodo::STATUS_COMPLETED) {
$todo->update([
'status' => SystemizationTodo::STATUS_COMPLETED,
'completed_at' => today()->toDateString(),
'progress' => $monthLabel . ' 进销存报表的仓储方和仓库均已配置仓库简称,自动完成提醒。',
'notes' => null,
]);
return [
'status' => 'complete',
'month' => $month,
'missing_pair_count' => 0,
'missing_row_count' => 0,
'task_id' => (int) $todo->id,
'action' => 'completed',
];
}
return [
'status' => 'complete',
'month' => $month,
'missing_pair_count' => 0,
'missing_row_count' => 0,
'task_id' => (int) $todo->id,
'action' => 'unchanged',
];
}
$missingRowCount = array_sum(array_column($missing, 'source_rows'));
$progress = [
sprintf(
'%s 聚水潭进销存报表发现 %d 个“仓储方 / 仓库”组合未配置仓库简称,共涉及 %d 行。',
$monthLabel,
count($missing),
$missingRowCount,
),
'请前往“商品价格管理 → 进销存报表 → 仓库名称映射表”补充映射。',
'',
];
foreach ($missing as $index => $item) {
$progress[] = sprintf(
'%d. %s / %s(%d 行)',
$index + 1,
$item['warehouse_provider'],
$item['warehouse'],
$item['source_rows'],
);
}
$payload = [
'category' => self::CATEGORY,
'section' => self::SECTION,
'title' => $monthLabel . ' 进销存仓库简称待映射',
'status' => SystemizationTodo::STATUS_INCOMPLETE,
'completed_at' => null,
'progress' => implode("\n", $progress),
'notes' => null,
];
if ($todo === null) {
$todo = SystemizationTodo::allCompanies()->create([
...$payload,
'company_id' => $companyId,
'start_date' => today()->toDateString(),
'sort_order' => (int) SystemizationTodo::allCompanies()
->where('company_id', $companyId)
->max('sort_order') + 1,
'source_key' => $sourceKey,
'imported_at' => null,
]);
$action = 'created';
} else {
$action = $todo->status === SystemizationTodo::STATUS_COMPLETED
? 'reopened'
: 'updated';
$todo->update($payload);
}
return [
'status' => 'missing',
'month' => $month,
'missing_pair_count' => count($missing),
'missing_row_count' => $missingRowCount,
'task_id' => (int) $todo->id,
'action' => $action,
];
}
}

View File

@ -2,6 +2,7 @@
namespace App\Console\Commands;
use App\Business\InventoryWarehouseMappingAlerts;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\InventoryReportAuthoritativeImporter;
use Throwable;
@ -9,11 +10,15 @@ use Throwable;
class ImportInventoryReportAuthoritativeMonth extends Command
{
protected $signature = 'business-mirror:import-inventory-report-month
{path : 聚水潭按商品、按仓库、按月多维分析完整 XLSX 导出文件}';
{path : 聚水潭按商品、按仓库、按月多维分析完整 XLSX 导出文件}
{--company-id=1 : 提醒任务归属公司}';
protected $description = '导入进销存报表权威月明细,保留仓储方和子仓维度';
public function handle(InventoryReportAuthoritativeImporter $importer): int
public function handle(
InventoryReportAuthoritativeImporter $importer,
InventoryWarehouseMappingAlerts $alerts,
): int
{
try {
$result = $importer->import((string) $this->argument('path'));
@ -31,6 +36,33 @@ class ImportInventoryReportAuthoritativeMonth extends Command
$result['source_rows'],
));
try {
$alert = $alerts->syncMonth(
$result['source_month'],
max(1, (int) $this->option('company-id')),
);
if ($alert['missing_pair_count'] > 0) {
$this->warn(sprintf(
'仓库简称提醒:%d 个仓储方/仓库组合未映射,涉及 %d 行;提醒任务 #%d 已%s。',
$alert['missing_pair_count'],
$alert['missing_row_count'],
$alert['task_id'],
match ($alert['action']) {
'created' => '创建',
'reopened' => '重新打开',
default => '更新',
},
));
} else {
$this->info('仓库简称映射完整。');
}
} catch (Throwable $exception) {
report($exception);
$this->error('进销存月报已导入,但仓库简称提醒任务创建失败:' . $exception->getMessage());
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -0,0 +1,76 @@
<?php
namespace App\Console\Commands;
use App\Business\InventoryWarehouseMappingAlerts;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Throwable;
class SyncInventoryWarehouseMappingAlerts extends Command
{
protected $signature = 'inventory:sync-warehouse-mapping-alert
{--month= : 指定月份(YYYY-MM),默认检查最新已激活的进销存月报}
{--company-id=1 : 提醒任务归属公司}';
protected $description = '检查进销存月报中未映射的仓库简称,并同步月度提醒任务';
public function handle(InventoryWarehouseMappingAlerts $alerts): int
{
$monthOption = trim((string) $this->option('month'));
$companyId = max(1, (int) $this->option('company-id'));
if ($monthOption !== '' && preg_match('/^\d{4}-\d{2}(?:-\d{2})?$/', $monthOption) !== 1) {
$this->error('月份格式应为 YYYY-MM。');
return self::FAILURE;
}
try {
$month = $monthOption !== ''
? Carbon::parse($monthOption)->startOfMonth()->toDateString()
: $alerts->latestMonth();
if ($month === null) {
$this->line('暂无已激活的进销存权威月报,未生成提醒任务。');
return self::SUCCESS;
}
$result = $alerts->syncMonth($month, $companyId);
} catch (Throwable $exception) {
report($exception);
$this->error('进销存仓库简称提醒任务同步失败:' . $exception->getMessage());
return self::FAILURE;
}
if ($result['status'] === 'skipped' && $result['action'] === 'deleted') {
$this->warn(sprintf(
'%s 的仓库简称提醒任务已被人工删除,本次不重新创建。',
substr($result['month'], 0, 7),
));
return self::SUCCESS;
}
if ($result['missing_pair_count'] > 0) {
$this->warn(sprintf(
'%s 有 %d 个仓储方/仓库组合未映射仓库简称,涉及 %d 行;提醒任务 #%d 已%s。',
substr($result['month'], 0, 7),
$result['missing_pair_count'],
$result['missing_row_count'],
$result['task_id'],
match ($result['action']) {
'created' => '创建',
'reopened' => '重新打开',
default => '更新',
},
));
return self::SUCCESS;
}
$this->info(substr($result['month'], 0, 7) . ' 的进销存仓库简称映射完整。');
return self::SUCCESS;
}
}

View File

@ -91,6 +91,14 @@ class Kernel extends ConsoleKernel
->appendOutputTo(storage_path('logs/supplier-negative-alert-dingtalk.log'))
->runInBackground();
// 进销存月报导入后检查仓库简称映射;每日补偿检查避免导入与提醒步骤间断。
$schedule->command('inventory:sync-warehouse-mapping-alert')
->dailyAt('10:15')
->timezone('Asia/Shanghai')
->withoutOverlapping(60)
->appendOutputTo(storage_path('logs/inventory-warehouse-mapping-alert.log'))
->runInBackground();
// 财务台账:从 AI 库 rpt 同步动账明细,按日重算账户流水。
// 生产宿主机 cron 仍需配置对应的 finance-ledger:sync-rpt 入口。
$schedule->command('finance-ledger:sync-rpt --days=7 --merge')

View File

@ -222,6 +222,8 @@ CRON_TZ=Asia/Shanghai
# 店铺违规预警推送:P0/P1 每天 09:00 起每 5 分钟检查;P2 每日 10:00 汇总(未配置 Webhook 时自动跳过)。
*/5 9-21 * * * root /usr/bin/flock -n /run/caiwu-violation-push.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:push-instant --quiet >/dev/null 2>&1
0 10 * * * root /usr/bin/flock -n /run/caiwu-violation-push.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:push-digest --quiet >/dev/null 2>&1
# 进销存月报导入后检查仓库简称映射;每日补偿检查避免导入与提醒步骤间断。
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
# 供应商管理每天北京时间 08:15 完整校准档案、合同、联系人与打款资料。
15 8 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-management --quiet >/dev/null 2>&1
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1

View File

@ -226,6 +226,8 @@ CRON_TZ=Asia/Shanghai
# 店铺违规预警推送:P0/P1 每天 09:00 起每 5 分钟检查;P2 每日 10:00 汇总(未配置 Webhook 时自动跳过)。
*/5 9-21 * * * root /usr/bin/flock -n /run/caiwu-violation-push.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:push-instant --quiet >/dev/null 2>&1
0 10 * * * root /usr/bin/flock -n /run/caiwu-violation-push.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:push-digest --quiet >/dev/null 2>&1
# 进销存月报导入后检查仓库简称映射;每日补偿检查避免导入与提醒步骤间断。
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
# 供应商管理每天北京时间 08:15 完整校准档案、合同、联系人与打款资料。
15 8 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-management --quiet >/dev/null 2>&1
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1

View File

@ -129,6 +129,7 @@
12. 得物完整账单使用聚胜算权威 XLSX,通过 `dewu-bills:import-authoritative` 写入 `dewu_settlement_bill_rows`。导入必须核验文件 SHA-256、账期、记录编码唯一性、行数、收入和支出控制数,并保留得物、退货退款订单、扣减其他费用明细三类渠道;页面 Repository 不得回退 `jiansun.dbo.jst_originalBillInfo.dewu_receiving`。详细流程见 `docs/得物完整账单取数方案留档.md`。
13. 聚水潭进销存首次全量按头表 `Id` 区间小批断点续传,头表保存全部仓库中 `io_date >= 2026-08-01` 的数据,不激活半份数据;日常增量以头表 `(modified, Id)` 作稳定游标并保留 48 小时时间重叠,由命中头单驱动整单明细替换。全量和增量都先写待发布代次,库存抓取完成后再把流水追平到库存抓取之后的固定源时间边界,三部分成功后才一次切换;运行中或失败时三方仓页面继续读取上一成功代次,全仓报表在首份完整全仓代次发布前明确提示同步中。页面只统计 `Confirmed` 的 12 类进销存流水,数量按上游 `qty * qty_type` 保留符号。库存同时保存上游 `source_modified_at` 和实际 `captured_at`,历史余额以每个“仓库 + SKU”的抓取时间为回推锚点;三方仓页面仍固定 `wms_co_id = 15045364` 并按“日期 + 商品”输出,全仓报表按“月份 + 仓库 + 商品”汇总。每天 `00:00` 执行增量同步,失败时继续展示上一成功代次。
14. 聚水潭商品操作日志按最多 7 天的固定时间窗和接口页码稳定断点同步,每页最多 50 条,首次全量从 `2000-01-01` 起扫描;只保留备注内容含“采购价”的记录,并从“采购价:旧值->新值”解析前后价格和差额。日常同步回看 48 小时,按接口记录字段生成稳定键幂等更新;接口失败时保留上一版镜像。页面不得把这些聚水潭记录与 `jiansun.dbo.pm_priceAdjustment` 的工作平台价格记录混为同一来源。
15. 进销存权威月报激活后,立即按“仓储方 + 仓库”核对仓库简称映射,每月生成一张系统化待办列出全部未映射组合及影响行数;同一月份重复执行只更新原任务,不重复创建。映射补齐后任务自动完成,若后续再次缺失则重新打开。生产每天 `10:15` 补偿检查一次,月报导入时也同步触发。
工作平台采购价格首次全量需在备份和负责人授权后单独执行:

View File

@ -2,6 +2,8 @@
namespace Tests\Feature\Console;
use App\Models\Business\InventoryWarehouseNameMapping;
use App\Models\Business\SystemizationTodo;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
@ -95,6 +97,79 @@ class InventoryReportAuthoritativeImportTest extends TestCase
->table('inventory_report_authoritative_rows')->count());
}
public function test_it_creates_and_reconciles_one_unmapped_warehouse_task_per_month(): void
{
$path = $this->workbook([
$this->headers(),
$this->row('2026-08-01', '仓储方甲', '主仓甲', 'SKU-A', 1, 1),
$this->row('2026-08-01', '仓储方乙', '主仓乙', 'SKU-B', 1, 1),
$this->row('2026-08-01', '仓储方乙', '主仓乙', 'SKU-C', 1, 1),
]);
$this->artisan('business-mirror:import-inventory-report-month', ['path' => $path])
->expectsOutputToContain('2 个仓储方/仓库组合未映射')
->assertSuccessful();
$sourceKey = 'inventory-warehouse-unmapped:2026-08';
$todo = SystemizationTodo::withTrashed()
->allCompanies()
->where('company_id', 1)
->where('source_key', $sourceKey)
->firstOrFail();
$this->assertSame(SystemizationTodo::STATUS_INCOMPLETE, $todo->status);
$this->assertStringContainsString('仓储方甲 / 主仓甲(1 行)', (string) $todo->progress);
$this->assertStringContainsString('仓储方乙 / 主仓乙(2 行)', (string) $todo->progress);
InventoryWarehouseNameMapping::allCompanies()->create([
'company_id' => 1,
'warehouse_provider' => '仓储方甲',
'warehouse' => '主仓甲',
'warehouse_short_name' => '仓储方甲简称',
]);
$this->artisan('inventory:sync-warehouse-mapping-alert', ['--month' => '2026-08'])
->expectsOutputToContain('1 个仓储方/仓库组合未映射')
->assertSuccessful();
$todo->refresh();
$this->assertSame(SystemizationTodo::STATUS_INCOMPLETE, $todo->status);
$this->assertStringNotContainsString('仓储方甲 / 主仓甲', (string) $todo->progress);
$this->assertStringContainsString('仓储方乙 / 主仓乙(2 行)', (string) $todo->progress);
$this->assertSame(1, SystemizationTodo::withTrashed()
->allCompanies()
->where('company_id', 1)
->where('source_key', $sourceKey)
->count());
InventoryWarehouseNameMapping::allCompanies()->create([
'company_id' => 1,
'warehouse_provider' => '仓储方乙',
'warehouse' => '主仓乙',
'warehouse_short_name' => '仓储方乙简称',
]);
$this->artisan('inventory:sync-warehouse-mapping-alert', ['--month' => '2026-08'])
->expectsOutputToContain('仓库简称映射完整')
->assertSuccessful();
$todo->refresh();
$this->assertSame(SystemizationTodo::STATUS_COMPLETED, $todo->status);
$this->assertNotNull($todo->completed_at);
$this->assertStringContainsString('自动完成提醒', (string) $todo->progress);
$this->assertSame(1, SystemizationTodo::withTrashed()
->allCompanies()
->where('company_id', 1)
->where('source_key', $sourceKey)
->count());
$this->artisan('inventory:sync-warehouse-mapping-alert', ['--month' => '2026-08'])
->assertSuccessful();
$this->assertSame(1, SystemizationTodo::withTrashed()
->allCompanies()
->where('company_id', 1)
->where('source_key', $sourceKey)
->count());
}
public function test_invalid_replacement_keeps_previous_generation(): void
{
$valid = app(InventoryReportAuthoritativeImporter::class)->import($this->workbook([

View File

@ -82,6 +82,11 @@ class BusinessMirrorScheduleTest extends TestCase
$contents,
$script,
);
$this->assertStringContainsString(
'15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet',
$contents,
$script,
);
$this->assertSame(1, substr_count($contents, 'business-mirror:sync-supplier-management --quiet'), $script);
$this->assertStringContainsString(
'business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet',