商品价格:自动生成月加权平均单价并输出对账简报 #476

Merged
chenxi merged 1 commits from feature/chenxi-monthly-weighted-average-automation into main 2026-10-23 16:21:16 +08:00
11 changed files with 1018 additions and 7 deletions

View File

@ -0,0 +1,261 @@
<?php
namespace App\Business;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* 汇总商品月加权平均单价结果,并将入库明细差异按原因分类。
*/
class ProductMonthlyWeightedAverageReporter
{
// 异常阈值未由业务另行指定:取至少 100 行,且不超过总行数的 0.1%。
private const ANOMALY_THRESHOLD_MIN_ROWS = 100;
private const ANOMALY_THRESHOLD_RATE = 0.001;
private const ROW_TABLE = 'product_monthly_weighted_average_rows';
private const STATE_TABLE = 'product_monthly_weighted_average_states';
private const INBOUND_TABLE = 'inventory_inbound_detail_rows';
private const INVENTORY_MONTH_TABLE = 'inventory_report_authoritative_months';
private const INVENTORY_ROW_TABLE = 'inventory_report_authoritative_rows';
/** @return array<string,mixed> */
public function build(string $connection, CarbonImmutable $month): array
{
$month = $month->startOfMonth();
$db = DB::connection($connection);
$baseQuery = static fn () => $db->table(self::ROW_TABLE)
->where('report_month', $month->toDateString());
$totals = $baseQuery()
->selectRaw('count(*) as total_rows')
->selectRaw('coalesce(sum(opening_quantity), 0) as opening_quantity')
->selectRaw('coalesce(sum(opening_amount), 0) as opening_amount')
->selectRaw('coalesce(sum(purchase_quantity), 0) as purchase_quantity')
->selectRaw('coalesce(sum(purchase_amount), 0) as purchase_amount')
->selectRaw('sum(case when weighted_average_unit_price is not null then 1 else 0 end) as weighted_price_rows')
->selectRaw('sum(case when weighted_average_unit_price is null then 1 else 0 end) as missing_weighted_rows')
->selectRaw('sum(case when pricing_status = ? then 1 else 0 end) as manual_review_rows', ['待人工核查'])
->first();
if ($totals === null || (int) $totals->total_rows === 0) {
return [
'status' => 'missing',
'report_month' => $month->toDateString(),
'message' => '该月份尚未生成商品月加权平均单价。',
'generated_at' => now()->toDateTimeString(),
];
}
$weightedKeys = [];
foreach ($baseQuery()->select('product_code', 'warehouse_short_name')->cursor() as $row) {
$weightedKeys[$this->key($row->product_code, $row->warehouse_short_name)] = true;
}
$inbound = [
'source_rows' => 0,
'source_quantity' => 0.0,
'source_amount' => 0.0,
'matched_rows' => 0,
'matched_quantity' => 0.0,
'matched_amount' => 0.0,
'unmatched_rows' => 0,
'unmatched_quantity' => 0.0,
'unmatched_amount' => 0.0,
'unmatched_groups' => [],
];
foreach ($db->table(self::INBOUND_TABLE)
->where('report_month', $month->toDateString())
->selectRaw('upper(barcode) as code, warehouse_short_name, count(*) as rows_count')
->selectRaw('coalesce(sum(quantity), 0) as quantity')
->selectRaw('coalesce(sum(coalesce(amount, 0) + coalesce(estimated_amount, 0)), 0) as amount')
->groupByRaw('upper(barcode), warehouse_short_name')
->cursor() as $row) {
$rows = (int) $row->rows_count;
$quantity = (float) $row->quantity;
$amount = (float) $row->amount;
$inbound['source_rows'] += $rows;
$inbound['source_quantity'] += $quantity;
$inbound['source_amount'] += $amount;
if (isset($weightedKeys[$this->key($row->code, $row->warehouse_short_name)])) {
$inbound['matched_rows'] += $rows;
$inbound['matched_quantity'] += $quantity;
$inbound['matched_amount'] += $amount;
continue;
}
$inbound['unmatched_rows'] += $rows;
$inbound['unmatched_quantity'] += $quantity;
$inbound['unmatched_amount'] += $amount;
$inbound['unmatched_groups'][] = [
'product_code' => trim((string) $row->code),
'warehouse_short_name' => trim((string) $row->warehouse_short_name),
'source_rows' => $rows,
'quantity' => $this->number($quantity),
'amount' => $this->number($amount),
'reason' => '入库明细未匹配到商品编码 + 仓库简称行',
];
}
usort(
$inbound['unmatched_groups'],
static fn (array $left, array $right): int =>
abs((float) $right['amount']) <=> abs((float) $left['amount']),
);
$inbound = $this->roundNestedNumbers($inbound);
$monthState = $db->table(self::INVENTORY_MONTH_TABLE)
->where('dataset_key', 'jiansun.inventory-report.authoritative-month')
->where('source_month', $month->toDateString())
->first();
$generation = $monthState?->active_generation;
$actualSourceRows = $generation === null
? 0
: $db->table(self::INVENTORY_ROW_TABLE)
->where('generation', (string) $generation)
->count();
$expectedSourceRows = (int) ($monthState?->source_row_count ?? 0);
$weightedAnomalyRows = $baseQuery()
->where(function ($query): void {
$query->whereNull('weighted_average_unit_price')
->orWhere('pricing_status', '待人工核查');
})
->count();
$reasons = [];
if ((int) $totals->missing_weighted_rows > 0) {
$reasons[] = [
'code' => 'missing_weighted_price',
'label' => '加权平均单价为空',
'rows' => (int) $totals->missing_weighted_rows,
];
}
if ((int) $totals->manual_review_rows > 0) {
$reasons[] = [
'code' => 'manual_review',
'label' => '待人工核查',
'rows' => (int) $totals->manual_review_rows,
];
}
if ((int) $inbound['unmatched_rows'] > 0) {
$reasons[] = [
'code' => 'inbound_without_inventory_dimension',
'label' => '入库明细未匹配到商品编码 + 仓库简称行',
'rows' => (int) $inbound['unmatched_rows'],
'groups' => count($inbound['unmatched_groups']),
];
}
if ($actualSourceRows !== $expectedSourceRows) {
$reasons[] = [
'code' => 'upstream_source_row_mismatch',
'label' => '上游进销存源表行数与已激活明细不一致',
'rows' => abs($actualSourceRows - $expectedSourceRows),
];
}
$anomalyRows = $weightedAnomalyRows + (int) $inbound['unmatched_rows'];
$threshold = max(
self::ANOMALY_THRESHOLD_MIN_ROWS,
(int) ceil((int) $totals->total_rows * self::ANOMALY_THRESHOLD_RATE),
);
return [
'status' => $reasons === [] ? 'computed' : 'review_required',
'report_month' => $month->toDateString(),
'totals' => [
'rows' => (int) $totals->total_rows,
'opening_quantity' => $this->number((float) $totals->opening_quantity),
'opening_amount' => $this->number((float) $totals->opening_amount),
'purchase_quantity' => $this->number((float) $totals->purchase_quantity),
'purchase_amount' => $this->number((float) $totals->purchase_amount),
'weighted_price_rows' => (int) $totals->weighted_price_rows,
'missing_weighted_rows' => (int) $totals->missing_weighted_rows,
'manual_review_rows' => (int) $totals->manual_review_rows,
],
'inbound' => $inbound,
'source' => [
'expected_rows' => $expectedSourceRows,
'active_rows' => $actualSourceRows,
'row_difference' => $actualSourceRows - $expectedSourceRows,
'status' => (string) ($monthState?->status ?? 'missing'),
'active_generation' => $generation,
'source_filename' => $monthState?->source_filename,
],
'anomalies' => [
'affected_rows' => $anomalyRows,
'threshold_rows' => $threshold,
'threshold_exceeded' => $anomalyRows > $threshold,
'reasons' => $reasons,
],
'state' => $db->table(self::STATE_TABLE)
->where('report_month', $month->toDateString())
->first(),
'generated_at' => now()->toDateTimeString(),
];
}
/** @param array<string,mixed> $report */
public function brief(array $report): string
{
if (($report['status'] ?? null) === 'missing') {
return (string) ($report['message'] ?? '商品月加权平均单价尚未生成');
}
$totals = $report['totals'] ?? [];
$inbound = $report['inbound'] ?? [];
$anomalies = $report['anomalies'] ?? [];
$reasonLabels = array_map(
static fn (array $reason): string =>
(string) ($reason['label'] ?? $reason['code'] ?? '未知异常'),
$anomalies['reasons'] ?? [],
);
return sprintf(
'%s:总行数 %s;期初 %s 件 / %s;入库 %s 件 / %s;加权单价 %s 行;异常 %s 行%s',
substr((string) ($report['report_month'] ?? ''), 0, 7),
number_format((int) ($totals['rows'] ?? 0)),
number_format((float) ($totals['opening_quantity'] ?? 0), 2),
number_format((float) ($totals['opening_amount'] ?? 0), 2),
number_format((float) ($inbound['matched_quantity'] ?? 0), 2),
number_format((float) ($inbound['matched_amount'] ?? 0), 2),
number_format((int) ($totals['weighted_price_rows'] ?? 0)),
number_format((int) ($anomalies['affected_rows'] ?? 0)),
$reasonLabels === [] ? '' : '(' . implode('、', $reasonLabels) . ')',
);
}
private function key(mixed $productCode, mixed $warehouseShortName): string
{
return mb_strtoupper(trim((string) $productCode))
. "\0"
. trim((string) $warehouseShortName);
}
private function number(float $value): float
{
return round($value, 6);
}
/**
* @param array<string,mixed> $value
* @return array<string,mixed>
*/
private function roundNestedNumbers(array $value): array
{
foreach ($value as $key => $item) {
if (is_array($item)) {
$value[$key] = $this->roundNestedNumbers($item);
} elseif (is_float($item)) {
$value[$key] = round($item, 6);
}
}
return $value;
}
}

