diff --git a/app/Console/Commands/RunPayablesUnpricedCycle.php b/app/Console/Commands/RunPayablesUnpricedCycle.php new file mode 100644 index 000000000..936dac15d --- /dev/null +++ b/app/Console/Commands/RunPayablesUnpricedCycle.php @@ -0,0 +1,59 @@ +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; + } + } +} diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 153f0f246..4df7df62a 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -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 # 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index dfa21c717..9be94d000 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -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 # 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。 diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index b90678361..b511c81d3 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -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", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 5f8330899..72b7d251e 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -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 ;; diff --git a/modules/EcommerceFinance/Services/PayablesUnpricedCycleProcessor.php b/modules/EcommerceFinance/Services/PayablesUnpricedCycleProcessor.php index 844f057db..b883ab0ff 100644 --- a/modules/EcommerceFinance/Services/PayablesUnpricedCycleProcessor.php +++ b/modules/EcommerceFinance/Services/PayablesUnpricedCycleProcessor.php @@ -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 + */ + 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 $priceMap + * @param array{price_file:string,price_source:string} $priceMetadata + * @return array + */ + 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 */ + 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> $rows * @param array $priceMap diff --git a/tests/Feature/Business/PayablesUnpricedCycleTest.php b/tests/Feature/Business/PayablesUnpricedCycleTest.php index b93a92b27..2607bd85a 100644 --- a/tests/Feature/Business/PayablesUnpricedCycleTest.php +++ b/tests/Feature/Business/PayablesUnpricedCycleTest.php @@ -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; diff --git a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php index 4fce45f77..d9932ea7d 100644 --- a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php +++ b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php @@ -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) {