feat: 每月2日自动生成未定价转本月定价

Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
This commit is contained in:
苏木 2026-12-02 18:57:47 +08:00 committed by sumu
parent 05f8cec37a
commit ae52465900
8 changed files with 389 additions and 8 deletions

View File

@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\PayablesUnpricedCycleProcessor;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use Throwable;
class RunPayablesUnpricedCycle extends Command
{
protected $signature = 'payables:unpriced-cycle:auto
{--period= : 货款账期,格式 YYYY-MM,默认上月}
{--cutoff= : 工作平台价格截止日,格式 YYYY-MM-DD,默认为本月1日}
{--company=1 : 公司 ID}
{--user= : 操作用户 ID}';
protected $description = '每月2日使用工作平台价格镜像自动生成上月未定价转本月定价数据';
public function handle(
PayablesUnpricedCycleProcessor $processor,
SupplierPayableOverrideStore $store,
): int {
$timezone = (string) config('app.platform_timezone', 'Asia/Shanghai');
$now = now($timezone);
$period = trim((string) $this->option('period')) ?: $now->copy()->subMonthNoOverflow()->format('Y-m');
$cutoff = trim((string) $this->option('cutoff')) ?: $now->copy()->startOfMonth()->toDateString();
$companyId = max(1, (int) $this->option('company'));
$userId = $this->option('user') !== null ? (int) $this->option('user') : null;
try {
$completed = $store->findLatestRow(
PayablesUnpricedCycleProcessor::RUN_DATASET,
['summary_month' => $period, 'status' => 'completed'],
$companyId,
);
if ($completed !== null) {
$this->info("账期 {$period} 已完成,本次自动任务跳过。");
return self::SUCCESS;
}
$result = $processor->processFromPlatformPrices(
$period,
$cutoff,
$companyId,
$userId,
);
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
return self::SUCCESS;
} catch (Throwable $exception) {
report($exception);
$this->error('自动定价失败:' . $exception->getMessage());
return self::FAILURE;
}
}
}

View File

@ -213,6 +213,8 @@ CRON_TZ=Asia/Shanghai
# 供应商货款预估:每天 07:00 日结前一天;每月 1 日 07:10 重跑上月并记录差异。
0 7 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1
10 7 1 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --monthly --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1
# 之前月未定价-本月定价:每月 2 日使用工作平台价格镜像自动生成上月数据;后两次仅在未完成时重试。
30 8,12,16 2 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh payables:unpriced-cycle:auto --company=1 --quiet >> /opt/caiwuxitong/runtime/sync-logs/payables-unpriced-cycle.log 2>&1
0 0 * * * 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:warm-report-caches --quiet' >/dev/null 2>&1
0 0 * * * 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-jushuitan-cost-price-history --quiet >/dev/null 2>&1
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。

View File

@ -217,6 +217,8 @@ CRON_TZ=Asia/Shanghai
# 供应商货款预估:每天 07:00 日结前一天;每月 1 日 07:10 重跑上月并记录差异。
0 7 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1
10 7 1 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --monthly --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1
# 之前月未定价-本月定价:每月 2 日使用工作平台价格镜像自动生成上月数据;后两次仅在未完成时重试。
30 8,12,16 2 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh payables:unpriced-cycle:auto --company=1 --quiet >> /opt/caiwuxitong/runtime/sync-logs/payables-unpriced-cycle.log 2>&1
0 0 * * * 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:warm-report-caches --quiet' >/dev/null 2>&1
0 0 * * * 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-jushuitan-cost-price-history --quiet >/dev/null 2>&1
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。

View File

@ -53,6 +53,7 @@
"planting-details:sync-work-orders",
"planting-details:import",
"payables:unpriced-cycle",
"payables:unpriced-cycle:auto",
"payables:final-import",
"product-catalog:import-authoritative-export",
"product:monthly-weighted-average:base",

View File

@ -9,7 +9,7 @@ CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
planting-reimbursement:auto-confirm) is_import=1 ;;
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;

View File

