科目映射表:存储改共享数据库(ec_account_mapping_rules / ec_account_mapping_events,本地与生产同一份,改完两边同时生效);旧文件保留为只读备份镜像;账单明细改读共享库;新增 account-mapping:import-files 导入命令

This commit is contained in:
yueyang 2026-10-16 17:19:27 +08:00
parent c50244544d
commit c4a39ec265
4 changed files with 306 additions and 14 deletions

View File

@ -0,0 +1,32 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\AccountMappingStore;
/**
* 把科目映射表的旧文件存储(storage/app/account-mapping/rules.json / events.json)
* 导入共享系统数据库(ec_account_mapping_rules / ec_account_mapping_events)。
*
* 幂等:以文件为准覆盖数据库内容,可重复执行。
*/
class ImportAccountMappingFiles extends Command
{
protected $signature = 'account-mapping:import-files {--events : 一并导入操作记录}';
protected $description = '把科目映射表的旧文件存储导入共享数据库';
public function handle(AccountMappingStore $store): int
{
$result = $store->syncFromFiles((bool) $this->option('events'));
$this->info(
'已导入规则 ' . $result['rules'] . ' 条'
. ($result['events'] > 0 ? ',操作记录 ' . $result['events'] . ' 条' : '')
. '。'
);
return self::SUCCESS;
}
}

View File

@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 科目映射表改为共享数据库存储:规则表 + 操作记录表。
*
* 落在默认连接(共享系统库 caiwu_system_config),本地与生产读同一份,
* 避免「本地文件 / 生产文件」两份内容不一致。
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('ec_account_mapping_rules', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('platform', 64)->default('');
$table->string('item', 191)->default('');
$table->string('memo', 191)->default('');
$table->string('goods', 255)->default('');
$table->string('invoice', 32)->default('');
$table->string('category', 64)->default('');
$table->string('d_acct', 191)->default('');
$table->string('d_sub', 191)->default('');
$table->string('c_acct', 191)->default('');
$table->string('c_sub', 191)->default('');
$table->string('basis', 32)->default('');
$table->timestamps();
$table->index(['platform', 'item'], 'ec_account_mapping_rules_platform_item_idx');
});
Schema::create('ec_account_mapping_events', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->dateTime('at');
$table->string('action', 32);
$table->unsignedBigInteger('rule_id')->nullable();
$table->longText('before_json')->nullable();
$table->longText('after_json')->nullable();
$table->unsignedBigInteger('user_id')->nullable();
$table->longText('extra_json')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('ec_account_mapping_events');
Schema::dropIfExists('ec_account_mapping_rules');
}
};

View File