View File

@ -0,0 +1,246 @@
<?php
namespace App\Console\Commands;
use App\Business\ProductMonthlyWeightedAverageReporter;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
/**
* 检查上游完整性后,自动生成尚未计算的最新月份商品月加权平均单价。
*/
class AutoComputeProductMonthlyWeightedAverage extends Command
{
protected $signature = 'product:monthly-weighted-average:auto
{--month= : 指定月份;默认取最新已成功的进销存月份}
{--result-json= : 将执行结果写入指定 JSON 文件}';
protected $description = '上游完整后自动计算商品月加权平均单价,并保护已计算历史月份';
public function handle(ProductMonthlyWeightedAverageReporter $reporter): int
{
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$month = $this->targetMonth($connection);
if ($month === null) {
return $this->finish('blocked', null, [
'message' => '未找到已成功导入的进销存月份。',
]);
}
$lock = Cache::lock('product-monthly-weighted-average-auto:' . $month->format('Y-m'), 7200);
if (! $lock->get()) {
return $this->finish('blocked', $month, [
'message' => '同月自动计算任务正在执行。',
]);
}
try {
$state = DB::connection($connection)->table('product_monthly_weighted_average_states')
->where('report_month', $month->toDateString())
->first();
if (($state?->status ?? null) === 'computed') {
$report = $reporter->build($connection, $month);
$report['calculation_status'] = $report['status'];
$report['status'] = 'already_computed';
return $this->finish('already_computed', $month, $report, $reporter);
}
$checks = $this->checks($connection, $month);
if (in_array(false, array_column($checks, 'passed'), true)) {
DB::connection($connection)->table('product_monthly_weighted_average_states')->updateOrInsert(
['report_month' => $month->toDateString()],
[
'status' => 'blocked',
'last_error' => '上游数据未通过完整性检查',
'updated_at' => now(),
'created_at' => now(),
],
);
return $this->finish('blocked', $month, [
'message' => '上游数据未更新或不完整,未执行计算。',
'checks' => $checks,
]);
}
$baseExit = $this->call('product:monthly-weighted-average:base', [
'month' => $month->format('Y-m'),
'--from-previous' => true,
// 自动任务只会在尚未 computed 的月份走到这里,可安全清理失败重试留下
// 的同月基表;已 computed 的历史月份在前面的门禁直接跳过。
'--force' => true,
]);
if ($baseExit !== self::SUCCESS) {
return $this->finish('failed', $month, [
'message' => '生成期初基数失败。',
]);
}
$computeExit = $this->call('product:monthly-weighted-average:compute', [
'month' => $month->format('Y-m'),
]);
if ($computeExit !== self::SUCCESS) {
return $this->finish('failed', $month, [
'message' => '加权平均单价计算失败。',
]);
}
$report = $reporter->build($connection, $month);
$report['checks'] = $checks;
return $this->finish(
($report['status'] ?? null) === 'review_required' ? 'review_required' : 'success',
$month,
$report,
$reporter,
);
} finally {
$lock->release();
}
}
private function targetMonth(string $connection): ?CarbonImmutable
{
$requested = trim((string) $this->option('month'));
if ($requested !== '') {
return CarbonImmutable::parse($requested)->startOfMonth();
}
$latest = DB::connection($connection)->table('inventory_report_authoritative_months')
->where('dataset_key', 'jiansun.inventory-report.authoritative-month')
->where('status', 'succeeded')
->whereNotNull('active_generation')
->orderByDesc('source_month')
->value('source_month');
return $latest === null ? null : CarbonImmutable::parse((string) $latest)->startOfMonth();
}
/** @return list<array{name:string,passed:bool,actual:mixed,expected:mixed}> */
private function checks(string $connection, CarbonImmutable $month): array
{
$db = DB::connection($connection);
$monthState = $db->table('inventory_report_authoritative_months')
->where('dataset_key', 'jiansun.inventory-report.authoritative-month')
->where('source_month', $month->toDateString())
->first();
$generation = $monthState?->active_generation;
$activeRows = $generation === null
? 0
: $db->table('inventory_report_authoritative_rows')
->where('generation', (string) $generation)
->count();
$expectedRows = (int) ($monthState?->source_row_count ?? 0);
$previous = $month->subMonthNoOverflow();
$previousState = $db->table('product_monthly_weighted_average_states')
->where('report_month', $previous->toDateString())
->value('status');
$previousRows = $db->table('product_monthly_weighted_average_rows')
->where('report_month', $previous->toDateString())
->count();
$inboundRows = $db->table('inventory_inbound_detail_rows')
->where('report_month', $month->toDateString())
->count();
$inboundMissingDimensions = $db->table('inventory_inbound_detail_rows')
->where('report_month', $month->toDateString())
->where(function ($query): void {
$query->whereNull('barcode')->orWhere('barcode', '')
->orWhereNull('warehouse_short_name')->orWhere('warehouse_short_name', '');
})
->count();
$inboundMissingAmounts = $db->table('inventory_inbound_detail_rows')
->where('report_month', $month->toDateString())
->whereNull('amount')
->whereNull('estimated_amount')
->count();
$productCatalogRows = $db->table('ops_jst_sku')->whereNotNull('sku_id')->count();
return [
[
'name' => '进销存月份状态成功',
'passed' => ($monthState?->status ?? null) === 'succeeded',
'actual' => $monthState?->status,
'expected' => 'succeeded',
],
[
'name' => '进销存激活明细行数完整',
'passed' => $expectedRows > 0 && $activeRows === $expectedRows,
'actual' => $activeRows,
'expected' => $expectedRows,
],
[
'name' => '上月加权平均结果已完成',
'passed' => $previousState === 'computed' && $previousRows > 0,
'actual' => ['status' => $previousState, 'rows' => $previousRows],
'expected' => ['status' => 'computed', 'rows' => '> 0'],
],
[
'name' => '入库明细已更新',
'passed' => $inboundRows > 0,
'actual' => $inboundRows,
'expected' => '> 0',
],
[
'name' => '入库商品编码与仓库简称无缺失',
'passed' => $inboundMissingDimensions === 0,
'actual' => $inboundMissingDimensions,
'expected' => 0,
],
[
'name' => '入库金额至少取金额或预估金额',
'passed' => $inboundMissingAmounts === 0,
'actual' => $inboundMissingAmounts,
'expected' => 0,
],
[
'name' => '普通商品资料已更新',
'passed' => $productCatalogRows > 0,
'actual' => $productCatalogRows,
'expected' => '> 0',
],
];
}
/**
* @param array<string,mixed> $payload
*/
private function finish(
string $status,
?CarbonImmutable $month,
array $payload,
?ProductMonthlyWeightedAverageReporter $reporter = null,
): int {
$result = ['status' => $status] + $payload;
if (! isset($result['report_month']) && $month !== null) {
$result['report_month'] = $month->toDateString();
}
$path = trim((string) $this->option('result-json'));
if ($path !== '') {
File::ensureDirectoryExists(dirname($path));
File::put(
$path,
json_encode(
$result,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT,
) . PHP_EOL,
);
}
if ($reporter !== null && isset($result['totals'])) {
$this->line($reporter->brief($result));
} elseif (isset($result['message'])) {
$this->error((string) $result['message']);
}
return in_array($status, ['blocked', 'failed'], true)
? self::FAILURE
: self::SUCCESS;
}
}