@ -3,8 +3,12 @@
namespace Modules\EcommerceFinance\Services;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Repositories\SupplierPayableForecastRepository;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use RuntimeException;
use Throwable;
/**
@ -41,16 +45,74 @@ class PayablesUnpricedCycleProcessor
int $companyId,
?int $userId = null,
): array {
if (preg_match('/^\d{4}-\d{2}$/', $period) !== 1) {
throw ValidationException::withMessages(['period' => '账期必须为 YYYY-MM 格式。']);
}
$this->assertInputs($period, $cutoff);
if (! is_file($priceFile)) {
throw ValidationException::withMessages(['price_file' => '价格文件不存在。']);
}
$priceMap = $this->readPriceMap($priceFile, $cutoff);
return $this->processWithPriceMap(
$priceMap,
$period,
$cutoff,
$companyId,
$userId,
[
'price_file' => basename($priceFile),
'price_source' => 'file',
],
);
}
/**
* 使用已经同步到共享业务镜像的工作平台定价历史。
*
* @return array<string,mixed>
*/
public function processFromPlatformPrices(
string $period,
string $cutoff,
int $companyId,
?int $userId = null,
): array {
$this->assertInputs($period, $cutoff);
return $this->processWithPriceMap(
$this->readPlatformPriceMap($cutoff),
$period,
$cutoff,
$companyId,
$userId,
[
'price_file' => SupplierPayableForecastRepository::PRICE_TABLE,
'price_source' => 'platform_mirror',
],
);
}
private function assertInputs(string $period, string $cutoff): void
{
if (preg_match('/^\d{4}-\d{2}$/', $period) !== 1) {
throw ValidationException::withMessages(['period' => '账期必须为 YYYY-MM 格式。']);
}
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $cutoff) !== 1) {
throw ValidationException::withMessages(['cutoff' => '价格截止日必须为 YYYY-MM-DD 格式。']);
}
}
/**
* @param array<string,array{price:float,start:string}> $priceMap
* @param array{price_file:string,price_source:string} $priceMetadata
* @return array<string,mixed>
*/
private function processWithPriceMap(
array $priceMap,
string $period,
string $cutoff,
int $companyId,
?int $userId,
array $priceMetadata,
): array {
$completedRun = $this->store->findLatestRow(self::RUN_DATASET, [
'summary_month' => $period,
'status' => 'completed',
@ -61,9 +123,12 @@ class PayablesUnpricedCycleProcessor
]);
}
$priceMap = $this->readPriceMap($priceFile, $cutoff);
if ($priceMap === []) {
throw ValidationException::withMessages(['price_file' => '价格文件中没有可用定价记录。']);
throw ValidationException::withMessages([
'price_file' => $priceMetadata['price_source'] === 'platform_mirror'
? '工作平台价格镜像中没有可用定价记录。'
: '价格文件中没有可用定价记录。',
]);
}
$deliveryHistory = $this->store->listRows(self::DELIVERY_HISTORY_DATASET, $companyId);
@ -99,10 +164,9 @@ class PayablesUnpricedCycleProcessor
$period,
);
$summary = [
$summary = $priceMetadata + [
'period' => $period,
'cutoff' => $cutoff,
'price_file' => basename($priceFile),
'price_codes' => count($priceMap),
'matched_delivery_rows' => count($deliveryMatched['rows']),
'matched_return_rows' => count($returnMatched['rows']),
@ -185,6 +249,84 @@ class PayablesUnpricedCycleProcessor
return $summary;
}
/** @return array<string,array{price:float,start:string}> */
private function readPlatformPriceMap(string $cutoff): array
{
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
$schema = Schema::connection($connectionName);
if (! $schema->hasTable(SupplierPayableForecastRepository::PRICE_TABLE)
|| ! $schema->hasTable('business_mirror_table_states')) {
throw new RuntimeException('工作平台价格镜像尚未初始化,无法执行自动定价。');
}
$state = DB::connection($connectionName)
->table('business_mirror_table_states')
->where('dataset_key', SupplierPayableForecastRepository::PRICE_DATASET)
->first();
if ($state === null) {
throw new RuntimeException('工作平台价格镜像尚未初始化,无法执行自动定价。');
}
$lastSucceededAt = $this->date($state->last_succeeded_at ?? null);
$cutoffStart = new DateTimeImmutable($cutoff . ' 00:00:00');
if ((string) ($state->status ?? '') !== 'succeeded'
|| ($state->initial_completed_at ?? null) === null
|| $lastSucceededAt === null
|| $lastSucceededAt < $cutoffStart) {
throw new RuntimeException(
'工作平台价格镜像未同步到 ' . $cutoff . ',为避免使用旧价格,本次自动定价未执行。',
);
}
$cutoffAt = new DateTimeImmutable($cutoff . ' 23:59:59');
$rows = DB::connection($connectionName)
->table(SupplierPayableForecastRepository::PRICE_TABLE)
->where('effectStartTime', '<=', $cutoffAt->format('Y-m-d H:i:s'))
->where(static function ($query) use ($cutoffAt): void {
$query->whereNull('effectEndTime')
->orWhere('effectEndTime', '')
->orWhere('effectEndTime', '>=', $cutoffAt->format('Y-m-d H:i:s'));
})
->orderBy('effectStartTime')
->orderBy('createTime')
->orderBy('Id')
->get(['Id', 'skucode', 'afterPrice', 'effectStartTime', 'effectEndTime', 'createTime']);
$latest = [];
foreach ($rows as $row) {
$code = $this->normalizeCode($row->skucode ?? null);
$price = $this->number($row->afterPrice ?? null);
$start = $this->date($row->effectStartTime ?? null);
$completed = $this->date($row->createTime ?? null);
$end = $this->date($row->effectEndTime ?? null);
if ($code === '' || $price === null || $start === null
|| $start > $cutoffAt || ($end !== null && $end < $cutoffAt)) {
continue;
}
$sortKey = implode('|', [
$start->format('Y-m-d H:i:s'),
$completed?->format('Y-m-d H:i:s') ?? '',
str_pad((string) ($row->Id ?? ''), 20, '0', STR_PAD_LEFT),
]);
if (! isset($latest[$code]) || $sortKey > $latest[$code]['sort']) {
$latest[$code] = [
'sort' => $sortKey,
'price' => $price,
'start' => $start->format('Y-m-d H:i:s'),
];
}
}
return array_map(
static fn (array $entry): array => [
'price' => $entry['price'],
'start' => $entry['start'],
],
$latest,
);
}
/**
* @param list<array<string,mixed>> $rows
* @param array<string,array{price:float,start:string}> $priceMap

View File

@ -3,6 +3,10 @@
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\PayablesUnpricedCycleProcessor;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
@ -19,6 +23,13 @@ class PayablesUnpricedCycleTest extends FeatureTestCase
);
}
protected function tearDown(): void
{
Carbon::setTestNow();
parent::tearDown();
}
public function test_cycle_matches_history_before_carrying_in_new_unpriced_rows(): void
{
$store = app(SupplierPayableOverrideStore::class);
@ -192,6 +203,147 @@ class PayablesUnpricedCycleTest extends FeatureTestCase
}
}
public function test_auto_cycle_uses_work_platform_price_mirror_and_is_idempotent(): void
{
Carbon::setTestNow(Carbon::parse('2026-11-02 08:30:00', 'Asia/Shanghai'));
$store = app(SupplierPayableOverrideStore::class);
$companyId = (int) $this->company->id;
$userId = (int) $this->user->id;
$this->configurePlatformPriceMirror('succeeded', '2026-11-02 08:00:00');
$store->saveBatch(PayablesUnpricedCycleProcessor::DELIVERY_HISTORY_DATASET, [
'id:auto:delivery:matched-1' => [
'supplier' => '供应商甲', 'barCode' => 'M-1', 'qty' => '2', 'unitPrice' => null, 'amount' => null,
],
], $companyId, $userId, 'test');
$store->saveBatch(PayablesUnpricedCycleProcessor::RETURN_HISTORY_DATASET, [
'id:auto:return:matched' => [
'supplier' => '退货甲', 'barcode' => 'R-1', 'qty' => '3', 'unit_price' => null, 'amount' => null,
],
], $companyId, $userId, 'test');
$this->artisan('payables:unpriced-cycle:auto', [
'--company' => $companyId,
'--user' => $userId,
])->assertSuccessful();
$pricedDelivery = $store->listRows(PayablesUnpricedCycleProcessor::DELIVERY_PRICED_DATASET, $companyId);
$pricedReturn = $store->listRows(PayablesUnpricedCycleProcessor::RETURN_PRICED_DATASET, $companyId);
$this->assertCount(1, $pricedDelivery);
$this->assertCount(1, $pricedReturn);
$this->assertSame('12', $pricedDelivery[0]['unitPrice']);
$this->assertSame('24.00', $pricedDelivery[0]['amount']);
$this->assertSame('8', $pricedReturn[0]['unit_price']);
$this->assertSame('24.00', $pricedReturn[0]['amount']);
$this->assertSame('2026-10', $pricedDelivery[0]['_accounting_period']);
$this->artisan('payables:unpriced-cycle:auto', [
'--company' => $companyId,
'--user' => $userId,
])->expectsOutputToContain('已完成,本次自动任务跳过')->assertSuccessful();
$this->assertCount(
1,
$store->listRows(PayablesUnpricedCycleProcessor::DELIVERY_PRICED_DATASET, $companyId),
);
}
public function test_auto_cycle_refuses_stale_work_platform_price_mirror(): void
{
$store = app(SupplierPayableOverrideStore::class);
$companyId = (int) $this->company->id;
$userId = (int) $this->user->id;
$this->configurePlatformPriceMirror('succeeded', '2026-11-01 23:00:00');
$store->saveBatch(PayablesUnpricedCycleProcessor::DELIVERY_HISTORY_DATASET, [
'id:auto:stale:delivery' => [
'supplier' => '供应商甲', 'barCode' => 'M-1', 'qty' => '2', 'unitPrice' => null, 'amount' => null,
],
], $companyId, $userId, 'test');
$this->artisan('payables:unpriced-cycle:auto', [
'--period' => '2026-10',
'--cutoff' => '2026-11-02',
'--company' => $companyId,
'--user' => $userId,
])->expectsOutputToContain('工作平台价格镜像未同步到 2026-11-02')->assertFailed();
$this->assertSame([], $store->listRows(PayablesUnpricedCycleProcessor::DELIVERY_PRICED_DATASET, $companyId));
$this->assertSame([], $store->listRows(PayablesUnpricedCycleProcessor::RUN_DATASET, $companyId));
}
private function configurePlatformPriceMirror(string $status, string $lastSucceededAt): void
{
config([
'database.connections.business_mirror' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'upstream_mirrors.connection' => 'business_mirror',
]);
DB::purge('business_mirror');
Schema::connection('business_mirror')->create('js_pm_price_adjustment_log', function (Blueprint $table): void {
$table->unsignedBigInteger('Id')->primary();
$table->string('skucode');
$table->string('priceType')->nullable();
$table->decimal('originalPrice', 18, 4)->nullable();
$table->decimal('afterPrice', 18, 4)->nullable();
$table->decimal('diffPrice', 18, 4)->nullable();
$table->dateTime('effectStartTime')->nullable();
$table->dateTime('effectEndTime')->nullable();
$table->dateTime('createTime')->nullable();
});
Schema::connection('business_mirror')->create('business_mirror_table_states', function (Blueprint $table): void {
$table->string('dataset_key')->primary();
$table->string('status')->nullable();
$table->dateTime('initial_completed_at')->nullable();
$table->dateTime('last_succeeded_at')->nullable();
});
DB::connection('business_mirror')->table('js_pm_price_adjustment_log')->insert([
[
'Id' => 1,
'skucode' => 'M-1',
'priceType' => '变价',
'originalPrice' => 10.5,
'afterPrice' => 10.5,
'diffPrice' => 0,
'effectStartTime' => '2026-01-01 00:00:00',
'effectEndTime' => '2026-09-30 00:00:00',
'createTime' => '2026-01-01 00:00:00',
],
[
'Id' => 2,
'skucode' => 'M-1',
'priceType' => '变价',
'originalPrice' => 10.5,
'afterPrice' => 12,
'diffPrice' => 1.5,
'effectStartTime' => '2026-10-01 00:00:00',
'effectEndTime' => null,
'createTime' => '2026-10-01 00:00:00',
],
[
'Id' => 3,
'skucode' => 'R-1',
'priceType' => '定价',
'originalPrice' => null,
'afterPrice' => 8,
'diffPrice' => null,
'effectStartTime' => '2026-09-01 00:00:00',
'effectEndTime' => null,
'createTime' => '2026-09-01 00:00:00',
],
]);
DB::connection('business_mirror')->table('business_mirror_table_states')->insert([
'dataset_key' => 'jiansun.dbo.pm_priceAdjustment_log',
'status' => $status,
'initial_completed_at' => '2026-09-10 14:18:05',
'last_succeeded_at' => $lastSucceededAt,
]);
}
private function makeFile(string $name, string $content): string
{
$path = sys_get_temp_dir() . '/caiwu-cycle-test-' . bin2hex(random_bytes(6)) . '-' . $name;

View File

@ -240,6 +240,29 @@ class BusinessMirrorScheduleTest extends TestCase
$this->assertStringNotContainsString('supplier-statement:send-reminders', $kernel);
}
public function test_release_scripts_run_unpriced_cycle_on_the_second_day(): void
{
foreach (['activate-release.sh', 'activate-incremental-release.sh'] as $script) {
$contents = file_get_contents(dirname(__DIR__, 3) . '/deploy/' . $script);
$this->assertIsString($contents);
$this->assertStringContainsString(
'30 8,12,16 2 * * root CAIWU_BATCH_LOCK_WAIT=10800 '
. '/bin/sh /opt/caiwuxitong/run-finance-batch.sh payables:unpriced-cycle:auto --company=1 --quiet '
. '>> /opt/caiwuxitong/runtime/sync-logs/payables-unpriced-cycle.log 2>&1',
$contents,
$script,
);
$this->assertSame(1, substr_count($contents, 'payables:unpriced-cycle:auto'), $script);
}
$runner = file_get_contents(dirname(__DIR__, 3) . '/deploy/run-finance-batch.sh');
$registry = file_get_contents(dirname(__DIR__, 3) . '/deploy/finance-batch-imports.json');
$this->assertIsString($runner);
$this->assertIsString($registry);
$this->assertStringContainsString('payables:unpriced-cycle:auto', $runner);
$this->assertStringContainsString('"payables:unpriced-cycle:auto"', $registry);
}
public function test_release_scripts_fully_reconcile_supplier_payable_receipts_daily(): void
{
foreach (['activate-release.sh', 'activate-incremental-release.sh'] as $script) {