@ -3,26 +3,36 @@
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Carbon;
use RuntimeException;
use Throwable;
/**
* 科目映射表存储。
* 科目映射表存储(共享数据库)。
*
* 一条规则 = 「走哪两个科目(科目对)」+「方向基准」,**不存最终借贷方向**。
* 记账时按这张账单在平台上的实际收支代入:
* 账单收支 === 基准方向 → 照抄;否则 → 借贷互换。
*
* 当前落盘在 storage/app/account-mapping/rules.json(持久卷,重启不丢),
* 首次访问会用 resources/data/account-mapping.json 作为初始 112 条规则灌入。
* 若要变成正式的数据表,只需替换本类的读写实现,页面与接口不用动。
* 规则存共享系统数据库(默认连接)的 ec_account_mapping_rules,操作记录存
* ec_account_mapping_events:本地与生产读同一份,改完即对两边同时生效。
* 旧的 storage/app/account-mapping/rules.json 仅作为只读备份镜像继续写出;
* 迁移前(表还不存在)或回滚场景自动退回读该文件;初始种子在
* resources/data/account-mapping.json。
*
* 时间统一按 config('app.platform_timezone')(= APP_TIMEZONE)落盘,不能用 now():
* 时间统一按 config('app.platform_timezone')(= APP_TIMEZONE)落库,不能用 now():
* 页面请求会被 App\Utilities\Overrider 按公司设置覆盖 app.timezone,ak_settings 里没有
* localisation.timezone 时回落成 Europe/London,会让记录时间比北京时间晚 7 小时。
*/
class AccountMappingStore
{
/** 共享系统数据库里的规则表 / 操作记录表 */
public const RULES_TABLE = 'ec_account_mapping_rules';
public const EVENTS_TABLE = 'ec_account_mapping_events';
/** 可维护字段(顺序即导出/模板列顺序) */
public const FIELDS = ['platform', 'item', 'memo', 'goods', 'invoice', 'category', 'dAcct', 'dSub', 'cAcct', 'cSub', 'basis'];
@ -88,9 +98,19 @@ class AccountMappingStore
return $this->dir() . DIRECTORY_SEPARATOR . 'events.json';
}
/** @return array<int,array<string,mixed>> 按 id 升序的全部规则 */
/** @return array<int,array<string,mixed>> 按 id 升序的全部规则(共享数据库优先,表不存在时退回旧文件) */
public function all(): array
{
if ($this->rulesTableReady()) {
$out = [];
foreach (DB::table(self::RULES_TABLE)->orderBy('id')->get() as $row) {
$out[] = $this->fromRow($row);
}
return $out;
}
// 兼容:迁移前的环境(或回滚场景)继续读文件
$this->ensureSeeded();
$payload = $this->read($this->path());
@ -353,9 +373,30 @@ class AccountMappingStore
];
}
/** @return array<int,array<string,mixed>> 最近的操作记录(倒序) */
/** @return array<int,array<string,mixed>> 最近的操作记录(倒序;共享数据库优先) */
public function events(int $limit = 50): array
{
if ($this->eventsTableReady()) {
$out = [];
foreach (DB::table(self::EVENTS_TABLE)->orderByDesc('id')->limit(max(1, $limit))->get() as $row) {
$event = [
'at' => (string) $row->at,
'action' => (string) $row->action,
'id' => $row->rule_id === null ? null : (int) $row->rule_id,
'before' => $row->before_json ? json_decode((string) $row->before_json, true) : null,
'after' => $row->after_json ? json_decode((string) $row->after_json, true) : null,
'user_id' => $row->user_id === null ? null : (int) $row->user_id,
];
$extra = $row->extra_json ? json_decode((string) $row->extra_json, true) : null;
if (is_array($extra)) {
$event = array_merge($event, $extra);
}
$out[] = $event;
}
return $out;
}
$payload = $this->read($this->eventPath());
$events = is_array($payload['events'] ?? null) ? $payload['events'] : [];
@ -388,17 +429,96 @@ class AccountMappingStore
&& trim((string) ($values['item'] ?? '')) === '';
}
/**
* 把旧文件存储(rules.json / events.json)导入共享数据库;幂等,以文件为准覆盖。
*
* @return array{rules:int,events:int}
*/
public function syncFromFiles(bool $withEvents = false): array
{
if (! $this->rulesTableReady()) {
throw new RuntimeException('共享数据库里还没有映射表,请先执行数据库迁移。');
}
$payload = $this->read($this->path());
$rules = is_array($payload['rules'] ?? null) ? $payload['rules'] : [];
$rules = array_values(array_filter($rules, static fn (mixed $r): bool => is_array($r) && isset($r['id'])));
usort($rules, static fn (array $a, array $b): int => ((int) $a['id']) <=> ((int) $b['id']));
$this->persist($rules);
$events = 0;
if ($withEvents && $this->eventsTableReady()) {
$payload = $this->read($this->eventPath());
$list = is_array($payload['events'] ?? null) ? $payload['events'] : [];
if ($list !== []) {
DB::table(self::EVENTS_TABLE)->delete();
$rows = [];
foreach ($list as $event) {
if (! is_array($event)) {
continue;
}
$at = (string) ($event['at'] ?? $this->platformNow()->toDateTimeString());
$rows[] = [
'at' => $at,
'action' => (string) ($event['action'] ?? 'unknown'),
'rule_id' => isset($event['id']) ? (int) $event['id'] : null,
'before_json' => array_key_exists('before', $event) && $event['before'] !== null ? json_encode($event['before'], JSON_UNESCAPED_UNICODE) : null,
'after_json' => array_key_exists('after', $event) && $event['after'] !== null ? json_encode($event['after'], JSON_UNESCAPED_UNICODE) : null,
'user_id' => isset($event['user_id']) ? (int) $event['user_id'] : null,
'extra_json' => null,
'created_at' => $at,
'updated_at' => $at,
];
}
foreach (array_chunk($rows, 200) as $chunk) {
DB::table(self::EVENTS_TABLE)->insert($chunk);
}
$events = count($rows);
}
}
return ['rules' => count($rules), 'events' => $events];
}
private function ensureSeeded(): void
{
if (File::exists($this->path())) {
return;
}
$this->persist($this->seed());
$this->persistFile($this->seed());
}
/** @param array<int,array<string,mixed>> $rules */
private function persist(array $rules): void
{
if (! $this->rulesTableReady()) {
$this->persistFile($rules);
return;
}
$now = $this->platformNow()->toDateTimeString();
DB::transaction(function () use ($rules, $now): void {
DB::table(self::RULES_TABLE)->delete();
$rows = [];
foreach ($rules as $rule) {
$rows[] = $this->toRow($rule, $now);
}
foreach (array_chunk($rows, 200) as $chunk) {
DB::table(self::RULES_TABLE)->insert($chunk);
}
});
// 文件只作为只读备份镜像:写失败不影响主存储
try {
$this->persistFile($rules);
} catch (Throwable) {
}
}
/** @param array<int,array<string,mixed>> $rules */
private function persistFile(array $rules): void
{
if (! File::isDirectory($this->dir()) && ! File::makeDirectory($this->dir(), 0775, true) && ! File::isDirectory($this->dir())) {
throw new RuntimeException('无法创建映射表存储目录。');
@ -418,11 +538,34 @@ class AccountMappingStore
private function logEvent(string $action, ?int $id, ?array $before, ?array $after, ?int $userId, array $extra = []): void
{
$at = $this->platformNow()->toDateTimeString();
if ($this->eventsTableReady()) {
DB::table(self::EVENTS_TABLE)->insert([
'at' => $at,
'action' => $action,
'rule_id' => $id,
'before_json' => $before === null ? null : json_encode($before, JSON_UNESCAPED_UNICODE),
'after_json' => $after === null ? null : json_encode($after, JSON_UNESCAPED_UNICODE),
'user_id' => $userId,
'extra_json' => $extra === [] ? null : json_encode($extra, JSON_UNESCAPED_UNICODE),
'created_at' => $at,
'updated_at' => $at,
]);
$maxId = (int) DB::table(self::EVENTS_TABLE)->max('id');
if ($maxId > 500) {
DB::table(self::EVENTS_TABLE)->where('id', '<=', $maxId - 500)->delete();
}
return;
}
$payload = $this->read($this->eventPath());
$events = is_array($payload['events'] ?? null) ? $payload['events'] : [];
$events[] = array_merge([
'at' => $this->platformNow()->toDateTimeString(),
'at' => $at,
'action' => $action,
'id' => $id,
'before' => $before,
@ -437,6 +580,67 @@ class AccountMappingStore
File::put($this->eventPath(), (string) json_encode(['events' => $events], JSON_UNESCAPED_UNICODE), true);
}
private function rulesTableReady(): bool
{
try {
return Schema::hasTable(self::RULES_TABLE);
} catch (Throwable) {
return false;
}
}
private function eventsTableReady(): bool
{
try {
return Schema::hasTable(self::EVENTS_TABLE);
} catch (Throwable) {
return false;
}
}
/** @return array<string,mixed> */
private function fromRow(object $row): array
{
return [
'id' => (int) $row->id,
'platform' => (string) $row->platform,
'item' => (string) $row->item,
'memo' => (string) $row->memo,
'goods' => (string) $row->goods,
'invoice' => (string) $row->invoice,
'category' => (string) $row->category,
'dAcct' => (string) $row->d_acct,
'dSub' => (string) $row->d_sub,
'cAcct' => (string) $row->c_acct,
'cSub' => (string) $row->c_sub,
'basis' => (string) $row->basis,
];
}
/** @param array<string,mixed> $rule */
private function toRow(array $rule, string $now): array
{
$id = (int) ($rule['id'] ?? 0);
$rule = $this->normalize($rule);
return [
'id' => $id,
'platform' => $rule['platform'],
'item' => $rule['item'],
'memo' => $rule['memo'],
'goods' => $rule['goods'],
'invoice' => $rule['invoice'],
'category' => $rule['category'],
'd_acct' => $rule['dAcct'],
'd_sub' => $rule['dSub'],
'c_acct' => $rule['cAcct'],
'c_sub' => $rule['cSub'],
'basis' => $rule['basis'],
'created_at' => $now,
'updated_at' => $now,
];
}
/** @return array<string,mixed> */
private function read(string $path): array
{

View File

@ -6,6 +6,7 @@ use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Services\AccountLedgerRemarkMap;
use Modules\EcommerceFinance\Services\AccountMappingMatcher;
use Modules\EcommerceFinance\Services\AccountMappingStore;
use Throwable;
/**
@ -1139,16 +1140,18 @@ class BillingDetailsPageData
return $this->columnCache[$table];
}
/** 科目映射表:平台|账单项目 → [memo, category] */
/** 科目映射表:平台|账单项目 → [memo, category](共享数据库,随页面请求实时读取) */
private function rules(): array
{
static $cache = null;
if ($cache !== null) { return $cache; }
$cache = [];
$path = storage_path('app/account-mapping/rules.json');
if (! is_file($path)) { return $cache; }
$raw = json_decode((string) file_get_contents($path), true);
foreach (($raw['rules'] ?? $raw) as $rule) {
try {
$all = app(AccountMappingStore::class)->all();
} catch (Throwable) {
return $cache;
}
foreach ($all as $rule) {
$key = trim((string) ($rule['platform'] ?? '')) . '|' . trim((string) ($rule['item'] ?? ''));
$prev = $cache[$key] ?? null;
$isCatchAll = trim((string) ($rule['memo'] ?? '')) === '' && trim((string) ($rule['goods'] ?? '')) === '';