View File

@ -2,26 +2,45 @@
namespace App\Console\Commands;
use App\Business\ProductMonthlyWeightedAverageReporter;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
/**
* 按取数逻辑计算某个月的更改价格、定价状态、采购单价、期初金额、入库金额和加权平均单价。
*/
class ComputeProductMonthlyWeightedAverage extends Command
{
protected $signature = 'product:monthly-weighted-average:compute {month : 报表月份,例如 2026-07}';
protected $signature = 'product:monthly-weighted-average:compute
{month : 报表月份,例如 2026-07}
{--force : 覆盖已经计算完成的同月结果}
{--result-json= : 将结果简报写入指定 JSON 文件}';
protected $description = '按取数逻辑计算商品月加权平均单价';
public function handle(): int
public function handle(ProductMonthlyWeightedAverageReporter $reporter): int
{
$month = CarbonImmutable::parse($this->argument('month'))->startOfMonth();
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$table = 'product_monthly_weighted_average_rows';
$deadline = $month->addMonthNoOverflow()->day(2)->startOfDay();
$stateStatus = DB::connection($connection)
->table('product_monthly_weighted_average_states')
->where('report_month', $month->toDateString())
->value('status');
$computedRows = DB::connection($connection)->table($table)
->where('report_month', $month->toDateString())
->whereNotNull('computed_at')
->count();
if (! $this->option('force') && ($stateStatus === 'computed' || $computedRows > 0)) {
$this->error($month->format('Y-m') . ' 已经计算完成,历史月份不自动覆盖;如需人工纠正请显式使用 --force。');
return self::FAILURE;
}
$query = DB::connection($connection)->table($table)->where('report_month', $month->toDateString());
$codes = (clone $query)->distinct()->pluck('product_code')->map(fn ($code) => trim((string) $code))->unique()->values()->all();
$this->info('待计算 SKU:' . count($codes));
@ -87,7 +106,21 @@ class ComputeProductMonthlyWeightedAverage extends Command
['status' => 'computed', 'computed_rows' => $computed, 'last_computed_at' => $now, 'updated_at' => $now, 'created_at' => $now],
);
$report = $reporter->build($connection, $month);
$json = json_encode($report, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if (is_string($json)) {
$resultPath = trim((string) $this->option('result-json'));
if ($resultPath !== '') {
File::ensureDirectoryExists(dirname($resultPath));
File::put($resultPath, $json . PHP_EOL);
}
}
$this->info($month->format('Y-m') . " 计算完成:{$computed} 行");
$this->line($reporter->brief($report));
if (($report['status'] ?? null) === 'review_required') {
$this->warn('存在待复核差异;结果已生成,但不会视为完全无异常。');
}
return self::SUCCESS;
}

View File

@ -21,7 +21,8 @@ class ImportProductMonthlyWeightedAverageBase extends Command
protected $signature = 'product:monthly-weighted-average:base
{month : 报表月份,例如 2026-07}
{--file= : 期初基数 Excel(表1),首月使用}
{--from-previous : 用上月的加权平均单价作为本月原始价格}';
{--from-previous : 用上月的加权平均单价作为本月原始价格}
{--force : 覆盖已经存在的同月基数}';
protected $description = '导入/生成商品月加权平均单价的期初基数';
@ -32,6 +33,18 @@ class ImportProductMonthlyWeightedAverageBase extends Command
$rowsTable = 'product_monthly_weighted_average_rows';
$now = now();
$existingRows = DB::connection($connection)->table($rowsTable)
->where('report_month', $month->toDateString())
->count();
$existingState = DB::connection($connection)->table('product_monthly_weighted_average_states')
->where('report_month', $month->toDateString())
->value('status');
if (! $this->option('force') && ($existingRows > 0 || $existingState !== null)) {
$this->error($month->format('Y-m') . ' 已存在基数或计算状态,不自动覆盖;如需人工纠正请显式使用 --force。');
return self::FAILURE;
}
$inventory = $this->inventoryAggregate($connection, $month);
$jiangxiPurchase = $this->jiangxiDeliveryPurchase($connection, $month);
$nanchangOpening = $this->nanchangOpeningQuantity($connection, $month);
@ -198,9 +211,13 @@ class ImportProductMonthlyWeightedAverageBase extends Command
throw new \RuntimeException($month->format('Y-m') . ' 的进销存总表尚未导入。');
}
$mappingTable = (new InventoryWarehouseNameMapping)->getConnection()->getDatabaseName()
. '.' . DB::connection((new InventoryWarehouseNameMapping)->getConnectionName())->getTablePrefix()
. (new InventoryWarehouseNameMapping)->getTable();
$mappingModel = new InventoryWarehouseNameMapping();
$mappingConnection = DB::connection($mappingModel->getConnectionName());
$mappingTable = $mappingConnection->getDriverName() === 'sqlite'
? $mappingModel->getTable()
: $mappingModel->getConnection()->getDatabaseName()
. '.' . $mappingConnection->getTablePrefix()
. $mappingModel->getTable();
$sql = "select m.warehouse_short_name as short_name, r.product_code as product_code,
sum(case when r.warehouse like '%主仓%' then r.opening_quantity else 0 end) as opening_quantity,

View File

@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\Business\ProductMonthlyWeightedAverageReporter;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class ReportProductMonthlyWeightedAverage extends Command
{
protected $signature = 'product:monthly-weighted-average:report
{month : 报表月份,例如 2026-09}
{--result-json= : 将结果写入指定 JSON 文件}';
protected $description = '输出商品月加权平均单价结果简报与差异分类';
public function handle(ProductMonthlyWeightedAverageReporter $reporter): int
{
$month = CarbonImmutable::parse($this->argument('month'))->startOfMonth();
$report = $reporter->build(
(string) config('upstream_mirrors.connection', 'business_mirror'),
$month,
);
$path = trim((string) $this->option('result-json'));
if ($path !== '') {
File::ensureDirectoryExists(dirname($path));
File::put(
$path,
json_encode(
$report,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT,
) . PHP_EOL,
);
}
$this->line($reporter->brief($report));
if (($report['status'] ?? null) === 'review_required') {
$this->warn('存在待人工复核差异,完整清单已写入结果 JSON。');
}
return ($report['status'] ?? null) === 'missing'
? self::FAILURE
: self::SUCCESS;
}
}

View File

@ -213,6 +213,8 @@ CRON_TZ=Asia/Shanghai
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。
3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1
0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-purchase-prices --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1
# 商品月加权平均单价:每天检查最新上游月份,完整且尚未计算时自动生成;历史 computed 月份跳过。
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh product:monthly-weighted-average:auto >/dev/null 2>&1
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1
# 店铺违规预警推送:P0/P1 每天 09:00 起每 5 分钟检查;P2 每日 10:00 汇总(未配置 Webhook 时自动跳过)。

View File

@ -217,6 +217,8 @@ CRON_TZ=Asia/Shanghai
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。
3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1
0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-product-purchase-prices --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1
# 商品月加权平均单价:每天检查最新上游月份,完整且尚未计算时自动生成;历史 computed 月份跳过。
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh product:monthly-weighted-average:auto >/dev/null 2>&1
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1
# 店铺违规预警推送:P0/P1 每天 09:00 起每 5 分钟检查;P2 每日 10:00 汇总(未配置 Webhook 时自动跳过)。

View File

@ -8,7 +8,7 @@ CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
*:import|*:import-*|*:import:*|product:monthly-weighted-average:base) is_import=1 ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|account-bills:exports:run|finance-ledger:recalculate) ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report) ;;
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;
esac
cd "$REMOTE_DIR"

View File

@ -0,0 +1,125 @@
#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
RUNTIME_DIR="${PRODUCT_WEIGHTED_AVERAGE_RUNTIME_DIR:-$REPO_ROOT/runtime/private/product-monthly-weighted-average-scheduler}"
CONTAINER="${PRODUCT_WEIGHTED_AVERAGE_CONTAINER:-jiangling_app}"
SYSTEM_PYTHON="${PRODUCT_WEIGHTED_AVERAGE_SYSTEM_PYTHON:-/usr/bin/python3}"
month=''
notify=1
while [ "$#" -gt 0 ]; do
case "$1" in
--month)
month="$2"
shift
;;
--no-notify)
notify=0
;;
*)
printf '未知参数:%s\n' "$1" >&2
exit 2
;;
esac
shift
done
timestamp="$(date '+%Y%m%dT%H%M%S')"
run_dir="$RUNTIME_DIR/runs/$timestamp"
history_dir="$RUNTIME_DIR/history"
mkdir -p "$run_dir" "$history_dir"
container_result="/tmp/product-weighted-average-$timestamp.json"
cleanup() {
docker exec "$CONTAINER" unlink "$container_result" >/dev/null 2>&1 || true
}
trap cleanup EXIT
notify_user() {
local title="$1"
local message="$2"
if [ "$notify" -eq 1 ] && command -v osascript >/dev/null 2>&1; then
osascript \
-e 'on run argv' \
-e 'display notification (item 2 of argv) with title (item 1 of argv)' \
-e 'end run' \
"$title" "$message" >/dev/null 2>&1 || true
fi
}
record_failure() {
local message="$1"
"$SYSTEM_PYTHON" - "$message" "$run_dir/result.json" "${month:-latest}" <<'PY'
import json
import sys
from pathlib import Path
message, output, month = sys.argv[1:]
result = {
"status": "failed",
"report_month": "" if month == "latest" else month + "-01",
"message": message,
}
Path(output).write_text(
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
PY
cp "$run_dir/result.json" "$RUNTIME_DIR/last-run.json"
cp "$run_dir/result.json" "$history_dir/$timestamp.json"
notify_user '商品月加权平均单价失败' "$message"
printf '%s\n' "$message"
exit 1
}
if ! command -v docker >/dev/null 2>&1; then
record_failure '找不到 docker 命令,无法执行商品月加权平均单价。'
fi
args=(php artisan product:monthly-weighted-average:auto)
if [ -n "$month" ]; then
args+=("--month=$month")
fi
args+=("--result-json=$container_result")
set +e
docker exec -u www-data -e HOME=/tmp "$CONTAINER" "${args[@]}" \
> "$run_dir/run.log" 2>&1
auto_exit=$?
set -e
if ! docker cp "$CONTAINER:$container_result" "$run_dir/result.json" >> "$run_dir/run.log" 2>&1; then
tail -20 "$run_dir/run.log" >&2 || true
record_failure "自动计算未生成结果文件,退出码:$auto_exit"
fi
"$SYSTEM_PYTHON" "$REPO_ROOT/scripts/summarize_product_weighted_average_result.py" \
--input "$run_dir/result.json" \
--result-json "$RUNTIME_DIR/last-run.json" > "$run_dir/brief.txt"
cp "$RUNTIME_DIR/last-run.json" "$history_dir/$timestamp.json"
brief="$(cat "$run_dir/brief.txt")"
printf '%s\n' "$brief"
result_status="$("$SYSTEM_PYTHON" - "$run_dir/result.json" <<'PY'
import json
import sys
from pathlib import Path
print(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")).get("status", "failed"))
PY
)"
if [ "$auto_exit" -ne 0 ] || [ "$result_status" = 'blocked' ] || [ "$result_status" = 'failed' ]; then
notify_user '商品月加权平均单价未完成' "$brief"
exit 1
fi
if [ "$result_status" = 'review_required' ]; then
notify_user '商品月加权平均单价需复核' "$brief"
exit 0
fi
notify_user '商品月加权平均单价完成' "$brief"
exit 0

View File

@ -0,0 +1,69 @@
#!/usr/bin/env python3
import argparse
import json
from datetime import datetime
from pathlib import Path
def money(value: object) -> str:
return f"{float(value or 0):,.2f}"
def brief(result: dict) -> str:
status = str(result.get("status") or "failed")
month = str(result.get("report_month") or "")[:7]
if status in {"blocked", "failed"}:
return f"{month or '本月'} 未执行:{result.get('message') or '上游数据不完整'}"
totals = result.get("totals") or {}
inbound = result.get("inbound") or {}
anomalies = result.get("anomalies") or {}
reasons = "、".join(
str(item.get("label") or item.get("code") or "未知异常")
for item in anomalies.get("reasons") or []
)
suffix = f";待复核:{reasons}" if reasons else ""
if status == "already_computed":
prefix = "已完成,本次跳过重算"
elif status == "review_required":
prefix = "计算完成,需人工复核"
else:
prefix = "计算完成"
return (
f"{month} {prefix}:总行数 {int(totals.get('rows') or 0):,};"
f"期初 {float(totals.get('opening_quantity') or 0):,.2f} 件 / "
f"{money(totals.get('opening_amount'))};"
f"入库 {float(inbound.get('matched_quantity') or 0):,.2f} 件 / "
f"{money(inbound.get('matched_amount'))};"
f"加权单价 {int(totals.get('weighted_price_rows') or 0):,} 行;"
f"异常 {int(anomalies.get('affected_rows') or 0):,} 行{suffix}"
)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True)
parser.add_argument("--result-json", required=True)
args = parser.parse_args()
result = json.loads(Path(args.input).read_text(encoding="utf-8"))
summary = brief(result)
payload = {
"finished_at": datetime.now().astimezone().isoformat(timespec="seconds"),
"brief": summary,
"result": result,
}
output = Path(args.result_json)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(summary)
return 0 if result.get("status") not in {"blocked", "failed", "missing"} else 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,209 @@
<?php
namespace Tests\Feature\Console;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Tests\TestCase;
class ProductMonthlyWeightedAverageAutomationTest extends TestCase
{
private string $connection = 'business_mirror';
/** @var list<string> */
private array $temporaryTables = [];
protected function setUp(): void
{
parent::setUp();
$schema = Schema::connection($this->connection);
$this->createTableIfMissing('ops_jst_sku', function (Blueprint $table): void {
$table->string('sku_id');
$table->decimal('cost_price', 20, 8)->nullable();
});
$this->createTableIfMissing('js_pm_price_adjustment', function (Blueprint $table): void {
$table->string('skuCode')->nullable();
$table->decimal('purchasePrice', 20, 8)->nullable();
$table->dateTime('effectTime')->nullable();
});
$this->createTableIfMissing('js_pm_price_adjustment_log', function (Blueprint $table): void {
$table->string('skucode')->nullable();
$table->decimal('afterPrice', 20, 8)->nullable();
$table->decimal('originalPrice', 20, 8)->nullable();
$table->dateTime('effectStartTime')->nullable();
$table->dateTime('createTime')->nullable();
});
$this->createTableIfMissing('jushuitan_cost_price_history_rows', function (Blueprint $table): void {
$table->string('sku_id')->nullable();
$table->string('sku_id_normalized')->nullable();
$table->dateTime('operated_at')->nullable();
});
DB::connection($this->connection)->table('ops_jst_sku')->insert([
'sku_id' => 'SKU-1',
'cost_price' => 9,
]);
}
protected function tearDown(): void
{
foreach (array_reverse($this->temporaryTables) as $table) {
Schema::connection($this->connection)->dropIfExists($table);
}
parent::tearDown();
}
public function test_compute_outputs_reconciliation_freeze_and_auto_skip(): void
{
$this->seedSourceMonth();
DB::connection($this->connection)->table('product_monthly_weighted_average_states')->insert([
'report_month' => '2026-09-01',
'status' => 'base_imported',
'created_at' => now(),
'updated_at' => now(),
]);
DB::connection($this->connection)->table('product_monthly_weighted_average_rows')->insert([
'report_month' => '2026-09-01',
'row_key' => str_repeat('a', 40),
'barcode_warehouse' => 'SKU-1测试仓',
'warehouse_short_name' => '测试仓',
'product_code' => 'SKU-1',
'opening_quantity' => 10,
'opening_unit_price' => 5,
'previous_pricing_status' => '已定价',
'base_source' => 'base',
'imported_at' => now(),
]);
DB::connection($this->connection)->table('inventory_inbound_detail_rows')->insert([
'report_month' => '2026-09-01',
'row_key' => hash('sha256', 'inbound-1'),
'barcode' => 'sku-1',
'warehouse_short_name' => '测试仓',
'quantity' => 2,
'amount' => 10,
'estimated_amount' => 2,
'imported_at' => now(),
]);
$resultPath = tempnam(sys_get_temp_dir(), 'weighted-result-') . '.json';
try {
$this->artisan('product:monthly-weighted-average:compute', [
'month' => '2026-09',
'--result-json' => $resultPath,
])->expectsOutputToContain('总行数 1')->assertSuccessful();
$row = DB::connection($this->connection)->table('product_monthly_weighted_average_rows')
->where('report_month', '2026-09-01')
->first();
$this->assertEquals(5.1667, (float) $row->weighted_average_unit_price);
$this->assertEquals(50, (float) $row->opening_amount);
$this->assertEquals(12, (float) $row->purchase_amount);
$result = json_decode((string) file_get_contents($resultPath), true);
$this->assertSame('computed', $result['status']);
$this->assertSame(1, $result['totals']['rows']);
$this->assertSame(1, $result['totals']['weighted_price_rows']);
$this->assertSame(1, $result['inbound']['matched_rows']);
$this->assertSame(0, $result['source']['row_difference']);
$this->assertSame(0, $result['anomalies']['affected_rows']);
$this->artisan('product:monthly-weighted-average:compute', [
'month' => '2026-09',
])->expectsOutputToContain('历史月份不自动覆盖')->assertFailed();
$autoPath = tempnam(sys_get_temp_dir(), 'weighted-auto-') . '.json';
$this->artisan('product:monthly-weighted-average:auto', [
'--month' => '2026-09',
'--result-json' => $autoPath,
])->assertSuccessful();
$auto = json_decode((string) file_get_contents($autoPath), true);
$this->assertSame('already_computed', $auto['status']);
$this->assertSame(1, $auto['totals']['rows']);
@unlink($autoPath);
} finally {
@unlink($resultPath);
}
}
public function test_auto_blocks_when_inbound_data_is_missing(): void
{
$this->seedSourceMonth();
DB::connection($this->connection)->table('product_monthly_weighted_average_states')->insert([
['report_month' => '2026-08-01', 'status' => 'computed', 'created_at' => now(), 'updated_at' => now()],
['report_month' => '2026-09-01', 'status' => 'base_imported', 'created_at' => now(), 'updated_at' => now()],
]);
DB::connection($this->connection)->table('product_monthly_weighted_average_rows')->insert([
'report_month' => '2026-08-01',
'row_key' => str_repeat('b', 40),
'barcode_warehouse' => 'SKU-1测试仓',
'warehouse_short_name' => '测试仓',
'product_code' => 'SKU-1',
'opening_quantity' => 1,
'weighted_average_unit_price' => 5,
'pricing_status' => '已定价',
'base_source' => 'base',
'imported_at' => now(),
'computed_at' => now(),
]);
$path = tempnam(sys_get_temp_dir(), 'weighted-blocked-') . '.json';
try {
$this->artisan('product:monthly-weighted-average:auto', [
'--month' => '2026-09',
'--result-json' => $path,
])->expectsOutputToContain('上游数据未更新或不完整')->assertFailed();
$result = json_decode((string) file_get_contents($path), true);
$this->assertSame('blocked', $result['status']);
$check = collect($result['checks'])->firstWhere('name', '入库明细已更新');
$this->assertFalse($check['passed']);
$this->assertSame(
'blocked',
DB::connection($this->connection)->table('product_monthly_weighted_average_states')
->where('report_month', '2026-09-01')->value('status'),
);
} finally {
@unlink($path);
}
}
private function seedSourceMonth(): void
{
$generation = (string) Str::uuid();
DB::connection($this->connection)->table('inventory_report_authoritative_months')->insert([
'dataset_key' => 'jiansun.inventory-report.authoritative-month',
'source_month' => '2026-09-01',
'status' => 'succeeded',
'active_generation' => $generation,
'source_filename' => 'inventory-2026-09.xlsx',
'source_row_count' => 1,
'last_succeeded_at' => now(),
'updated_at' => now(),
]);
DB::connection($this->connection)->table('inventory_report_authoritative_rows')->insert([
'generation' => $generation,
'row_key' => hash('sha256', 'source-row-1'),
'report_month' => '2026-09-01',
'owner' => '测试货主',
'warehouse_provider' => '测试仓',
'warehouse' => '测试仓主仓',
'product_code' => 'SKU-1',
'opening_quantity' => 10,
'closing_quantity' => 10,
'imported_at' => now(),
]);
}
private function createTableIfMissing(string $table, \Closure $definition): void
{
if (Schema::connection($this->connection)->hasTable($table)) {
return;
}
Schema::connection($this->connection)->create($table, $definition);
$this->temporaryTables[] = $table;
}
}